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