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