xref: /openbsd-src/lib/libcrypto/x509/x509_vfy.c (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 /* $OpenBSD: x509_vfy.c,v 1.89 2021/09/03 08:58:53 beck Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <errno.h>
60 #include <stdio.h>
61 #include <string.h>
62 #include <time.h>
63 #include <unistd.h>
64 
65 #include <openssl/opensslconf.h>
66 
67 #include <openssl/asn1.h>
68 #include <openssl/buffer.h>
69 #include <openssl/crypto.h>
70 #include <openssl/err.h>
71 #include <openssl/evp.h>
72 #include <openssl/lhash.h>
73 #include <openssl/objects.h>
74 #include <openssl/x509.h>
75 #include <openssl/x509v3.h>
76 #include "asn1_locl.h"
77 #include "vpm_int.h"
78 #include "x509_internal.h"
79 #include "x509_lcl.h"
80 #include "x509_internal.h"
81 
82 /* CRL score values */
83 
84 /* No unhandled critical extensions */
85 
86 #define CRL_SCORE_NOCRITICAL	0x100
87 
88 /* certificate is within CRL scope */
89 
90 #define CRL_SCORE_SCOPE		0x080
91 
92 /* CRL times valid */
93 
94 #define CRL_SCORE_TIME		0x040
95 
96 /* Issuer name matches certificate */
97 
98 #define CRL_SCORE_ISSUER_NAME	0x020
99 
100 /* If this score or above CRL is probably valid */
101 
102 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
103 
104 /* CRL issuer is certificate issuer */
105 
106 #define CRL_SCORE_ISSUER_CERT	0x018
107 
108 /* CRL issuer is on certificate path */
109 
110 #define CRL_SCORE_SAME_PATH	0x008
111 
112 /* CRL issuer matches CRL AKID */
113 
114 #define CRL_SCORE_AKID		0x004
115 
116 /* Have a delta CRL with valid times */
117 
118 #define CRL_SCORE_TIME_DELTA	0x002
119 
120 static int null_callback(int ok, X509_STORE_CTX *e);
121 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
122 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x,
123     int allow_expired);
124 static int check_chain_extensions(X509_STORE_CTX *ctx);
125 static int check_name_constraints(X509_STORE_CTX *ctx);
126 static int check_trust(X509_STORE_CTX *ctx);
127 static int check_revocation(X509_STORE_CTX *ctx);
128 static int check_cert(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, int depth);
129 static int check_policy(X509_STORE_CTX *ctx);
130 
131 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
132     unsigned int *preasons, X509_CRL *crl, X509 *x);
133 static int get_crl_delta(X509_STORE_CTX *ctx,
134     X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
135 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pcrl_score,
136     X509_CRL *base, STACK_OF(X509_CRL) *crls);
137 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
138     int *pcrl_score);
139 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
140     unsigned int *preasons);
141 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
142 static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
143     STACK_OF(X509) *crl_path);
144 static int X509_cmp_time_internal(const ASN1_TIME *ctm, time_t *cmp_time,
145     int clamp_notafter);
146 
147 static int internal_verify(X509_STORE_CTX *ctx);
148 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
149 
150 int ASN1_time_tm_clamp_notafter(struct tm *tm);
151 
152 static int
153 null_callback(int ok, X509_STORE_CTX *e)
154 {
155 	return ok;
156 }
157 
158 #if 0
159 static int
160 x509_subject_cmp(X509 **a, X509 **b)
161 {
162 	return X509_subject_name_cmp(*a, *b);
163 }
164 #endif
165 
166 /* Return 1 if a certificate is self signed */
167 static int
168 cert_self_signed(X509 *x)
169 {
170 	X509_check_purpose(x, -1, 0);
171 	if (x->ex_flags & EXFLAG_SS)
172 		return 1;
173 	else
174 		return 0;
175 }
176 
177 static int
178 check_id_error(X509_STORE_CTX *ctx, int errcode)
179 {
180 	ctx->error = errcode;
181 	ctx->current_cert = ctx->cert;
182 	ctx->error_depth = 0;
183 	return ctx->verify_cb(0, ctx);
184 }
185 
186 static int
187 check_hosts(X509 *x, X509_VERIFY_PARAM_ID *id)
188 {
189 	size_t i, n;
190 	char *name;
191 
192 	n = sk_OPENSSL_STRING_num(id->hosts);
193 	free(id->peername);
194 	id->peername = NULL;
195 
196 	for (i = 0; i < n; ++i) {
197 		name = sk_OPENSSL_STRING_value(id->hosts, i);
198 		if (X509_check_host(x, name, strlen(name), id->hostflags,
199 		    &id->peername) > 0)
200 			return 1;
201 	}
202 	return n == 0;
203 }
204 
205 static int
206 check_id(X509_STORE_CTX *ctx)
207 {
208 	X509_VERIFY_PARAM *vpm = ctx->param;
209 	X509_VERIFY_PARAM_ID *id = vpm->id;
210 	X509 *x = ctx->cert;
211 
212 	if (id->hosts && check_hosts(x, id) <= 0) {
213 		if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
214 			return 0;
215 	}
216 	if (id->email != NULL && X509_check_email(x, id->email, id->emaillen, 0)
217 	    <= 0) {
218 		if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
219 			return 0;
220 	}
221 	if (id->ip != NULL && X509_check_ip(x, id->ip, id->iplen, 0) <= 0) {
222 		if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
223 			return 0;
224 	}
225 	return 1;
226 }
227 
228 int
229 x509_vfy_check_id(X509_STORE_CTX *ctx) {
230 	return check_id(ctx);
231 }
232 
233 /*
234  * This is the effectively broken legacy OpenSSL chain builder. It
235  * might find an unvalidated chain and leave it sitting in
236  * ctx->chain. It does not correctly handle many cases where multiple
237  * chains could exist.
238  *
239  * Oh no.. I know a dirty word...
240  * Oooooooh..
241  */
242 static int
243 X509_verify_cert_legacy_build_chain(X509_STORE_CTX *ctx, int *bad, int *out_ok)
244 {
245 	X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
246 	int bad_chain = 0;
247 	X509_VERIFY_PARAM *param = ctx->param;
248 	int ok = 0, ret = 0;
249 	int depth, i;
250 	int num, j, retry, trust;
251 	int (*cb) (int xok, X509_STORE_CTX *xctx);
252 	STACK_OF(X509) *sktmp = NULL;
253 
254 	cb = ctx->verify_cb;
255 
256 	/*
257 	 * First we make sure the chain we are going to build is
258 	 * present and that the first entry is in place.
259 	 */
260 	ctx->chain = sk_X509_new_null();
261 	if (ctx->chain == NULL || !sk_X509_push(ctx->chain, ctx->cert)) {
262 		X509error(ERR_R_MALLOC_FAILURE);
263 		ctx->error = X509_V_ERR_OUT_OF_MEM;
264 		goto end;
265 	}
266 	X509_up_ref(ctx->cert);
267 	ctx->last_untrusted = 1;
268 
269 	/* We use a temporary STACK so we can chop and hack at it */
270 	if (ctx->untrusted != NULL &&
271 	    (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
272 		X509error(ERR_R_MALLOC_FAILURE);
273 		ctx->error = X509_V_ERR_OUT_OF_MEM;
274 		goto end;
275 	}
276 
277 	num = sk_X509_num(ctx->chain);
278 	x = sk_X509_value(ctx->chain, num - 1);
279 	depth = param->depth;
280 
281 	for (;;) {
282 		/* If we have enough, we break */
283 		/* FIXME: If this happens, we should take
284 		 * note of it and, if appropriate, use the
285 		 * X509_V_ERR_CERT_CHAIN_TOO_LONG error code
286 		 * later.
287 		 */
288 		if (depth < num)
289 			break;
290 		/* If we are self signed, we break */
291 		if (cert_self_signed(x))
292 			break;
293 		/*
294 		 * If asked see if we can find issuer in trusted store first
295 		 */
296 		if (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) {
297 			ok = ctx->get_issuer(&xtmp, ctx, x);
298 			if (ok < 0) {
299 				ctx->error = X509_V_ERR_STORE_LOOKUP;
300 				goto end;
301 			}
302 			/*
303 			 * If successful for now free up cert so it
304 			 * will be picked up again later.
305 			 */
306 			if (ok > 0) {
307 				X509_free(xtmp);
308 				break;
309 			}
310 		}
311 		/* If we were passed a cert chain, use it first */
312 		if (ctx->untrusted != NULL) {
313 			/*
314 			 * If we do not find a non-expired untrusted cert, peek
315 			 * ahead and see if we can satisify this from the trusted
316 			 * store. If not, see if we have an expired untrusted cert.
317 			 */
318 			xtmp = find_issuer(ctx, sktmp, x, 0);
319 			if (xtmp == NULL &&
320 			    !(ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)) {
321 				ok = ctx->get_issuer(&xtmp, ctx, x);
322 				if (ok < 0) {
323 					ctx->error = X509_V_ERR_STORE_LOOKUP;
324 					goto end;
325 				}
326 				if (ok > 0) {
327 					X509_free(xtmp);
328 					break;
329 				}
330 				xtmp = find_issuer(ctx, sktmp, x, 1);
331 			}
332 			if (xtmp != NULL) {
333 				if (!sk_X509_push(ctx->chain, xtmp)) {
334 					X509error(ERR_R_MALLOC_FAILURE);
335 					ctx->error = X509_V_ERR_OUT_OF_MEM;
336 					ok = 0;
337 					goto end;
338 				}
339 				X509_up_ref(xtmp);
340 				(void)sk_X509_delete_ptr(sktmp, xtmp);
341 				ctx->last_untrusted++;
342 				x = xtmp;
343 				num++;
344 				/*
345 				 * reparse the full chain for the next one
346 				 */
347 				continue;
348 			}
349 		}
350 		break;
351 	}
352 	/* Remember how many untrusted certs we have */
353 	j = num;
354 
355 	/*
356 	 * At this point, chain should contain a list of untrusted
357 	 * certificates.  We now need to add at least one trusted one,
358 	 * if possible, otherwise we complain.
359 	 */
360 
361 	do {
362 		/*
363 		 * Examine last certificate in chain and see if it is
364 		 * self signed.
365 		 */
366 		i = sk_X509_num(ctx->chain);
367 		x = sk_X509_value(ctx->chain, i - 1);
368 		if (cert_self_signed(x)) {
369 			/* we have a self signed certificate */
370 			if (i == 1) {
371 				/*
372 				 * We have a single self signed
373 				 * certificate: see if we can find it
374 				 * in the store. We must have an exact
375 				 * match to avoid possible
376 				 * impersonation.
377 				 */
378 				ok = ctx->get_issuer(&xtmp, ctx, x);
379 				if ((ok <= 0) || X509_cmp(x, xtmp)) {
380 					ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
381 					ctx->current_cert = x;
382 					ctx->error_depth = i - 1;
383 					if (ok == 1)
384 						X509_free(xtmp);
385 					bad_chain = 1;
386 					ok = cb(0, ctx);
387 					if (!ok)
388 						goto end;
389 				} else {
390 					/*
391 					 * We have a match: replace
392 					 * certificate with store
393 					 * version so we get any trust
394 					 * settings.
395 					 */
396 					X509_free(x);
397 					x = xtmp;
398 					(void)sk_X509_set(ctx->chain, i - 1, x);
399 					ctx->last_untrusted = 0;
400 				}
401 			} else {
402 				/*
403 				 * extract and save self signed
404 				 * certificate for later use
405 				 */
406 				chain_ss = sk_X509_pop(ctx->chain);
407 				ctx->last_untrusted--;
408 				num--;
409 				j--;
410 				x = sk_X509_value(ctx->chain, num - 1);
411 			}
412 		}
413 		/* We now lookup certs from the certificate store */
414 		for (;;) {
415 			/* If we have enough, we break */
416 			if (depth < num)
417 				break;
418 			/* If we are self signed, we break */
419 			if (cert_self_signed(x))
420 				break;
421 			ok = ctx->get_issuer(&xtmp, ctx, x);
422 
423 			if (ok < 0) {
424 				ctx->error = X509_V_ERR_STORE_LOOKUP;
425 				goto end;
426 			}
427 			if (ok == 0)
428 				break;
429 			x = xtmp;
430 			if (!sk_X509_push(ctx->chain, x)) {
431 				X509_free(xtmp);
432 				X509error(ERR_R_MALLOC_FAILURE);
433 				ctx->error = X509_V_ERR_OUT_OF_MEM;
434 				ok = 0;
435 				goto end;
436 			}
437 			num++;
438 		}
439 
440 		/* we now have our chain, lets check it... */
441 		trust = check_trust(ctx);
442 
443 		/* If explicitly rejected error */
444 		if (trust == X509_TRUST_REJECTED) {
445 			ok = 0;
446 			goto end;
447 		}
448 		/*
449 		 * If it's not explicitly trusted then check if there
450 		 * is an alternative chain that could be used. We only
451 		 * do this if we haven't already checked via
452 		 * TRUSTED_FIRST and the user hasn't switched off
453 		 * alternate chain checking
454 		 */
455 		retry = 0;
456 		if (trust != X509_TRUST_TRUSTED &&
457 		    !(ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) &&
458 		    !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
459 			while (j-- > 1) {
460 				xtmp2 = sk_X509_value(ctx->chain, j - 1);
461 				ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
462 				if (ok < 0)
463 					goto end;
464 				/* Check if we found an alternate chain */
465 				if (ok > 0) {
466 					/*
467 					 * Free up the found cert
468 					 * we'll add it again later
469 					 */
470 					X509_free(xtmp);
471 					/*
472 					 * Dump all the certs above
473 					 * this point - we've found an
474 					 * alternate chain
475 					 */
476 					while (num > j) {
477 						xtmp = sk_X509_pop(ctx->chain);
478 						X509_free(xtmp);
479 						num--;
480 					}
481 					ctx->last_untrusted = sk_X509_num(ctx->chain);
482 					retry = 1;
483 					break;
484 				}
485 			}
486 		}
487 	} while (retry);
488 
489 	/*
490 	 * If not explicitly trusted then indicate error unless it's a single
491 	 * self signed certificate in which case we've indicated an error already
492 	 * and set bad_chain == 1
493 	 */
494 	if (trust != X509_TRUST_TRUSTED && !bad_chain) {
495 		if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
496 			if (ctx->last_untrusted >= num)
497 				ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
498 			else
499 				ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
500 			ctx->current_cert = x;
501 		} else {
502 			if (!sk_X509_push(ctx->chain, chain_ss)) {
503 				X509error(ERR_R_MALLOC_FAILURE);
504 				ctx->error = X509_V_ERR_OUT_OF_MEM;
505 				ok = 0;
506 				goto end;
507 			}
508 			num++;
509 			ctx->last_untrusted = num;
510 			ctx->current_cert = chain_ss;
511 			ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
512 			chain_ss = NULL;
513 		}
514 
515 		ctx->error_depth = num - 1;
516 		bad_chain = 1;
517 		ok = cb(0, ctx);
518 		if (!ok)
519 			goto end;
520 	}
521 
522 	ret = 1;
523  end:
524 	sk_X509_free(sktmp);
525 	X509_free(chain_ss);
526 	*bad = bad_chain;
527 	*out_ok = ok;
528 
529 	return ret;
530 }
531 
532 static int
533 X509_verify_cert_legacy(X509_STORE_CTX *ctx)
534 {
535 	int ok = 0, bad_chain;
536 
537 	ctx->error = X509_V_OK; /* Initialize to OK */
538 
539 	if (!X509_verify_cert_legacy_build_chain(ctx, &bad_chain, &ok))
540 		goto end;
541 
542 	/* We have the chain complete: now we need to check its purpose */
543 	ok = check_chain_extensions(ctx);
544 	if (!ok)
545 		goto end;
546 
547 	/* Check name constraints */
548 	ok = check_name_constraints(ctx);
549 	if (!ok)
550 		goto end;
551 
552 	ok = check_id(ctx);
553 	if (!ok)
554 		goto end;
555 
556 	/*
557 	 * Check revocation status: we do this after copying parameters because
558 	 * they may be needed for CRL signature verification.
559 	 */
560 	ok = ctx->check_revocation(ctx);
561 	if (!ok)
562 		goto end;
563 
564 	/* At this point, we have a chain and need to verify it */
565 	if (ctx->verify != NULL)
566 		ok = ctx->verify(ctx);
567 	else
568 		ok = internal_verify(ctx);
569 	if (!ok)
570 		goto end;
571 
572 	/* If we get this far evaluate policies */
573 	if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
574 		ok = ctx->check_policy(ctx);
575 
576  end:
577 	/* Safety net, error returns must set ctx->error */
578 	if (ok <= 0 && ctx->error == X509_V_OK)
579 		ctx->error = X509_V_ERR_UNSPECIFIED;
580 
581 	return ok;
582 }
583 
584 int
585 X509_verify_cert(X509_STORE_CTX *ctx)
586 {
587 	STACK_OF(X509) *roots = NULL;
588 	struct x509_verify_ctx *vctx = NULL;
589 	int chain_count = 0;
590 
591 	if (ctx->cert == NULL) {
592 		X509error(X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
593 		ctx->error = X509_V_ERR_INVALID_CALL;
594 		return -1;
595 	}
596 	if (ctx->chain != NULL) {
597 		/*
598 		 * This X509_STORE_CTX has already been used to verify
599 		 * a cert. We cannot do another one.
600 		 */
601 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
602 		ctx->error = X509_V_ERR_INVALID_CALL;
603 		return -1;
604 	}
605 	if (ctx->param->id->poisoned) {
606 		/*
607 		 * This X509_STORE_CTX had failures setting
608 		 * up verify parameters. We can not use it.
609 		 */
610 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
611 		ctx->error = X509_V_ERR_INVALID_CALL;
612 		return -1;
613 	}
614 	if (ctx->error != X509_V_ERR_INVALID_CALL) {
615 		/*
616 		 * This X509_STORE_CTX has not been properly initialized.
617 		 */
618 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
619 		ctx->error = X509_V_ERR_INVALID_CALL;
620 		return -1;
621 	}
622 
623 	/*
624 	 * If flags request legacy, use the legacy verifier. If we
625 	 * requested "no alt chains" from the age of hammer pants, use
626 	 * the legacy verifier because the multi chain verifier really
627 	 * does find all the "alt chains".
628 	 *
629 	 * XXX deprecate the NO_ALT_CHAINS flag?
630 	 */
631 	if ((ctx->param->flags & X509_V_FLAG_LEGACY_VERIFY) ||
632 	    (ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
633 		return X509_verify_cert_legacy(ctx);
634 
635 	/* Use the modern multi-chain verifier from x509_verify_cert */
636 
637 	if ((vctx = x509_verify_ctx_new_from_xsc(ctx)) != NULL) {
638 		ctx->error = X509_V_OK; /* Initialize to OK */
639 		chain_count = x509_verify(vctx, NULL, NULL);
640 	}
641 	x509_verify_ctx_free(vctx);
642 
643 	sk_X509_pop_free(roots, X509_free);
644 
645 	/* if we succeed we have a chain in ctx->chain */
646 	return (chain_count > 0 && ctx->chain != NULL);
647 }
648 
649 /* Given a STACK_OF(X509) find the issuer of cert (if any)
650  */
651 
652 static X509 *
653 find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x,
654     int allow_expired)
655 {
656 	int i;
657 	X509 *issuer, *rv = NULL;
658 
659 	for (i = 0; i < sk_X509_num(sk); i++) {
660 		issuer = sk_X509_value(sk, i);
661 		if (ctx->check_issued(ctx, x, issuer)) {
662 			if (x509_check_cert_time(ctx, issuer, -1))
663 				return issuer;
664 			if (allow_expired)
665 				rv = issuer;
666 		}
667 	}
668 	return rv;
669 }
670 
671 /* Given a possible certificate and issuer check them */
672 
673 static int
674 check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
675 {
676 	int ret;
677 
678 	ret = X509_check_issued(issuer, x);
679 	if (ret == X509_V_OK)
680 		return 1;
681 	/* If we haven't asked for issuer errors don't set ctx */
682 	if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
683 		return 0;
684 
685 	ctx->error = ret;
686 	ctx->current_cert = x;
687 	ctx->current_issuer = issuer;
688 	return ctx->verify_cb(0, ctx);
689 }
690 
691 /* Alternative lookup method: look from a STACK stored in other_ctx */
692 
693 static int
694 get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
695 {
696 	*issuer = find_issuer(ctx, ctx->other_ctx, x, 1);
697 	if (*issuer) {
698 		CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
699 		return 1;
700 	} else
701 		return 0;
702 }
703 
704 /* Check a certificate chains extensions for consistency
705  * with the supplied purpose
706  */
707 
708 int
709 x509_vfy_check_chain_extensions(X509_STORE_CTX *ctx)
710 {
711 #ifdef OPENSSL_NO_CHAIN_VERIFY
712 	return 1;
713 #else
714 	int i, ok = 0, must_be_ca, plen = 0;
715 	X509 *x;
716 	int (*cb)(int xok, X509_STORE_CTX *xctx);
717 	int proxy_path_length = 0;
718 	int purpose;
719 	int allow_proxy_certs;
720 
721 	cb = ctx->verify_cb;
722 
723 	/* must_be_ca can have 1 of 3 values:
724 	   -1: we accept both CA and non-CA certificates, to allow direct
725 	       use of self-signed certificates (which are marked as CA).
726 	   0:  we only accept non-CA certificates.  This is currently not
727 	       used, but the possibility is present for future extensions.
728 	   1:  we only accept CA certificates.  This is currently used for
729 	       all certificates in the chain except the leaf certificate.
730 	*/
731 	must_be_ca = -1;
732 
733 	/* CRL path validation */
734 	if (ctx->parent) {
735 		allow_proxy_certs = 0;
736 		purpose = X509_PURPOSE_CRL_SIGN;
737 	} else {
738 		allow_proxy_certs =
739 		    !!(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
740 		purpose = ctx->param->purpose;
741 	}
742 
743 	/* Check all untrusted certificates */
744 	for (i = 0; i < ctx->last_untrusted; i++) {
745 		int ret;
746 		x = sk_X509_value(ctx->chain, i);
747 		if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
748 		    (x->ex_flags & EXFLAG_CRITICAL)) {
749 			ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
750 			ctx->error_depth = i;
751 			ctx->current_cert = x;
752 			ok = cb(0, ctx);
753 			if (!ok)
754 				goto end;
755 		}
756 		if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
757 			ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
758 			ctx->error_depth = i;
759 			ctx->current_cert = x;
760 			ok = cb(0, ctx);
761 			if (!ok)
762 				goto end;
763 		}
764 		ret = X509_check_ca(x);
765 		switch (must_be_ca) {
766 		case -1:
767 			if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
768 			    (ret != 1) && (ret != 0)) {
769 				ret = 0;
770 				ctx->error = X509_V_ERR_INVALID_CA;
771 			} else
772 				ret = 1;
773 			break;
774 		case 0:
775 			if (ret != 0) {
776 				ret = 0;
777 				ctx->error = X509_V_ERR_INVALID_NON_CA;
778 			} else
779 				ret = 1;
780 			break;
781 		default:
782 			if ((ret == 0) ||
783 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
784 			    (ret != 1))) {
785 				ret = 0;
786 				ctx->error = X509_V_ERR_INVALID_CA;
787 			} else
788 				ret = 1;
789 			break;
790 		}
791 		if (ret == 0) {
792 			ctx->error_depth = i;
793 			ctx->current_cert = x;
794 			ok = cb(0, ctx);
795 			if (!ok)
796 				goto end;
797 		}
798 		if (ctx->param->purpose > 0) {
799 			ret = X509_check_purpose(x, purpose, must_be_ca > 0);
800 			if ((ret == 0) ||
801 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
802 			    (ret != 1))) {
803 				ctx->error = X509_V_ERR_INVALID_PURPOSE;
804 				ctx->error_depth = i;
805 				ctx->current_cert = x;
806 				ok = cb(0, ctx);
807 				if (!ok)
808 					goto end;
809 			}
810 		}
811 		/* Check pathlen if not self issued */
812 		if ((i > 1) && !(x->ex_flags & EXFLAG_SI) &&
813 		    (x->ex_pathlen != -1) &&
814 		    (plen > (x->ex_pathlen + proxy_path_length + 1))) {
815 			ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
816 			ctx->error_depth = i;
817 			ctx->current_cert = x;
818 			ok = cb(0, ctx);
819 			if (!ok)
820 				goto end;
821 		}
822 		/* Increment path length if not self issued */
823 		if (!(x->ex_flags & EXFLAG_SI))
824 			plen++;
825 		/* If this certificate is a proxy certificate, the next
826 		   certificate must be another proxy certificate or a EE
827 		   certificate.  If not, the next certificate must be a
828 		   CA certificate.  */
829 		if (x->ex_flags & EXFLAG_PROXY) {
830 			if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
831 				ctx->error =
832 				    X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
833 				ctx->error_depth = i;
834 				ctx->current_cert = x;
835 				ok = cb(0, ctx);
836 				if (!ok)
837 					goto end;
838 			}
839 			proxy_path_length++;
840 			must_be_ca = 0;
841 		} else
842 			must_be_ca = 1;
843 	}
844 	ok = 1;
845 
846 end:
847 	return ok;
848 #endif
849 }
850 
851 static int
852 check_chain_extensions(X509_STORE_CTX *ctx) {
853 	return x509_vfy_check_chain_extensions(ctx);
854 }
855 
856 static int
857 check_name_constraints(X509_STORE_CTX *ctx)
858 {
859 	if (!x509_constraints_chain(ctx->chain, &ctx->error,
860 	    &ctx->error_depth)) {
861 		ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth);
862 		if (!ctx->verify_cb(0, ctx))
863 			return 0;
864 	}
865 	return 1;
866 }
867 
868 /* Given a certificate try and find an exact match in the store */
869 
870 static X509 *
871 lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
872 {
873 	STACK_OF(X509) *certs;
874 	X509 *xtmp = NULL;
875 	size_t i;
876 
877 	/* Lookup all certs with matching subject name */
878 	certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
879 	if (certs == NULL)
880 		return NULL;
881 
882 	/* Look for exact match */
883 	for (i = 0; i < sk_X509_num(certs); i++) {
884 		xtmp = sk_X509_value(certs, i);
885 		if (!X509_cmp(xtmp, x))
886 			break;
887 	}
888 
889 	if (i < sk_X509_num(certs))
890 		X509_up_ref(xtmp);
891 	else
892 		xtmp = NULL;
893 
894 	sk_X509_pop_free(certs, X509_free);
895 	return xtmp;
896 }
897 
898 X509 *
899 x509_vfy_lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
900 {
901 	if (ctx->lookup_certs == NULL || ctx->ctx == NULL ||
902 	    ctx->ctx->objs == NULL)
903 		return NULL;
904 	return lookup_cert_match(ctx, x);
905 }
906 
907 static int
908 check_trust(X509_STORE_CTX *ctx)
909 {
910 	size_t i;
911 	int ok;
912 	X509 *x = NULL;
913 	int (*cb) (int xok, X509_STORE_CTX *xctx);
914 
915 	cb = ctx->verify_cb;
916 	/* Check all trusted certificates in chain */
917 	for (i = ctx->last_untrusted; i < sk_X509_num(ctx->chain); i++) {
918 		x = sk_X509_value(ctx->chain, i);
919 		ok = X509_check_trust(x, ctx->param->trust, 0);
920 
921 		/* If explicitly trusted return trusted */
922 		if (ok == X509_TRUST_TRUSTED)
923 			return X509_TRUST_TRUSTED;
924 		/*
925 		 * If explicitly rejected notify callback and reject if not
926 		 * overridden.
927 		 */
928 		if (ok == X509_TRUST_REJECTED) {
929 			ctx->error_depth = i;
930 			ctx->current_cert = x;
931 			ctx->error = X509_V_ERR_CERT_REJECTED;
932 			ok = cb(0, ctx);
933 			if (!ok)
934 				return X509_TRUST_REJECTED;
935 		}
936 	}
937 	/*
938 	 * If we accept partial chains and have at least one trusted certificate
939 	 * return success.
940 	 */
941 	if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
942 		X509 *mx;
943 		if (ctx->last_untrusted < (int)sk_X509_num(ctx->chain))
944 			return X509_TRUST_TRUSTED;
945 		x = sk_X509_value(ctx->chain, 0);
946 		mx = lookup_cert_match(ctx, x);
947 		if (mx) {
948 			(void)sk_X509_set(ctx->chain, 0, mx);
949 			X509_free(x);
950 			ctx->last_untrusted = 0;
951 			return X509_TRUST_TRUSTED;
952 		}
953 	}
954 
955 	/*
956 	 * If no trusted certs in chain at all return untrusted and allow
957 	 * standard (no issuer cert) etc errors to be indicated.
958 	 */
959 	return X509_TRUST_UNTRUSTED;
960 }
961 
962 int
963 x509_vfy_check_trust(X509_STORE_CTX *ctx)
964 {
965 	return check_trust(ctx);
966 }
967 
968 static int
969 check_revocation(X509_STORE_CTX *ctx)
970 {
971 	int i, last, ok;
972 
973 	if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
974 		return 1;
975 	if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
976 		last = sk_X509_num(ctx->chain) - 1;
977 	else {
978 		/* If checking CRL paths this isn't the EE certificate */
979 		if (ctx->parent)
980 			return 1;
981 		last = 0;
982 	}
983 	for (i = 0; i <= last; i++) {
984 		ok = check_cert(ctx, ctx->chain, i);
985 		if (!ok)
986 			return ok;
987 	}
988 	return 1;
989 }
990 
991 int
992 x509_vfy_check_revocation(X509_STORE_CTX *ctx)
993 {
994 	return check_revocation(ctx);
995 }
996 
997 static int
998 check_cert(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, int depth)
999 {
1000 	X509_CRL *crl = NULL, *dcrl = NULL;
1001 	X509 *x;
1002 	int ok = 0, cnum;
1003 	unsigned int last_reasons;
1004 
1005 	cnum = ctx->error_depth = depth;
1006 	x = sk_X509_value(chain, cnum);
1007 	ctx->current_cert = x;
1008 	ctx->current_issuer = NULL;
1009 	ctx->current_crl_score = 0;
1010 	ctx->current_reasons = 0;
1011 	while (ctx->current_reasons != CRLDP_ALL_REASONS) {
1012 		last_reasons = ctx->current_reasons;
1013 		/* Try to retrieve relevant CRL */
1014 		if (ctx->get_crl)
1015 			ok = ctx->get_crl(ctx, &crl, x);
1016 		else
1017 			ok = get_crl_delta(ctx, &crl, &dcrl, x);
1018 		/* If error looking up CRL, nothing we can do except
1019 		 * notify callback
1020 		 */
1021 		if (!ok) {
1022 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
1023 			ok = ctx->verify_cb(0, ctx);
1024 			goto err;
1025 		}
1026 		ctx->current_crl = crl;
1027 		ok = ctx->check_crl(ctx, crl);
1028 		if (!ok)
1029 			goto err;
1030 
1031 		if (dcrl) {
1032 			ok = ctx->check_crl(ctx, dcrl);
1033 			if (!ok)
1034 				goto err;
1035 			ok = ctx->cert_crl(ctx, dcrl, x);
1036 			if (!ok)
1037 				goto err;
1038 		} else
1039 			ok = 1;
1040 
1041 		/* Don't look in full CRL if delta reason is removefromCRL */
1042 		if (ok != 2) {
1043 			ok = ctx->cert_crl(ctx, crl, x);
1044 			if (!ok)
1045 				goto err;
1046 		}
1047 
1048 		ctx->current_crl = NULL;
1049 		X509_CRL_free(crl);
1050 		X509_CRL_free(dcrl);
1051 		crl = NULL;
1052 		dcrl = NULL;
1053 		/* If reasons not updated we wont get anywhere by
1054 		 * another iteration, so exit loop.
1055 		 */
1056 		if (last_reasons == ctx->current_reasons) {
1057 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
1058 			ok = ctx->verify_cb(0, ctx);
1059 			goto err;
1060 		}
1061 	}
1062 
1063 err:
1064 	ctx->current_crl = NULL;
1065 	X509_CRL_free(crl);
1066 	X509_CRL_free(dcrl);
1067 	return ok;
1068 }
1069 
1070 /* Check CRL times against values in X509_STORE_CTX */
1071 
1072 static int
1073 check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
1074 {
1075 	time_t *ptime = NULL;
1076 	int i;
1077 
1078 	if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1079 		return (1);
1080 
1081 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1082 		ptime = &ctx->param->check_time;
1083 
1084 	if (notify)
1085 		ctx->current_crl = crl;
1086 
1087 	i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
1088 	if (i == 0) {
1089 		if (!notify)
1090 			return 0;
1091 		ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
1092 		if (!ctx->verify_cb(0, ctx))
1093 			return 0;
1094 	}
1095 
1096 	if (i > 0) {
1097 		if (!notify)
1098 			return 0;
1099 		ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
1100 		if (!ctx->verify_cb(0, ctx))
1101 			return 0;
1102 	}
1103 
1104 	if (X509_CRL_get_nextUpdate(crl)) {
1105 		i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
1106 
1107 		if (i == 0) {
1108 			if (!notify)
1109 				return 0;
1110 			ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
1111 			if (!ctx->verify_cb(0, ctx))
1112 				return 0;
1113 		}
1114 		/* Ignore expiry of base CRL is delta is valid */
1115 		if ((i < 0) &&
1116 		    !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
1117 			if (!notify)
1118 				return 0;
1119 			ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
1120 			if (!ctx->verify_cb(0, ctx))
1121 				return 0;
1122 		}
1123 	}
1124 
1125 	if (notify)
1126 		ctx->current_crl = NULL;
1127 
1128 	return 1;
1129 }
1130 
1131 static int
1132 get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1133     X509 **pissuer, int *pscore, unsigned int *preasons,
1134     STACK_OF(X509_CRL) *crls)
1135 {
1136 	int i, crl_score, best_score = *pscore;
1137 	unsigned int reasons, best_reasons = 0;
1138 	X509 *x = ctx->current_cert;
1139 	X509_CRL *crl, *best_crl = NULL;
1140 	X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1141 
1142 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1143 		crl = sk_X509_CRL_value(crls, i);
1144 		reasons = *preasons;
1145 		crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1146 
1147 		if (crl_score > best_score) {
1148 			best_crl = crl;
1149 			best_crl_issuer = crl_issuer;
1150 			best_score = crl_score;
1151 			best_reasons = reasons;
1152 		}
1153 	}
1154 
1155 	if (best_crl) {
1156 		if (*pcrl)
1157 			X509_CRL_free(*pcrl);
1158 		*pcrl = best_crl;
1159 		*pissuer = best_crl_issuer;
1160 		*pscore = best_score;
1161 		*preasons = best_reasons;
1162 		CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
1163 		if (*pdcrl) {
1164 			X509_CRL_free(*pdcrl);
1165 			*pdcrl = NULL;
1166 		}
1167 		get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1168 	}
1169 
1170 	if (best_score >= CRL_SCORE_VALID)
1171 		return 1;
1172 
1173 	return 0;
1174 }
1175 
1176 /* Compare two CRL extensions for delta checking purposes. They should be
1177  * both present or both absent. If both present all fields must be identical.
1178  */
1179 
1180 static int
1181 crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1182 {
1183 	ASN1_OCTET_STRING *exta, *extb;
1184 	int i;
1185 
1186 	i = X509_CRL_get_ext_by_NID(a, nid, -1);
1187 	if (i >= 0) {
1188 		/* Can't have multiple occurrences */
1189 		if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1190 			return 0;
1191 		exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1192 	} else
1193 		exta = NULL;
1194 
1195 	i = X509_CRL_get_ext_by_NID(b, nid, -1);
1196 
1197 	if (i >= 0) {
1198 		if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1199 			return 0;
1200 		extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1201 	} else
1202 		extb = NULL;
1203 
1204 	if (!exta && !extb)
1205 		return 1;
1206 
1207 	if (!exta || !extb)
1208 		return 0;
1209 
1210 	if (ASN1_OCTET_STRING_cmp(exta, extb))
1211 		return 0;
1212 
1213 	return 1;
1214 }
1215 
1216 /* See if a base and delta are compatible */
1217 
1218 static int
1219 check_delta_base(X509_CRL *delta, X509_CRL *base)
1220 {
1221 	/* Delta CRL must be a delta */
1222 	if (!delta->base_crl_number)
1223 		return 0;
1224 	/* Base must have a CRL number */
1225 	if (!base->crl_number)
1226 		return 0;
1227 	/* Issuer names must match */
1228 	if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1229 	    X509_CRL_get_issuer(delta)))
1230 		return 0;
1231 	/* AKID and IDP must match */
1232 	if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1233 		return 0;
1234 	if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1235 		return 0;
1236 	/* Delta CRL base number must not exceed Full CRL number. */
1237 	if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1238 		return 0;
1239 	/* Delta CRL number must exceed full CRL number */
1240 	if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
1241 		return 1;
1242 	return 0;
1243 }
1244 
1245 /* For a given base CRL find a delta... maybe extend to delta scoring
1246  * or retrieve a chain of deltas...
1247  */
1248 
1249 static void
1250 get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore, X509_CRL *base,
1251     STACK_OF(X509_CRL) *crls)
1252 {
1253 	X509_CRL *delta;
1254 	int i;
1255 
1256 	if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
1257 		return;
1258 	if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
1259 		return;
1260 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1261 		delta = sk_X509_CRL_value(crls, i);
1262 		if (check_delta_base(delta, base)) {
1263 			if (check_crl_time(ctx, delta, 0))
1264 				*pscore |= CRL_SCORE_TIME_DELTA;
1265 			CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL);
1266 			*dcrl = delta;
1267 			return;
1268 		}
1269 	}
1270 	*dcrl = NULL;
1271 }
1272 
1273 /* For a given CRL return how suitable it is for the supplied certificate 'x'.
1274  * The return value is a mask of several criteria.
1275  * If the issuer is not the certificate issuer this is returned in *pissuer.
1276  * The reasons mask is also used to determine if the CRL is suitable: if
1277  * no new reasons the CRL is rejected, otherwise reasons is updated.
1278  */
1279 
1280 static int
1281 get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons,
1282     X509_CRL *crl, X509 *x)
1283 {
1284 	int crl_score = 0;
1285 	unsigned int tmp_reasons = *preasons, crl_reasons;
1286 
1287 	/* First see if we can reject CRL straight away */
1288 
1289 	/* Invalid IDP cannot be processed */
1290 	if (crl->idp_flags & IDP_INVALID)
1291 		return 0;
1292 	/* Reason codes or indirect CRLs need extended CRL support */
1293 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1294 		if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1295 			return 0;
1296 	} else if (crl->idp_flags & IDP_REASONS) {
1297 		/* If no new reasons reject */
1298 		if (!(crl->idp_reasons & ~tmp_reasons))
1299 			return 0;
1300 	}
1301 	/* Don't process deltas at this stage */
1302 	else if (crl->base_crl_number)
1303 		return 0;
1304 	/* If issuer name doesn't match certificate need indirect CRL */
1305 	if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1306 		if (!(crl->idp_flags & IDP_INDIRECT))
1307 			return 0;
1308 	} else
1309 		crl_score |= CRL_SCORE_ISSUER_NAME;
1310 
1311 	if (!(crl->flags & EXFLAG_CRITICAL))
1312 		crl_score |= CRL_SCORE_NOCRITICAL;
1313 
1314 	/* Check expiry */
1315 	if (check_crl_time(ctx, crl, 0))
1316 		crl_score |= CRL_SCORE_TIME;
1317 
1318 	/* Check authority key ID and locate certificate issuer */
1319 	crl_akid_check(ctx, crl, pissuer, &crl_score);
1320 
1321 	/* If we can't locate certificate issuer at this point forget it */
1322 
1323 	if (!(crl_score & CRL_SCORE_AKID))
1324 		return 0;
1325 
1326 	/* Check cert for matching CRL distribution points */
1327 
1328 	if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1329 		/* If no new reasons reject */
1330 		if (!(crl_reasons & ~tmp_reasons))
1331 			return 0;
1332 		tmp_reasons |= crl_reasons;
1333 		crl_score |= CRL_SCORE_SCOPE;
1334 	}
1335 
1336 	*preasons = tmp_reasons;
1337 
1338 	return crl_score;
1339 }
1340 
1341 static void
1342 crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
1343     int *pcrl_score)
1344 {
1345 	X509 *crl_issuer = NULL;
1346 	X509_NAME *cnm = X509_CRL_get_issuer(crl);
1347 	int cidx = ctx->error_depth;
1348 	int i;
1349 
1350 	if (cidx != sk_X509_num(ctx->chain) - 1)
1351 		cidx++;
1352 
1353 	crl_issuer = sk_X509_value(ctx->chain, cidx);
1354 
1355 	if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1356 		if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1357 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_ISSUER_CERT;
1358 			*pissuer = crl_issuer;
1359 			return;
1360 		}
1361 	}
1362 
1363 	for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1364 		crl_issuer = sk_X509_value(ctx->chain, cidx);
1365 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1366 			continue;
1367 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1368 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_SAME_PATH;
1369 			*pissuer = crl_issuer;
1370 			return;
1371 		}
1372 	}
1373 
1374 	/* Anything else needs extended CRL support */
1375 
1376 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1377 		return;
1378 
1379 	/* Otherwise the CRL issuer is not on the path. Look for it in the
1380 	 * set of untrusted certificates.
1381 	 */
1382 	for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1383 		crl_issuer = sk_X509_value(ctx->untrusted, i);
1384 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1385 			continue;
1386 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1387 			*pissuer = crl_issuer;
1388 			*pcrl_score |= CRL_SCORE_AKID;
1389 			return;
1390 		}
1391 	}
1392 }
1393 
1394 /* Check the path of a CRL issuer certificate. This creates a new
1395  * X509_STORE_CTX and populates it with most of the parameters from the
1396  * parent. This could be optimised somewhat since a lot of path checking
1397  * will be duplicated by the parent, but this will rarely be used in
1398  * practice.
1399  */
1400 
1401 static int
1402 check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1403 {
1404 	X509_STORE_CTX crl_ctx;
1405 	int ret;
1406 
1407 	/* Don't allow recursive CRL path validation */
1408 	if (ctx->parent)
1409 		return 0;
1410 	if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted)) {
1411 		ret = -1;
1412 		goto err;
1413 	}
1414 
1415 	crl_ctx.crls = ctx->crls;
1416 	/* Copy verify params across */
1417 	X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1418 
1419 	crl_ctx.parent = ctx;
1420 	crl_ctx.verify_cb = ctx->verify_cb;
1421 
1422 	/* Verify CRL issuer */
1423 	ret = X509_verify_cert(&crl_ctx);
1424 
1425 	if (ret <= 0)
1426 		goto err;
1427 
1428 	/* Check chain is acceptable */
1429 	ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1430 
1431 err:
1432 	X509_STORE_CTX_cleanup(&crl_ctx);
1433 	return ret;
1434 }
1435 
1436 /* RFC3280 says nothing about the relationship between CRL path
1437  * and certificate path, which could lead to situations where a
1438  * certificate could be revoked or validated by a CA not authorised
1439  * to do so. RFC5280 is more strict and states that the two paths must
1440  * end in the same trust anchor, though some discussions remain...
1441  * until this is resolved we use the RFC5280 version
1442  */
1443 
1444 static int
1445 check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
1446     STACK_OF(X509) *crl_path)
1447 {
1448 	X509 *cert_ta, *crl_ta;
1449 
1450 	cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1451 	crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1452 	if (!X509_cmp(cert_ta, crl_ta))
1453 		return 1;
1454 	return 0;
1455 }
1456 
1457 /* Check for match between two dist point names: three separate cases.
1458  * 1. Both are relative names and compare X509_NAME types.
1459  * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1460  * 3. Both are full names and compare two GENERAL_NAMES.
1461  * 4. One is NULL: automatic match.
1462  */
1463 
1464 static int
1465 idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1466 {
1467 	X509_NAME *nm = NULL;
1468 	GENERAL_NAMES *gens = NULL;
1469 	GENERAL_NAME *gena, *genb;
1470 	int i, j;
1471 
1472 	if (!a || !b)
1473 		return 1;
1474 	if (a->type == 1) {
1475 		if (!a->dpname)
1476 			return 0;
1477 		/* Case 1: two X509_NAME */
1478 		if (b->type == 1) {
1479 			if (!b->dpname)
1480 				return 0;
1481 			if (!X509_NAME_cmp(a->dpname, b->dpname))
1482 				return 1;
1483 			else
1484 				return 0;
1485 		}
1486 		/* Case 2: set name and GENERAL_NAMES appropriately */
1487 		nm = a->dpname;
1488 		gens = b->name.fullname;
1489 	} else if (b->type == 1) {
1490 		if (!b->dpname)
1491 			return 0;
1492 		/* Case 2: set name and GENERAL_NAMES appropriately */
1493 		gens = a->name.fullname;
1494 		nm = b->dpname;
1495 	}
1496 
1497 	/* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1498 	if (nm) {
1499 		for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1500 			gena = sk_GENERAL_NAME_value(gens, i);
1501 			if (gena->type != GEN_DIRNAME)
1502 				continue;
1503 			if (!X509_NAME_cmp(nm, gena->d.directoryName))
1504 				return 1;
1505 		}
1506 		return 0;
1507 	}
1508 
1509 	/* Else case 3: two GENERAL_NAMES */
1510 
1511 	for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1512 		gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1513 		for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1514 			genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1515 			if (!GENERAL_NAME_cmp(gena, genb))
1516 				return 1;
1517 		}
1518 	}
1519 
1520 	return 0;
1521 }
1522 
1523 static int
1524 crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1525 {
1526 	int i;
1527 	X509_NAME *nm = X509_CRL_get_issuer(crl);
1528 
1529 	/* If no CRLissuer return is successful iff don't need a match */
1530 	if (!dp->CRLissuer)
1531 		return !!(crl_score & CRL_SCORE_ISSUER_NAME);
1532 	for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1533 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1534 		if (gen->type != GEN_DIRNAME)
1535 			continue;
1536 		if (!X509_NAME_cmp(gen->d.directoryName, nm))
1537 			return 1;
1538 	}
1539 	return 0;
1540 }
1541 
1542 /* Check CRLDP and IDP */
1543 
1544 static int
1545 crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons)
1546 {
1547 	int i;
1548 
1549 	if (crl->idp_flags & IDP_ONLYATTR)
1550 		return 0;
1551 	if (x->ex_flags & EXFLAG_CA) {
1552 		if (crl->idp_flags & IDP_ONLYUSER)
1553 			return 0;
1554 	} else {
1555 		if (crl->idp_flags & IDP_ONLYCA)
1556 			return 0;
1557 	}
1558 	*preasons = crl->idp_reasons;
1559 	for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1560 		DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1561 		if (crldp_check_crlissuer(dp, crl, crl_score)) {
1562 			if (!crl->idp ||
1563 			    idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1564 				*preasons &= dp->dp_reasons;
1565 				return 1;
1566 			}
1567 		}
1568 	}
1569 	if ((!crl->idp || !crl->idp->distpoint) &&
1570 	    (crl_score & CRL_SCORE_ISSUER_NAME))
1571 		return 1;
1572 	return 0;
1573 }
1574 
1575 /* Retrieve CRL corresponding to current certificate.
1576  * If deltas enabled try to find a delta CRL too
1577  */
1578 
1579 static int
1580 get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1581 {
1582 	int ok;
1583 	X509 *issuer = NULL;
1584 	int crl_score = 0;
1585 	unsigned int reasons;
1586 	X509_CRL *crl = NULL, *dcrl = NULL;
1587 	STACK_OF(X509_CRL) *skcrl;
1588 	X509_NAME *nm = X509_get_issuer_name(x);
1589 
1590 	reasons = ctx->current_reasons;
1591 	ok = get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons,
1592 	    ctx->crls);
1593 	if (ok)
1594 		goto done;
1595 
1596 	/* Lookup CRLs from store */
1597 	skcrl = ctx->lookup_crls(ctx, nm);
1598 
1599 	/* If no CRLs found and a near match from get_crl_sk use that */
1600 	if (!skcrl && crl)
1601 		goto done;
1602 
1603 	get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1604 
1605 	sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1606 
1607 done:
1608 
1609 	/* If we got any kind of CRL use it and return success */
1610 	if (crl) {
1611 		ctx->current_issuer = issuer;
1612 		ctx->current_crl_score = crl_score;
1613 		ctx->current_reasons = reasons;
1614 		*pcrl = crl;
1615 		*pdcrl = dcrl;
1616 		return 1;
1617 	}
1618 
1619 	return 0;
1620 }
1621 
1622 /* Check CRL validity */
1623 static int
1624 check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1625 {
1626 	X509 *issuer = NULL;
1627 	EVP_PKEY *ikey = NULL;
1628 	int ok = 0, chnum, cnum;
1629 
1630 	cnum = ctx->error_depth;
1631 	chnum = sk_X509_num(ctx->chain) - 1;
1632 	/* if we have an alternative CRL issuer cert use that */
1633 	if (ctx->current_issuer) {
1634 		issuer = ctx->current_issuer;
1635 	} else if (cnum < chnum) {
1636 		/*
1637 		 * Else find CRL issuer: if not last certificate then issuer
1638 		 * is next certificate in chain.
1639 		 */
1640 		issuer = sk_X509_value(ctx->chain, cnum + 1);
1641 	} else {
1642 		issuer = sk_X509_value(ctx->chain, chnum);
1643 		/* If not self signed, can't check signature */
1644 		if (!ctx->check_issued(ctx, issuer, issuer)) {
1645 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1646 			ok = ctx->verify_cb(0, ctx);
1647 			if (!ok)
1648 				goto err;
1649 		}
1650 	}
1651 
1652 	if (issuer) {
1653 		/* Skip most tests for deltas because they have already
1654 		 * been done
1655 		 */
1656 		if (!crl->base_crl_number) {
1657 			/* Check for cRLSign bit if keyUsage present */
1658 			if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1659 			    !(issuer->ex_kusage & KU_CRL_SIGN)) {
1660 				ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1661 				ok = ctx->verify_cb(0, ctx);
1662 				if (!ok)
1663 					goto err;
1664 			}
1665 
1666 			if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1667 				ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1668 				ok = ctx->verify_cb(0, ctx);
1669 				if (!ok)
1670 					goto err;
1671 			}
1672 
1673 			if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1674 				if (check_crl_path(ctx,
1675 				    ctx->current_issuer) <= 0) {
1676 					ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1677 					ok = ctx->verify_cb(0, ctx);
1678 					if (!ok)
1679 						goto err;
1680 				}
1681 			}
1682 
1683 			if (crl->idp_flags & IDP_INVALID) {
1684 				ctx->error = X509_V_ERR_INVALID_EXTENSION;
1685 				ok = ctx->verify_cb(0, ctx);
1686 				if (!ok)
1687 					goto err;
1688 			}
1689 
1690 
1691 		}
1692 
1693 		if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1694 			ok = check_crl_time(ctx, crl, 1);
1695 			if (!ok)
1696 				goto err;
1697 		}
1698 
1699 		/* Attempt to get issuer certificate public key */
1700 		ikey = X509_get_pubkey(issuer);
1701 
1702 		if (!ikey) {
1703 			ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1704 			ok = ctx->verify_cb(0, ctx);
1705 			if (!ok)
1706 				goto err;
1707 		} else {
1708 			/* Verify CRL signature */
1709 			if (X509_CRL_verify(crl, ikey) <= 0) {
1710 				ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1711 				ok = ctx->verify_cb(0, ctx);
1712 				if (!ok)
1713 					goto err;
1714 			}
1715 		}
1716 	}
1717 
1718 	ok = 1;
1719 
1720 err:
1721 	EVP_PKEY_free(ikey);
1722 	return ok;
1723 }
1724 
1725 /* Check certificate against CRL */
1726 static int
1727 cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1728 {
1729 	int ok;
1730 	X509_REVOKED *rev;
1731 
1732 	/* The rules changed for this... previously if a CRL contained
1733 	 * unhandled critical extensions it could still be used to indicate
1734 	 * a certificate was revoked. This has since been changed since
1735 	 * critical extension can change the meaning of CRL entries.
1736 	 */
1737 	if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
1738 	    (crl->flags & EXFLAG_CRITICAL)) {
1739 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1740 		ok = ctx->verify_cb(0, ctx);
1741 		if (!ok)
1742 			return 0;
1743 	}
1744 	/* Look for serial number of certificate in CRL
1745 	 * If found make sure reason is not removeFromCRL.
1746 	 */
1747 	if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1748 		if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1749 			return 2;
1750 		ctx->error = X509_V_ERR_CERT_REVOKED;
1751 		ok = ctx->verify_cb(0, ctx);
1752 		if (!ok)
1753 			return 0;
1754 	}
1755 
1756 	return 1;
1757 }
1758 
1759 int
1760 x509_vfy_check_policy(X509_STORE_CTX *ctx)
1761 {
1762 	int ret;
1763 
1764 	if (ctx->parent)
1765 		return 1;
1766 
1767 	/* X509_policy_check always allocates a new tree. */
1768 	X509_policy_tree_free(ctx->tree);
1769 	ctx->tree = NULL;
1770 
1771 	ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1772 	    ctx->param->policies, ctx->param->flags);
1773 	if (ret == 0) {
1774 		X509error(ERR_R_MALLOC_FAILURE);
1775 		return 0;
1776 	}
1777 	/* Invalid or inconsistent extensions */
1778 	if (ret == -1) {
1779 		/* Locate certificates with bad extensions and notify
1780 		 * callback.
1781 		 */
1782 		X509 *x;
1783 		int i;
1784 		for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1785 			x = sk_X509_value(ctx->chain, i);
1786 			if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1787 				continue;
1788 			ctx->current_cert = x;
1789 			ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1790 			if (!ctx->verify_cb(0, ctx))
1791 				return 0;
1792 		}
1793 		return 1;
1794 	}
1795 	if (ret == -2) {
1796 		ctx->current_cert = NULL;
1797 		ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1798 		return ctx->verify_cb(0, ctx);
1799 	}
1800 
1801 	if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1802 		ctx->current_cert = NULL;
1803 		ctx->error = X509_V_OK;
1804 		if (!ctx->verify_cb(2, ctx))
1805 			return 0;
1806 	}
1807 
1808 	return 1;
1809 }
1810 
1811 static int
1812 check_policy(X509_STORE_CTX *ctx)
1813 {
1814 	return x509_vfy_check_policy(ctx);
1815 }
1816 
1817 /*
1818  * Inform the verify callback of an error.
1819  *
1820  * If x is not NULL it is the error cert, otherwise use the chain cert
1821  * at depth.
1822  *
1823  * If err is not X509_V_OK, that's the error value, otherwise leave
1824  * unchanged (presumably set by the caller).
1825  *
1826  * Returns 0 to abort verification with an error, non-zero to continue.
1827  */
1828 static int
1829 verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err)
1830 {
1831 	ctx->error_depth = depth;
1832 	ctx->current_cert = (x != NULL) ? x : sk_X509_value(ctx->chain, depth);
1833 	if (err != X509_V_OK)
1834 		ctx->error = err;
1835 	return ctx->verify_cb(0, ctx);
1836 }
1837 
1838 /*
1839  * Check certificate validity times.
1840  *
1841  * If depth >= 0, invoke verification callbacks on error, otherwise just return
1842  * the validation status.
1843  *
1844  * Return 1 on success, 0 otherwise.
1845  */
1846 int
1847 x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1848 {
1849 	time_t *ptime;
1850 	int i;
1851 
1852 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1853 		ptime = &ctx->param->check_time;
1854 	else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1855 		return 1;
1856 	else
1857 		ptime = NULL;
1858 
1859 	i = X509_cmp_time(X509_get_notBefore(x), ptime);
1860 	if (i >= 0 && depth < 0)
1861 		return 0;
1862 	if (i == 0 && !verify_cb_cert(ctx, x, depth,
1863 	    X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD))
1864 		return 0;
1865 	if (i > 0 && !verify_cb_cert(ctx, x, depth,
1866 	    X509_V_ERR_CERT_NOT_YET_VALID))
1867 		return 0;
1868 
1869 	i = X509_cmp_time_internal(X509_get_notAfter(x), ptime, 1);
1870 	if (i <= 0 && depth < 0)
1871 		return 0;
1872 	if (i == 0 && !verify_cb_cert(ctx, x, depth,
1873 	    X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD))
1874 		return 0;
1875 	if (i < 0 && !verify_cb_cert(ctx, x, depth,
1876 	    X509_V_ERR_CERT_HAS_EXPIRED))
1877 		return 0;
1878 	return 1;
1879 }
1880 
1881 static int
1882 x509_vfy_internal_verify(X509_STORE_CTX *ctx, int chain_verified)
1883 {
1884 	int n = sk_X509_num(ctx->chain) - 1;
1885 	X509 *xi = sk_X509_value(ctx->chain, n);
1886 	X509 *xs;
1887 
1888 	if (ctx->check_issued(ctx, xi, xi))
1889 		xs = xi;
1890 	else {
1891 		if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1892 			xs = xi;
1893 			goto check_cert;
1894 		}
1895 		if (n <= 0)
1896 			return verify_cb_cert(ctx, xi, 0,
1897 			    X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1898 		n--;
1899 		ctx->error_depth = n;
1900 		xs = sk_X509_value(ctx->chain, n);
1901 	}
1902 
1903 	/*
1904 	 * Do not clear ctx->error=0, it must be "sticky", only the
1905 	 * user's callback is allowed to reset errors (at its own
1906 	 * peril).
1907 	 */
1908 	while (n >= 0) {
1909 
1910 		/*
1911 		 * Skip signature check for self signed certificates
1912 		 * unless explicitly asked for.  It doesn't add any
1913 		 * security and just wastes time.  If the issuer's
1914 		 * public key is unusable, report the issuer
1915 		 * certificate and its depth (rather than the depth of
1916 		 * the subject).
1917 		 */
1918 		if (!chain_verified && ( xs != xi ||
1919 		    (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1920 			EVP_PKEY *pkey;
1921 			if ((pkey = X509_get_pubkey(xi)) == NULL) {
1922 				if (!verify_cb_cert(ctx, xi, xi != xs ? n+1 : n,
1923 				    X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1924 					return 0;
1925 			} else if (X509_verify(xs, pkey) <= 0) {
1926 				if (!verify_cb_cert(ctx, xs, n,
1927 				    X509_V_ERR_CERT_SIGNATURE_FAILURE)) {
1928 					EVP_PKEY_free(pkey);
1929 					return 0;
1930 				}
1931 			}
1932 			EVP_PKEY_free(pkey);
1933 		}
1934 check_cert:
1935 		/* Calls verify callback as needed */
1936 		if (!chain_verified && !x509_check_cert_time(ctx, xs, n))
1937 			return 0;
1938 
1939 		/*
1940 		 * Signal success at this depth.  However, the
1941 		 * previous error (if any) is retained.
1942 		 */
1943 		ctx->current_issuer = xi;
1944 		ctx->current_cert = xs;
1945 		ctx->error_depth = n;
1946 		if (!ctx->verify_cb(1, ctx))
1947 			return 0;
1948 
1949 		if (--n >= 0) {
1950 			xi = xs;
1951 			xs = sk_X509_value(ctx->chain, n);
1952 		}
1953 	}
1954 	return 1;
1955 }
1956 
1957 static int
1958 internal_verify(X509_STORE_CTX *ctx)
1959 {
1960 	return x509_vfy_internal_verify(ctx, 0);
1961 }
1962 
1963 int
1964 x509_vfy_callback_indicate_success(X509_STORE_CTX *ctx)
1965 {
1966 	return x509_vfy_internal_verify(ctx, 1);
1967 }
1968 
1969 int
1970 X509_cmp_current_time(const ASN1_TIME *ctm)
1971 {
1972 	return X509_cmp_time(ctm, NULL);
1973 }
1974 
1975 /*
1976  * Compare a possibly unvalidated ASN1_TIME string against a time_t
1977  * using RFC 5280 rules for the time string. If *cmp_time is NULL
1978  * the current system time is used.
1979  *
1980  * XXX NOTE that unlike what you expect a "cmp" function to do in C,
1981  * XXX this one is "special", and returns 0 for error.
1982  *
1983  * Returns:
1984  * -1 if the ASN1_time is earlier than OR the same as *cmp_time.
1985  * 1 if the ASN1_time is later than *cmp_time.
1986  * 0 on error.
1987  */
1988 static int
1989 X509_cmp_time_internal(const ASN1_TIME *ctm, time_t *cmp_time, int clamp_notafter)
1990 {
1991 	time_t compare;
1992 	struct tm tm1, tm2;
1993 	int ret = 0;
1994 
1995 	if (cmp_time == NULL)
1996 		compare = time(NULL);
1997 	else
1998 		compare = *cmp_time;
1999 
2000 	memset(&tm1, 0, sizeof(tm1));
2001 
2002 	if (!x509_verify_asn1_time_to_tm(ctm, &tm1, clamp_notafter))
2003 		goto out; /* invalid time */
2004 
2005 	if (gmtime_r(&compare, &tm2) == NULL)
2006 		goto out;
2007 
2008 	ret = ASN1_time_tm_cmp(&tm1, &tm2);
2009 	if (ret == 0)
2010 		ret = -1; /* 0 is used for error, so map same to less than */
2011  out:
2012 	return (ret);
2013 }
2014 
2015 int
2016 X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
2017 {
2018 	return X509_cmp_time_internal(ctm, cmp_time, 0);
2019 }
2020 
2021 
2022 ASN1_TIME *
2023 X509_gmtime_adj(ASN1_TIME *s, long adj)
2024 {
2025 	return X509_time_adj(s, adj, NULL);
2026 }
2027 
2028 ASN1_TIME *
2029 X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_time)
2030 {
2031 	return X509_time_adj_ex(s, 0, offset_sec, in_time);
2032 }
2033 
2034 ASN1_TIME *
2035 X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *in_time)
2036 {
2037 	time_t t;
2038 	if (in_time == NULL)
2039 		t = time(NULL);
2040 	else
2041 		t = *in_time;
2042 
2043 	return ASN1_TIME_adj(s, t, offset_day, offset_sec);
2044 }
2045 
2046 int
2047 X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
2048 {
2049 	EVP_PKEY *ktmp = NULL, *ktmp2;
2050 	int i, j;
2051 
2052 	if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
2053 		return 1;
2054 
2055 	for (i = 0; i < sk_X509_num(chain); i++) {
2056 		ktmp = X509_get_pubkey(sk_X509_value(chain, i));
2057 		if (ktmp == NULL) {
2058 			X509error(X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
2059 			return 0;
2060 		}
2061 		if (!EVP_PKEY_missing_parameters(ktmp))
2062 			break;
2063 		else {
2064 			EVP_PKEY_free(ktmp);
2065 			ktmp = NULL;
2066 		}
2067 	}
2068 	if (ktmp == NULL) {
2069 		X509error(X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
2070 		return 0;
2071 	}
2072 
2073 	/* first, populate the other certs */
2074 	for (j = i - 1; j >= 0; j--) {
2075 		ktmp2 = X509_get_pubkey(sk_X509_value(chain, j));
2076 		EVP_PKEY_copy_parameters(ktmp2, ktmp);
2077 		EVP_PKEY_free(ktmp2);
2078 	}
2079 
2080 	if (pkey != NULL)
2081 		EVP_PKEY_copy_parameters(pkey, ktmp);
2082 	EVP_PKEY_free(ktmp);
2083 	return 1;
2084 }
2085 
2086 int
2087 X509_STORE_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2088     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2089 {
2090 	/* This function is (usually) called only once, by
2091 	 * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c). */
2092 	return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX,
2093 	    argl, argp, new_func, dup_func, free_func);
2094 }
2095 
2096 int
2097 X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2098 {
2099 	return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2100 }
2101 
2102 void *
2103 X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
2104 {
2105 	return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2106 }
2107 
2108 int
2109 X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
2110 {
2111 	return ctx->error;
2112 }
2113 
2114 void
2115 X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2116 {
2117 	ctx->error = err;
2118 }
2119 
2120 int
2121 X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
2122 {
2123 	return ctx->error_depth;
2124 }
2125 
2126 X509 *
2127 X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
2128 {
2129 	return ctx->current_cert;
2130 }
2131 
2132 STACK_OF(X509) *
2133 X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
2134 {
2135 	return ctx->chain;
2136 }
2137 
2138 STACK_OF(X509) *
2139 X509_STORE_CTX_get0_chain(X509_STORE_CTX *xs)
2140 {
2141 	return xs->chain;
2142 }
2143 
2144 STACK_OF(X509) *
2145 X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
2146 {
2147 	int i;
2148 	X509 *x;
2149 	STACK_OF(X509) *chain;
2150 
2151 	if (!ctx->chain || !(chain = sk_X509_dup(ctx->chain)))
2152 		return NULL;
2153 	for (i = 0; i < sk_X509_num(chain); i++) {
2154 		x = sk_X509_value(chain, i);
2155 		CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
2156 	}
2157 	return chain;
2158 }
2159 
2160 X509 *
2161 X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
2162 {
2163 	return ctx->current_issuer;
2164 }
2165 
2166 X509_CRL *
2167 X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
2168 {
2169 	return ctx->current_crl;
2170 }
2171 
2172 X509_STORE_CTX *
2173 X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
2174 {
2175 	return ctx->parent;
2176 }
2177 
2178 X509_STORE *
2179 X509_STORE_CTX_get0_store(X509_STORE_CTX *xs)
2180 {
2181 	return xs->ctx;
2182 }
2183 
2184 void
2185 X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2186 {
2187 	ctx->cert = x;
2188 }
2189 
2190 void
2191 X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2192 {
2193 	ctx->untrusted = sk;
2194 }
2195 
2196 void
2197 X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2198 {
2199 	ctx->crls = sk;
2200 }
2201 
2202 int
2203 X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2204 {
2205 	return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2206 }
2207 
2208 int
2209 X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2210 {
2211 	return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2212 }
2213 
2214 /* This function is used to set the X509_STORE_CTX purpose and trust
2215  * values. This is intended to be used when another structure has its
2216  * own trust and purpose values which (if set) will be inherited by
2217  * the ctx. If they aren't set then we will usually have a default
2218  * purpose in mind which should then be used to set the trust value.
2219  * An example of this is SSL use: an SSL structure will have its own
2220  * purpose and trust settings which the application can set: if they
2221  * aren't set then we use the default of SSL client/server.
2222  */
2223 
2224 int
2225 X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2226     int purpose, int trust)
2227 {
2228 	int idx;
2229 
2230 	/* If purpose not set use default */
2231 	if (!purpose)
2232 		purpose = def_purpose;
2233 	/* If we have a purpose then check it is valid */
2234 	if (purpose) {
2235 		X509_PURPOSE *ptmp;
2236 		idx = X509_PURPOSE_get_by_id(purpose);
2237 		if (idx == -1) {
2238 			X509error(X509_R_UNKNOWN_PURPOSE_ID);
2239 			return 0;
2240 		}
2241 		ptmp = X509_PURPOSE_get0(idx);
2242 		if (ptmp->trust == X509_TRUST_DEFAULT) {
2243 			idx = X509_PURPOSE_get_by_id(def_purpose);
2244 			if (idx == -1) {
2245 				X509error(X509_R_UNKNOWN_PURPOSE_ID);
2246 				return 0;
2247 			}
2248 			ptmp = X509_PURPOSE_get0(idx);
2249 		}
2250 		/* If trust not set then get from purpose default */
2251 		if (!trust)
2252 			trust = ptmp->trust;
2253 	}
2254 	if (trust) {
2255 		idx = X509_TRUST_get_by_id(trust);
2256 		if (idx == -1) {
2257 			X509error(X509_R_UNKNOWN_TRUST_ID);
2258 			return 0;
2259 		}
2260 	}
2261 
2262 	if (purpose && !ctx->param->purpose)
2263 		ctx->param->purpose = purpose;
2264 	if (trust && !ctx->param->trust)
2265 		ctx->param->trust = trust;
2266 	return 1;
2267 }
2268 
2269 X509_STORE_CTX *
2270 X509_STORE_CTX_new(void)
2271 {
2272 	X509_STORE_CTX *ctx;
2273 
2274 	ctx = calloc(1, sizeof(X509_STORE_CTX));
2275 	if (!ctx) {
2276 		X509error(ERR_R_MALLOC_FAILURE);
2277 		return NULL;
2278 	}
2279 	return ctx;
2280 }
2281 
2282 void
2283 X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2284 {
2285 	if (ctx == NULL)
2286 		return;
2287 
2288 	X509_STORE_CTX_cleanup(ctx);
2289 	free(ctx);
2290 }
2291 
2292 int
2293 X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2294     STACK_OF(X509) *chain)
2295 {
2296 	int param_ret = 1;
2297 
2298 	/*
2299 	 * Make sure everything is initialized properly even in case of an
2300 	 * early return due to an error.
2301 	 *
2302 	 * While this 'ctx' can be reused, X509_STORE_CTX_cleanup() will have
2303 	 * freed everything and memset ex_data anyway.  This also allows us
2304 	 * to safely use X509_STORE_CTX variables from the stack which will
2305 	 * have uninitialized data.
2306 	 */
2307 	memset(ctx, 0, sizeof(*ctx));
2308 
2309 	/*
2310 	 * Start with this set to not valid - it will be set to valid
2311 	 * in X509_verify_cert.
2312 	 */
2313 	ctx->error = X509_V_ERR_INVALID_CALL;
2314 
2315 	/*
2316 	 * Set values other than 0.  Keep this in the same order as
2317 	 * X509_STORE_CTX except for values that may fail.  All fields that
2318 	 * may fail should go last to make sure 'ctx' is as consistent as
2319 	 * possible even on early exits.
2320 	 */
2321 	ctx->ctx = store;
2322 	ctx->cert = x509;
2323 	ctx->untrusted = chain;
2324 
2325 	if (store && store->verify)
2326 		ctx->verify = store->verify;
2327 	else
2328 		ctx->verify = internal_verify;
2329 
2330 	if (store && store->verify_cb)
2331 		ctx->verify_cb = store->verify_cb;
2332 	else
2333 		ctx->verify_cb = null_callback;
2334 
2335 	if (store && store->get_issuer)
2336 		ctx->get_issuer = store->get_issuer;
2337 	else
2338 		ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2339 
2340 	if (store && store->check_issued)
2341 		ctx->check_issued = store->check_issued;
2342 	else
2343 		ctx->check_issued = check_issued;
2344 
2345 	if (store && store->check_revocation)
2346 		ctx->check_revocation = store->check_revocation;
2347 	else
2348 		ctx->check_revocation = check_revocation;
2349 
2350 	if (store && store->get_crl)
2351 		ctx->get_crl = store->get_crl;
2352 	else
2353 		ctx->get_crl = NULL;
2354 
2355 	if (store && store->check_crl)
2356 		ctx->check_crl = store->check_crl;
2357 	else
2358 		ctx->check_crl = check_crl;
2359 
2360 	if (store && store->cert_crl)
2361 		ctx->cert_crl = store->cert_crl;
2362 	else
2363 		ctx->cert_crl = cert_crl;
2364 
2365 	ctx->check_policy = check_policy;
2366 
2367 	if (store && store->lookup_certs)
2368 		ctx->lookup_certs = store->lookup_certs;
2369 	else
2370 		ctx->lookup_certs = X509_STORE_get1_certs;
2371 
2372 	if (store && store->lookup_crls)
2373 		ctx->lookup_crls = store->lookup_crls;
2374 	else
2375 		ctx->lookup_crls = X509_STORE_get1_crls;
2376 
2377 	if (store && store->cleanup)
2378 		ctx->cleanup = store->cleanup;
2379 	else
2380 		ctx->cleanup = NULL;
2381 
2382 	ctx->param = X509_VERIFY_PARAM_new();
2383 	if (!ctx->param) {
2384 		X509error(ERR_R_MALLOC_FAILURE);
2385 		return 0;
2386 	}
2387 
2388 	/* Inherit callbacks and flags from X509_STORE if not set
2389 	 * use defaults.
2390 	 */
2391 	if (store)
2392 		param_ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2393 	else
2394 		ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT|X509_VP_FLAG_ONCE;
2395 
2396 	if (param_ret)
2397 		param_ret = X509_VERIFY_PARAM_inherit(ctx->param,
2398 		    X509_VERIFY_PARAM_lookup("default"));
2399 
2400 	if (param_ret == 0) {
2401 		X509error(ERR_R_MALLOC_FAILURE);
2402 		return 0;
2403 	}
2404 
2405 	if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2406 	    &(ctx->ex_data)) == 0) {
2407 		X509error(ERR_R_MALLOC_FAILURE);
2408 		return 0;
2409 	}
2410 	return 1;
2411 }
2412 
2413 /* Set alternative lookup method: just a STACK of trusted certificates.
2414  * This avoids X509_STORE nastiness where it isn't needed.
2415  */
2416 
2417 void
2418 X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2419 {
2420 	ctx->other_ctx = sk;
2421 	ctx->get_issuer = get_issuer_sk;
2422 }
2423 
2424 void
2425 X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2426 {
2427 	X509_STORE_CTX_trusted_stack(ctx, sk);
2428 }
2429 
2430 void
2431 X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2432 {
2433 	if (ctx->cleanup)
2434 		ctx->cleanup(ctx);
2435 	if (ctx->param != NULL) {
2436 		if (ctx->parent == NULL)
2437 			X509_VERIFY_PARAM_free(ctx->param);
2438 		ctx->param = NULL;
2439 	}
2440 	if (ctx->tree != NULL) {
2441 		X509_policy_tree_free(ctx->tree);
2442 		ctx->tree = NULL;
2443 	}
2444 	if (ctx->chain != NULL) {
2445 		sk_X509_pop_free(ctx->chain, X509_free);
2446 		ctx->chain = NULL;
2447 	}
2448 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX,
2449 	    ctx, &(ctx->ex_data));
2450 	memset(&ctx->ex_data, 0, sizeof(CRYPTO_EX_DATA));
2451 }
2452 
2453 void
2454 X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2455 {
2456 	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2457 }
2458 
2459 void
2460 X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2461 {
2462 	X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2463 }
2464 
2465 void
2466 X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, time_t t)
2467 {
2468 	X509_VERIFY_PARAM_set_time(ctx->param, t);
2469 }
2470 
2471 void
2472 X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2473     int (*verify_cb)(int, X509_STORE_CTX *))
2474 {
2475 	ctx->verify_cb = verify_cb;
2476 }
2477 
2478 X509 *
2479 X509_STORE_CTX_get0_cert(X509_STORE_CTX *ctx)
2480 {
2481 	return ctx->cert;
2482 }
2483 
2484 STACK_OF(X509) *
2485 X509_STORE_CTX_get0_untrusted(X509_STORE_CTX *ctx)
2486 {
2487 	return ctx->untrusted;
2488 }
2489 
2490 void
2491 X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2492 {
2493 	ctx->untrusted = sk;
2494 }
2495 
2496 X509_POLICY_TREE *
2497 X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2498 {
2499 	return ctx->tree;
2500 }
2501 
2502 int
2503 X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2504 {
2505 	return ctx->explicit_policy;
2506 }
2507 
2508 int
2509 X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2510 {
2511 	const X509_VERIFY_PARAM *param;
2512 	param = X509_VERIFY_PARAM_lookup(name);
2513 	if (!param)
2514 		return 0;
2515 	return X509_VERIFY_PARAM_inherit(ctx->param, param);
2516 }
2517 
2518 X509_VERIFY_PARAM *
2519 X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2520 {
2521 	return ctx->param;
2522 }
2523 
2524 void
2525 X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2526 {
2527 	if (ctx->param)
2528 		X509_VERIFY_PARAM_free(ctx->param);
2529 	ctx->param = param;
2530 }
2531