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