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