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 SECONDS_PER_YEAR 365 * SECONDS_PER_DAY
48 #ifndef VE_UTC_MAX_JUMP
49 # define VE_UTC_MAX_JUMP 20 * SECONDS_PER_YEAR
51 #define X509_DAYS_TO_UTC0 719528
55 typedef VECTOR(br_x509_certificate) cert_list;
56 typedef VECTOR(hash_data) digest_list;
58 static anchor_list trust_anchors = VEC_INIT;
59 static anchor_list forbidden_anchors = VEC_INIT;
60 static digest_list forbidden_digests = VEC_INIT;
62 static int anchor_verbose = 0;
65 ve_anchor_verbose_set(int n)
71 ve_anchor_verbose_get(void)
73 return (anchor_verbose);
82 static char ebuf[512];
91 ve_error_set(const char *fmt, ...)
101 vsprintf(ebuf, fmt, ap); /* no vsnprintf in libstand */
102 ebuf[sizeof(ebuf) - 1] = '\0';
105 rc = vsnprintf(ebuf, sizeof(ebuf), fmt, ap);
112 /* this is the time we use for verifying certs */
113 static time_t ve_utc = 0;
117 * set ve_utc used for certificate verification
120 * time - ignored unless greater than current value
121 * and not a leap of 20 years or more.
124 ve_utc_set(time_t utc)
127 (ve_utc == 0 || (utc - ve_utc) < VE_UTC_MAX_JUMP)) {
128 DEBUG_PRINTF(2, ("Set ve_utc=%jd\n", (intmax_t)utc));
134 free_cert_contents(br_x509_certificate *xc)
140 * a bit of a dance to get commonName from a certificate
143 x509_cn_get(br_x509_certificate *xc, char *buf, size_t len)
145 br_x509_minimal_context mc;
147 unsigned char cn_oid[4];
153 * We want the commonName field
154 * the OID we want is 2,5,4,3 - but DER encoded
165 br_x509_minimal_init(&mc, &br_sha256_vtable, NULL, 0);
166 br_x509_minimal_set_name_elements(&mc, &cn, 1);
167 /* the below actually does the work - updates cn.status */
168 mc.vtable->start_chain(&mc.vtable, NULL);
169 mc.vtable->start_cert(&mc.vtable, xc->data_len);
170 mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
171 mc.vtable->end_cert(&mc.vtable);
172 /* we don' actually care about cert status - just its name */
173 err = mc.vtable->end_chain(&mc.vtable);
180 /* ASN parsing related defines */
181 #define ASN1_PRIMITIVE_TAG 0x1F
182 #define ASN1_INF_LENGTH 0x80
183 #define ASN1_LENGTH_MASK 0x7F
186 * Get TBS part of certificate.
187 * Since BearSSL doesn't provide any API to do this,
188 * it has to be implemented here.
191 X509_to_tbs(unsigned char* cert, size_t* output_size)
193 unsigned char *result;
200 /* Strip two sequences to get to the TBS section */
201 for (i = 0; i < 2; i++) {
203 * XXX: We don't need to support extended tags since
204 * they should not be present in certificates.
206 if ((*cert & ASN1_PRIMITIVE_TAG) == ASN1_PRIMITIVE_TAG)
211 if (*cert == ASN1_INF_LENGTH)
214 size = *cert & ASN1_LENGTH_MASK;
217 /* Size can either be stored on a single or multiple bytes */
218 if (*cert & (ASN1_LENGTH_MASK + 1)) {
220 while (*cert == 0 && size > 0) {
226 tbs_size |= *(cert++);
232 tbs_size += (cert - result);
234 if (output_size != NULL)
235 *output_size = tbs_size;
241 ve_forbidden_digest_add(hash_data *digest, size_t num)
244 VEC_ADD(forbidden_digests, digest[num]);
248 ve_anchors_add(br_x509_certificate *xcs, size_t num, anchor_list *anchors,
249 const char *anchors_name)
251 br_x509_trust_anchor ta;
254 for (u = 0; u < num; u++) {
255 if (certificate_to_trust_anchor_inner(&ta, &xcs[u]) < 0) {
258 VEC_ADD(*anchors, ta);
259 if (anchor_verbose && anchors_name) {
263 cp = x509_cn_get(&xcs[u], buf, sizeof(buf));
265 printf("x509_anchor(%s) %s\n", cp, anchors_name);
274 * add certs to our trust store
277 ve_trust_anchors_add(br_x509_certificate *xcs, size_t num)
279 return (ve_anchors_add(xcs, num, &trust_anchors, "trusted"));
283 ve_forbidden_anchors_add(br_x509_certificate *xcs, size_t num)
285 return (ve_anchors_add(xcs, num, &forbidden_anchors, "forbidden"));
290 * @brief add trust anchors in buf
292 * Assume buf contains x509 certificates, but if not and
293 * we support OpenPGP try adding as that.
295 * @return number of anchors added
298 ve_trust_anchors_add_buf(unsigned char *buf, size_t len)
300 br_x509_certificate *xcs;
304 xcs = parse_certificates(buf, len, &num);
306 num = ve_trust_anchors_add(xcs, num);
307 #ifdef VE_OPENPGP_SUPPORT
309 num = openpgp_trust_add_buf(buf, len);
316 * @brief revoke trust anchors in buf
318 * Assume buf contains x509 certificates, but if not and
319 * we support OpenPGP try revoking keyId
321 * @return number of anchors revoked
324 ve_trust_anchors_revoke(unsigned char *buf, size_t len)
326 br_x509_certificate *xcs;
330 xcs = parse_certificates(buf, len, &num);
332 num = ve_forbidden_anchors_add(xcs, num);
333 #ifdef VE_OPENPGP_SUPPORT
335 if (buf[len - 1] == '\n')
337 num = openpgp_trust_revoke((char *)buf);
345 * initialize our trust_anchors from ta_PEM
350 static int once = -1;
354 once = 0; /* to be sure */
356 ve_utc_set(BUILD_UTC); /* ensure sanity */
358 ve_utc_set(time(NULL));
359 ve_error_set(NULL); /* make sure it is empty */
360 #ifdef VE_PCR_SUPPORT
364 #ifdef TRUST_ANCHOR_STR
365 ve_trust_anchors_add_buf(__DECONST(unsigned char *, TRUST_ANCHOR_STR),
366 sizeof(TRUST_ANCHOR_STR));
368 once = (int) VEC_LEN(trust_anchors);
369 #ifdef VE_OPENPGP_SUPPORT
370 once += openpgp_trust_init();
376 * if we can verify the certificate chain in "certs",
377 * return the public key and if "xcp" is !NULL the associated
380 static br_x509_pkey *
381 verify_signer_xcs(br_x509_certificate *xcs,
383 br_name_element *elts, size_t num_elts,
384 anchor_list *anchors)
386 br_x509_minimal_context mc;
387 br_x509_certificate *xc;
389 cert_list chain = VEC_INIT;
390 const br_x509_pkey *tpk;
395 DEBUG_PRINTF(5, ("verify_signer: %zu certs in chain\n", num));
396 VEC_ADDMANY(chain, xcs, num);
397 if (VEC_LEN(chain) == 0) {
398 ve_error_set("ERROR: no/invalid certificate chain\n");
402 DEBUG_PRINTF(5, ("verify_signer: %zu trust anchors\n",
405 br_x509_minimal_init(&mc, &br_sha256_vtable,
406 &VEC_ELT(*anchors, 0),
408 #ifdef VE_ECDSA_SUPPORT
409 br_x509_minimal_set_ecdsa(&mc,
410 &br_ec_prime_i31, &br_ecdsa_i31_vrfy_asn1);
412 #ifdef VE_RSA_SUPPORT
413 br_x509_minimal_set_rsa(&mc, &br_rsa_i31_pkcs1_vrfy);
415 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
416 /* This is deprecated! do not enable unless you absoultely have to */
417 br_x509_minimal_set_hash(&mc, br_sha1_ID, &br_sha1_vtable);
419 br_x509_minimal_set_hash(&mc, br_sha256_ID, &br_sha256_vtable);
420 #ifdef VE_SHA384_SUPPORT
421 br_x509_minimal_set_hash(&mc, br_sha384_ID, &br_sha384_vtable);
423 #ifdef VE_SHA512_SUPPORT
424 br_x509_minimal_set_hash(&mc, br_sha512_ID, &br_sha512_vtable);
426 br_x509_minimal_set_name_elements(&mc, elts, num_elts);
430 * Clock is probably bogus so we use ve_utc.
432 mc.days = (ve_utc / SECONDS_PER_DAY) + X509_DAYS_TO_UTC0;
433 mc.seconds = (ve_utc % SECONDS_PER_DAY);
436 mc.vtable->start_chain(&mc.vtable, NULL);
437 for (u = 0; u < VEC_LEN(chain); u ++) {
438 xc = &VEC_ELT(chain, u);
439 mc.vtable->start_cert(&mc.vtable, xc->data_len);
440 mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
441 mc.vtable->end_cert(&mc.vtable);
445 case BR_ERR_X509_EXPIRED:
448 printf("u=%zu mc.err=%d\n", u, mc.err);
452 err = mc.vtable->end_chain(&mc.vtable);
455 ve_error_set("Validation failed, err = %d", err);
457 tpk = mc.vtable->get_pkey(&mc.vtable, &usages);
467 * Check if digest of one of the certificates from verified chain
468 * is present in the forbidden database.
469 * Since UEFI allows to store three types of digests
470 * all of them have to be checked separately.
473 check_forbidden_digests(br_x509_certificate *xcs, size_t num)
475 unsigned char sha256_digest[br_sha256_SIZE];
476 unsigned char sha384_digest[br_sha384_SIZE];
477 unsigned char sha512_digest[br_sha512_SIZE];
480 br_hash_compat_context ctx;
481 const br_hash_class *md;
483 int have_sha256, have_sha384, have_sha512;
485 if (VEC_LEN(forbidden_digests) == 0)
489 * Iterate through certificates, extract their To-Be-Signed section,
490 * and compare its digest against the ones in the forbidden database.
493 tbs = X509_to_tbs(xcs[num].data, &tbs_len);
495 printf("Failed to obtain TBS part of certificate\n");
498 have_sha256 = have_sha384 = have_sha512 = 0;
500 for (i = 0; i < VEC_LEN(forbidden_digests); i++) {
501 digest = &VEC_ELT(forbidden_digests, i);
502 switch (digest->hash_size) {
506 md = &br_sha256_vtable;
507 md->init(&ctx.vtable);
508 md->update(&ctx.vtable, tbs, tbs_len);
509 md->out(&ctx.vtable, sha256_digest);
511 if (!memcmp(sha256_digest,
520 md = &br_sha384_vtable;
521 md->init(&ctx.vtable);
522 md->update(&ctx.vtable, tbs, tbs_len);
523 md->out(&ctx.vtable, sha384_digest);
525 if (!memcmp(sha384_digest,
534 md = &br_sha512_vtable;
535 md->init(&ctx.vtable);
536 md->update(&ctx.vtable, tbs, tbs_len);
537 md->out(&ctx.vtable, sha512_digest);
539 if (!memcmp(sha512_digest,
552 static br_x509_pkey *
553 verify_signer(const char *certs,
554 br_name_element *elts, size_t num_elts)
556 br_x509_certificate *xcs;
563 xcs = read_certificates(certs, &num);
565 ve_error_set("cannot read certificates\n");
571 * 1. There is a direct match between cert from forbidden_anchors
572 * and a cert from chain.
573 * 2. CA that signed the chain is found in forbidden_anchors.
575 if (VEC_LEN(forbidden_anchors) > 0)
576 pk = verify_signer_xcs(xcs, num, elts, num_elts, &forbidden_anchors);
578 ve_error_set("Certificate is on forbidden list\n");
584 pk = verify_signer_xcs(xcs, num, elts, num_elts, &trust_anchors);
589 * Check if hash of tbs part of any certificate in chain
590 * is on the forbidden list.
592 if (check_forbidden_digests(xcs, num)) {
593 ve_error_set("Certificate hash is on forbidden list\n");
598 free_certificates(xcs, num);
603 * we need a hex digest including trailing newline below
606 hexdigest(char *buf, size_t bufsz, unsigned char *foo, size_t foo_len)
608 char const hex2ascii[] = "0123456789abcdef";
611 /* every binary byte is 2 chars in hex + newline + null */
612 if (bufsz < (2 * foo_len) + 2)
615 for (i = 0; i < foo_len; i++) {
616 buf[i * 2] = hex2ascii[foo[i] >> 4];
617 buf[i * 2 + 1] = hex2ascii[foo[i] & 0x0f];
620 buf[i * 2] = 0x0A; /* we also want a newline */
621 buf[i * 2 + 1] = '\0';
628 * verify file against sigfile using pk
630 * When we generated the signature in sigfile,
631 * we hashed (sha256) file, and sent that to signing server
632 * which hashed (sha256) that hash.
634 * To verify we need to replicate that result.
640 * file to be verified
643 * signature (PEM encoded)
645 * @return NULL on error, otherwise content of file.
647 #ifdef VE_ECDSA_SUPPORT
648 static unsigned char *
649 verify_ec(br_x509_pkey *pk, const char *file, const char *sigfile)
651 #ifdef VE_ECDSA_HASH_AGAIN
652 char *hex, hexbuf[br_sha512_SIZE * 2 + 2];
654 unsigned char rhbuf[br_sha512_SIZE];
655 br_sha256_context ctx;
656 unsigned char *fcp, *scp;
657 size_t flen, slen, plen;
659 const br_ec_impl *ec;
662 if ((fcp = read_file(file, &flen)) == NULL)
664 if ((scp = read_file(sigfile, &slen)) == NULL) {
668 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
673 br_sha256_init(&ctx);
674 br_sha256_update(&ctx, fcp, flen);
675 br_sha256_out(&ctx, rhbuf);
676 #ifdef VE_ECDSA_HASH_AGAIN
677 hex = hexdigest(hexbuf, sizeof(hexbuf), rhbuf, br_sha256_SIZE);
680 br_sha256_init(&ctx);
681 br_sha256_update(&ctx, hex, strlen(hex));
682 br_sha256_out(&ctx, rhbuf);
685 ec = br_ec_get_default();
686 vrfy = br_ecdsa_vrfy_asn1_get_default();
687 if (!vrfy(ec, rhbuf, br_sha256_SIZE, &pk->key.ec, po->data,
697 #if defined(VE_RSA_SUPPORT) || defined(VE_OPENPGP_SUPPORT)
699 * @brief verify an rsa digest
701 * @return 0 on failure
704 verify_rsa_digest (br_rsa_public_key *pkey,
705 const unsigned char *hash_oid,
706 unsigned char *mdata, size_t mlen,
707 unsigned char *sdata, size_t slen)
709 br_rsa_pkcs1_vrfy vrfy;
710 unsigned char vhbuf[br_sha512_SIZE];
712 vrfy = br_rsa_pkcs1_vrfy_get_default();
714 if (!vrfy(sdata, slen, hash_oid, mlen, pkey, vhbuf) ||
715 memcmp(vhbuf, mdata, mlen) != 0) {
716 return (0); /* fail */
724 * verify file against sigfile using pk
726 * When we generated the signature in sigfile,
727 * we hashed (sha256) file, and sent that to signing server
728 * which hashed (sha256) that hash.
730 * Or (deprecated) we simply used sha1 hash directly.
732 * To verify we need to replicate that result.
738 * file to be verified
741 * signature (PEM encoded)
743 * @return NULL on error, otherwise content of file.
745 #ifdef VE_RSA_SUPPORT
746 static unsigned char *
747 verify_rsa(br_x509_pkey *pk, const char *file, const char *sigfile)
749 unsigned char rhbuf[br_sha512_SIZE];
750 const unsigned char *hash_oid;
751 const br_hash_class *md;
752 br_hash_compat_context mctx;
753 unsigned char *fcp, *scp;
754 size_t flen, slen, plen, hlen;
757 if ((fcp = read_file(file, &flen)) == NULL)
759 if ((scp = read_file(sigfile, &slen)) == NULL) {
763 if ((po = decode_pem(scp, slen, &plen)) == NULL) {
769 switch (po->data_len) {
770 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
772 // this is our old deprecated sig method
773 md = &br_sha1_vtable;
775 hash_oid = BR_HASH_OID_SHA1;
779 md = &br_sha256_vtable;
780 hlen = br_sha256_SIZE;
781 hash_oid = BR_HASH_OID_SHA256;
784 md->init(&mctx.vtable);
785 md->update(&mctx.vtable, fcp, flen);
786 md->out(&mctx.vtable, rhbuf);
787 if (!verify_rsa_digest(&pk->key.rsa, hash_oid,
788 rhbuf, hlen, po->data, po->data_len)) {
799 * verify a signature and return content of signed file
802 * file containing signature
803 * we derrive path of signed file and certificate change from
807 * only bit 1 significant so far
809 * @return NULL on error otherwise content of signed file
812 verify_sig(const char *sigfile, int flags)
817 unsigned char cn_oid[4];
818 char pbuf[MAXPATHLEN];
823 DEBUG_PRINTF(5, ("verify_sig: %s\n", sigfile));
824 n = strlcpy(pbuf, sigfile, sizeof(pbuf));
825 if (n > (sizeof(pbuf) - 5) || strcmp(&sigfile[n - 3], "sig") != 0)
827 cp = strcpy(&pbuf[n - 3], "certs");
829 * We want the commonName field
830 * the OID we want is 2,5,4,3 - but DER encoded
838 cn.len = sizeof(cn_buf);
840 pk = verify_signer(pbuf, &cn, 1);
842 printf("cannot verify: %s: %s\n", pbuf, ve_error_get());
845 for (; cp > pbuf; cp--) {
851 switch (pk->key_type) {
852 #ifdef VE_ECDSA_SUPPORT
854 ucp = verify_ec(pk, pbuf, sigfile);
857 #ifdef VE_RSA_SUPPORT
859 ucp = verify_rsa(pk, pbuf, sigfile);
863 ucp = NULL; /* not supported */
867 printf("Unverified %s (%s)\n", pbuf,
868 cn.status ? cn_buf : "unknown");
869 } else if ((flags & 1) != 0) {
870 printf("Verified %s signed by %s\n", pbuf,
871 cn.status ? cn_buf : "someone we trust");
878 * @brief verify hash matches
880 * We have finished hashing a file,
881 * see if we got the desired result.
884 * pointer to hash context
887 * pointer to hash class
890 * name of the file we are checking
893 * the expected result
896 * size of hash output
898 * @return 0 on success
901 ve_check_hash(br_hash_compat_context *ctx, const br_hash_class *md,
902 const char *path, const char *want, size_t hlen)
904 char hexbuf[br_sha512_SIZE * 2 + 2];
905 unsigned char hbuf[br_sha512_SIZE];
910 md->out(&ctx->vtable, hbuf);
911 #ifdef VE_PCR_SUPPORT
912 ve_pcr_update(path, hbuf, hlen);
914 hex = hexdigest(hexbuf, sizeof(hexbuf), hbuf, hlen);
916 return (VE_FINGERPRINT_WRONG);
918 if ((rc = strncmp(hex, want, n))) {
919 ve_error_set("%s: %.*s != %.*s", path, n, hex, n, want);
920 rc = VE_FINGERPRINT_WRONG;
922 return (rc ? rc : VE_FINGERPRINT_OK);
925 #ifdef VE_HASH_KAT_STR
927 test_hash(const br_hash_class *md, size_t hlen,
928 const char *hname, const char *s, size_t slen, const char *want)
930 br_hash_compat_context mctx;
932 md->init(&mctx.vtable);
933 md->update(&mctx.vtable, s, slen);
934 return (ve_check_hash(&mctx, md, hname, want, hlen) != VE_FINGERPRINT_OK);
939 #define ve_test_hash(n, N) \
940 printf("Testing hash: " #n "\t\t\t\t%s\n", \
941 test_hash(&br_ ## n ## _vtable, br_ ## n ## _SIZE, #n, \
942 VE_HASH_KAT_STR, VE_HASH_KAT_STRLEN(VE_HASH_KAT_STR), \
943 vh_ ## N) ? "Failed" : "Passed")
947 * run self tests on hash and signature verification
949 * Test that the hash methods (SHA1 and SHA256) work.
950 * Test that we can verify a certificate for each supported
953 * @return cached result.
958 static int once = -1;
959 #ifdef VERIFY_CERTS_STR
960 br_x509_certificate *xcs;
964 unsigned char cn_oid[4];
973 DEBUG_PRINTF(5, ("Self tests...\n"));
974 #ifdef VE_HASH_KAT_STR
975 #ifdef VE_SHA1_SUPPORT
976 ve_test_hash(sha1, SHA1);
978 #ifdef VE_SHA256_SUPPORT
979 ve_test_hash(sha256, SHA256);
981 #ifdef VE_SHA384_SUPPORT
982 ve_test_hash(sha384, SHA384);
984 #ifdef VE_SHA512_SUPPORT
985 ve_test_hash(sha512, SHA512);
988 #ifdef VERIFY_CERTS_STR
989 xcs = parse_certificates(__DECONST(unsigned char *, VERIFY_CERTS_STR),
990 sizeof(VERIFY_CERTS_STR), &num);
993 * We want the commonName field
994 * the OID we want is 2,5,4,3 - but DER encoded
1003 for (u = 0; u < num; u ++) {
1004 cn.len = sizeof(cn_buf);
1005 if ((pk = verify_signer_xcs(&xcs[u], 1, &cn, 1, &trust_anchors)) != NULL) {
1006 free_cert_contents(&xcs[u]);
1008 printf("Testing verify certificate: %s\tPassed\n",
1009 cn.status ? cn_buf : "");
1014 printf("Testing verify certificate:\t\t\tFailed\n");
1017 #endif /* VERIFY_CERTS_STR */
1018 #ifdef VE_OPENPGP_SUPPORT
1019 if (!openpgp_self_tests())