esp_image_format.c 33 KB

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