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