1 /* $OpenBSD: x509_verify.c,v 1.60.2.1 2022/10/20 09:45:18 tb 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_ctx_cert_is_root(struct x509_verify_ctx *ctx, X509 *cert,
272     int full_chain)
273 {
274 	X509 *match = NULL;
275 	int i;
276 
277 	if (!x509_verify_cert_cache_extensions(cert))
278 		return 0;
279 
280 	/* Check by lookup if we have a legacy xsc */
281 	if (ctx->xsc != NULL) {
282 		if ((match = x509_vfy_lookup_cert_match(ctx->xsc,
283 		    cert)) != NULL) {
284 			X509_free(match);
285 			return x509_verify_check_chain_end(cert, full_chain);
286 
287 		}
288 	} else {
289 		/* Check the provided roots */
290 		for (i = 0; i < sk_X509_num(ctx->roots); i++) {
291 			if (X509_cmp(sk_X509_value(ctx->roots, i), cert) == 0)
292 				return x509_verify_check_chain_end(cert,
293 				    full_chain);
294 		}
295 	}
296 
297 	return 0;
298 }
299 
300 static int
301 x509_verify_ctx_set_xsc_chain(struct x509_verify_ctx *ctx,
302     struct x509_verify_chain *chain, int set_error, int is_trusted)
303 {
304 	size_t num_untrusted;
305 	int i;
306 
307 	if (ctx->xsc == NULL)
308 		return 1;
309 
310 	/*
311 	 * XXX num_untrusted is the number of untrusted certs at the
312 	 * bottom of the chain. This works now since we stop at the first
313 	 * trusted cert. This will need fixing once we allow more than one
314 	 * trusted certificate.
315 	 */
316 	num_untrusted = sk_X509_num(chain->certs);
317 	if (is_trusted && num_untrusted > 0)
318 		num_untrusted--;
319 	ctx->xsc->num_untrusted = num_untrusted;
320 
321 	sk_X509_pop_free(ctx->xsc->chain, X509_free);
322 	ctx->xsc->chain = X509_chain_up_ref(chain->certs);
323 	if (ctx->xsc->chain == NULL)
324 		return x509_verify_cert_error(ctx, NULL, 0,
325 		    X509_V_ERR_OUT_OF_MEM, 0);
326 
327 	if (set_error) {
328 		ctx->xsc->error = X509_V_OK;
329 		ctx->xsc->error_depth = 0;
330 		for (i = 0; i < sk_X509_num(chain->certs); i++) {
331 			if (chain->cert_errors[i] != X509_V_OK) {
332 				ctx->xsc->error = chain->cert_errors[i];
333 				ctx->xsc->error_depth = i;
334 				break;
335 			}
336 		}
337 	}
338 
339 	return 1;
340 }
341 
342 
343 /*
344  * Save the error state and unvalidated chain off of the xsc for
345  * later.
346  */
347 static int
348 x509_verify_ctx_save_xsc_error(struct x509_verify_ctx *ctx)
349 {
350 	if (ctx->xsc != NULL && ctx->xsc->chain != NULL) {
351 		sk_X509_pop_free(ctx->saved_error_chain, X509_free);
352 		ctx->saved_error_chain = X509_chain_up_ref(ctx->xsc->chain);
353 		if (ctx->saved_error_chain == NULL)
354 			return x509_verify_cert_error(ctx, NULL, 0,
355 			    X509_V_ERR_OUT_OF_MEM, 0);
356 		ctx->saved_error = ctx->xsc->error;
357 		ctx->saved_error_depth = ctx->xsc->error_depth;
358 	}
359 	return 1;
360 }
361 
362 /*
363  * Restore the saved error state and unvalidated chain to the xsc
364  * if we do not have a validated chain.
365  */
366 static int
367 x509_verify_ctx_restore_xsc_error(struct x509_verify_ctx *ctx)
368 {
369 	if (ctx->xsc != NULL && ctx->chains_count == 0 &&
370 	    ctx->saved_error_chain != NULL) {
371 		sk_X509_pop_free(ctx->xsc->chain, X509_free);
372 		ctx->xsc->chain = X509_chain_up_ref(ctx->saved_error_chain);
373 		if (ctx->xsc->chain == NULL)
374 			return x509_verify_cert_error(ctx, NULL, 0,
375 			    X509_V_ERR_OUT_OF_MEM, 0);
376 		ctx->xsc->error = ctx->saved_error;
377 		ctx->xsc->error_depth = ctx->saved_error_depth;
378 	}
379 	return 1;
380 }
381 
382 /* Perform legacy style validation of a chain */
383 static int
384 x509_verify_ctx_validate_legacy_chain(struct x509_verify_ctx *ctx,
385     struct x509_verify_chain *chain, size_t depth)
386 {
387 	int ret = 0, trust;
388 
389 	if (ctx->xsc == NULL)
390 		return 1;
391 
392 	/*
393 	 * If we have a legacy xsc, choose a validated chain, and
394 	 * apply the extensions, revocation, and policy checks just
395 	 * like the legacy code did. We do this here instead of as
396 	 * building the chains to more easily support the callback and
397 	 * the bewildering array of VERIFY_PARAM knobs that are there
398 	 * for the fiddling.
399 	 */
400 
401 	/* These may be set in one of the following calls. */
402 	ctx->xsc->error = X509_V_OK;
403 	ctx->xsc->error_depth = 0;
404 
405 	if (!x509_verify_ctx_set_xsc_chain(ctx, chain, 0, 1))
406 		goto err;
407 
408 	/*
409 	 * Call the legacy code to walk the chain and check trust
410 	 * in the legacy way to handle partial chains and get the
411 	 * callback fired correctly.
412 	 */
413 	trust = x509_vfy_check_trust(ctx->xsc);
414 	if (trust == X509_TRUST_REJECTED)
415 		goto err; /* callback was called in x509_vfy_check_trust */
416 	if (trust != X509_TRUST_TRUSTED) {
417 		/* NOTREACHED */
418 		goto err;  /* should not happen if we get in here - abort? */
419 	}
420 
421 	/*
422 	 * XXX currently this duplicates some work done in chain
423 	 * build, but we keep it here until we have feature parity
424 	 */
425 	if (!x509_vfy_check_chain_extensions(ctx->xsc))
426 		goto err;
427 
428 #ifndef OPENSSL_NO_RFC3779
429 	if (!X509v3_asid_validate_path(ctx->xsc))
430 		goto err;
431 
432 	if (!X509v3_addr_validate_path(ctx->xsc))
433 		goto err;
434 #endif
435 
436 	if (!x509_vfy_check_security_level(ctx->xsc))
437 		goto err;
438 
439 	if (!x509_constraints_chain(ctx->xsc->chain,
440 		&ctx->xsc->error, &ctx->xsc->error_depth)) {
441 		X509 *cert = sk_X509_value(ctx->xsc->chain, depth);
442 		if (!x509_verify_cert_error(ctx, cert,
443 			ctx->xsc->error_depth, ctx->xsc->error, 0))
444 			goto err;
445 	}
446 
447 	if (!x509_vfy_check_revocation(ctx->xsc))
448 		goto err;
449 
450 	if (!x509_vfy_check_policy(ctx->xsc))
451 		goto err;
452 
453 	ret = 1;
454 
455  err:
456 	/*
457 	 * The above checks may have set ctx->xsc->error and
458 	 * ctx->xsc->error_depth - save these for later on.
459 	 */
460 	if (ctx->xsc->error != X509_V_OK) {
461 		if (ctx->xsc->error_depth < 0 ||
462 		    ctx->xsc->error_depth >= X509_VERIFY_MAX_CHAIN_CERTS)
463 			return 0;
464 		chain->cert_errors[ctx->xsc->error_depth] =
465 		    ctx->xsc->error;
466 		ctx->error_depth = ctx->xsc->error_depth;
467 	}
468 
469 	return ret;
470 }
471 
472 /* Add a validated chain to our list of valid chains */
473 static int
474 x509_verify_ctx_add_chain(struct x509_verify_ctx *ctx,
475     struct x509_verify_chain *chain, char *name)
476 {
477 	size_t depth;
478 	X509 *last = x509_verify_chain_last(chain);
479 	X509 *leaf = x509_verify_chain_leaf(chain);
480 
481 	depth = sk_X509_num(chain->certs);
482 	if (depth > 0)
483 		depth--;
484 
485 	if (ctx->chains_count >= ctx->max_chains)
486 		return x509_verify_cert_error(ctx, last, depth,
487 		    X509_V_ERR_CERT_CHAIN_TOO_LONG, 0);
488 
489 	/* Clear a get issuer failure for a root certificate. */
490 	if (chain->cert_errors[depth] ==
491 	    X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
492 		chain->cert_errors[depth] = X509_V_OK;
493 
494 	if (!x509_verify_ctx_validate_legacy_chain(ctx, chain, depth))
495 		return 0;
496 
497 	/* Verify the leaf certificate and store any resulting error. */
498 	if (!x509_verify_cert_valid(ctx, leaf, NULL))
499 		return 0;
500 	if (!x509_verify_cert_hostname(ctx, leaf, name))
501 		return 0;
502 	if (ctx->error_depth == 0 &&
503 	    ctx->error != X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
504 		chain->cert_errors[0] = ctx->error;
505 
506 	/*
507 	 * In the non-legacy code, extensions and purpose are dealt
508 	 * with as the chain is built.
509 	 *
510 	 * The non-legacy api returns multiple chains but does not do
511 	 * any revocation checking (it must be done by the caller on
512 	 * any chain they wish to use)
513 	 */
514 
515 	if ((ctx->chains[ctx->chains_count] = x509_verify_chain_dup(chain)) ==
516 	    NULL) {
517 		return x509_verify_cert_error(ctx, last, depth,
518 		    X509_V_ERR_OUT_OF_MEM, 0);
519 	}
520 	ctx->chains_count++;
521 
522 	ctx->error = X509_V_OK;
523 	ctx->error_depth = depth;
524 
525 	return 1;
526 }
527 
528 static int
529 x509_verify_potential_parent(struct x509_verify_ctx *ctx, X509 *parent,
530     X509 *child)
531 {
532 	if (!x509_verify_cert_cache_extensions(parent))
533 		return 0;
534 	if (ctx->xsc != NULL)
535 		return (ctx->xsc->check_issued(ctx->xsc, child, parent));
536 
537 	/* XXX key usage */
538 	return X509_check_issued(child, parent) != X509_V_OK;
539 }
540 
541 static int
542 x509_verify_parent_signature(X509 *parent, X509 *child, int *error)
543 {
544 	EVP_PKEY *pkey;
545 	int cached;
546 	int ret = 0;
547 
548 	/* Use cached value if we have it */
549 	if ((cached = x509_issuer_cache_find(parent->hash, child->hash)) >= 0)
550 		return cached;
551 
552 	/* Check signature. Did parent sign child? */
553 	if ((pkey = X509_get_pubkey(parent)) == NULL) {
554 		*error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
555 		return 0;
556 	}
557 	if (X509_verify(child, pkey) <= 0)
558 		*error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
559 	else
560 		ret = 1;
561 
562 	/* Add result to cache */
563 	x509_issuer_cache_add(parent->hash, child->hash, ret);
564 
565 	EVP_PKEY_free(pkey);
566 
567 	return ret;
568 }
569 
570 static int
571 x509_verify_consider_candidate(struct x509_verify_ctx *ctx, X509 *cert,
572     int is_root_cert, X509 *candidate, struct x509_verify_chain *current_chain,
573     int full_chain, char *name)
574 {
575 	int depth = sk_X509_num(current_chain->certs);
576 	struct x509_verify_chain *new_chain;
577 	int i;
578 
579 	/* Fail if the certificate is already in the chain */
580 	for (i = 0; i < sk_X509_num(current_chain->certs); i++) {
581 		if (X509_cmp(sk_X509_value(current_chain->certs, i),
582 		    candidate) == 0)
583 			return 0;
584 	}
585 
586 	if (ctx->sig_checks++ > X509_VERIFY_MAX_SIGCHECKS) {
587 		/* don't allow callback to override safety check */
588 		(void) x509_verify_cert_error(ctx, candidate, depth,
589 		    X509_V_ERR_CERT_CHAIN_TOO_LONG, 0);
590 		return 0;
591 	}
592 
593 	if (!x509_verify_parent_signature(candidate, cert, &ctx->error)) {
594 		if (!x509_verify_cert_error(ctx, candidate, depth,
595 		    ctx->error, 0))
596 			return 0;
597 	}
598 
599 	if (!x509_verify_cert_valid(ctx, candidate, current_chain))
600 		return 0;
601 
602 	/* candidate is good, add it to a copy of the current chain */
603 	if ((new_chain = x509_verify_chain_dup(current_chain)) == NULL) {
604 		x509_verify_cert_error(ctx, candidate, depth,
605 		    X509_V_ERR_OUT_OF_MEM, 0);
606 		return 0;
607 	}
608 	if (!x509_verify_chain_append(new_chain, candidate, &ctx->error)) {
609 		x509_verify_cert_error(ctx, candidate, depth, ctx->error, 0);
610 		x509_verify_chain_free(new_chain);
611 		return 0;
612 	}
613 
614 	/*
615 	 * If candidate is a trusted root, we have a validated chain,
616 	 * so we save it.  Otherwise, recurse until we find a root or
617 	 * give up.
618 	 */
619 	if (is_root_cert) {
620 		if (!x509_verify_ctx_set_xsc_chain(ctx, new_chain, 0, 1)) {
621 			x509_verify_chain_free(new_chain);
622 			return 0;
623 		}
624 		if (!x509_verify_ctx_add_chain(ctx, new_chain, name)) {
625 			x509_verify_chain_free(new_chain);
626 			return 0;
627 		}
628 		goto done;
629 	}
630 
631 	x509_verify_build_chains(ctx, candidate, new_chain, full_chain, name);
632 
633  done:
634 	x509_verify_chain_free(new_chain);
635 	return 1;
636 }
637 
638 static int
639 x509_verify_cert_error(struct x509_verify_ctx *ctx, X509 *cert, size_t depth,
640     int error, int ok)
641 {
642 	ctx->error = error;
643 	ctx->error_depth = depth;
644 	if (ctx->xsc != NULL) {
645 		ctx->xsc->error = error;
646 		ctx->xsc->error_depth = depth;
647 		ctx->xsc->current_cert = cert;
648 		return ctx->xsc->verify_cb(ok, ctx->xsc);
649 	}
650 	return ok;
651 }
652 
653 static void
654 x509_verify_build_chains(struct x509_verify_ctx *ctx, X509 *cert,
655     struct x509_verify_chain *current_chain, int full_chain, char *name)
656 {
657 	X509 *candidate;
658 	int i, depth, count, ret, is_root;
659 
660 	/*
661 	 * If we are finding chains with an xsc, just stop after we have
662 	 * one chain, there's no point in finding more, it just exercises
663 	 * the potentially buggy callback processing in the calling software.
664 	 */
665 	if (ctx->xsc != NULL && ctx->chains_count > 0)
666 		return;
667 
668 	depth = sk_X509_num(current_chain->certs);
669 	if (depth > 0)
670 		depth--;
671 
672 	if (depth >= ctx->max_depth &&
673 	    !x509_verify_cert_error(ctx, cert, depth,
674 		X509_V_ERR_CERT_CHAIN_TOO_LONG, 0))
675 		return;
676 
677 	count = ctx->chains_count;
678 
679 	ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
680 	ctx->error_depth = depth;
681 
682 	if (ctx->saved_error != 0)
683 		ctx->error = ctx->saved_error;
684 	if (ctx->saved_error_depth != 0)
685 		ctx->error_depth = ctx->saved_error_depth;
686 
687 	if (ctx->xsc != NULL) {
688 		/*
689 		 * Long ago experiments at Muppet labs resulted in a
690 		 * situation where software not only sees these errors
691 		 * but forced developers to expect them in certain cases.
692 		 * so we must mimic this awfulness for the legacy case.
693 		 */
694 		if (cert->ex_flags & EXFLAG_SS)
695 			ctx->error = (depth == 0) ?
696 			    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
697 			    X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
698 	}
699 
700 	/* Check for legacy mode roots */
701 	if (ctx->xsc != NULL) {
702 		if ((ret = ctx->xsc->get_issuer(&candidate, ctx->xsc, cert)) < 0) {
703 			x509_verify_cert_error(ctx, cert, depth,
704 			    X509_V_ERR_STORE_LOOKUP, 0);
705 			return;
706 		}
707 		if (ret > 0) {
708 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
709 				is_root = x509_verify_check_chain_end(candidate,
710 				    full_chain);
711 				x509_verify_consider_candidate(ctx, cert,
712 				    is_root, candidate, current_chain,
713 				    full_chain, name);
714 			}
715 			X509_free(candidate);
716 		}
717 	} else {
718 		/* Check to see if we have a trusted root issuer. */
719 		for (i = 0; i < sk_X509_num(ctx->roots); i++) {
720 			candidate = sk_X509_value(ctx->roots, i);
721 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
722 				is_root = x509_verify_check_chain_end(candidate,
723 				    full_chain);
724 				x509_verify_consider_candidate(ctx, cert,
725 				    is_root, candidate, current_chain,
726 				    full_chain, name);
727 			}
728 		}
729 	}
730 
731 	/* Check intermediates after checking roots */
732 	if (ctx->intermediates != NULL) {
733 		for (i = 0; i < sk_X509_num(ctx->intermediates); i++) {
734 			candidate = sk_X509_value(ctx->intermediates, i);
735 			if (x509_verify_potential_parent(ctx, candidate, cert)) {
736 				x509_verify_consider_candidate(ctx, cert,
737 				    0, candidate, current_chain,
738 				    full_chain, name);
739 			}
740 		}
741 	}
742 
743 	if (ctx->chains_count > count) {
744 		if (ctx->xsc != NULL) {
745 			ctx->xsc->error = X509_V_OK;
746 			ctx->xsc->error_depth = depth;
747 			ctx->xsc->current_cert = cert;
748 		}
749 	} else if (ctx->error_depth == depth) {
750 		if (!x509_verify_ctx_set_xsc_chain(ctx, current_chain, 0, 0))
751 			return;
752 	}
753 }
754 
755 static int
756 x509_verify_cert_hostname(struct x509_verify_ctx *ctx, X509 *cert, char *name)
757 {
758 	char *candidate;
759 	size_t len;
760 
761 	if (name == NULL) {
762 		if (ctx->xsc != NULL) {
763 			int ret;
764 
765 			if ((ret = x509_vfy_check_id(ctx->xsc)) == 0)
766 				ctx->error = ctx->xsc->error;
767 			return ret;
768 		}
769 		return 1;
770 	}
771 	if ((candidate = strdup(name)) == NULL) {
772 		ctx->error = X509_V_ERR_OUT_OF_MEM;
773 		goto err;
774 	}
775 	if ((len = strlen(candidate)) < 1) {
776 		ctx->error = X509_V_ERR_UNSPECIFIED; /* XXX */
777 		goto err;
778 	}
779 
780 	/* IP addresses may be written in [ ]. */
781 	if (candidate[0] == '[' && candidate[len - 1] == ']') {
782 		candidate[len - 1] = '\0';
783 		if (X509_check_ip_asc(cert, candidate + 1, 0) <= 0) {
784 			ctx->error = X509_V_ERR_IP_ADDRESS_MISMATCH;
785 			goto err;
786 		}
787 	} else {
788 		int flags = 0;
789 
790 		if (ctx->xsc == NULL)
791 			flags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
792 
793 		if (X509_check_host(cert, candidate, len, flags, NULL) <= 0) {
794 			ctx->error = X509_V_ERR_HOSTNAME_MISMATCH;
795 			goto err;
796 		}
797 	}
798 	free(candidate);
799 	return 1;
800  err:
801 	free(candidate);
802 	return x509_verify_cert_error(ctx, cert, 0, ctx->error, 0);
803 }
804 
805 static int
806 x509_verify_set_check_time(struct x509_verify_ctx *ctx)
807 {
808 	if (ctx->xsc != NULL)  {
809 		if (ctx->xsc->param->flags & X509_V_FLAG_USE_CHECK_TIME) {
810 			ctx->check_time = &ctx->xsc->param->check_time;
811 			return 1;
812 		}
813 		if (ctx->xsc->param->flags & X509_V_FLAG_NO_CHECK_TIME)
814 			return 0;
815 	}
816 
817 	ctx->check_time = NULL;
818 	return 1;
819 }
820 
821 static int
822 x509_verify_cert_times(X509 *cert, time_t *cmp_time, int *error)
823 {
824 	time_t when;
825 
826 	if (cmp_time == NULL)
827 		when = time(NULL);
828 	else
829 		when = *cmp_time;
830 
831 	if (cert->not_before == -1) {
832 		*error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
833 		return 0;
834 	}
835 	if (when < cert->not_before) {
836 		*error = X509_V_ERR_CERT_NOT_YET_VALID;
837 		return 0;
838 	}
839 	if (cert->not_after == -1) {
840 		*error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
841 		return 0;
842 	}
843 	if (when > cert->not_after) {
844 		*error = X509_V_ERR_CERT_HAS_EXPIRED;
845 		return 0;
846 	}
847 
848 	return 1;
849 }
850 
851 static int
852 x509_verify_validate_constraints(X509 *cert,
853     struct x509_verify_chain *current_chain, int *error)
854 {
855 	struct x509_constraints_names *excluded = NULL;
856 	struct x509_constraints_names *permitted = NULL;
857 	int err = X509_V_ERR_UNSPECIFIED;
858 
859 	if (current_chain == NULL)
860 		return 1;
861 
862 	if (cert->nc != NULL) {
863 		if ((permitted = x509_constraints_names_new(
864 		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
865 			err = X509_V_ERR_OUT_OF_MEM;
866 			goto err;
867 		}
868 		if ((excluded = x509_constraints_names_new(
869 		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
870 			err = X509_V_ERR_OUT_OF_MEM;
871 			goto err;
872 		}
873 		if (!x509_constraints_extract_constraints(cert,
874 		    permitted, excluded, &err))
875 			goto err;
876 		if (!x509_constraints_check(current_chain->names,
877 		    permitted, excluded, &err))
878 			goto err;
879 		x509_constraints_names_free(excluded);
880 		x509_constraints_names_free(permitted);
881 	}
882 
883 	return 1;
884  err:
885 	*error = err;
886 	x509_constraints_names_free(excluded);
887 	x509_constraints_names_free(permitted);
888 	return 0;
889 }
890 
891 static int
892 x509_verify_cert_extensions(struct x509_verify_ctx *ctx, X509 *cert, int need_ca)
893 {
894 	if (!x509_verify_cert_cache_extensions(cert)) {
895 		ctx->error = X509_V_ERR_UNSPECIFIED;
896 		return 0;
897 	}
898 
899 	if (ctx->xsc != NULL)
900 		return 1;	/* legacy is checked after chain is built */
901 
902 	if (cert->ex_flags & EXFLAG_CRITICAL) {
903 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
904 		return 0;
905 	}
906 	/* No we don't care about v1, netscape, and other ancient silliness */
907 	if (need_ca && (!(cert->ex_flags & EXFLAG_BCONS) &&
908 	    (cert->ex_flags & EXFLAG_CA))) {
909 		ctx->error = X509_V_ERR_INVALID_CA;
910 		return 0;
911 	}
912 	if (ctx->purpose > 0 && X509_check_purpose(cert, ctx->purpose, need_ca)) {
913 		ctx->error = X509_V_ERR_INVALID_PURPOSE;
914 		return 0;
915 	}
916 
917 	/* XXX support proxy certs later in new api */
918 	if (ctx->xsc == NULL && cert->ex_flags & EXFLAG_PROXY) {
919 		ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
920 		return 0;
921 	}
922 
923 	return 1;
924 }
925 
926 /* Validate that cert is a possible candidate to append to current_chain */
927 static int
928 x509_verify_cert_valid(struct x509_verify_ctx *ctx, X509 *cert,
929     struct x509_verify_chain *current_chain)
930 {
931 	X509 *issuer_candidate;
932 	int should_be_ca = current_chain != NULL;
933 	size_t depth = 0;
934 
935 	if (current_chain != NULL)
936 		depth = sk_X509_num(current_chain->certs);
937 
938 	if (!x509_verify_cert_extensions(ctx, cert, should_be_ca))
939 		return 0;
940 
941 	if (should_be_ca) {
942 		issuer_candidate = x509_verify_chain_last(current_chain);
943 		if (issuer_candidate != NULL &&
944 		    !X509_check_issued(issuer_candidate, cert))
945 			if (!x509_verify_cert_error(ctx, cert, depth,
946 			    X509_V_ERR_SUBJECT_ISSUER_MISMATCH, 0))
947 				return 0;
948 	}
949 
950 	if (x509_verify_set_check_time(ctx)) {
951 		if (!x509_verify_cert_times(cert, ctx->check_time,
952 		    &ctx->error)) {
953 			if (!x509_verify_cert_error(ctx, cert, depth,
954 			    ctx->error, 0))
955 				return 0;
956 		}
957 	}
958 
959 	if (!x509_verify_validate_constraints(cert, current_chain,
960 	    &ctx->error) && !x509_verify_cert_error(ctx, cert, depth,
961 	    ctx->error, 0))
962 		return 0;
963 
964 	return 1;
965 }
966 
967 struct x509_verify_ctx *
968 x509_verify_ctx_new_from_xsc(X509_STORE_CTX *xsc)
969 {
970 	struct x509_verify_ctx *ctx;
971 	size_t max_depth;
972 
973 	if (xsc == NULL)
974 		return NULL;
975 
976 	if ((ctx = x509_verify_ctx_new(NULL)) == NULL)
977 		return NULL;
978 
979 	ctx->xsc = xsc;
980 
981 	if (xsc->untrusted &&
982 	    (ctx->intermediates = X509_chain_up_ref(xsc->untrusted)) == NULL)
983 		goto err;
984 
985 	max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
986 	if (xsc->param->depth > 0 && xsc->param->depth < X509_VERIFY_MAX_CHAIN_CERTS)
987 		max_depth = xsc->param->depth;
988 	if (!x509_verify_ctx_set_max_depth(ctx, max_depth))
989 		goto err;
990 
991 	return ctx;
992  err:
993 	x509_verify_ctx_free(ctx);
994 	return NULL;
995 }
996 
997 /* Public API */
998 
999 struct x509_verify_ctx *
1000 x509_verify_ctx_new(STACK_OF(X509) *roots)
1001 {
1002 	struct x509_verify_ctx *ctx;
1003 
1004 	if ((ctx = calloc(1, sizeof(struct x509_verify_ctx))) == NULL)
1005 		return NULL;
1006 
1007 	if (roots != NULL) {
1008 		if  ((ctx->roots = X509_chain_up_ref(roots)) == NULL)
1009 			goto err;
1010 	} else {
1011 		if ((ctx->roots = sk_X509_new_null()) == NULL)
1012 			goto err;
1013 	}
1014 
1015 	ctx->max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
1016 	ctx->max_chains = X509_VERIFY_MAX_CHAINS;
1017 	ctx->max_sigs = X509_VERIFY_MAX_SIGCHECKS;
1018 
1019 	if ((ctx->chains = calloc(X509_VERIFY_MAX_CHAINS,
1020 	    sizeof(*ctx->chains))) == NULL)
1021 		goto err;
1022 
1023 	return ctx;
1024  err:
1025 	x509_verify_ctx_free(ctx);
1026 	return NULL;
1027 }
1028 
1029 void
1030 x509_verify_ctx_free(struct x509_verify_ctx *ctx)
1031 {
1032 	if (ctx == NULL)
1033 		return;
1034 	sk_X509_pop_free(ctx->roots, X509_free);
1035 	x509_verify_ctx_clear(ctx);
1036 	free(ctx);
1037 }
1038 
1039 int
1040 x509_verify_ctx_set_max_depth(struct x509_verify_ctx *ctx, size_t max)
1041 {
1042 	if (max < 1 || max > X509_VERIFY_MAX_CHAIN_CERTS)
1043 		return 0;
1044 	ctx->max_depth = max;
1045 	return 1;
1046 }
1047 
1048 int
1049 x509_verify_ctx_set_max_chains(struct x509_verify_ctx *ctx, size_t max)
1050 {
1051 	if (max < 1 || max > X509_VERIFY_MAX_CHAINS)
1052 		return 0;
1053 	ctx->max_chains = max;
1054 	return 1;
1055 }
1056 
1057 int
1058 x509_verify_ctx_set_max_signatures(struct x509_verify_ctx *ctx, size_t max)
1059 {
1060 	if (max < 1 || max > 100000)
1061 		return 0;
1062 	ctx->max_sigs = max;
1063 	return 1;
1064 }
1065 
1066 int
1067 x509_verify_ctx_set_purpose(struct x509_verify_ctx *ctx, int purpose)
1068 {
1069 	if (purpose < X509_PURPOSE_MIN || purpose > X509_PURPOSE_MAX)
1070 		return 0;
1071 	ctx->purpose = purpose;
1072 	return 1;
1073 }
1074 
1075 int
1076 x509_verify_ctx_set_intermediates(struct x509_verify_ctx *ctx,
1077     STACK_OF(X509) *intermediates)
1078 {
1079 	if ((ctx->intermediates = X509_chain_up_ref(intermediates)) == NULL)
1080 		return 0;
1081 	return 1;
1082 }
1083 
1084 const char *
1085 x509_verify_ctx_error_string(struct x509_verify_ctx *ctx)
1086 {
1087 	return X509_verify_cert_error_string(ctx->error);
1088 }
1089 
1090 size_t
1091 x509_verify_ctx_error_depth(struct x509_verify_ctx *ctx)
1092 {
1093 	return ctx->error_depth;
1094 }
1095 
1096 STACK_OF(X509) *
1097 x509_verify_ctx_chain(struct x509_verify_ctx *ctx, size_t i)
1098 {
1099 	if (i >= ctx->chains_count)
1100 		return NULL;
1101 	return ctx->chains[i]->certs;
1102 }
1103 
1104 size_t
1105 x509_verify(struct x509_verify_ctx *ctx, X509 *leaf, char *name)
1106 {
1107 	struct x509_verify_chain *current_chain;
1108 	int retry_chain_build, full_chain = 0;
1109 
1110 	if (ctx->roots == NULL || ctx->max_depth == 0) {
1111 		ctx->error = X509_V_ERR_INVALID_CALL;
1112 		goto err;
1113 	}
1114 
1115 	if (ctx->xsc != NULL) {
1116 		if (leaf != NULL || name != NULL) {
1117 			ctx->error = X509_V_ERR_INVALID_CALL;
1118 			goto err;
1119 		}
1120 		leaf = ctx->xsc->cert;
1121 
1122 		/* XXX */
1123 		full_chain = 1;
1124 		if (ctx->xsc->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
1125 			full_chain = 0;
1126 		/*
1127 		 * XXX
1128 		 * The legacy code expects the top level cert to be
1129 		 * there, even if we didn't find a chain. So put it
1130 		 * there, we will clobber it later if we find a valid
1131 		 * chain.
1132 		 */
1133 		if ((ctx->xsc->chain = sk_X509_new_null()) == NULL) {
1134 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1135 			goto err;
1136 		}
1137 		if (!X509_up_ref(leaf)) {
1138 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1139 			goto err;
1140 		}
1141 		if (!sk_X509_push(ctx->xsc->chain, leaf)) {
1142 			X509_free(leaf);
1143 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1144 			goto err;
1145 		}
1146 		ctx->xsc->error_depth = 0;
1147 		ctx->xsc->current_cert = leaf;
1148 	}
1149 
1150 	if ((current_chain = x509_verify_chain_new()) == NULL) {
1151 		ctx->error = X509_V_ERR_OUT_OF_MEM;
1152 		goto err;
1153 	}
1154 
1155 	/*
1156 	 * Add the leaf to the chain and try to build chains from it.
1157 	 * Note that unlike Go's verifier, we have not yet checked
1158 	 * anything about the leaf, This is intentional, so that we
1159 	 * report failures in chain building before we report problems
1160 	 * with the leaf.
1161 	 */
1162 	if (!x509_verify_chain_append(current_chain, leaf, &ctx->error)) {
1163 		x509_verify_chain_free(current_chain);
1164 		goto err;
1165 	}
1166 	do {
1167 		retry_chain_build = 0;
1168 		if (x509_verify_ctx_cert_is_root(ctx, leaf, full_chain)) {
1169 			if (!x509_verify_ctx_add_chain(ctx, current_chain,
1170 			    name)) {
1171 				x509_verify_chain_free(current_chain);
1172 				goto err;
1173 			}
1174 		} else {
1175 			x509_verify_build_chains(ctx, leaf, current_chain,
1176 			    full_chain, name);
1177 			if (full_chain && ctx->chains_count == 0) {
1178 				/*
1179 				 * Save the error state from the xsc
1180 				 * at this point to put back on the
1181 				 * xsc in case we do not find a chain
1182 				 * that is trusted but not a full
1183 				 * chain to a self signed root. This
1184 				 * is because the unvalidated chain is
1185 				 * used by the autochain batshittery
1186 				 * on failure and will be needed for
1187 				 * that.
1188 				 */
1189 				ctx->xsc->error_depth = ctx->error_depth;
1190 				if (!x509_verify_ctx_save_xsc_error(ctx)) {
1191 					x509_verify_chain_free(current_chain);
1192 					goto err;
1193 				}
1194 				full_chain = 0;
1195 				retry_chain_build = 1;
1196 			}
1197 		}
1198 	} while (retry_chain_build);
1199 
1200 	x509_verify_chain_free(current_chain);
1201 
1202 	/*
1203 	 * Do the new verifier style return, where we don't have an xsc
1204 	 * that allows a crazy callback to turn invalid things into valid.
1205 	 */
1206 	if (ctx->xsc == NULL) {
1207 		/*
1208 		 * Safety net:
1209 		 * We could not find a validated chain, and for some reason do not
1210 		 * have an error set.
1211 		 */
1212 		if (ctx->chains_count == 0 && ctx->error == X509_V_OK)
1213 			ctx->error = X509_V_ERR_UNSPECIFIED;
1214 
1215 		/*
1216 		 * If we are not using an xsc, and have no possibility for the
1217 		 * crazy OpenSSL callback API changing the results of
1218 		 * validation steps (because the callback can make validation
1219 		 * proceed in the presence of invalid certs), any chains we
1220 		 * have here are correctly built and verified.
1221 		 */
1222 		if (ctx->chains_count > 0)
1223 			ctx->error = X509_V_OK;
1224 
1225 		return ctx->chains_count;
1226 	}
1227 
1228 	/*
1229 	 * Otherwise we are doing compatibility with an xsc, which means that we
1230 	 * will have one chain, which might actually be a bogus chain because
1231 	 * the callback told us to ignore errors and proceed to build an invalid
1232 	 * chain. Possible return values from this include returning 1 with an
1233 	 * invalid chain and a value of xsc->error != X509_V_OK (It's tradition
1234 	 * that makes it ok).
1235 	 */
1236 
1237 	if (ctx->chains_count > 0) {
1238 		/*
1239 		 * The chain we have using an xsc might not be a verified chain
1240 		 * if the callback perverted things while we built it to ignore
1241 		 * failures and proceed with chain building. We put this chain
1242 		 * and the error associated with it on the xsc.
1243 		 */
1244 		if (!x509_verify_ctx_set_xsc_chain(ctx, ctx->chains[0], 1, 1))
1245 			goto err;
1246 
1247 		/*
1248 		 * Call the callback for completion up our built
1249 		 * chain. The callback could still tell us to
1250 		 * fail. Since this chain might exist as the result of
1251 		 * callback doing perversions, we could still return
1252 		 * "success" with something other than X509_V_OK set
1253 		 * as the error.
1254 		 */
1255 		if (!x509_vfy_callback_indicate_completion(ctx->xsc))
1256 			goto err;
1257 	} else {
1258 		/*
1259 		 * We did not find a chain. Bring back the failure
1260 		 * case we wanted to the xsc if we saved one. If we
1261 		 * did not we should have just the leaf on the xsc.
1262 		 */
1263 		if (!x509_verify_ctx_restore_xsc_error(ctx))
1264 			goto err;
1265 
1266 		/*
1267 		 * Safety net, ensure we have an error set in the
1268 		 * failing case.
1269 		 */
1270 		if (ctx->xsc->error == X509_V_OK) {
1271 			if (ctx->error == X509_V_OK)
1272 				ctx->error = X509_V_ERR_UNSPECIFIED;
1273 			ctx->xsc->error = ctx->error;
1274 		}
1275 
1276 		/*
1277 		 * Let the callback override the return value
1278 		 * at depth 0 if it chooses to
1279 		 */
1280 		return ctx->xsc->verify_cb(0, ctx->xsc);
1281 	}
1282 
1283 	/* We only ever find one chain in compat mode with an xsc. */
1284 	return 1;
1285 
1286  err:
1287 	if (ctx->error == X509_V_OK)
1288 		ctx->error = X509_V_ERR_UNSPECIFIED;
1289 
1290 	if (ctx->xsc != NULL) {
1291 		if (ctx->xsc->error == X509_V_OK)
1292 			ctx->xsc->error = X509_V_ERR_UNSPECIFIED;
1293 		ctx->error = ctx->xsc->error;
1294 	}
1295 
1296 	return 0;
1297 }
1298