1 /*
2 * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <stdint.h>
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <assert.h>
14
15 #include "esp_err.h"
16 #include "esp_partition.h"
17 #include "esp_spi_flash.h"
18 #include "esp_image_format.h"
19 #include "esp_secure_boot.h"
20 #include "esp_flash_encrypt.h"
21 #include "esp_spi_flash.h"
22 #include "sdkconfig.h"
23
24 #include "esp_ota_ops.h"
25 #include "sys/queue.h"
26 #include "esp_log.h"
27 #include "esp_flash_partitions.h"
28 #include "bootloader_common.h"
29 #include "sys/param.h"
30 #include "esp_system.h"
31 #include "esp_efuse.h"
32 #include "esp_attr.h"
33
34 #define SUB_TYPE_ID(i) (i & 0x0F)
35
36 /* Partial_data is word aligned so no reallocation is necessary for encrypted flash write */
37 typedef struct ota_ops_entry_ {
38 uint32_t handle;
39 const esp_partition_t *part;
40 bool need_erase;
41 uint32_t wrote_size;
42 uint8_t partial_bytes;
43 WORD_ALIGNED_ATTR uint8_t partial_data[16];
44 LIST_ENTRY(ota_ops_entry_) entries;
45 } ota_ops_entry_t;
46
47 static LIST_HEAD(ota_ops_entries_head, ota_ops_entry_) s_ota_ops_entries_head =
48 LIST_HEAD_INITIALIZER(s_ota_ops_entries_head);
49
50 static uint32_t s_ota_ops_last_handle = 0;
51
52 const static char *TAG = "esp_ota_ops";
53
54 /* Return true if this is an OTA app partition */
is_ota_partition(const esp_partition_t * p)55 static bool is_ota_partition(const esp_partition_t *p)
56 {
57 return (p != NULL
58 && p->type == ESP_PARTITION_TYPE_APP
59 && p->subtype >= ESP_PARTITION_SUBTYPE_APP_OTA_0
60 && p->subtype < ESP_PARTITION_SUBTYPE_APP_OTA_MAX);
61 }
62
63 // Read otadata partition and fill array from two otadata structures.
64 // Also return pointer to otadata info partition.
read_otadata(esp_ota_select_entry_t * two_otadata)65 static const esp_partition_t *read_otadata(esp_ota_select_entry_t *two_otadata)
66 {
67 const esp_partition_t *otadata_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL);
68
69 if (otadata_partition == NULL) {
70 ESP_LOGE(TAG, "not found otadata");
71 return NULL;
72 }
73
74 spi_flash_mmap_handle_t ota_data_map;
75 const void *result = NULL;
76 esp_err_t err = esp_partition_mmap(otadata_partition, 0, otadata_partition->size, SPI_FLASH_MMAP_DATA, &result, &ota_data_map);
77 if (err != ESP_OK) {
78 ESP_LOGE(TAG, "mmap otadata filed. Err=0x%8x", err);
79 return NULL;
80 } else {
81 memcpy(&two_otadata[0], result, sizeof(esp_ota_select_entry_t));
82 memcpy(&two_otadata[1], result + SPI_FLASH_SEC_SIZE, sizeof(esp_ota_select_entry_t));
83 spi_flash_munmap(ota_data_map);
84 }
85 return otadata_partition;
86 }
87
image_validate(const esp_partition_t * partition,esp_image_load_mode_t load_mode)88 static esp_err_t image_validate(const esp_partition_t *partition, esp_image_load_mode_t load_mode)
89 {
90 esp_image_metadata_t data;
91 const esp_partition_pos_t part_pos = {
92 .offset = partition->address,
93 .size = partition->size,
94 };
95
96 if (esp_image_verify(load_mode, &part_pos, &data) != ESP_OK) {
97 return ESP_ERR_OTA_VALIDATE_FAILED;
98 }
99
100 return ESP_OK;
101 }
102
set_new_state_otadata(void)103 static esp_ota_img_states_t set_new_state_otadata(void)
104 {
105 #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
106 ESP_LOGD(TAG, "Monitoring the first boot of the app is enabled.");
107 return ESP_OTA_IMG_NEW;
108 #else
109 return ESP_OTA_IMG_UNDEFINED;
110 #endif
111 }
112
esp_ota_begin(const esp_partition_t * partition,size_t image_size,esp_ota_handle_t * out_handle)113 esp_err_t esp_ota_begin(const esp_partition_t *partition, size_t image_size, esp_ota_handle_t *out_handle)
114 {
115 ota_ops_entry_t *new_entry;
116 esp_err_t ret = ESP_OK;
117
118 if ((partition == NULL) || (out_handle == NULL)) {
119 return ESP_ERR_INVALID_ARG;
120 }
121
122 partition = esp_partition_verify(partition);
123 if (partition == NULL) {
124 return ESP_ERR_NOT_FOUND;
125 }
126
127 if (!is_ota_partition(partition)) {
128 return ESP_ERR_INVALID_ARG;
129 }
130
131 const esp_partition_t* running_partition = esp_ota_get_running_partition();
132 if (partition == running_partition) {
133 return ESP_ERR_OTA_PARTITION_CONFLICT;
134 }
135
136 #ifdef CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
137 esp_ota_img_states_t ota_state_running_part;
138 if (esp_ota_get_state_partition(running_partition, &ota_state_running_part) == ESP_OK) {
139 if (ota_state_running_part == ESP_OTA_IMG_PENDING_VERIFY) {
140 ESP_LOGE(TAG, "Running app has not confirmed state (ESP_OTA_IMG_PENDING_VERIFY)");
141 return ESP_ERR_OTA_ROLLBACK_INVALID_STATE;
142 }
143 }
144 #endif
145
146 if (image_size != OTA_WITH_SEQUENTIAL_WRITES) {
147 // If input image size is 0 or OTA_SIZE_UNKNOWN, erase entire partition
148 if ((image_size == 0) || (image_size == OTA_SIZE_UNKNOWN)) {
149 ret = esp_partition_erase_range(partition, 0, partition->size);
150 } else {
151 const int aligned_erase_size = (image_size + SPI_FLASH_SEC_SIZE - 1) & ~(SPI_FLASH_SEC_SIZE - 1);
152 ret = esp_partition_erase_range(partition, 0, aligned_erase_size);
153 }
154 if (ret != ESP_OK) {
155 return ret;
156 }
157 }
158
159 new_entry = (ota_ops_entry_t *) calloc(sizeof(ota_ops_entry_t), 1);
160 if (new_entry == NULL) {
161 return ESP_ERR_NO_MEM;
162 }
163
164 LIST_INSERT_HEAD(&s_ota_ops_entries_head, new_entry, entries);
165
166 new_entry->part = partition;
167 new_entry->handle = ++s_ota_ops_last_handle;
168 new_entry->need_erase = (image_size == OTA_WITH_SEQUENTIAL_WRITES);
169 *out_handle = new_entry->handle;
170 return ESP_OK;
171 }
172
esp_ota_write(esp_ota_handle_t handle,const void * data,size_t size)173 esp_err_t esp_ota_write(esp_ota_handle_t handle, const void *data, size_t size)
174 {
175 const uint8_t *data_bytes = (const uint8_t *)data;
176 esp_err_t ret;
177 ota_ops_entry_t *it;
178
179 if (data == NULL) {
180 ESP_LOGE(TAG, "write data is invalid");
181 return ESP_ERR_INVALID_ARG;
182 }
183
184 // find ota handle in linked list
185 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
186 if (it->handle == handle) {
187 if (it->need_erase) {
188 // must erase the partition before writing to it
189 uint32_t first_sector = it->wrote_size / SPI_FLASH_SEC_SIZE;
190 uint32_t last_sector = (it->wrote_size + size) / SPI_FLASH_SEC_SIZE;
191
192 ret = ESP_OK;
193 if ((it->wrote_size % SPI_FLASH_SEC_SIZE) == 0) {
194 ret = esp_partition_erase_range(it->part, it->wrote_size, ((last_sector - first_sector) + 1) * SPI_FLASH_SEC_SIZE);
195 } else if (first_sector != last_sector) {
196 ret = esp_partition_erase_range(it->part, (first_sector + 1) * SPI_FLASH_SEC_SIZE, (last_sector - first_sector) * SPI_FLASH_SEC_SIZE);
197 }
198 if (ret != ESP_OK) {
199 return ret;
200 }
201 }
202
203 if (it->wrote_size == 0 && it->partial_bytes == 0 && size > 0 && data_bytes[0] != ESP_IMAGE_HEADER_MAGIC) {
204 ESP_LOGE(TAG, "OTA image has invalid magic byte (expected 0xE9, saw 0x%02x)", data_bytes[0]);
205 return ESP_ERR_OTA_VALIDATE_FAILED;
206 }
207
208 if (esp_flash_encryption_enabled()) {
209 /* Can only write 16 byte blocks to flash, so need to cache anything else */
210 size_t copy_len;
211
212 /* check if we have partially written data from earlier */
213 if (it->partial_bytes != 0) {
214 copy_len = MIN(16 - it->partial_bytes, size);
215 memcpy(it->partial_data + it->partial_bytes, data_bytes, copy_len);
216 it->partial_bytes += copy_len;
217 if (it->partial_bytes != 16) {
218 return ESP_OK; /* nothing to write yet, just filling buffer */
219 }
220 /* write 16 byte to partition */
221 ret = esp_partition_write(it->part, it->wrote_size, it->partial_data, 16);
222 if (ret != ESP_OK) {
223 return ret;
224 }
225 it->partial_bytes = 0;
226 memset(it->partial_data, 0xFF, 16);
227 it->wrote_size += 16;
228 data_bytes += copy_len;
229 size -= copy_len;
230 }
231
232 /* check if we need to save trailing data that we're about to write */
233 it->partial_bytes = size % 16;
234 if (it->partial_bytes != 0) {
235 size -= it->partial_bytes;
236 memcpy(it->partial_data, data_bytes + size, it->partial_bytes);
237 }
238 }
239
240 ret = esp_partition_write(it->part, it->wrote_size, data_bytes, size);
241 if(ret == ESP_OK){
242 it->wrote_size += size;
243 }
244 return ret;
245 }
246 }
247
248 //if go to here ,means don't find the handle
249 ESP_LOGE(TAG,"not found the handle");
250 return ESP_ERR_INVALID_ARG;
251 }
252
esp_ota_write_with_offset(esp_ota_handle_t handle,const void * data,size_t size,uint32_t offset)253 esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t offset)
254 {
255 const uint8_t *data_bytes = (const uint8_t *)data;
256 esp_err_t ret;
257 ota_ops_entry_t *it;
258
259 if (data == NULL) {
260 ESP_LOGE(TAG, "write data is invalid");
261 return ESP_ERR_INVALID_ARG;
262 }
263
264 // find ota handle in linked list
265 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
266 if (it->handle == handle) {
267 // must erase the partition before writing to it
268 assert(it->need_erase == 0 && "must erase the partition before writing to it");
269
270 /* esp_ota_write_with_offset is used to write data in non contiguous manner.
271 * Hence, unaligned data(less than 16 bytes) cannot be cached if flash encryption is enabled.
272 */
273 if (esp_flash_encryption_enabled() && (size % 16)) {
274 ESP_LOGE(TAG, "Size should be 16byte aligned for flash encryption case");
275 return ESP_ERR_INVALID_ARG;
276 }
277 ret = esp_partition_write(it->part, offset, data_bytes, size);
278 if (ret == ESP_OK) {
279 it->wrote_size += size;
280 }
281 return ret;
282 }
283 }
284
285 // OTA handle is not found in linked list
286 ESP_LOGE(TAG,"OTA handle not found");
287 return ESP_ERR_INVALID_ARG;
288 }
289
get_ota_ops_entry(esp_ota_handle_t handle)290 static ota_ops_entry_t *get_ota_ops_entry(esp_ota_handle_t handle)
291 {
292 ota_ops_entry_t *it = NULL;
293 for (it = LIST_FIRST(&s_ota_ops_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
294 if (it->handle == handle) {
295 break;
296 }
297 }
298 return it;
299 }
300
esp_ota_abort(esp_ota_handle_t handle)301 esp_err_t esp_ota_abort(esp_ota_handle_t handle)
302 {
303 ota_ops_entry_t *it = get_ota_ops_entry(handle);
304
305 if (it == NULL) {
306 return ESP_ERR_NOT_FOUND;
307 }
308 LIST_REMOVE(it, entries);
309 free(it);
310 return ESP_OK;
311 }
312
esp_ota_end(esp_ota_handle_t handle)313 esp_err_t esp_ota_end(esp_ota_handle_t handle)
314 {
315 ota_ops_entry_t *it = get_ota_ops_entry(handle);
316 esp_err_t ret = ESP_OK;
317
318 if (it == NULL) {
319 return ESP_ERR_NOT_FOUND;
320 }
321
322 /* 'it' holds the ota_ops_entry_t for 'handle' */
323
324 // esp_ota_end() is only valid if some data was written to this handle
325 if (it->wrote_size == 0) {
326 ret = ESP_ERR_INVALID_ARG;
327 goto cleanup;
328 }
329
330 if (it->partial_bytes > 0) {
331 /* Write out last 16 bytes, if necessary */
332 ret = esp_partition_write(it->part, it->wrote_size, it->partial_data, 16);
333 if (ret != ESP_OK) {
334 ret = ESP_ERR_INVALID_STATE;
335 goto cleanup;
336 }
337 it->wrote_size += 16;
338 it->partial_bytes = 0;
339 }
340
341 esp_image_metadata_t data;
342 const esp_partition_pos_t part_pos = {
343 .offset = it->part->address,
344 .size = it->part->size,
345 };
346
347 if (esp_image_verify(ESP_IMAGE_VERIFY, &part_pos, &data) != ESP_OK) {
348 ret = ESP_ERR_OTA_VALIDATE_FAILED;
349 goto cleanup;
350 }
351
352 cleanup:
353 LIST_REMOVE(it, entries);
354 free(it);
355 return ret;
356 }
357
rewrite_ota_seq(esp_ota_select_entry_t * two_otadata,uint32_t seq,uint8_t sec_id,const esp_partition_t * ota_data_partition)358 static esp_err_t rewrite_ota_seq(esp_ota_select_entry_t *two_otadata, uint32_t seq, uint8_t sec_id, const esp_partition_t *ota_data_partition)
359 {
360 if (two_otadata == NULL || sec_id > 1) {
361 return ESP_ERR_INVALID_ARG;
362 }
363
364 two_otadata[sec_id].ota_seq = seq;
365 two_otadata[sec_id].crc = bootloader_common_ota_select_crc(&two_otadata[sec_id]);
366 esp_err_t ret = esp_partition_erase_range(ota_data_partition, sec_id * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
367 if (ret != ESP_OK) {
368 return ret;
369 } else {
370 return esp_partition_write(ota_data_partition, SPI_FLASH_SEC_SIZE * sec_id, &two_otadata[sec_id], sizeof(esp_ota_select_entry_t));
371 }
372 }
373
esp_ota_get_app_partition_count(void)374 uint8_t esp_ota_get_app_partition_count(void)
375 {
376 uint16_t ota_app_count = 0;
377 while (esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_app_count, NULL) != NULL) {
378 assert(ota_app_count < 16 && "must erase the partition before writing to it");
379 ota_app_count++;
380 }
381 return ota_app_count;
382 }
383
esp_rewrite_ota_data(esp_partition_subtype_t subtype)384 static esp_err_t esp_rewrite_ota_data(esp_partition_subtype_t subtype)
385 {
386 esp_ota_select_entry_t otadata[2];
387 const esp_partition_t *otadata_partition = read_otadata(otadata);
388 if (otadata_partition == NULL) {
389 return ESP_ERR_NOT_FOUND;
390 }
391
392 uint8_t ota_app_count = esp_ota_get_app_partition_count();
393 if (SUB_TYPE_ID(subtype) >= ota_app_count) {
394 return ESP_ERR_INVALID_ARG;
395 }
396
397 //esp32_idf use two sector for store information about which partition is running
398 //it defined the two sector as ota data partition,two structure esp_ota_select_entry_t is saved in the two sector
399 //named data in first sector as otadata[0], second sector data as otadata[1]
400 //e.g.
401 //if otadata[0].ota_seq == otadata[1].ota_seq == 0xFFFFFFFF,means ota info partition is in init status
402 //so it will boot factory application(if there is),if there's no factory application,it will boot ota[0] application
403 //if otadata[0].ota_seq != 0 and otadata[1].ota_seq != 0,it will choose a max seq ,and get value of max_seq%max_ota_app_number
404 //and boot a subtype (mask 0x0F) value is (max_seq - 1)%max_ota_app_number,so if want switch to run ota[x],can use next formulas.
405 //for example, if otadata[0].ota_seq = 4, otadata[1].ota_seq = 5, and there are 8 ota application,
406 //current running is (5-1)%8 = 4,running ota[4],so if we want to switch to run ota[7],
407 //we should add otadata[0].ota_seq (is 4) to 4 ,(8-1)%8=7,then it will boot ota[7]
408 //if A=(B - C)%D
409 //then B=(A + C)%D + D*n ,n= (0,1,2...)
410 //so current ota app sub type id is x , dest bin subtype is y,total ota app count is n
411 //seq will add (x + n*1 + 1 - seq)%n
412
413 int active_otadata = bootloader_common_get_active_otadata(otadata);
414 if (active_otadata != -1) {
415 uint32_t seq = otadata[active_otadata].ota_seq;
416 uint32_t i = 0;
417 while (seq > (SUB_TYPE_ID(subtype) + 1) % ota_app_count + i * ota_app_count) {
418 i++;
419 }
420 int next_otadata = (~active_otadata)&1; // if 0 -> will be next 1. and if 1 -> will be next 0.
421 otadata[next_otadata].ota_state = set_new_state_otadata();
422 return rewrite_ota_seq(otadata, (SUB_TYPE_ID(subtype) + 1) % ota_app_count + i * ota_app_count, next_otadata, otadata_partition);
423 } else {
424 /* Both OTA slots are invalid, probably because unformatted... */
425 int next_otadata = 0;
426 otadata[next_otadata].ota_state = set_new_state_otadata();
427 return rewrite_ota_seq(otadata, SUB_TYPE_ID(subtype) + 1, next_otadata, otadata_partition);
428 }
429 }
430
esp_ota_set_boot_partition(const esp_partition_t * partition)431 esp_err_t esp_ota_set_boot_partition(const esp_partition_t *partition)
432 {
433 if (partition == NULL) {
434 return ESP_ERR_INVALID_ARG;
435 }
436
437 if (image_validate(partition, ESP_IMAGE_VERIFY) != ESP_OK) {
438 return ESP_ERR_OTA_VALIDATE_FAILED;
439 }
440
441 // if set boot partition to factory bin ,just format ota info partition
442 if (partition->type == ESP_PARTITION_TYPE_APP) {
443 if (partition->subtype == ESP_PARTITION_SUBTYPE_APP_FACTORY) {
444 const esp_partition_t *find_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL);
445 if (find_partition != NULL) {
446 return esp_partition_erase_range(find_partition, 0, find_partition->size);
447 } else {
448 return ESP_ERR_NOT_FOUND;
449 }
450 } else {
451 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
452 esp_app_desc_t partition_app_desc;
453 esp_err_t err = esp_ota_get_partition_description(partition, &partition_app_desc);
454 if (err != ESP_OK) {
455 return err;
456 }
457
458 if (esp_efuse_check_secure_version(partition_app_desc.secure_version) == false) {
459 ESP_LOGE(TAG, "This a new partition can not be booted due to a secure version is lower than stored in efuse. Partition will be erased.");
460 esp_err_t err = esp_partition_erase_range(partition, 0, partition->size);
461 if (err != ESP_OK) {
462 return err;
463 }
464 return ESP_ERR_OTA_SMALL_SEC_VER;
465 }
466 #endif
467 return esp_rewrite_ota_data(partition->subtype);
468 }
469 } else {
470 return ESP_ERR_INVALID_ARG;
471 }
472 }
473
find_default_boot_partition(void)474 static const esp_partition_t *find_default_boot_partition(void)
475 {
476 // This logic matches the logic of bootloader get_selected_boot_partition() & load_boot_image().
477
478 // Default to factory if present
479 const esp_partition_t *result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
480 if (result != NULL) {
481 return result;
482 }
483
484 // Try first OTA slot if no factory partition
485 for (esp_partition_subtype_t s = ESP_PARTITION_SUBTYPE_APP_OTA_MIN; s != ESP_PARTITION_SUBTYPE_APP_OTA_MAX; s++) {
486 result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, s, NULL);
487 if (result != NULL) {
488 return result;
489 }
490 }
491
492 // Test app slot if present
493 result = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_TEST, NULL);
494 if (result != NULL) {
495 return result;
496 }
497
498 ESP_LOGE(TAG, "invalid partition table, no app partitions");
499 return NULL;
500 }
501
esp_ota_get_boot_partition(void)502 const esp_partition_t *esp_ota_get_boot_partition(void)
503 {
504 esp_ota_select_entry_t otadata[2];
505 const esp_partition_t *otadata_partition = read_otadata(otadata);
506 if (otadata_partition == NULL) {
507 return NULL;
508 }
509
510 int ota_app_count = esp_ota_get_app_partition_count();
511 ESP_LOGD(TAG, "found ota app max = %d", ota_app_count);
512
513 if ((bootloader_common_ota_select_invalid(&otadata[0]) &&
514 bootloader_common_ota_select_invalid(&otadata[1])) ||
515 ota_app_count == 0) {
516 ESP_LOGD(TAG, "finding factory app...");
517 return find_default_boot_partition();
518 } else {
519 int active_otadata = bootloader_common_get_active_otadata(otadata);
520 if (active_otadata != -1) {
521 int ota_slot = (otadata[active_otadata].ota_seq - 1) % ota_app_count; // Actual OTA partition selection
522 ESP_LOGD(TAG, "finding ota_%d app...", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
523 return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
524 } else {
525 ESP_LOGE(TAG, "ota data invalid, no current app. Assuming factory");
526 return find_default_boot_partition();
527 }
528 }
529 }
530
531
esp_ota_get_running_partition(void)532 const esp_partition_t* esp_ota_get_running_partition(void)
533 {
534 static const esp_partition_t *curr_partition = NULL;
535
536 /*
537 * Currently running partition is unlikely to change across reset cycle,
538 * so it can be cached here, and avoid lookup on every flash write operation.
539 */
540 if (curr_partition != NULL) {
541 return curr_partition;
542 }
543
544 /* Find the flash address of this exact function. By definition that is part
545 of the currently running firmware. Then find the enclosing partition. */
546 size_t phys_offs = spi_flash_cache2phys(esp_ota_get_running_partition);
547
548 assert (phys_offs != SPI_FLASH_CACHE2PHYS_FAIL); /* indicates cache2phys lookup is buggy */
549
550 esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_APP,
551 ESP_PARTITION_SUBTYPE_ANY,
552 NULL);
553 assert(it != NULL); /* has to be at least one app partition */
554
555 while (it != NULL) {
556 const esp_partition_t *p = esp_partition_get(it);
557 if (p->address <= phys_offs && p->address + p->size > phys_offs) {
558 esp_partition_iterator_release(it);
559 curr_partition = p;
560 return p;
561 }
562 it = esp_partition_next(it);
563 }
564
565 abort(); /* Partition table is invalid or corrupt */
566 }
567
568
esp_ota_get_next_update_partition(const esp_partition_t * start_from)569 const esp_partition_t* esp_ota_get_next_update_partition(const esp_partition_t *start_from)
570 {
571 const esp_partition_t *default_ota = NULL;
572 bool next_is_result = false;
573 if (start_from == NULL) {
574 start_from = esp_ota_get_running_partition();
575 } else {
576 start_from = esp_partition_verify(start_from);
577 }
578 assert (start_from != NULL);
579 /* at this point, 'start_from' points to actual partition table data in flash */
580
581
582 /* Two possibilities: either we want the OTA partition immediately after the current running OTA partition, or we
583 want the first OTA partition in the table (for the case when the last OTA partition is the running partition, or
584 if the current running partition is not OTA.)
585
586 This loop iterates subtypes instead of using esp_partition_find, so we
587 get all OTA partitions in a known order (low slot to high slot).
588 */
589
590 for (esp_partition_subtype_t t = ESP_PARTITION_SUBTYPE_APP_OTA_0;
591 t != ESP_PARTITION_SUBTYPE_APP_OTA_MAX;
592 t++) {
593 const esp_partition_t *p = esp_partition_find_first(ESP_PARTITION_TYPE_APP, t, NULL);
594 if (p == NULL) {
595 continue;
596 }
597
598 if (default_ota == NULL) {
599 /* Default to first OTA partition we find,
600 will be used if nothing else matches */
601 default_ota = p;
602 }
603
604 if (p == start_from) {
605 /* Next OTA partition is the one to use */
606 next_is_result = true;
607 }
608 else if (next_is_result) {
609 return p;
610 }
611 }
612
613 return default_ota;
614
615 }
616
esp_ota_get_partition_description(const esp_partition_t * partition,esp_app_desc_t * app_desc)617 esp_err_t esp_ota_get_partition_description(const esp_partition_t *partition, esp_app_desc_t *app_desc)
618 {
619 if (partition == NULL || app_desc == NULL) {
620 return ESP_ERR_INVALID_ARG;
621 }
622
623 if(partition->type != ESP_PARTITION_TYPE_APP) {
624 return ESP_ERR_NOT_SUPPORTED;
625 }
626
627 esp_err_t err = esp_partition_read(partition, sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t), app_desc, sizeof(esp_app_desc_t));
628 if (err != ESP_OK) {
629 return err;
630 }
631
632 if (app_desc->magic_word != ESP_APP_DESC_MAGIC_WORD) {
633 return ESP_ERR_NOT_FOUND;
634 }
635
636 return ESP_OK;
637 }
638
639 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
esp_ota_set_anti_rollback(void)640 static esp_err_t esp_ota_set_anti_rollback(void) {
641 const esp_app_desc_t *app_desc = esp_ota_get_app_description();
642 return esp_efuse_update_secure_version(app_desc->secure_version);
643 }
644 #endif
645
646 // Checks applications on the slots which can be booted in case of rollback.
647 // Returns true if the slots have at least one app (except the running app).
esp_ota_check_rollback_is_possible(void)648 bool esp_ota_check_rollback_is_possible(void)
649 {
650 esp_ota_select_entry_t otadata[2];
651 if (read_otadata(otadata) == NULL) {
652 return false;
653 }
654
655 int ota_app_count = esp_ota_get_app_partition_count();
656 if (ota_app_count == 0) {
657 return false;
658 }
659
660 bool valid_otadata[2];
661 valid_otadata[0] = bootloader_common_ota_select_valid(&otadata[0]);
662 valid_otadata[1] = bootloader_common_ota_select_valid(&otadata[1]);
663
664 int active_ota = bootloader_common_select_otadata(otadata, valid_otadata, true);
665 if (active_ota == -1) {
666 return false;
667 }
668 int last_active_ota = (~active_ota)&1;
669
670 const esp_partition_t *partition = NULL;
671 #ifndef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
672 if (valid_otadata[last_active_ota] == false) {
673 partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_FACTORY, NULL);
674 if (partition != NULL) {
675 if(image_validate(partition, ESP_IMAGE_VERIFY_SILENT) == ESP_OK) {
676 return true;
677 }
678 }
679 }
680 #endif
681
682 if (valid_otadata[last_active_ota] == true) {
683 int slot = (otadata[last_active_ota].ota_seq - 1) % ota_app_count;
684 partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + slot, NULL);
685 if (partition != NULL) {
686 if(image_validate(partition, ESP_IMAGE_VERIFY_SILENT) == ESP_OK) {
687 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
688 esp_app_desc_t app_desc;
689 if (esp_ota_get_partition_description(partition, &app_desc) == ESP_OK &&
690 esp_efuse_check_secure_version(app_desc.secure_version) == true) {
691 return true;
692 }
693 #else
694 return true;
695 #endif
696 }
697 }
698 }
699 return false;
700 }
701
702 // if valid == false - will done rollback with reboot. After reboot will boot previous OTA[x] or Factory partition.
703 // if valid == true - it confirm that current OTA[x] is workable. Reboot will not happen.
esp_ota_current_ota_is_workable(bool valid)704 static esp_err_t esp_ota_current_ota_is_workable(bool valid)
705 {
706 esp_ota_select_entry_t otadata[2];
707 const esp_partition_t *otadata_partition = read_otadata(otadata);
708 if (otadata_partition == NULL) {
709 return ESP_ERR_NOT_FOUND;
710 }
711
712 int active_otadata = bootloader_common_get_active_otadata(otadata);
713 if (active_otadata != -1 && esp_ota_get_app_partition_count() != 0) {
714 if (valid == true && otadata[active_otadata].ota_state != ESP_OTA_IMG_VALID) {
715 otadata[active_otadata].ota_state = ESP_OTA_IMG_VALID;
716 ESP_LOGD(TAG, "OTA[current] partition is marked as VALID");
717 esp_err_t err = rewrite_ota_seq(otadata, otadata[active_otadata].ota_seq, active_otadata, otadata_partition);
718 #ifdef CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
719 if (err == ESP_OK) {
720 return esp_ota_set_anti_rollback();
721 }
722 #endif
723 return err;
724 } else if (valid == false) {
725 if (esp_ota_check_rollback_is_possible() == false) {
726 ESP_LOGE(TAG, "Rollback is not possible, do not have any suitable apps in slots");
727 return ESP_ERR_OTA_ROLLBACK_FAILED;
728 }
729 ESP_LOGD(TAG, "OTA[current] partition is marked as INVALID");
730 otadata[active_otadata].ota_state = ESP_OTA_IMG_INVALID;
731 esp_err_t err = rewrite_ota_seq(otadata, otadata[active_otadata].ota_seq, active_otadata, otadata_partition);
732 if (err != ESP_OK) {
733 return err;
734 }
735 ESP_LOGI(TAG, "Rollback to previously worked partition. Restart.");
736 esp_restart();
737 }
738 } else {
739 ESP_LOGE(TAG, "Running firmware is factory");
740 return ESP_FAIL;
741 }
742 return ESP_OK;
743 }
744
esp_ota_mark_app_valid_cancel_rollback(void)745 esp_err_t esp_ota_mark_app_valid_cancel_rollback(void)
746 {
747 return esp_ota_current_ota_is_workable(true);
748 }
749
esp_ota_mark_app_invalid_rollback_and_reboot(void)750 esp_err_t esp_ota_mark_app_invalid_rollback_and_reboot(void)
751 {
752 return esp_ota_current_ota_is_workable(false);
753 }
754
check_invalid_otadata(const esp_ota_select_entry_t * s)755 static bool check_invalid_otadata (const esp_ota_select_entry_t *s) {
756 return s->ota_seq != UINT32_MAX &&
757 s->crc == bootloader_common_ota_select_crc(s) &&
758 (s->ota_state == ESP_OTA_IMG_INVALID ||
759 s->ota_state == ESP_OTA_IMG_ABORTED);
760 }
761
get_last_invalid_otadata(const esp_ota_select_entry_t * two_otadata)762 static int get_last_invalid_otadata(const esp_ota_select_entry_t *two_otadata)
763 {
764
765 bool invalid_otadata[2];
766 invalid_otadata[0] = check_invalid_otadata(&two_otadata[0]);
767 invalid_otadata[1] = check_invalid_otadata(&two_otadata[1]);
768 int num_invalid_otadata = bootloader_common_select_otadata(two_otadata, invalid_otadata, false);
769 ESP_LOGD(TAG, "Invalid otadata[%d]", num_invalid_otadata);
770 return num_invalid_otadata;
771 }
772
esp_ota_get_last_invalid_partition(void)773 const esp_partition_t* esp_ota_get_last_invalid_partition(void)
774 {
775 esp_ota_select_entry_t otadata[2];
776 if (read_otadata(otadata) == NULL) {
777 return NULL;
778 }
779
780 int invalid_otadata = get_last_invalid_otadata(otadata);
781
782 int ota_app_count = esp_ota_get_app_partition_count();
783 if (invalid_otadata != -1 && ota_app_count != 0) {
784 int ota_slot = (otadata[invalid_otadata].ota_seq - 1) % ota_app_count;
785 ESP_LOGD(TAG, "Find invalid ota_%d app", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
786
787 const esp_partition_t* invalid_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
788 if (invalid_partition != NULL) {
789 if (image_validate(invalid_partition, ESP_IMAGE_VERIFY_SILENT) != ESP_OK) {
790 ESP_LOGD(TAG, "Last invalid partition has corrupted app");
791 return NULL;
792 }
793 }
794 return invalid_partition;
795 }
796 return NULL;
797 }
798
esp_ota_get_state_partition(const esp_partition_t * partition,esp_ota_img_states_t * ota_state)799 esp_err_t esp_ota_get_state_partition(const esp_partition_t *partition, esp_ota_img_states_t *ota_state)
800 {
801 if (partition == NULL || ota_state == NULL) {
802 return ESP_ERR_INVALID_ARG;
803 }
804
805 if (!is_ota_partition(partition)) {
806 return ESP_ERR_NOT_SUPPORTED;
807 }
808
809 esp_ota_select_entry_t otadata[2];
810 int ota_app_count = esp_ota_get_app_partition_count();
811 if (read_otadata(otadata) == NULL || ota_app_count == 0) {
812 return ESP_ERR_NOT_FOUND;
813 }
814
815 int req_ota_slot = partition->subtype - ESP_PARTITION_SUBTYPE_APP_OTA_MIN;
816 bool not_found = true;
817 for (int i = 0; i < 2; ++i) {
818 int ota_slot = (otadata[i].ota_seq - 1) % ota_app_count;
819 if (ota_slot == req_ota_slot && otadata[i].crc == bootloader_common_ota_select_crc(&otadata[i])) {
820 *ota_state = otadata[i].ota_state;
821 not_found = false;
822 break;
823 }
824 }
825
826 if (not_found) {
827 return ESP_ERR_NOT_FOUND;
828 }
829
830 return ESP_OK;
831 }
832
esp_ota_erase_last_boot_app_partition(void)833 esp_err_t esp_ota_erase_last_boot_app_partition(void)
834 {
835 esp_ota_select_entry_t otadata[2];
836 const esp_partition_t* ota_data_partition = read_otadata(otadata);
837 if (ota_data_partition == NULL) {
838 return ESP_FAIL;
839 }
840
841 int active_otadata = bootloader_common_get_active_otadata(otadata);
842 int ota_app_count = esp_ota_get_app_partition_count();
843 if (active_otadata == -1 || ota_app_count == 0) {
844 return ESP_FAIL;
845 }
846
847 int inactive_otadata = (~active_otadata)&1;
848 if (otadata[inactive_otadata].ota_seq == UINT32_MAX || otadata[inactive_otadata].crc != bootloader_common_ota_select_crc(&otadata[inactive_otadata])) {
849 return ESP_FAIL;
850 }
851
852 int ota_slot = (otadata[inactive_otadata].ota_seq - 1) % ota_app_count; // Actual OTA partition selection
853 ESP_LOGD(TAG, "finding last_boot_app_partition ota_%d app...", ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot);
854
855 const esp_partition_t* last_boot_app_partition_from_otadata = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_MIN + ota_slot, NULL);
856 if (last_boot_app_partition_from_otadata == NULL) {
857 return ESP_FAIL;
858 }
859
860 const esp_partition_t* running_partition = esp_ota_get_running_partition();
861 if (running_partition == NULL || last_boot_app_partition_from_otadata == running_partition) {
862 return ESP_FAIL;
863 }
864
865 esp_err_t err = esp_partition_erase_range(last_boot_app_partition_from_otadata, 0, last_boot_app_partition_from_otadata->size);
866 if (err != ESP_OK) {
867 return err;
868 }
869
870 int sec_id = inactive_otadata;
871 err = esp_partition_erase_range(ota_data_partition, sec_id * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
872 if (err != ESP_OK) {
873 return err;
874 }
875
876 return ESP_OK;
877 }
878
879 #if SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 && CONFIG_SECURE_BOOT_V2_ENABLED
esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index)880 esp_err_t esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index) {
881
882 if (!esp_secure_boot_enabled()) {
883 ESP_LOGE(TAG, "Secure boot v2 has not been enabled.");
884 return ESP_FAIL;
885 }
886
887 if (index != SECURE_BOOT_PUBLIC_KEY_INDEX_0 &&
888 index != SECURE_BOOT_PUBLIC_KEY_INDEX_1 &&
889 index != SECURE_BOOT_PUBLIC_KEY_INDEX_2) {
890 ESP_LOGE(TAG, "Invalid Index found for public key revocation %d.", index);
891 return ESP_ERR_INVALID_ARG;
892 }
893
894 esp_image_sig_public_key_digests_t app_digests = { 0 };
895 esp_err_t err = esp_secure_boot_get_signature_blocks_for_running_app(true, &app_digests);
896 if (err != ESP_OK || app_digests.num_digests == 0) {
897 ESP_LOGE(TAG, "This app is not signed, but check signature on update is enabled in config. It won't be possible to verify any update.");
898 return ESP_FAIL;
899 }
900
901 esp_err_t ret;
902 ets_secure_boot_key_digests_t trusted_keys;
903 ret = esp_secure_boot_read_key_digests(&trusted_keys);
904 if (ret != ESP_OK) {
905 ESP_LOGE(TAG, "Could not read the secure boot key digests from efuse. Aborting..");
906 return ESP_FAIL;
907 }
908
909 if (trusted_keys.key_digests[index] == NULL) {
910 ESP_LOGI(TAG, "Trusted Key block(%d) already revoked.", index);
911 return ESP_OK;
912 }
913
914 esp_image_sig_public_key_digests_t trusted_digests = { 0 };
915 for (unsigned i = 0; i < SECURE_BOOT_NUM_BLOCKS; i++) {
916 if (i == index) {
917 continue; // omitting - to find if there is a valid key after revoking this digest
918 }
919
920 if (trusted_keys.key_digests[i] != NULL) {
921 bool all_zeroes = true;
922 for (unsigned j = 0; j < ESP_SECURE_BOOT_DIGEST_LEN; j++) {
923 all_zeroes = all_zeroes && (*(uint8_t *)(trusted_keys.key_digests[i] + j) == 0);
924 }
925 if (!all_zeroes) {
926 memcpy(trusted_digests.key_digests[trusted_digests.num_digests++], (uint8_t *)trusted_keys.key_digests[i], ESP_SECURE_BOOT_DIGEST_LEN);
927 } else {
928 ESP_LOGD(TAG, "Empty trusted key block (%d).", i);
929 }
930 }
931 }
932
933 bool match = false;
934 for (unsigned i = 0; i < trusted_digests.num_digests; i++) {
935 if (match == true) {
936 break;
937 }
938
939 for (unsigned j = 0; j < app_digests.num_digests; j++) {
940 if (memcmp(trusted_digests.key_digests[i], app_digests.key_digests[j], ESP_SECURE_BOOT_DIGEST_LEN) == 0) {
941 ESP_LOGI(TAG, "App key block(%d) matches Trusted key block(%d)[%d -> Next active trusted key block].", j, i, i);
942 esp_err_t err = esp_efuse_set_digest_revoke(index);
943 if (err != ESP_OK) {
944 ESP_LOGE(TAG, "Failed to revoke digest (0x%x).", err);
945 return ESP_FAIL;
946 }
947 ESP_LOGI(TAG, "Revoked signature block %d.", index);
948 match = true;
949 break;
950 }
951 }
952 }
953
954 if (match == false) {
955 ESP_LOGE(TAG, "Running app doesn't have another valid secure boot key. Cannot revoke current key(%d).", index);
956 return ESP_FAIL;
957 }
958
959 return ESP_OK;
960 }
961 #endif
962