1 /*
2  * SPDX-License-Identifier: Apache-2.0
3  *
4  * Copyright (c) 2017-2019 Linaro LTD
5  * Copyright (c) 2016-2019 JUUL Labs
6  * Copyright (c) 2019-2024 Arm Limited
7  *
8  * Original license:
9  *
10  * Licensed to the Apache Software Foundation (ASF) under one
11  * or more contributor license agreements.  See the NOTICE file
12  * distributed with this work for additional information
13  * regarding copyright ownership.  The ASF licenses this file
14  * to you under the Apache License, Version 2.0 (the
15  * "License"); you may not use this file except in compliance
16  * with the License.  You may obtain a copy of the License at
17  *
18  *  http://www.apache.org/licenses/LICENSE-2.0
19  *
20  * Unless required by applicable law or agreed to in writing,
21  * software distributed under the License is distributed on an
22  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
23  * KIND, either express or implied.  See the License for the
24  * specific language governing permissions and limitations
25  * under the License.
26  */
27 
28 #include <stddef.h>
29 #include <stdint.h>
30 #include <inttypes.h>
31 #include <string.h>
32 
33 #include <flash_map_backend/flash_map_backend.h>
34 
35 #include "bootutil/image.h"
36 #include "bootutil/crypto/sha.h"
37 #include "bootutil/sign_key.h"
38 #include "bootutil/security_cnt.h"
39 #include "bootutil/fault_injection_hardening.h"
40 
41 #include "mcuboot_config/mcuboot_config.h"
42 
43 #ifdef MCUBOOT_ENC_IMAGES
44 #include "bootutil/enc_key.h"
45 #endif
46 #if defined(MCUBOOT_SIGN_RSA)
47 #include "mbedtls/rsa.h"
48 #endif
49 #if defined(MCUBOOT_SIGN_EC256)
50 #include "mbedtls/ecdsa.h"
51 #endif
52 #if defined(MCUBOOT_ENC_IMAGES) || defined(MCUBOOT_SIGN_RSA) || \
53     defined(MCUBOOT_SIGN_EC256)
54 #include "mbedtls/asn1.h"
55 #endif
56 
57 #include "bootutil_priv.h"
58 
59 /*
60  * Compute SHA hash over the image.
61  * (SHA384 if ECDSA-P384 is being used,
62  *  SHA256 otherwise).
63  */
64 static int
bootutil_img_hash(struct enc_key_data * enc_state,int image_index,struct image_header * hdr,const struct flash_area * fap,uint8_t * tmp_buf,uint32_t tmp_buf_sz,uint8_t * hash_result,uint8_t * seed,int seed_len)65 bootutil_img_hash(struct enc_key_data *enc_state, int image_index,
66                   struct image_header *hdr, const struct flash_area *fap,
67                   uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *hash_result,
68                   uint8_t *seed, int seed_len)
69 {
70     bootutil_sha_context sha_ctx;
71     uint32_t blk_sz;
72     uint32_t size;
73     uint16_t hdr_size;
74     uint32_t off;
75     int rc;
76     uint32_t blk_off;
77     uint32_t tlv_off;
78 
79 #if (BOOT_IMAGE_NUMBER == 1) || !defined(MCUBOOT_ENC_IMAGES) || \
80     defined(MCUBOOT_RAM_LOAD)
81     (void)enc_state;
82     (void)image_index;
83     (void)hdr_size;
84     (void)blk_off;
85     (void)tlv_off;
86 #ifdef MCUBOOT_RAM_LOAD
87     (void)blk_sz;
88     (void)off;
89     (void)rc;
90     (void)fap;
91     (void)tmp_buf;
92     (void)tmp_buf_sz;
93 #endif
94 #endif
95 
96 #ifdef MCUBOOT_ENC_IMAGES
97     /* Encrypted images only exist in the secondary slot */
98     if (MUST_DECRYPT(fap, image_index, hdr) &&
99             !boot_enc_valid(enc_state, image_index, fap)) {
100         return -1;
101     }
102 #endif
103 
104     bootutil_sha_init(&sha_ctx);
105 
106     /* in some cases (split image) the hash is seeded with data from
107      * the loader image */
108     if (seed && (seed_len > 0)) {
109         bootutil_sha_update(&sha_ctx, seed, seed_len);
110     }
111 
112     /* Hash is computed over image header and image itself. */
113     size = hdr_size = hdr->ih_hdr_size;
114     size += hdr->ih_img_size;
115     tlv_off = size;
116 
117     /* If protected TLVs are present they are also hashed. */
118     size += hdr->ih_protect_tlv_size;
119 
120 #ifdef MCUBOOT_RAM_LOAD
121     bootutil_sha_update(&sha_ctx,
122                         (void*)(IMAGE_RAM_BASE + hdr->ih_load_addr),
123                         size);
124 #else
125     for (off = 0; off < size; off += blk_sz) {
126         blk_sz = size - off;
127         if (blk_sz > tmp_buf_sz) {
128             blk_sz = tmp_buf_sz;
129         }
130 #ifdef MCUBOOT_ENC_IMAGES
131         /* The only data that is encrypted in an image is the payload;
132          * both header and TLVs (when protected) are not.
133          */
134         if ((off < hdr_size) && ((off + blk_sz) > hdr_size)) {
135             /* read only the header */
136             blk_sz = hdr_size - off;
137         }
138         if ((off < tlv_off) && ((off + blk_sz) > tlv_off)) {
139             /* read only up to the end of the image payload */
140             blk_sz = tlv_off - off;
141         }
142 #endif
143         rc = flash_area_read(fap, off, tmp_buf, blk_sz);
144         if (rc) {
145             bootutil_sha_drop(&sha_ctx);
146             return rc;
147         }
148 #ifdef MCUBOOT_ENC_IMAGES
149         if (MUST_DECRYPT(fap, image_index, hdr)) {
150             /* Only payload is encrypted (area between header and TLVs) */
151             if (off >= hdr_size && off < tlv_off) {
152                 blk_off = (off - hdr_size) & 0xf;
153                 boot_encrypt(enc_state, image_index, fap, off - hdr_size,
154                         blk_sz, blk_off, tmp_buf);
155             }
156         }
157 #endif
158         bootutil_sha_update(&sha_ctx, tmp_buf, blk_sz);
159     }
160 #endif /* MCUBOOT_RAM_LOAD */
161     bootutil_sha_finish(&sha_ctx, hash_result);
162     bootutil_sha_drop(&sha_ctx);
163 
164     return 0;
165 }
166 
167 /*
168  * Currently, we only support being able to verify one type of
169  * signature, because there is a single verification function that we
170  * call.  List the type of TLV we are expecting.  If we aren't
171  * configured for any signature, don't define this macro.
172  */
173 #if (defined(MCUBOOT_SIGN_RSA)      + \
174      defined(MCUBOOT_SIGN_EC256)    + \
175      defined(MCUBOOT_SIGN_EC384)    + \
176      defined(MCUBOOT_SIGN_ED25519)) > 1
177 #error "Only a single signature type is supported!"
178 #endif
179 
180 #if defined(MCUBOOT_SIGN_RSA)
181 #    if MCUBOOT_SIGN_RSA_LEN == 2048
182 #        define EXPECTED_SIG_TLV IMAGE_TLV_RSA2048_PSS
183 #    elif MCUBOOT_SIGN_RSA_LEN == 3072
184 #        define EXPECTED_SIG_TLV IMAGE_TLV_RSA3072_PSS
185 #    else
186 #        error "Unsupported RSA signature length"
187 #    endif
188 #    define SIG_BUF_SIZE (MCUBOOT_SIGN_RSA_LEN / 8)
189 #    define EXPECTED_SIG_LEN(x) ((x) == SIG_BUF_SIZE) /* 2048 bits */
190 #elif defined(MCUBOOT_SIGN_EC256) || \
191       defined(MCUBOOT_SIGN_EC384) || \
192       defined(MCUBOOT_SIGN_EC)
193 #    define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA_SIG
194 #    define SIG_BUF_SIZE 128
195 #    define EXPECTED_SIG_LEN(x) (1) /* always true, ASN.1 will validate */
196 #elif defined(MCUBOOT_SIGN_ED25519)
197 #    define EXPECTED_SIG_TLV IMAGE_TLV_ED25519
198 #    define SIG_BUF_SIZE 64
199 #    define EXPECTED_SIG_LEN(x) ((x) == SIG_BUF_SIZE)
200 #else
201 #    define SIG_BUF_SIZE 32 /* no signing, sha256 digest only */
202 #endif
203 
204 #if (defined(MCUBOOT_HW_KEY)       + \
205      defined(MCUBOOT_BUILTIN_KEY)) > 1
206 #error "Please use either MCUBOOT_HW_KEY or the MCUBOOT_BUILTIN_KEY feature."
207 #endif
208 
209 #ifdef EXPECTED_SIG_TLV
210 
211 #if !defined(MCUBOOT_BUILTIN_KEY)
212 #if !defined(MCUBOOT_HW_KEY)
213 /* The key TLV contains the hash of the public key. */
214 #   define EXPECTED_KEY_TLV     IMAGE_TLV_KEYHASH
215 #   define KEY_BUF_SIZE         IMAGE_HASH_SIZE
216 #else
217 /* The key TLV contains the whole public key.
218  * Add a few extra bytes to the key buffer size for encoding and
219  * for public exponent.
220  */
221 #   define EXPECTED_KEY_TLV     IMAGE_TLV_PUBKEY
222 #   define KEY_BUF_SIZE         (SIG_BUF_SIZE + 24)
223 #endif /* !MCUBOOT_HW_KEY */
224 
225 #if !defined(MCUBOOT_HW_KEY)
226 static int
bootutil_find_key(uint8_t * keyhash,uint8_t keyhash_len)227 bootutil_find_key(uint8_t *keyhash, uint8_t keyhash_len)
228 {
229     bootutil_sha_context sha_ctx;
230     int i;
231     const struct bootutil_key *key;
232     uint8_t hash[IMAGE_HASH_SIZE];
233 
234     if (keyhash_len > IMAGE_HASH_SIZE) {
235         return -1;
236     }
237 
238     for (i = 0; i < bootutil_key_cnt; i++) {
239         key = &bootutil_keys[i];
240         bootutil_sha_init(&sha_ctx);
241         bootutil_sha_update(&sha_ctx, key->key, *key->len);
242         bootutil_sha_finish(&sha_ctx, hash);
243         if (!memcmp(hash, keyhash, keyhash_len)) {
244             bootutil_sha_drop(&sha_ctx);
245             return i;
246         }
247     }
248     bootutil_sha_drop(&sha_ctx);
249     return -1;
250 }
251 #else /* !MCUBOOT_HW_KEY */
252 extern unsigned int pub_key_len;
253 static int
bootutil_find_key(uint8_t image_index,uint8_t * key,uint16_t key_len)254 bootutil_find_key(uint8_t image_index, uint8_t *key, uint16_t key_len)
255 {
256     bootutil_sha_context sha_ctx;
257     uint8_t hash[IMAGE_HASH_SIZE];
258     uint8_t key_hash[IMAGE_HASH_SIZE];
259     size_t key_hash_size = sizeof(key_hash);
260     int rc;
261     FIH_DECLARE(fih_rc, FIH_FAILURE);
262 
263     bootutil_sha_init(&sha_ctx);
264     bootutil_sha_update(&sha_ctx, key, key_len);
265     bootutil_sha_finish(&sha_ctx, hash);
266     bootutil_sha_drop(&sha_ctx);
267 
268     rc = boot_retrieve_public_key_hash(image_index, key_hash, &key_hash_size);
269     if (rc) {
270         return -1;
271     }
272 
273     /* Adding hardening to avoid this potential attack:
274      *  - Image is signed with an arbitrary key and the corresponding public
275      *    key is added as a TLV field.
276      * - During public key validation (comparing against key-hash read from
277      *   HW) a fault is injected to accept the public key as valid one.
278      */
279     FIH_CALL(boot_fih_memequal, fih_rc, hash, key_hash, key_hash_size);
280     if (FIH_EQ(fih_rc, FIH_SUCCESS)) {
281         bootutil_keys[0].key = key;
282         pub_key_len = key_len;
283         return 0;
284     }
285 
286     return -1;
287 }
288 #endif /* !MCUBOOT_HW_KEY */
289 #endif /* !MCUBOOT_BUILTIN_KEY */
290 #endif /* EXPECTED_SIG_TLV */
291 
292 /**
293  * Reads the value of an image's security counter.
294  *
295  * @param hdr           Pointer to the image header structure.
296  * @param fap           Pointer to a description structure of the image's
297  *                      flash area.
298  * @param security_cnt  Pointer to store the security counter value.
299  *
300  * @return              0 on success; nonzero on failure.
301  */
302 int32_t
bootutil_get_img_security_cnt(struct image_header * hdr,const struct flash_area * fap,uint32_t * img_security_cnt)303 bootutil_get_img_security_cnt(struct image_header *hdr,
304                               const struct flash_area *fap,
305                               uint32_t *img_security_cnt)
306 {
307     struct image_tlv_iter it;
308     uint32_t off;
309     uint16_t len;
310     int32_t rc;
311 
312     if ((hdr == NULL) ||
313         (fap == NULL) ||
314         (img_security_cnt == NULL)) {
315         /* Invalid parameter. */
316         return BOOT_EBADARGS;
317     }
318 
319     /* The security counter TLV is in the protected part of the TLV area. */
320     if (hdr->ih_protect_tlv_size == 0) {
321         return BOOT_EBADIMAGE;
322     }
323 
324     rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_SEC_CNT, true);
325     if (rc) {
326         return rc;
327     }
328 
329     /* Traverse through the protected TLV area to find
330      * the security counter TLV.
331      */
332 
333     rc = bootutil_tlv_iter_next(&it, &off, &len, NULL);
334     if (rc != 0) {
335         /* Security counter TLV has not been found. */
336         return -1;
337     }
338 
339     if (len != sizeof(*img_security_cnt)) {
340         /* Security counter is not valid. */
341         return BOOT_EBADIMAGE;
342     }
343 
344     rc = LOAD_IMAGE_DATA(hdr, fap, off, img_security_cnt, len);
345     if (rc != 0) {
346         return BOOT_EFLASH;
347     }
348 
349     return 0;
350 }
351 
352 #ifndef ALLOW_ROGUE_TLVS
353 /*
354  * The following list of TLVs are the only entries allowed in the unprotected
355  * TLV section.  All other TLV entries must be in the protected section.
356  */
357 static const uint16_t allowed_unprot_tlvs[] = {
358      IMAGE_TLV_KEYHASH,
359      IMAGE_TLV_PUBKEY,
360      IMAGE_TLV_SHA256,
361      IMAGE_TLV_SHA384,
362      IMAGE_TLV_RSA2048_PSS,
363      IMAGE_TLV_ECDSA224,
364      IMAGE_TLV_ECDSA_SIG,
365      IMAGE_TLV_RSA3072_PSS,
366      IMAGE_TLV_ED25519,
367      IMAGE_TLV_ENC_RSA2048,
368      IMAGE_TLV_ENC_KW,
369      IMAGE_TLV_ENC_EC256,
370      IMAGE_TLV_ENC_X25519,
371      /* Mark end with ANY. */
372      IMAGE_TLV_ANY,
373 };
374 #endif
375 
376 /*
377  * Verify the integrity of the image.
378  * Return non-zero if image could not be validated/does not validate.
379  */
380 fih_ret
bootutil_img_validate(struct enc_key_data * enc_state,int image_index,struct image_header * hdr,const struct flash_area * fap,uint8_t * tmp_buf,uint32_t tmp_buf_sz,uint8_t * seed,int seed_len,uint8_t * out_hash)381 bootutil_img_validate(struct enc_key_data *enc_state, int image_index,
382                       struct image_header *hdr, const struct flash_area *fap,
383                       uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *seed,
384                       int seed_len, uint8_t *out_hash)
385 {
386     uint32_t off;
387     uint16_t len;
388     uint16_t type;
389     int image_hash_valid = 0;
390 #ifdef EXPECTED_SIG_TLV
391     FIH_DECLARE(valid_signature, FIH_FAILURE);
392 #ifndef MCUBOOT_BUILTIN_KEY
393     int key_id = -1;
394 #else
395     /* Pass a key ID equal to the image index, the underlying crypto library
396      * is responsible for mapping the image index to a builtin key ID.
397      */
398     int key_id = image_index;
399 #endif /* !MCUBOOT_BUILTIN_KEY */
400 #ifdef MCUBOOT_HW_KEY
401     uint8_t key_buf[KEY_BUF_SIZE];
402 #endif
403 #endif /* EXPECTED_SIG_TLV */
404     struct image_tlv_iter it;
405     uint8_t buf[SIG_BUF_SIZE];
406     uint8_t hash[IMAGE_HASH_SIZE];
407     int rc = 0;
408     FIH_DECLARE(fih_rc, FIH_FAILURE);
409 #ifdef MCUBOOT_HW_ROLLBACK_PROT
410     fih_int security_cnt = fih_int_encode(INT_MAX);
411     uint32_t img_security_cnt = 0;
412     FIH_DECLARE(security_counter_valid, FIH_FAILURE);
413 #endif
414 
415     rc = bootutil_img_hash(enc_state, image_index, hdr, fap, tmp_buf,
416             tmp_buf_sz, hash, seed, seed_len);
417     if (rc) {
418         goto out;
419     }
420 
421     if (out_hash) {
422         memcpy(out_hash, hash, IMAGE_HASH_SIZE);
423     }
424 
425     rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
426     if (rc) {
427         goto out;
428     }
429 
430     if (it.tlv_end > bootutil_max_image_size(fap)) {
431         rc = -1;
432         goto out;
433     }
434 
435     /*
436      * Traverse through all of the TLVs, performing any checks we know
437      * and are able to do.
438      */
439     while (true) {
440         rc = bootutil_tlv_iter_next(&it, &off, &len, &type);
441         if (rc < 0) {
442             goto out;
443         } else if (rc > 0) {
444             break;
445         }
446 
447 #ifndef ALLOW_ROGUE_TLVS
448         /*
449          * Ensure that the non-protected TLV only has entries necessary to hold
450          * the signature.  We also allow encryption related keys to be in the
451          * unprotected area.
452          */
453         if (!bootutil_tlv_iter_is_prot(&it, off)) {
454              bool found = false;
455              for (const uint16_t *p = allowed_unprot_tlvs; *p != IMAGE_TLV_ANY; p++) {
456                   if (type == *p) {
457                        found = true;
458                        break;
459                   }
460              }
461              if (!found) {
462                   FIH_SET(fih_rc, FIH_FAILURE);
463                   goto out;
464              }
465         }
466 #endif
467 
468         if (type == EXPECTED_HASH_TLV) {
469             /* Verify the image hash. This must always be present. */
470             if (len != sizeof(hash)) {
471                 rc = -1;
472                 goto out;
473             }
474             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, sizeof(hash));
475             if (rc) {
476                 goto out;
477             }
478 
479             FIH_CALL(boot_fih_memequal, fih_rc, hash, buf, sizeof(hash));
480             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
481                 FIH_SET(fih_rc, FIH_FAILURE);
482                 goto out;
483             }
484 
485             image_hash_valid = 1;
486 #ifdef EXPECTED_KEY_TLV
487         } else if (type == EXPECTED_KEY_TLV) {
488             /*
489              * Determine which key we should be checking.
490              */
491             if (len > KEY_BUF_SIZE) {
492                 rc = -1;
493                 goto out;
494             }
495 #ifndef MCUBOOT_HW_KEY
496             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, len);
497             if (rc) {
498                 goto out;
499             }
500             key_id = bootutil_find_key(buf, len);
501 #else
502             rc = LOAD_IMAGE_DATA(hdr, fap, off, key_buf, len);
503             if (rc) {
504                 goto out;
505             }
506             key_id = bootutil_find_key(image_index, key_buf, len);
507 #endif /* !MCUBOOT_HW_KEY */
508             /*
509              * The key may not be found, which is acceptable.  There
510              * can be multiple signatures, each preceded by a key.
511              */
512 #endif /* EXPECTED_KEY_TLV */
513 #ifdef EXPECTED_SIG_TLV
514         } else if (type == EXPECTED_SIG_TLV) {
515             /* Ignore this signature if it is out of bounds. */
516             if (key_id < 0 || key_id >= bootutil_key_cnt) {
517                 key_id = -1;
518                 continue;
519             }
520             if (!EXPECTED_SIG_LEN(len) || len > sizeof(buf)) {
521                 rc = -1;
522                 goto out;
523             }
524             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, len);
525             if (rc) {
526                 goto out;
527             }
528             FIH_CALL(bootutil_verify_sig, valid_signature, hash, sizeof(hash),
529                                                            buf, len, key_id);
530             key_id = -1;
531 #endif /* EXPECTED_SIG_TLV */
532 #ifdef MCUBOOT_HW_ROLLBACK_PROT
533         } else if (type == IMAGE_TLV_SEC_CNT) {
534             /*
535              * Verify the image's security counter.
536              * This must always be present.
537              */
538             if (len != sizeof(img_security_cnt)) {
539                 /* Security counter is not valid. */
540                 rc = -1;
541                 goto out;
542             }
543 
544             rc = LOAD_IMAGE_DATA(hdr, fap, off, &img_security_cnt, len);
545             if (rc) {
546                 goto out;
547             }
548 
549             FIH_CALL(boot_nv_security_counter_get, fih_rc, image_index,
550                                                            &security_cnt);
551             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
552                 FIH_SET(fih_rc, FIH_FAILURE);
553                 goto out;
554             }
555 
556             /* Compare the new image's security counter value against the
557              * stored security counter value.
558              */
559             fih_rc = fih_ret_encode_zero_equality(img_security_cnt <
560                                    (uint32_t)fih_int_decode(security_cnt));
561             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
562                 FIH_SET(fih_rc, FIH_FAILURE);
563                 goto out;
564             }
565 
566             /* The image's security counter has been successfully verified. */
567             security_counter_valid = fih_rc;
568 #endif /* MCUBOOT_HW_ROLLBACK_PROT */
569         }
570     }
571 
572     rc = !image_hash_valid;
573     if (rc) {
574         goto out;
575     }
576 #ifdef EXPECTED_SIG_TLV
577     FIH_SET(fih_rc, valid_signature);
578 #endif
579 #ifdef MCUBOOT_HW_ROLLBACK_PROT
580     if (FIH_NOT_EQ(security_counter_valid, FIH_SUCCESS)) {
581         rc = -1;
582         goto out;
583     }
584 #endif
585 
586 out:
587     if (rc) {
588         FIH_SET(fih_rc, FIH_FAILURE);
589     }
590 
591     FIH_RET(fih_rc);
592 }
593