1/* $OpenBSD: x509_verify.c,v 1.70 2024/06/07 06:21:40 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 "asn1_local.h"
31#include "x509_internal.h"
32#include "x509_issuer_cache.h"
33
34static int x509_verify_cert_valid(struct x509_verify_ctx *ctx, X509 *cert,
35    struct x509_verify_chain *current_chain);
36static int x509_verify_cert_hostname(struct x509_verify_ctx *ctx, X509 *cert,
37    char *name);
38static void x509_verify_build_chains(struct x509_verify_ctx *ctx, X509 *cert,
39    struct x509_verify_chain *current_chain, int full_chain, char *name);
40static int x509_verify_cert_error(struct x509_verify_ctx *ctx, X509 *cert,
41    size_t depth, int error, int ok);
42static void x509_verify_chain_free(struct x509_verify_chain *chain);
43
44/*
45 * Parse an asn1 to a representable time_t as per RFC 5280 rules.
46 * Returns -1 if that can't be done for any reason.
47 */
48int
49x509_verify_asn1_time_to_time_t(const ASN1_TIME *atime, int notAfter,
50    time_t *out)
51{
52	struct tm tm = { 0 };
53	int type;
54
55	if (atime == NULL)
56		return 0;
57
58	type = ASN1_time_parse(atime->data, atime->length, &tm, atime->type);
59	if (type == -1)
60		return 0;
61
62	/* RFC 5280 section 4.1.2.5 */
63	if (tm.tm_year < 150 && type != V_ASN1_UTCTIME)
64		return 0;
65	if (tm.tm_year >= 150 && type != V_ASN1_GENERALIZEDTIME)
66		return 0;
67
68	if (notAfter) {
69		/*
70		 * If we are a completely broken operating system with a
71		 * 32 bit time_t, and we have been told this is a notAfter
72		 * date, limit the date to a 32 bit representable value.
73		 */
74		if (!ASN1_time_tm_clamp_notafter(&tm))
75			return 0;
76	}
77
78	/*
79	 * Defensively fail if the time string is not representable as
80	 * a time_t. A time_t must be sane if you care about times after
81	 * Jan 19 2038.
82	 */
83	return asn1_time_tm_to_time_t(&tm, out);
84}
85
86struct x509_verify_chain *
87x509_verify_chain_new(void)
88{
89	struct x509_verify_chain *chain;
90
91	if ((chain = calloc(1, sizeof(*chain))) == NULL)
92		goto err;
93	if ((chain->certs = sk_X509_new_null()) == NULL)
94		goto err;
95	if ((chain->cert_errors = calloc(X509_VERIFY_MAX_CHAIN_CERTS,
96	    sizeof(int))) == NULL)
97		goto err;
98	if ((chain->names =
99	    x509_constraints_names_new(X509_VERIFY_MAX_CHAIN_NAMES)) == NULL)
100		goto err;
101
102	return chain;
103 err:
104	x509_verify_chain_free(chain);
105	return NULL;
106}
107
108static void
109x509_verify_chain_clear(struct x509_verify_chain *chain)
110{
111	sk_X509_pop_free(chain->certs, X509_free);
112	chain->certs = NULL;
113	free(chain->cert_errors);
114	chain->cert_errors = NULL;
115	x509_constraints_names_free(chain->names);
116	chain->names = NULL;
117}
118
119static void
120x509_verify_chain_free(struct x509_verify_chain *chain)
121{
122	if (chain == NULL)
123		return;
124	x509_verify_chain_clear(chain);
125	free(chain);
126}
127
128static struct x509_verify_chain *
129x509_verify_chain_dup(struct x509_verify_chain *chain)
130{
131	struct x509_verify_chain *new_chain;
132
133	if ((new_chain = calloc(1, sizeof(*chain))) == NULL)
134		goto err;
135	if ((new_chain->certs = X509_chain_up_ref(chain->certs)) == NULL)
136		goto err;
137	if ((new_chain->cert_errors = calloc(X509_VERIFY_MAX_CHAIN_CERTS,
138	    sizeof(int))) == NULL)
139		goto err;
140	memcpy(new_chain->cert_errors, chain->cert_errors,
141	    X509_VERIFY_MAX_CHAIN_CERTS * sizeof(int));
142	if ((new_chain->names =
143	    x509_constraints_names_dup(chain->names)) == NULL)
144		goto err;
145	return(new_chain);
146 err:
147	x509_verify_chain_free(new_chain);
148	return NULL;
149}
150
151static int
152x509_verify_chain_append(struct x509_verify_chain *chain, X509 *cert,
153    int *error)
154{
155	int verify_err = X509_V_ERR_UNSPECIFIED;
156	size_t idx;
157
158	if (!x509_constraints_extract_names(chain->names, cert,
159	    sk_X509_num(chain->certs) == 0, &verify_err)) {
160		*error = verify_err;
161		return 0;
162	}
163
164	X509_up_ref(cert);
165	if (!sk_X509_push(chain->certs, cert)) {
166		X509_free(cert);
167		*error = X509_V_ERR_OUT_OF_MEM;
168		return 0;
169	}
170
171	idx = sk_X509_num(chain->certs) - 1;
172	chain->cert_errors[idx] = *error;
173
174	/*
175	 * We've just added the issuer for the previous certificate,
176	 * clear its error if appropriate.
177	 */
178	if (idx > 1 && chain->cert_errors[idx - 1] ==
179	    X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
180		chain->cert_errors[idx - 1] = X509_V_OK;
181
182	return 1;
183}
184
185static X509 *
186x509_verify_chain_last(struct x509_verify_chain *chain)
187{
188	int last;
189
190	if (chain->certs == NULL)
191		return NULL;
192	if ((last = sk_X509_num(chain->certs) - 1) < 0)
193		return NULL;
194	return sk_X509_value(chain->certs, last);
195}
196
197X509 *
198x509_verify_chain_leaf(struct x509_verify_chain *chain)
199{
200	if (chain->certs == NULL)
201		return NULL;
202	return sk_X509_value(chain->certs, 0);
203}
204
205static void
206x509_verify_ctx_reset(struct x509_verify_ctx *ctx)
207{
208	size_t i;
209
210	for (i = 0; i < ctx->chains_count; i++)
211		x509_verify_chain_free(ctx->chains[i]);
212	sk_X509_pop_free(ctx->saved_error_chain, X509_free);
213	ctx->saved_error = 0;
214	ctx->saved_error_depth = 0;
215	ctx->error = 0;
216	ctx->error_depth = 0;
217	ctx->chains_count = 0;
218	ctx->sig_checks = 0;
219	ctx->check_time = NULL;
220}
221
222static void
223x509_verify_ctx_clear(struct x509_verify_ctx *ctx)
224{
225	x509_verify_ctx_reset(ctx);
226	sk_X509_pop_free(ctx->intermediates, X509_free);
227	free(ctx->chains);
228
229}
230
231static int
232x509_verify_cert_cache_extensions(X509 *cert)
233{
234	return x509v3_cache_extensions(cert);
235}
236
237static int
238x509_verify_cert_self_signed(X509 *cert)
239{
240	return (cert->ex_flags & EXFLAG_SS) ? 1 : 0;
241}
242
243/* XXX beck - clean up this mess of is_root */
244static int
245x509_verify_check_chain_end(X509 *cert, int full_chain)
246{
247	if (full_chain)
248		return x509_verify_cert_self_signed(cert);
249	return 1;
250}
251
252static int
253x509_verify_ctx_cert_is_root(struct x509_verify_ctx *ctx, X509 *cert,
254    int full_chain)
255{
256	X509 *match = NULL;
257	int i;
258
259	if (!x509_verify_cert_cache_extensions(cert))
260		return 0;
261
262	/* Check by lookup if we have a legacy xsc */
263	if (ctx->xsc != NULL) {
264		/*
265		 * "alternative" lookup method, using the "trusted" stack in the
266		 * xsc as the source for roots.
267		 */
268		if (ctx->xsc->trusted != NULL) {
269			for (i = 0; i < sk_X509_num(ctx->xsc->trusted); i++) {
270				if (X509_cmp(sk_X509_value(ctx->xsc->trusted,
271				    i), cert) == 0)
272					return x509_verify_check_chain_end(cert,
273					    full_chain);
274			}
275		}
276		if ((match = x509_vfy_lookup_cert_match(ctx->xsc,
277		    cert)) != NULL) {
278			X509_free(match);
279			return x509_verify_check_chain_end(cert, full_chain);
280		}
281	} else {
282		/* Check the provided roots */
283		for (i = 0; i < sk_X509_num(ctx->roots); i++) {
284			if (X509_cmp(sk_X509_value(ctx->roots, i), cert) == 0)
285				return x509_verify_check_chain_end(cert,
286				    full_chain);
287		}
288	}
289
290	return 0;
291}
292
293static int
294x509_verify_ctx_set_xsc_chain(struct x509_verify_ctx *ctx,
295    struct x509_verify_chain *chain, int set_error, int is_trusted)
296{
297	size_t num_untrusted;
298	int i;
299
300	if (ctx->xsc == NULL)
301		return 1;
302
303	/*
304	 * XXX num_untrusted is the number of untrusted certs at the
305	 * bottom of the chain. This works now since we stop at the first
306	 * trusted cert. This will need fixing once we allow more than one
307	 * trusted certificate.
308	 */
309	num_untrusted = sk_X509_num(chain->certs);
310	if (is_trusted && num_untrusted > 0)
311		num_untrusted--;
312	ctx->xsc->num_untrusted = num_untrusted;
313
314	sk_X509_pop_free(ctx->xsc->chain, X509_free);
315	ctx->xsc->chain = X509_chain_up_ref(chain->certs);
316	if (ctx->xsc->chain == NULL)
317		return x509_verify_cert_error(ctx, NULL, 0,
318		    X509_V_ERR_OUT_OF_MEM, 0);
319
320	if (set_error) {
321		ctx->xsc->error = X509_V_OK;
322		ctx->xsc->error_depth = 0;
323		for (i = 0; i < sk_X509_num(chain->certs); i++) {
324			if (chain->cert_errors[i] != X509_V_OK) {
325				ctx->xsc->error = chain->cert_errors[i];
326				ctx->xsc->error_depth = i;
327				break;
328			}
329		}
330	}
331
332	return 1;
333}
334
335
336/*
337 * Save the error state and unvalidated chain off of the xsc for
338 * later.
339 */
340static int
341x509_verify_ctx_save_xsc_error(struct x509_verify_ctx *ctx)
342{
343	if (ctx->xsc != NULL && ctx->xsc->chain != NULL) {
344		sk_X509_pop_free(ctx->saved_error_chain, X509_free);
345		ctx->saved_error_chain = X509_chain_up_ref(ctx->xsc->chain);
346		if (ctx->saved_error_chain == NULL)
347			return x509_verify_cert_error(ctx, NULL, 0,
348			    X509_V_ERR_OUT_OF_MEM, 0);
349		ctx->saved_error = ctx->xsc->error;
350		ctx->saved_error_depth = ctx->xsc->error_depth;
351	}
352	return 1;
353}
354
355/*
356 * Restore the saved error state and unvalidated chain to the xsc
357 * if we do not have a validated chain.
358 */
359static int
360x509_verify_ctx_restore_xsc_error(struct x509_verify_ctx *ctx)
361{
362	if (ctx->xsc != NULL && ctx->chains_count == 0 &&
363	    ctx->saved_error_chain != NULL) {
364		sk_X509_pop_free(ctx->xsc->chain, X509_free);
365		ctx->xsc->chain = X509_chain_up_ref(ctx->saved_error_chain);
366		if (ctx->xsc->chain == NULL)
367			return x509_verify_cert_error(ctx, NULL, 0,
368			    X509_V_ERR_OUT_OF_MEM, 0);
369		ctx->xsc->error = ctx->saved_error;
370		ctx->xsc->error_depth = ctx->saved_error_depth;
371	}
372	return 1;
373}
374
375/* Perform legacy style validation of a chain */
376static int
377x509_verify_ctx_validate_legacy_chain(struct x509_verify_ctx *ctx,
378    struct x509_verify_chain *chain, size_t depth)
379{
380	int ret = 0, trust;
381
382	if (ctx->xsc == NULL)
383		return 1;
384
385	/*
386	 * If we have a legacy xsc, choose a validated chain, and
387	 * apply the extensions, revocation, and policy checks just
388	 * like the legacy code did. We do this here instead of as
389	 * building the chains to more easily support the callback and
390	 * the bewildering array of VERIFY_PARAM knobs that are there
391	 * for the fiddling.
392	 */
393
394	/* These may be set in one of the following calls. */
395	ctx->xsc->error = X509_V_OK;
396	ctx->xsc->error_depth = 0;
397
398	if (!x509_verify_ctx_set_xsc_chain(ctx, chain, 0, 1))
399		goto err;
400
401	/*
402	 * Call the legacy code to walk the chain and check trust
403	 * in the legacy way to handle partial chains and get the
404	 * callback fired correctly.
405	 */
406	trust = x509_vfy_check_trust(ctx->xsc);
407	if (trust == X509_TRUST_REJECTED)
408		goto err; /* callback was called in x509_vfy_check_trust */
409	if (trust != X509_TRUST_TRUSTED) {
410		/* NOTREACHED */
411		goto err;  /* should not happen if we get in here - abort? */
412	}
413
414	/*
415	 * XXX currently this duplicates some work done in chain
416	 * build, but we keep it here until we have feature parity
417	 */
418	if (!x509_vfy_check_chain_extensions(ctx->xsc))
419		goto err;
420
421#ifndef OPENSSL_NO_RFC3779
422	if (!X509v3_asid_validate_path(ctx->xsc))
423		goto err;
424
425	if (!X509v3_addr_validate_path(ctx->xsc))
426		goto err;
427#endif
428
429	if (!x509_vfy_check_security_level(ctx->xsc))
430		goto err;
431
432	if (!x509_constraints_chain(ctx->xsc->chain,
433		&ctx->xsc->error, &ctx->xsc->error_depth)) {
434		X509 *cert = sk_X509_value(ctx->xsc->chain, depth);
435		if (!x509_verify_cert_error(ctx, cert,
436			ctx->xsc->error_depth, ctx->xsc->error, 0))
437			goto err;
438	}
439
440	if (!x509_vfy_check_revocation(ctx->xsc))
441		goto err;
442
443	if (!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 */
466static int
467x509_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
521static int
522x509_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(parent, child) == X509_V_OK;
532}
533
534static int
535x509_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
563static int
564x509_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
631static int
632x509_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
646static void
647x509_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
748static int
749x509_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
798static int
799x509_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
814static int
815x509_verify_cert_times(X509 *cert, time_t *cmp_time, int *error)
816{
817	time_t when, not_before, not_after;
818
819	if (cmp_time == NULL)
820		when = time(NULL);
821	else
822		when = *cmp_time;
823
824	if (!x509_verify_asn1_time_to_time_t(X509_get_notBefore(cert), 0,
825	    &not_before)) {
826		*error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
827		return 0;
828	}
829	if (when < not_before) {
830		*error = X509_V_ERR_CERT_NOT_YET_VALID;
831		return 0;
832	}
833	if (!x509_verify_asn1_time_to_time_t(X509_get_notAfter(cert), 1,
834	    &not_after)) {
835		*error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
836		return 0;
837	}
838	if (when > not_after) {
839		*error = X509_V_ERR_CERT_HAS_EXPIRED;
840		return 0;
841	}
842
843	return 1;
844}
845
846static int
847x509_verify_validate_constraints(X509 *cert,
848    struct x509_verify_chain *current_chain, int *error)
849{
850	struct x509_constraints_names *excluded = NULL;
851	struct x509_constraints_names *permitted = NULL;
852	int err = X509_V_ERR_UNSPECIFIED;
853
854	if (current_chain == NULL)
855		return 1;
856
857	if (cert->nc != NULL) {
858		if ((permitted = x509_constraints_names_new(
859		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
860			err = X509_V_ERR_OUT_OF_MEM;
861			goto err;
862		}
863		if ((excluded = x509_constraints_names_new(
864		    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
865			err = X509_V_ERR_OUT_OF_MEM;
866			goto err;
867		}
868		if (!x509_constraints_extract_constraints(cert,
869		    permitted, excluded, &err))
870			goto err;
871		if (!x509_constraints_check(current_chain->names,
872		    permitted, excluded, &err))
873			goto err;
874		x509_constraints_names_free(excluded);
875		x509_constraints_names_free(permitted);
876	}
877
878	return 1;
879 err:
880	*error = err;
881	x509_constraints_names_free(excluded);
882	x509_constraints_names_free(permitted);
883	return 0;
884}
885
886static int
887x509_verify_cert_extensions(struct x509_verify_ctx *ctx, X509 *cert, int need_ca)
888{
889	if (!x509_verify_cert_cache_extensions(cert)) {
890		ctx->error = X509_V_ERR_UNSPECIFIED;
891		return 0;
892	}
893
894	if (ctx->xsc != NULL)
895		return 1;	/* legacy is checked after chain is built */
896
897	if (cert->ex_flags & EXFLAG_CRITICAL) {
898		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
899		return 0;
900	}
901	/* No we don't care about v1, netscape, and other ancient silliness */
902	if (need_ca && (!(cert->ex_flags & EXFLAG_BCONS) &&
903	    (cert->ex_flags & EXFLAG_CA))) {
904		ctx->error = X509_V_ERR_INVALID_CA;
905		return 0;
906	}
907	if (ctx->purpose > 0 && X509_check_purpose(cert, ctx->purpose, need_ca)) {
908		ctx->error = X509_V_ERR_INVALID_PURPOSE;
909		return 0;
910	}
911
912	return 1;
913}
914
915/* Validate that cert is a possible candidate to append to current_chain */
916static int
917x509_verify_cert_valid(struct x509_verify_ctx *ctx, X509 *cert,
918    struct x509_verify_chain *current_chain)
919{
920	X509 *issuer_candidate;
921	int should_be_ca = current_chain != NULL;
922	size_t depth = 0;
923
924	if (current_chain != NULL)
925		depth = sk_X509_num(current_chain->certs);
926
927	if (!x509_verify_cert_extensions(ctx, cert, should_be_ca))
928		return 0;
929
930	if (should_be_ca) {
931		issuer_candidate = x509_verify_chain_last(current_chain);
932		if (issuer_candidate != NULL &&
933		    !X509_check_issued(issuer_candidate, cert))
934			if (!x509_verify_cert_error(ctx, cert, depth,
935			    X509_V_ERR_SUBJECT_ISSUER_MISMATCH, 0))
936				return 0;
937	}
938
939	if (x509_verify_set_check_time(ctx)) {
940		if (!x509_verify_cert_times(cert, ctx->check_time,
941		    &ctx->error)) {
942			if (!x509_verify_cert_error(ctx, cert, depth,
943			    ctx->error, 0))
944				return 0;
945		}
946	}
947
948	if (!x509_verify_validate_constraints(cert, current_chain,
949	    &ctx->error) && !x509_verify_cert_error(ctx, cert, depth,
950	    ctx->error, 0))
951		return 0;
952
953	return 1;
954}
955
956struct x509_verify_ctx *
957x509_verify_ctx_new_from_xsc(X509_STORE_CTX *xsc)
958{
959	struct x509_verify_ctx *ctx;
960	size_t max_depth;
961
962	if (xsc == NULL)
963		return NULL;
964
965	if ((ctx = x509_verify_ctx_new(NULL)) == NULL)
966		return NULL;
967
968	ctx->xsc = xsc;
969
970	if (xsc->untrusted &&
971	    (ctx->intermediates = X509_chain_up_ref(xsc->untrusted)) == NULL)
972		goto err;
973
974	max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
975	if (xsc->param->depth > 0 && xsc->param->depth < X509_VERIFY_MAX_CHAIN_CERTS)
976		max_depth = xsc->param->depth;
977	if (!x509_verify_ctx_set_max_depth(ctx, max_depth))
978		goto err;
979
980	return ctx;
981 err:
982	x509_verify_ctx_free(ctx);
983	return NULL;
984}
985
986/* Public API */
987
988struct x509_verify_ctx *
989x509_verify_ctx_new(STACK_OF(X509) *roots)
990{
991	struct x509_verify_ctx *ctx;
992
993	if ((ctx = calloc(1, sizeof(struct x509_verify_ctx))) == NULL)
994		return NULL;
995
996	if (roots != NULL) {
997		if  ((ctx->roots = X509_chain_up_ref(roots)) == NULL)
998			goto err;
999	} else {
1000		if ((ctx->roots = sk_X509_new_null()) == NULL)
1001			goto err;
1002	}
1003
1004	ctx->max_depth = X509_VERIFY_MAX_CHAIN_CERTS;
1005	ctx->max_chains = X509_VERIFY_MAX_CHAINS;
1006	ctx->max_sigs = X509_VERIFY_MAX_SIGCHECKS;
1007
1008	if ((ctx->chains = calloc(X509_VERIFY_MAX_CHAINS,
1009	    sizeof(*ctx->chains))) == NULL)
1010		goto err;
1011
1012	return ctx;
1013 err:
1014	x509_verify_ctx_free(ctx);
1015	return NULL;
1016}
1017
1018void
1019x509_verify_ctx_free(struct x509_verify_ctx *ctx)
1020{
1021	if (ctx == NULL)
1022		return;
1023	sk_X509_pop_free(ctx->roots, X509_free);
1024	x509_verify_ctx_clear(ctx);
1025	free(ctx);
1026}
1027
1028int
1029x509_verify_ctx_set_max_depth(struct x509_verify_ctx *ctx, size_t max)
1030{
1031	if (max < 1 || max > X509_VERIFY_MAX_CHAIN_CERTS)
1032		return 0;
1033	ctx->max_depth = max;
1034	return 1;
1035}
1036
1037int
1038x509_verify_ctx_set_max_chains(struct x509_verify_ctx *ctx, size_t max)
1039{
1040	if (max < 1 || max > X509_VERIFY_MAX_CHAINS)
1041		return 0;
1042	ctx->max_chains = max;
1043	return 1;
1044}
1045
1046int
1047x509_verify_ctx_set_max_signatures(struct x509_verify_ctx *ctx, size_t max)
1048{
1049	if (max < 1 || max > 100000)
1050		return 0;
1051	ctx->max_sigs = max;
1052	return 1;
1053}
1054
1055int
1056x509_verify_ctx_set_purpose(struct x509_verify_ctx *ctx, int purpose)
1057{
1058	if (purpose < X509_PURPOSE_MIN || purpose > X509_PURPOSE_MAX)
1059		return 0;
1060	ctx->purpose = purpose;
1061	return 1;
1062}
1063
1064int
1065x509_verify_ctx_set_intermediates(struct x509_verify_ctx *ctx,
1066    STACK_OF(X509) *intermediates)
1067{
1068	if ((ctx->intermediates = X509_chain_up_ref(intermediates)) == NULL)
1069		return 0;
1070	return 1;
1071}
1072
1073const char *
1074x509_verify_ctx_error_string(struct x509_verify_ctx *ctx)
1075{
1076	return X509_verify_cert_error_string(ctx->error);
1077}
1078
1079size_t
1080x509_verify_ctx_error_depth(struct x509_verify_ctx *ctx)
1081{
1082	return ctx->error_depth;
1083}
1084
1085STACK_OF(X509) *
1086x509_verify_ctx_chain(struct x509_verify_ctx *ctx, size_t i)
1087{
1088	if (i >= ctx->chains_count)
1089		return NULL;
1090	return ctx->chains[i]->certs;
1091}
1092
1093size_t
1094x509_verify(struct x509_verify_ctx *ctx, X509 *leaf, char *name)
1095{
1096	struct x509_verify_chain *current_chain;
1097	int retry_chain_build, full_chain = 0;
1098
1099	if (ctx->roots == NULL || ctx->max_depth == 0) {
1100		ctx->error = X509_V_ERR_INVALID_CALL;
1101		goto err;
1102	}
1103
1104	if (ctx->xsc != NULL) {
1105		if (leaf != NULL || name != NULL) {
1106			ctx->error = X509_V_ERR_INVALID_CALL;
1107			goto err;
1108		}
1109		leaf = ctx->xsc->cert;
1110
1111		/* XXX */
1112		full_chain = 1;
1113		if (ctx->xsc->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
1114			full_chain = 0;
1115		/*
1116		 * XXX
1117		 * The legacy code expects the top level cert to be
1118		 * there, even if we didn't find a chain. So put it
1119		 * there, we will clobber it later if we find a valid
1120		 * chain.
1121		 */
1122		if ((ctx->xsc->chain = sk_X509_new_null()) == NULL) {
1123			ctx->error = X509_V_ERR_OUT_OF_MEM;
1124			goto err;
1125		}
1126		if (!X509_up_ref(leaf)) {
1127			ctx->error = X509_V_ERR_OUT_OF_MEM;
1128			goto err;
1129		}
1130		if (!sk_X509_push(ctx->xsc->chain, leaf)) {
1131			X509_free(leaf);
1132			ctx->error = X509_V_ERR_OUT_OF_MEM;
1133			goto err;
1134		}
1135		ctx->xsc->error_depth = 0;
1136		ctx->xsc->current_cert = leaf;
1137	}
1138
1139	if ((current_chain = x509_verify_chain_new()) == NULL) {
1140		ctx->error = X509_V_ERR_OUT_OF_MEM;
1141		goto err;
1142	}
1143
1144	/*
1145	 * Add the leaf to the chain and try to build chains from it.
1146	 * Note that unlike Go's verifier, we have not yet checked
1147	 * anything about the leaf, This is intentional, so that we
1148	 * report failures in chain building before we report problems
1149	 * with the leaf.
1150	 */
1151	if (!x509_verify_chain_append(current_chain, leaf, &ctx->error)) {
1152		x509_verify_chain_free(current_chain);
1153		goto err;
1154	}
1155	do {
1156		retry_chain_build = 0;
1157		if (x509_verify_ctx_cert_is_root(ctx, leaf, full_chain)) {
1158			if (!x509_verify_ctx_add_chain(ctx, current_chain,
1159			    name)) {
1160				x509_verify_chain_free(current_chain);
1161				goto err;
1162			}
1163		} else {
1164			x509_verify_build_chains(ctx, leaf, current_chain,
1165			    full_chain, name);
1166			if (full_chain && ctx->chains_count == 0) {
1167				/*
1168				 * Save the error state from the xsc
1169				 * at this point to put back on the
1170				 * xsc in case we do not find a chain
1171				 * that is trusted but not a full
1172				 * chain to a self signed root. This
1173				 * is because the unvalidated chain is
1174				 * used by the autochain batshittery
1175				 * on failure and will be needed for
1176				 * that.
1177				 */
1178				ctx->xsc->error_depth = ctx->error_depth;
1179				if (!x509_verify_ctx_save_xsc_error(ctx)) {
1180					x509_verify_chain_free(current_chain);
1181					goto err;
1182				}
1183				full_chain = 0;
1184				retry_chain_build = 1;
1185			}
1186		}
1187	} while (retry_chain_build);
1188
1189	x509_verify_chain_free(current_chain);
1190
1191	/*
1192	 * Do the new verifier style return, where we don't have an xsc
1193	 * that allows a crazy callback to turn invalid things into valid.
1194	 */
1195	if (ctx->xsc == NULL) {
1196		/*
1197		 * Safety net:
1198		 * We could not find a validated chain, and for some reason do not
1199		 * have an error set.
1200		 */
1201		if (ctx->chains_count == 0 && ctx->error == X509_V_OK)
1202			ctx->error = X509_V_ERR_UNSPECIFIED;
1203
1204		/*
1205		 * If we are not using an xsc, and have no possibility for the
1206		 * crazy OpenSSL callback API changing the results of
1207		 * validation steps (because the callback can make validation
1208		 * proceed in the presence of invalid certs), any chains we
1209		 * have here are correctly built and verified.
1210		 */
1211		if (ctx->chains_count > 0)
1212			ctx->error = X509_V_OK;
1213
1214		return ctx->chains_count;
1215	}
1216
1217	/*
1218	 * Otherwise we are doing compatibility with an xsc, which means that we
1219	 * will have one chain, which might actually be a bogus chain because
1220	 * the callback told us to ignore errors and proceed to build an invalid
1221	 * chain. Possible return values from this include returning 1 with an
1222	 * invalid chain and a value of xsc->error != X509_V_OK (It's tradition
1223	 * that makes it ok).
1224	 */
1225
1226	if (ctx->chains_count > 0) {
1227		/*
1228		 * The chain we have using an xsc might not be a verified chain
1229		 * if the callback perverted things while we built it to ignore
1230		 * failures and proceed with chain building. We put this chain
1231		 * and the error associated with it on the xsc.
1232		 */
1233		if (!x509_verify_ctx_set_xsc_chain(ctx, ctx->chains[0], 1, 1))
1234			goto err;
1235
1236		/*
1237		 * Call the callback for completion up our built
1238		 * chain. The callback could still tell us to
1239		 * fail. Since this chain might exist as the result of
1240		 * callback doing perversions, we could still return
1241		 * "success" with something other than X509_V_OK set
1242		 * as the error.
1243		 */
1244		if (!x509_vfy_callback_indicate_completion(ctx->xsc))
1245			goto err;
1246	} else {
1247		/*
1248		 * We did not find a chain. Bring back the failure
1249		 * case we wanted to the xsc if we saved one. If we
1250		 * did not we should have just the leaf on the xsc.
1251		 */
1252		if (!x509_verify_ctx_restore_xsc_error(ctx))
1253			goto err;
1254
1255		/*
1256		 * Safety net, ensure we have an error set in the
1257		 * failing case.
1258		 */
1259		if (ctx->xsc->error == X509_V_OK) {
1260			if (ctx->error == X509_V_OK)
1261				ctx->error = X509_V_ERR_UNSPECIFIED;
1262			ctx->xsc->error = ctx->error;
1263		}
1264
1265		/*
1266		 * Let the callback override the return value
1267		 * at depth 0 if it chooses to
1268		 */
1269		return ctx->xsc->verify_cb(0, ctx->xsc);
1270	}
1271
1272	/* We only ever find one chain in compat mode with an xsc. */
1273	return 1;
1274
1275 err:
1276	if (ctx->error == X509_V_OK)
1277		ctx->error = X509_V_ERR_UNSPECIFIED;
1278
1279	if (ctx->xsc != NULL) {
1280		if (ctx->xsc->error == X509_V_OK)
1281			ctx->xsc->error = X509_V_ERR_UNSPECIFIED;
1282		ctx->error = ctx->xsc->error;
1283	}
1284
1285	return 0;
1286}
1287