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);
249 #ifdef VE_OPENPGP_SUPPORT
250 once += openpgp_trust_init();
256 * if we can verify the certificate chain in "certs",
257 * return the public key and if "xcp" is !NULL the associated
260 static br_x509_pkey *
261 verify_signer_xcs(br_x509_certificate *xcs,
263 br_name_element *elts, size_t num_elts,
264 anchor_list *anchors)
266 br_x509_minimal_context mc;
267 br_x509_certificate *xc;
269 cert_list chain = VEC_INIT;
270 const br_x509_pkey *tpk;
275 DEBUG_PRINTF(5, ("verify_signer: %zu certs in chain\n", num));
276 VEC_ADDMANY(chain, xcs, num);
277 if (VEC_LEN(chain) == 0) {
278 ve_error_set("ERROR: no/invalid certificate chain\n");
282 DEBUG_PRINTF(5, ("verify_signer: %zu trust anchors\n",
285 br_x509_minimal_init(&mc, &br_sha256_vtable,
286 &VEC_ELT(*anchors, 0),
288 #ifdef VE_ECDSA_SUPPORT
289 br_x509_minimal_set_ecdsa(&mc,
290 &br_ec_prime_i31, &br_ecdsa_i31_vrfy_asn1);
292 #ifdef VE_RSA_SUPPORT
293 br_x509_minimal_set_rsa(&mc, &br_rsa_i31_pkcs1_vrfy);
295 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
296 /* This is deprecated! do not enable unless you absoultely have to */
297 br_x509_minimal_set_hash(&mc, br_sha1_ID, &br_sha1_vtable);
299 br_x509_minimal_set_hash(&mc, br_sha256_ID, &br_sha256_vtable);
300 #ifdef VE_SHA384_SUPPORT
301 br_x509_minimal_set_hash(&mc, br_sha384_ID, &br_sha384_vtable);
303 #ifdef VE_SHA512_SUPPORT
304 br_x509_minimal_set_hash(&mc, br_sha512_ID, &br_sha512_vtable);
306 br_x509_minimal_set_name_elements(&mc, elts, num_elts);
310 * Clock is probably bogus so we use ve_utc.
312 mc.days = (ve_utc / SECONDS_PER_DAY) + X509_DAYS_TO_UTC0;
313 mc.seconds = (ve_utc % SECONDS_PER_DAY);
316 mc.vtable->start_chain(&mc.vtable, NULL);
317 for (u = 0; u < VEC_LEN(chain); u ++) {
318 xc = &VEC_ELT(chain, u);
319 mc.vtable->start_cert(&mc.vtable, xc->data_len);
320 mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
321 mc.vtable->end_cert(&mc.vtable);
325 case BR_ERR_X509_EXPIRED:
328 printf("u=%zu mc.err=%d\n", u, mc.err);
332 err = mc.vtable->end_chain(&mc.vtable);
335 ve_error_set("Validation failed, err = %d", err);
337 tpk = mc.vtable->get_pkey(&mc.vtable, &usages);
347 * Check if digest of one of the certificates from verified chain
348 * is present in the forbidden database.
349 * Since UEFI allows to store three types of digests
350 * all of them have to be checked separately.
353 check_forbidden_digests(br_x509_certificate *xcs, size_t num)
355 unsigned char sha256_digest[br_sha256_SIZE];
356 unsigned char sha384_digest[br_sha384_SIZE];
357 unsigned char sha512_digest[br_sha512_SIZE];
360 br_hash_compat_context ctx;
361 const br_hash_class *md;
363 int have_sha256, have_sha384, have_sha512;
365 if (VEC_LEN(forbidden_digests) == 0)
369 * Iterate through certificates, extract their To-Be-Signed section,
370 * and compare its digest against the ones in the forbidden database.
373 tbs = X509_to_tbs(xcs[num].data, &tbs_len);
375 printf("Failed to obtain TBS part of certificate\n");
378 have_sha256 = have_sha384 = have_sha512 = 0;
380 for (i = 0; i < VEC_LEN(forbidden_digests); i++) {
381 digest = &VEC_ELT(forbidden_digests, i);
382 switch (digest->hash_size) {
386 md = &br_sha256_vtable;
387 md->init(&ctx.vtable);
388 md->update(&ctx.vtable, tbs, tbs_len);
389 md->out(&ctx.vtable, sha256_digest);
391 if (!memcmp(sha256_digest,
400 md = &br_sha384_vtable;
401 md->init(&ctx.vtable);
402 md->update(&ctx.vtable, tbs, tbs_len);
403 md->out(&ctx.vtable, sha384_digest);
405 if (!memcmp(sha384_digest,
414 md = &br_sha512_vtable;
415 md->init(&ctx.vtable);
416 md->update(&ctx.vtable, tbs, tbs_len);
417 md->out(&ctx.vtable, sha512_digest);
419 if (!memcmp(sha512_digest,
432 static br_x509_pkey *
433 verify_signer(const char *certs,
434 br_name_element *elts, size_t num_elts)
436 br_x509_certificate *xcs;
443 xcs = read_certificates(certs, &num);
445 ve_error_set("cannot read certificates\n");
451 * 1. There is a direct match between cert from forbidden_anchors
452 * and a cert from chain.
453 * 2. CA that signed the chain is found in forbidden_anchors.
455 if (VEC_LEN(forbidden_anchors) > 0)
456 pk = verify_signer_xcs(xcs, num, elts, num_elts, &forbidden_anchors);
458 ve_error_set("Certificate is on forbidden list\n");
464 pk = verify_signer_xcs(xcs, num, elts, num_elts, &trust_anchors);
469 * Check if hash of tbs part of any certificate in chain
470 * is on the forbidden list.
472 if (check_forbidden_digests(xcs, num)) {
473 ve_error_set("Certificate hash is on forbidden list\n");
478 free_certificates(xcs, num);
483 * we need a hex digest including trailing newline below
486 hexdigest(char *buf, size_t bufsz, unsigned char *foo, size_t foo_len)
488 char const hex2ascii[] = "0123456789abcdef";
491 /* every binary byte is 2 chars in hex + newline + null */
492 if (bufsz < (2 * foo_len) + 2)
495 for (i = 0; i < foo_len; i++) {
496 buf[i * 2] = hex2ascii[foo[i] >> 4];
497 buf[i * 2 + 1] = hex2ascii[foo[i] & 0x0f];
500 buf[i * 2] = 0x0A; /* we also want a newline */
501 buf[i * 2 + 1] = '\0';
508 * verify file against sigfile using pk
510 * When we generated the signature in sigfile,
511 * we hashed (sha256) file, and sent that to signing server
512 * which hashed (sha256) that hash.
514 * To verify we need to replicate that result.
520 * file to be verified
523 * signature (PEM encoded)
525 * @return NULL on error, otherwise content of file.
527 #ifdef VE_ECDSA_SUPPORT
528 static unsigned char *
529 verify_ec(br_x509_pkey *pk, const char *file, const char *sigfile)
531 char hexbuf[br_sha512_SIZE * 2 + 2];
532 unsigned char rhbuf[br_sha512_SIZE];
534 br_sha256_context ctx;
535 unsigned char *fcp, *scp;
536 size_t flen, slen, plen;
538 const br_ec_impl *ec;
541 if ((fcp = read_file(file, &flen)) == NULL)
543 if ((scp = read_file(sigfile, &slen)) == NULL) {
547 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
552 br_sha256_init(&ctx);
553 br_sha256_update(&ctx, fcp, flen);
554 br_sha256_out(&ctx, rhbuf);
555 hex = hexdigest(hexbuf, sizeof(hexbuf), rhbuf, br_sha256_SIZE);
558 br_sha256_init(&ctx);
559 br_sha256_update(&ctx, hex, strlen(hex));
560 br_sha256_out(&ctx, rhbuf);
562 ec = br_ec_get_default();
563 vrfy = br_ecdsa_vrfy_asn1_get_default();
564 if (!vrfy(ec, rhbuf, br_sha256_SIZE, &pk->key.ec, po->data,
574 #if defined(VE_RSA_SUPPORT) || defined(VE_OPENPGP_SUPPORT)
576 * @brief verify an rsa digest
578 * @return 0 on failure
581 verify_rsa_digest (br_rsa_public_key *pkey,
582 const unsigned char *hash_oid,
583 unsigned char *mdata, size_t mlen,
584 unsigned char *sdata, size_t slen)
586 br_rsa_pkcs1_vrfy vrfy;
587 unsigned char vhbuf[br_sha512_SIZE];
589 vrfy = br_rsa_pkcs1_vrfy_get_default();
591 if (!vrfy(sdata, slen, hash_oid, mlen, pkey, vhbuf) ||
592 memcmp(vhbuf, mdata, mlen) != 0) {
593 return (0); /* fail */
601 * verify file against sigfile using pk
603 * When we generated the signature in sigfile,
604 * we hashed (sha256) file, and sent that to signing server
605 * which hashed (sha256) that hash.
607 * Or (deprecated) we simply used sha1 hash directly.
609 * To verify we need to replicate that result.
615 * file to be verified
618 * signature (PEM encoded)
620 * @return NULL on error, otherwise content of file.
622 #ifdef VE_RSA_SUPPORT
623 static unsigned char *
624 verify_rsa(br_x509_pkey *pk, const char *file, const char *sigfile)
626 unsigned char rhbuf[br_sha512_SIZE];
627 const unsigned char *hash_oid;
628 const br_hash_class *md;
629 br_hash_compat_context mctx;
630 unsigned char *fcp, *scp;
631 size_t flen, slen, plen, hlen;
634 if ((fcp = read_file(file, &flen)) == NULL)
636 if ((scp = read_file(sigfile, &slen)) == NULL) {
640 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
646 switch (po->data_len) {
647 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
649 // this is our old deprecated sig method
650 md = &br_sha1_vtable;
652 hash_oid = BR_HASH_OID_SHA1;
656 md = &br_sha256_vtable;
657 hlen = br_sha256_SIZE;
658 hash_oid = BR_HASH_OID_SHA256;
661 md->init(&mctx.vtable);
662 md->update(&mctx.vtable, fcp, flen);
663 md->out(&mctx.vtable, rhbuf);
664 if (!verify_rsa_digest(&pk->key.rsa, hash_oid,
665 rhbuf, hlen, po->data, po->data_len)) {
676 * verify a signature and return content of signed file
679 * file containing signature
680 * we derrive path of signed file and certificate change from
684 * only bit 1 significant so far
686 * @return NULL on error otherwise content of signed file
689 verify_sig(const char *sigfile, int flags)
694 unsigned char cn_oid[4];
695 char pbuf[MAXPATHLEN];
700 DEBUG_PRINTF(5, ("verify_sig: %s\n", sigfile));
701 n = strlcpy(pbuf, sigfile, sizeof(pbuf));
702 if (n > (sizeof(pbuf) - 5) || strcmp(&sigfile[n - 3], "sig") != 0)
704 cp = strcpy(&pbuf[n - 3], "certs");
706 * We want the commonName field
707 * the OID we want is 2,5,4,3 - but DER encoded
715 cn.len = sizeof(cn_buf);
717 pk = verify_signer(pbuf, &cn, 1);
719 printf("cannot verify: %s: %s\n", pbuf, ve_error_get());
722 for (; cp > pbuf; cp--) {
728 switch (pk->key_type) {
729 #ifdef VE_ECDSA_SUPPORT
731 ucp = verify_ec(pk, pbuf, sigfile);
734 #ifdef VE_RSA_SUPPORT
736 ucp = verify_rsa(pk, pbuf, sigfile);
740 ucp = NULL; /* not supported */
744 printf("Unverified %s (%s)\n", pbuf,
745 cn.status ? cn_buf : "unknown");
746 } else if ((flags & 1) != 0) {
747 printf("Verified %s signed by %s\n", pbuf,
748 cn.status ? cn_buf : "someone we trust");
755 * @brief verify hash matches
757 * We have finished hashing a file,
758 * see if we got the desired result.
761 * pointer to hash context
764 * pointer to hash class
767 * name of the file we are checking
770 * the expected result
773 * size of hash output
775 * @return 0 on success
778 ve_check_hash(br_hash_compat_context *ctx, const br_hash_class *md,
779 const char *path, const char *want, size_t hlen)
781 char hexbuf[br_sha512_SIZE * 2 + 2];
782 unsigned char hbuf[br_sha512_SIZE];
787 md->out(&ctx->vtable, hbuf);
788 #ifdef VE_PCR_SUPPORT
789 ve_pcr_update(hbuf, hlen);
791 hex = hexdigest(hexbuf, sizeof(hexbuf), hbuf, hlen);
793 return (VE_FINGERPRINT_WRONG);
795 if ((rc = strncmp(hex, want, n))) {
796 ve_error_set("%s: %.*s != %.*s", path, n, hex, n, want);
797 rc = VE_FINGERPRINT_WRONG;
799 return (rc ? rc : VE_FINGERPRINT_OK);
802 #ifdef VE_HASH_KAT_STR
804 test_hash(const br_hash_class *md, size_t hlen,
805 const char *hname, const char *s, size_t slen, const char *want)
807 br_hash_compat_context mctx;
809 md->init(&mctx.vtable);
810 md->update(&mctx.vtable, s, slen);
811 return (ve_check_hash(&mctx, md, hname, want, hlen) != VE_FINGERPRINT_OK);
816 #define ve_test_hash(n, N) \
817 printf("Testing hash: " #n "\t\t\t\t%s\n", \
818 test_hash(&br_ ## n ## _vtable, br_ ## n ## _SIZE, #n, \
819 VE_HASH_KAT_STR, VE_HASH_KAT_STRLEN(VE_HASH_KAT_STR), \
820 vh_ ## N) ? "Failed" : "Passed")
824 * run self tests on hash and signature verification
826 * Test that the hash methods (SHA1 and SHA256) work.
827 * Test that we can verify a certificate for each supported
830 * @return cached result.
835 static int once = -1;
836 #ifdef VERIFY_CERTS_STR
837 br_x509_certificate *xcs;
841 unsigned char cn_oid[4];
850 DEBUG_PRINTF(5, ("Self tests...\n"));
851 #ifdef VE_HASH_KAT_STR
852 #ifdef VE_SHA1_SUPPORT
853 ve_test_hash(sha1, SHA1);
855 #ifdef VE_SHA256_SUPPORT
856 ve_test_hash(sha256, SHA256);
858 #ifdef VE_SHA384_SUPPORT
859 ve_test_hash(sha384, SHA384);
861 #ifdef VE_SHA512_SUPPORT
862 ve_test_hash(sha512, SHA512);
865 #ifdef VERIFY_CERTS_STR
866 xcs = parse_certificates(__DECONST(unsigned char *, VERIFY_CERTS_STR),
867 sizeof(VERIFY_CERTS_STR), &num);
870 * We want the commonName field
871 * the OID we want is 2,5,4,3 - but DER encoded
880 for (u = 0; u < num; u ++) {
881 cn.len = sizeof(cn_buf);
882 if ((pk = verify_signer_xcs(&xcs[u], 1, &cn, 1, &trust_anchors)) != NULL) {
883 free_cert_contents(&xcs[u]);
885 printf("Testing verify certificate: %s\tPassed\n",
886 cn.status ? cn_buf : "");
891 printf("Testing verify certificate:\t\t\tFailed\n");
894 #endif /* VERIFY_CERTS_STR */
895 #ifdef VE_OPENPGP_SUPPORT
896 if (!openpgp_self_tests())