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