xref: /freebsd/lib/libsecureboot/vets.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*-
2  * Copyright (c) 2017-2018, Juniper Networks, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27 
28 /**
29  * @file vets.c - trust store
30  * @brief verify signatures
31  *
32  * We leverage code from BearSSL www.bearssl.org
33  */
34 
35 #include <sys/time.h>
36 #include <stdarg.h>
37 #define NEED_BRSSL_H
38 #include "libsecureboot-priv.h"
39 #include <brssl.h>
40 #include <ta.h>
41 
42 #ifndef TRUST_ANCHOR_STR
43 # define TRUST_ANCHOR_STR ta_PEM
44 #endif
45 
46 #define EPOCH_YEAR		1970
47 #define AVG_SECONDS_PER_YEAR	31556952L
48 #define SECONDS_PER_DAY		86400
49 #define SECONDS_PER_YEAR	365 * SECONDS_PER_DAY
50 #ifndef VE_UTC_MAX_JUMP
51 # define VE_UTC_MAX_JUMP	20 * SECONDS_PER_YEAR
52 #endif
53 #define X509_DAYS_TO_UTC0	719528
54 
55 int DebugVe = 0;
56 
57 #ifndef VE_VERIFY_FLAGS
58 # define VE_VERIFY_FLAGS VEF_VERBOSE
59 #endif
60 int VerifyFlags = VE_VERIFY_FLAGS;
61 
62 typedef VECTOR(br_x509_certificate) cert_list;
63 typedef VECTOR(hash_data) digest_list;
64 
65 static anchor_list trust_anchors = VEC_INIT;
66 static anchor_list forbidden_anchors = VEC_INIT;
67 static digest_list forbidden_digests = VEC_INIT;
68 
69 static int anchor_verbose = 0;
70 
71 void
72 ve_anchor_verbose_set(int n)
73 {
74 	anchor_verbose = n;
75 }
76 
77 int
78 ve_anchor_verbose_get(void)
79 {
80 	return (anchor_verbose);
81 }
82 
83 void
84 ve_debug_set(int n)
85 {
86 	DebugVe = n;
87 }
88 
89 /*
90  * For embedded systems (and boot loaders)
91  * we do not want to enforce certificate validity post install.
92  * It is generally unacceptible for infrastructure to stop working
93  * just because it has not been updated recently.
94  */
95 static int enforce_validity = 0;
96 
97 void
98 ve_enforce_validity_set(int i)
99 {
100     enforce_validity = i;
101 }
102 
103 static char ebuf[512];
104 
105 char *
106 ve_error_get(void)
107 {
108 	return (ebuf);
109 }
110 
111 int
112 ve_error_set(const char *fmt, ...)
113 {
114 	int rc;
115 	va_list ap;
116 
117 	va_start(ap, fmt);
118 	ebuf[0] = '\0';
119 	rc = 0;
120 	if (fmt) {
121 #ifdef STAND_H
122 		vsprintf(ebuf, fmt, ap); /* no vsnprintf in libstand */
123 		ebuf[sizeof(ebuf) - 1] = '\0';
124 		rc = strlen(ebuf);
125 #else
126 		rc = vsnprintf(ebuf, sizeof(ebuf), fmt, ap);
127 #endif
128 	}
129 	va_end(ap);
130 	return (rc);
131 }
132 
133 #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
134 
135 /*
136  * The *approximate* date.
137  *
138  * When certificate verification fails for being
139  * expired or not yet valid, it helps to indicate
140  * our current date.
141  * Since libsa lacks strftime and gmtime,
142  * this simple implementation suffices.
143  */
144 static const char *
145 gdate(char *buf, size_t bufsz, time_t clock)
146 {
147 	int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
148 	int year, y, m, d;
149 
150 	y = clock / AVG_SECONDS_PER_YEAR;
151 	year = EPOCH_YEAR + y;
152 	for (y = EPOCH_YEAR; y < year; y++) {
153 		clock -= SECONDS_PER_YEAR;
154 		if (isleap(y))
155 			clock -= SECONDS_PER_DAY;
156 	}
157 	d = clock / SECONDS_PER_DAY;
158 	for (m = 0; d > 1 && m < 12; m++) {
159 		if (d > days[m]) {
160 			d -= days[m];
161 			if (m == 1 && d > 0 && isleap(year))
162 				d--;
163 		} else
164 			break;
165 	}
166 	d++;
167 	if (d > days[m]) {
168 	    d = 1;
169 	    m++;
170 	    if (m >= 12) {
171 		year++;
172 		m = 0;
173 	    }
174 	}
175 	(void)snprintf(buf, bufsz, "%04d-%02d-%02d", year, m+1, d);
176 	return(buf);
177 }
178 
179 /* this is the time we use for verifying certs */
180 #ifdef UNIT_TEST
181 extern time_t ve_utc;
182 time_t ve_utc = 0;
183 #else
184 static time_t ve_utc = 0;
185 #endif
186 
187 /**
188  * @brief
189  * set ve_utc used for certificate verification
190  *
191  * @param[in] utc
192  *	time - ignored unless greater than current value
193  *	and not a leap of 20 years or more.
194  */
195 void
196 ve_utc_set(time_t utc)
197 {
198 	if (utc > ve_utc &&
199 	    (ve_utc == 0 || (utc - ve_utc) < VE_UTC_MAX_JUMP)) {
200 		DEBUG_PRINTF(2, ("Set ve_utc=%jd\n", (intmax_t)utc));
201 		ve_utc = utc;
202 	}
203 }
204 
205 static void
206 free_cert_contents(br_x509_certificate *xc)
207 {
208 	xfree(xc->data);
209 }
210 
211 /*
212  * a bit of a dance to get commonName from a certificate
213  */
214 static char *
215 x509_cn_get(br_x509_certificate *xc, char *buf, size_t len)
216 {
217 	br_x509_minimal_context mc;
218 	br_name_element cn;
219 	unsigned char cn_oid[4];
220 	int err;
221 
222 	if (buf == NULL)
223 		return (buf);
224 	/*
225 	 * We want the commonName field
226 	 * the OID we want is 2,5,4,3 - but DER encoded
227 	 */
228 	cn_oid[0] = 3;
229 	cn_oid[1] = 0x55;
230 	cn_oid[2] = 4;
231 	cn_oid[3] = 3;
232 	cn.oid = cn_oid;
233 	cn.buf = buf;
234 	cn.len = len;
235 	cn.buf[0] = '\0';
236 
237 	br_x509_minimal_init(&mc, &br_sha256_vtable, NULL, 0);
238 	br_x509_minimal_set_name_elements(&mc, &cn, 1);
239 	/* the below actually does the work - updates cn.status */
240 	mc.vtable->start_chain(&mc.vtable, NULL);
241 	mc.vtable->start_cert(&mc.vtable, xc->data_len);
242 	mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
243 	mc.vtable->end_cert(&mc.vtable);
244 	/* we don't actually care about cert status - just its name */
245 	err = mc.vtable->end_chain(&mc.vtable);
246 	(void)err;			/* keep compiler quiet */
247 
248 	if (cn.status <= 0)
249 		buf = NULL;
250 	return (buf);
251 }
252 
253 /* ASN parsing related defines */
254 #define ASN1_PRIMITIVE_TAG 0x1F
255 #define ASN1_INF_LENGTH    0x80
256 #define ASN1_LENGTH_MASK   0x7F
257 
258 /*
259  * Get TBS part of certificate.
260  * Since BearSSL doesn't provide any API to do this,
261  * it has to be implemented here.
262  */
263 static void*
264 X509_to_tbs(unsigned char* cert, size_t* output_size)
265 {
266 	unsigned char *result;
267 	size_t tbs_size;
268 	int size, i;
269 
270 	if (cert == NULL)
271 		return (NULL);
272 
273 	/* Strip two sequences to get to the TBS section */
274 	for (i = 0; i < 2; i++) {
275 		/*
276 		 * XXX: We don't need to support extended tags since
277 		 * they should not be present in certificates.
278 		 */
279 		if ((*cert & ASN1_PRIMITIVE_TAG) == ASN1_PRIMITIVE_TAG)
280 			return (NULL);
281 
282 		cert++;
283 
284 		if (*cert == ASN1_INF_LENGTH)
285 			return (NULL);
286 
287 		size = *cert & ASN1_LENGTH_MASK;
288 		tbs_size = 0;
289 
290 		/* Size can either be stored on a single or multiple bytes */
291 		if (*cert & (ASN1_LENGTH_MASK + 1)) {
292 			cert++;
293 			while (*cert == 0 && size > 0) {
294 				cert++;
295 				size--;
296 			}
297 			while (size-- > 0) {
298 				tbs_size <<= 8;
299 				tbs_size |= *(cert++);
300 			}
301 		}
302 		if (i == 0)
303 			result = cert;
304 	}
305 	tbs_size += (cert - result);
306 
307 	if (output_size != NULL)
308 		*output_size = tbs_size;
309 
310 	return (result);
311 }
312 
313 void
314 ve_forbidden_digest_add(hash_data *digest, size_t num)
315 {
316 	while (num--)
317 		VEC_ADD(forbidden_digests, digest[num]);
318 }
319 
320 static size_t
321 ve_anchors_add(br_x509_certificate *xcs, size_t num, anchor_list *anchors,
322     const char *anchors_name)
323 {
324 	br_x509_trust_anchor ta;
325 	size_t u;
326 
327 	for (u = 0; u < num; u++) {
328 		if (certificate_to_trust_anchor_inner(&ta, &xcs[u]) < 0) {
329 			break;
330 		}
331 		VEC_ADD(*anchors, ta);
332 		if (anchor_verbose && anchors_name) {
333 			char buf[64];
334 			char *cp;
335 
336 			cp = x509_cn_get(&xcs[u], buf, sizeof(buf));
337 			if (cp) {
338 				printf("x509_anchor(%s) %s\n", cp, anchors_name);
339 			}
340 		}
341 	}
342 	return (u);
343 }
344 
345 /**
346  * @brief
347  * add certs to our trust store
348  */
349 size_t
350 ve_trust_anchors_add(br_x509_certificate *xcs, size_t num)
351 {
352 	return (ve_anchors_add(xcs, num, &trust_anchors, "trusted"));
353 }
354 
355 size_t
356 ve_forbidden_anchors_add(br_x509_certificate *xcs, size_t num)
357 {
358 	return (ve_anchors_add(xcs, num, &forbidden_anchors, "forbidden"));
359 }
360 
361 
362 /**
363  * @brief add trust anchors in buf
364  *
365  * Assume buf contains x509 certificates, but if not and
366  * we support OpenPGP try adding as that.
367  *
368  * @return number of anchors added
369  */
370 size_t
371 ve_trust_anchors_add_buf(unsigned char *buf, size_t len)
372 {
373 	br_x509_certificate *xcs;
374 	size_t num;
375 
376 	num = 0;
377 	xcs = parse_certificates(buf, len, &num);
378 	if (xcs != NULL) {
379 		num = ve_trust_anchors_add(xcs, num);
380 #ifdef VE_OPENPGP_SUPPORT
381 	} else {
382 		num = openpgp_trust_add_buf(buf, len);
383 #endif
384 	}
385 	return (num);
386 }
387 
388 /**
389  * @brief revoke trust anchors in buf
390  *
391  * Assume buf contains x509 certificates, but if not and
392  * we support OpenPGP try revoking keyId
393  *
394  * @return number of anchors revoked
395  */
396 size_t
397 ve_trust_anchors_revoke(unsigned char *buf, size_t len)
398 {
399 	br_x509_certificate *xcs;
400 	size_t num;
401 
402 	num = 0;
403 	xcs = parse_certificates(buf, len, &num);
404 	if (xcs != NULL) {
405 		num = ve_forbidden_anchors_add(xcs, num);
406 #ifdef VE_OPENPGP_SUPPORT
407 	} else {
408 		if (buf[len - 1] == '\n')
409 			buf[len - 1] = '\0';
410 		num = openpgp_trust_revoke((char *)buf);
411 #endif
412 	}
413 	return (num);
414 }
415 
416 /**
417  * @brief
418  * initialize our trust_anchors from ta_PEM
419  */
420 int
421 ve_trust_init(void)
422 {
423 	static int once = -1;
424 
425 	if (once >= 0)
426 		return (once);
427 	once = 0;			/* to be sure */
428 #ifdef BUILD_UTC
429 	ve_utc_set(BUILD_UTC);		/* ensure sanity */
430 #endif
431 	ve_utc_set(time(NULL));
432 	ve_error_set(NULL);		/* make sure it is empty */
433 #ifdef VE_PCR_SUPPORT
434 	ve_pcr_init();
435 #endif
436 
437 #ifdef TRUST_ANCHOR_STR
438 	if (TRUST_ANCHOR_STR != NULL && strlen(TRUST_ANCHOR_STR) != 0ul)
439 		ve_trust_anchors_add_buf(__DECONST(unsigned char *,
440 		    TRUST_ANCHOR_STR), sizeof(TRUST_ANCHOR_STR));
441 #endif
442 	once = (int) VEC_LEN(trust_anchors);
443 #ifdef VE_OPENPGP_SUPPORT
444 	once += openpgp_trust_init();
445 #endif
446 	return (once);
447 }
448 
449 #ifdef HAVE_BR_X509_TIME_CHECK
450 static int
451 verify_time_cb(void *tctx __unused,
452     uint32_t not_before_days, uint32_t not_before_seconds,
453     uint32_t not_after_days, uint32_t not_after_seconds)
454 {
455 	time_t not_before;
456 	time_t not_after;
457 	int rc;
458 #ifdef UNIT_TEST
459 	char date[12], nb_date[12], na_date[12];
460 #endif
461 
462 	if (enforce_validity) {
463 		not_before = ((not_before_days - X509_DAYS_TO_UTC0) * SECONDS_PER_DAY) + not_before_seconds;
464 		not_after =  ((not_after_days - X509_DAYS_TO_UTC0) * SECONDS_PER_DAY) + not_after_seconds;
465 		if (ve_utc < not_before)
466 			rc = -1;
467 		else if (ve_utc > not_after)
468 			rc = 1;
469 		else
470 			rc = 0;
471 #ifdef UNIT_TEST
472 		printf("notBefore %s notAfter %s date %s rc %d\n",
473 		    gdate(nb_date, sizeof(nb_date), not_before),
474 		    gdate(na_date, sizeof(na_date), not_after),
475 		    gdate(date, sizeof(date), ve_utc), rc);
476 #endif
477 	} else
478 		rc = 0;			/* don't fail */
479 	return rc;
480 }
481 #endif
482 
483 /**
484  * if we can verify the certificate chain in "certs",
485  * return the public key and if "xcp" is !NULL the associated
486  * certificate
487  */
488 static br_x509_pkey *
489 verify_signer_xcs(br_x509_certificate *xcs,
490     size_t num,
491     br_name_element *elts, size_t num_elts,
492     anchor_list *anchors)
493 {
494 	br_x509_minimal_context mc;
495 	br_x509_certificate *xc;
496 	size_t u;
497 	cert_list chain = VEC_INIT;
498 	const br_x509_pkey *tpk;
499 	br_x509_pkey *pk;
500 	unsigned int usages;
501 	int err;
502 
503 	DEBUG_PRINTF(5, ("verify_signer: %zu certs in chain\n", num));
504 	VEC_ADDMANY(chain, xcs, num);
505 	if (VEC_LEN(chain) == 0) {
506 		ve_error_set("ERROR: no/invalid certificate chain\n");
507 		return (NULL);
508 	}
509 
510 	DEBUG_PRINTF(5, ("verify_signer: %zu trust anchors\n",
511 		VEC_LEN(*anchors)));
512 
513 	br_x509_minimal_init(&mc, &br_sha256_vtable,
514 	    &VEC_ELT(*anchors, 0),
515 	    VEC_LEN(*anchors));
516 #ifdef VE_ECDSA_SUPPORT
517 	br_x509_minimal_set_ecdsa(&mc,
518 	    &br_ec_prime_i31, &br_ecdsa_i31_vrfy_asn1);
519 #endif
520 #ifdef VE_RSA_SUPPORT
521 	br_x509_minimal_set_rsa(&mc, &br_rsa_i31_pkcs1_vrfy);
522 #endif
523 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
524 	/* This is deprecated! do not enable unless you absolutely have to */
525 	br_x509_minimal_set_hash(&mc, br_sha1_ID, &br_sha1_vtable);
526 #endif
527 	br_x509_minimal_set_hash(&mc, br_sha256_ID, &br_sha256_vtable);
528 #ifdef VE_SHA384_SUPPORT
529 	br_x509_minimal_set_hash(&mc, br_sha384_ID, &br_sha384_vtable);
530 #endif
531 #ifdef VE_SHA512_SUPPORT
532 	br_x509_minimal_set_hash(&mc, br_sha512_ID, &br_sha512_vtable);
533 #endif
534 	br_x509_minimal_set_name_elements(&mc, elts, num_elts);
535 
536 #ifdef HAVE_BR_X509_TIME_CHECK
537 	br_x509_minimal_set_time_callback(&mc, NULL, verify_time_cb);
538 #else
539 #if defined(_STANDALONE) || defined(UNIT_TEST)
540 	/*
541 	 * Clock is probably bogus so we use ve_utc.
542 	 */
543 	mc.days = (ve_utc / SECONDS_PER_DAY) + X509_DAYS_TO_UTC0;
544 	mc.seconds = (ve_utc % SECONDS_PER_DAY);
545 #endif
546 #endif
547 	mc.vtable->start_chain(&mc.vtable, NULL);
548 	for (u = 0; u < VEC_LEN(chain); u ++) {
549 		xc = &VEC_ELT(chain, u);
550 		mc.vtable->start_cert(&mc.vtable, xc->data_len);
551 		mc.vtable->append(&mc.vtable, xc->data, xc->data_len);
552 		mc.vtable->end_cert(&mc.vtable);
553 		switch (mc.err) {
554 		case 0:
555 		case BR_ERR_X509_OK:
556 		case BR_ERR_X509_EXPIRED:
557 			break;
558 		default:
559 			printf("u=%zu mc.err=%d\n", u, mc.err);
560 			break;
561 		}
562 	}
563 	err = mc.vtable->end_chain(&mc.vtable);
564 	pk = NULL;
565 	if (err) {
566 		char date[12];
567 
568 		switch (err) {
569 		case 54:
570 			ve_error_set("Validation failed, certificate not valid as of %s",
571 			    gdate(date, sizeof(date), ve_utc));
572 			break;
573 		default:
574 			ve_error_set("Validation failed, err = %d", err);
575 			break;
576 		}
577 	} else {
578 		tpk = mc.vtable->get_pkey(&mc.vtable, &usages);
579 		if (tpk != NULL) {
580 			pk = xpkeydup(tpk);
581 		}
582 	}
583 	VEC_CLEAR(chain);
584 	return (pk);
585 }
586 
587 /*
588  * Check if digest of one of the certificates from verified chain
589  * is present in the forbidden database.
590  * Since UEFI allows to store three types of digests
591  * all of them have to be checked separately.
592  */
593 static int
594 check_forbidden_digests(br_x509_certificate *xcs, size_t num)
595 {
596 	unsigned char sha256_digest[br_sha256_SIZE];
597 	unsigned char sha384_digest[br_sha384_SIZE];
598 	unsigned char sha512_digest[br_sha512_SIZE];
599 	void *tbs;
600 	hash_data *digest;
601 	br_hash_compat_context ctx;
602 	const br_hash_class *md;
603 	size_t tbs_len, i;
604 	int have_sha256, have_sha384, have_sha512;
605 
606 	if (VEC_LEN(forbidden_digests) == 0)
607 		return (0);
608 
609 	/*
610 	 * Iterate through certificates, extract their To-Be-Signed section,
611 	 * and compare its digest against the ones in the forbidden database.
612 	 */
613 	while (num--) {
614 		tbs = X509_to_tbs(xcs[num].data, &tbs_len);
615 		if (tbs == NULL) {
616 			printf("Failed to obtain TBS part of certificate\n");
617 			return (1);
618 		}
619 		have_sha256 = have_sha384 = have_sha512 = 0;
620 
621 		for (i = 0; i < VEC_LEN(forbidden_digests); i++) {
622 			digest = &VEC_ELT(forbidden_digests, i);
623 			switch (digest->hash_size) {
624 			case br_sha256_SIZE:
625 				if (!have_sha256) {
626 					have_sha256 = 1;
627 					md = &br_sha256_vtable;
628 					md->init(&ctx.vtable);
629 					md->update(&ctx.vtable, tbs, tbs_len);
630 					md->out(&ctx.vtable, sha256_digest);
631 				}
632 				if (!memcmp(sha256_digest,
633 					digest->data,
634 					br_sha256_SIZE))
635 					return (1);
636 
637 				break;
638 			case br_sha384_SIZE:
639 				if (!have_sha384) {
640 					have_sha384 = 1;
641 					md = &br_sha384_vtable;
642 					md->init(&ctx.vtable);
643 					md->update(&ctx.vtable, tbs, tbs_len);
644 					md->out(&ctx.vtable, sha384_digest);
645 				}
646 				if (!memcmp(sha384_digest,
647 					digest->data,
648 					br_sha384_SIZE))
649 					return (1);
650 
651 				break;
652 			case br_sha512_SIZE:
653 				if (!have_sha512) {
654 					have_sha512 = 1;
655 					md = &br_sha512_vtable;
656 					md->init(&ctx.vtable);
657 					md->update(&ctx.vtable, tbs, tbs_len);
658 					md->out(&ctx.vtable, sha512_digest);
659 				}
660 				if (!memcmp(sha512_digest,
661 					digest->data,
662 					br_sha512_SIZE))
663 					return (1);
664 
665 				break;
666 			}
667 		}
668 	}
669 
670 	return (0);
671 }
672 
673 static br_x509_pkey *
674 verify_signer(const char *certs,
675     br_name_element *elts, size_t num_elts)
676 {
677 	br_x509_certificate *xcs;
678 	br_x509_pkey *pk;
679 	size_t num;
680 
681 	pk = NULL;
682 
683 	ve_trust_init();
684 	xcs = read_certificates(certs, &num);
685 	if (xcs == NULL) {
686 		ve_error_set("cannot read certificates\n");
687 		return (NULL);
688 	}
689 
690 	/*
691 	 * Check if either
692 	 * 1. There is a direct match between cert from forbidden_anchors
693 	 * and a cert from chain.
694 	 * 2. CA that signed the chain is found in forbidden_anchors.
695 	 */
696 	if (VEC_LEN(forbidden_anchors) > 0)
697 		pk = verify_signer_xcs(xcs, num, elts, num_elts, &forbidden_anchors);
698 	if (pk != NULL) {
699 		ve_error_set("Certificate is on forbidden list\n");
700 		xfreepkey(pk);
701 		pk = NULL;
702 		goto out;
703 	}
704 
705 	pk = verify_signer_xcs(xcs, num, elts, num_elts, &trust_anchors);
706 	if (pk == NULL)
707 		goto out;
708 
709 	/*
710 	 * Check if hash of tbs part of any certificate in chain
711 	 * is on the forbidden list.
712 	 */
713 	if (check_forbidden_digests(xcs, num)) {
714 		ve_error_set("Certificate hash is on forbidden list\n");
715 		xfreepkey(pk);
716 		pk = NULL;
717 	}
718 out:
719 	free_certificates(xcs, num);
720 	return (pk);
721 }
722 
723 /**
724  * we need a hex digest including trailing newline below
725  */
726 char *
727 hexdigest(char *buf, size_t bufsz, unsigned char *foo, size_t foo_len)
728 {
729 	char const hex2ascii[] = "0123456789abcdef";
730 	size_t i;
731 
732 	/* every binary byte is 2 chars in hex + newline + null  */
733 	if (bufsz < (2 * foo_len) + 2)
734 		return (NULL);
735 
736 	for (i = 0; i < foo_len; i++) {
737 		buf[i * 2] = hex2ascii[foo[i] >> 4];
738 		buf[i * 2 + 1] = hex2ascii[foo[i] & 0x0f];
739 	}
740 
741 	buf[i * 2] = 0x0A; /* we also want a newline */
742 	buf[i * 2 + 1] = '\0';
743 
744 	return (buf);
745 }
746 
747 /**
748  * @brief
749  * verify file against sigfile using pk
750  *
751  * When we generated the signature in sigfile,
752  * we hashed (sha256) file, and sent that to signing server
753  * which hashed (sha256) that hash.
754  *
755  * To verify we need to replicate that result.
756  *
757  * @param[in] pk
758  *	br_x509_pkey
759  *
760  * @paramp[in] file
761  *	file to be verified
762  *
763  * @param[in] sigfile
764  * 	signature (PEM encoded)
765  *
766  * @return NULL on error, otherwise content of file.
767  */
768 #ifdef VE_ECDSA_SUPPORT
769 static unsigned char *
770 verify_ec(br_x509_pkey *pk, const char *file, const char *sigfile)
771 {
772 #ifdef VE_ECDSA_HASH_AGAIN
773 	char *hex, hexbuf[br_sha512_SIZE * 2 + 2];
774 #endif
775 	unsigned char rhbuf[br_sha512_SIZE];
776 	br_sha256_context ctx;
777 	unsigned char *fcp, *scp;
778 	size_t flen, slen, plen;
779 	pem_object *po;
780 	const br_ec_impl *ec;
781 	br_ecdsa_vrfy vrfy;
782 
783 	if ((fcp = read_file(file, &flen)) == NULL)
784 		return (NULL);
785 	if ((scp = read_file(sigfile, &slen)) == NULL) {
786 		free(fcp);
787 		return (NULL);
788 	}
789 	if ((po = decode_pem(scp, slen, &plen)) == NULL) {
790 		free(fcp);
791 		free(scp);
792 		return (NULL);
793 	}
794 	br_sha256_init(&ctx);
795 	br_sha256_update(&ctx, fcp, flen);
796 	br_sha256_out(&ctx, rhbuf);
797 #ifdef VE_ECDSA_HASH_AGAIN
798 	hex = hexdigest(hexbuf, sizeof(hexbuf), rhbuf, br_sha256_SIZE);
799 	/* now hash that */
800 	if (hex) {
801 		br_sha256_init(&ctx);
802 		br_sha256_update(&ctx, hex, strlen(hex));
803 		br_sha256_out(&ctx, rhbuf);
804 	}
805 #endif
806 	ec = br_ec_get_default();
807 	vrfy = br_ecdsa_vrfy_asn1_get_default();
808 	if (!vrfy(ec, rhbuf, br_sha256_SIZE, &pk->key.ec, po->data,
809 		po->data_len)) {
810 		free(fcp);
811 		fcp = NULL;
812 	}
813 	free(scp);
814 	return (fcp);
815 }
816 #endif
817 
818 #if defined(VE_RSA_SUPPORT) || defined(VE_OPENPGP_SUPPORT)
819 /**
820  * @brief verify an rsa digest
821  *
822  * @return 0 on failure
823  */
824 int
825 verify_rsa_digest (br_rsa_public_key *pkey,
826     const unsigned char *hash_oid,
827     unsigned char *mdata, size_t mlen,
828     unsigned char *sdata, size_t slen)
829 {
830 	br_rsa_pkcs1_vrfy vrfy;
831 	unsigned char vhbuf[br_sha512_SIZE];
832 
833 	vrfy = br_rsa_pkcs1_vrfy_get_default();
834 
835 	if (!vrfy(sdata, slen, hash_oid, mlen, pkey, vhbuf) ||
836 	    memcmp(vhbuf, mdata, mlen) != 0) {
837 		return (0);		/* fail */
838 	}
839 	return (1);			/* ok */
840 }
841 #endif
842 
843 /**
844  * @brief
845  * verify file against sigfile using pk
846  *
847  * When we generated the signature in sigfile,
848  * we hashed (sha256) file, and sent that to signing server
849  * which hashed (sha256) that hash.
850  *
851  * Or (deprecated) we simply used sha1 hash directly.
852  *
853  * To verify we need to replicate that result.
854  *
855  * @param[in] pk
856  *	br_x509_pkey
857  *
858  * @paramp[in] file
859  *	file to be verified
860  *
861  * @param[in] sigfile
862  * 	signature (PEM encoded)
863  *
864  * @return NULL on error, otherwise content of file.
865  */
866 #ifdef VE_RSA_SUPPORT
867 static unsigned char *
868 verify_rsa(br_x509_pkey *pk,  const char *file, const char *sigfile)
869 {
870 	unsigned char rhbuf[br_sha512_SIZE];
871 	const unsigned char *hash_oid;
872 	const br_hash_class *md;
873 	br_hash_compat_context mctx;
874 	unsigned char *fcp, *scp;
875 	size_t flen, slen, plen, hlen;
876 	pem_object *po;
877 
878 	if ((fcp = read_file(file, &flen)) == NULL)
879 		return (NULL);
880 	if ((scp = read_file(sigfile, &slen)) == NULL) {
881 		free(fcp);
882 		return (NULL);
883 	}
884 	if ((po = decode_pem(scp, slen, &plen)) == NULL) {
885 		free(fcp);
886 		free(scp);
887 		return (NULL);
888 	}
889 
890 	switch (po->data_len) {
891 #if defined(UNIT_TEST) && defined(VE_DEPRECATED_RSA_SHA1_SUPPORT)
892 	case 256:
893 		// this is our old deprecated sig method
894 		md = &br_sha1_vtable;
895 		hlen = br_sha1_SIZE;
896 		hash_oid = BR_HASH_OID_SHA1;
897 		break;
898 #endif
899 	default:
900 		md = &br_sha256_vtable;
901 		hlen = br_sha256_SIZE;
902 		hash_oid = BR_HASH_OID_SHA256;
903 		break;
904 	}
905 	md->init(&mctx.vtable);
906 	md->update(&mctx.vtable, fcp, flen);
907 	md->out(&mctx.vtable, rhbuf);
908 	if (!verify_rsa_digest(&pk->key.rsa, hash_oid,
909 		rhbuf, hlen, po->data, po->data_len)) {
910 		free(fcp);
911 		fcp = NULL;
912 	}
913 	free(scp);
914 	return (fcp);
915 }
916 #endif
917 
918 /**
919  * @brief
920  * verify a signature and return content of signed file
921  *
922  * @param[in] sigfile
923  * 	file containing signature
924  * 	we derrive path of signed file and certificate change from
925  * 	this.
926  *
927  * @param[in] flags
928  * 	only bit 1 significant so far
929  *
930  * @return NULL on error otherwise content of signed file
931  */
932 unsigned char *
933 verify_sig(const char *sigfile, int flags)
934 {
935 	br_x509_pkey *pk;
936 	br_name_element cn;
937 	char cn_buf[80];
938 	unsigned char cn_oid[4];
939 	char pbuf[MAXPATHLEN];
940 	char *cp;
941 	unsigned char *ucp;
942 	size_t n;
943 
944 	DEBUG_PRINTF(5, ("verify_sig: %s\n", sigfile));
945 	n = strlcpy(pbuf, sigfile, sizeof(pbuf));
946 	if (n > (sizeof(pbuf) - 5) || strcmp(&sigfile[n - 3], "sig") != 0)
947 		return (NULL);
948 	cp = strcpy(&pbuf[n - 3], "certs");
949 	/*
950 	 * We want the commonName field
951 	 * the OID we want is 2,5,4,3 - but DER encoded
952 	 */
953 	cn_oid[0] = 3;
954 	cn_oid[1] = 0x55;
955 	cn_oid[2] = 4;
956 	cn_oid[3] = 3;
957 	cn.oid = cn_oid;
958 	cn.buf = cn_buf;
959 	cn.len = sizeof(cn_buf);
960 
961 	pk = verify_signer(pbuf, &cn, 1);
962 	if (!pk) {
963 		printf("cannot verify: %s: %s\n", pbuf, ve_error_get());
964 		return (NULL);
965 	}
966 	for (; cp > pbuf; cp--) {
967 		if (*cp == '.') {
968 			*cp = '\0';
969 			break;
970 		}
971 	}
972 	switch (pk->key_type) {
973 #ifdef VE_ECDSA_SUPPORT
974 	case BR_KEYTYPE_EC:
975 		ucp = verify_ec(pk, pbuf, sigfile);
976 		break;
977 #endif
978 #ifdef VE_RSA_SUPPORT
979 	case BR_KEYTYPE_RSA:
980 		ucp = verify_rsa(pk, pbuf, sigfile);
981 		break;
982 #endif
983 	default:
984 		ucp = NULL;		/* not supported */
985 	}
986 	xfreepkey(pk);
987 	if (!ucp) {
988 		printf("Unverified %s (%s)\n", pbuf,
989 		    cn.status ? cn_buf : "unknown");
990 	} else if ((flags & VEF_VERBOSE) != 0) {
991 		printf("Verified %s signed by %s\n", pbuf,
992 		    cn.status ? cn_buf : "someone we trust");
993 	}
994 	return (ucp);
995 }
996 
997 
998 /**
999  * @brief verify hash matches
1000  *
1001  * We have finished hashing a file,
1002  * see if we got the desired result.
1003  *
1004  * @param[in] ctx
1005  *	pointer to hash context
1006  *
1007  * @param[in] md
1008  *	pointer to hash class
1009  *
1010  * @param[in] path
1011  *	name of the file we are checking
1012  *
1013  * @param[in] want
1014  *	the expected result
1015  *
1016  * @param[in] hlen
1017  *	size of hash output
1018  *
1019  * @return 0 on success
1020  */
1021 int
1022 ve_check_hash(br_hash_compat_context *ctx, const br_hash_class *md,
1023     const char *path, const char *want, size_t hlen)
1024 {
1025 	char hexbuf[br_sha512_SIZE * 2 + 2];
1026 	unsigned char hbuf[br_sha512_SIZE];
1027 	char *hex;
1028 	int rc;
1029 	int n;
1030 
1031 	md->out(&ctx->vtable, hbuf);
1032 #ifdef VE_PCR_SUPPORT
1033 	ve_pcr_update(path, hbuf, hlen);
1034 #endif
1035 	hex = hexdigest(hexbuf, sizeof(hexbuf), hbuf, hlen);
1036 	if (!hex)
1037 		return (VE_FINGERPRINT_WRONG);
1038 	n = 2*hlen;
1039 	if ((rc = strncmp(hex, want, n))) {
1040 		ve_error_set("%s: %.*s != %.*s", path, n, hex, n, want);
1041 		rc = VE_FINGERPRINT_WRONG;
1042 	}
1043 	return (rc ? rc : VE_FINGERPRINT_OK);
1044 }
1045 
1046 #ifdef VE_HASH_KAT_STR
1047 static int
1048 test_hash(const br_hash_class *md, size_t hlen,
1049     const char *hname, const char *s, size_t slen, const char *want)
1050 {
1051 	br_hash_compat_context mctx;
1052 
1053 	md->init(&mctx.vtable);
1054 	md->update(&mctx.vtable, s, slen);
1055 	return (ve_check_hash(&mctx, md, hname, want, hlen) != VE_FINGERPRINT_OK);
1056 }
1057 
1058 #endif
1059 
1060 #define ve_test_hash(n, N) \
1061 	printf("Testing hash: " #n "\t\t\t\t%s\n", \
1062 	    test_hash(&br_ ## n ## _vtable, br_ ## n ## _SIZE, #n, \
1063 	    VE_HASH_KAT_STR, VE_HASH_KAT_STRLEN(VE_HASH_KAT_STR), \
1064 	    vh_ ## N) ? "Failed" : "Passed")
1065 
1066 /**
1067  * @brief
1068  * run self tests on hash and signature verification
1069  *
1070  * Test that the hash methods (SHA1 and SHA256) work.
1071  * Test that we can verify a certificate for each supported
1072  * Root CA.
1073  *
1074  * @return cached result.
1075  */
1076 int
1077 ve_self_tests(void)
1078 {
1079 	static int once = -1;
1080 #ifdef VERIFY_CERTS_STR
1081 	br_x509_certificate *xcs;
1082 	br_x509_pkey *pk;
1083 	br_name_element cn;
1084 	char cn_buf[80];
1085 	unsigned char cn_oid[4];
1086 	size_t num;
1087 	size_t u;
1088 #endif
1089 
1090 	if (once >= 0)
1091 		return (once);
1092 	once = 0;
1093 
1094 	DEBUG_PRINTF(5, ("Self tests...\n"));
1095 #ifdef VE_HASH_KAT_STR
1096 #ifdef VE_SHA1_SUPPORT
1097 	ve_test_hash(sha1, SHA1);
1098 #endif
1099 #ifdef VE_SHA256_SUPPORT
1100 	ve_test_hash(sha256, SHA256);
1101 #endif
1102 #ifdef VE_SHA384_SUPPORT
1103 	ve_test_hash(sha384, SHA384);
1104 #endif
1105 #ifdef VE_SHA512_SUPPORT
1106 	ve_test_hash(sha512, SHA512);
1107 #endif
1108 #endif
1109 #ifdef VERIFY_CERTS_STR
1110 	xcs = parse_certificates(__DECONST(unsigned char *, VERIFY_CERTS_STR),
1111 	    sizeof(VERIFY_CERTS_STR), &num);
1112 	if (xcs != NULL) {
1113 		/*
1114 		 * We want the commonName field
1115 		 * the OID we want is 2,5,4,3 - but DER encoded
1116 		 */
1117 		cn_oid[0] = 3;
1118 		cn_oid[1] = 0x55;
1119 		cn_oid[2] = 4;
1120 		cn_oid[3] = 3;
1121 		cn.oid = cn_oid;
1122 		cn.buf = cn_buf;
1123 
1124 		for (u = 0; u < num; u ++) {
1125 			cn.len = sizeof(cn_buf);
1126 			if ((pk = verify_signer_xcs(&xcs[u], 1, &cn, 1, &trust_anchors)) != NULL) {
1127 				free_cert_contents(&xcs[u]);
1128 				once++;
1129 				printf("Testing verify certificate: %s\tPassed\n",
1130 				    cn.status ? cn_buf : "");
1131 				xfreepkey(pk);
1132 			}
1133 		}
1134 		if (!once)
1135 			printf("Testing verify certificate:\t\t\tFailed\n");
1136 		xfree(xcs);
1137 	}
1138 #endif	/* VERIFY_CERTS_STR */
1139 #ifdef VE_OPENPGP_SUPPORT
1140 	if (!openpgp_self_tests())
1141 		once++;
1142 #endif
1143 	return (once);
1144 }
1145