1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <string.h>
7 
8 #include "esp_log.h"
9 #include "esp_secure_boot.h"
10 #include "soc/efuse_reg.h"
11 
12 #include "bootloader_flash_priv.h"
13 #include "bootloader_sha.h"
14 #include "bootloader_utility.h"
15 
16 #include "esp_rom_crc.h"
17 #include "esp_efuse.h"
18 #include "esp_efuse_table.h"
19 
20 #include "esp32h2/rom/efuse.h"
21 #include "esp32h2/rom/secure_boot.h"
22 
23 static const char *TAG = "secure_boot_v2";
24 #define ALIGN_UP(num, align) (((num) + ((align) - 1)) & ~((align) - 1))
25 
26 /* A signature block is valid when it has correct magic byte, crc and image digest. */
validate_signature_block(const ets_secure_boot_sig_block_t * block,int block_num,const uint8_t * image_digest)27 static esp_err_t validate_signature_block(const ets_secure_boot_sig_block_t *block, int block_num, const uint8_t *image_digest)
28 {
29     uint32_t crc = esp_rom_crc32_le(0, (uint8_t *)block, CRC_SIGN_BLOCK_LEN);
30     if (block->magic_byte != ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC) {
31         // All signature blocks have been parsed, no new signature block present.
32         ESP_LOGD(TAG, "Signature block(%d) invalid/absent.", block_num);
33         return ESP_FAIL;
34     }
35     if (block->block_crc != crc) {
36         ESP_LOGE(TAG, "Magic byte correct but incorrect crc.");
37         return ESP_FAIL;
38     }
39     if (memcmp(image_digest, block->image_digest, ESP_SECURE_BOOT_DIGEST_LEN)) {
40         ESP_LOGE(TAG, "Magic byte & CRC correct but incorrect image digest.");
41         return ESP_FAIL;
42     } else {
43         ESP_LOGD(TAG, "valid signature block(%d) found", block_num);
44         return ESP_OK;
45     }
46 
47     return ESP_FAIL;
48 }
49 
50 /* Generates the public key digests of the valid public keys in an image's
51    signature block, verifies each signature, and stores the key digests in the
52    public_key_digests structure.
53 
54    @param flash_offset Image offset in flash
55    @param flash_size Image size in flash (not including signature block)
56    @param[out] public_key_digests Pointer to structure to hold the key digests for valid sig blocks
57 
58 
59    Note that this function doesn't read any eFuses, so it doesn't know if the
60    keys are ultimately trusted by the hardware or not
61 
62    @return - ESP_OK if no signatures failed to verify, or if no valid signature blocks are found at all.
63            - ESP_FAIL if there's a valid signature block that doesn't verify using the included public key (unexpected!)
64 */
s_calculate_image_public_key_digests(uint32_t flash_offset,uint32_t flash_size,esp_image_sig_public_key_digests_t * public_key_digests)65 static esp_err_t s_calculate_image_public_key_digests(uint32_t flash_offset, uint32_t flash_size, esp_image_sig_public_key_digests_t *public_key_digests)
66 {
67     esp_err_t ret;
68     uint8_t image_digest[ESP_SECURE_BOOT_DIGEST_LEN] = {0};
69     uint8_t __attribute__((aligned(4))) key_digest[ESP_SECURE_BOOT_DIGEST_LEN] = {0};
70     size_t sig_block_addr = flash_offset + ALIGN_UP(flash_size, FLASH_SECTOR_SIZE);
71 
72     ESP_LOGD(TAG, "calculating public key digests for sig blocks of image offset 0x%x (sig block offset 0x%x)", flash_offset, sig_block_addr);
73 
74     bzero(public_key_digests, sizeof(esp_image_sig_public_key_digests_t));
75 
76     ret = bootloader_sha256_flash_contents(flash_offset, sig_block_addr - flash_offset, image_digest);
77     if (ret != ESP_OK) {
78         ESP_LOGE(TAG, "error generating image digest, %d", ret);
79         return ret;
80     }
81 
82     ESP_LOGD(TAG, "reading signatures");
83     const ets_secure_boot_signature_t *signatures = bootloader_mmap(sig_block_addr, sizeof(ets_secure_boot_signature_t));
84     if (signatures == NULL) {
85         ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", sig_block_addr, sizeof(ets_secure_boot_signature_t));
86         return ESP_FAIL;
87     }
88 
89     for (int i = 0; i < SECURE_BOOT_NUM_BLOCKS; i++) {
90         const ets_secure_boot_sig_block_t *block = &signatures->block[i];
91 
92         ret = validate_signature_block(block, i, image_digest);
93         if (ret != ESP_OK) {
94             ret = ESP_OK;  // past the last valid signature block
95             break;
96         }
97 
98         /* Generating the SHA of the public key components in the signature block */
99         bootloader_sha256_handle_t sig_block_sha;
100         sig_block_sha = bootloader_sha256_start();
101         bootloader_sha256_data(sig_block_sha, &block->key, sizeof(block->key));
102         bootloader_sha256_finish(sig_block_sha, key_digest);
103 
104         // Check we can verify the image using this signature and this key
105         uint8_t temp_verified_digest[ESP_SECURE_BOOT_DIGEST_LEN];
106         bool verified = ets_rsa_pss_verify(&block->key, block->signature, image_digest, temp_verified_digest);
107 
108         if (!verified) {
109             /* We don't expect this: the signature blocks before we enable secure boot should all be verifiable or invalid,
110                so this is a fatal error
111             */
112             ret = ESP_FAIL;
113             ESP_LOGE(TAG, "Secure boot key (%d) verification failed.", i);
114             break;
115         }
116         ESP_LOGD(TAG, "Signature block (%d) is verified", i);
117         /* Copy the key digest to the buffer provided by the caller */
118         memcpy((void *)public_key_digests->key_digests[i], key_digest, ESP_SECURE_BOOT_DIGEST_LEN);
119         public_key_digests->num_digests++;
120     }
121 
122     if (ret == ESP_OK && public_key_digests->num_digests > 0) {
123         ESP_LOGI(TAG, "Digests successfully calculated, %d valid signatures (image offset 0x%x)",
124                  public_key_digests->num_digests, flash_offset);
125     }
126 
127     bootloader_munmap(signatures);
128     return ret;
129 }
130 
check_and_generate_secure_boot_keys(const esp_image_metadata_t * image_data)131 static esp_err_t check_and_generate_secure_boot_keys(const esp_image_metadata_t *image_data)
132 {
133     esp_err_t ret;
134     /* Verify the bootloader */
135     esp_image_metadata_t bootloader_data = { 0 };
136     ret = esp_image_verify_bootloader_data(&bootloader_data);
137     if (ret != ESP_OK) {
138         ESP_LOGE(TAG, "bootloader image appears invalid! error %d", ret);
139         return ret;
140     }
141 
142     /* Check if secure boot digests are present */
143     bool has_secure_boot_digest = esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0, NULL);
144     has_secure_boot_digest |= esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1, NULL);
145     has_secure_boot_digest |= esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2, NULL);
146     ESP_LOGI(TAG, "Secure boot digests %s", has_secure_boot_digest ? "already present":"absent, generating..");
147 
148     if (!has_secure_boot_digest) {
149         esp_image_sig_public_key_digests_t boot_key_digests = {0};
150         esp_image_sig_public_key_digests_t app_key_digests = {0};
151 
152         /* Generate the bootloader public key digests */
153         ret = s_calculate_image_public_key_digests(bootloader_data.start_addr, bootloader_data.image_len - SIG_BLOCK_PADDING, &boot_key_digests);
154         if (ret != ESP_OK) {
155             ESP_LOGE(TAG, "Bootloader signature block is invalid");
156             return ret;
157         }
158 
159         if (boot_key_digests.num_digests == 0) {
160             ESP_LOGE(TAG, "No valid bootloader signature blocks found.");
161             return ESP_FAIL;
162         }
163         ESP_LOGI(TAG, "%d signature block(s) found appended to the bootloader.", boot_key_digests.num_digests);
164 
165         esp_efuse_purpose_t secure_boot_key_purpose[SECURE_BOOT_NUM_BLOCKS] = {
166             ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0,
167             ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1,
168             ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2,
169         };
170 
171         ret = esp_efuse_write_keys(secure_boot_key_purpose, boot_key_digests.key_digests, boot_key_digests.num_digests);
172         if (ret) {
173             if (ret == ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS) {
174                 ESP_LOGE(TAG, "Bootloader signatures(%d) more than available key slots.", boot_key_digests.num_digests);
175             } else {
176                 ESP_LOGE(TAG, "Failed to write efuse block with purpose (err=0x%x). Can't continue.", ret);
177             }
178             return ret;
179         }
180 
181         /* Generate the application public key digests */
182         ret = s_calculate_image_public_key_digests(image_data->start_addr, image_data->image_len - SIG_BLOCK_PADDING, &app_key_digests);
183         if (ret != ESP_OK) {
184             ESP_LOGE(TAG, "App signature block is invalid.");
185             return ret;
186         }
187 
188         if (app_key_digests.num_digests == 0) {
189             ESP_LOGE(TAG, "No valid applications signature blocks found.");
190             return ESP_FAIL;
191         }
192 
193         ESP_LOGI(TAG, "%d signature block(s) found appended to the app.", app_key_digests.num_digests);
194         if (app_key_digests.num_digests > boot_key_digests.num_digests) {
195             ESP_LOGW(TAG, "App has %d signature blocks but bootloader only has %d. Some keys missing from bootloader?");
196         }
197 
198         /* Confirm if at least one public key from the application matches a public key in the bootloader
199            (Also, ensure if that public revoke bit is not set for the matched key) */
200         bool match = false;
201 
202         for (int i = 0; i < boot_key_digests.num_digests; i++) {
203 
204             if (esp_efuse_get_digest_revoke(i)) {
205                 ESP_LOGI(TAG, "Key block(%d) has been revoked.", i);
206                 continue; // skip if the key block is revoked
207             }
208 
209             for (int j = 0; j < app_key_digests.num_digests; j++) {
210                 if (!memcmp(boot_key_digests.key_digests[i], app_key_digests.key_digests[j], ESP_SECURE_BOOT_DIGEST_LEN)) {
211                     ESP_LOGI(TAG, "Application key(%d) matches with bootloader key(%d).", j, i);
212                     match = true;
213                 }
214             }
215         }
216 
217         if (match == false) {
218             ESP_LOGE(TAG, "No application key digest matches the bootloader key digest.");
219             return ESP_FAIL;
220         }
221 
222         /* Revoke the empty signature blocks */
223         if (boot_key_digests.num_digests < SECURE_BOOT_NUM_BLOCKS) {
224             /* The revocation index can be 0, 1, 2. Bootloader count can be 1,2,3. */
225             for (uint8_t i = boot_key_digests.num_digests; i < SECURE_BOOT_NUM_BLOCKS; i++) {
226                 ESP_LOGI(TAG, "Revoking empty key digest slot (%d)...", i);
227                 esp_efuse_set_digest_revoke(i);
228             }
229         }
230     }
231     return ESP_OK;
232 }
233 
esp_secure_boot_v2_permanently_enable(const esp_image_metadata_t * image_data)234 esp_err_t esp_secure_boot_v2_permanently_enable(const esp_image_metadata_t *image_data)
235 {
236     ESP_LOGI(TAG, "enabling secure boot v2...");
237 
238     if (esp_secure_boot_enabled()) {
239         ESP_LOGI(TAG, "secure boot v2 is already enabled, continuing..");
240         return ESP_OK;
241     }
242 
243     esp_efuse_batch_write_begin(); /* Batch all efuse writes at the end of this function */
244 
245     esp_err_t key_state = check_and_generate_secure_boot_keys(image_data);
246     if (key_state != ESP_OK) {
247         esp_efuse_batch_write_cancel();
248         return key_state;
249     }
250 
251     esp_efuse_write_field_bit(ESP_EFUSE_DIS_LEGACY_SPI_BOOT);
252 
253     esp_err_t err = ESP_FAIL;
254 #ifdef CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE
255     ESP_LOGI(TAG, "Enabling Security download mode...");
256     err = esp_efuse_enable_rom_secure_download_mode();
257     if (err != ESP_OK) {
258         ESP_LOGE(TAG, "Could not enable Security download mode...");
259         return err;
260     }
261 #elif CONFIG_SECURE_DISABLE_ROM_DL_MODE
262     ESP_LOGI(TAG, "Disable ROM Download mode...");
263     err = esp_efuse_disable_rom_download_mode();
264     if (err != ESP_OK) {
265         ESP_LOGE(TAG, "Could not disable ROM Download mode...");
266         return err;
267     }
268 #else
269     ESP_LOGW(TAG, "UART ROM Download mode kept enabled - SECURITY COMPROMISED");
270 #endif
271 
272 #ifndef CONFIG_SECURE_BOOT_ALLOW_JTAG
273     ESP_LOGI(TAG, "Disable hardware & software JTAG...");
274     esp_efuse_write_field_bit(ESP_EFUSE_DIS_PAD_JTAG);
275     esp_efuse_write_field_bit(ESP_EFUSE_DIS_USB_JTAG);
276     esp_efuse_write_field_cnt(ESP_EFUSE_SOFT_DIS_JTAG, ESP_EFUSE_SOFT_DIS_JTAG[0]->bit_count);
277 #else
278     ESP_LOGW(TAG, "Not disabling JTAG - SECURITY COMPROMISED");
279 #endif
280 
281 #ifdef CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE
282     esp_efuse_write_field_bit(ESP_EFUSE_SECURE_BOOT_AGGRESSIVE_REVOKE);
283 #endif
284 
285     esp_efuse_write_field_bit(ESP_EFUSE_SECURE_BOOT_EN);
286 
287     err = esp_efuse_batch_write_commit();
288     if (err != ESP_OK) {
289         ESP_LOGE(TAG, "Error programming security eFuses (err=0x%x).", err);
290         return err;
291     }
292 
293 #ifdef CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE
294     assert(ets_efuse_secure_boot_aggressive_revoke_enabled());
295 #endif
296 
297     assert(esp_rom_efuse_is_secure_boot_enabled());
298     ESP_LOGI(TAG, "Secure boot permanently enabled");
299 
300     return ESP_OK;
301 }
302