esp_image_format.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #include <string.h>
  14. #include <sys/param.h>
  15. #include <soc/cpu.h>
  16. #include <bootloader_utility.h>
  17. #include <esp_secure_boot.h>
  18. #include <esp_log.h>
  19. #include <esp_spi_flash.h>
  20. #include <bootloader_flash.h>
  21. #include <bootloader_random.h>
  22. #include <bootloader_sha.h>
  23. #include "bootloader_util.h"
  24. #include "bootloader_common.h"
  25. #if CONFIG_IDF_TARGET_ESP32
  26. #include <esp32/rom/rtc.h>
  27. #include <esp32/rom/secure_boot.h>
  28. #elif CONFIG_IDF_TARGET_ESP32S2BETA
  29. #include <esp32s2beta/rom/rtc.h>
  30. #include <esp32s2beta/rom/secure_boot.h>
  31. #endif
  32. /* Checking signatures as part of verifying images is necessary:
  33. - Always if secure boot is enabled
  34. - Differently in bootloader and/or app, depending on kconfig
  35. */
  36. #ifdef BOOTLOADER_BUILD
  37. #ifdef CONFIG_SECURE_SIGNED_ON_BOOT
  38. #define SECURE_BOOT_CHECK_SIGNATURE
  39. #endif
  40. #else /* !BOOTLOADER_BUILD */
  41. #ifdef CONFIG_SECURE_SIGNED_ON_UPDATE
  42. #define SECURE_BOOT_CHECK_SIGNATURE
  43. #endif
  44. #endif
  45. static const char *TAG = "esp_image";
  46. #define HASH_LEN ESP_IMAGE_HASH_LEN
  47. #define SIXTEEN_MB 0x1000000
  48. #define ESP_ROM_CHECKSUM_INITIAL 0xEF
  49. /* Headroom to ensure between stack SP (at time of checking) and data loaded from flash */
  50. #define STACK_LOAD_HEADROOM 32768
  51. /* Mmap source address mask */
  52. #define MMAP_ALIGNED_MASK 0x0000FFFF
  53. #ifdef BOOTLOADER_BUILD
  54. /* 64 bits of random data to obfuscate loaded RAM with, until verification is complete
  55. (Means loaded code isn't executable until after the secure boot check.)
  56. */
  57. static uint32_t ram_obfs_value[2];
  58. /* Range of IRAM used by the loader, defined in ld script */
  59. extern int _loader_text_start;
  60. extern int _loader_text_end;
  61. #endif
  62. /* Return true if load_addr is an address the bootloader should load into */
  63. static bool should_load(uint32_t load_addr);
  64. /* Return true if load_addr is an address the bootloader should map via flash cache */
  65. static bool should_map(uint32_t load_addr);
  66. /* Load or verify a segment */
  67. static esp_err_t process_segment(int index, uint32_t flash_addr, esp_image_segment_header_t *header, bool silent, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum);
  68. /* split segment and verify if data_len is too long */
  69. static esp_err_t process_segment_data(intptr_t load_addr, uint32_t data_addr, uint32_t data_len, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum);
  70. /* Verify the main image header */
  71. static esp_err_t verify_image_header(uint32_t src_addr, const esp_image_header_t *image, bool silent);
  72. /* Verify a segment header */
  73. static esp_err_t verify_segment_header(int index, const esp_image_segment_header_t *segment, uint32_t segment_data_offs, bool silent);
  74. /* Log-and-fail macro for use in esp_image_load */
  75. #define FAIL_LOAD(...) do { \
  76. if (!silent) { \
  77. ESP_LOGE(TAG, __VA_ARGS__); \
  78. } \
  79. goto err; \
  80. } \
  81. while(0)
  82. static esp_err_t verify_checksum(bootloader_sha256_handle_t sha_handle, uint32_t checksum_word, esp_image_metadata_t *data);
  83. static esp_err_t __attribute__((unused)) verify_secure_boot_signature(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data);
  84. static esp_err_t __attribute__((unused)) verify_simple_hash(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data);
  85. static esp_err_t image_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data)
  86. {
  87. #ifdef BOOTLOADER_BUILD
  88. bool do_load = (mode == ESP_IMAGE_LOAD) || (mode == ESP_IMAGE_LOAD_NO_VALIDATE);
  89. bool do_verify = (mode == ESP_IMAGE_LOAD) || (mode == ESP_IMAGE_VERIFY) || (mode == ESP_IMAGE_VERIFY_SILENT);
  90. #else
  91. bool do_load = false; // Can't load the image in app mode
  92. bool do_verify = true; // In app mode is avalible only verify mode
  93. #endif
  94. bool silent = (mode == ESP_IMAGE_VERIFY_SILENT);
  95. esp_err_t err = ESP_OK;
  96. // checksum the image a word at a time. This shaves 30-40ms per MB of image size
  97. uint32_t checksum_word = ESP_ROM_CHECKSUM_INITIAL;
  98. uint32_t *checksum = NULL;
  99. bootloader_sha256_handle_t sha_handle = NULL;
  100. if (data == NULL || part == NULL) {
  101. return ESP_ERR_INVALID_ARG;
  102. }
  103. if (part->size > SIXTEEN_MB) {
  104. err = ESP_ERR_INVALID_ARG;
  105. FAIL_LOAD("partition size 0x%x invalid, larger than 16MB", part->size);
  106. }
  107. bzero(data, sizeof(esp_image_metadata_t));
  108. data->start_addr = part->offset;
  109. ESP_LOGD(TAG, "reading image header @ 0x%x", data->start_addr);
  110. err = bootloader_flash_read(data->start_addr, &data->image, sizeof(esp_image_header_t), true);
  111. if (err != ESP_OK) {
  112. goto err;
  113. }
  114. if (do_verify) {
  115. checksum = &checksum_word;
  116. // Calculate SHA-256 of image if secure boot is on, or if image has a hash appended
  117. #ifdef SECURE_BOOT_CHECK_SIGNATURE
  118. if (1) {
  119. #else
  120. if (data->image.hash_appended) {
  121. #endif
  122. sha_handle = bootloader_sha256_start();
  123. if (sha_handle == NULL) {
  124. return ESP_ERR_NO_MEM;
  125. }
  126. bootloader_sha256_data(sha_handle, &data->image, sizeof(esp_image_header_t));
  127. }
  128. ESP_LOGD(TAG, "image header: 0x%02x 0x%02x 0x%02x 0x%02x %08x",
  129. data->image.magic,
  130. data->image.segment_count,
  131. data->image.spi_mode,
  132. data->image.spi_size,
  133. data->image.entry_addr);
  134. err = verify_image_header(data->start_addr, &data->image, silent);
  135. if (err != ESP_OK) {
  136. goto err;
  137. }
  138. if (data->image.segment_count > ESP_IMAGE_MAX_SEGMENTS) {
  139. FAIL_LOAD("image at 0x%x segment count %d exceeds max %d",
  140. data->start_addr, data->image.segment_count, ESP_IMAGE_MAX_SEGMENTS);
  141. }
  142. } // if (do_verify)
  143. uint32_t next_addr = data->start_addr + sizeof(esp_image_header_t);
  144. for (int i = 0; i < data->image.segment_count; i++) {
  145. esp_image_segment_header_t *header = &data->segments[i];
  146. ESP_LOGV(TAG, "loading segment header %d at offset 0x%x", i, next_addr);
  147. err = process_segment(i, next_addr, header, silent, do_load, sha_handle, checksum);
  148. if (err != ESP_OK) {
  149. goto err;
  150. }
  151. next_addr += sizeof(esp_image_segment_header_t);
  152. data->segment_data[i] = next_addr;
  153. next_addr += header->data_len;
  154. }
  155. if (do_verify) {
  156. // Segments all loaded, verify length
  157. uint32_t end_addr = next_addr;
  158. if (end_addr < data->start_addr) {
  159. FAIL_LOAD("image offset has wrapped");
  160. }
  161. data->image_len = end_addr - data->start_addr;
  162. ESP_LOGV(TAG, "image start 0x%08x end of last section 0x%08x", data->start_addr, end_addr);
  163. if (NULL != checksum && !esp_cpu_in_ocd_debug_mode()) {
  164. err = verify_checksum(sha_handle, checksum_word, data);
  165. if (err != ESP_OK) {
  166. goto err;
  167. }
  168. }
  169. /* For secure boot on ESP32, we don't calculate SHA or verify signautre on bootloaders.
  170. For ESP32S2, we do verify signature on botoloaders which includes the SHA calculation.
  171. (For non-secure boot, we don't verify any SHA-256 hash appended to the bootloader because
  172. esptool.py may have rewritten the header - rely on esptool.py having verified the bootloader at flashing time, instead.)
  173. */
  174. bool verify_sha;
  175. #if defined(CONFIG_SECURE_BOOT_ENABLED) && defined(CONFIG_IDF_TARGET_ESP32S2BETA)
  176. verify_sha = true;
  177. #else // ESP32, or ESP32S2 without secure boot enabled
  178. verify_sha = (data->start_addr != ESP_BOOTLOADER_OFFSET);
  179. #endif
  180. if (verify_sha) {
  181. if (data->image_len > part->size) {
  182. FAIL_LOAD("Image length %d doesn't fit in partition length %d", data->image_len, part->size);
  183. }
  184. #ifdef SECURE_BOOT_CHECK_SIGNATURE
  185. // secure boot images have a signature appended
  186. err = verify_secure_boot_signature(sha_handle, data);
  187. #else
  188. // No secure boot, but SHA-256 can be appended for basic corruption detection
  189. if (sha_handle != NULL && !esp_cpu_in_ocd_debug_mode()) {
  190. err = verify_simple_hash(sha_handle, data);
  191. sha_handle = NULL; // calling verify_simple_hash finishes sha_handle
  192. }
  193. #endif // SECURE_BOOT_CHECK_SIGNATURE
  194. } else { // verify_sha
  195. // bootloader may still have a sha256 digest handle open
  196. if (sha_handle != NULL) {
  197. bootloader_sha256_finish(sha_handle, NULL);
  198. }
  199. sha_handle = NULL;
  200. } //verify_sha
  201. // Separately, if there's a hash appended to the image then copy it out to the data->image_digest field
  202. if (data->image.hash_appended) {
  203. const void *hash = bootloader_mmap(data->start_addr + data->image_len - HASH_LEN, HASH_LEN);
  204. if (hash == NULL) {
  205. err = ESP_FAIL;
  206. goto err;
  207. }
  208. memcpy(data->image_digest, hash, HASH_LEN);
  209. bootloader_munmap(hash);
  210. }
  211. } // do_verify
  212. if (err != ESP_OK) {
  213. goto err;
  214. }
  215. #ifdef BOOTLOADER_BUILD
  216. if (do_load && ram_obfs_value[0] != 0 && ram_obfs_value[1] != 0) { // Need to deobfuscate RAM
  217. for (int i = 0; i < data->image.segment_count; i++) {
  218. uint32_t load_addr = data->segments[i].load_addr;
  219. if (should_load(load_addr)) {
  220. uint32_t *loaded = (uint32_t *)load_addr;
  221. for (int j = 0; j < data->segments[i].data_len / sizeof(uint32_t); j++) {
  222. loaded[j] ^= (j & 1) ? ram_obfs_value[0] : ram_obfs_value[1];
  223. }
  224. }
  225. }
  226. }
  227. #endif
  228. // Success!
  229. return ESP_OK;
  230. err:
  231. if (err == ESP_OK) {
  232. err = ESP_ERR_IMAGE_INVALID;
  233. }
  234. if (sha_handle != NULL) {
  235. // Need to finish the hash process to free the handle
  236. bootloader_sha256_finish(sha_handle, NULL);
  237. }
  238. // Prevent invalid/incomplete data leaking out
  239. bzero(data, sizeof(esp_image_metadata_t));
  240. return err;
  241. }
  242. esp_err_t bootloader_load_image(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  243. {
  244. #ifdef BOOTLOADER_BUILD
  245. return image_load(ESP_IMAGE_LOAD, part, data);
  246. #else
  247. return ESP_FAIL;
  248. #endif
  249. }
  250. esp_err_t bootloader_load_image_no_verify(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  251. {
  252. #ifdef BOOTLOADER_BUILD
  253. return image_load(ESP_IMAGE_LOAD_NO_VALIDATE, part, data);
  254. #else
  255. return ESP_FAIL;
  256. #endif
  257. }
  258. esp_err_t esp_image_verify(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data)
  259. {
  260. return image_load(mode, part, data);
  261. }
  262. static esp_err_t verify_image_header(uint32_t src_addr, const esp_image_header_t *image, bool silent)
  263. {
  264. esp_err_t err = ESP_OK;
  265. if (image->magic != ESP_IMAGE_HEADER_MAGIC) {
  266. if (!silent) {
  267. ESP_LOGE(TAG, "image at 0x%x has invalid magic byte", src_addr);
  268. }
  269. err = ESP_ERR_IMAGE_INVALID;
  270. }
  271. if (!silent) {
  272. if (image->spi_mode > ESP_IMAGE_SPI_MODE_SLOW_READ) {
  273. ESP_LOGW(TAG, "image at 0x%x has invalid SPI mode %d", src_addr, image->spi_mode);
  274. }
  275. if (image->spi_speed > ESP_IMAGE_SPI_SPEED_80M) {
  276. ESP_LOGW(TAG, "image at 0x%x has invalid SPI speed %d", src_addr, image->spi_speed);
  277. }
  278. if (image->spi_size > ESP_IMAGE_FLASH_SIZE_MAX) {
  279. ESP_LOGW(TAG, "image at 0x%x has invalid SPI size %d", src_addr, image->spi_size);
  280. }
  281. }
  282. if (err == ESP_OK) {
  283. // Checking the chip revision header *will* print a bunch of other info
  284. // regardless of silent setting as this may be important, but don't bother checking it
  285. // if it looks like the app partition is erased or otherwise garbage
  286. if (bootloader_common_check_chip_validity(image, ESP_IMAGE_APPLICATION) != ESP_OK) {
  287. err = ESP_ERR_IMAGE_INVALID;
  288. }
  289. }
  290. return err;
  291. }
  292. static esp_err_t process_segment(int index, uint32_t flash_addr, esp_image_segment_header_t *header, bool silent, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum)
  293. {
  294. esp_err_t err;
  295. /* read segment header */
  296. err = bootloader_flash_read(flash_addr, header, sizeof(esp_image_segment_header_t), true);
  297. if (err != ESP_OK) {
  298. ESP_LOGE(TAG, "bootloader_flash_read failed at 0x%08x", flash_addr);
  299. return err;
  300. }
  301. if (sha_handle != NULL) {
  302. bootloader_sha256_data(sha_handle, header, sizeof(esp_image_segment_header_t));
  303. }
  304. intptr_t load_addr = header->load_addr;
  305. uint32_t data_len = header->data_len;
  306. uint32_t data_addr = flash_addr + sizeof(esp_image_segment_header_t);
  307. ESP_LOGV(TAG, "segment data length 0x%x data starts 0x%x", data_len, data_addr);
  308. err = verify_segment_header(index, header, data_addr, silent);
  309. if (err != ESP_OK) {
  310. return err;
  311. }
  312. if (data_len % 4 != 0) {
  313. FAIL_LOAD("unaligned segment length 0x%x", data_len);
  314. }
  315. bool is_mapping = should_map(load_addr);
  316. do_load = do_load && should_load(load_addr);
  317. if (!silent) {
  318. ESP_LOGI(TAG, "segment %d: paddr=0x%08x vaddr=0x%08x size=0x%05x (%6d) %s",
  319. index, data_addr, load_addr,
  320. data_len, data_len,
  321. (do_load) ? "load" : (is_mapping) ? "map" : "");
  322. }
  323. #ifdef BOOTLOADER_BUILD
  324. /* Before loading segment, check it doesn't clobber bootloader RAM. */
  325. if (do_load) {
  326. const intptr_t load_end = load_addr + data_len;
  327. if (load_end < (intptr_t) SOC_DRAM_HIGH) {
  328. /* Writing to DRAM */
  329. intptr_t sp = (intptr_t)get_sp();
  330. if (load_end > sp - STACK_LOAD_HEADROOM) {
  331. /* Bootloader .data/.rodata/.bss is above the stack, so this
  332. * also checks that we aren't overwriting these segments.
  333. *
  334. * TODO: This assumes specific arrangement of sections we have
  335. * in the ESP32. Rewrite this in a generic way to support other
  336. * layouts.
  337. */
  338. ESP_LOGE(TAG, "Segment %d end address 0x%08x too high (bootloader stack 0x%08x limit 0x%08x)",
  339. index, load_end, sp, sp - STACK_LOAD_HEADROOM);
  340. return ESP_ERR_IMAGE_INVALID;
  341. }
  342. } else {
  343. /* Writing to IRAM */
  344. const intptr_t loader_iram_start = (intptr_t) &_loader_text_start;
  345. const intptr_t loader_iram_end = (intptr_t) &_loader_text_end;
  346. if (bootloader_util_regions_overlap(loader_iram_start, loader_iram_end,
  347. load_addr, load_end)) {
  348. ESP_LOGE(TAG, "Segment %d (0x%08x-0x%08x) overlaps bootloader IRAM (0x%08x-0x%08x)",
  349. index, load_addr, load_end, loader_iram_start, loader_iram_end);
  350. return ESP_ERR_IMAGE_INVALID;
  351. }
  352. }
  353. }
  354. #endif // BOOTLOADER_BUILD
  355. uint32_t free_page_count = bootloader_mmap_get_free_pages();
  356. ESP_LOGD(TAG, "free data page_count 0x%08x", free_page_count);
  357. int32_t data_len_remain = data_len;
  358. while (data_len_remain > 0) {
  359. uint32_t offset_page = ((data_addr & MMAP_ALIGNED_MASK) != 0) ? 1 : 0;
  360. /* Data we could map in case we are not aligned to PAGE boundary is one page size lesser. */
  361. data_len = MIN(data_len_remain, ((free_page_count - offset_page) * SPI_FLASH_MMU_PAGE_SIZE));
  362. err = process_segment_data(load_addr, data_addr, data_len, do_load, sha_handle, checksum);
  363. if (err != ESP_OK) {
  364. return err;
  365. }
  366. data_addr += data_len;
  367. data_len_remain -= data_len;
  368. }
  369. return ESP_OK;
  370. err:
  371. if (err == ESP_OK) {
  372. err = ESP_ERR_IMAGE_INVALID;
  373. }
  374. return err;
  375. }
  376. static esp_err_t process_segment_data(intptr_t load_addr, uint32_t data_addr, uint32_t data_len, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum)
  377. {
  378. // If we are not loading, and the checksum is empty, skip processing this
  379. // segment for data
  380. if(!do_load && checksum == NULL) {
  381. ESP_LOGD(TAG, "skipping checksum for segment");
  382. return ESP_OK;
  383. }
  384. const uint32_t *data = (const uint32_t *)bootloader_mmap(data_addr, data_len);
  385. if (!data) {
  386. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed",
  387. data_addr, data_len);
  388. return ESP_FAIL;
  389. }
  390. if (checksum == NULL && sha_handle == NULL) {
  391. memcpy((void *)load_addr, data, data_len);
  392. bootloader_munmap(data);
  393. return ESP_OK;
  394. }
  395. #ifdef BOOTLOADER_BUILD
  396. // Set up the obfuscation value to use for loading
  397. while (ram_obfs_value[0] == 0 || ram_obfs_value[1] == 0) {
  398. bootloader_fill_random(ram_obfs_value, sizeof(ram_obfs_value));
  399. }
  400. uint32_t *dest = (uint32_t *)load_addr;
  401. #endif
  402. const uint32_t *src = data;
  403. for (int i = 0; i < data_len; i += 4) {
  404. int w_i = i / 4; // Word index
  405. uint32_t w = src[w_i];
  406. if (checksum != NULL) {
  407. *checksum ^= w;
  408. }
  409. #ifdef BOOTLOADER_BUILD
  410. if (do_load) {
  411. dest[w_i] = w ^ ((w_i & 1) ? ram_obfs_value[0] : ram_obfs_value[1]);
  412. }
  413. #endif
  414. // SHA_CHUNK determined experimentally as the optimum size
  415. // to call bootloader_sha256_data() with. This is a bit
  416. // counter-intuitive, but it's ~3ms better than using the
  417. // SHA256 block size.
  418. const size_t SHA_CHUNK = 1024;
  419. if (sha_handle != NULL && i % SHA_CHUNK == 0) {
  420. bootloader_sha256_data(sha_handle, &src[w_i],
  421. MIN(SHA_CHUNK, data_len - i));
  422. }
  423. }
  424. bootloader_munmap(data);
  425. return ESP_OK;
  426. }
  427. static esp_err_t verify_segment_header(int index, const esp_image_segment_header_t *segment, uint32_t segment_data_offs, bool silent)
  428. {
  429. if ((segment->data_len & 3) != 0
  430. || segment->data_len >= SIXTEEN_MB) {
  431. if (!silent) {
  432. ESP_LOGE(TAG, "invalid segment length 0x%x", segment->data_len);
  433. }
  434. return ESP_ERR_IMAGE_INVALID;
  435. }
  436. uint32_t load_addr = segment->load_addr;
  437. bool map_segment = should_map(load_addr);
  438. /* Check that flash cache mapped segment aligns correctly from flash to its mapped address,
  439. relative to the 64KB page mapping size.
  440. */
  441. ESP_LOGV(TAG, "segment %d map_segment %d segment_data_offs 0x%x load_addr 0x%x",
  442. index, map_segment, segment_data_offs, load_addr);
  443. if (map_segment
  444. && ((segment_data_offs % SPI_FLASH_MMU_PAGE_SIZE) != (load_addr % SPI_FLASH_MMU_PAGE_SIZE))) {
  445. if (!silent) {
  446. ESP_LOGE(TAG, "Segment %d load address 0x%08x, doesn't match data 0x%08x",
  447. index, load_addr, segment_data_offs);
  448. }
  449. return ESP_ERR_IMAGE_INVALID;
  450. }
  451. return ESP_OK;
  452. }
  453. static bool should_map(uint32_t load_addr)
  454. {
  455. return (load_addr >= SOC_IROM_LOW && load_addr < SOC_IROM_HIGH)
  456. || (load_addr >= SOC_DROM_LOW && load_addr < SOC_DROM_HIGH);
  457. }
  458. static bool should_load(uint32_t load_addr)
  459. {
  460. /* Reload the RTC memory segments whenever a non-deepsleep reset
  461. is occurring */
  462. bool load_rtc_memory = rtc_get_reset_reason(0) != DEEPSLEEP_RESET;
  463. if (should_map(load_addr)) {
  464. return false;
  465. }
  466. if (load_addr < 0x10000000) {
  467. // Reserved for non-loaded addresses.
  468. // Current reserved values are
  469. // 0x0 (padding block)
  470. // 0x4 (unused, but reserved for an MD5 block)
  471. return false;
  472. }
  473. if (!load_rtc_memory) {
  474. if (load_addr >= SOC_RTC_IRAM_LOW && load_addr < SOC_RTC_IRAM_HIGH) {
  475. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  476. return false;
  477. }
  478. if (load_addr >= SOC_RTC_DRAM_LOW && load_addr < SOC_RTC_DRAM_HIGH) {
  479. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  480. return false;
  481. }
  482. if (load_addr >= SOC_RTC_DATA_LOW && load_addr < SOC_RTC_DATA_HIGH) {
  483. ESP_LOGD(TAG, "Skipping RTC slow memory segment at 0x%08x", load_addr);
  484. return false;
  485. }
  486. }
  487. return true;
  488. }
  489. esp_err_t esp_image_verify_bootloader(uint32_t *length)
  490. {
  491. esp_image_metadata_t data;
  492. esp_err_t err = esp_image_verify_bootloader_data(&data);
  493. if (length != NULL) {
  494. *length = (err == ESP_OK) ? data.image_len : 0;
  495. }
  496. return err;
  497. }
  498. esp_err_t esp_image_verify_bootloader_data(esp_image_metadata_t *data)
  499. {
  500. if (data == NULL) {
  501. return ESP_ERR_INVALID_ARG;
  502. }
  503. const esp_partition_pos_t bootloader_part = {
  504. .offset = ESP_BOOTLOADER_OFFSET,
  505. .size = ESP_PARTITION_TABLE_OFFSET - ESP_BOOTLOADER_OFFSET,
  506. };
  507. return esp_image_verify(ESP_IMAGE_VERIFY,
  508. &bootloader_part,
  509. data);
  510. }
  511. static esp_err_t verify_checksum(bootloader_sha256_handle_t sha_handle, uint32_t checksum_word, esp_image_metadata_t *data)
  512. {
  513. uint32_t unpadded_length = data->image_len;
  514. uint32_t length = unpadded_length + 1; // Add a byte for the checksum
  515. length = (length + 15) & ~15; // Pad to next full 16 byte block
  516. // Verify checksum
  517. uint8_t buf[16];
  518. esp_err_t err = bootloader_flash_read(data->start_addr + unpadded_length, buf, length - unpadded_length, true);
  519. uint8_t calc = buf[length - unpadded_length - 1];
  520. uint8_t checksum = (checksum_word >> 24)
  521. ^ (checksum_word >> 16)
  522. ^ (checksum_word >> 8)
  523. ^ (checksum_word >> 0);
  524. if (err != ESP_OK || checksum != calc) {
  525. ESP_LOGE(TAG, "Checksum failed. Calculated 0x%x read 0x%x", checksum, calc);
  526. return ESP_ERR_IMAGE_INVALID;
  527. }
  528. if (sha_handle != NULL) {
  529. bootloader_sha256_data(sha_handle, buf, length - unpadded_length);
  530. }
  531. if (data->image.hash_appended) {
  532. // Account for the hash in the total image length
  533. length += HASH_LEN;
  534. }
  535. data->image_len = length;
  536. return ESP_OK;
  537. }
  538. static esp_err_t verify_secure_boot_signature(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data)
  539. {
  540. uint8_t image_hash[HASH_LEN] = { 0 };
  541. uint32_t end = data->start_addr + data->image_len;
  542. ESP_LOGI(TAG, "Verifying image signature...");
  543. // For secure boot, we calculate the signature hash over the whole file, which includes any "simple" hash
  544. // appended to the image for corruption detection
  545. if (data->image.hash_appended) {
  546. const void *simple_hash = bootloader_mmap(end - HASH_LEN, HASH_LEN);
  547. bootloader_sha256_data(sha_handle, simple_hash, HASH_LEN);
  548. bootloader_munmap(simple_hash);
  549. }
  550. #ifdef CONFIG_IDF_TARGET_ESP32S2BETA
  551. // Pad to 4096 byte sector boundary
  552. if (end % FLASH_SECTOR_SIZE != 0) {
  553. uint32_t pad_len = FLASH_SECTOR_SIZE - (end % FLASH_SECTOR_SIZE);
  554. const void *padding = bootloader_mmap(end, pad_len);
  555. bootloader_sha256_data(sha_handle, padding, pad_len);
  556. bootloader_munmap(padding);
  557. end += pad_len;
  558. }
  559. #endif
  560. bootloader_sha256_finish(sha_handle, image_hash);
  561. // Log the hash for debugging
  562. bootloader_debug_buffer(image_hash, HASH_LEN, "Calculated secure boot hash");
  563. // Use hash to verify signature block
  564. const esp_secure_boot_sig_block_t *sig_block = bootloader_mmap(data->start_addr + data->image_len, sizeof(esp_secure_boot_sig_block_t));
  565. esp_err_t err = esp_secure_boot_verify_signature_block(sig_block, image_hash);
  566. bootloader_munmap(sig_block);
  567. if (err != ESP_OK) {
  568. ESP_LOGE(TAG, "Secure boot signature verification failed");
  569. // Go back and check if the simple hash matches or not (we're off the fast path so we can re-hash the whole image now)
  570. ESP_LOGI(TAG, "Calculating simple hash to check for corruption...");
  571. const void *whole_image = bootloader_mmap(data->start_addr, data->image_len - HASH_LEN);
  572. if (whole_image != NULL) {
  573. sha_handle = bootloader_sha256_start();
  574. bootloader_sha256_data(sha_handle, whole_image, data->image_len - HASH_LEN);
  575. bootloader_munmap(whole_image);
  576. if (verify_simple_hash(sha_handle, data) != ESP_OK) {
  577. ESP_LOGW(TAG, "image corrupted on flash");
  578. } else {
  579. ESP_LOGW(TAG, "image valid, signature bad");
  580. }
  581. }
  582. return ESP_ERR_IMAGE_INVALID;
  583. }
  584. #if CONFIG_IDF_TARGET_ESP32S2BETA
  585. // Adjust image length result to include the appended signature
  586. data->image_len = end - data->start_addr + sizeof(ets_secure_boot_signature_t);
  587. #endif
  588. return ESP_OK;
  589. }
  590. static esp_err_t verify_simple_hash(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data)
  591. {
  592. uint8_t image_hash[HASH_LEN] = { 0 };
  593. bootloader_sha256_finish(sha_handle, image_hash);
  594. // Log the hash for debugging
  595. bootloader_debug_buffer(image_hash, HASH_LEN, "Calculated hash");
  596. // Simple hash for verification only
  597. const void *hash = bootloader_mmap(data->start_addr + data->image_len - HASH_LEN, HASH_LEN);
  598. if (memcmp(hash, image_hash, HASH_LEN) != 0) {
  599. ESP_LOGE(TAG, "Image hash failed - image is corrupt");
  600. bootloader_debug_buffer(hash, HASH_LEN, "Expected hash");
  601. bootloader_munmap(hash);
  602. return ESP_ERR_IMAGE_INVALID;
  603. }
  604. bootloader_munmap(hash);
  605. return ESP_OK;
  606. }