blob: ebcf00eef4c49cb9917c291a284e9c981d032b1e [file] [log] [blame]
Fabio Utzig48764842019-05-10 19:28:24 -03001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#include <string.h>
21
22#include "mcuboot_config/mcuboot_config.h"
23
24#ifdef MCUBOOT_SIGN_ED25519
25#include "bootutil/sign_key.h"
26
27#include "mbedtls/oid.h"
28#include "mbedtls/asn1.h"
29
30#include "bootutil_priv.h"
31
32static const uint8_t ed25519_pubkey_oid[] = MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x65\x70";
33#define NUM_ED25519_BYTES 32
34
35extern int ED25519_verify(const uint8_t *message, size_t message_len,
36 const uint8_t signature[64],
37 const uint8_t public_key[32]);
38
39/*
40 * Parse the public key used for signing.
41 */
42static int
43bootutil_import_key(uint8_t **cp, uint8_t *end)
44{
45 size_t len;
46 mbedtls_asn1_buf alg;
47 mbedtls_asn1_buf param;
48
49 if (mbedtls_asn1_get_tag(cp, end, &len,
50 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
51 return -1;
52 }
53 end = *cp + len;
54
55 if (mbedtls_asn1_get_alg(cp, end, &alg, &param)) {
56 return -2;
57 }
58
59 if (alg.len != sizeof(ed25519_pubkey_oid) - 1 ||
60 memcmp(alg.p, ed25519_pubkey_oid, sizeof(ed25519_pubkey_oid) - 1)) {
61 return -3;
62 }
63
64 if (mbedtls_asn1_get_bitstring_null(cp, end, &len)) {
65 return -4;
66 }
67 if (*cp + len != end) {
68 return -5;
69 }
70
71 if (len != NUM_ED25519_BYTES) {
72 return -6;
73 }
74
75 return 0;
76}
77
78int
79bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, size_t slen,
80 uint8_t key_id)
81{
82 int rc;
83 uint8_t *pubkey;
84 uint8_t *end;
85
86 if (hlen != 32 || slen != 64) {
87 return -1;
88 }
89
90 pubkey = (uint8_t *)bootutil_keys[key_id].key;
91 end = pubkey + *bootutil_keys[key_id].len;
92
93 rc = bootutil_import_key(&pubkey, end);
94 if (rc) {
95 return -1;
96 }
97
98 rc = ED25519_verify(hash, 32, sig, pubkey);
99 if (rc == 0) {
100 return -2;
101 }
102
103 return 0;
104}
105
106#endif /* MCUBOOT_SIGN_ED25519 */