esp_image_format.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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_ESP32S2BETA
  32. #include <esp32s2beta/rom/rtc.h>
  33. #include <esp32s2beta/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 avalible 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. err = verify_secure_boot_signature(sha_handle, data, image_digest, verified_digest);
  190. #else
  191. // No secure boot, but SHA-256 can be appended for basic corruption detection
  192. if (sha_handle != NULL && !esp_cpu_in_ocd_debug_mode()) {
  193. err = verify_simple_hash(sha_handle, data);
  194. sha_handle = NULL; // calling verify_simple_hash finishes sha_handle
  195. }
  196. #endif // SECURE_BOOT_CHECK_SIGNATURE
  197. } else { // verify_sha
  198. // bootloader may still have a sha256 digest handle open
  199. if (sha_handle != NULL) {
  200. bootloader_sha256_finish(sha_handle, NULL);
  201. }
  202. sha_handle = NULL;
  203. } //verify_sha
  204. // Separately, if there's a hash appended to the image then copy it out to the data->image_digest field
  205. if (data->image.hash_appended) {
  206. const void *hash = bootloader_mmap(data->start_addr + data->image_len - HASH_LEN, HASH_LEN);
  207. if (hash == NULL) {
  208. err = ESP_FAIL;
  209. goto err;
  210. }
  211. memcpy(data->image_digest, hash, HASH_LEN);
  212. bootloader_munmap(hash);
  213. }
  214. } // do_verify
  215. if (err != ESP_OK) {
  216. goto err;
  217. }
  218. #ifdef BOOTLOADER_BUILD
  219. #ifdef SECURE_BOOT_CHECK_SIGNATURE
  220. /* If signature was checked in bootloader build, verified_digest should equal image_digest
  221. This is to detect any fault injection that caused signature verification to not complete normally.
  222. Any attack which bypasses this check should be of limited use as the RAM contents are still obfuscated, therefore we do the check
  223. immediately before we deobfuscate.
  224. 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
  225. "only verify signature in bootloader" into the macro so it's tested multiple times.
  226. */
  227. #if CONFIG_SECURE_BOOT_V2_ENABLED
  228. ESP_FAULT_ASSERT(memcmp(image_digest, verified_digest, HASH_LEN) == 0);
  229. #else // Secure Boot V1 on ESP32, only verify signatures for apps not bootloaders
  230. ESP_FAULT_ASSERT(data->start_addr == ESP_BOOTLOADER_OFFSET || memcmp(image_digest, verified_digest, HASH_LEN) == 0);
  231. #endif
  232. #endif // SECURE_BOOT_CHECK_SIGNATURE
  233. // Deobfuscate RAM
  234. if (do_load && ram_obfs_value[0] != 0 && ram_obfs_value[1] != 0) {
  235. for (int i = 0; i < data->image.segment_count; i++) {
  236. uint32_t load_addr = data->segments[i].load_addr;
  237. if (should_load(load_addr)) {
  238. uint32_t *loaded = (uint32_t *)load_addr;
  239. for (int j = 0; j < data->segments[i].data_len / sizeof(uint32_t); j++) {
  240. loaded[j] ^= (j & 1) ? ram_obfs_value[0] : ram_obfs_value[1];
  241. }
  242. }
  243. }
  244. }
  245. #endif
  246. // Success!
  247. return ESP_OK;
  248. err:
  249. if (err == ESP_OK) {
  250. err = ESP_ERR_IMAGE_INVALID;
  251. }
  252. if (sha_handle != NULL) {
  253. // Need to finish the hash process to free the handle
  254. bootloader_sha256_finish(sha_handle, NULL);
  255. }
  256. // Prevent invalid/incomplete data leaking out
  257. bzero(data, sizeof(esp_image_metadata_t));
  258. return err;
  259. }
  260. esp_err_t bootloader_load_image(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  261. {
  262. #ifdef BOOTLOADER_BUILD
  263. return image_load(ESP_IMAGE_LOAD, part, data);
  264. #else
  265. return ESP_FAIL;
  266. #endif
  267. }
  268. esp_err_t bootloader_load_image_no_verify(const esp_partition_pos_t *part, esp_image_metadata_t *data)
  269. {
  270. #ifdef BOOTLOADER_BUILD
  271. return image_load(ESP_IMAGE_LOAD_NO_VALIDATE, part, data);
  272. #else
  273. return ESP_FAIL;
  274. #endif
  275. }
  276. esp_err_t esp_image_verify(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data)
  277. {
  278. return image_load(mode, part, data);
  279. }
  280. static esp_err_t verify_image_header(uint32_t src_addr, const esp_image_header_t *image, bool silent)
  281. {
  282. esp_err_t err = ESP_OK;
  283. if (image->magic != ESP_IMAGE_HEADER_MAGIC) {
  284. if (!silent) {
  285. ESP_LOGE(TAG, "image at 0x%x has invalid magic byte", src_addr);
  286. }
  287. err = ESP_ERR_IMAGE_INVALID;
  288. }
  289. if (!silent) {
  290. if (image->spi_mode > ESP_IMAGE_SPI_MODE_SLOW_READ) {
  291. ESP_LOGW(TAG, "image at 0x%x has invalid SPI mode %d", src_addr, image->spi_mode);
  292. }
  293. if (image->spi_speed > ESP_IMAGE_SPI_SPEED_80M) {
  294. ESP_LOGW(TAG, "image at 0x%x has invalid SPI speed %d", src_addr, image->spi_speed);
  295. }
  296. if (image->spi_size > ESP_IMAGE_FLASH_SIZE_MAX) {
  297. ESP_LOGW(TAG, "image at 0x%x has invalid SPI size %d", src_addr, image->spi_size);
  298. }
  299. }
  300. if (err == ESP_OK) {
  301. // Checking the chip revision header *will* print a bunch of other info
  302. // regardless of silent setting as this may be important, but don't bother checking it
  303. // if it looks like the app partition is erased or otherwise garbage
  304. if (bootloader_common_check_chip_validity(image, ESP_IMAGE_APPLICATION) != ESP_OK) {
  305. err = ESP_ERR_IMAGE_INVALID;
  306. }
  307. }
  308. return err;
  309. }
  310. #ifdef BOOTLOADER_BUILD
  311. /* Check the region load_addr - load_end doesn't overlap any memory used by the bootloader, registers, or other invalid memory
  312. */
  313. static bool verify_load_addresses(int segment_index, intptr_t load_addr, intptr_t load_end, bool print_error, bool no_recurse)
  314. {
  315. /* Addresses of static data and the "loader" section of bootloader IRAM, all defined in ld script */
  316. const char *reason = NULL;
  317. extern int _dram_start, _dram_end, _loader_text_start, _loader_text_end;
  318. void *load_addr_p = (void *)load_addr;
  319. void *load_end_p = (void *)load_end;
  320. if (load_end == load_addr) {
  321. return true; // zero-length segments are fine
  322. }
  323. 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
  324. if (esp_ptr_in_dram(load_addr_p) && esp_ptr_in_dram(load_end_p)) { /* Writing to DRAM */
  325. /* Check if we're clobbering the stack */
  326. intptr_t sp = (intptr_t)get_sp();
  327. if (bootloader_util_regions_overlap(sp - STACK_LOAD_HEADROOM, SOC_ROM_STACK_START,
  328. load_addr, load_end)) {
  329. reason = "overlaps bootloader stack";
  330. goto invalid;
  331. }
  332. /* Check if we're clobbering static data
  333. (_dram_start.._dram_end includes bss, data, rodata sections in DRAM)
  334. */
  335. if (bootloader_util_regions_overlap((intptr_t)&_dram_start, (intptr_t)&_dram_end, load_addr, load_end)) {
  336. reason = "overlaps bootloader data";
  337. goto invalid;
  338. }
  339. /* LAST DRAM CHECK (recursive): for D/IRAM, check the equivalent IRAM addresses if needed
  340. Allow for the possibility that even though both pointers are IRAM, only part of the region is in a D/IRAM
  341. section. In which case we recurse to check the part which falls in D/IRAM.
  342. Note: We start with SOC_DIRAM_DRAM_LOW/HIGH and convert that address to IRAM to account for any reversing of word order
  343. (chip-specific).
  344. */
  345. if (!no_recurse && bootloader_util_regions_overlap(SOC_DIRAM_DRAM_LOW, SOC_DIRAM_DRAM_HIGH, load_addr, load_end)) {
  346. intptr_t iram_load_addr, iram_load_end;
  347. if (esp_ptr_in_diram_dram(load_addr_p)) {
  348. iram_load_addr = (intptr_t)esp_ptr_diram_dram_to_iram(load_addr_p);
  349. } else {
  350. iram_load_addr = (intptr_t)esp_ptr_diram_dram_to_iram((void *)SOC_DIRAM_DRAM_LOW);
  351. }
  352. if (esp_ptr_in_diram_dram(load_end_p)) {
  353. iram_load_end = (intptr_t)esp_ptr_diram_dram_to_iram(load_end_p);
  354. } else {
  355. iram_load_end = (intptr_t)esp_ptr_diram_dram_to_iram((void *)SOC_DIRAM_DRAM_HIGH);
  356. }
  357. if (iram_load_end < iram_load_addr) {
  358. return verify_load_addresses(segment_index, iram_load_end, iram_load_addr, print_error, true);
  359. } else {
  360. return verify_load_addresses(segment_index, iram_load_addr, iram_load_end, print_error, true);
  361. }
  362. }
  363. }
  364. else if (esp_ptr_in_iram(load_addr_p) && esp_ptr_in_iram(load_end_p)) { /* Writing to IRAM */
  365. /* Check for overlap of 'loader' section of IRAM */
  366. if (bootloader_util_regions_overlap((intptr_t)&_loader_text_start, (intptr_t)&_loader_text_end,
  367. load_addr, load_end)) {
  368. reason = "overlaps loader IRAM";
  369. goto invalid;
  370. }
  371. /* LAST IRAM CHECK (recursive): for D/IRAM, check the equivalent DRAM address if needed
  372. Allow for the possibility that even though both pointers are IRAM, only part of the region is in a D/IRAM
  373. section. In which case we recurse to check the part which falls in D/IRAM.
  374. Note: We start with SOC_DIRAM_IRAM_LOW/HIGH and convert that address to DRAM to account for any reversing of word order
  375. (chip-specific).
  376. */
  377. if (!no_recurse && bootloader_util_regions_overlap(SOC_DIRAM_IRAM_LOW, SOC_DIRAM_IRAM_HIGH, load_addr, load_end)) {
  378. intptr_t dram_load_addr, dram_load_end;
  379. if (esp_ptr_in_diram_iram(load_addr_p)) {
  380. dram_load_addr = (intptr_t)esp_ptr_diram_iram_to_dram(load_addr_p);
  381. } else {
  382. dram_load_addr = (intptr_t)esp_ptr_diram_iram_to_dram((void *)SOC_DIRAM_IRAM_LOW);
  383. }
  384. if (esp_ptr_in_diram_iram(load_end_p)) {
  385. dram_load_end = (intptr_t)esp_ptr_diram_iram_to_dram(load_end_p);
  386. } else {
  387. dram_load_end = (intptr_t)esp_ptr_diram_iram_to_dram((void *)SOC_DIRAM_IRAM_HIGH);
  388. }
  389. if (dram_load_end < dram_load_addr) {
  390. return verify_load_addresses(segment_index, dram_load_end, dram_load_addr, print_error, true);
  391. } else {
  392. return verify_load_addresses(segment_index, dram_load_addr, dram_load_end, print_error, true);
  393. }
  394. }
  395. /* Sections entirely in RTC memory won't overlap with a vanilla bootloader but are valid load addresses, thus skipping them from the check */
  396. } else if (esp_ptr_in_rtc_iram_fast(load_addr_p) && esp_ptr_in_rtc_iram_fast(load_end_p)){
  397. return true;
  398. } else if (esp_ptr_in_rtc_dram_fast(load_addr_p) && esp_ptr_in_rtc_dram_fast(load_end_p)){
  399. return true;
  400. } else if (esp_ptr_in_rtc_slow(load_addr_p) && esp_ptr_in_rtc_slow(load_end_p)) {
  401. return true;
  402. } else { /* Not a DRAM or an IRAM or RTC Fast IRAM, RTC Fast DRAM or RTC Slow address */
  403. reason = "bad load address range";
  404. goto invalid;
  405. }
  406. return true;
  407. invalid:
  408. if (print_error) {
  409. ESP_LOGE(TAG, "Segment %d 0x%08x-0x%08x invalid: %s", segment_index, load_addr, load_end, reason);
  410. }
  411. return false;
  412. }
  413. #endif // BOOTLOADER_BUILD
  414. 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)
  415. {
  416. esp_err_t err;
  417. /* read segment header */
  418. err = bootloader_flash_read(flash_addr, header, sizeof(esp_image_segment_header_t), true);
  419. if (err != ESP_OK) {
  420. ESP_LOGE(TAG, "bootloader_flash_read failed at 0x%08x", flash_addr);
  421. return err;
  422. }
  423. if (sha_handle != NULL) {
  424. bootloader_sha256_data(sha_handle, header, sizeof(esp_image_segment_header_t));
  425. }
  426. intptr_t load_addr = header->load_addr;
  427. uint32_t data_len = header->data_len;
  428. uint32_t data_addr = flash_addr + sizeof(esp_image_segment_header_t);
  429. ESP_LOGV(TAG, "segment data length 0x%x data starts 0x%x", data_len, data_addr);
  430. err = verify_segment_header(index, header, data_addr, silent);
  431. if (err != ESP_OK) {
  432. return err;
  433. }
  434. if (data_len % 4 != 0) {
  435. FAIL_LOAD("unaligned segment length 0x%x", data_len);
  436. }
  437. bool is_mapping = should_map(load_addr);
  438. do_load = do_load && should_load(load_addr);
  439. if (!silent) {
  440. ESP_LOGI(TAG, "segment %d: paddr=0x%08x vaddr=0x%08x size=0x%05x (%6d) %s",
  441. index, data_addr, load_addr,
  442. data_len, data_len,
  443. (do_load) ? "load" : (is_mapping) ? "map" : "");
  444. }
  445. #ifdef BOOTLOADER_BUILD
  446. /* Before loading segment, check it doesn't clobber bootloader RAM. */
  447. if (do_load && data_len > 0) {
  448. if (!verify_load_addresses(index, load_addr, load_addr + data_len, true, false)) {
  449. return ESP_ERR_IMAGE_INVALID;
  450. }
  451. }
  452. #endif // BOOTLOADER_BUILD
  453. uint32_t free_page_count = bootloader_mmap_get_free_pages();
  454. ESP_LOGD(TAG, "free data page_count 0x%08x", free_page_count);
  455. int32_t data_len_remain = data_len;
  456. while (data_len_remain > 0) {
  457. #if SECURE_BOOT_CHECK_SIGNATURE && defined(BOOTLOADER_BUILD)
  458. /* Double check the address verification done above */
  459. ESP_FAULT_ASSERT(!do_load || verify_load_addresses(0, load_addr, load_addr + data_len_remain, false, false));
  460. #endif
  461. uint32_t offset_page = ((data_addr & MMAP_ALIGNED_MASK) != 0) ? 1 : 0;
  462. /* Data we could map in case we are not aligned to PAGE boundary is one page size lesser. */
  463. data_len = MIN(data_len_remain, ((free_page_count - offset_page) * SPI_FLASH_MMU_PAGE_SIZE));
  464. err = process_segment_data(load_addr, data_addr, data_len, do_load, sha_handle, checksum);
  465. if (err != ESP_OK) {
  466. return err;
  467. }
  468. data_addr += data_len;
  469. data_len_remain -= data_len;
  470. }
  471. return ESP_OK;
  472. err:
  473. if (err == ESP_OK) {
  474. err = ESP_ERR_IMAGE_INVALID;
  475. }
  476. return err;
  477. }
  478. 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)
  479. {
  480. // If we are not loading, and the checksum is empty, skip processing this
  481. // segment for data
  482. if (!do_load && checksum == NULL) {
  483. ESP_LOGD(TAG, "skipping checksum for segment");
  484. return ESP_OK;
  485. }
  486. const uint32_t *data = (const uint32_t *)bootloader_mmap(data_addr, data_len);
  487. if (!data) {
  488. ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed",
  489. data_addr, data_len);
  490. return ESP_FAIL;
  491. }
  492. if (checksum == NULL && sha_handle == NULL) {
  493. memcpy((void *)load_addr, data, data_len);
  494. bootloader_munmap(data);
  495. return ESP_OK;
  496. }
  497. #ifdef BOOTLOADER_BUILD
  498. // Set up the obfuscation value to use for loading
  499. while (ram_obfs_value[0] == 0 || ram_obfs_value[1] == 0) {
  500. bootloader_fill_random(ram_obfs_value, sizeof(ram_obfs_value));
  501. }
  502. uint32_t *dest = (uint32_t *)load_addr;
  503. #endif
  504. const uint32_t *src = data;
  505. for (int i = 0; i < data_len; i += 4) {
  506. int w_i = i / 4; // Word index
  507. uint32_t w = src[w_i];
  508. if (checksum != NULL) {
  509. *checksum ^= w;
  510. }
  511. #ifdef BOOTLOADER_BUILD
  512. if (do_load) {
  513. dest[w_i] = w ^ ((w_i & 1) ? ram_obfs_value[0] : ram_obfs_value[1]);
  514. }
  515. #endif
  516. // SHA_CHUNK determined experimentally as the optimum size
  517. // to call bootloader_sha256_data() with. This is a bit
  518. // counter-intuitive, but it's ~3ms better than using the
  519. // SHA256 block size.
  520. const size_t SHA_CHUNK = 1024;
  521. if (sha_handle != NULL && i % SHA_CHUNK == 0) {
  522. bootloader_sha256_data(sha_handle, &src[w_i],
  523. MIN(SHA_CHUNK, data_len - i));
  524. }
  525. }
  526. bootloader_munmap(data);
  527. return ESP_OK;
  528. }
  529. static esp_err_t verify_segment_header(int index, const esp_image_segment_header_t *segment, uint32_t segment_data_offs, bool silent)
  530. {
  531. if ((segment->data_len & 3) != 0
  532. || segment->data_len >= SIXTEEN_MB) {
  533. if (!silent) {
  534. ESP_LOGE(TAG, "invalid segment length 0x%x", segment->data_len);
  535. }
  536. return ESP_ERR_IMAGE_INVALID;
  537. }
  538. uint32_t load_addr = segment->load_addr;
  539. bool map_segment = should_map(load_addr);
  540. /* Check that flash cache mapped segment aligns correctly from flash to its mapped address,
  541. relative to the 64KB page mapping size.
  542. */
  543. ESP_LOGV(TAG, "segment %d map_segment %d segment_data_offs 0x%x load_addr 0x%x",
  544. index, map_segment, segment_data_offs, load_addr);
  545. if (map_segment
  546. && ((segment_data_offs % SPI_FLASH_MMU_PAGE_SIZE) != (load_addr % SPI_FLASH_MMU_PAGE_SIZE))) {
  547. if (!silent) {
  548. ESP_LOGE(TAG, "Segment %d load address 0x%08x, doesn't match data 0x%08x",
  549. index, load_addr, segment_data_offs);
  550. }
  551. return ESP_ERR_IMAGE_INVALID;
  552. }
  553. return ESP_OK;
  554. }
  555. static bool should_map(uint32_t load_addr)
  556. {
  557. return (load_addr >= SOC_IROM_LOW && load_addr < SOC_IROM_HIGH)
  558. || (load_addr >= SOC_DROM_LOW && load_addr < SOC_DROM_HIGH);
  559. }
  560. static bool should_load(uint32_t load_addr)
  561. {
  562. /* Reload the RTC memory segments whenever a non-deepsleep reset
  563. is occurring */
  564. bool load_rtc_memory = rtc_get_reset_reason(0) != DEEPSLEEP_RESET;
  565. if (should_map(load_addr)) {
  566. return false;
  567. }
  568. if (load_addr < 0x10000000) {
  569. // Reserved for non-loaded addresses.
  570. // Current reserved values are
  571. // 0x0 (padding block)
  572. // 0x4 (unused, but reserved for an MD5 block)
  573. return false;
  574. }
  575. if (!load_rtc_memory) {
  576. if (load_addr >= SOC_RTC_IRAM_LOW && load_addr < SOC_RTC_IRAM_HIGH) {
  577. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  578. return false;
  579. }
  580. if (load_addr >= SOC_RTC_DRAM_LOW && load_addr < SOC_RTC_DRAM_HIGH) {
  581. ESP_LOGD(TAG, "Skipping RTC fast memory segment at 0x%08x", load_addr);
  582. return false;
  583. }
  584. if (load_addr >= SOC_RTC_DATA_LOW && load_addr < SOC_RTC_DATA_HIGH) {
  585. ESP_LOGD(TAG, "Skipping RTC slow memory segment at 0x%08x", load_addr);
  586. return false;
  587. }
  588. }
  589. return true;
  590. }
  591. esp_err_t esp_image_verify_bootloader(uint32_t *length)
  592. {
  593. esp_image_metadata_t data;
  594. esp_err_t err = esp_image_verify_bootloader_data(&data);
  595. if (length != NULL) {
  596. *length = (err == ESP_OK) ? data.image_len : 0;
  597. }
  598. return err;
  599. }
  600. esp_err_t esp_image_verify_bootloader_data(esp_image_metadata_t *data)
  601. {
  602. if (data == NULL) {
  603. return ESP_ERR_INVALID_ARG;
  604. }
  605. const esp_partition_pos_t bootloader_part = {
  606. .offset = ESP_BOOTLOADER_OFFSET,
  607. .size = ESP_PARTITION_TABLE_OFFSET - ESP_BOOTLOADER_OFFSET,
  608. };
  609. return esp_image_verify(ESP_IMAGE_VERIFY,
  610. &bootloader_part,
  611. data);
  612. }
  613. static esp_err_t verify_checksum(bootloader_sha256_handle_t sha_handle, uint32_t checksum_word, esp_image_metadata_t *data)
  614. {
  615. uint32_t unpadded_length = data->image_len;
  616. uint32_t length = unpadded_length + 1; // Add a byte for the checksum
  617. length = (length + 15) & ~15; // Pad to next full 16 byte block
  618. // Verify checksum
  619. WORD_ALIGNED_ATTR uint8_t buf[16];
  620. esp_err_t err = bootloader_flash_read(data->start_addr + unpadded_length, buf, length - unpadded_length, true);
  621. uint8_t calc = buf[length - unpadded_length - 1];
  622. uint8_t checksum = (checksum_word >> 24)
  623. ^ (checksum_word >> 16)
  624. ^ (checksum_word >> 8)
  625. ^ (checksum_word >> 0);
  626. if (err != ESP_OK || checksum != calc) {
  627. ESP_LOGE(TAG, "Checksum failed. Calculated 0x%x read 0x%x", checksum, calc);
  628. return ESP_ERR_IMAGE_INVALID;
  629. }
  630. if (sha_handle != NULL) {
  631. bootloader_sha256_data(sha_handle, buf, length - unpadded_length);
  632. }
  633. if (data->image.hash_appended) {
  634. // Account for the hash in the total image length
  635. length += HASH_LEN;
  636. }
  637. data->image_len = length;
  638. return ESP_OK;
  639. }
  640. 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)
  641. {
  642. #ifdef SECURE_BOOT_CHECK_SIGNATURE
  643. uint32_t end = data->start_addr + data->image_len;
  644. ESP_LOGI(TAG, "Verifying image signature...");
  645. // For secure boot, we calculate the signature hash over the whole file, which includes any "simple" hash
  646. // appended to the image for corruption detection
  647. if (data->image.hash_appended) {
  648. const void *simple_hash = bootloader_mmap(end - HASH_LEN, HASH_LEN);
  649. bootloader_sha256_data(sha_handle, simple_hash, HASH_LEN);
  650. bootloader_munmap(simple_hash);
  651. }
  652. #if CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME
  653. // End of the image needs to be padded all the way to a 4KB boundary, after the simple hash
  654. // (for apps they are usually already padded due to --secure-pad-v2, only a problem if this option was not used.)
  655. uint32_t padded_end = (end + FLASH_SECTOR_SIZE - 1) & ~(FLASH_SECTOR_SIZE-1);
  656. if (padded_end > end) {
  657. const void *padding = bootloader_mmap(end, padded_end - end);
  658. bootloader_sha256_data(sha_handle, padding, padded_end - end);
  659. bootloader_munmap(padding);
  660. end = padded_end;
  661. }
  662. #endif
  663. bootloader_sha256_finish(sha_handle, image_digest);
  664. // Log the hash for debugging
  665. bootloader_debug_buffer(image_digest, HASH_LEN, "Calculated secure boot hash");
  666. // Use hash to verify signature block
  667. esp_err_t err = ESP_ERR_IMAGE_INVALID;
  668. const void *sig_block;
  669. #ifdef CONFIG_SECURE_SIGNED_APPS_ECDSA_SCHEME
  670. ESP_FAULT_ASSERT(memcmp(image_digest, verified_digest, HASH_LEN) != 0); /* sanity check that these values start differently */
  671. sig_block = bootloader_mmap(data->start_addr + data->image_len, sizeof(esp_secure_boot_sig_block_t));
  672. err = esp_secure_boot_verify_ecdsa_signature_block(sig_block, image_digest, verified_digest);
  673. #elif CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME
  674. ESP_FAULT_ASSERT(memcmp(image_digest, verified_digest, HASH_LEN) != 0); /* sanity check that these values start differently */
  675. sig_block = bootloader_mmap(end, sizeof(ets_secure_boot_signature_t));
  676. err = esp_secure_boot_verify_rsa_signature_block(sig_block, image_digest, verified_digest);
  677. #endif
  678. bootloader_munmap(sig_block);
  679. if (err != ESP_OK) {
  680. ESP_LOGE(TAG, "Secure boot signature verification failed");
  681. // 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)
  682. ESP_LOGI(TAG, "Calculating simple hash to check for corruption...");
  683. const void *whole_image = bootloader_mmap(data->start_addr, data->image_len - HASH_LEN);
  684. if (whole_image != NULL) {
  685. sha_handle = bootloader_sha256_start();
  686. bootloader_sha256_data(sha_handle, whole_image, data->image_len - HASH_LEN);
  687. bootloader_munmap(whole_image);
  688. if (verify_simple_hash(sha_handle, data) != ESP_OK) {
  689. ESP_LOGW(TAG, "image corrupted on flash");
  690. } else {
  691. ESP_LOGW(TAG, "image valid, signature bad");
  692. }
  693. }
  694. return ESP_ERR_IMAGE_INVALID;
  695. }
  696. #if CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME
  697. // Adjust image length result to include the appended signature
  698. data->image_len = end - data->start_addr + sizeof(ets_secure_boot_signature_t);
  699. #endif
  700. #endif // SECURE_BOOT_CHECK_SIGNATURE
  701. return ESP_OK;
  702. }
  703. static esp_err_t verify_simple_hash(bootloader_sha256_handle_t sha_handle, esp_image_metadata_t *data)
  704. {
  705. uint8_t image_hash[HASH_LEN] = { 0 };
  706. bootloader_sha256_finish(sha_handle, image_hash);
  707. // Log the hash for debugging
  708. bootloader_debug_buffer(image_hash, HASH_LEN, "Calculated hash");
  709. // Simple hash for verification only
  710. const void *hash = bootloader_mmap(data->start_addr + data->image_len - HASH_LEN, HASH_LEN);
  711. if (memcmp(hash, image_hash, HASH_LEN) != 0) {
  712. ESP_LOGE(TAG, "Image hash failed - image is corrupt");
  713. bootloader_debug_buffer(hash, HASH_LEN, "Expected hash");
  714. bootloader_munmap(hash);
  715. return ESP_ERR_IMAGE_INVALID;
  716. }
  717. bootloader_munmap(hash);
  718. return ESP_OK;
  719. }