esp_image_format.c 23 KB

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