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