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