esp_image_format.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <sys/param.h>
  8. #include <esp_cpu.h>
  9. #include <bootloader_utility.h>
  10. #include <bootloader_signature.h>
  11. #include <esp_secure_boot.h>
  12. #include <esp_fault.h>
  13. #include <esp_log.h>
  14. #include <esp_attr.h>
  15. #include <spi_flash_mmap.h>
  16. #include <bootloader_flash_priv.h>
  17. #include <bootloader_random.h>
  18. #include <bootloader_sha.h>
  19. #include "bootloader_util.h"
  20. #include "bootloader_common.h"
  21. #include "esp_rom_sys.h"
  22. #include "bootloader_memory_utils.h"
  23. #include "soc/soc_caps.h"
  24. #if CONFIG_IDF_TARGET_ESP32
  25. #include "esp32/rom/secure_boot.h"
  26. #elif CONFIG_IDF_TARGET_ESP32S2
  27. #include "esp32s2/rom/secure_boot.h"
  28. #elif CONFIG_IDF_TARGET_ESP32S3
  29. #include "esp32s3/rom/secure_boot.h"
  30. #elif CONFIG_IDF_TARGET_ESP32C3
  31. #include "esp32c3/rom/secure_boot.h"
  32. #elif CONFIG_IDF_TARGET_ESP32H2
  33. #include "esp32h2/rom/secure_boot.h"
  34. #elif CONFIG_IDF_TARGET_ESP32C2
  35. #include "esp32c2/rom/rtc.h"
  36. #include "esp32c2/rom/secure_boot.h"
  37. #endif
  38. /* Checking signatures as part of verifying images is necessary:
  39. - Always if secure boot is enabled
  40. - Differently in bootloader and/or app, depending on kconfig
  41. */
  42. #ifdef BOOTLOADER_BUILD
  43. #ifdef CONFIG_SECURE_SIGNED_ON_BOOT
  44. #define SECURE_BOOT_CHECK_SIGNATURE 1
  45. #else
  46. #define SECURE_BOOT_CHECK_SIGNATURE 0
  47. #endif
  48. #else /* !BOOTLOADER_BUILD */
  49. #ifdef CONFIG_SECURE_SIGNED_ON_UPDATE
  50. #define SECURE_BOOT_CHECK_SIGNATURE 1
  51. #else
  52. #define SECURE_BOOT_CHECK_SIGNATURE 0
  53. #endif
  54. #endif
  55. static const char *TAG = "esp_image";
  56. #define HASH_LEN ESP_IMAGE_HASH_LEN
  57. #define SIXTEEN_MB 0x1000000
  58. #define ESP_ROM_CHECKSUM_INITIAL 0xEF
  59. /* Headroom to ensure between stack SP (at time of checking) and data loaded from flash */
  60. #define STACK_LOAD_HEADROOM 32768
  61. #ifdef BOOTLOADER_BUILD
  62. /* 64 bits of random data to obfuscate loaded RAM with, until verification is complete
  63. (Means loaded code isn't executable until after the secure boot check.)
  64. */
  65. static uint32_t ram_obfs_value[2];
  66. #endif
  67. /* Return true if load_addr is an address the bootloader should load into */
  68. static bool should_load(uint32_t load_addr);
  69. /* Return true if load_addr is an address the bootloader should map via flash cache */
  70. static bool should_map(uint32_t load_addr);
  71. static esp_err_t process_segments(esp_image_metadata_t *data, bool silent, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum);
  72. /* Load or verify a segment */
  73. 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);
  74. /* split segment and verify if data_len is too long */
  75. 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);
  76. /* Verify the main image header */
  77. static esp_err_t verify_image_header(uint32_t src_addr, const esp_image_header_t *image, bool silent);
  78. /* Verify a segment header */
  79. static esp_err_t verify_segment_header(int index, const esp_image_segment_header_t *segment, uint32_t segment_data_offs, bool silent);
  80. /* Log-and-fail macro for use in esp_image_load */
  81. #define FAIL_LOAD(...) do { \
  82. if (!silent) { \
  83. ESP_LOGE(TAG, __VA_ARGS__); \
  84. } \
  85. goto err; \
  86. } \
  87. while(0)
  88. #define CHECK_ERR(func) do { \
  89. if ((err = func) != ESP_OK) { \
  90. goto err; \
  91. } \
  92. } \
  93. while(0)
  94. static esp_err_t process_image_header(esp_image_metadata_t *data, uint32_t part_offset, bootloader_sha256_handle_t *sha_handle, bool do_verify, bool silent);
  95. static esp_err_t process_appended_hash(esp_image_metadata_t *data, uint32_t part_len, bool do_verify, bool silent);
  96. static esp_err_t process_checksum(bootloader_sha256_handle_t sha_handle, uint32_t checksum_word, esp_image_metadata_t *data, bool silent, bool skip_check_checksum);
  97. static esp_err_t __attribute__((unused)) verify_secure_boot_signature(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data, uint8_t *image_digest, uint8_t *verified_digest);
  98. static esp_err_t __attribute__((unused)) verify_simple_hash(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data);
  99. static esp_err_t image_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data)
  100. {
  101. #ifdef BOOTLOADER_BUILD
  102. bool do_load = (mode == ESP_IMAGE_LOAD) || (mode == ESP_IMAGE_LOAD_NO_VALIDATE);
  103. bool do_verify = (mode == ESP_IMAGE_LOAD) || (mode == ESP_IMAGE_VERIFY) || (mode == ESP_IMAGE_VERIFY_SILENT);
  104. #else
  105. bool do_load = false; // Can't load the image in app mode
  106. bool do_verify = true; // In app mode is available only verify mode
  107. #endif
  108. bool silent = (mode == ESP_IMAGE_VERIFY_SILENT);
  109. esp_err_t err = ESP_OK;
  110. // checksum the image a word at a time. This shaves 30-40ms per MB of image size
  111. uint32_t checksum_word = ESP_ROM_CHECKSUM_INITIAL;
  112. uint32_t *checksum = (do_verify) ? &checksum_word : NULL;
  113. bootloader_sha256_handle_t sha_handle = NULL;
  114. bool verify_sha;
  115. #if (SECURE_BOOT_CHECK_SIGNATURE == 1)
  116. /* used for anti-FI checks */
  117. uint8_t image_digest[HASH_LEN] = { [ 0 ... 31] = 0xEE };
  118. uint8_t verified_digest[HASH_LEN] = { [ 0 ... 31 ] = 0x01 };
  119. #endif
  120. if (data == NULL || part == NULL) {
  121. return ESP_ERR_INVALID_ARG;
  122. }
  123. #if CONFIG_SECURE_BOOT_V2_ENABLED
  124. // For Secure Boot V2, we do verify signature on bootloader which includes the SHA calculation.
  125. verify_sha = do_verify;
  126. #else // Secure boot not enabled
  127. // For secure boot V1 on ESP32, we don't calculate SHA or verify signature on bootloaders.
  128. // (For non-secure boot, we don't verify any SHA-256 hash appended to the bootloader because
  129. // esptool.py may have rewritten the header - rely on esptool.py having verified the bootloader at flashing time, instead.)
  130. verify_sha = (part->offset != ESP_BOOTLOADER_OFFSET) && do_verify;
  131. #endif
  132. if (part->size > SIXTEEN_MB) {
  133. err = ESP_ERR_INVALID_ARG;
  134. FAIL_LOAD("partition size 0x%x invalid, larger than 16MB", part->size);
  135. }
  136. bootloader_sha256_handle_t *p_sha_handle = &sha_handle;
  137. CHECK_ERR(process_image_header(data, part->offset, (verify_sha) ? p_sha_handle : NULL, do_verify, silent));
  138. CHECK_ERR(process_segments(data, silent, do_load, sha_handle, checksum));
  139. bool skip_check_checksum = !do_verify || esp_cpu_in_ocd_debug_mode();
  140. CHECK_ERR(process_checksum(sha_handle, checksum_word, data, silent, skip_check_checksum));
  141. CHECK_ERR(process_appended_hash(data, part->size, do_verify, silent));
  142. if (verify_sha) {
  143. #if (SECURE_BOOT_CHECK_SIGNATURE == 1)
  144. // secure boot images have a signature appended
  145. #if defined(BOOTLOADER_BUILD) && !defined(CONFIG_SECURE_BOOT)
  146. // If secure boot is not enabled in hardware, then
  147. // skip the signature check in bootloader when the debugger is attached.
  148. // This is done to allow for breakpoints in Flash.
  149. bool do_verify_sig = !esp_cpu_in_ocd_debug_mode();
  150. #else // CONFIG_SECURE_BOOT
  151. bool do_verify_sig = true;
  152. #endif // end checking for JTAG
  153. if (do_verify_sig) {
  154. err = verify_secure_boot_signature(sha_handle, data, image_digest, verified_digest);
  155. sha_handle = NULL; // verify_secure_boot_signature finishes sha_handle
  156. }
  157. #else // SECURE_BOOT_CHECK_SIGNATURE
  158. // No secure boot, but SHA-256 can be appended for basic corruption detection
  159. if (sha_handle != NULL && !esp_cpu_in_ocd_debug_mode()) {
  160. err = verify_simple_hash(sha_handle, data);
  161. sha_handle = NULL; // calling verify_simple_hash finishes sha_handle
  162. }
  163. #endif // SECURE_BOOT_CHECK_SIGNATURE
  164. } // verify_sha
  165. // bootloader may still have a sha256 digest handle open
  166. if (sha_handle != NULL) {
  167. bootloader_sha256_finish(sha_handle, NULL);
  168. sha_handle = NULL;
  169. }
  170. if (err != ESP_OK) {
  171. goto err;
  172. }
  173. #ifdef BOOTLOADER_BUILD
  174. #if (SECURE_BOOT_CHECK_SIGNATURE == 1)
  175. /* If signature was checked in bootloader build, verified_digest should equal image_digest
  176. This is to detect any fault injection that caused signature verification to not complete normally.
  177. Any attack which bypasses this check should be of limited use as the RAM contents are still obfuscated, therefore we do the check
  178. immediately before we deobfuscate.
  179. Note: the conditions for making this check are the same as for setting verify_sha above, but on ESP32 SB V1 we move the test for
  180. "only verify signature in bootloader" into the macro so it's tested multiple times.
  181. */
  182. #if CONFIG_SECURE_BOOT_V2_ENABLED
  183. ESP_FAULT_ASSERT(!esp_secure_boot_enabled() || memcmp(image_digest, verified_digest, HASH_LEN) == 0);
  184. #else // Secure Boot V1 on ESP32, only verify signatures for apps not bootloaders
  185. ESP_FAULT_ASSERT(data->start_addr == ESP_BOOTLOADER_OFFSET || memcmp(image_digest, verified_digest, HASH_LEN) == 0);
  186. #endif
  187. #endif // SECURE_BOOT_CHECK_SIGNATURE
  188. // Deobfuscate RAM
  189. if (do_load && ram_obfs_value[0] != 0 && ram_obfs_value[1] != 0) {
  190. for (int i = 0; i < data->image.segment_count; i++) {
  191. uint32_t load_addr = data->segments[i].load_addr;
  192. if (should_load(load_addr)) {
  193. uint32_t *loaded = (uint32_t *)load_addr;
  194. for (size_t j = 0; j < data->segments[i].data_len / sizeof(uint32_t); j++) {
  195. loaded[j] ^= (j & 1) ? ram_obfs_value[0] : ram_obfs_value[1];
  196. }
  197. }
  198. }
  199. }
  200. #endif // BOOTLOADER_BUILD
  201. // Success!
  202. return ESP_OK;
  203. err:
  204. if (err == ESP_OK) {
  205. err = ESP_ERR_IMAGE_INVALID;
  206. }
  207. if (sha_handle != NULL) {
  208. // Need to finish the hash process to free the handle
  209. bootloader_sha256_finish(sha_handle, NULL);
  210. }
  211. // Prevent invalid/incomplete data leaking out
  212. bzero(data, sizeof(esp_image_metadata_t));
  213. return err;
  214. }
  215. esp_err_t bootloader_load_image(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  216. {
  217. #if !defined(BOOTLOADER_BUILD)
  218. return ESP_FAIL;
  219. #else
  220. esp_image_load_mode_t mode = ESP_IMAGE_LOAD;
  221. #if !defined(CONFIG_SECURE_BOOT)
  222. /* Skip validation under particular configurations */
  223. #if CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS
  224. mode = ESP_IMAGE_LOAD_NO_VALIDATE;
  225. #elif CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON
  226. if (esp_rom_get_reset_reason(0) == RESET_REASON_CHIP_POWER_ON
  227. #if SOC_EFUSE_HAS_EFUSE_RST_BUG
  228. || esp_rom_get_reset_reason(0) == RESET_REASON_CORE_EFUSE_CRC
  229. #endif
  230. ) {
  231. mode = ESP_IMAGE_LOAD_NO_VALIDATE;
  232. }
  233. #endif // CONFIG_BOOTLOADER_SKIP_...
  234. #endif // CONFIG_SECURE_BOOT
  235. return image_load(mode, part, data);
  236. #endif // BOOTLOADER_BUILD
  237. }
  238. esp_err_t bootloader_load_image_no_verify(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  239. {
  240. #ifdef BOOTLOADER_BUILD
  241. return image_load(ESP_IMAGE_LOAD_NO_VALIDATE, part, data);
  242. #else
  243. return ESP_FAIL;
  244. #endif
  245. }
  246. esp_err_t esp_image_verify(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data)
  247. {
  248. return image_load(mode, part, data);
  249. }
  250. esp_err_t esp_image_get_metadata(const esp_partition_pos_t *part, esp_image_metadata_t *metadata)
  251. {
  252. esp_err_t err;
  253. if (metadata == NULL || part == NULL || part->size > SIXTEEN_MB) {
  254. return ESP_ERR_INVALID_ARG;
  255. }
  256. bool silent = true;
  257. bool do_verify = false;
  258. bool do_load = false;
  259. CHECK_ERR(process_image_header(metadata, part->offset, NULL, do_verify, silent));
  260. CHECK_ERR(process_segments(metadata, silent, do_load, NULL, NULL));
  261. bool skip_check_checksum = true;
  262. CHECK_ERR(process_checksum(NULL, 0, metadata, silent, skip_check_checksum));
  263. CHECK_ERR(process_appended_hash(metadata, part->size, true, silent));
  264. return ESP_OK;
  265. err:
  266. return err;
  267. }
  268. static esp_err_t verify_image_header(uint32_t src_addr, const esp_image_header_t *image, bool silent)
  269. {
  270. esp_err_t err = ESP_OK;
  271. ESP_LOGD(TAG, "image header: 0x%02x 0x%02x 0x%02x 0x%02x %08x",
  272. image->magic,
  273. image->segment_count,
  274. image->spi_mode,
  275. image->spi_size,
  276. image->entry_addr);
  277. if (image->magic != ESP_IMAGE_HEADER_MAGIC) {
  278. FAIL_LOAD("image at 0x%x has invalid magic byte (nothing flashed here?)", src_addr);
  279. }
  280. // Checking the chip revision header *will* print a bunch of other info
  281. // regardless of silent setting as this may be important, but don't bother checking it
  282. // if it looks like the app partition is erased or otherwise garbage
  283. CHECK_ERR(bootloader_common_check_chip_validity(image, ESP_IMAGE_APPLICATION));
  284. if (image->segment_count > ESP_IMAGE_MAX_SEGMENTS) {
  285. FAIL_LOAD("image at 0x%x segment count %d exceeds max %d", src_addr, image->segment_count, ESP_IMAGE_MAX_SEGMENTS);
  286. }
  287. return err;
  288. err:
  289. if (err == ESP_OK) {
  290. err = ESP_ERR_IMAGE_INVALID;
  291. }
  292. return err;
  293. }
  294. #ifdef BOOTLOADER_BUILD
  295. /* Check the region load_addr - load_end doesn't overlap any memory used by the bootloader, registers, or other invalid memory
  296. */
  297. static bool verify_load_addresses(int segment_index, intptr_t load_addr, intptr_t load_end, bool print_error, bool no_recurse)
  298. {
  299. /* Addresses of static data and the "loader" section of bootloader IRAM, all defined in ld script */
  300. const char *reason = NULL;
  301. extern int _dram_start, _dram_end, _loader_text_start, _loader_text_end;
  302. void *load_addr_p = (void *)load_addr;
  303. void *load_inclusive_end_p = (void *)load_end - 0x1;
  304. void *load_exclusive_end_p = (void *)load_end;
  305. if (load_end == load_addr) {
  306. return true; // zero-length segments are fine
  307. }
  308. assert(load_end > load_addr); // data_len<16MB is checked in verify_segment_header() which is called before this, so this should always be true
  309. if (esp_ptr_in_dram(load_addr_p) && esp_ptr_in_dram(load_inclusive_end_p)) { /* Writing to DRAM */
  310. /* Check if we're clobbering the stack */
  311. intptr_t sp = (intptr_t)esp_cpu_get_sp();
  312. if (bootloader_util_regions_overlap(sp - STACK_LOAD_HEADROOM, SOC_ROM_STACK_START,
  313. load_addr, load_end)) {
  314. reason = "overlaps bootloader stack";
  315. goto invalid;
  316. }
  317. /* Check if we're clobbering static data
  318. (_dram_start.._dram_end includes bss, data, rodata sections in DRAM)
  319. */
  320. if (bootloader_util_regions_overlap((intptr_t)&_dram_start, (intptr_t)&_dram_end, load_addr, load_end)) {
  321. reason = "overlaps bootloader data";
  322. goto invalid;
  323. }
  324. /* LAST DRAM CHECK (recursive): for D/IRAM, check the equivalent IRAM addresses if needed
  325. Allow for the possibility that even though both pointers are IRAM, only part of the region is in a D/IRAM
  326. section. In which case we recurse to check the part which falls in D/IRAM.
  327. Note: We start with SOC_DIRAM_DRAM_LOW/HIGH and convert that address to IRAM to account for any reversing of word order
  328. (chip-specific).
  329. */
  330. if (!no_recurse && bootloader_util_regions_overlap(SOC_DIRAM_DRAM_LOW, SOC_DIRAM_DRAM_HIGH, load_addr, load_end)) {
  331. intptr_t iram_load_addr, iram_load_end;
  332. if (esp_ptr_in_diram_dram(load_addr_p)) {
  333. iram_load_addr = (intptr_t)esp_ptr_diram_dram_to_iram(load_addr_p);
  334. } else {
  335. iram_load_addr = (intptr_t)esp_ptr_diram_dram_to_iram((void *)SOC_DIRAM_DRAM_LOW);
  336. }
  337. if (esp_ptr_in_diram_dram(load_inclusive_end_p)) {
  338. iram_load_end = (intptr_t)esp_ptr_diram_dram_to_iram(load_exclusive_end_p);
  339. } else {
  340. iram_load_end = (intptr_t)esp_ptr_diram_dram_to_iram((void *)SOC_DIRAM_DRAM_HIGH);
  341. }
  342. if (iram_load_end < iram_load_addr) {
  343. return verify_load_addresses(segment_index, iram_load_end, iram_load_addr, print_error, true);
  344. } else {
  345. return verify_load_addresses(segment_index, iram_load_addr, iram_load_end, print_error, true);
  346. }
  347. }
  348. }
  349. else if (esp_ptr_in_iram(load_addr_p) && esp_ptr_in_iram(load_inclusive_end_p)) { /* Writing to IRAM */
  350. /* Check for overlap of 'loader' section of IRAM */
  351. if (bootloader_util_regions_overlap((intptr_t)&_loader_text_start, (intptr_t)&_loader_text_end,
  352. load_addr, load_end)) {
  353. reason = "overlaps loader IRAM";
  354. goto invalid;
  355. }
  356. /* LAST IRAM CHECK (recursive): for D/IRAM, check the equivalent DRAM address if needed
  357. Allow for the possibility that even though both pointers are IRAM, only part of the region is in a D/IRAM
  358. section. In which case we recurse to check the part which falls in D/IRAM.
  359. Note: We start with SOC_DIRAM_IRAM_LOW/HIGH and convert that address to DRAM to account for any reversing of word order
  360. (chip-specific).
  361. */
  362. if (!no_recurse && bootloader_util_regions_overlap(SOC_DIRAM_IRAM_LOW, SOC_DIRAM_IRAM_HIGH, load_addr, load_end)) {
  363. intptr_t dram_load_addr, dram_load_end;
  364. if (esp_ptr_in_diram_iram(load_addr_p)) {
  365. dram_load_addr = (intptr_t)esp_ptr_diram_iram_to_dram(load_addr_p);
  366. } else {
  367. dram_load_addr = (intptr_t)esp_ptr_diram_iram_to_dram((void *)SOC_DIRAM_IRAM_LOW);
  368. }
  369. if (esp_ptr_in_diram_iram(load_inclusive_end_p)) {
  370. dram_load_end = (intptr_t)esp_ptr_diram_iram_to_dram(load_exclusive_end_p);
  371. } else {
  372. dram_load_end = (intptr_t)esp_ptr_diram_iram_to_dram((void *)SOC_DIRAM_IRAM_HIGH);
  373. }
  374. if (dram_load_end < dram_load_addr) {
  375. return verify_load_addresses(segment_index, dram_load_end, dram_load_addr, print_error, true);
  376. } else {
  377. return verify_load_addresses(segment_index, dram_load_addr, dram_load_end, print_error, true);
  378. }
  379. }
  380. /* Sections entirely in RTC memory won't overlap with a vanilla bootloader but are valid load addresses, thus skipping them from the check */
  381. }
  382. #if SOC_RTC_FAST_MEM_SUPPORTED
  383. else if (esp_ptr_in_rtc_iram_fast(load_addr_p) && esp_ptr_in_rtc_iram_fast(load_inclusive_end_p)){
  384. return true;
  385. } else if (esp_ptr_in_rtc_dram_fast(load_addr_p) && esp_ptr_in_rtc_dram_fast(load_inclusive_end_p)){
  386. return true;
  387. }
  388. #endif
  389. #if SOC_RTC_SLOW_MEM_SUPPORTED
  390. else if (esp_ptr_in_rtc_slow(load_addr_p) && esp_ptr_in_rtc_slow(load_inclusive_end_p)) {
  391. return true;
  392. }
  393. #endif
  394. else { /* Not a DRAM or an IRAM or RTC Fast IRAM, RTC Fast DRAM or RTC Slow address */
  395. reason = "bad load address range";
  396. goto invalid;
  397. }
  398. return true;
  399. invalid:
  400. if (print_error) {
  401. ESP_LOGE(TAG, "Segment %d 0x%08x-0x%08x invalid: %s", segment_index, load_addr, load_end, reason);
  402. }
  403. return false;
  404. }
  405. #endif // BOOTLOADER_BUILD
  406. static esp_err_t process_image_header(esp_image_metadata_t *data, uint32_t part_offset, bootloader_sha256_handle_t *sha_handle, bool do_verify, bool silent)
  407. {
  408. esp_err_t err;
  409. bzero(data, sizeof(esp_image_metadata_t));
  410. data->start_addr = part_offset;
  411. ESP_LOGD(TAG, "reading image header @ 0x%x", data->start_addr);
  412. CHECK_ERR(bootloader_flash_read(data->start_addr, &data->image, sizeof(esp_image_header_t), true));
  413. if (do_verify) {
  414. // Calculate SHA-256 of image if secure boot is on, or if image has a hash appended
  415. if (SECURE_BOOT_CHECK_SIGNATURE || data->image.hash_appended) {
  416. if (sha_handle != NULL) {
  417. *sha_handle = bootloader_sha256_start();
  418. if (*sha_handle == NULL) {
  419. return ESP_ERR_NO_MEM;
  420. }
  421. bootloader_sha256_data(*sha_handle, &data->image, sizeof(esp_image_header_t));
  422. }
  423. }
  424. CHECK_ERR(verify_image_header(data->start_addr, &data->image, silent));
  425. }
  426. data->image_len = sizeof(esp_image_header_t);
  427. return ESP_OK;
  428. err:
  429. return err;
  430. }
  431. static esp_err_t process_segments(esp_image_metadata_t *data, bool silent, bool do_load, bootloader_sha256_handle_t sha_handle, uint32_t *checksum)
  432. {
  433. esp_err_t err = ESP_OK;
  434. uint32_t start_segments = data->start_addr + data->image_len;
  435. uint32_t next_addr = start_segments;
  436. for (int i = 0; i < data->image.segment_count; i++) {
  437. esp_image_segment_header_t *header = &data->segments[i];
  438. ESP_LOGV(TAG, "loading segment header %d at offset 0x%x", i, next_addr);
  439. CHECK_ERR(process_segment(i, next_addr, header, silent, do_load, sha_handle, checksum));
  440. next_addr += sizeof(esp_image_segment_header_t);
  441. data->segment_data[i] = next_addr;
  442. next_addr += header->data_len;
  443. }
  444. // Segments all loaded, verify length
  445. uint32_t end_addr = next_addr;
  446. if (end_addr < data->start_addr) {
  447. FAIL_LOAD("image offset has wrapped");
  448. }
  449. data->image_len += end_addr - start_segments;
  450. ESP_LOGV(TAG, "image start 0x%08x end of last section 0x%08x", data->start_addr, end_addr);
  451. return err;
  452. err:
  453. if (err == ESP_OK) {
  454. err = ESP_ERR_IMAGE_INVALID;
  455. }
  456. return err;
  457. }
  458. 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)
  459. {
  460. esp_err_t err;
  461. /* read segment header */
  462. err = bootloader_flash_read(flash_addr, header, sizeof(esp_image_segment_header_t), true);
  463. if (err != ESP_OK) {
  464. ESP_LOGE(TAG, "bootloader_flash_read failed at 0x%08x", flash_addr);
  465. return err;
  466. }
  467. if (sha_handle != NULL) {
  468. bootloader_sha256_data(sha_handle, header, sizeof(esp_image_segment_header_t));
  469. }
  470. intptr_t load_addr = header->load_addr;
  471. uint32_t data_len = header->data_len;
  472. uint32_t data_addr = flash_addr + sizeof(esp_image_segment_header_t);
  473. ESP_LOGV(TAG, "segment data length 0x%x data starts 0x%x", data_len, data_addr);
  474. CHECK_ERR(verify_segment_header(index, header, data_addr, silent));
  475. if (data_len % 4 != 0) {
  476. FAIL_LOAD("unaligned segment length 0x%x", data_len);
  477. }
  478. bool is_mapping = should_map(load_addr);
  479. do_load = do_load && should_load(load_addr);
  480. if (!silent) {
  481. ESP_LOGI(TAG, "segment %d: paddr=%08x vaddr=%08x size=%05xh (%6d) %s",
  482. index, data_addr, load_addr,
  483. data_len, data_len,
  484. (do_load) ? "load" : (is_mapping) ? "map" : "");
  485. }
  486. #ifdef BOOTLOADER_BUILD
  487. /* Before loading segment, check it doesn't clobber bootloader RAM. */
  488. if (do_load && data_len > 0) {
  489. if (!verify_load_addresses(index, load_addr, load_addr + data_len, true, false)) {
  490. return ESP_ERR_IMAGE_INVALID;
  491. }
  492. }
  493. #endif // BOOTLOADER_BUILD
  494. uint32_t free_page_count = bootloader_mmap_get_free_pages();
  495. ESP_LOGD(TAG, "free data page_count 0x%08x", free_page_count);
  496. uint32_t data_len_remain = data_len;
  497. while (data_len_remain > 0) {
  498. #if (SECURE_BOOT_CHECK_SIGNATURE == 1) && defined(BOOTLOADER_BUILD)
  499. /* Double check the address verification done above */
  500. ESP_FAULT_ASSERT(!do_load || verify_load_addresses(0, load_addr, load_addr + data_len_remain, false, false));
  501. #endif
  502. uint32_t offset_page = ((data_addr & MMAP_ALIGNED_MASK) != 0) ? 1 : 0;
  503. /* Data we could map in case we are not aligned to PAGE boundary is one page size lesser. */
  504. data_len = MIN(data_len_remain, ((free_page_count - offset_page) * SPI_FLASH_MMU_PAGE_SIZE));
  505. CHECK_ERR(process_segment_data(load_addr, data_addr, data_len, do_load, sha_handle, checksum));
  506. data_addr += data_len;
  507. data_len_remain -= data_len;
  508. }
  509. return ESP_OK;
  510. err:
  511. if (err == ESP_OK) {
  512. err = ESP_ERR_IMAGE_INVALID;
  513. }
  514. return err;
  515. }
  516. 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)
  517. {
  518. // If we are not loading, and the checksum is empty, skip processing this
  519. // segment for data
  520. if (!do_load && checksum == NULL) {
  521. ESP_LOGD(TAG, "skipping checksum for segment");
  522. return ESP_OK;
  523. }
  524. const uint32_t *data = (const uint32_t *)bootloader_mmap(data_addr, data_len);
  525. if (!data) {
  526. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed",
  527. data_addr, data_len);
  528. return ESP_FAIL;
  529. }
  530. if (checksum == NULL && sha_handle == NULL) {
  531. memcpy((void *)load_addr, data, data_len);
  532. bootloader_munmap(data);
  533. return ESP_OK;
  534. }
  535. #ifdef BOOTLOADER_BUILD
  536. // Set up the obfuscation value to use for loading
  537. while (ram_obfs_value[0] == 0 || ram_obfs_value[1] == 0) {
  538. bootloader_fill_random(ram_obfs_value, sizeof(ram_obfs_value));
  539. #if CONFIG_IDF_ENV_FPGA
  540. /* FPGA doesn't always emulate the RNG */
  541. ram_obfs_value[0] ^= 0x33;
  542. ram_obfs_value[1] ^= 0x66;
  543. #endif
  544. }
  545. uint32_t *dest = (uint32_t *)load_addr;
  546. #endif
  547. const uint32_t *src = data;
  548. for (size_t i = 0; i < data_len; i += 4) {
  549. int w_i = i / 4; // Word index
  550. uint32_t w = src[w_i];
  551. if (checksum != NULL) {
  552. *checksum ^= w;
  553. }
  554. #ifdef BOOTLOADER_BUILD
  555. if (do_load) {
  556. dest[w_i] = w ^ ((w_i & 1) ? ram_obfs_value[0] : ram_obfs_value[1]);
  557. }
  558. #endif
  559. // SHA_CHUNK determined experimentally as the optimum size
  560. // to call bootloader_sha256_data() with. This is a bit
  561. // counter-intuitive, but it's ~3ms better than using the
  562. // SHA256 block size.
  563. const size_t SHA_CHUNK = 1024;
  564. if (sha_handle != NULL && i % SHA_CHUNK == 0) {
  565. bootloader_sha256_data(sha_handle, &src[w_i],
  566. MIN(SHA_CHUNK, data_len - i));
  567. }
  568. }
  569. bootloader_munmap(data);
  570. return ESP_OK;
  571. }
  572. static esp_err_t verify_segment_header(int index, const esp_image_segment_header_t *segment, uint32_t segment_data_offs, bool silent)
  573. {
  574. if ((segment->data_len & 3) != 0
  575. || segment->data_len >= SIXTEEN_MB) {
  576. if (!silent) {
  577. ESP_LOGE(TAG, "invalid segment length 0x%x", segment->data_len);
  578. }
  579. return ESP_ERR_IMAGE_INVALID;
  580. }
  581. uint32_t load_addr = segment->load_addr;
  582. bool map_segment = should_map(load_addr);
  583. /* Check that flash cache mapped segment aligns correctly from flash to its mapped address,
  584. relative to the 64KB page mapping size.
  585. */
  586. ESP_LOGV(TAG, "segment %d map_segment %d segment_data_offs 0x%x load_addr 0x%x",
  587. index, map_segment, segment_data_offs, load_addr);
  588. if (map_segment
  589. && ((segment_data_offs % SPI_FLASH_MMU_PAGE_SIZE) != (load_addr % SPI_FLASH_MMU_PAGE_SIZE))) {
  590. if (!silent) {
  591. ESP_LOGE(TAG, "Segment %d load address 0x%08x, doesn't match data 0x%08x",
  592. index, load_addr, segment_data_offs);
  593. }
  594. return ESP_ERR_IMAGE_INVALID;
  595. }
  596. return ESP_OK;
  597. }
  598. static bool should_map(uint32_t load_addr)
  599. {
  600. return (load_addr >= SOC_IROM_LOW && load_addr < SOC_IROM_HIGH)
  601. || (load_addr >= SOC_DROM_LOW && load_addr < SOC_DROM_HIGH);
  602. }
  603. static bool should_load(uint32_t load_addr)
  604. {
  605. /* Reload the RTC memory segments whenever a non-deepsleep reset
  606. is occurring */
  607. bool load_rtc_memory = esp_rom_get_reset_reason(0) != RESET_REASON_CORE_DEEP_SLEEP;
  608. if (should_map(load_addr)) {
  609. return false;
  610. }
  611. if (load_addr < 0x10000000) {
  612. // Reserved for non-loaded addresses.
  613. // Current reserved values are
  614. // 0x0 (padding block)
  615. // 0x4 (unused, but reserved for an MD5 block)
  616. return false;
  617. }
  618. if (!load_rtc_memory) {
  619. #if SOC_RTC_FAST_MEM_SUPPORTED
  620. if (load_addr >= SOC_RTC_IRAM_LOW && load_addr < SOC_RTC_IRAM_HIGH) {
  621. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  622. return false;
  623. }
  624. if (load_addr >= SOC_RTC_DRAM_LOW && load_addr < SOC_RTC_DRAM_HIGH) {
  625. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  626. return false;
  627. }
  628. #endif
  629. #if SOC_RTC_SLOW_MEM_SUPPORTED
  630. if (load_addr >= SOC_RTC_DATA_LOW && load_addr < SOC_RTC_DATA_HIGH) {
  631. ESP_LOGD(TAG, "Skipping RTC slow memory segment at 0x%08x", load_addr);
  632. return false;
  633. }
  634. #endif
  635. }
  636. return true;
  637. }
  638. esp_err_t esp_image_verify_bootloader(uint32_t *length)
  639. {
  640. esp_image_metadata_t data;
  641. esp_err_t err = esp_image_verify_bootloader_data(&data);
  642. if (length != NULL) {
  643. *length = (err == ESP_OK) ? data.image_len : 0;
  644. }
  645. return err;
  646. }
  647. esp_err_t esp_image_verify_bootloader_data(esp_image_metadata_t *data)
  648. {
  649. if (data == NULL) {
  650. return ESP_ERR_INVALID_ARG;
  651. }
  652. const esp_partition_pos_t bootloader_part = {
  653. .offset = ESP_BOOTLOADER_OFFSET,
  654. .size = ESP_PARTITION_TABLE_OFFSET - ESP_BOOTLOADER_OFFSET,
  655. };
  656. return esp_image_verify(ESP_IMAGE_VERIFY,
  657. &bootloader_part,
  658. data);
  659. }
  660. static esp_err_t process_appended_hash(esp_image_metadata_t *data, uint32_t part_len, bool do_verify, bool silent)
  661. {
  662. esp_err_t err = ESP_OK;
  663. if (data->image.hash_appended) {
  664. // Account for the hash in the total image length
  665. if (do_verify) {
  666. CHECK_ERR(bootloader_flash_read(data->start_addr + data->image_len, &data->image_digest, HASH_LEN, true));
  667. }
  668. data->image_len += HASH_LEN;
  669. }
  670. if (data->image_len > part_len) {
  671. FAIL_LOAD("Image length %d doesn't fit in partition length %d", data->image_len, part_len);
  672. }
  673. return err;
  674. err:
  675. if (err == ESP_OK) {
  676. err = ESP_ERR_IMAGE_INVALID;
  677. }
  678. return err;
  679. }
  680. static esp_err_t process_checksum(bootloader_sha256_handle_t sha_handle, uint32_t checksum_word, esp_image_metadata_t *data, bool silent, bool skip_check_checksum)
  681. {
  682. esp_err_t err = ESP_OK;
  683. uint32_t unpadded_length = data->image_len;
  684. uint32_t length = unpadded_length + 1; // Add a byte for the checksum
  685. length = (length + 15) & ~15; // Pad to next full 16 byte block
  686. length = length - unpadded_length;
  687. // Verify checksum
  688. WORD_ALIGNED_ATTR uint8_t buf[16] = {0};
  689. if (!skip_check_checksum || sha_handle != NULL) {
  690. CHECK_ERR(bootloader_flash_read(data->start_addr + unpadded_length, buf, length, true));
  691. }
  692. uint8_t read_checksum = buf[length - 1];
  693. uint8_t calc_checksum = (checksum_word >> 24) ^ (checksum_word >> 16) ^ (checksum_word >> 8) ^ (checksum_word >> 0);
  694. if (!skip_check_checksum && calc_checksum != read_checksum) {
  695. FAIL_LOAD("Checksum failed. Calculated 0x%x read 0x%x", calc_checksum, read_checksum);
  696. }
  697. if (sha_handle != NULL) {
  698. bootloader_sha256_data(sha_handle, buf, length);
  699. }
  700. data->image_len += length;
  701. return err;
  702. err:
  703. if (err == ESP_OK) {
  704. err = ESP_ERR_IMAGE_INVALID;
  705. }
  706. return err;
  707. }
  708. static esp_err_t verify_secure_boot_signature(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data, uint8_t *image_digest, uint8_t *verified_digest)
  709. {
  710. #if (SECURE_BOOT_CHECK_SIGNATURE == 1)
  711. uint32_t end = data->start_addr + data->image_len;
  712. ESP_LOGI(TAG, "Verifying image signature...");
  713. // For secure boot, we calculate the signature hash over the whole file, which includes any "simple" hash
  714. // appended to the image for corruption detection
  715. if (data->image.hash_appended) {
  716. const void *simple_hash = bootloader_mmap(end - HASH_LEN, HASH_LEN);
  717. bootloader_sha256_data(sha_handle, simple_hash, HASH_LEN);
  718. bootloader_munmap(simple_hash);
  719. }
  720. #if CONFIG_SECURE_BOOT_V2_ENABLED
  721. // End of the image needs to be padded all the way to a 4KB boundary, after the simple hash
  722. // (for apps they are usually already padded due to --secure-pad-v2, only a problem if this option was not used.)
  723. uint32_t padded_end = (end + FLASH_SECTOR_SIZE - 1) & ~(FLASH_SECTOR_SIZE-1);
  724. if (padded_end > end) {
  725. const void *padding = bootloader_mmap(end, padded_end - end);
  726. bootloader_sha256_data(sha_handle, padding, padded_end - end);
  727. bootloader_munmap(padding);
  728. end = padded_end;
  729. }
  730. #endif
  731. bootloader_sha256_finish(sha_handle, image_digest);
  732. // Log the hash for debugging
  733. bootloader_debug_buffer(image_digest, HASH_LEN, "Calculated secure boot hash");
  734. // Use hash to verify signature block
  735. esp_err_t err = ESP_ERR_IMAGE_INVALID;
  736. #if CONFIG_SECURE_BOOT || CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT
  737. const void *sig_block;
  738. ESP_FAULT_ASSERT(memcmp(image_digest, verified_digest, HASH_LEN) != 0); /* sanity check that these values start differently */
  739. #if defined(CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME)
  740. sig_block = bootloader_mmap(data->start_addr + data->image_len, sizeof(esp_secure_boot_sig_block_t));
  741. err = esp_secure_boot_verify_ecdsa_signature_block(sig_block, image_digest, verified_digest);
  742. #else
  743. sig_block = bootloader_mmap(end, sizeof(ets_secure_boot_signature_t));
  744. err = esp_secure_boot_verify_sbv2_signature_block(sig_block, image_digest, verified_digest);
  745. #endif
  746. bootloader_munmap(sig_block);
  747. #endif // CONFIG_SECURE_BOOT || CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT
  748. if (err != ESP_OK) {
  749. ESP_LOGE(TAG, "Secure boot signature verification failed");
  750. // 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)
  751. ESP_LOGI(TAG, "Calculating simple hash to check for corruption...");
  752. const void *whole_image = bootloader_mmap(data->start_addr, data->image_len - HASH_LEN);
  753. if (whole_image != NULL) {
  754. sha_handle = bootloader_sha256_start();
  755. bootloader_sha256_data(sha_handle, whole_image, data->image_len - HASH_LEN);
  756. bootloader_munmap(whole_image);
  757. if (verify_simple_hash(sha_handle, data) != ESP_OK) {
  758. ESP_LOGW(TAG, "image corrupted on flash");
  759. } else {
  760. ESP_LOGW(TAG, "image valid, signature bad");
  761. }
  762. }
  763. return ESP_ERR_IMAGE_INVALID;
  764. }
  765. #if CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME || CONFIG_SECURE_SIGNED_APPS_ECDSA_V2_SCHEME
  766. // Adjust image length result to include the appended signature
  767. data->image_len = end - data->start_addr + sizeof(ets_secure_boot_signature_t);
  768. #endif
  769. #endif // SECURE_BOOT_CHECK_SIGNATURE
  770. return ESP_OK;
  771. }
  772. static esp_err_t verify_simple_hash(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data)
  773. {
  774. uint8_t image_hash[HASH_LEN] = { 0 };
  775. bootloader_sha256_finish(sha_handle, image_hash);
  776. // Log the hash for debugging
  777. bootloader_debug_buffer(image_hash, HASH_LEN, "Calculated hash");
  778. // Simple hash for verification only
  779. if (memcmp(data->image_digest, image_hash, HASH_LEN) != 0) {
  780. ESP_LOGE(TAG, "Image hash failed - image is corrupt");
  781. bootloader_debug_buffer(data->image_digest, HASH_LEN, "Expected hash");
  782. #ifdef CONFIG_IDF_ENV_FPGA
  783. ESP_LOGW(TAG, "Ignoring invalid SHA-256 as running on FPGA");
  784. return ESP_OK;
  785. #endif
  786. return ESP_ERR_IMAGE_INVALID;
  787. }
  788. return ESP_OK;
  789. }
  790. int esp_image_get_flash_size(esp_image_flash_size_t app_flash_size)
  791. {
  792. switch (app_flash_size) {
  793. case ESP_IMAGE_FLASH_SIZE_1MB:
  794. return 1 * 1024 * 1024;
  795. case ESP_IMAGE_FLASH_SIZE_2MB:
  796. return 2 * 1024 * 1024;
  797. case ESP_IMAGE_FLASH_SIZE_4MB:
  798. return 4 * 1024 * 1024;
  799. case ESP_IMAGE_FLASH_SIZE_8MB:
  800. return 8 * 1024 * 1024;
  801. case ESP_IMAGE_FLASH_SIZE_16MB:
  802. return 16 * 1024 * 1024;
  803. case ESP_IMAGE_FLASH_SIZE_32MB:
  804. return 32 * 1024 * 1024;
  805. case ESP_IMAGE_FLASH_SIZE_64MB:
  806. return 64 * 1024 * 1024;
  807. case ESP_IMAGE_FLASH_SIZE_128MB:
  808. return 128 * 1024 * 1024;
  809. default:
  810. return 0;
  811. }
  812. }