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