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