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, 1)) {
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             int slot = flash_area_id_to_multi_image_slot(image_index,
152                             flash_area_get_id(fap));
153 
154             if (off >= hdr_size && off < tlv_off) {
155                 blk_off = (off - hdr_size) & 0xf;
156                 boot_enc_decrypt(enc_state, slot, off - hdr_size,
157                                  blk_sz, blk_off, tmp_buf);
158             }
159         }
160 #endif
161         bootutil_sha_update(&sha_ctx, tmp_buf, blk_sz);
162     }
163 #endif /* MCUBOOT_RAM_LOAD */
164     bootutil_sha_finish(&sha_ctx, hash_result);
165     bootutil_sha_drop(&sha_ctx);
166 
167     return 0;
168 }
169 
170 /*
171  * Currently, we only support being able to verify one type of
172  * signature, because there is a single verification function that we
173  * call.  List the type of TLV we are expecting.  If we aren't
174  * configured for any signature, don't define this macro.
175  */
176 #if (defined(MCUBOOT_SIGN_RSA)      + \
177      defined(MCUBOOT_SIGN_EC256)    + \
178      defined(MCUBOOT_SIGN_EC384)    + \
179      defined(MCUBOOT_SIGN_ED25519)) > 1
180 #error "Only a single signature type is supported!"
181 #endif
182 
183 #if defined(MCUBOOT_SIGN_RSA)
184 #    if MCUBOOT_SIGN_RSA_LEN == 2048
185 #        define EXPECTED_SIG_TLV IMAGE_TLV_RSA2048_PSS
186 #    elif MCUBOOT_SIGN_RSA_LEN == 3072
187 #        define EXPECTED_SIG_TLV IMAGE_TLV_RSA3072_PSS
188 #    else
189 #        error "Unsupported RSA signature length"
190 #    endif
191 #    define SIG_BUF_SIZE (MCUBOOT_SIGN_RSA_LEN / 8)
192 #    define EXPECTED_SIG_LEN(x) ((x) == SIG_BUF_SIZE) /* 2048 bits */
193 #elif defined(MCUBOOT_SIGN_EC256) || \
194       defined(MCUBOOT_SIGN_EC384) || \
195       defined(MCUBOOT_SIGN_EC)
196 #    define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA_SIG
197 #    define SIG_BUF_SIZE 128
198 #    define EXPECTED_SIG_LEN(x) (1) /* always true, ASN.1 will validate */
199 #elif defined(MCUBOOT_SIGN_ED25519)
200 #    define EXPECTED_SIG_TLV IMAGE_TLV_ED25519
201 #    define SIG_BUF_SIZE 64
202 #    define EXPECTED_SIG_LEN(x) ((x) == SIG_BUF_SIZE)
203 #else
204 #    define SIG_BUF_SIZE 32 /* no signing, sha256 digest only */
205 #endif
206 
207 #if (defined(MCUBOOT_HW_KEY)       + \
208      defined(MCUBOOT_BUILTIN_KEY)) > 1
209 #error "Please use either MCUBOOT_HW_KEY or the MCUBOOT_BUILTIN_KEY feature."
210 #endif
211 
212 #ifdef EXPECTED_SIG_TLV
213 
214 #if !defined(MCUBOOT_BUILTIN_KEY)
215 #if !defined(MCUBOOT_HW_KEY)
216 /* The key TLV contains the hash of the public key. */
217 #   define EXPECTED_KEY_TLV     IMAGE_TLV_KEYHASH
218 #   define KEY_BUF_SIZE         IMAGE_HASH_SIZE
219 #else
220 /* The key TLV contains the whole public key.
221  * Add a few extra bytes to the key buffer size for encoding and
222  * for public exponent.
223  */
224 #   define EXPECTED_KEY_TLV     IMAGE_TLV_PUBKEY
225 #   define KEY_BUF_SIZE         (SIG_BUF_SIZE + 24)
226 #endif /* !MCUBOOT_HW_KEY */
227 
228 #if !defined(MCUBOOT_HW_KEY)
229 static int
bootutil_find_key(uint8_t * keyhash,uint8_t keyhash_len)230 bootutil_find_key(uint8_t *keyhash, uint8_t keyhash_len)
231 {
232     bootutil_sha_context sha_ctx;
233     int i;
234     const struct bootutil_key *key;
235     uint8_t hash[IMAGE_HASH_SIZE];
236 
237     if (keyhash_len > IMAGE_HASH_SIZE) {
238         return -1;
239     }
240 
241     for (i = 0; i < bootutil_key_cnt; i++) {
242         key = &bootutil_keys[i];
243         bootutil_sha_init(&sha_ctx);
244         bootutil_sha_update(&sha_ctx, key->key, *key->len);
245         bootutil_sha_finish(&sha_ctx, hash);
246         if (!memcmp(hash, keyhash, keyhash_len)) {
247             bootutil_sha_drop(&sha_ctx);
248             return i;
249         }
250     }
251     bootutil_sha_drop(&sha_ctx);
252     return -1;
253 }
254 #else /* !MCUBOOT_HW_KEY */
255 extern unsigned int pub_key_len;
256 static int
bootutil_find_key(uint8_t image_index,uint8_t * key,uint16_t key_len)257 bootutil_find_key(uint8_t image_index, uint8_t *key, uint16_t key_len)
258 {
259     bootutil_sha_context sha_ctx;
260     uint8_t hash[IMAGE_HASH_SIZE];
261     uint8_t key_hash[IMAGE_HASH_SIZE];
262     size_t key_hash_size = sizeof(key_hash);
263     int rc;
264     FIH_DECLARE(fih_rc, FIH_FAILURE);
265 
266     bootutil_sha_init(&sha_ctx);
267     bootutil_sha_update(&sha_ctx, key, key_len);
268     bootutil_sha_finish(&sha_ctx, hash);
269     bootutil_sha_drop(&sha_ctx);
270 
271     rc = boot_retrieve_public_key_hash(image_index, key_hash, &key_hash_size);
272     if (rc) {
273         return -1;
274     }
275 
276     /* Adding hardening to avoid this potential attack:
277      *  - Image is signed with an arbitrary key and the corresponding public
278      *    key is added as a TLV field.
279      * - During public key validation (comparing against key-hash read from
280      *   HW) a fault is injected to accept the public key as valid one.
281      */
282     FIH_CALL(boot_fih_memequal, fih_rc, hash, key_hash, key_hash_size);
283     if (FIH_EQ(fih_rc, FIH_SUCCESS)) {
284         bootutil_keys[0].key = key;
285         pub_key_len = key_len;
286         return 0;
287     }
288 
289     return -1;
290 }
291 #endif /* !MCUBOOT_HW_KEY */
292 #endif /* !MCUBOOT_BUILTIN_KEY */
293 #endif /* EXPECTED_SIG_TLV */
294 
295 /**
296  * Reads the value of an image's security counter.
297  *
298  * @param hdr           Pointer to the image header structure.
299  * @param fap           Pointer to a description structure of the image's
300  *                      flash area.
301  * @param security_cnt  Pointer to store the security counter value.
302  *
303  * @return              0 on success; nonzero on failure.
304  */
305 int32_t
bootutil_get_img_security_cnt(struct image_header * hdr,const struct flash_area * fap,uint32_t * img_security_cnt)306 bootutil_get_img_security_cnt(struct image_header *hdr,
307                               const struct flash_area *fap,
308                               uint32_t *img_security_cnt)
309 {
310     struct image_tlv_iter it;
311     uint32_t off;
312     uint16_t len;
313     int32_t rc;
314 
315     if ((hdr == NULL) ||
316         (fap == NULL) ||
317         (img_security_cnt == NULL)) {
318         /* Invalid parameter. */
319         return BOOT_EBADARGS;
320     }
321 
322     /* The security counter TLV is in the protected part of the TLV area. */
323     if (hdr->ih_protect_tlv_size == 0) {
324         return BOOT_EBADIMAGE;
325     }
326 
327     rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_SEC_CNT, true);
328     if (rc) {
329         return rc;
330     }
331 
332     /* Traverse through the protected TLV area to find
333      * the security counter TLV.
334      */
335 
336     rc = bootutil_tlv_iter_next(&it, &off, &len, NULL);
337     if (rc != 0) {
338         /* Security counter TLV has not been found. */
339         return -1;
340     }
341 
342     if (len != sizeof(*img_security_cnt)) {
343         /* Security counter is not valid. */
344         return BOOT_EBADIMAGE;
345     }
346 
347     rc = LOAD_IMAGE_DATA(hdr, fap, off, img_security_cnt, len);
348     if (rc != 0) {
349         return BOOT_EFLASH;
350     }
351 
352     return 0;
353 }
354 
355 #ifndef ALLOW_ROGUE_TLVS
356 /*
357  * The following list of TLVs are the only entries allowed in the unprotected
358  * TLV section.  All other TLV entries must be in the protected section.
359  */
360 static const uint16_t allowed_unprot_tlvs[] = {
361      IMAGE_TLV_KEYHASH,
362      IMAGE_TLV_PUBKEY,
363      IMAGE_TLV_SHA256,
364      IMAGE_TLV_SHA384,
365      IMAGE_TLV_SHA512,
366      IMAGE_TLV_RSA2048_PSS,
367      IMAGE_TLV_ECDSA224,
368      IMAGE_TLV_ECDSA_SIG,
369      IMAGE_TLV_RSA3072_PSS,
370      IMAGE_TLV_ED25519,
371      IMAGE_TLV_ENC_RSA2048,
372      IMAGE_TLV_ENC_KW,
373      IMAGE_TLV_ENC_EC256,
374      IMAGE_TLV_ENC_X25519,
375      /* Mark end with ANY. */
376      IMAGE_TLV_ANY,
377 };
378 #endif
379 
380 /*
381  * Verify the integrity of the image.
382  * Return non-zero if image could not be validated/does not validate.
383  */
384 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)385 bootutil_img_validate(struct enc_key_data *enc_state, int image_index,
386                       struct image_header *hdr, const struct flash_area *fap,
387                       uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *seed,
388                       int seed_len, uint8_t *out_hash)
389 {
390     uint32_t off;
391     uint16_t len;
392     uint16_t type;
393     int image_hash_valid = 0;
394 #ifdef EXPECTED_SIG_TLV
395     FIH_DECLARE(valid_signature, FIH_FAILURE);
396 #ifndef MCUBOOT_BUILTIN_KEY
397     int key_id = -1;
398 #else
399     /* Pass a key ID equal to the image index, the underlying crypto library
400      * is responsible for mapping the image index to a builtin key ID.
401      */
402     int key_id = image_index;
403 #endif /* !MCUBOOT_BUILTIN_KEY */
404 #ifdef MCUBOOT_HW_KEY
405     uint8_t key_buf[KEY_BUF_SIZE];
406 #endif
407 #endif /* EXPECTED_SIG_TLV */
408     struct image_tlv_iter it;
409     uint8_t buf[SIG_BUF_SIZE];
410     uint8_t hash[IMAGE_HASH_SIZE];
411     int rc = 0;
412     FIH_DECLARE(fih_rc, FIH_FAILURE);
413 #ifdef MCUBOOT_HW_ROLLBACK_PROT
414     fih_int security_cnt = fih_int_encode(INT_MAX);
415     uint32_t img_security_cnt = 0;
416     FIH_DECLARE(security_counter_valid, FIH_FAILURE);
417 #endif
418 
419     rc = bootutil_img_hash(enc_state, image_index, hdr, fap, tmp_buf,
420             tmp_buf_sz, hash, seed, seed_len);
421     if (rc) {
422         goto out;
423     }
424 
425     if (out_hash) {
426         memcpy(out_hash, hash, IMAGE_HASH_SIZE);
427     }
428 
429     rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
430     if (rc) {
431         goto out;
432     }
433 
434     if (it.tlv_end > bootutil_max_image_size(fap)) {
435         rc = -1;
436         goto out;
437     }
438 
439     /*
440      * Traverse through all of the TLVs, performing any checks we know
441      * and are able to do.
442      */
443     while (true) {
444         rc = bootutil_tlv_iter_next(&it, &off, &len, &type);
445         if (rc < 0) {
446             goto out;
447         } else if (rc > 0) {
448             break;
449         }
450 
451 #ifndef ALLOW_ROGUE_TLVS
452         /*
453          * Ensure that the non-protected TLV only has entries necessary to hold
454          * the signature.  We also allow encryption related keys to be in the
455          * unprotected area.
456          */
457         if (!bootutil_tlv_iter_is_prot(&it, off)) {
458              bool found = false;
459              for (const uint16_t *p = allowed_unprot_tlvs; *p != IMAGE_TLV_ANY; p++) {
460                   if (type == *p) {
461                        found = true;
462                        break;
463                   }
464              }
465              if (!found) {
466                   FIH_SET(fih_rc, FIH_FAILURE);
467                   goto out;
468              }
469         }
470 #endif
471 
472         if (type == EXPECTED_HASH_TLV) {
473             /* Verify the image hash. This must always be present. */
474             if (len != sizeof(hash)) {
475                 rc = -1;
476                 goto out;
477             }
478             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, sizeof(hash));
479             if (rc) {
480                 goto out;
481             }
482 
483             FIH_CALL(boot_fih_memequal, fih_rc, hash, buf, sizeof(hash));
484             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
485                 FIH_SET(fih_rc, FIH_FAILURE);
486                 goto out;
487             }
488 
489             image_hash_valid = 1;
490 #ifdef EXPECTED_KEY_TLV
491         } else if (type == EXPECTED_KEY_TLV) {
492             /*
493              * Determine which key we should be checking.
494              */
495             if (len > KEY_BUF_SIZE) {
496                 rc = -1;
497                 goto out;
498             }
499 #ifndef MCUBOOT_HW_KEY
500             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, len);
501             if (rc) {
502                 goto out;
503             }
504             key_id = bootutil_find_key(buf, len);
505 #else
506             rc = LOAD_IMAGE_DATA(hdr, fap, off, key_buf, len);
507             if (rc) {
508                 goto out;
509             }
510             key_id = bootutil_find_key(image_index, key_buf, len);
511 #endif /* !MCUBOOT_HW_KEY */
512             /*
513              * The key may not be found, which is acceptable.  There
514              * can be multiple signatures, each preceded by a key.
515              */
516 #endif /* EXPECTED_KEY_TLV */
517 #ifdef EXPECTED_SIG_TLV
518         } else if (type == EXPECTED_SIG_TLV) {
519             /* Ignore this signature if it is out of bounds. */
520             if (key_id < 0 || key_id >= bootutil_key_cnt) {
521                 key_id = -1;
522                 continue;
523             }
524             if (!EXPECTED_SIG_LEN(len) || len > sizeof(buf)) {
525                 rc = -1;
526                 goto out;
527             }
528             rc = LOAD_IMAGE_DATA(hdr, fap, off, buf, len);
529             if (rc) {
530                 goto out;
531             }
532             FIH_CALL(bootutil_verify_sig, valid_signature, hash, sizeof(hash),
533                                                            buf, len, key_id);
534             key_id = -1;
535 #endif /* EXPECTED_SIG_TLV */
536 #ifdef MCUBOOT_HW_ROLLBACK_PROT
537         } else if (type == IMAGE_TLV_SEC_CNT) {
538             /*
539              * Verify the image's security counter.
540              * This must always be present.
541              */
542             if (len != sizeof(img_security_cnt)) {
543                 /* Security counter is not valid. */
544                 rc = -1;
545                 goto out;
546             }
547 
548             rc = LOAD_IMAGE_DATA(hdr, fap, off, &img_security_cnt, len);
549             if (rc) {
550                 goto out;
551             }
552 
553             FIH_CALL(boot_nv_security_counter_get, fih_rc, image_index,
554                                                            &security_cnt);
555             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
556                 FIH_SET(fih_rc, FIH_FAILURE);
557                 goto out;
558             }
559 
560             /* Compare the new image's security counter value against the
561              * stored security counter value.
562              */
563             fih_rc = fih_ret_encode_zero_equality(img_security_cnt <
564                                    (uint32_t)fih_int_decode(security_cnt));
565             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
566                 FIH_SET(fih_rc, FIH_FAILURE);
567                 goto out;
568             }
569 
570             /* The image's security counter has been successfully verified. */
571             security_counter_valid = fih_rc;
572 #endif /* MCUBOOT_HW_ROLLBACK_PROT */
573         }
574     }
575 
576     rc = !image_hash_valid;
577     if (rc) {
578         goto out;
579     }
580 #ifdef EXPECTED_SIG_TLV
581     FIH_SET(fih_rc, valid_signature);
582 #endif
583 #ifdef MCUBOOT_HW_ROLLBACK_PROT
584     if (FIH_NOT_EQ(security_counter_valid, FIH_SUCCESS)) {
585         rc = -1;
586         goto out;
587     }
588 #endif
589 
590 out:
591     if (rc) {
592         FIH_SET(fih_rc, FIH_FAILURE);
593     }
594 
595     FIH_RET(fih_rc);
596 }
597