xref: /openbsd-src/lib/libcrypto/x509/x509_verify.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /* $OpenBSD: x509_verify.c,v 1.59 2022/06/28 16:05:42 beck Exp $ */
2 /*
3  * Copyright (c) 2020-2021 Bob Beck <beck@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /* x509_verify - inspired by golang's crypto/x509.Verify */
19 
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <time.h>
24 #include <unistd.h>
25 
26 #include <openssl/safestack.h>
27 #include <openssl/x509.h>
28 #include <openssl/x509v3.h>
29 
30 #include "x509_internal.h"
31 #include "x509_issuer_cache.h"
32 
33 static int x509_verify_cert_valid(struct x509_verify_ctx *ctx, X509 *cert,
34     struct x509_verify_chain *current_chain);
35 static int x509_verify_cert_hostname(struct x509_verify_ctx *ctx, X509 *cert,
36     char *name);
37 static void x509_verify_build_chains(struct x509_verify_ctx *ctx, X509 *cert,
38     struct x509_verify_chain *current_chain, int full_chain, char *name);
39 static int x509_verify_cert_error(struct x509_verify_ctx *ctx, X509 *cert,
40     size_t depth, int error, int ok);
41 static void x509_verify_chain_free(struct x509_verify_chain *chain);
42 
43 /*
44  * Parse an asn1 to a representable time_t as per RFC 5280 rules.
45  * Returns -1 if that can't be done for any reason.
46  */
47 time_t
48 x509_verify_asn1_time_to_time_t(const ASN1_TIME *atime, int notAfter)
49 {
50 	struct tm tm = { 0 };
51 	int type;
52 
53 	type = ASN1_time_parse(atime->data, atime->length, &tm, atime->type);
54 	if (type == -1)
55 		return -1;
56 
57 	/* RFC 5280 section 4.1.2.5 */
58 	if (tm.tm_year < 150 && type != V_ASN1_UTCTIME)
59 		return -1;
60 	if (tm.tm_year >= 150 && type != V_ASN1_GENERALIZEDTIME)
61 		return -1;
62 
63 	if (notAfter) {
64 		/*
65 		 * If we are a completely broken operating system with a
66 		 * 32 bit time_t, and we have been told this is a notAfter
67 		 * date, limit the date to a 32 bit representable value.
68 		 */
69 		if (!ASN1_time_tm_clamp_notafter(&tm))
70 			return -1;
71 	}
72 
73 	/*
74 	 * Defensively fail if the time string is not representable as
75 	 * a time_t. A time_t must be sane if you care about times after
76 	 * Jan 19 2038.
77 	 */
78 	return timegm(&tm);
79 }
80 
81 /*
82  * Cache certificate hash, and values parsed out of an X509.
83  * called from cache_extensions()
84  */
85 void
86 x509_verify_cert_info_populate(X509 *cert)
87 {
88 	/*
89 	 * Parse and save the cert times, or remember that they
90 	 * are unacceptable/unparsable.
91 	 */
92 	cert->not_before = x509_verify_asn1_time_to_time_t(X509_get_notBefore(cert), 0);
93 	cert->not_after = x509_verify_asn1_time_to_time_t(X509_get_notAfter(cert), 1);
94 }
95 
96 struct x509_verify_chain *
97 x509_verify_chain_new(void)
98 {
99 	struct x509_verify_chain *chain;
100 
101 	if ((chain = calloc(1, sizeof(*chain))) == NULL)
102 		goto err;
103 	if ((chain->certs = sk_X509_new_null()) == NULL)
104 		goto err;
105 	if ((chain->cert_errors = calloc(X509_VERIFY_MAX_CHAIN_CERTS,
106 	    sizeof(int))) == NULL)
107 		goto err;
108 	if ((chain->names =
109 	    x509_constraints_names_new(X509_VERIFY_MAX_CHAIN_NAMES)) == NULL)
110 		goto err;
111 
112 	return chain;
113  err:
114 	x509_verify_chain_free(chain);
115 	return NULL;
116 }
117 
118 static void
119 x509_verify_chain_clear(struct x509_verify_chain *chain)
120 {
121 	sk_X509_pop_free(chain->certs, X509_free);
122 	chain->certs = NULL;
123 	free(chain->cert_errors);
124 	chain->cert_errors = NULL;
125 	x509_constraints_names_free(chain->names);
126 	chain->names = NULL;
127 }
128 
129 static void
130 x509_verify_chain_free(struct x509_verify_chain *chain)
131 {
132 	if (chain == NULL)
133 		return;
134 	x509_verify_chain_clear(chain);
135 	free(chain);
136 }
137 
138 static struct x509_verify_chain *
139 x509_verify_chain_dup(struct x509_verify_chain *chain)
140 {
141 	struct x509_verify_chain *new_chain;
142 
143 	if ((new_chain = calloc(1, sizeof(*chain))) == NULL)
144 		goto err;
145 	if ((new_chain->certs = X509_chain_up_ref(chain->certs)) == NULL)
146 		goto err;
147 	if ((new_chain->cert_errors = calloc(X509_VERIFY_MAX_CHAIN_CERTS,
148 	    sizeof(int))) == NULL)
149 		goto err;
150 	memcpy(new_chain->cert_errors, chain->cert_errors,
151 	    X509_VERIFY_MAX_CHAIN_CERTS * sizeof(int));
152 	if ((new_chain->names =
153 	    x509_constraints_names_dup(chain->names)) == NULL)
154 		goto err;
155 	return(new_chain);
156  err:
157 	x509_verify_chain_free(new_chain);
158 	return NULL;
159 }
160 
161 static int
162 x509_verify_chain_append(struct x509_verify_chain *chain, X509 *cert,
163     int *error)
164 {
165 	int verify_err = X509_V_ERR_UNSPECIFIED;
166 	size_t idx;
167 
168 	if (!x509_constraints_extract_names(chain->names, cert,
169 	    sk_X509_num(chain->certs) == 0, &verify_err)) {
170 		*error = verify_err;
171 		return 0;
172 	}
173 
174 	X509_up_ref(cert);
175 	if (!sk_X509_push(chain->certs, cert)) {
176 		X509_free(cert);
177 		*error = X509_V_ERR_OUT_OF_MEM;
178 		return 0;
179 	}
180 
181 	idx = sk_X509_num(chain->certs) - 1;
182 	chain->cert_errors[idx] = *error;
183 
184 	/*
185 	 * We've just added the issuer for the previous certificate,
186 	 * clear its error if appropriate.
187 	 */
188 	if (idx > 1 && chain->cert_errors[idx - 1] ==
189 	    X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
190 		chain->cert_errors[idx - 1] = X509_V_OK;
191 
192 	return 1;
193 }
194 
195 static X509 *
196 x509_verify_chain_last(struct x509_verify_chain *chain)
197 {
198 	int last;
199 
200 	if (chain->certs == NULL)
201 		return NULL;
202 	if ((last = sk_X509_num(chain->certs) - 1) < 0)
203 		return NULL;
204 	return sk_X509_value(chain->certs, last);
205 }
206 
207 X509 *
208 x509_verify_chain_leaf(struct x509_verify_chain *chain)
209 {
210 	if (chain->certs == NULL)
211 		return NULL;
212 	return sk_X509_value(chain->certs, 0);
213 }
214 
215 static void
216 x509_verify_ctx_reset(struct x509_verify_ctx *ctx)
217 {
218 	size_t i;
219 
220 	for (i = 0; i < ctx->chains_count; i++)
221 		x509_verify_chain_free(ctx->chains[i]);
222 	sk_X509_pop_free(ctx->saved_error_chain, X509_free);
223 	ctx->saved_error = 0;
224 	ctx->saved_error_depth = 0;
225 	ctx->error = 0;
226 	ctx->error_depth = 0;
227 	ctx->chains_count = 0;
228 	ctx->sig_checks = 0;
229 	ctx->check_time = NULL;
230 }
231 
232 static void
233 x509_verify_ctx_clear(struct x509_verify_ctx *ctx)
234 {
235 	x509_verify_ctx_reset(ctx);
236 	sk_X509_pop_free(ctx->intermediates, X509_free);
237 	free(ctx->chains);
238 
239 }
240 
241 static int
242 x509_verify_cert_cache_extensions(X509 *cert)
243 {
244 	if (!(cert->ex_flags & EXFLAG_SET)) {
245 		CRYPTO_w_lock(CRYPTO_LOCK_X509);
246 		x509v3_cache_extensions(cert);
247 		CRYPTO_w_unlock(CRYPTO_LOCK_X509);
248 	}
249 	if (cert->ex_flags & EXFLAG_INVALID)
250 		return 0;
251 
252 	return (cert->ex_flags & EXFLAG_SET);
253 }
254 
255 static int
256 x509_verify_cert_self_signed(X509 *cert)
257 {
258 	return (cert->ex_flags & EXFLAG_SS) ? 1 : 0;
259 }
260 
261 /* XXX beck - clean up this mess of is_root */
262 static int
263 x509_verify_check_chain_end(X509 *cert, int full_chain)
264 {
265 	if (full_chain)
266 		return x509_verify_cert_self_signed(cert);
267 	return 1;
268 }
269 
270 static int
271 x509_verify_check_legacy_chain_end(struct x509_verify_ctx *ctx, X509 *cert,
272     int full_chain)
273 {
274 	if (X509_check_trust(cert, ctx->xsc->param->trust, 0) !=
275 	    X509_TRUST_TRUSTED)
276 		return 0;
277 	return x509_verify_check_chain_end(cert, full_chain);
278 }
279 
280 static int
281 x509_verify_ctx_cert_is_root(struct x509_verify_ctx *ctx, X509 *cert,
282     int full_chain)
283 {
284 	X509 *match = NULL;
285 	int i;
286 
287 	if (!x509_verify_cert_cache_extensions(cert))
288 		return 0;
289 
290 	/* Check by lookup if we have a legacy xsc */
291 	if (ctx->xsc != NULL) {
292 		if ((match = x509_vfy_lookup_cert_match(ctx->xsc,
293 		    cert)) != NULL) {
294 			X509_free(match);
295 			return x509_verify_check_legacy_chain_end(ctx, cert,
296 			    full_chain);
297 
298 		}
299 	} else {
300 		/* Check the provided roots */
301 		for (i = 0; i < sk_X509_num(ctx->roots); i++) {
302 			if (X509_cmp(sk_X509_value(ctx->roots, i), cert) == 0)
303 				return x509_verify_check_chain_end(cert,
304 				    full_chain);
305 		}
306 	}
307 
308 	return 0;
309 }
310 
311 static int
312 x509_verify_ctx_set_xsc_chain(struct x509_verify_ctx *ctx,
313     struct x509_verify_chain *chain, int set_error, int is_trusted)
314 {
315 	size_t num_untrusted;
316 	int i;
317 
318 	if (ctx->xsc == NULL)
319 		return 1;
320 
321 	/*
322 	 * XXX num_untrusted is the number of untrusted certs at the
323 	 * bottom of the chain. This works now since we stop at the first
324 	 * trusted cert. This will need fixing once we allow more than one
325 	 * trusted certificate.
326 	 */
327 	num_untrusted = sk_X509_num(chain->certs);
328 	if (is_trusted && num_untrusted > 0)
329 		num_untrusted--;
330 	ctx->xsc->num_untrusted = num_untrusted;
331 
332 	sk_X509_pop_free(ctx->xsc->chain, X509_free);
333 	ctx->xsc->chain = X509_chain_up_ref(chain->certs);
334 	if (ctx->xsc->chain == NULL)
335 		return x509_verify_cert_error(ctx, NULL, 0,
336 		    X509_V_ERR_OUT_OF_MEM, 0);
337 
338 	if (set_error) {
339 		ctx->xsc->error = X509_V_OK;
340 		ctx->xsc->error_depth = 0;
341 		for (i = 0; i < sk_X509_num(chain->certs); i++) {
342 			if (chain->cert_errors[i] != X509_V_OK) {
343 				ctx->xsc->error = chain->cert_errors[i];
344 				ctx->xsc->error_depth = i;
345 				break;
346 			}
347 		}
348 	}
349 
350 	return 1;
351 }
352 
353 
354 /*
355  * Save the error state and unvalidated chain off of the xsc for
356  * later.
357  */
358 static int
359 x509_verify_ctx_save_xsc_error(struct x509_verify_ctx *ctx)
360 {
361 	if (ctx->xsc != NULL && ctx->xsc->chain != NULL) {
362 		sk_X509_pop_free(ctx->saved_error_chain, X509_free);
363 		ctx->saved_error_chain = X509_chain_up_ref(ctx->xsc->chain);
364 		if (ctx->saved_error_chain == NULL)
365 			return x509_verify_cert_error(ctx, NULL, 0,
366 			    X509_V_ERR_OUT_OF_MEM, 0);
367 		ctx->saved_error = ctx->xsc->error;
368 		ctx->saved_error_depth = ctx->xsc->error_depth;
369 	}
370 	return 1;
371 }
372 
373 /*
374  * Restore the saved error state and unvalidated chain to the xsc
375  * if we do not have a validated chain.
376  */
377 static int
378 x509_verify_ctx_restore_xsc_error(struct x509_verify_ctx *ctx)
379 {
380 	if (ctx->xsc != NULL && ctx->chains_count == 0 &&
381 	    ctx->saved_error_chain != NULL) {
382 		sk_X509_pop_free(ctx->xsc->chain, X509_free);
383 		ctx->xsc->chain = X509_chain_up_ref(ctx->saved_error_chain);
384 		if (ctx->xsc->chain == NULL)
385 			return x509_verify_cert_error(ctx, NULL, 0,
386 			    X509_V_ERR_OUT_OF_MEM, 0);
387 		ctx->xsc->error = ctx->saved_error;
388 		ctx->xsc->error_depth = ctx->saved_error_depth;
389 	}
390 	return 1;
391 }
392 
393 /* Perform legacy style validation of a chain */
394 static int
395 x509_verify_ctx_validate_legacy_chain(struct x509_verify_ctx *ctx,
396     struct x509_verify_chain *chain, size_t depth)
397 {
398 	int ret = 0, trust;
399 
400 	if (ctx->xsc == NULL)
401 		return 1;
402 
403 	/*
404 	 * If we have a legacy xsc, choose a validated chain, and
405 	 * apply the extensions, revocation, and policy checks just
406 	 * like the legacy code did. We do this here instead of as
407 	 * building the chains to more easily support the callback and
408 	 * the bewildering array of VERIFY_PARAM knobs that are there
409 	 * for the fiddling.
410 	 */
411 
412 	/* These may be set in one of the following calls. */
413 	ctx->xsc->error = X509_V_OK;
414 	ctx->xsc->error_depth = 0;
415 
416 	if (!x509_verify_ctx_set_xsc_chain(ctx, chain, 0, 1))
417 		goto err;
418 
419 	/*
420 	 * Call the legacy code to walk the chain and check trust
421 	 * in the legacy way to handle partial chains and get the
422 	 * callback fired correctly.
423 	 */
424 	trust = x509_vfy_check_trust(ctx->xsc);
425 	if (trust == X509_TRUST_REJECTED)
426 		goto err; /* callback was called in x509_vfy_check_trust */
427 	if (trust != X509_TRUST_TRUSTED) {
428 		/* NOTREACHED */
429 		goto err;  /* should not happen if we get in here - abort? */
430 	}
431 
432 	/*
433 	 * XXX currently this duplicates some work done in chain
434 	 * build, but we keep it here until we have feature parity
435 	 */
436 	if (!x509_vfy_check_chain_extensions(ctx->xsc))
437 		goto err;
438 
439 #ifndef OPENSSL_NO_RFC3779
440 	if (!X509v3_asid_validate_path(ctx->xsc))
441 		goto err;
442 
443 	if (!X509v3_addr_validate_path(ctx->xsc))
444 		goto err;
445 #endif
446 
447 	if (!x509_vfy_check_security_level(ctx->xsc))
448 		goto err;
449 
450 	if (!x509_constraints_chain(ctx->xsc->chain,
451 		&ctx->xsc->error, &ctx->xsc->error_depth)) {
452 		X509 *cert = sk_X509_value(ctx->xsc->chain, depth);
453 		if (!x509_verify_cert_error(ctx, cert,
454 			ctx->xsc->error_depth, ctx->xsc->error, 0))
455 			goto err;
456 	}
457 
458 	if (!x509_vfy_check_revocation(ctx->xsc))
459 		goto err;
460 
461 	if (!x509_vfy_check_policy(ctx->xsc))
462 		goto err;
463 
464 	ret = 1;
465 
466  err:
467 	/*
468 	 * The above checks may have set ctx->xsc->error and
469 	 * ctx->xsc->error_depth - save these for later on.
470 	 */
471 	if (ctx->xsc->error != X509_V_OK) {
472 		if (ctx->xsc->error_depth < 0 ||
473 		    ctx->xsc->error_depth >= X509_VERIFY_MAX_CHAIN_CERTS)
474 			return 0;
475 		chain->cert_errors[ctx->xsc->error_depth] =
476 		    ctx->xsc->error;
477 		ctx->error_depth = ctx->xsc->error_depth;
478 	}
479 
480 	return ret;
481 }
482 
483 /* Add a validated chain to our list of valid chains */
484 static int
485 x509_verify_ctx_add_chain(struct x509_verify_ctx *ctx,
486     struct x509_verify_chain *chain, char *name)
487 {
488 	size_t depth;
489 	X509 *last = x509_verify_chain_last(chain);
490 	X509 *leaf = x509_verify_chain_leaf(chain);
491 
492 	depth = sk_X509_num(chain->certs);
493 	if (depth > 0)
494 		depth--;
495 
496 	if (ctx->chains_count >= ctx->max_chains)
497 		return x509_verify_cert_error(ctx, last, depth,
498 		    X509_V_ERR_CERT_CHAIN_TOO_LONG, 0);
499 
500 	/* Clear a get issuer failure for a root certificate. */
501 	if (chain->cert_errors[depth] ==
502 	    X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
503 		chain->cert_errors[depth] = X509_V_OK;
504 
505 	if (!x509_verify_ctx_validate_legacy_chain(ctx, chain, depth))
506 		return 0;
507 
508 	/*
509 	 * In the non-legacy code, extensions and purpose are dealt
510 	 * with as the chain is built.
511 	 *
512 	 * The non-legacy api returns multiple chains but does not do
513 	 * any revocation checking (it must be done by the caller on
514 	 * any chain they wish to use)
515 	 */
516 
517 	if ((ctx->chains[ctx->chains_count] = x509_verify_chain_dup(chain)) ==
518 	    NULL) {
519 		return x509_verify_cert_error(ctx, last, depth,
520 		    X509_V_ERR_OUT_OF_MEM, 0);
521 	}
522 
523 	if (!x509_verify_cert_valid(ctx, leaf, NULL))
524 		return 0;
525 
526 	if (!x509_verify_cert_hostname(ctx, leaf, name))
527 		return 0;
528 
529 	ctx->chains_count++;
530 	ctx->error = X509_V_OK;
531 	ctx->error_depth = depth;
532 	return 1;
533 }
534 
535 static int
536 x509_verify_potential_parent(struct x509_verify_ctx *ctx, X509 *parent,
537     X509 *child)
538 {
539 	if (!x509_verify_cert_cache_extensions(parent))
540 		return 0;
541 	if (ctx->xsc != NULL)
542 		return (ctx->xsc->check_issued(ctx->xsc, child, parent));
543 
544 	/* XXX key usage */
545 	return X509_check_issued(child, parent) != X509_V_OK;
546 }
547 
548 static int
549 x509_verify_parent_signature(X509 *parent, X509 *child, int *error)
550 {
551 	EVP_PKEY *pkey;
552 	int cached;
553 	int ret = 0;
554 
555 	/* Use cached value if we have it */
556 	if ((cached = x509_issuer_cache_find(parent->hash, child->hash)) >= 0)
557 		return cached;
558 
559 	/* Check signature. Did parent sign child? */
560 	if ((pkey = X509_get_pubkey(parent)) == NULL) {
561 		*error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
562 		return 0;
563 	}
564 	if (X509_verify(child, pkey) <= 0)
565 		*error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
566 	else
567 		ret = 1;
568 
569 	/* Add result to cache */
570 	x509_issuer_cache_add(parent->hash, child->hash, ret);
571 
572 	EVP_PKEY_free(pkey);
573 
574 	return ret;
575 }
576 
577 static int
578 x509_verify_consider_candidate(struct x509_verify_ctx *ctx, X509 *cert,
579     int is_root_cert, X509 *candidate, struct x509_verify_chain *current_chain,
580     int full_chain, char *name)
581 {
582 	int depth = sk_X509_num(current_chain->certs);
583 	struct x509_verify_chain *new_chain;
584 	int i;
585 
586 	/* Fail if the certificate is already in the chain */
587 	for (i = 0; i < sk_X509_num(current_chain->certs); i++) {
588 		if (X509_cmp(sk_X509_value(current_chain->certs, i),
589 		    candidate) == 0)
590 			return 0;
591 	}
592 
593 	if (ctx->sig_checks++ > X509_VERIFY_MAX_SIGCHECKS) {
594 		/* don't allow callback to override safety check */
595 		(void) x509_verify_cert_error(ctx, candidate, depth,
596 		    X509_V_ERR_CERT_CHAIN_TOO_LONG, 0);
597 		return 0;
598 	}
599 
600 	if (!x509_verify_parent_signature(candidate, cert, &ctx->error)) {
601 		if (!x509_verify_cert_error(ctx, candidate, depth,
602 		    ctx->error, 0))
603 			return 0;
604 	}
605 
606 	if (!x509_verify_cert_valid(ctx, candidate, current_chain))
607 		return 0;
608 
609 	/* candidate is good, add it to a copy of the current chain */
610 	if ((new_chain = x509_verify_chain_dup(current_chain)) == NULL) {
611 		x509_verify_cert_error(ctx, candidate, depth,
612 		    X509_V_ERR_OUT_OF_MEM, 0);
613 		return 0;
614 	}
615 	if (!x509_verify_chain_append(new_chain, candidate, &ctx->error)) {
616 		x509_verify_cert_error(ctx, candidate, depth, ctx->error, 0);
617 		x509_verify_chain_free(new_chain);
618 		return 0;
619 	}
620 
621 	/*
622 	 * If candidate is a trusted root, we have a validated chain,
623 	 * so we save it.  Otherwise, recurse until we find a root or
624 	 * give up.
625 	 */
626 	if (is_root_cert) {
627 		if (!x509_verify_ctx_set_xsc_chain(ctx, new_chain, 0, 1)) {
628 			x509_verify_chain_free(new_chain);
629 			return 0;
630 		}
631 		if (!x509_verify_ctx_add_chain(ctx, new_chain, name)) {
632 			x509_verify_chain_free(new_chain);
633 			return 0;
634 		}
635 		goto done;
636 	}
637 
638 	x509_verify_build_chains(ctx, candidate, new_chain, full_chain, name);
639 
640  done:
641 	x509_verify_chain_free(new_chain);
642 	return 1;
643 }
644 
645 static int
646 x509_verify_cert_error(struct x509_verify_ctx *ctx, X509 *cert, size_t depth,
647     int error, int ok)
648 {
649 	ctx->error = error;
650 	ctx->error_depth = depth;
651 	if (ctx->xsc != NULL) {
652 		ctx->xsc->error = error;
653 		ctx->xsc->error_depth = depth;
654 		ctx->xsc->current_cert = cert;
655 		return ctx->xsc->verify_cb(ok, ctx->xsc);
656 	}
657 	return ok;
658 }
659 
660 static void
661 x509_verify_build_chains(struct x509_verify_ctx *ctx, X509 *cert,
662     struct x509_verify_chain *current_chain, int full_chain, char *name)
663 {
664 	X509 *candidate;
665 	int i, depth, count, ret, is_root;
666 
667 	/*
668 	 * If we are finding chains with an xsc, just stop after we have
669 	 * one chain, there's no point in finding more, it just exercises
670 	 * the potentially buggy callback processing in the calling software.
671 	 */
672 	if (ctx->xsc != NULL && ctx->chains_count > 0)
673 		return;
674 
675 	depth = sk_X509_num(current_chain->certs);
676 	if (depth > 0)
677 		depth--;
678 
679 	if (depth >= ctx->max_depth &&
680 	    !x509_verify_cert_error(ctx, cert, depth,
681 		X509_V_ERR_CERT_CHAIN_TOO_LONG, 0))
682 		return;
683 
684 	count = ctx->chains_count;
685 
686 	ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
687 	ctx->error_depth = depth;
688 
689 	if (ctx->saved_error != 0)
690 		ctx->error = ctx->saved_error;
691 	if (ctx->saved_error_depth != 0)
692 		ctx->error_depth = ctx->saved_error_depth;
693 
694 	if (ctx->xsc != NULL) {
695 		/*
696 		 * Long ago experiments at Muppet labs resulted in a
697 		 * situation where software not only sees these errors
698 		 * but forced developers to expect them in certain cases.
699 		 * so we must mimic this awfulness for the legacy case.
700 		 */
701 		if (cert->ex_flags & EXFLAG_SS)
702 			ctx->error = (depth == 0) ?
703 			    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
704 			    X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
705 	}
706 
707 	/* Check for legacy mode roots */
708 	if (ctx->xsc != NULL) {
709 		if ((ret = ctx->xsc->get_issuer(&candidate, ctx->xsc, cert)) < 0) {
710 			x509_verify_cert_error(ctx, cert, depth,
711 			    X509_V_ERR_STORE_LOOKUP, 0);
712 			return;
713 		}
714 		if (ret > 0) {
715 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
716 				is_root = x509_verify_check_legacy_chain_end(
717 				    ctx, candidate, full_chain);
718 				x509_verify_consider_candidate(ctx, cert,
719 				    is_root, candidate, current_chain,
720 				    full_chain, name);
721 			}
722 			X509_free(candidate);
723 		}
724 	} else {
725 		/* Check to see if we have a trusted root issuer. */
726 		for (i = 0; i < sk_X509_num(ctx->roots); i++) {
727 			candidate = sk_X509_value(ctx->roots, i);
728 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
729 				is_root = x509_verify_check_chain_end(candidate,
730 				    full_chain);
731 				x509_verify_consider_candidate(ctx, cert,
732 				    is_root, candidate, current_chain,
733 				    full_chain, name);
734 			}
735 		}
736 	}
737 
738 	/* Check intermediates after checking roots */
739 	if (ctx->intermediates != NULL) {
740 		for (i = 0; i < sk_X509_num(ctx->intermediates); i++) {
741 			candidate = sk_X509_value(ctx->intermediates, i);
742 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
743 				x509_verify_consider_candidate(ctx, cert,
744 				    0, candidate, current_chain,
745 				    full_chain, name);
746 			}
747 		}
748 	}
749 
750 	if (ctx->chains_count > count) {
751 		if (ctx->xsc != NULL) {
752 			ctx->xsc->error = X509_V_OK;
753 			ctx->xsc->error_depth = depth;
754 			ctx->xsc->current_cert = cert;
755 		}
756 	} else if (ctx->error_depth == depth) {
757 		if (!x509_verify_ctx_set_xsc_chain(ctx, current_chain, 0, 0))
758 			return;
759 	}
760 }
761 
762 static int
763 x509_verify_cert_hostname(struct x509_verify_ctx *ctx, X509 *cert, char *name)
764 {
765 	char *candidate;
766 	size_t len;
767 
768 	if (name == NULL) {
769 		if (ctx->xsc != NULL) {
770 			int ret;
771 
772 			if ((ret = x509_vfy_check_id(ctx->xsc)) == 0)
773 				ctx->error = ctx->xsc->error;
774 			return ret;
775 		}
776 		return 1;
777 	}
778 	if ((candidate = strdup(name)) == NULL) {
779 		ctx->error = X509_V_ERR_OUT_OF_MEM;
780 		goto err;
781 	}
782 	if ((len = strlen(candidate)) < 1) {
783 		ctx->error = X509_V_ERR_UNSPECIFIED; /* XXX */
784 		goto err;
785 	}
786 
787 	/* IP addresses may be written in [ ]. */
788 	if (candidate[0] == '[' && candidate[len - 1] == ']') {
789 		candidate[len - 1] = '\0';
790 		if (X509_check_ip_asc(cert, candidate + 1, 0) <= 0) {
791 			ctx->error = X509_V_ERR_IP_ADDRESS_MISMATCH;
792 			goto err;
793 		}
794 	} else {
795 		int flags = 0;
796 
797 		if (ctx->xsc == NULL)
798 			flags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
799 
800 		if (X509_check_host(cert, candidate, len, flags, NULL) <= 0) {
801 			ctx->error = X509_V_ERR_HOSTNAME_MISMATCH;
802 			goto err;
803 		}
804 	}
805 	free(candidate);
806 	return 1;
807  err:
808 	free(candidate);
809 	return x509_verify_cert_error(ctx, cert, 0, ctx->error, 0);
810 }
811 
812 static int
813 x509_verify_set_check_time(struct x509_verify_ctx *ctx)
814 {
815 	if (ctx->xsc != NULL)  {
816 		if (ctx->xsc->param->flags & X509_V_FLAG_USE_CHECK_TIME) {
817 			ctx->check_time = &ctx->xsc->param->check_time;
818 			return 1;
819 		}
820 		if (ctx->xsc->param->flags & X509_V_FLAG_NO_CHECK_TIME)
821 			return 0;
822 	}
823 
824 	ctx->check_time = NULL;
825 	return 1;
826 }
827 
828 static int
829 x509_verify_cert_times(X509 *cert, time_t *cmp_time, int *error)
830 {
831 	time_t when;
832 
833 	if (cmp_time == NULL)
834 		when = time(NULL);
835 	else
836 		when = *cmp_time;
837 
838 	if (cert->not_before == -1) {
839 		*error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
840 		return 0;
841 	}
842 	if (when < cert->not_before) {
843 		*error = X509_V_ERR_CERT_NOT_YET_VALID;
844 		return 0;
845 	}
846 	if (cert->not_after == -1) {
847 		*error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
848 		return 0;
849 	}
850 	if (when > cert->not_after) {
851 		*error = X509_V_ERR_CERT_HAS_EXPIRED;
852 		return 0;
853 	}
854 
855 	return 1;
856 }
857 
858 static int
859 x509_verify_validate_constraints(X509 *cert,
860     struct x509_verify_chain *current_chain, int *error)
861 {
862 	struct x509_constraints_names *excluded = NULL;
863 	struct x509_constraints_names *permitted = NULL;
864 	int err = X509_V_ERR_UNSPECIFIED;
865 
866 	if (current_chain == NULL)
867 		return 1;
868 
869 	if (cert->nc != NULL) {
870 		if ((permitted = x509_constraints_names_new(
871 		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
872 			err = X509_V_ERR_OUT_OF_MEM;
873 			goto err;
874 		}
875 		if ((excluded = x509_constraints_names_new(
876 		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
877 			err = X509_V_ERR_OUT_OF_MEM;
878 			goto err;
879 		}
880 		if (!x509_constraints_extract_constraints(cert,
881 		    permitted, excluded, &err))
882 			goto err;
883 		if (!x509_constraints_check(current_chain->names,
884 		    permitted, excluded, &err))
885 			goto err;
886 		x509_constraints_names_free(excluded);
887 		x509_constraints_names_free(permitted);
888 	}
889 
890 	return 1;
891  err:
892 	*error = err;
893 	x509_constraints_names_free(excluded);
894 	x509_constraints_names_free(permitted);
895 	return 0;
896 }
897 
898 static int
899 x509_verify_cert_extensions(struct x509_verify_ctx *ctx, X509 *cert, int need_ca)
900 {
901 	if (!x509_verify_cert_cache_extensions(cert)) {
902 		ctx->error = X509_V_ERR_UNSPECIFIED;
903 		return 0;
904 	}
905 
906 	if (ctx->xsc != NULL)
907 		return 1;	/* legacy is checked after chain is built */
908 
909 	if (cert->ex_flags & EXFLAG_CRITICAL) {
910 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
911 		return 0;
912 	}
913 	/* No we don't care about v1, netscape, and other ancient silliness */
914 	if (need_ca && (!(cert->ex_flags & EXFLAG_BCONS) &&
915 	    (cert->ex_flags & EXFLAG_CA))) {
916 		ctx->error = X509_V_ERR_INVALID_CA;
917 		return 0;
918 	}
919 	if (ctx->purpose > 0 && X509_check_purpose(cert, ctx->purpose, need_ca)) {
920 		ctx->error = X509_V_ERR_INVALID_PURPOSE;
921 		return 0;
922 	}
923 
924 	/* XXX support proxy certs later in new api */
925 	if (ctx->xsc == NULL && cert->ex_flags & EXFLAG_PROXY) {
926 		ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
927 		return 0;
928 	}
929 
930 	return 1;
931 }
932 
933 /* Validate that cert is a possible candidate to append to current_chain */
934 static int
935 x509_verify_cert_valid(struct x509_verify_ctx *ctx, X509 *cert,
936     struct x509_verify_chain *current_chain)
937 {
938 	X509 *issuer_candidate;
939 	int should_be_ca = current_chain != NULL;
940 	size_t depth = 0;
941 
942 	if (current_chain != NULL)
943 		depth = sk_X509_num(current_chain->certs);
944 
945 	if (!x509_verify_cert_extensions(ctx, cert, should_be_ca))
946 		return 0;
947 
948 	if (should_be_ca) {
949 		issuer_candidate = x509_verify_chain_last(current_chain);
950 		if (issuer_candidate != NULL &&
951 		    !X509_check_issued(issuer_candidate, cert))
952 			if (!x509_verify_cert_error(ctx, cert, depth,
953 			    X509_V_ERR_SUBJECT_ISSUER_MISMATCH, 0))
954 				return 0;
955 	}
956 
957 	if (x509_verify_set_check_time(ctx)) {
958 		if (!x509_verify_cert_times(cert, ctx->check_time,
959 		    &ctx->error)) {
960 			if (!x509_verify_cert_error(ctx, cert, depth,
961 			    ctx->error, 0))
962 				return 0;
963 		}
964 	}
965 
966 	if (!x509_verify_validate_constraints(cert, current_chain,
967 	    &ctx->error) && !x509_verify_cert_error(ctx, cert, depth,
968 	    ctx->error, 0))
969 		return 0;
970 
971 	return 1;
972 }
973 
974 struct x509_verify_ctx *
975 x509_verify_ctx_new_from_xsc(X509_STORE_CTX *xsc)
976 {
977 	struct x509_verify_ctx *ctx;
978 	size_t max_depth;
979 
980 	if (xsc == NULL)
981 		return NULL;
982 
983 	if ((ctx = x509_verify_ctx_new(NULL)) == NULL)
984 		return NULL;
985 
986 	ctx->xsc = xsc;
987 
988 	if (xsc->untrusted &&
989 	    (ctx->intermediates = X509_chain_up_ref(xsc->untrusted)) == NULL)
990 		goto err;
991 
992 	max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
993 	if (xsc->param->depth > 0 && xsc->param->depth < X509_VERIFY_MAX_CHAIN_CERTS)
994 		max_depth = xsc->param->depth;
995 	if (!x509_verify_ctx_set_max_depth(ctx, max_depth))
996 		goto err;
997 
998 	return ctx;
999  err:
1000 	x509_verify_ctx_free(ctx);
1001 	return NULL;
1002 }
1003 
1004 /* Public API */
1005 
1006 struct x509_verify_ctx *
1007 x509_verify_ctx_new(STACK_OF(X509) *roots)
1008 {
1009 	struct x509_verify_ctx *ctx;
1010 
1011 	if ((ctx = calloc(1, sizeof(struct x509_verify_ctx))) == NULL)
1012 		return NULL;
1013 
1014 	if (roots != NULL) {
1015 		if  ((ctx->roots = X509_chain_up_ref(roots)) == NULL)
1016 			goto err;
1017 	} else {
1018 		if ((ctx->roots = sk_X509_new_null()) == NULL)
1019 			goto err;
1020 	}
1021 
1022 	ctx->max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
1023 	ctx->max_chains = X509_VERIFY_MAX_CHAINS;
1024 	ctx->max_sigs = X509_VERIFY_MAX_SIGCHECKS;
1025 
1026 	if ((ctx->chains = calloc(X509_VERIFY_MAX_CHAINS,
1027 	    sizeof(*ctx->chains))) == NULL)
1028 		goto err;
1029 
1030 	return ctx;
1031  err:
1032 	x509_verify_ctx_free(ctx);
1033 	return NULL;
1034 }
1035 
1036 void
1037 x509_verify_ctx_free(struct x509_verify_ctx *ctx)
1038 {
1039 	if (ctx == NULL)
1040 		return;
1041 	sk_X509_pop_free(ctx->roots, X509_free);
1042 	x509_verify_ctx_clear(ctx);
1043 	free(ctx);
1044 }
1045 
1046 int
1047 x509_verify_ctx_set_max_depth(struct x509_verify_ctx *ctx, size_t max)
1048 {
1049 	if (max < 1 || max > X509_VERIFY_MAX_CHAIN_CERTS)
1050 		return 0;
1051 	ctx->max_depth = max;
1052 	return 1;
1053 }
1054 
1055 int
1056 x509_verify_ctx_set_max_chains(struct x509_verify_ctx *ctx, size_t max)
1057 {
1058 	if (max < 1 || max > X509_VERIFY_MAX_CHAINS)
1059 		return 0;
1060 	ctx->max_chains = max;
1061 	return 1;
1062 }
1063 
1064 int
1065 x509_verify_ctx_set_max_signatures(struct x509_verify_ctx *ctx, size_t max)
1066 {
1067 	if (max < 1 || max > 100000)
1068 		return 0;
1069 	ctx->max_sigs = max;
1070 	return 1;
1071 }
1072 
1073 int
1074 x509_verify_ctx_set_purpose(struct x509_verify_ctx *ctx, int purpose)
1075 {
1076 	if (purpose < X509_PURPOSE_MIN || purpose > X509_PURPOSE_MAX)
1077 		return 0;
1078 	ctx->purpose = purpose;
1079 	return 1;
1080 }
1081 
1082 int
1083 x509_verify_ctx_set_intermediates(struct x509_verify_ctx *ctx,
1084     STACK_OF(X509) *intermediates)
1085 {
1086 	if ((ctx->intermediates = X509_chain_up_ref(intermediates)) == NULL)
1087 		return 0;
1088 	return 1;
1089 }
1090 
1091 const char *
1092 x509_verify_ctx_error_string(struct x509_verify_ctx *ctx)
1093 {
1094 	return X509_verify_cert_error_string(ctx->error);
1095 }
1096 
1097 size_t
1098 x509_verify_ctx_error_depth(struct x509_verify_ctx *ctx)
1099 {
1100 	return ctx->error_depth;
1101 }
1102 
1103 STACK_OF(X509) *
1104 x509_verify_ctx_chain(struct x509_verify_ctx *ctx, size_t i)
1105 {
1106 	if (i >= ctx->chains_count)
1107 		return NULL;
1108 	return ctx->chains[i]->certs;
1109 }
1110 
1111 size_t
1112 x509_verify(struct x509_verify_ctx *ctx, X509 *leaf, char *name)
1113 {
1114 	struct x509_verify_chain *current_chain;
1115 	int retry_chain_build, full_chain = 0;
1116 
1117 	if (ctx->roots == NULL || ctx->max_depth == 0) {
1118 		ctx->error = X509_V_ERR_INVALID_CALL;
1119 		goto err;
1120 	}
1121 
1122 	if (ctx->xsc != NULL) {
1123 		if (leaf != NULL || name != NULL) {
1124 			ctx->error = X509_V_ERR_INVALID_CALL;
1125 			goto err;
1126 		}
1127 		leaf = ctx->xsc->cert;
1128 
1129 		/* XXX */
1130 		full_chain = 1;
1131 		if (ctx->xsc->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
1132 			full_chain = 0;
1133 		/*
1134 		 * XXX
1135 		 * The legacy code expects the top level cert to be
1136 		 * there, even if we didn't find a chain. So put it
1137 		 * there, we will clobber it later if we find a valid
1138 		 * chain.
1139 		 */
1140 		if ((ctx->xsc->chain = sk_X509_new_null()) == NULL) {
1141 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1142 			goto err;
1143 		}
1144 		if (!X509_up_ref(leaf)) {
1145 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1146 			goto err;
1147 		}
1148 		if (!sk_X509_push(ctx->xsc->chain, leaf)) {
1149 			X509_free(leaf);
1150 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1151 			goto err;
1152 		}
1153 		ctx->xsc->error_depth = 0;
1154 		ctx->xsc->current_cert = leaf;
1155 	}
1156 
1157 	if ((current_chain = x509_verify_chain_new()) == NULL) {
1158 		ctx->error = X509_V_ERR_OUT_OF_MEM;
1159 		goto err;
1160 	}
1161 
1162 	/*
1163 	 * Add the leaf to the chain and try to build chains from it.
1164 	 * Note that unlike Go's verifier, we have not yet checked
1165 	 * anything about the leaf, This is intentional, so that we
1166 	 * report failures in chain building before we report problems
1167 	 * with the leaf.
1168 	 */
1169 	if (!x509_verify_chain_append(current_chain, leaf, &ctx->error)) {
1170 		x509_verify_chain_free(current_chain);
1171 		goto err;
1172 	}
1173 	do {
1174 		retry_chain_build = 0;
1175 		if (x509_verify_ctx_cert_is_root(ctx, leaf, full_chain)) {
1176 			if (!x509_verify_ctx_add_chain(ctx, current_chain,
1177 			    name)) {
1178 				x509_verify_chain_free(current_chain);
1179 				goto err;
1180 			}
1181 		} else {
1182 			x509_verify_build_chains(ctx, leaf, current_chain,
1183 			    full_chain, name);
1184 			if (full_chain && ctx->chains_count == 0) {
1185 				/*
1186 				 * Save the error state from the xsc
1187 				 * at this point to put back on the
1188 				 * xsc in case we do not find a chain
1189 				 * that is trusted but not a full
1190 				 * chain to a self signed root. This
1191 				 * is because the unvalidated chain is
1192 				 * used by the autochain batshittery
1193 				 * on failure and will be needed for
1194 				 * that.
1195 				 */
1196 				ctx->xsc->error_depth = ctx->error_depth;
1197 				if (!x509_verify_ctx_save_xsc_error(ctx)) {
1198 					x509_verify_chain_free(current_chain);
1199 					goto err;
1200 				}
1201 				full_chain = 0;
1202 				retry_chain_build = 1;
1203 			}
1204 		}
1205 	} while (retry_chain_build);
1206 
1207 	x509_verify_chain_free(current_chain);
1208 
1209 	/*
1210 	 * Do the new verifier style return, where we don't have an xsc
1211 	 * that allows a crazy callback to turn invalid things into valid.
1212 	 */
1213 	if (ctx->xsc == NULL) {
1214 		/*
1215 		 * Safety net:
1216 		 * We could not find a validated chain, and for some reason do not
1217 		 * have an error set.
1218 		 */
1219 		if (ctx->chains_count == 0 && ctx->error == X509_V_OK)
1220 			ctx->error = X509_V_ERR_UNSPECIFIED;
1221 
1222 		/*
1223 		 * If we are not using an xsc, and have no possibility for the
1224 		 * crazy OpenSSL callback API changing the results of
1225 		 * validation steps (because the callback can make validation
1226 		 * proceed in the presence of invalid certs), any chains we
1227 		 * have here are correctly built and verified.
1228 		 */
1229 		if (ctx->chains_count > 0)
1230 			ctx->error = X509_V_OK;
1231 
1232 		return ctx->chains_count;
1233 	}
1234 
1235 	/*
1236 	 * Otherwise we are doing compatibility with an xsc, which means that we
1237 	 * will have one chain, which might actually be a bogus chain because
1238 	 * the callback told us to ignore errors and proceed to build an invalid
1239 	 * chain. Possible return values from this include returning 1 with an
1240 	 * invalid chain and a value of xsc->error != X509_V_OK (It's tradition
1241 	 * that makes it ok).
1242 	 */
1243 
1244 	if (ctx->chains_count > 0) {
1245 		/*
1246 		 * The chain we have using an xsc might not be a verified chain
1247 		 * if the callback perverted things while we built it to ignore
1248 		 * failures and proceed with chain building. We put this chain
1249 		 * and the error associated with it on the xsc.
1250 		 */
1251 		if (!x509_verify_ctx_set_xsc_chain(ctx, ctx->chains[0], 1, 1))
1252 			goto err;
1253 
1254 		/*
1255 		 * Call the callback for completion up our built
1256 		 * chain. The callback could still tell us to
1257 		 * fail. Since this chain might exist as the result of
1258 		 * callback doing perversions, we could still return
1259 		 * "success" with something other than X509_V_OK set
1260 		 * as the error.
1261 		 */
1262 		if (!x509_vfy_callback_indicate_completion(ctx->xsc))
1263 			goto err;
1264 	} else {
1265 		/*
1266 		 * We did not find a chain. Bring back the failure
1267 		 * case we wanted to the xsc if we saved one. If we
1268 		 * did not we should have just the leaf on the xsc.
1269 		 */
1270 		if (!x509_verify_ctx_restore_xsc_error(ctx))
1271 			goto err;
1272 
1273 		/*
1274 		 * Safety net, ensure we have an error set in the
1275 		 * failing case.
1276 		 */
1277 		if (ctx->xsc->error == X509_V_OK) {
1278 			if (ctx->error == X509_V_OK)
1279 				ctx->error = X509_V_ERR_UNSPECIFIED;
1280 			ctx->xsc->error = ctx->error;
1281 		}
1282 
1283 		/*
1284 		 * Let the callback override the return value
1285 		 * at depth 0 if it chooses to
1286 		 */
1287 		return ctx->xsc->verify_cb(0, ctx->xsc);
1288 	}
1289 
1290 	/* We only ever find one chain in compat mode with an xsc. */
1291 	return 1;
1292 
1293  err:
1294 	if (ctx->error == X509_V_OK)
1295 		ctx->error = X509_V_ERR_UNSPECIFIED;
1296 
1297 	if (ctx->xsc != NULL) {
1298 		if (ctx->xsc->error == X509_V_OK)
1299 			ctx->xsc->error = X509_V_ERR_UNSPECIFIED;
1300 		ctx->error = ctx->xsc->error;
1301 	}
1302 
1303 	return 0;
1304 }
1305