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 
15 #include <strings.h>
16 
17 #include "bootloader_flash_priv.h"
18 #include "bootloader_random.h"
19 #include "bootloader_utility.h"
20 #include "esp_image_format.h"
21 #include "esp_flash_encrypt.h"
22 #include "esp_flash_partitions.h"
23 #include "esp_secure_boot.h"
24 #include "esp_log.h"
25 #include "esp32s3/rom/secure_boot.h"
26 #include "esp32s3/rom/cache.h"
27 #include "esp32s3/rom/efuse.h"
28 #include "esp_efuse.h"
29 #include "esp_efuse_table.h"
30 #include "hal/wdt_hal.h"
31 
32 static const char *TAG = "flash_encrypt";
33 
34 /* Static functions for stages of flash encryption */
35 static esp_err_t initialise_flash_encryption(void);
36 static esp_err_t encrypt_flash_contents(uint32_t flash_crypt_cnt, bool flash_crypt_wr_dis) __attribute__((unused));
37 static esp_err_t encrypt_bootloader(void);
38 static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions);
39 static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition);
40 
esp_flash_encrypt_check_and_update(void)41 esp_err_t esp_flash_encrypt_check_and_update(void)
42 {
43     uint8_t flash_crypt_wr_dis = 0;
44     uint32_t flash_crypt_cnt = 0;
45 
46     esp_efuse_read_field_blob(ESP_EFUSE_SPI_BOOT_CRYPT_CNT, &flash_crypt_cnt, 3);
47     esp_efuse_read_field_blob(ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT, &flash_crypt_wr_dis, 1);
48 
49     ESP_LOGV(TAG, "SPI_BOOT_CRYPT_CNT 0x%x", flash_crypt_cnt);
50     ESP_LOGV(TAG, "EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT 0x%x", flash_crypt_wr_dis);
51 
52     if (__builtin_parity(flash_crypt_cnt) == 1) {
53         /* Flash is already encrypted */
54         int left = (flash_crypt_cnt == 1) ? 1 : 0;
55         if (flash_crypt_wr_dis) {
56             left = 0; /* can't update FLASH_CRYPT_CNT, no more flashes */
57         }
58         ESP_LOGI(TAG, "flash encryption is enabled (%d plaintext flashes left)", left);
59         return ESP_OK;
60     } else {
61 
62 #ifndef CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
63         /* Flash is not encrypted, so encrypt it! */
64         return encrypt_flash_contents(flash_crypt_cnt, flash_crypt_wr_dis);
65 #else
66         ESP_LOGE(TAG, "flash encryption is not enabled, and SECURE_FLASH_REQUIRE_ALREADY_ENABLED "
67                       "is set, refusing to boot.");
68         return ESP_ERR_INVALID_STATE;
69 #endif // CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
70 
71     }
72 }
73 
check_and_generate_encryption_keys(void)74 static esp_err_t check_and_generate_encryption_keys(void)
75 {
76     esp_efuse_block_t aes_128_key_block;
77     esp_efuse_block_t aes_256_key_block_1;
78     esp_efuse_block_t aes_256_key_block_2;
79 
80     bool has_aes128   = esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY,   &aes_128_key_block);
81     bool has_aes256_1 = esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_1, &aes_256_key_block_1);
82     bool has_aes256_2 = esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_2, &aes_256_key_block_2);
83     bool has_key = has_aes128 || (has_aes256_1 && has_aes256_2);
84     bool dis_write = false;
85     bool dis_read = false;
86 
87     // If there are keys set, they must be write and read protected!
88     if(has_key && has_aes128) {
89         dis_write = esp_efuse_get_key_dis_write(aes_128_key_block);
90         dis_read  = esp_efuse_get_key_dis_read(aes_128_key_block);
91     } else if (has_key && has_aes256_1 && has_aes256_2) {
92         dis_write = esp_efuse_get_key_dis_write(aes_256_key_block_1) && esp_efuse_get_key_dis_write(aes_256_key_block_2);
93         dis_read  = esp_efuse_get_key_dis_read(aes_256_key_block_1) && esp_efuse_get_key_dis_read(aes_256_key_block_2);
94     }
95 
96     if (!has_key && (has_aes256_1 || has_aes256_2)) {
97         ESP_LOGE(TAG, "Invalid efuse key blocks: Both AES-256 key blocks must be set.");
98         return ESP_ERR_INVALID_STATE;
99     }
100 
101     if(has_key && (!dis_read || !dis_write)) {
102         ESP_LOGE(TAG, "Invalid key state, a key was set but not read and write protected.");
103         return ESP_ERR_INVALID_STATE;
104     }
105 
106     if(!has_key && !dis_write && !dis_read) {
107         ESP_LOGI(TAG, "Generating new flash encryption key...");
108 #ifdef CONFIG_SECURE_FLASH_ENCRYPTION_AES256
109         enum { BLOCKS_NEEDED = 2 };
110         esp_efuse_purpose_t purposes[BLOCKS_NEEDED] = {
111             ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_1,
112             ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_2,
113         };
114 #else
115         enum { BLOCKS_NEEDED = 1 };
116         esp_efuse_purpose_t purposes[BLOCKS_NEEDED] = {
117             ESP_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY,
118         };
119 #endif
120         uint8_t keys[BLOCKS_NEEDED][32] = { 0 };
121         for (int i = 0; i < BLOCKS_NEEDED; ++i) {
122             bootloader_fill_random(keys[i], 32);
123         }
124 
125         esp_err_t err = esp_efuse_write_keys(purposes, keys, BLOCKS_NEEDED);
126         if (err != ESP_OK) {
127             if (err == ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS) {
128                 ESP_LOGE(TAG, "Not enough free efuse key blocks (need %d) to continue", BLOCKS_NEEDED);
129             } else {
130                 ESP_LOGE(TAG, "Failed to write efuse block with purpose (err=0x%x). Can't continue.", err);
131             }
132             return err;
133         }
134         ESP_LOGD(TAG, "Key generation complete");
135         return ESP_OK;
136 
137     } else {
138         ESP_LOGI(TAG, "Using pre-existing key in efuse");
139         return ESP_OK;
140     }
141 }
142 
initialise_flash_encryption(void)143 static esp_err_t initialise_flash_encryption(void)
144 {
145     esp_efuse_batch_write_begin(); /* Batch all efuse writes at the end of this function */
146 
147     esp_err_t key_state = check_and_generate_encryption_keys();
148     if (key_state != ESP_OK) {
149         esp_efuse_batch_write_cancel();
150         return key_state;
151     }
152 
153 #ifndef CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC
154     ESP_LOGI(TAG, "Disable UART bootloader encryption...");
155     esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT);
156 #else
157     ESP_LOGW(TAG, "Not disabling UART bootloader encryption");
158 #endif
159 
160 #ifndef CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE
161     ESP_LOGI(TAG, "Disable UART bootloader cache...");
162     esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_DCACHE);
163     esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_ICACHE);
164 #else
165     ESP_LOGW(TAG, "Not disabling UART bootloader cache - SECURITY COMPROMISED");
166 #endif
167 
168 #ifndef CONFIG_SECURE_BOOT_ALLOW_JTAG
169     ESP_LOGI(TAG, "Disable JTAG...");
170     esp_efuse_write_field_bit(ESP_EFUSE_HARD_DIS_JTAG);
171 #else
172     ESP_LOGW(TAG, "Not disabling JTAG - SECURITY COMPROMISED");
173 #endif
174 
175     esp_efuse_write_field_bit(ESP_EFUSE_DIS_LEGACY_SPI_BOOT);
176 
177     esp_err_t err = esp_efuse_batch_write_commit();
178     if (err != ESP_OK) {
179         ESP_LOGE(TAG, "Error programming security eFuses (err=0x%x).", err);
180     }
181 
182     return err;
183 }
184 
185 /* Encrypt all flash data that should be encrypted */
encrypt_flash_contents(uint32_t spi_boot_crypt_cnt,bool flash_crypt_wr_dis)186 static esp_err_t encrypt_flash_contents(uint32_t spi_boot_crypt_cnt, bool flash_crypt_wr_dis)
187 {
188     esp_err_t err;
189     esp_partition_info_t partition_table[ESP_PARTITION_TABLE_MAX_ENTRIES];
190     int num_partitions;
191 
192     /* If the last spi_boot_crypt_cnt bit is burned or write-disabled, the
193        device can't re-encrypt itself. */
194     if (flash_crypt_wr_dis) {
195         ESP_LOGE(TAG, "Cannot re-encrypt data SPI_BOOT_CRYPT_CNT 0x%02x write disabled %d", spi_boot_crypt_cnt, flash_crypt_wr_dis);
196         return ESP_FAIL;
197     }
198 
199     if (spi_boot_crypt_cnt == 0) {
200         /* Very first flash of encrypted data: generate keys, etc. */
201         err = initialise_flash_encryption();
202         if (err != ESP_OK) {
203             return err;
204         }
205     }
206 
207     err = encrypt_bootloader();
208     if (err != ESP_OK) {
209         return err;
210     }
211 
212     err = encrypt_and_load_partition_table(partition_table, &num_partitions);
213     if (err != ESP_OK) {
214         return err;
215     }
216 
217     /* Now iterate the just-loaded partition table, looking for entries to encrypt */
218     for (int i = 0; i < num_partitions; i++) {
219         err = encrypt_partition(i, &partition_table[i]);
220         if (err != ESP_OK) {
221             return err;
222         }
223     }
224 
225     ESP_LOGD(TAG, "All flash regions checked for encryption pass");
226 
227     /* Set least significant 0-bit in spi_boot_crypt_cnt */
228     int ffs_inv = __builtin_ffs((~spi_boot_crypt_cnt) & 0x7);
229     /* ffs_inv shouldn't be zero, as zero implies spi_boot_crypt_cnt == 0xFF */
230     uint32_t new_spi_boot_crypt_cnt = (1 << (ffs_inv - 1));
231     ESP_LOGD(TAG, "SPI_BOOT_CRYPT_CNT 0x%x -> 0x%x", spi_boot_crypt_cnt, new_spi_boot_crypt_cnt + spi_boot_crypt_cnt);
232 
233     esp_efuse_write_field_blob(ESP_EFUSE_SPI_BOOT_CRYPT_CNT, &new_spi_boot_crypt_cnt, 3);
234 
235 #ifdef CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE
236     //Secure SPI boot cnt after its update if needed.
237     const uint32_t spi_boot_cnt_wr_dis = 1;
238     ESP_LOGI(TAG, "Write protecting SPI_CRYPT_CNT eFuse");
239     esp_efuse_write_field_blob(ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT, &spi_boot_cnt_wr_dis, 1);
240 #endif
241     ESP_LOGI(TAG, "Flash encryption completed");
242 
243     return ESP_OK;
244 }
245 
encrypt_bootloader(void)246 static esp_err_t encrypt_bootloader(void)
247 {
248     esp_err_t err;
249     uint32_t image_length;
250     /* Check for plaintext bootloader (verification will fail if it's already encrypted) */
251     if (esp_image_verify_bootloader(&image_length) == ESP_OK) {
252         ESP_LOGD(TAG, "bootloader is plaintext. Encrypting...");
253 
254 #if CONFIG_SECURE_BOOT_V2_ENABLED
255         /* The image length obtained from esp_image_verify_bootloader includes the sector boundary padding and the signature block lengths */
256         if (ESP_BOOTLOADER_OFFSET + image_length > ESP_PARTITION_TABLE_OFFSET) {
257             ESP_LOGE(TAG, "Bootloader is too large to fit Secure Boot V2 signature sector and partition table (configured offset 0x%x)", ESP_PARTITION_TABLE_OFFSET);
258             return ESP_ERR_INVALID_SIZE;
259         }
260 #endif // CONFIG_SECURE_BOOT_V2_ENABLED
261 
262         err = esp_flash_encrypt_region(ESP_BOOTLOADER_OFFSET, image_length);
263         if (err != ESP_OK) {
264             ESP_LOGE(TAG, "Failed to encrypt bootloader in place: 0x%x", err);
265             return err;
266         }
267 
268         ESP_LOGI(TAG, "bootloader encrypted successfully");
269         return err;
270     }
271     else {
272         ESP_LOGW(TAG, "no valid bootloader was found");
273         return ESP_ERR_NOT_FOUND;
274     }
275 }
276 
encrypt_and_load_partition_table(esp_partition_info_t * partition_table,int * num_partitions)277 static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions)
278 {
279     esp_err_t err;
280     /* Check for plaintext partition table */
281     err = bootloader_flash_read(ESP_PARTITION_TABLE_OFFSET, partition_table, ESP_PARTITION_TABLE_MAX_LEN, false);
282     if (err != ESP_OK) {
283         ESP_LOGE(TAG, "Failed to read partition table data");
284         return err;
285     }
286     if (esp_partition_table_verify(partition_table, false, num_partitions) == ESP_OK) {
287         ESP_LOGD(TAG, "partition table is plaintext. Encrypting...");
288         esp_err_t err = esp_flash_encrypt_region(ESP_PARTITION_TABLE_OFFSET,
289                                                  FLASH_SECTOR_SIZE);
290         if (err != ESP_OK) {
291             ESP_LOGE(TAG, "Failed to encrypt partition table in place. %x", err);
292             return err;
293         }
294     }
295     else {
296         ESP_LOGE(TAG, "Failed to read partition table data - not plaintext?");
297         return ESP_ERR_INVALID_STATE;
298     }
299 
300     /* Valid partition table loded */
301     ESP_LOGI(TAG, "partition table encrypted and loaded successfully");
302     return ESP_OK;
303 }
304 
305 
encrypt_partition(int index,const esp_partition_info_t * partition)306 static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition)
307 {
308     esp_err_t err;
309     bool should_encrypt = (partition->flags & PART_FLAG_ENCRYPTED);
310 
311     if (partition->type == PART_TYPE_APP) {
312       /* check if the partition holds a valid unencrypted app */
313       esp_image_metadata_t data_ignored;
314       err = esp_image_verify(ESP_IMAGE_VERIFY,
315                            &partition->pos,
316                            &data_ignored);
317       should_encrypt = (err == ESP_OK);
318     } else if (partition->type == PART_TYPE_DATA && partition->subtype == PART_SUBTYPE_DATA_OTA) {
319         /* check if we have ota data partition and the partition should be encrypted unconditionally */
320         should_encrypt = true;
321     }
322 
323     if (!should_encrypt) {
324         return ESP_OK;
325     }
326     else {
327         /* should_encrypt */
328         ESP_LOGI(TAG, "Encrypting partition %d at offset 0x%x (length 0x%x)...", index, partition->pos.offset, partition->pos.size);
329 
330         err = esp_flash_encrypt_region(partition->pos.offset, partition->pos.size);
331         ESP_LOGI(TAG, "Done encrypting");
332         if (err != ESP_OK) {
333             ESP_LOGE(TAG, "Failed to encrypt partition %d", index);
334         }
335         return err;
336     }
337 }
338 
339 
esp_flash_encrypt_region(uint32_t src_addr,size_t data_length)340 esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length)
341 {
342     esp_err_t err;
343     uint32_t buf[FLASH_SECTOR_SIZE / sizeof(uint32_t)];
344 
345     if (src_addr % FLASH_SECTOR_SIZE != 0) {
346         ESP_LOGE(TAG, "esp_flash_encrypt_region bad src_addr 0x%x",src_addr);
347         return ESP_FAIL;
348     }
349 
350     wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
351     for (size_t i = 0; i < data_length; i += FLASH_SECTOR_SIZE) {
352 
353         wdt_hal_write_protect_disable(&rtc_wdt_ctx);
354         wdt_hal_feed(&rtc_wdt_ctx);
355         wdt_hal_write_protect_enable(&rtc_wdt_ctx);
356 
357         uint32_t sec_start = i + src_addr;
358         err = bootloader_flash_read(sec_start, buf, FLASH_SECTOR_SIZE, false);
359         if (err != ESP_OK) {
360             goto flash_failed;
361         }
362         err = bootloader_flash_erase_sector(sec_start / FLASH_SECTOR_SIZE);
363         if (err != ESP_OK) {
364             goto flash_failed;
365         }
366         err = bootloader_flash_write(sec_start, buf, FLASH_SECTOR_SIZE, true);
367         if (err != ESP_OK) {
368             goto flash_failed;
369         }
370     }
371     return ESP_OK;
372 
373  flash_failed:
374     ESP_LOGE(TAG, "flash operation failed: 0x%x", err);
375     return err;
376 }
377