Fabio Utzig | 4876484 | 2019-05-10 19:28:24 -0300 | [diff] [blame] | 1 | /* |
David Brown | aac7111 | 2020-02-03 16:13:42 -0700 | [diff] [blame] | 2 | * SPDX-License-Identifier: Apache-2.0 |
Fabio Utzig | 4876484 | 2019-05-10 19:28:24 -0300 | [diff] [blame] | 3 | * |
David Brown | aac7111 | 2020-02-03 16:13:42 -0700 | [diff] [blame] | 4 | * Copyright (c) 2019 JUUL Labs |
Fabio Utzig | 4876484 | 2019-05-10 19:28:24 -0300 | [diff] [blame] | 5 | */ |
| 6 | |
| 7 | #include <string.h> |
| 8 | |
| 9 | #include "mcuboot_config/mcuboot_config.h" |
| 10 | |
| 11 | #ifdef MCUBOOT_SIGN_ED25519 |
| 12 | #include "bootutil/sign_key.h" |
| 13 | |
| 14 | #include "mbedtls/oid.h" |
| 15 | #include "mbedtls/asn1.h" |
| 16 | |
| 17 | #include "bootutil_priv.h" |
| 18 | |
| 19 | static const uint8_t ed25519_pubkey_oid[] = MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x65\x70"; |
| 20 | #define NUM_ED25519_BYTES 32 |
| 21 | |
| 22 | extern int ED25519_verify(const uint8_t *message, size_t message_len, |
| 23 | const uint8_t signature[64], |
| 24 | const uint8_t public_key[32]); |
| 25 | |
| 26 | /* |
| 27 | * Parse the public key used for signing. |
| 28 | */ |
| 29 | static int |
| 30 | bootutil_import_key(uint8_t **cp, uint8_t *end) |
| 31 | { |
| 32 | size_t len; |
| 33 | mbedtls_asn1_buf alg; |
| 34 | mbedtls_asn1_buf param; |
| 35 | |
| 36 | if (mbedtls_asn1_get_tag(cp, end, &len, |
| 37 | MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) { |
| 38 | return -1; |
| 39 | } |
| 40 | end = *cp + len; |
| 41 | |
| 42 | if (mbedtls_asn1_get_alg(cp, end, &alg, ¶m)) { |
| 43 | return -2; |
| 44 | } |
| 45 | |
| 46 | if (alg.len != sizeof(ed25519_pubkey_oid) - 1 || |
| 47 | memcmp(alg.p, ed25519_pubkey_oid, sizeof(ed25519_pubkey_oid) - 1)) { |
| 48 | return -3; |
| 49 | } |
| 50 | |
| 51 | if (mbedtls_asn1_get_bitstring_null(cp, end, &len)) { |
| 52 | return -4; |
| 53 | } |
| 54 | if (*cp + len != end) { |
| 55 | return -5; |
| 56 | } |
| 57 | |
| 58 | if (len != NUM_ED25519_BYTES) { |
| 59 | return -6; |
| 60 | } |
| 61 | |
| 62 | return 0; |
| 63 | } |
| 64 | |
| 65 | int |
| 66 | bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, size_t slen, |
| 67 | uint8_t key_id) |
| 68 | { |
| 69 | int rc; |
| 70 | uint8_t *pubkey; |
| 71 | uint8_t *end; |
| 72 | |
| 73 | if (hlen != 32 || slen != 64) { |
| 74 | return -1; |
| 75 | } |
| 76 | |
| 77 | pubkey = (uint8_t *)bootutil_keys[key_id].key; |
| 78 | end = pubkey + *bootutil_keys[key_id].len; |
| 79 | |
| 80 | rc = bootutil_import_key(&pubkey, end); |
| 81 | if (rc) { |
| 82 | return -1; |
| 83 | } |
| 84 | |
| 85 | rc = ED25519_verify(hash, 32, sig, pubkey); |
| 86 | if (rc == 0) { |
| 87 | return -2; |
| 88 | } |
| 89 | |
| 90 | return 0; |
| 91 | } |
| 92 | |
| 93 | #endif /* MCUBOOT_SIGN_ED25519 */ |