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