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