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