2 * Copyright (c) 2017-2018, Juniper Networks, Inc.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
14 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
15 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
16 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
17 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
29 * @file vets.c - trust store
30 * @brief verify signatures
32 * We leverage code from BearSSL www.bearssl.org
38 #include "libsecureboot-priv.h"
42 #ifndef TRUST_ANCHOR_STR
43 # define TRUST_ANCHOR_STR ta_PEM
46 #define SECONDS_PER_DAY 86400
47 #define X509_DAYS_TO_UTC0 719528
51 typedef VECTOR(br_x509_certificate) cert_list;
52 typedef VECTOR(hash_data) digest_list;
54 static anchor_list trust_anchors = VEC_INIT;
55 static anchor_list forbidden_anchors = VEC_INIT;
56 static digest_list forbidden_digests = VEC_INIT;
64 static char ebuf[512];
73 ve_error_set(const char *fmt, ...)
83 vsprintf(ebuf, fmt, ap); /* no vsnprintf in libstand */
84 ebuf[sizeof(ebuf) - 1] = '\0';
87 rc = vsnprintf(ebuf, sizeof(ebuf), fmt, ap);
94 /* this is the time we use for verifying certs */
95 static time_t ve_utc = 0;
99 * set ve_utc used for certificate verification
102 * time - ignored unless greater than current value.
105 ve_utc_set(time_t utc)
108 DEBUG_PRINTF(2, ("Set ve_utc=%jd\n", (intmax_t)utc));
114 free_cert_contents(br_x509_certificate *xc)
119 /* ASN parsing related defines */
120 #define ASN1_PRIMITIVE_TAG 0x1F
121 #define ASN1_INF_LENGTH 0x80
122 #define ASN1_LENGTH_MASK 0x7F
125 * Get TBS part of certificate.
126 * Since BearSSL doesn't provide any API to do this,
127 * it has to be implemented here.
130 X509_to_tbs(unsigned char* cert, size_t* output_size)
132 unsigned char *result;
139 /* Strip two sequences to get to the TBS section */
140 for (i = 0; i < 2; i++) {
142 * XXX: We don't need to support extended tags since
143 * they should not be present in certificates.
145 if ((*cert & ASN1_PRIMITIVE_TAG) == ASN1_PRIMITIVE_TAG)
150 if (*cert == ASN1_INF_LENGTH)
153 size = *cert & ASN1_LENGTH_MASK;
156 /* Size can either be stored on a single or multiple bytes */
157 if (*cert & (ASN1_LENGTH_MASK + 1)) {
159 while (*cert == 0 && size > 0) {
165 tbs_size |= *(cert++);
171 tbs_size += (cert - result);
173 if (output_size != NULL)
174 *output_size = tbs_size;
180 ve_forbidden_digest_add(hash_data *digest, size_t num)
183 VEC_ADD(forbidden_digests, digest[num]);
187 ve_anchors_add(br_x509_certificate *xcs, size_t num, anchor_list *anchors)
189 br_x509_trust_anchor ta;
192 for (u = 0; u < num; u++) {
193 if (certificate_to_trust_anchor_inner(&ta, &xcs[u]) < 0) {
196 VEC_ADD(*anchors, ta);
203 * add certs to our trust store
206 ve_trust_anchors_add(br_x509_certificate *xcs, size_t num)
208 return (ve_anchors_add(xcs, num, &trust_anchors));
212 ve_forbidden_anchors_add(br_x509_certificate *xcs, size_t num)
214 return (ve_anchors_add(xcs, num, &forbidden_anchors));
219 * initialize our trust_anchors from ta_PEM
224 #ifdef TRUST_ANCHOR_STR
225 br_x509_certificate *xcs;
227 static int once = -1;
233 ve_utc_set(time(NULL));
235 ve_utc_set(BUILD_UTC); /* just in case */
237 ve_error_set(NULL); /* make sure it is empty */
238 #ifdef VE_PCR_SUPPORT
242 #ifdef TRUST_ANCHOR_STR
243 xcs = parse_certificates(__DECONST(unsigned char *, TRUST_ANCHOR_STR),
244 sizeof(TRUST_ANCHOR_STR), &num);
246 num = ve_trust_anchors_add(xcs, num);
248 once = (int) VEC_LEN(trust_anchors);
254 * if we can verify the certificate chain in "certs",
255 * return the public key and if "xcp" is !NULL the associated
258 static br_x509_pkey *
259 verify_signer_xcs(br_x509_certificate *xcs,
261 br_name_element *elts, size_t num_elts,
262 anchor_list *anchors)
264 br_x509_minimal_context mc;
265 br_x509_certificate *xc;
267 cert_list chain = VEC_INIT;
268 const br_x509_pkey *tpk;
273 DEBUG_PRINTF(5, ("verify_signer: %zu certs in chain\n", num));
274 VEC_ADDMANY(chain, xcs, num);
275 if (VEC_LEN(chain) == 0) {
276 ve_error_set("ERROR: no/invalid certificate chain\n");
280 DEBUG_PRINTF(5, ("verify_signer: %zu trust anchors\n",
283 br_x509_minimal_init(&mc, &br_sha256_vtable,
284 &VEC_ELT(*anchors, 0),
286 #ifdef VE_ECDSA_SUPPORT
287 br_x509_minimal_set_ecdsa(&mc,
288 &br_ec_prime_i31, &br_ecdsa_i31_vrfy_asn1);
290 #ifdef VE_RSA_SUPPORT
291 br_x509_minimal_set_rsa(&mc, &br_rsa_i31_pkcs1_vrfy);
293 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
294 /* This is deprecated! do not enable unless you absoultely have to */
295 br_x509_minimal_set_hash(&mc, br_sha1_ID, &br_sha1_vtable);
297 br_x509_minimal_set_hash(&mc, br_sha256_ID, &br_sha256_vtable);
298 #ifdef VE_SHA384_SUPPORT
299 br_x509_minimal_set_hash(&mc, br_sha384_ID, &br_sha384_vtable);
301 #ifdef VE_SHA512_SUPPORT
302 br_x509_minimal_set_hash(&mc, br_sha512_ID, &br_sha512_vtable);
304 br_x509_minimal_set_name_elements(&mc, elts, num_elts);
308 * Clock is probably bogus so we use ve_utc.
310 mc.days = (ve_utc / SECONDS_PER_DAY) + X509_DAYS_TO_UTC0;
311 mc.seconds = (ve_utc % SECONDS_PER_DAY);
314 mc.vtable->start_chain(&mc.vtable, NULL);
315 for (u = 0; u < VEC_LEN(chain); u ++) {
316 xc = &VEC_ELT(chain, u);
317 mc.vtable->start_cert(&mc.vtable, xc->data_len);
318 mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
319 mc.vtable->end_cert(&mc.vtable);
323 case BR_ERR_X509_EXPIRED:
326 printf("u=%zu mc.err=%d\n", u, mc.err);
330 err = mc.vtable->end_chain(&mc.vtable);
333 ve_error_set("Validation failed, err = %d", err);
335 tpk = mc.vtable->get_pkey(&mc.vtable, &usages);
345 * Check if digest of one of the certificates from verified chain
346 * is present in the forbidden database.
347 * Since UEFI allows to store three types of digests
348 * all of them have to be checked separately.
351 check_forbidden_digests(br_x509_certificate *xcs, size_t num)
353 unsigned char sha256_digest[br_sha256_SIZE];
354 unsigned char sha384_digest[br_sha384_SIZE];
355 unsigned char sha512_digest[br_sha512_SIZE];
358 br_hash_compat_context ctx;
359 const br_hash_class *md;
361 int have_sha256, have_sha384, have_sha512;
363 if (VEC_LEN(forbidden_digests) == 0)
367 * Iterate through certificates, extract their To-Be-Signed section,
368 * and compare its digest against the ones in the forbidden database.
371 tbs = X509_to_tbs(xcs[num].data, &tbs_len);
373 printf("Failed to obtain TBS part of certificate\n");
376 have_sha256 = have_sha384 = have_sha512 = 0;
378 for (i = 0; i < VEC_LEN(forbidden_digests); i++) {
379 digest = &VEC_ELT(forbidden_digests, i);
380 switch (digest->hash_size) {
384 md = &br_sha256_vtable;
385 md->init(&ctx.vtable);
386 md->update(&ctx.vtable, tbs, tbs_len);
387 md->out(&ctx.vtable, sha256_digest);
389 if (!memcmp(sha256_digest,
398 md = &br_sha384_vtable;
399 md->init(&ctx.vtable);
400 md->update(&ctx.vtable, tbs, tbs_len);
401 md->out(&ctx.vtable, sha384_digest);
403 if (!memcmp(sha384_digest,
412 md = &br_sha512_vtable;
413 md->init(&ctx.vtable);
414 md->update(&ctx.vtable, tbs, tbs_len);
415 md->out(&ctx.vtable, sha512_digest);
417 if (!memcmp(sha512_digest,
430 static br_x509_pkey *
431 verify_signer(const char *certs,
432 br_name_element *elts, size_t num_elts)
434 br_x509_certificate *xcs;
441 xcs = read_certificates(certs, &num);
443 ve_error_set("cannot read certificates\n");
449 * 1. There is a direct match between cert from forbidden_anchors
450 * and a cert from chain.
451 * 2. CA that signed the chain is found in forbidden_anchors.
453 if (VEC_LEN(forbidden_anchors) > 0)
454 pk = verify_signer_xcs(xcs, num, elts, num_elts, &forbidden_anchors);
456 ve_error_set("Certificate is on forbidden list\n");
462 pk = verify_signer_xcs(xcs, num, elts, num_elts, &trust_anchors);
467 * Check if hash of tbs part of any certificate in chain
468 * is on the forbidden list.
470 if (check_forbidden_digests(xcs, num)) {
471 ve_error_set("Certificate hash is on forbidden list\n");
476 free_certificates(xcs, num);
481 * we need a hex digest including trailing newline below
484 hexdigest(char *buf, size_t bufsz, unsigned char *foo, size_t foo_len)
486 char const hex2ascii[] = "0123456789abcdef";
489 /* every binary byte is 2 chars in hex + newline + null */
490 if (bufsz < (2 * foo_len) + 2)
493 for (i = 0; i < foo_len; i++) {
494 buf[i * 2] = hex2ascii[foo[i] >> 4];
495 buf[i * 2 + 1] = hex2ascii[foo[i] & 0x0f];
498 buf[i * 2] = 0x0A; /* we also want a newline */
499 buf[i * 2 + 1] = '\0';
506 * verify file against sigfile using pk
508 * When we generated the signature in sigfile,
509 * we hashed (sha256) file, and sent that to signing server
510 * which hashed (sha256) that hash.
512 * To verify we need to replicate that result.
518 * file to be verified
521 * signature (PEM encoded)
523 * @return NULL on error, otherwise content of file.
525 #ifdef VE_ECDSA_SUPPORT
526 static unsigned char *
527 verify_ec(br_x509_pkey *pk, const char *file, const char *sigfile)
529 char hexbuf[br_sha512_SIZE * 2 + 2];
530 unsigned char rhbuf[br_sha512_SIZE];
532 br_sha256_context ctx;
533 unsigned char *fcp, *scp;
534 size_t flen, slen, plen;
536 const br_ec_impl *ec;
539 if ((fcp = read_file(file, &flen)) == NULL)
541 if ((scp = read_file(sigfile, &slen)) == NULL) {
545 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
550 br_sha256_init(&ctx);
551 br_sha256_update(&ctx, fcp, flen);
552 br_sha256_out(&ctx, rhbuf);
553 hex = hexdigest(hexbuf, sizeof(hexbuf), rhbuf, br_sha256_SIZE);
556 br_sha256_init(&ctx);
557 br_sha256_update(&ctx, hex, strlen(hex));
558 br_sha256_out(&ctx, rhbuf);
560 ec = br_ec_get_default();
561 vrfy = br_ecdsa_vrfy_asn1_get_default();
562 if (!vrfy(ec, rhbuf, br_sha256_SIZE, &pk->key.ec, po->data,
572 #if defined(VE_RSA_SUPPORT) || defined(VE_OPENPGP_SUPPORT)
574 * @brief verify an rsa digest
576 * @return 0 on failure
579 verify_rsa_digest (br_rsa_public_key *pkey,
580 const unsigned char *hash_oid,
581 unsigned char *mdata, size_t mlen,
582 unsigned char *sdata, size_t slen)
584 br_rsa_pkcs1_vrfy vrfy;
585 unsigned char vhbuf[br_sha512_SIZE];
587 vrfy = br_rsa_pkcs1_vrfy_get_default();
589 if (!vrfy(sdata, slen, hash_oid, mlen, pkey, vhbuf) ||
590 memcmp(vhbuf, mdata, mlen) != 0) {
591 return (0); /* fail */
599 * verify file against sigfile using pk
601 * When we generated the signature in sigfile,
602 * we hashed (sha256) file, and sent that to signing server
603 * which hashed (sha256) that hash.
605 * Or (deprecated) we simply used sha1 hash directly.
607 * To verify we need to replicate that result.
613 * file to be verified
616 * signature (PEM encoded)
618 * @return NULL on error, otherwise content of file.
620 #ifdef VE_RSA_SUPPORT
621 static unsigned char *
622 verify_rsa(br_x509_pkey *pk, const char *file, const char *sigfile)
624 unsigned char rhbuf[br_sha512_SIZE];
625 const unsigned char *hash_oid;
626 const br_hash_class *md;
627 br_hash_compat_context mctx;
628 unsigned char *fcp, *scp;
629 size_t flen, slen, plen, hlen;
632 if ((fcp = read_file(file, &flen)) == NULL)
634 if ((scp = read_file(sigfile, &slen)) == NULL) {
638 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
644 switch (po->data_len) {
645 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
647 // this is our old deprecated sig method
648 md = &br_sha1_vtable;
650 hash_oid = BR_HASH_OID_SHA1;
654 md = &br_sha256_vtable;
655 hlen = br_sha256_SIZE;
656 hash_oid = BR_HASH_OID_SHA256;
659 md->init(&mctx.vtable);
660 md->update(&mctx.vtable, fcp, flen);
661 md->out(&mctx.vtable, rhbuf);
662 if (!verify_rsa_digest(&pk->key.rsa, hash_oid,
663 rhbuf, hlen, po->data, po->data_len)) {
674 * verify a signature and return content of signed file
677 * file containing signature
678 * we derrive path of signed file and certificate change from
682 * only bit 1 significant so far
684 * @return NULL on error otherwise content of signed file
687 verify_sig(const char *sigfile, int flags)
692 unsigned char cn_oid[4];
693 char pbuf[MAXPATHLEN];
698 DEBUG_PRINTF(5, ("verify_sig: %s\n", sigfile));
699 n = strlcpy(pbuf, sigfile, sizeof(pbuf));
700 if (n > (sizeof(pbuf) - 5) || strcmp(&sigfile[n - 3], "sig") != 0)
702 cp = strcpy(&pbuf[n - 3], "certs");
704 * We want the commonName field
705 * the OID we want is 2,5,4,3 - but DER encoded
713 cn.len = sizeof(cn_buf);
715 pk = verify_signer(pbuf, &cn, 1);
717 printf("cannot verify: %s: %s\n", pbuf, ve_error_get());
720 for (; cp > pbuf; cp--) {
726 switch (pk->key_type) {
727 #ifdef VE_ECDSA_SUPPORT
729 ucp = verify_ec(pk, pbuf, sigfile);
732 #ifdef VE_RSA_SUPPORT
734 ucp = verify_rsa(pk, pbuf, sigfile);
738 ucp = NULL; /* not supported */
742 printf("Unverified %s (%s)\n", pbuf,
743 cn.status ? cn_buf : "unknown");
744 } else if ((flags & 1) != 0) {
745 printf("Verified %s signed by %s\n", pbuf,
746 cn.status ? cn_buf : "someone we trust");
753 * @brief verify hash matches
755 * We have finished hashing a file,
756 * see if we got the desired result.
759 * pointer to hash context
762 * pointer to hash class
765 * name of the file we are checking
768 * the expected result
771 * size of hash output
773 * @return 0 on success
776 ve_check_hash(br_hash_compat_context *ctx, const br_hash_class *md,
777 const char *path, const char *want, size_t hlen)
779 char hexbuf[br_sha512_SIZE * 2 + 2];
780 unsigned char hbuf[br_sha512_SIZE];
785 md->out(&ctx->vtable, hbuf);
786 #ifdef VE_PCR_SUPPORT
787 ve_pcr_update(hbuf, hlen);
789 hex = hexdigest(hexbuf, sizeof(hexbuf), hbuf, hlen);
791 return (VE_FINGERPRINT_WRONG);
793 if ((rc = strncmp(hex, want, n))) {
794 ve_error_set("%s: %.*s != %.*s", path, n, hex, n, want);
795 rc = VE_FINGERPRINT_WRONG;
797 return (rc ? rc : VE_FINGERPRINT_OK);
800 #ifdef VE_HASH_KAT_STR
802 test_hash(const br_hash_class *md, size_t hlen,
803 const char *hname, const char *s, size_t slen, const char *want)
805 br_hash_compat_context mctx;
807 md->init(&mctx.vtable);
808 md->update(&mctx.vtable, s, slen);
809 return (ve_check_hash(&mctx, md, hname, want, hlen) != VE_FINGERPRINT_OK);
814 #define ve_test_hash(n, N) \
815 printf("Testing hash: " #n "\t\t\t\t%s\n", \
816 test_hash(&br_ ## n ## _vtable, br_ ## n ## _SIZE, #n, \
817 VE_HASH_KAT_STR, sizeof(VE_HASH_KAT_STR), \
818 vh_ ## N) ? "Failed" : "Passed")
822 * run self tests on hash and signature verification
824 * Test that the hash methods (SHA1 and SHA256) work.
825 * Test that we can verify a certificate for each supported
828 * @return cached result.
833 static int once = -1;
834 #ifdef VERIFY_CERTS_STR
835 br_x509_certificate *xcs;
839 unsigned char cn_oid[4];
848 DEBUG_PRINTF(5, ("Self tests...\n"));
849 #ifdef VE_HASH_KAT_STR
850 #ifdef VE_SHA1_SUPPORT
851 ve_test_hash(sha1, SHA1);
853 #ifdef VE_SHA256_SUPPORT
854 ve_test_hash(sha256, SHA256);
856 #ifdef VE_SHA384_SUPPORT
857 ve_test_hash(sha384, SHA384);
859 #ifdef VE_SHA512_SUPPORT
860 ve_test_hash(sha512, SHA512);
863 #ifdef VERIFY_CERTS_STR
864 xcs = parse_certificates(__DECONST(unsigned char *, VERIFY_CERTS_STR),
865 sizeof(VERIFY_CERTS_STR), &num);
869 * We want the commonName field
870 * the OID we want is 2,5,4,3 - but DER encoded
879 for (u = 0; u < num; u ++) {
880 cn.len = sizeof(cn_buf);
881 if ((pk = verify_signer_xcs(&xcs[u], 1, &cn, 1, &trust_anchors)) != NULL) {
882 free_cert_contents(&xcs[u]);
884 printf("Testing verify certificate: %s\tPassed\n",
885 cn.status ? cn_buf : "");
890 printf("Testing verify certificate:\t\t\tFailed\n");
893 printf("No X.509 self tests\n");
894 #endif /* VERIFY_CERTS_STR */
895 #ifdef VE_OPENPGP_SUPPORT
896 if (!openpgp_self_tests())