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