esp_image_format.c 36 KB

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