1 /*
2 * SPDX-License-Identifier: Apache-2.0
3 *
4 * Copyright (c) 2019 JUUL Labs
5 * Copyright (c) 2021-2023 Arm Limited
6 */
7
8 #include <string.h>
9
10 #include "mcuboot_config/mcuboot_config.h"
11
12 #ifdef MCUBOOT_SIGN_ED25519
13 #include "bootutil/sign_key.h"
14
15 #include "mbedtls/oid.h"
16 #include "mbedtls/asn1.h"
17
18 #include "bootutil_priv.h"
19 #include "bootutil/crypto/common.h"
20 #include "bootutil/crypto/sha.h"
21
22 static const uint8_t ed25519_pubkey_oid[] = MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x65\x70";
23 #define NUM_ED25519_BYTES 32
24
25 extern int ED25519_verify(const uint8_t *message, size_t message_len,
26 const uint8_t signature[64],
27 const uint8_t public_key[32]);
28
29 /*
30 * Parse the public key used for signing.
31 */
32 static int
bootutil_import_key(uint8_t ** cp,uint8_t * end)33 bootutil_import_key(uint8_t **cp, uint8_t *end)
34 {
35 size_t len;
36 mbedtls_asn1_buf alg;
37 mbedtls_asn1_buf param;
38
39 if (mbedtls_asn1_get_tag(cp, end, &len,
40 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
41 return -1;
42 }
43 end = *cp + len;
44
45 if (mbedtls_asn1_get_alg(cp, end, &alg, ¶m)) {
46 return -2;
47 }
48
49 if (alg.ASN1_CONTEXT_MEMBER(len) != sizeof(ed25519_pubkey_oid) - 1 ||
50 memcmp(alg.ASN1_CONTEXT_MEMBER(p), ed25519_pubkey_oid, sizeof(ed25519_pubkey_oid) - 1)) {
51 return -3;
52 }
53
54 if (mbedtls_asn1_get_bitstring_null(cp, end, &len)) {
55 return -4;
56 }
57 if (*cp + len != end) {
58 return -5;
59 }
60
61 if (len != NUM_ED25519_BYTES) {
62 return -6;
63 }
64
65 return 0;
66 }
67
68 fih_ret
bootutil_verify_sig(uint8_t * hash,uint32_t hlen,uint8_t * sig,size_t slen,uint8_t key_id)69 bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, size_t slen,
70 uint8_t key_id)
71 {
72 int rc;
73 FIH_DECLARE(fih_rc, FIH_FAILURE);
74 uint8_t *pubkey;
75 uint8_t *end;
76
77 if (hlen != IMAGE_HASH_SIZE || slen != 64) {
78 FIH_SET(fih_rc, FIH_FAILURE);
79 goto out;
80 }
81
82 pubkey = (uint8_t *)bootutil_keys[key_id].key;
83 end = pubkey + *bootutil_keys[key_id].len;
84
85 rc = bootutil_import_key(&pubkey, end);
86 if (rc) {
87 FIH_SET(fih_rc, FIH_FAILURE);
88 goto out;
89 }
90
91 rc = ED25519_verify(hash, IMAGE_HASH_SIZE, sig, pubkey);
92
93 if (rc == 0) {
94 /* if verify returns 0, there was an error. */
95 FIH_SET(fih_rc, FIH_FAILURE);
96 goto out;
97 }
98
99 FIH_SET(fih_rc, FIH_SUCCESS);
100 out:
101
102 FIH_RET(fih_rc);
103 }
104
105 #endif /* MCUBOOT_SIGN_ED25519 */
106