• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "sdkconfig.h"
15 
16 #include "bootloader_flash_priv.h"
17 #include "bootloader_sha.h"
18 #include "bootloader_utility.h"
19 #include "esp_log.h"
20 #include "esp_image_format.h"
21 #include "mbedtls/sha256.h"
22 #include "mbedtls/x509.h"
23 #include "mbedtls/md.h"
24 #include "mbedtls/platform.h"
25 #include "mbedtls/entropy.h"
26 #include "mbedtls/ctr_drbg.h"
27 #include <string.h>
28 #include <sys/param.h>
29 #include "esp_secure_boot.h"
30 #include "esp_ota_ops.h"
31 
32 // Secure boot V2 for app
33 
34 _Static_assert(SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS == SECURE_BOOT_NUM_BLOCKS,
35                "Parts of this code rely on the max number of signatures appended to an image"
36                "being the same as the max number of trusted keys.");
37 
38 #if CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME || CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
39 
40 static const char *TAG = "secure_boot_v2";
41 #define ALIGN_UP(num, align) (((num) + ((align) - 1)) & ~((align) - 1))
42 
43 /* A signature block is valid when it has correct magic byte, crc. */
validate_signature_block(const ets_secure_boot_sig_block_t * block)44 static esp_err_t validate_signature_block(const ets_secure_boot_sig_block_t *block)
45 {
46     if (block->magic_byte != ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC
47         || block->block_crc != esp_rom_crc32_le(0, (uint8_t *)block, CRC_SIGN_BLOCK_LEN)) {
48         return ESP_FAIL;
49     }
50     return ESP_OK;
51 }
52 
esp_secure_boot_get_signature_blocks_for_running_app(bool digest_public_keys,esp_image_sig_public_key_digests_t * public_key_digests)53 esp_err_t esp_secure_boot_get_signature_blocks_for_running_app(bool digest_public_keys, esp_image_sig_public_key_digests_t *public_key_digests)
54 {
55     esp_image_metadata_t metadata;
56     const esp_partition_t* running_app_part = esp_ota_get_running_partition();
57     if (running_app_part == NULL) {
58         ESP_LOGE(TAG, "Cannot get running partition");
59         return ESP_FAIL;
60     }
61     const esp_partition_pos_t part_pos = {
62         .offset = running_app_part->address,
63         .size   = running_app_part->size,
64     };
65     esp_err_t err = esp_image_get_metadata(&part_pos, &metadata);
66     if (err != ESP_OK) {
67         ESP_LOGE(TAG, "Error reading metadata from running app (err=0x%x)", err);
68         return ESP_FAIL;
69     }
70 
71     memset(public_key_digests, 0, sizeof(esp_image_sig_public_key_digests_t));
72 
73     // Generating the SHA of the public key components in the signature block
74 
75     // metadata.image_len doesn't include any padding to start of the signature sector, so pad it here
76     size_t sig_block_addr = metadata.start_addr + ALIGN_UP(metadata.image_len, FLASH_SECTOR_SIZE);
77     ESP_LOGD(TAG, "reading signatures for app address 0x%x sig block address 0x%x", part_pos.offset, sig_block_addr);
78     for (unsigned i = 0; i < SECURE_BOOT_NUM_BLOCKS; i++) {
79         ets_secure_boot_sig_block_t block;
80         size_t addr = sig_block_addr + sizeof(ets_secure_boot_sig_block_t) * i;
81         esp_err_t err = bootloader_flash_read(addr, &block, sizeof(ets_secure_boot_sig_block_t), true);
82         if (err == ESP_OK) {
83             if (validate_signature_block(&block) == ESP_OK) {
84                 if (digest_public_keys) {
85                     bootloader_sha256_handle_t sig_block_sha = bootloader_sha256_start();
86                     bootloader_sha256_data(sig_block_sha, &block.key, sizeof(block.key));
87                     bootloader_sha256_finish(sig_block_sha, public_key_digests->key_digests[i]);
88                 }
89                 public_key_digests->num_digests++;
90             }
91         } else {
92             ESP_LOGE(TAG, "Secure boot sign blocks cannot be read from a running app (err=0x%x)", err);
93             return ESP_FAIL;
94         }
95     }
96     if (public_key_digests->num_digests > 0) {
97         return ESP_OK;
98     }
99     ESP_LOGE(TAG, "No signatures were found for the running app");
100     return ESP_ERR_NOT_FOUND;
101 }
102 
get_secure_boot_key_digests(esp_image_sig_public_key_digests_t * public_key_digests)103 static esp_err_t get_secure_boot_key_digests(esp_image_sig_public_key_digests_t *public_key_digests)
104 {
105 #ifdef CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
106     // Gets key digests from running app
107     ESP_LOGI(TAG, "Take trusted digest key(s) from running app");
108     return esp_secure_boot_get_signature_blocks_for_running_app(true, public_key_digests);
109 #elif CONFIG_SECURE_BOOT_V2_ENABLED
110     ESP_LOGI(TAG, "Take trusted digest key(s) from eFuse block(s)");
111 #if SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1
112     // Read key digests from efuse
113     ets_secure_boot_key_digests_t efuse_trusted;
114     if (ets_secure_boot_read_key_digests(&efuse_trusted) == ETS_OK) {
115         for (unsigned i = 0; i < SECURE_BOOT_NUM_BLOCKS; i++) {
116             if (efuse_trusted.key_digests[i] != NULL) {
117                 memcpy(public_key_digests->key_digests[i], (uint8_t *)efuse_trusted.key_digests[i], ESP_SECURE_BOOT_DIGEST_LEN);
118                 public_key_digests->num_digests++;
119             }
120         }
121     }
122     if (public_key_digests->num_digests > 0) {
123         return ESP_OK;
124     }
125     return ESP_ERR_NOT_FOUND;
126 #else
127     memcpy(public_key_digests->key_digests[0], (uint8_t *)EFUSE_BLK2_RDATA0_REG, ESP_SECURE_BOOT_DIGEST_LEN);
128     public_key_digests->num_digests = 1;
129     return ESP_OK;
130 #endif // SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS
131 #endif // CONFIG_SECURE_BOOT_V2_ENABLED
132 }
133 
esp_secure_boot_verify_signature(uint32_t src_addr,uint32_t length)134 esp_err_t esp_secure_boot_verify_signature(uint32_t src_addr, uint32_t length)
135 {
136     uint8_t digest[ESP_SECURE_BOOT_DIGEST_LEN] = {0};
137     uint8_t verified_digest[ESP_SECURE_BOOT_DIGEST_LEN] = {0};
138 
139     /* Rounding off length to the upper 4k boundary */
140     uint32_t padded_length = ALIGN_UP(length, FLASH_SECTOR_SIZE);
141     ESP_LOGD(TAG, "verifying signature src_addr 0x%x length 0x%x", src_addr, length);
142 
143     esp_err_t err = bootloader_sha256_flash_contents(src_addr, padded_length, digest);
144     if (err != ESP_OK) {
145         ESP_LOGE(TAG, "Digest calculation failed 0x%x, 0x%x", src_addr, padded_length);
146         return err;
147     }
148 
149     const ets_secure_boot_signature_t *sig_block = bootloader_mmap(src_addr + padded_length, sizeof(ets_secure_boot_signature_t));
150     if (sig_block == NULL) {
151         ESP_LOGE(TAG, "Failed to mmap data at offset 0x%x", src_addr + padded_length);
152         return ESP_FAIL;
153     }
154 
155     err = esp_secure_boot_verify_rsa_signature_block(sig_block, digest, verified_digest);
156     if (err != ESP_OK) {
157         ESP_LOGE(TAG, "Secure Boot V2 verification failed.");
158     }
159     bootloader_munmap(sig_block);
160     return err;
161 }
162 
163 // This verify function is called only from app, during ota update.
164 // This function is compiled in case when CONFIG_SECURE_BOOT_V2_ENABLED==y or CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT==y.
165 // if CONFIG_SECURE_BOOT_V2_ENABLED==y and key digests from eFuse are missing, then FAIL (eFuse blocks should be set).
esp_secure_boot_verify_rsa_signature_block(const ets_secure_boot_signature_t * sig_block,const uint8_t * image_digest,uint8_t * verified_digest)166 esp_err_t esp_secure_boot_verify_rsa_signature_block(const ets_secure_boot_signature_t *sig_block, const uint8_t *image_digest, uint8_t *verified_digest)
167 {
168     bool any_trusted_key = false;
169 
170     /* Note: in IDF verification we don't add any fault injection resistance, as we don't expect this to be called
171         during boot-time verification. */
172     memset(verified_digest, 0, ESP_SECURE_BOOT_DIGEST_LEN);
173 
174     esp_image_sig_public_key_digests_t trusted = {0};
175 
176     if (get_secure_boot_key_digests(&trusted) != ESP_OK) {
177         ESP_LOGE(TAG, "Could not read secure boot digests!");
178         return ESP_FAIL;
179     }
180 
181 
182     int ret = 0;
183     mbedtls_rsa_context pk;
184     mbedtls_entropy_context entropy;
185     mbedtls_ctr_drbg_context ctr_drbg;
186     const unsigned rsa_key_size = sizeof(sig_block->block[0].signature);
187     unsigned char *sig_be = calloc(1, rsa_key_size);
188     unsigned char *buf = calloc(1, rsa_key_size);
189     if (sig_be == NULL || buf == NULL) {
190         return ESP_ERR_NO_MEM;
191     }
192 
193     mbedtls_entropy_init(&entropy);
194     mbedtls_ctr_drbg_init(&ctr_drbg);
195     ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
196     if (ret != 0) {
197         ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned -0x%04x\n", ret);
198         goto exit_outer;
199     }
200 
201 #ifdef CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
202     const unsigned secure_boot_num_blocks = 1;
203 #else
204     const unsigned secure_boot_num_blocks = SECURE_BOOT_NUM_BLOCKS;
205 #endif
206 
207     for (unsigned app_blk_idx = 0; app_blk_idx < secure_boot_num_blocks; app_blk_idx++) {
208         uint8_t app_blk_digest[ESP_SECURE_BOOT_DIGEST_LEN] = { 0 };
209         const ets_secure_boot_sig_block_t *app_blk = &sig_block->block[app_blk_idx];
210         const ets_secure_boot_sig_block_t *trusted_block = NULL;
211 
212         if (validate_signature_block(app_blk) != ESP_OK) {
213             continue; // Skip invalid signature blocks
214         }
215 
216         /* Generate the SHA of the public key components in the signature block */
217         bootloader_sha256_handle_t sig_block_sha = bootloader_sha256_start();
218         bootloader_sha256_data(sig_block_sha, &app_blk->key, sizeof(app_blk->key));
219         bootloader_sha256_finish(sig_block_sha, app_blk_digest);
220 
221         /* Check if the key is one we trust */
222         for (unsigned trusted_key_idx = 0; trusted_key_idx < secure_boot_num_blocks; trusted_key_idx++) {
223             if (memcmp(app_blk_digest, trusted.key_digests[trusted_key_idx], ESP_SECURE_BOOT_DIGEST_LEN) == 0) {
224                 ESP_LOGI(TAG, "#%d app key digest == #%d trusted key digest", app_blk_idx, trusted_key_idx);
225                 trusted_block = app_blk;
226                 any_trusted_key = true;
227                 break;
228             }
229             ESP_LOGV(TAG, "not trusting app sig %d trust idx %d", app_blk_idx, trusted_key_idx);
230         }
231 
232         if (trusted_block == NULL) {
233             continue; // Skip the signature blocks with no trusted digest
234         }
235 
236         ESP_LOGI(TAG, "Verifying with RSA-PSS...");
237 
238         const mbedtls_mpi N = { .s = 1,
239                                 .n = sizeof(trusted_block->key.n)/sizeof(mbedtls_mpi_uint),
240                                 .p = (void *)trusted_block->key.n,
241         };
242         const mbedtls_mpi e = { .s = 1,
243                                 .n = sizeof(trusted_block->key.e)/sizeof(mbedtls_mpi_uint), // 1
244                                 .p = (void *)&trusted_block->key.e,
245         };
246         mbedtls_rsa_init(&pk, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256);
247         ret = mbedtls_rsa_import(&pk, &N, NULL, NULL, NULL, &e);
248         if (ret != 0) {
249             ESP_LOGE(TAG, "Failed mbedtls_rsa_import, err: %d", ret);
250             goto exit_inner;
251         }
252 
253         ret = mbedtls_rsa_complete(&pk);
254         if (ret != 0) {
255             ESP_LOGE(TAG, "Failed mbedtls_rsa_complete, err: %d", ret);
256             goto exit_inner;
257         }
258 
259         ret = mbedtls_rsa_check_pubkey(&pk);
260         if (ret != 0) {
261             ESP_LOGI(TAG, "Key is not an RSA key -%0x", -ret);
262             goto exit_inner;
263         }
264 
265         /* Signature needs to be byte swapped into BE representation */
266         for (int j = 0; j < rsa_key_size; j++) {
267             sig_be[rsa_key_size - j - 1] = trusted_block->signature[j];
268         }
269 
270         ret = mbedtls_rsa_public( &pk, sig_be, buf);
271         if (ret != 0) {
272             ESP_LOGE(TAG, "mbedtls_rsa_public failed, err: %d", ret);
273             goto exit_inner;
274         }
275 
276         ret = mbedtls_rsa_rsassa_pss_verify( &pk, mbedtls_ctr_drbg_random, &ctr_drbg, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA256, ESP_SECURE_BOOT_DIGEST_LEN,
277                                             image_digest, sig_be);
278         if (ret != 0) {
279             ESP_LOGE(TAG, "Failed mbedtls_rsa_rsassa_pss_verify, err: %d", ret);
280         } else {
281             ESP_LOGI(TAG, "Signature verified successfully!");
282         }
283 exit_inner:
284         mbedtls_rsa_free(&pk);
285         if (ret == 0) {
286             break;
287         }
288     }
289 
290  exit_outer:
291     free(sig_be);
292     free(buf);
293     return (ret != 0 || any_trusted_key == false) ? ESP_ERR_IMAGE_INVALID: ESP_OK;
294 }
295 #endif // CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME || CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
296