]> granicus.if.org Git - esp-idf/blob - components/bootloader_support/src/flash_encrypt.c
Flash encryption: Support enabling flash encryption in bootloader, app support
[esp-idf] / components / bootloader_support / src / flash_encrypt.c
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.h"
18 #include "bootloader_random.h"
19 #include "esp_image_format.h"
20 #include "esp_flash_encrypt.h"
21 #include "esp_flash_partitions.h"
22 #include "esp_flash_data_types.h"
23 #include "esp_secure_boot.h"
24 #include "esp_efuse.h"
25 #include "esp_log.h"
26 #include "rom/secure_boot.h"
27
28 #include "rom/cache.h"
29 #include "rom/spi_flash.h"   /* TODO: Remove this */
30
31 static const char *TAG = "flash_encrypt";
32
33 /* Static functions for stages of flash encryption */
34 static esp_err_t initialise_flash_encryption(void);
35 static esp_err_t encrypt_flash_contents(uint32_t flash_crypt_cnt, bool flash_crypt_wr_dis);
36 static esp_err_t encrypt_bootloader();
37 static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions);
38 static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition);
39
40 esp_err_t esp_flash_encrypt_check_and_update(void)
41 {
42     uint32_t efuse_blk0 = REG_READ(EFUSE_BLK0_RDATA0_REG);
43     ESP_LOGV(TAG, "efuse_blk0 raw value %08x", efuse_blk0);
44     uint32_t flash_crypt_cnt = (efuse_blk0 & EFUSE_RD_FLASH_CRYPT_CNT_M) >> EFUSE_RD_FLASH_CRYPT_CNT_S;
45     bool flash_crypt_wr_dis = efuse_blk0 & EFUSE_WR_DIS_FLASH_CRYPT_CNT;
46     ESP_LOGV(TAG, "efuse FLASH_CRYPT_CNT 0x%x WR_DIS_FLASH_CRYPT_CNT 0x%x", flash_crypt_cnt, flash_crypt_wr_dis);
47
48     if (__builtin_parity(flash_crypt_cnt) == 1) {
49         /* Flash is already encrypted */
50         int left = (7 - __builtin_popcount(flash_crypt_cnt)) / 2;
51         if (flash_crypt_wr_dis) {
52             left = 0; /* can't update FLASH_CRYPT_CNT, no more flashes */
53         }
54         ESP_LOGI(TAG, "flash encryption is enabled (%d plaintext flashes left)", left);
55         return ESP_OK;
56     }
57     else {
58         /* Flash is not encrypted, so encrypt it! */
59         return encrypt_flash_contents(flash_crypt_cnt, flash_crypt_wr_dis);
60     }
61 }
62
63 static esp_err_t initialise_flash_encryption(void)
64 {
65     /* Before first flash encryption pass, need to initialise key & crypto config */
66
67     /* Generate key */
68     uint32_t dis_reg = REG_READ(EFUSE_BLK0_RDATA0_REG);
69     bool efuse_key_read_protected = dis_reg & EFUSE_RD_DIS_BLK1;
70     bool efuse_key_write_protected = dis_reg & EFUSE_WR_DIS_BLK1;
71     if (efuse_key_read_protected == false
72         && efuse_key_write_protected == false
73         && REG_READ(EFUSE_BLK1_RDATA0_REG) == 0
74         && REG_READ(EFUSE_BLK1_RDATA1_REG) == 0
75         && REG_READ(EFUSE_BLK1_RDATA2_REG) == 0
76         && REG_READ(EFUSE_BLK1_RDATA3_REG) == 0
77         && REG_READ(EFUSE_BLK1_RDATA4_REG) == 0
78         && REG_READ(EFUSE_BLK1_RDATA5_REG) == 0
79         && REG_READ(EFUSE_BLK1_RDATA6_REG) == 0
80         && REG_READ(EFUSE_BLK1_RDATA7_REG) == 0) {
81         ESP_LOGI(TAG, "Generating new flash encryption key...");
82         uint32_t buf[8];
83         bootloader_fill_random(buf, sizeof(buf));
84         for (int i = 0; i < 8; i++) {
85             ESP_LOGV(TAG, "EFUSE_BLK1_WDATA%d_REG = 0x%08x", i, buf[i]);
86             REG_WRITE(EFUSE_BLK1_WDATA0_REG + 4*i, buf[i]);
87         }
88         bzero(buf, sizeof(buf));
89         esp_efuse_burn_new_values();
90
91         ESP_LOGI(TAG, "Read & write protecting new key...");
92         REG_WRITE(EFUSE_BLK0_WDATA0_REG, EFUSE_WR_DIS_BLK1 | EFUSE_RD_DIS_BLK1);
93         esp_efuse_burn_new_values();
94     } else {
95
96         if(!(efuse_key_read_protected && efuse_key_write_protected)) {
97             ESP_LOGE(TAG, "Flash encryption key has to be either unset or both read and write protected");
98             return ESP_ERR_INVALID_STATE;
99         }
100         ESP_LOGW(TAG, "Using pre-loaded flash encryption key in EFUSE block 1");
101     }
102     /* CRYPT_CONFIG determines which bits of the AES block key are XORed
103        with bits from the flash address, to provide the key tweak.
104
105        CRYPT_CONFIG == 0 is effectively AES ECB mode (NOT SUPPORTED)
106
107        For now this is hardcoded to XOR all 256 bits of the key.
108
109        If you need to override it, you can pre-burn this efuse to the
110        desired value and then write-protect it, in which case this
111        operation does nothing. Please note this is not recommended!
112     */
113     ESP_LOGI(TAG, "Setting CRYPT_CONFIG efuse to 0xF");
114     REG_WRITE(EFUSE_BLK0_WDATA5_REG, EFUSE_FLASH_CRYPT_CONFIG_M);
115     esp_efuse_burn_new_values();
116
117 #ifndef CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_WRITE
118     ESP_LOGI(TAG, "Disable UART bootloader write...");
119     //REG_WRITE(EFUSE_BLK0_
120
121 #endif
122     return ESP_OK;
123 }
124
125 /* Encrypt all flash data that should be encrypted */
126 static esp_err_t encrypt_flash_contents(uint32_t flash_crypt_cnt, bool flash_crypt_wr_dis)
127 {
128     esp_err_t err;
129     esp_partition_info_t partition_table[ESP_PARTITION_TABLE_MAX_ENTRIES];
130     int num_partitions;
131
132     /* If the last flash_crypt_cnt bit is burned or write-disabled, the
133        device can't re-encrypt itself. */
134     if (flash_crypt_wr_dis || flash_crypt_cnt == 0xFF) {
135         ESP_LOGE(TAG, "Cannot re-encrypt data (FLASH_CRYPT_CNT 0x%02x write disabled %d", flash_crypt_cnt, flash_crypt_wr_dis);
136         return ESP_FAIL;
137     }
138
139     if (flash_crypt_cnt == 0) {
140         /* Very first flash of encrypted data: generate keys, etc. */
141         err = initialise_flash_encryption();
142         if (err != ESP_OK) {
143             return err;
144         }
145     }
146
147     err = encrypt_bootloader();
148     if (err != ESP_OK) {
149         return err;
150     }
151
152     err = encrypt_and_load_partition_table(partition_table, &num_partitions);
153     if (err != ESP_OK) {
154         return err;
155     }
156
157     /* Now iterate the just-loaded partition table, looking for entries to encrypt
158      */
159
160     /* Go through each partition and encrypt if necessary */
161     for (int i = 0; i < num_partitions; i++) {
162         err = encrypt_partition(i, &partition_table[i]);
163         if (err != ESP_OK) {
164             return err;
165         }
166     }
167
168     ESP_LOGD(TAG, "All flash regions checked for encryption pass");
169
170     /* Set least significant 0-bit in flash_crypt_cnt */
171     int ffs_inv = __builtin_ffs((~flash_crypt_cnt) & 0xFF);
172     /* ffs_inv shouldn't be zero, as zero implies flash_crypt_cnt == 0xFF */
173     uint32_t new_flash_crypt_cnt = flash_crypt_cnt + (1 << (ffs_inv - 1));
174     ESP_LOGD(TAG, "FLASH_CRYPT_CNT 0x%x -> 0x%x", flash_crypt_cnt, new_flash_crypt_cnt);
175     REG_SET_FIELD(EFUSE_BLK0_WDATA0_REG, EFUSE_FLASH_CRYPT_CNT, new_flash_crypt_cnt);
176     esp_efuse_burn_new_values();
177
178     ESP_LOGI(TAG, "Flash encryption completed");
179
180     return ESP_OK;
181 }
182
183 static esp_err_t encrypt_bootloader()
184 {
185     esp_err_t err;
186     uint32_t image_length;
187     /* Check for plaintext bootloader */
188     if (esp_image_basic_verify(ESP_BOOTLOADER_OFFSET, false, &image_length) == ESP_OK) {
189         ESP_LOGD(TAG, "bootloader is plaintext. Encrypting...");
190         err = esp_flash_encrypt_region(ESP_BOOTLOADER_OFFSET, image_length);
191         if (err != ESP_OK) {
192             ESP_LOGE(TAG, "Failed to encrypt bootloader in place: 0x%x", err);
193             return err;
194         }
195
196         if (esp_secure_boot_enabled()) {
197             /* If secure boot is enabled and bootloader was plaintext, also
198                need to encrypt secure boot IV+digest.
199             */
200             ESP_LOGD(TAG, "Encrypting secure bootloader IV & digest...");
201             err = esp_flash_encrypt_region(FLASH_OFFS_SECURE_BOOT_IV_DIGEST,
202                                            FLASH_SECTOR_SIZE);
203             if (err != ESP_OK) {
204                 ESP_LOGE(TAG, "Failed to encrypt bootloader IV & digest in place: 0x%x", err);
205                 return err;
206             }
207         }
208     }
209     else {
210         ESP_LOGW(TAG, "no valid bootloader was found");
211     }
212
213     return ESP_OK;
214 }
215
216 static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions)
217 {
218     esp_err_t err;
219     /* Check for plaintext partition table */
220     err = bootloader_flash_read(ESP_PARTITION_TABLE_OFFSET, partition_table, ESP_PARTITION_TABLE_MAX_LEN, false);
221     if (err != ESP_OK) {
222         ESP_LOGE(TAG, "Failed to read partition table data");
223         return err;
224     }
225     if (esp_partition_table_basic_verify(partition_table, false, num_partitions) == ESP_OK) {
226         ESP_LOGD(TAG, "partition table is plaintext. Encrypting...");
227         esp_err_t err = esp_flash_encrypt_region(ESP_PARTITION_TABLE_OFFSET,
228                                                  FLASH_SECTOR_SIZE);
229         if (err != ESP_OK) {
230             ESP_LOGE(TAG, "Failed to encrypt partition table in place. %x", err);
231             return err;
232         }
233     }
234     else {
235         ESP_LOGE(TAG, "Failed to read partition table data - not plaintext?");
236         return ESP_ERR_INVALID_STATE;
237     }
238
239     /* Valid partition table loded */
240     return ESP_OK;
241 }
242
243
244 static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition)
245 {
246     esp_err_t err;
247     uint32_t image_len = partition->pos.size;
248     bool should_encrypt = (partition->flags & PART_FLAG_ENCRYPTED);
249
250     if (partition->type == PART_TYPE_APP) {
251         /* check if the partition holds an unencrypted app */
252         if (esp_image_basic_verify(partition->pos.offset, false, &image_len) == ESP_OK) {
253             if(image_len > partition->pos.size) {
254                 ESP_LOGE(TAG, "partition entry %d has image longer than partition (%d vs %d)", index, image_len, partition->pos.size);
255                 should_encrypt = false;
256             } else {
257                 should_encrypt = true;
258             }
259         } else {
260             should_encrypt = false;
261         }
262     }
263
264     if (!should_encrypt) {
265         return ESP_OK;
266     }
267     else {
268         /* should_encrypt */
269         ESP_LOGI(TAG, "Encrypting partition %d at offset 0x%x...", index, partition->pos.offset);
270
271         err = esp_flash_encrypt_region(partition->pos.offset, partition->pos.size);
272         if (err != ESP_OK) {
273             ESP_LOGE(TAG, "Failed to encrypt partition %d", index);
274         }
275         return err;
276     }
277 }
278
279
280 esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length)
281 {
282     esp_err_t err;
283     uint32_t buf[FLASH_SECTOR_SIZE / sizeof(uint32_t)];
284
285     if (src_addr % FLASH_SECTOR_SIZE != 0) {
286         ESP_LOGE(TAG, "esp_flash_encrypt_region bad src_addr 0x%x",src_addr);
287         return ESP_FAIL;
288     }
289
290     for (size_t i = 0; i < data_length; i += FLASH_SECTOR_SIZE) {
291         uint32_t sec_start = i + src_addr;
292         err = bootloader_flash_read(sec_start, buf, FLASH_SECTOR_SIZE, false);
293         if (err != ESP_OK) {
294             goto flash_failed;
295         }
296         err = bootloader_flash_erase_sector(sec_start / FLASH_SECTOR_SIZE);
297         if (err != ESP_OK) {
298             goto flash_failed;
299         }
300         err = bootloader_flash_write(sec_start, buf, FLASH_SECTOR_SIZE, true);
301         if (err != ESP_OK) {
302             goto flash_failed;
303         }
304     }
305     return ESP_OK;
306
307  flash_failed:
308     ESP_LOGE(TAG, "flash operation failed: 0x%x", err);
309     return err;
310 }