xref: /openbsd-src/lib/libcrypto/x509/x509_vfy.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: x509_vfy.c,v 1.37 2014/07/17 07:13:02 logan 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 "x509_lcl.h"
77 
78 /* CRL score values */
79 
80 /* No unhandled critical extensions */
81 
82 #define CRL_SCORE_NOCRITICAL	0x100
83 
84 /* certificate is within CRL scope */
85 
86 #define CRL_SCORE_SCOPE		0x080
87 
88 /* CRL times valid */
89 
90 #define CRL_SCORE_TIME		0x040
91 
92 /* Issuer name matches certificate */
93 
94 #define CRL_SCORE_ISSUER_NAME	0x020
95 
96 /* If this score or above CRL is probably valid */
97 
98 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
99 
100 /* CRL issuer is certificate issuer */
101 
102 #define CRL_SCORE_ISSUER_CERT	0x018
103 
104 /* CRL issuer is on certificate path */
105 
106 #define CRL_SCORE_SAME_PATH	0x008
107 
108 /* CRL issuer matches CRL AKID */
109 
110 #define CRL_SCORE_AKID		0x004
111 
112 /* Have a delta CRL with valid times */
113 
114 #define CRL_SCORE_TIME_DELTA	0x002
115 
116 static int null_callback(int ok, X509_STORE_CTX *e);
117 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
118 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
119 static int check_chain_extensions(X509_STORE_CTX *ctx);
120 static int check_name_constraints(X509_STORE_CTX *ctx);
121 static int check_trust(X509_STORE_CTX *ctx);
122 static int check_revocation(X509_STORE_CTX *ctx);
123 static int check_cert(X509_STORE_CTX *ctx);
124 static int check_policy(X509_STORE_CTX *ctx);
125 
126 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
127     unsigned int *preasons, X509_CRL *crl, X509 *x);
128 static int get_crl_delta(X509_STORE_CTX *ctx,
129     X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
130 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pcrl_score,
131     X509_CRL *base, STACK_OF(X509_CRL) *crls);
132 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
133     int *pcrl_score);
134 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
135     unsigned int *preasons);
136 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
137 static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
138     STACK_OF(X509) *crl_path);
139 
140 static int internal_verify(X509_STORE_CTX *ctx);
141 
142 static int
143 null_callback(int ok, X509_STORE_CTX *e)
144 {
145 	return ok;
146 }
147 
148 #if 0
149 static int
150 x509_subject_cmp(X509 **a, X509 **b)
151 {
152 	return X509_subject_name_cmp(*a, *b);
153 }
154 #endif
155 
156 int
157 X509_verify_cert(X509_STORE_CTX *ctx)
158 {
159 	X509 *x, *xtmp, *chain_ss = NULL;
160 	int bad_chain = 0;
161 	X509_VERIFY_PARAM *param = ctx->param;
162 	int depth, i, ok = 0;
163 	int num;
164 	int (*cb)(int xok, X509_STORE_CTX *xctx);
165 	STACK_OF(X509) *sktmp = NULL;
166 
167 	if (ctx->cert == NULL) {
168 		X509err(X509_F_X509_VERIFY_CERT,
169 		    X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
170 		return -1;
171 	}
172 
173 	cb = ctx->verify_cb;
174 
175 	/* first we make sure the chain we are going to build is
176 	 * present and that the first entry is in place */
177 	if (ctx->chain == NULL) {
178 		if (((ctx->chain = sk_X509_new_null()) == NULL) ||
179 		    (!sk_X509_push(ctx->chain, ctx->cert))) {
180 			X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
181 			goto end;
182 		}
183 		CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
184 		ctx->last_untrusted = 1;
185 	}
186 
187 	/* We use a temporary STACK so we can chop and hack at it */
188 	if (ctx->untrusted != NULL &&
189 	    (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
190 		X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
191 		goto end;
192 	}
193 
194 	num = sk_X509_num(ctx->chain);
195 	x = sk_X509_value(ctx->chain, num - 1);
196 	depth = param->depth;
197 
198 	for (;;) {
199 		/* If we have enough, we break */
200 		if (depth < num)
201 			break;	/* FIXME: If this happens, we should take
202 				 * note of it and, if appropriate, use the
203 				 * X509_V_ERR_CERT_CHAIN_TOO_LONG error
204 				 * code later.
205 				 */
206 
207 		/* If we are self signed, we break */
208 		if (ctx->check_issued(ctx, x, x))
209 			break;
210 
211 		/* If we were passed a cert chain, use it first */
212 		if (ctx->untrusted != NULL) {
213 			xtmp = find_issuer(ctx, sktmp, x);
214 			if (xtmp != NULL) {
215 				if (!sk_X509_push(ctx->chain, xtmp)) {
216 					X509err(X509_F_X509_VERIFY_CERT,
217 					    ERR_R_MALLOC_FAILURE);
218 					goto end;
219 				}
220 				CRYPTO_add(&xtmp->references, 1,
221 				    CRYPTO_LOCK_X509);
222 				(void)sk_X509_delete_ptr(sktmp, xtmp);
223 				ctx->last_untrusted++;
224 				x = xtmp;
225 				num++;
226 				/* reparse the full chain for
227 				 * the next one */
228 				continue;
229 			}
230 		}
231 		break;
232 	}
233 	sk_X509_free(sktmp);
234 	sktmp = NULL;
235 
236 	/* at this point, chain should contain a list of untrusted
237 	 * certificates.  We now need to add at least one trusted one,
238 	 * if possible, otherwise we complain. */
239 
240 	/* Examine last certificate in chain and see if it
241  	 * is self signed.
242  	 */
243 
244 	i = sk_X509_num(ctx->chain);
245 	x = sk_X509_value(ctx->chain, i - 1);
246 	if (ctx->check_issued(ctx, x, x)) {
247 		/* we have a self signed certificate */
248 		if (sk_X509_num(ctx->chain) == 1) {
249 			/* We have a single self signed certificate: see if
250 			 * we can find it in the store. We must have an exact
251 			 * match to avoid possible impersonation.
252 			 */
253 			ok = ctx->get_issuer(&xtmp, ctx, x);
254 			if ((ok <= 0) || X509_cmp(x, xtmp)) {
255 				ctx->error =
256 				    X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
257 				ctx->current_cert = x;
258 				ctx->error_depth = i - 1;
259 				if (ok == 1)
260 					X509_free(xtmp);
261 				bad_chain = 1;
262 				ok = cb(0, ctx);
263 				if (!ok)
264 					goto end;
265 			} else {
266 				/* We have a match: replace certificate with store version
267 				 * so we get any trust settings.
268 				 */
269 				X509_free(x);
270 				x = xtmp;
271 				(void)sk_X509_set(ctx->chain, i - 1, x);
272 				ctx->last_untrusted = 0;
273 			}
274 		} else {
275 			/* extract and save self signed certificate for later use */
276 			chain_ss = sk_X509_pop(ctx->chain);
277 			ctx->last_untrusted--;
278 			num--;
279 			x = sk_X509_value(ctx->chain, num - 1);
280 		}
281 	}
282 
283 	/* We now lookup certs from the certificate store */
284 	for (;;) {
285 		/* If we have enough, we break */
286 		if (depth < num)
287 			break;
288 
289 		/* If we are self signed, we break */
290 		if (ctx->check_issued(ctx, x, x))
291 			break;
292 
293 		ok = ctx->get_issuer(&xtmp, ctx, x);
294 		if (ok < 0)
295 			return ok;
296 		if (ok == 0)
297 			break;
298 
299 		x = xtmp;
300 		if (!sk_X509_push(ctx->chain, x)) {
301 			X509_free(xtmp);
302 			X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
303 			return 0;
304 		}
305 		num++;
306 	}
307 
308 	/* we now have our chain, lets check it... */
309 
310 	/* Is last certificate looked up self signed? */
311 	if (!ctx->check_issued(ctx, x, x)) {
312 		if ((chain_ss == NULL) ||
313 		    !ctx->check_issued(ctx, x, chain_ss)) {
314 			if (ctx->last_untrusted >= num)
315 				ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
316 			else
317 				ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
318 			ctx->current_cert = x;
319 		} else {
320 
321 			if (!sk_X509_push(ctx->chain, chain_ss)) {
322 				X509_free(chain_ss);
323 				X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
324 				return 0;
325 			}
326 			num++;
327 			ctx->last_untrusted = num;
328 			ctx->current_cert = chain_ss;
329 			ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
330 			chain_ss = NULL;
331 		}
332 
333 		ctx->error_depth = num - 1;
334 		bad_chain = 1;
335 		ok = cb(0, ctx);
336 		if (!ok)
337 			goto end;
338 	}
339 
340 	/* We have the chain complete: now we need to check its purpose */
341 	ok = check_chain_extensions(ctx);
342 
343 	if (!ok)
344 		goto end;
345 
346 	/* Check name constraints */
347 
348 	ok = check_name_constraints(ctx);
349 
350 	if (!ok)
351 		goto end;
352 
353 	/* The chain extensions are OK: check trust */
354 
355 	if (param->trust > 0)
356 		ok = check_trust(ctx);
357 
358 	if (!ok)
359 		goto end;
360 
361 	/* We may as well copy down any DSA parameters that are required */
362 	X509_get_pubkey_parameters(NULL, ctx->chain);
363 
364 	/* Check revocation status: we do this after copying parameters
365 	 * because they may be needed for CRL signature verification.
366 	 */
367 
368 	ok = ctx->check_revocation(ctx);
369 	if (!ok)
370 		goto end;
371 
372 	/* At this point, we have a chain and need to verify it */
373 	if (ctx->verify != NULL)
374 		ok = ctx->verify(ctx);
375 	else
376 		ok = internal_verify(ctx);
377 	if (!ok)
378 		goto end;
379 
380 #ifndef OPENSSL_NO_RFC3779
381 	/* RFC 3779 path validation, now that CRL check has been done */
382 	ok = v3_asid_validate_path(ctx);
383 	if (!ok)
384 		goto end;
385 	ok = v3_addr_validate_path(ctx);
386 	if (!ok)
387 		goto end;
388 #endif
389 
390 	/* If we get this far evaluate policies */
391 	if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
392 		ok = ctx->check_policy(ctx);
393 	if (!ok)
394 		goto end;
395 	if (0) {
396 end:
397 		X509_get_pubkey_parameters(NULL, ctx->chain);
398 	}
399 	if (sktmp != NULL)
400 		sk_X509_free(sktmp);
401 	if (chain_ss != NULL)
402 		X509_free(chain_ss);
403 	return ok;
404 }
405 
406 
407 /* Given a STACK_OF(X509) find the issuer of cert (if any)
408  */
409 
410 static X509 *
411 find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
412 {
413 	int i;
414 	X509 *issuer, *rv = NULL;
415 
416 	for (i = 0; i < sk_X509_num(sk); i++) {
417 		issuer = sk_X509_value(sk, i);
418 		if (ctx->check_issued(ctx, x, issuer)) {
419 			rv = issuer;
420 			if (x509_check_cert_time(ctx, rv, 1))
421 				break;
422 		}
423 	}
424 	return rv;
425 }
426 
427 /* Given a possible certificate and issuer check them */
428 
429 static int
430 check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
431 {
432 	int ret;
433 
434 	ret = X509_check_issued(issuer, x);
435 	if (ret == X509_V_OK)
436 		return 1;
437 	/* If we haven't asked for issuer errors don't set ctx */
438 	if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
439 		return 0;
440 
441 	ctx->error = ret;
442 	ctx->current_cert = x;
443 	ctx->current_issuer = issuer;
444 	return ctx->verify_cb(0, ctx);
445 }
446 
447 /* Alternative lookup method: look from a STACK stored in other_ctx */
448 
449 static int
450 get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
451 {
452 	*issuer = find_issuer(ctx, ctx->other_ctx, x);
453 	if (*issuer) {
454 		CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
455 		return 1;
456 	} else
457 		return 0;
458 }
459 
460 /* Check a certificate chains extensions for consistency
461  * with the supplied purpose
462  */
463 
464 static int
465 check_chain_extensions(X509_STORE_CTX *ctx)
466 {
467 #ifdef OPENSSL_NO_CHAIN_VERIFY
468 	return 1;
469 #else
470 	int i, ok = 0, must_be_ca, plen = 0;
471 	X509 *x;
472 	int (*cb)(int xok, X509_STORE_CTX *xctx);
473 	int proxy_path_length = 0;
474 	int purpose;
475 	int allow_proxy_certs;
476 
477 	cb = ctx->verify_cb;
478 
479 	/* must_be_ca can have 1 of 3 values:
480 	   -1: we accept both CA and non-CA certificates, to allow direct
481 	       use of self-signed certificates (which are marked as CA).
482 	   0:  we only accept non-CA certificates.  This is currently not
483 	       used, but the possibility is present for future extensions.
484 	   1:  we only accept CA certificates.  This is currently used for
485 	       all certificates in the chain except the leaf certificate.
486 	*/
487 	must_be_ca = -1;
488 
489 	/* CRL path validation */
490 	if (ctx->parent) {
491 		allow_proxy_certs = 0;
492 		purpose = X509_PURPOSE_CRL_SIGN;
493 	} else {
494 		allow_proxy_certs =
495 		    !!(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
496 #if 0
497 		/* A hack to keep people who don't want to modify their
498 		   software happy */
499 		if (issetugid() == 0 && getenv("OPENSSL_ALLOW_PROXY_CERTS"))
500 			allow_proxy_certs = 1;
501 #endif
502 		purpose = ctx->param->purpose;
503 	}
504 
505 	/* Check all untrusted certificates */
506 	for (i = 0; i < ctx->last_untrusted; i++) {
507 		int ret;
508 		x = sk_X509_value(ctx->chain, i);
509 		if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
510 		    (x->ex_flags & EXFLAG_CRITICAL)) {
511 			ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
512 			ctx->error_depth = i;
513 			ctx->current_cert = x;
514 			ok = cb(0, ctx);
515 			if (!ok)
516 				goto end;
517 		}
518 		if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
519 			ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
520 			ctx->error_depth = i;
521 			ctx->current_cert = x;
522 			ok = cb(0, ctx);
523 			if (!ok)
524 				goto end;
525 		}
526 		ret = X509_check_ca(x);
527 		switch (must_be_ca) {
528 		case -1:
529 			if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
530 			    (ret != 1) && (ret != 0)) {
531 				ret = 0;
532 				ctx->error = X509_V_ERR_INVALID_CA;
533 			} else
534 				ret = 1;
535 			break;
536 		case 0:
537 			if (ret != 0) {
538 				ret = 0;
539 				ctx->error = X509_V_ERR_INVALID_NON_CA;
540 			} else
541 				ret = 1;
542 			break;
543 		default:
544 			if ((ret == 0) ||
545 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
546 			    (ret != 1))) {
547 				ret = 0;
548 				ctx->error = X509_V_ERR_INVALID_CA;
549 			} else
550 				ret = 1;
551 			break;
552 		}
553 		if (ret == 0) {
554 			ctx->error_depth = i;
555 			ctx->current_cert = x;
556 			ok = cb(0, ctx);
557 			if (!ok)
558 				goto end;
559 		}
560 		if (ctx->param->purpose > 0) {
561 			ret = X509_check_purpose(x, purpose, must_be_ca > 0);
562 			if ((ret == 0) ||
563 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
564 			    (ret != 1))) {
565 				ctx->error = X509_V_ERR_INVALID_PURPOSE;
566 				ctx->error_depth = i;
567 				ctx->current_cert = x;
568 				ok = cb(0, ctx);
569 				if (!ok)
570 					goto end;
571 			}
572 		}
573 		/* Check pathlen if not self issued */
574 		if ((i > 1) && !(x->ex_flags & EXFLAG_SI) &&
575 		    (x->ex_pathlen != -1) &&
576 		    (plen > (x->ex_pathlen + proxy_path_length + 1))) {
577 			ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
578 			ctx->error_depth = i;
579 			ctx->current_cert = x;
580 			ok = cb(0, ctx);
581 			if (!ok)
582 				goto end;
583 		}
584 		/* Increment path length if not self issued */
585 		if (!(x->ex_flags & EXFLAG_SI))
586 			plen++;
587 		/* If this certificate is a proxy certificate, the next
588 		   certificate must be another proxy certificate or a EE
589 		   certificate.  If not, the next certificate must be a
590 		   CA certificate.  */
591 		if (x->ex_flags & EXFLAG_PROXY) {
592 			if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
593 				ctx->error =
594 				    X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
595 				ctx->error_depth = i;
596 				ctx->current_cert = x;
597 				ok = cb(0, ctx);
598 				if (!ok)
599 					goto end;
600 			}
601 			proxy_path_length++;
602 			must_be_ca = 0;
603 		} else
604 			must_be_ca = 1;
605 	}
606 	ok = 1;
607 
608 end:
609 	return ok;
610 #endif
611 }
612 
613 static int
614 check_name_constraints(X509_STORE_CTX *ctx)
615 {
616 	X509 *x;
617 	int i, j, rv;
618 
619 	/* Check name constraints for all certificates */
620 	for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
621 		x = sk_X509_value(ctx->chain, i);
622 		/* Ignore self issued certs unless last in chain */
623 		if (i && (x->ex_flags & EXFLAG_SI))
624 			continue;
625 		/* Check against constraints for all certificates higher in
626 		 * chain including trust anchor. Trust anchor not strictly
627 		 * speaking needed but if it includes constraints it is to be
628 		 * assumed it expects them to be obeyed.
629 		 */
630 		for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
631 			NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
632 			if (nc) {
633 				rv = NAME_CONSTRAINTS_check(x, nc);
634 				if (rv != X509_V_OK) {
635 					ctx->error = rv;
636 					ctx->error_depth = i;
637 					ctx->current_cert = x;
638 					if (!ctx->verify_cb(0, ctx))
639 						return 0;
640 				}
641 			}
642 		}
643 	}
644 	return 1;
645 }
646 
647 static int
648 check_trust(X509_STORE_CTX *ctx)
649 {
650 #ifdef OPENSSL_NO_CHAIN_VERIFY
651 	return 1;
652 #else
653 	int i, ok;
654 	X509 *x;
655 	int (*cb)(int xok, X509_STORE_CTX *xctx);
656 
657 	cb = ctx->verify_cb;
658 	/* For now just check the last certificate in the chain */
659 	i = sk_X509_num(ctx->chain) - 1;
660 	x = sk_X509_value(ctx->chain, i);
661 	ok = X509_check_trust(x, ctx->param->trust, 0);
662 	if (ok == X509_TRUST_TRUSTED)
663 		return 1;
664 	ctx->error_depth = i;
665 	ctx->current_cert = x;
666 	if (ok == X509_TRUST_REJECTED)
667 		ctx->error = X509_V_ERR_CERT_REJECTED;
668 	else
669 		ctx->error = X509_V_ERR_CERT_UNTRUSTED;
670 	ok = cb(0, ctx);
671 	return ok;
672 #endif
673 }
674 
675 static int
676 check_revocation(X509_STORE_CTX *ctx)
677 {
678 	int i, last, ok;
679 
680 	if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
681 		return 1;
682 	if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
683 		last = sk_X509_num(ctx->chain) - 1;
684 	else {
685 		/* If checking CRL paths this isn't the EE certificate */
686 		if (ctx->parent)
687 			return 1;
688 		last = 0;
689 	}
690 	for (i = 0; i <= last; i++) {
691 		ctx->error_depth = i;
692 		ok = check_cert(ctx);
693 		if (!ok)
694 			return ok;
695 	}
696 	return 1;
697 }
698 
699 static int
700 check_cert(X509_STORE_CTX *ctx)
701 {
702 	X509_CRL *crl = NULL, *dcrl = NULL;
703 	X509 *x;
704 	int ok, cnum;
705 	unsigned int last_reasons;
706 
707 	cnum = ctx->error_depth;
708 	x = sk_X509_value(ctx->chain, cnum);
709 	ctx->current_cert = x;
710 	ctx->current_issuer = NULL;
711 	ctx->current_crl_score = 0;
712 	ctx->current_reasons = 0;
713 	while (ctx->current_reasons != CRLDP_ALL_REASONS) {
714 		last_reasons = ctx->current_reasons;
715 		/* Try to retrieve relevant CRL */
716 		if (ctx->get_crl)
717 			ok = ctx->get_crl(ctx, &crl, x);
718 		else
719 			ok = get_crl_delta(ctx, &crl, &dcrl, x);
720 		/* If error looking up CRL, nothing we can do except
721 		 * notify callback
722 		 */
723 		if (!ok) {
724 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
725 			ok = ctx->verify_cb(0, ctx);
726 			goto err;
727 		}
728 		ctx->current_crl = crl;
729 		ok = ctx->check_crl(ctx, crl);
730 		if (!ok)
731 			goto err;
732 
733 		if (dcrl) {
734 			ok = ctx->check_crl(ctx, dcrl);
735 			if (!ok)
736 				goto err;
737 			ok = ctx->cert_crl(ctx, dcrl, x);
738 			if (!ok)
739 				goto err;
740 		} else
741 			ok = 1;
742 
743 		/* Don't look in full CRL if delta reason is removefromCRL */
744 		if (ok != 2) {
745 			ok = ctx->cert_crl(ctx, crl, x);
746 			if (!ok)
747 				goto err;
748 		}
749 
750 		X509_CRL_free(crl);
751 		X509_CRL_free(dcrl);
752 		crl = NULL;
753 		dcrl = NULL;
754 		/* If reasons not updated we wont get anywhere by
755 		 * another iteration, so exit loop.
756 		 */
757 		if (last_reasons == ctx->current_reasons) {
758 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
759 			ok = ctx->verify_cb(0, ctx);
760 			goto err;
761 		}
762 	}
763 
764 err:
765 	X509_CRL_free(crl);
766 	X509_CRL_free(dcrl);
767 
768 	ctx->current_crl = NULL;
769 	return ok;
770 }
771 
772 /* Check CRL times against values in X509_STORE_CTX */
773 
774 static int
775 check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
776 {
777 	time_t *ptime;
778 	int i;
779 
780 	if (notify)
781 		ctx->current_crl = crl;
782 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
783 		ptime = &ctx->param->check_time;
784 	else
785 		ptime = NULL;
786 
787 	i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
788 	if (i == 0) {
789 		if (!notify)
790 			return 0;
791 		ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
792 		if (!ctx->verify_cb(0, ctx))
793 			return 0;
794 	}
795 
796 	if (i > 0) {
797 		if (!notify)
798 			return 0;
799 		ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
800 		if (!ctx->verify_cb(0, ctx))
801 			return 0;
802 	}
803 
804 	if (X509_CRL_get_nextUpdate(crl)) {
805 		i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
806 
807 		if (i == 0) {
808 			if (!notify)
809 				return 0;
810 			ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
811 			if (!ctx->verify_cb(0, ctx))
812 				return 0;
813 		}
814 		/* Ignore expiry of base CRL is delta is valid */
815 		if ((i < 0) &&
816 		    !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
817 			if (!notify)
818 				return 0;
819 			ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
820 			if (!ctx->verify_cb(0, ctx))
821 				return 0;
822 		}
823 	}
824 
825 	if (notify)
826 		ctx->current_crl = NULL;
827 
828 	return 1;
829 }
830 
831 static int
832 get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
833     X509 **pissuer, int *pscore, unsigned int *preasons,
834     STACK_OF(X509_CRL) *crls)
835 {
836 	int i, crl_score, best_score = *pscore;
837 	unsigned int reasons, best_reasons = 0;
838 	X509 *x = ctx->current_cert;
839 	X509_CRL *crl, *best_crl = NULL;
840 	X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
841 
842 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
843 		crl = sk_X509_CRL_value(crls, i);
844 		reasons = *preasons;
845 		crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
846 
847 		if (crl_score > best_score) {
848 			best_crl = crl;
849 			best_crl_issuer = crl_issuer;
850 			best_score = crl_score;
851 			best_reasons = reasons;
852 		}
853 	}
854 
855 	if (best_crl) {
856 		if (*pcrl)
857 			X509_CRL_free(*pcrl);
858 		*pcrl = best_crl;
859 		*pissuer = best_crl_issuer;
860 		*pscore = best_score;
861 		*preasons = best_reasons;
862 		CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
863 		if (*pdcrl) {
864 			X509_CRL_free(*pdcrl);
865 			*pdcrl = NULL;
866 		}
867 		get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
868 	}
869 
870 	if (best_score >= CRL_SCORE_VALID)
871 		return 1;
872 
873 	return 0;
874 }
875 
876 /* Compare two CRL extensions for delta checking purposes. They should be
877  * both present or both absent. If both present all fields must be identical.
878  */
879 
880 static int
881 crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
882 {
883 	ASN1_OCTET_STRING *exta, *extb;
884 	int i;
885 
886 	i = X509_CRL_get_ext_by_NID(a, nid, -1);
887 	if (i >= 0) {
888 		/* Can't have multiple occurrences */
889 		if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
890 			return 0;
891 		exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
892 	} else
893 		exta = NULL;
894 
895 	i = X509_CRL_get_ext_by_NID(b, nid, -1);
896 
897 	if (i >= 0) {
898 		if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
899 			return 0;
900 		extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
901 	} else
902 		extb = NULL;
903 
904 	if (!exta && !extb)
905 		return 1;
906 
907 	if (!exta || !extb)
908 		return 0;
909 
910 	if (ASN1_OCTET_STRING_cmp(exta, extb))
911 		return 0;
912 
913 	return 1;
914 }
915 
916 /* See if a base and delta are compatible */
917 
918 static int
919 check_delta_base(X509_CRL *delta, X509_CRL *base)
920 {
921 	/* Delta CRL must be a delta */
922 	if (!delta->base_crl_number)
923 		return 0;
924 	/* Base must have a CRL number */
925 	if (!base->crl_number)
926 		return 0;
927 	/* Issuer names must match */
928 	if (X509_NAME_cmp(X509_CRL_get_issuer(base),
929 	    X509_CRL_get_issuer(delta)))
930 		return 0;
931 	/* AKID and IDP must match */
932 	if (!crl_extension_match(delta, base, NID_authority_key_identifier))
933 		return 0;
934 	if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
935 		return 0;
936 	/* Delta CRL base number must not exceed Full CRL number. */
937 	if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
938 		return 0;
939 	/* Delta CRL number must exceed full CRL number */
940 	if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
941 		return 1;
942 	return 0;
943 }
944 
945 /* For a given base CRL find a delta... maybe extend to delta scoring
946  * or retrieve a chain of deltas...
947  */
948 
949 static void
950 get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore, X509_CRL *base,
951     STACK_OF(X509_CRL) *crls)
952 {
953 	X509_CRL *delta;
954 	int i;
955 
956 	if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
957 		return;
958 	if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
959 		return;
960 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
961 		delta = sk_X509_CRL_value(crls, i);
962 		if (check_delta_base(delta, base)) {
963 			if (check_crl_time(ctx, delta, 0))
964 				*pscore |= CRL_SCORE_TIME_DELTA;
965 			CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL);
966 			*dcrl = delta;
967 			return;
968 		}
969 	}
970 	*dcrl = NULL;
971 }
972 
973 /* For a given CRL return how suitable it is for the supplied certificate 'x'.
974  * The return value is a mask of several criteria.
975  * If the issuer is not the certificate issuer this is returned in *pissuer.
976  * The reasons mask is also used to determine if the CRL is suitable: if
977  * no new reasons the CRL is rejected, otherwise reasons is updated.
978  */
979 
980 static int
981 get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons,
982     X509_CRL *crl, X509 *x)
983 {
984 	int crl_score = 0;
985 	unsigned int tmp_reasons = *preasons, crl_reasons;
986 
987 	/* First see if we can reject CRL straight away */
988 
989 	/* Invalid IDP cannot be processed */
990 	if (crl->idp_flags & IDP_INVALID)
991 		return 0;
992 	/* Reason codes or indirect CRLs need extended CRL support */
993 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
994 		if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
995 			return 0;
996 	} else if (crl->idp_flags & IDP_REASONS) {
997 		/* If no new reasons reject */
998 		if (!(crl->idp_reasons & ~tmp_reasons))
999 			return 0;
1000 	}
1001 	/* Don't process deltas at this stage */
1002 	else if (crl->base_crl_number)
1003 		return 0;
1004 	/* If issuer name doesn't match certificate need indirect CRL */
1005 	if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1006 		if (!(crl->idp_flags & IDP_INDIRECT))
1007 			return 0;
1008 	} else
1009 		crl_score |= CRL_SCORE_ISSUER_NAME;
1010 
1011 	if (!(crl->flags & EXFLAG_CRITICAL))
1012 		crl_score |= CRL_SCORE_NOCRITICAL;
1013 
1014 	/* Check expiry */
1015 	if (check_crl_time(ctx, crl, 0))
1016 		crl_score |= CRL_SCORE_TIME;
1017 
1018 	/* Check authority key ID and locate certificate issuer */
1019 	crl_akid_check(ctx, crl, pissuer, &crl_score);
1020 
1021 	/* If we can't locate certificate issuer at this point forget it */
1022 
1023 	if (!(crl_score & CRL_SCORE_AKID))
1024 		return 0;
1025 
1026 	/* Check cert for matching CRL distribution points */
1027 
1028 	if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1029 		/* If no new reasons reject */
1030 		if (!(crl_reasons & ~tmp_reasons))
1031 			return 0;
1032 		tmp_reasons |= crl_reasons;
1033 		crl_score |= CRL_SCORE_SCOPE;
1034 	}
1035 
1036 	*preasons = tmp_reasons;
1037 
1038 	return crl_score;
1039 }
1040 
1041 static void
1042 crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
1043     int *pcrl_score)
1044 {
1045 	X509 *crl_issuer = NULL;
1046 	X509_NAME *cnm = X509_CRL_get_issuer(crl);
1047 	int cidx = ctx->error_depth;
1048 	int i;
1049 
1050 	if (cidx != sk_X509_num(ctx->chain) - 1)
1051 		cidx++;
1052 
1053 	crl_issuer = sk_X509_value(ctx->chain, cidx);
1054 
1055 	if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1056 		if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1057 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_ISSUER_CERT;
1058 			*pissuer = crl_issuer;
1059 			return;
1060 		}
1061 	}
1062 
1063 	for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1064 		crl_issuer = sk_X509_value(ctx->chain, cidx);
1065 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1066 			continue;
1067 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1068 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_SAME_PATH;
1069 			*pissuer = crl_issuer;
1070 			return;
1071 		}
1072 	}
1073 
1074 	/* Anything else needs extended CRL support */
1075 
1076 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1077 		return;
1078 
1079 	/* Otherwise the CRL issuer is not on the path. Look for it in the
1080 	 * set of untrusted certificates.
1081 	 */
1082 	for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1083 		crl_issuer = sk_X509_value(ctx->untrusted, i);
1084 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1085 			continue;
1086 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1087 			*pissuer = crl_issuer;
1088 			*pcrl_score |= CRL_SCORE_AKID;
1089 			return;
1090 		}
1091 	}
1092 }
1093 
1094 /* Check the path of a CRL issuer certificate. This creates a new
1095  * X509_STORE_CTX and populates it with most of the parameters from the
1096  * parent. This could be optimised somewhat since a lot of path checking
1097  * will be duplicated by the parent, but this will rarely be used in
1098  * practice.
1099  */
1100 
1101 static int
1102 check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1103 {
1104 	X509_STORE_CTX crl_ctx;
1105 	int ret;
1106 
1107 	/* Don't allow recursive CRL path validation */
1108 	if (ctx->parent)
1109 		return 0;
1110 	if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
1111 		return -1;
1112 
1113 	crl_ctx.crls = ctx->crls;
1114 	/* Copy verify params across */
1115 	X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1116 
1117 	crl_ctx.parent = ctx;
1118 	crl_ctx.verify_cb = ctx->verify_cb;
1119 
1120 	/* Verify CRL issuer */
1121 	ret = X509_verify_cert(&crl_ctx);
1122 
1123 	if (ret <= 0)
1124 		goto err;
1125 
1126 	/* Check chain is acceptable */
1127 	ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1128 
1129 err:
1130 	X509_STORE_CTX_cleanup(&crl_ctx);
1131 	return ret;
1132 }
1133 
1134 /* RFC3280 says nothing about the relationship between CRL path
1135  * and certificate path, which could lead to situations where a
1136  * certificate could be revoked or validated by a CA not authorised
1137  * to do so. RFC5280 is more strict and states that the two paths must
1138  * end in the same trust anchor, though some discussions remain...
1139  * until this is resolved we use the RFC5280 version
1140  */
1141 
1142 static int
1143 check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
1144     STACK_OF(X509) *crl_path)
1145 {
1146 	X509 *cert_ta, *crl_ta;
1147 
1148 	cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1149 	crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1150 	if (!X509_cmp(cert_ta, crl_ta))
1151 		return 1;
1152 	return 0;
1153 }
1154 
1155 /* Check for match between two dist point names: three separate cases.
1156  * 1. Both are relative names and compare X509_NAME types.
1157  * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1158  * 3. Both are full names and compare two GENERAL_NAMES.
1159  * 4. One is NULL: automatic match.
1160  */
1161 
1162 static int
1163 idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1164 {
1165 	X509_NAME *nm = NULL;
1166 	GENERAL_NAMES *gens = NULL;
1167 	GENERAL_NAME *gena, *genb;
1168 	int i, j;
1169 
1170 	if (!a || !b)
1171 		return 1;
1172 	if (a->type == 1) {
1173 		if (!a->dpname)
1174 			return 0;
1175 		/* Case 1: two X509_NAME */
1176 		if (b->type == 1) {
1177 			if (!b->dpname)
1178 				return 0;
1179 			if (!X509_NAME_cmp(a->dpname, b->dpname))
1180 				return 1;
1181 			else
1182 				return 0;
1183 		}
1184 		/* Case 2: set name and GENERAL_NAMES appropriately */
1185 		nm = a->dpname;
1186 		gens = b->name.fullname;
1187 	} else if (b->type == 1) {
1188 		if (!b->dpname)
1189 			return 0;
1190 		/* Case 2: set name and GENERAL_NAMES appropriately */
1191 		gens = a->name.fullname;
1192 		nm = b->dpname;
1193 	}
1194 
1195 	/* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1196 	if (nm) {
1197 		for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1198 			gena = sk_GENERAL_NAME_value(gens, i);
1199 			if (gena->type != GEN_DIRNAME)
1200 				continue;
1201 			if (!X509_NAME_cmp(nm, gena->d.directoryName))
1202 				return 1;
1203 		}
1204 		return 0;
1205 	}
1206 
1207 	/* Else case 3: two GENERAL_NAMES */
1208 
1209 	for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1210 		gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1211 		for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1212 			genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1213 			if (!GENERAL_NAME_cmp(gena, genb))
1214 				return 1;
1215 		}
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 static int
1222 crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1223 {
1224 	int i;
1225 	X509_NAME *nm = X509_CRL_get_issuer(crl);
1226 
1227 	/* If no CRLissuer return is successful iff don't need a match */
1228 	if (!dp->CRLissuer)
1229 		return !!(crl_score & CRL_SCORE_ISSUER_NAME);
1230 	for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1231 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1232 		if (gen->type != GEN_DIRNAME)
1233 			continue;
1234 		if (!X509_NAME_cmp(gen->d.directoryName, nm))
1235 			return 1;
1236 	}
1237 	return 0;
1238 }
1239 
1240 /* Check CRLDP and IDP */
1241 
1242 static int
1243 crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons)
1244 {
1245 	int i;
1246 
1247 	if (crl->idp_flags & IDP_ONLYATTR)
1248 		return 0;
1249 	if (x->ex_flags & EXFLAG_CA) {
1250 		if (crl->idp_flags & IDP_ONLYUSER)
1251 			return 0;
1252 	} else {
1253 		if (crl->idp_flags & IDP_ONLYCA)
1254 			return 0;
1255 	}
1256 	*preasons = crl->idp_reasons;
1257 	for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1258 		DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1259 		if (crldp_check_crlissuer(dp, crl, crl_score)) {
1260 			if (!crl->idp ||
1261 			    idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1262 				*preasons &= dp->dp_reasons;
1263 				return 1;
1264 			}
1265 		}
1266 	}
1267 	if ((!crl->idp || !crl->idp->distpoint) &&
1268 	    (crl_score & CRL_SCORE_ISSUER_NAME))
1269 		return 1;
1270 	return 0;
1271 }
1272 
1273 /* Retrieve CRL corresponding to current certificate.
1274  * If deltas enabled try to find a delta CRL too
1275  */
1276 
1277 static int
1278 get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1279 {
1280 	int ok;
1281 	X509 *issuer = NULL;
1282 	int crl_score = 0;
1283 	unsigned int reasons;
1284 	X509_CRL *crl = NULL, *dcrl = NULL;
1285 	STACK_OF(X509_CRL) *skcrl;
1286 	X509_NAME *nm = X509_get_issuer_name(x);
1287 
1288 	reasons = ctx->current_reasons;
1289 	ok = get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons,
1290 	    ctx->crls);
1291 	if (ok)
1292 		goto done;
1293 
1294 	/* Lookup CRLs from store */
1295 	skcrl = ctx->lookup_crls(ctx, nm);
1296 
1297 	/* If no CRLs found and a near match from get_crl_sk use that */
1298 	if (!skcrl && crl)
1299 		goto done;
1300 
1301 	get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1302 
1303 	sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1304 
1305 done:
1306 
1307 	/* If we got any kind of CRL use it and return success */
1308 	if (crl) {
1309 		ctx->current_issuer = issuer;
1310 		ctx->current_crl_score = crl_score;
1311 		ctx->current_reasons = reasons;
1312 		*pcrl = crl;
1313 		*pdcrl = dcrl;
1314 		return 1;
1315 	}
1316 
1317 	return 0;
1318 }
1319 
1320 /* Check CRL validity */
1321 static int
1322 check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1323 {
1324 	X509 *issuer = NULL;
1325 	EVP_PKEY *ikey = NULL;
1326 	int ok = 0, chnum, cnum;
1327 
1328 	cnum = ctx->error_depth;
1329 	chnum = sk_X509_num(ctx->chain) - 1;
1330 	/* if we have an alternative CRL issuer cert use that */
1331 	if (ctx->current_issuer) {
1332 		issuer = ctx->current_issuer;
1333 	} else if (cnum < chnum) {
1334 		/* Else find CRL issuer: if not last certificate then issuer
1335 	 	* is next certificate in chain.
1336 	 	*/
1337 		issuer = sk_X509_value(ctx->chain, cnum + 1);
1338 	} else {
1339 		issuer = sk_X509_value(ctx->chain, chnum);
1340 		/* If not self signed, can't check signature */
1341 		if (!ctx->check_issued(ctx, issuer, issuer)) {
1342 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1343 			ok = ctx->verify_cb(0, ctx);
1344 			if (!ok)
1345 				goto err;
1346 		}
1347 	}
1348 
1349 	if (issuer) {
1350 		/* Skip most tests for deltas because they have already
1351 		 * been done
1352 		 */
1353 		if (!crl->base_crl_number) {
1354 			/* Check for cRLSign bit if keyUsage present */
1355 			if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1356 			    !(issuer->ex_kusage & KU_CRL_SIGN)) {
1357 				ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1358 				ok = ctx->verify_cb(0, ctx);
1359 				if (!ok)
1360 					goto err;
1361 			}
1362 
1363 			if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1364 				ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1365 				ok = ctx->verify_cb(0, ctx);
1366 				if (!ok)
1367 					goto err;
1368 			}
1369 
1370 			if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1371 				if (check_crl_path(ctx,
1372 				    ctx->current_issuer) <= 0) {
1373 					ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1374 					ok = ctx->verify_cb(0, ctx);
1375 					if (!ok)
1376 						goto err;
1377 				}
1378 			}
1379 
1380 			if (crl->idp_flags & IDP_INVALID) {
1381 				ctx->error = X509_V_ERR_INVALID_EXTENSION;
1382 				ok = ctx->verify_cb(0, ctx);
1383 				if (!ok)
1384 					goto err;
1385 			}
1386 
1387 
1388 		}
1389 
1390 		if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1391 			ok = check_crl_time(ctx, crl, 1);
1392 			if (!ok)
1393 				goto err;
1394 		}
1395 
1396 		/* Attempt to get issuer certificate public key */
1397 		ikey = X509_get_pubkey(issuer);
1398 
1399 		if (!ikey) {
1400 			ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1401 			ok = ctx->verify_cb(0, ctx);
1402 			if (!ok)
1403 				goto err;
1404 		} else {
1405 			/* Verify CRL signature */
1406 			if (X509_CRL_verify(crl, ikey) <= 0) {
1407 				ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1408 				ok = ctx->verify_cb(0, ctx);
1409 				if (!ok)
1410 					goto err;
1411 			}
1412 		}
1413 	}
1414 
1415 	ok = 1;
1416 
1417 err:
1418 	EVP_PKEY_free(ikey);
1419 	return ok;
1420 }
1421 
1422 /* Check certificate against CRL */
1423 static int
1424 cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1425 {
1426 	int ok;
1427 	X509_REVOKED *rev;
1428 
1429 	/* The rules changed for this... previously if a CRL contained
1430 	 * unhandled critical extensions it could still be used to indicate
1431 	 * a certificate was revoked. This has since been changed since
1432 	 * critical extension can change the meaning of CRL entries.
1433 	 */
1434 	if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
1435 	    (crl->flags & EXFLAG_CRITICAL)) {
1436 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1437 		ok = ctx->verify_cb(0, ctx);
1438 		if (!ok)
1439 			return 0;
1440 	}
1441 	/* Look for serial number of certificate in CRL
1442 	 * If found make sure reason is not removeFromCRL.
1443 	 */
1444 	if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1445 		if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1446 			return 2;
1447 		ctx->error = X509_V_ERR_CERT_REVOKED;
1448 		ok = ctx->verify_cb(0, ctx);
1449 		if (!ok)
1450 			return 0;
1451 	}
1452 
1453 	return 1;
1454 }
1455 
1456 static int
1457 check_policy(X509_STORE_CTX *ctx)
1458 {
1459 	int ret;
1460 
1461 	if (ctx->parent)
1462 		return 1;
1463 	ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1464 	    ctx->param->policies, ctx->param->flags);
1465 	if (ret == 0) {
1466 		X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1467 		return 0;
1468 	}
1469 	/* Invalid or inconsistent extensions */
1470 	if (ret == -1) {
1471 		/* Locate certificates with bad extensions and notify
1472 		 * callback.
1473 		 */
1474 		X509 *x;
1475 		int i;
1476 		for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1477 			x = sk_X509_value(ctx->chain, i);
1478 			if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1479 				continue;
1480 			ctx->current_cert = x;
1481 			ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1482 			if (!ctx->verify_cb(0, ctx))
1483 				return 0;
1484 		}
1485 		return 1;
1486 	}
1487 	if (ret == -2) {
1488 		ctx->current_cert = NULL;
1489 		ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1490 		return ctx->verify_cb(0, ctx);
1491 	}
1492 
1493 	if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1494 		ctx->current_cert = NULL;
1495 		ctx->error = X509_V_OK;
1496 		if (!ctx->verify_cb(2, ctx))
1497 			return 0;
1498 	}
1499 
1500 	return 1;
1501 }
1502 
1503 int
1504 x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet)
1505 {
1506 	time_t *ptime;
1507 	int i;
1508 
1509 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1510 		ptime = &ctx->param->check_time;
1511 	else
1512 		ptime = NULL;
1513 
1514 	i = X509_cmp_time(X509_get_notBefore(x), ptime);
1515 	if (i == 0) {
1516 		if (quiet)
1517 			return 0;
1518 		ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
1519 		ctx->current_cert = x;
1520 		if (!ctx->verify_cb(0, ctx))
1521 			return 0;
1522 	}
1523 
1524 	if (i > 0) {
1525 		if (quiet)
1526 			return 0;
1527 		ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
1528 		ctx->current_cert = x;
1529 		if (!ctx->verify_cb(0, ctx))
1530 			return 0;
1531 	}
1532 
1533 	i = X509_cmp_time(X509_get_notAfter(x), ptime);
1534 	if (i == 0) {
1535 		if (quiet)
1536 			return 0;
1537 		ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
1538 		ctx->current_cert = x;
1539 		if (!ctx->verify_cb(0, ctx))
1540 			return 0;
1541 	}
1542 
1543 	if (i < 0) {
1544 		if (quiet)
1545 			return 0;
1546 		ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
1547 		ctx->current_cert = x;
1548 		if (!ctx->verify_cb(0, ctx))
1549 			return 0;
1550 	}
1551 
1552 	return 1;
1553 }
1554 
1555 static int
1556 internal_verify(X509_STORE_CTX *ctx)
1557 {
1558 	int ok = 0, n;
1559 	X509 *xs, *xi;
1560 	EVP_PKEY *pkey = NULL;
1561 	int (*cb)(int xok, X509_STORE_CTX *xctx);
1562 
1563 	cb = ctx->verify_cb;
1564 
1565 	n = sk_X509_num(ctx->chain);
1566 	ctx->error_depth = n - 1;
1567 	n--;
1568 	xi = sk_X509_value(ctx->chain, n);
1569 
1570 	if (ctx->check_issued(ctx, xi, xi))
1571 		xs = xi;
1572 	else {
1573 		if (n <= 0) {
1574 			ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
1575 			ctx->current_cert = xi;
1576 			ok = cb(0, ctx);
1577 			goto end;
1578 		} else {
1579 			n--;
1580 			ctx->error_depth = n;
1581 			xs = sk_X509_value(ctx->chain, n);
1582 		}
1583 	}
1584 
1585 /*	ctx->error=0;  not needed */
1586 	while (n >= 0) {
1587 		ctx->error_depth = n;
1588 
1589 		/* Skip signature check for self signed certificates unless
1590 		 * explicitly asked for. It doesn't add any security and
1591 		 * just wastes time.
1592 		 */
1593 		if (!xs->valid && (xs != xi ||
1594 		    (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1595 			if ((pkey = X509_get_pubkey(xi)) == NULL) {
1596 				ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1597 				ctx->current_cert = xi;
1598 				ok = (*cb)(0, ctx);
1599 				if (!ok)
1600 					goto end;
1601 			} else if (X509_verify(xs, pkey) <= 0) {
1602 				ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1603 				ctx->current_cert = xs;
1604 				ok = (*cb)(0, ctx);
1605 				if (!ok) {
1606 					EVP_PKEY_free(pkey);
1607 					goto end;
1608 				}
1609 			}
1610 			EVP_PKEY_free(pkey);
1611 			pkey = NULL;
1612 		}
1613 
1614 		xs->valid = 1;
1615 
1616 		ok = x509_check_cert_time(ctx, xs, 0);
1617 		if (!ok)
1618 			goto end;
1619 
1620 		/* The last error (if any) is still in the error value */
1621 		ctx->current_issuer = xi;
1622 		ctx->current_cert = xs;
1623 		ok = (*cb)(1, ctx);
1624 		if (!ok)
1625 			goto end;
1626 
1627 		n--;
1628 		if (n >= 0) {
1629 			xi = xs;
1630 			xs = sk_X509_value(ctx->chain, n);
1631 		}
1632 	}
1633 	ok = 1;
1634 
1635 end:
1636 	return ok;
1637 }
1638 
1639 int
1640 X509_cmp_current_time(const ASN1_TIME *ctm)
1641 {
1642 	return X509_cmp_time(ctm, NULL);
1643 }
1644 
1645 int
1646 X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1647 {
1648 	char *str;
1649 	ASN1_TIME atm;
1650 	long offset;
1651 	char buff1[24], buff2[24], *p;
1652 	int i, j;
1653 
1654 	p = buff1;
1655 	i = ctm->length;
1656 	str = (char *)ctm->data;
1657 	if (ctm->type == V_ASN1_UTCTIME) {
1658 		if ((i < 11) || (i > 17))
1659 			return 0;
1660 		memcpy(p, str, 10);
1661 		p += 10;
1662 		str += 10;
1663 	} else {
1664 		if (i < 13)
1665 			return 0;
1666 		memcpy(p, str, 12);
1667 		p += 12;
1668 		str += 12;
1669 	}
1670 
1671 	if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1672 		*(p++) = '0';
1673 		*(p++) = '0';
1674 	} else {
1675 		*(p++) = *(str++);
1676 		*(p++) = *(str++);
1677 		/* Skip any fractional seconds... */
1678 		if (*str == '.') {
1679 			str++;
1680 			while ((*str >= '0') && (*str <= '9'))
1681 				str++;
1682 		}
1683 	}
1684 	*(p++) = 'Z';
1685 	*(p++) = '\0';
1686 
1687 	if (*str == 'Z')
1688 		offset = 0;
1689 	else {
1690 		if ((*str != '+') && (*str != '-'))
1691 			return 0;
1692 		offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1693 		offset += (str[3] - '0') * 10 + (str[4] - '0');
1694 		if (*str == '-')
1695 			offset = -offset;
1696 	}
1697 	atm.type = ctm->type;
1698 	atm.flags = 0;
1699 	atm.length = sizeof(buff2);
1700 	atm.data = (unsigned char *)buff2;
1701 
1702 	if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1703 		return 0;
1704 
1705 	if (ctm->type == V_ASN1_UTCTIME) {
1706 		i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1707 		if (i < 50)
1708 			i += 100; /* cf. RFC 2459 */
1709 		j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1710 		if (j < 50)
1711 			j += 100;
1712 		if (i < j)
1713 			return -1;
1714 		if (i > j)
1715 			return 1;
1716 	}
1717 	i = strcmp(buff1, buff2);
1718 	if (i == 0) /* wait a second then return younger :-) */
1719 		return -1;
1720 	else
1721 		return i;
1722 }
1723 
1724 ASN1_TIME *
1725 X509_gmtime_adj(ASN1_TIME *s, long adj)
1726 {
1727 	return X509_time_adj(s, adj, NULL);
1728 }
1729 
1730 ASN1_TIME *
1731 X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1732 {
1733 	return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1734 }
1735 
1736 ASN1_TIME *
1737 X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *in_tm)
1738 {
1739 	time_t t;
1740 
1741 	if (in_tm)
1742 		t = *in_tm;
1743 	else
1744 		time(&t);
1745 
1746 	if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1747 		if (s->type == V_ASN1_UTCTIME)
1748 			return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1749 		if (s->type == V_ASN1_GENERALIZEDTIME)
1750 			return ASN1_GENERALIZEDTIME_adj(s, t, offset_day,
1751 			    offset_sec);
1752 	}
1753 	return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1754 }
1755 
1756 int
1757 X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1758 {
1759 	EVP_PKEY *ktmp = NULL, *ktmp2;
1760 	int i, j;
1761 
1762 	if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1763 		return 1;
1764 
1765 	for (i = 0; i < sk_X509_num(chain); i++) {
1766 		ktmp = X509_get_pubkey(sk_X509_value(chain, i));
1767 		if (ktmp == NULL) {
1768 			X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1769 			    X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1770 			return 0;
1771 		}
1772 		if (!EVP_PKEY_missing_parameters(ktmp))
1773 			break;
1774 		else {
1775 			EVP_PKEY_free(ktmp);
1776 			ktmp = NULL;
1777 		}
1778 	}
1779 	if (ktmp == NULL) {
1780 		X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1781 		    X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1782 		return 0;
1783 	}
1784 
1785 	/* first, populate the other certs */
1786 	for (j = i - 1; j >= 0; j--) {
1787 		ktmp2 = X509_get_pubkey(sk_X509_value(chain, j));
1788 		EVP_PKEY_copy_parameters(ktmp2, ktmp);
1789 		EVP_PKEY_free(ktmp2);
1790 	}
1791 
1792 	if (pkey != NULL)
1793 		EVP_PKEY_copy_parameters(pkey, ktmp);
1794 	EVP_PKEY_free(ktmp);
1795 	return 1;
1796 }
1797 
1798 int
1799 X509_STORE_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
1800     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
1801 {
1802 	/* This function is (usually) called only once, by
1803 	 * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c). */
1804 	return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX,
1805 	    argl, argp, new_func, dup_func, free_func);
1806 }
1807 
1808 int
1809 X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1810 {
1811 	return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1812 }
1813 
1814 void *
1815 X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1816 {
1817 	return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1818 }
1819 
1820 int
1821 X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1822 {
1823 	return ctx->error;
1824 }
1825 
1826 void
1827 X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1828 {
1829 	ctx->error = err;
1830 }
1831 
1832 int
1833 X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1834 {
1835 	return ctx->error_depth;
1836 }
1837 
1838 X509 *
1839 X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1840 {
1841 	return ctx->current_cert;
1842 }
1843 
1844 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1845 {
1846 	return ctx->chain;
1847 }
1848 
1849 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1850 {
1851 	int i;
1852 	X509 *x;
1853 	STACK_OF(X509) *chain;
1854 
1855 	if (!ctx->chain || !(chain = sk_X509_dup(ctx->chain)))
1856 		return NULL;
1857 	for (i = 0; i < sk_X509_num(chain); i++) {
1858 		x = sk_X509_value(chain, i);
1859 		CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1860 	}
1861 	return chain;
1862 }
1863 
1864 X509 *
1865 X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
1866 {
1867 	return ctx->current_issuer;
1868 }
1869 
1870 X509_CRL *
1871 X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
1872 {
1873 	return ctx->current_crl;
1874 }
1875 
1876 X509_STORE_CTX *
1877 X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
1878 {
1879 	return ctx->parent;
1880 }
1881 
1882 void
1883 X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
1884 {
1885 	ctx->cert = x;
1886 }
1887 
1888 void
1889 X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
1890 {
1891 	ctx->untrusted = sk;
1892 }
1893 
1894 void
1895 X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
1896 {
1897 	ctx->crls = sk;
1898 }
1899 
1900 int
1901 X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
1902 {
1903 	return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
1904 }
1905 
1906 int
1907 X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
1908 {
1909 	return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
1910 }
1911 
1912 /* This function is used to set the X509_STORE_CTX purpose and trust
1913  * values. This is intended to be used when another structure has its
1914  * own trust and purpose values which (if set) will be inherited by
1915  * the ctx. If they aren't set then we will usually have a default
1916  * purpose in mind which should then be used to set the trust value.
1917  * An example of this is SSL use: an SSL structure will have its own
1918  * purpose and trust settings which the application can set: if they
1919  * aren't set then we use the default of SSL client/server.
1920  */
1921 
1922 int
1923 X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
1924     int purpose, int trust)
1925 {
1926 	int idx;
1927 
1928 	/* If purpose not set use default */
1929 	if (!purpose)
1930 		purpose = def_purpose;
1931 	/* If we have a purpose then check it is valid */
1932 	if (purpose) {
1933 		X509_PURPOSE *ptmp;
1934 		idx = X509_PURPOSE_get_by_id(purpose);
1935 		if (idx == -1) {
1936 			X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1937 			    X509_R_UNKNOWN_PURPOSE_ID);
1938 			return 0;
1939 		}
1940 		ptmp = X509_PURPOSE_get0(idx);
1941 		if (ptmp->trust == X509_TRUST_DEFAULT) {
1942 			idx = X509_PURPOSE_get_by_id(def_purpose);
1943 			if (idx == -1) {
1944 				X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1945 				    X509_R_UNKNOWN_PURPOSE_ID);
1946 				return 0;
1947 			}
1948 			ptmp = X509_PURPOSE_get0(idx);
1949 		}
1950 		/* If trust not set then get from purpose default */
1951 		if (!trust)
1952 			trust = ptmp->trust;
1953 	}
1954 	if (trust) {
1955 		idx = X509_TRUST_get_by_id(trust);
1956 		if (idx == -1) {
1957 			X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1958 			    X509_R_UNKNOWN_TRUST_ID);
1959 			return 0;
1960 		}
1961 	}
1962 
1963 	if (purpose && !ctx->param->purpose)
1964 		ctx->param->purpose = purpose;
1965 	if (trust && !ctx->param->trust)
1966 		ctx->param->trust = trust;
1967 	return 1;
1968 }
1969 
1970 X509_STORE_CTX *
1971 X509_STORE_CTX_new(void)
1972 {
1973 	X509_STORE_CTX *ctx;
1974 
1975 	ctx = calloc(1, sizeof(X509_STORE_CTX));
1976 	if (!ctx) {
1977 		X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
1978 		return NULL;
1979 	}
1980 	return ctx;
1981 }
1982 
1983 void
1984 X509_STORE_CTX_free(X509_STORE_CTX *ctx)
1985 {
1986 	if (ctx == NULL)
1987 		return;
1988 
1989 	X509_STORE_CTX_cleanup(ctx);
1990 	free(ctx);
1991 }
1992 
1993 int
1994 X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
1995     STACK_OF(X509) *chain)
1996 {
1997 	int ret = 1;
1998 
1999 	ctx->ctx = store;
2000 	ctx->current_method = 0;
2001 	ctx->cert = x509;
2002 	ctx->untrusted = chain;
2003 	ctx->crls = NULL;
2004 	ctx->last_untrusted = 0;
2005 	ctx->other_ctx = NULL;
2006 	ctx->valid = 0;
2007 	ctx->chain = NULL;
2008 	ctx->error = 0;
2009 	ctx->explicit_policy = 0;
2010 	ctx->error_depth = 0;
2011 	ctx->current_cert = NULL;
2012 	ctx->current_issuer = NULL;
2013 	ctx->current_crl = NULL;
2014 	ctx->current_crl_score = 0;
2015 	ctx->current_reasons = 0;
2016 	ctx->tree = NULL;
2017 	ctx->parent = NULL;
2018 
2019 	ctx->param = X509_VERIFY_PARAM_new();
2020 
2021 	if (!ctx->param) {
2022 		X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2023 		return 0;
2024 	}
2025 
2026 	/* Inherit callbacks and flags from X509_STORE if not set
2027 	 * use defaults.
2028 	 */
2029 
2030 	if (store)
2031 		ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2032 	else
2033 		ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT|X509_VP_FLAG_ONCE;
2034 
2035 	if (store) {
2036 		ctx->verify_cb = store->verify_cb;
2037 		ctx->cleanup = store->cleanup;
2038 	} else
2039 		ctx->cleanup = 0;
2040 
2041 	if (ret)
2042 		ret = X509_VERIFY_PARAM_inherit(ctx->param,
2043 		    X509_VERIFY_PARAM_lookup("default"));
2044 
2045 	if (ret == 0) {
2046 		X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2047 		return 0;
2048 	}
2049 
2050 	if (store && store->check_issued)
2051 		ctx->check_issued = store->check_issued;
2052 	else
2053 		ctx->check_issued = check_issued;
2054 
2055 	if (store && store->get_issuer)
2056 		ctx->get_issuer = store->get_issuer;
2057 	else
2058 		ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2059 
2060 	if (store && store->verify_cb)
2061 		ctx->verify_cb = store->verify_cb;
2062 	else
2063 		ctx->verify_cb = null_callback;
2064 
2065 	if (store && store->verify)
2066 		ctx->verify = store->verify;
2067 	else
2068 		ctx->verify = internal_verify;
2069 
2070 	if (store && store->check_revocation)
2071 		ctx->check_revocation = store->check_revocation;
2072 	else
2073 		ctx->check_revocation = check_revocation;
2074 
2075 	if (store && store->get_crl)
2076 		ctx->get_crl = store->get_crl;
2077 	else
2078 		ctx->get_crl = NULL;
2079 
2080 	if (store && store->check_crl)
2081 		ctx->check_crl = store->check_crl;
2082 	else
2083 		ctx->check_crl = check_crl;
2084 
2085 	if (store && store->cert_crl)
2086 		ctx->cert_crl = store->cert_crl;
2087 	else
2088 		ctx->cert_crl = cert_crl;
2089 
2090 	if (store && store->lookup_certs)
2091 		ctx->lookup_certs = store->lookup_certs;
2092 	else
2093 		ctx->lookup_certs = X509_STORE_get1_certs;
2094 
2095 	if (store && store->lookup_crls)
2096 		ctx->lookup_crls = store->lookup_crls;
2097 	else
2098 		ctx->lookup_crls = X509_STORE_get1_crls;
2099 
2100 	ctx->check_policy = check_policy;
2101 
2102 
2103 	/* This memset() can't make any sense anyway, so it's removed. As
2104 	 * X509_STORE_CTX_cleanup does a proper "free" on the ex_data, we put a
2105 	 * corresponding "new" here and remove this bogus initialisation. */
2106 	/* memset(&(ctx->ex_data),0,sizeof(CRYPTO_EX_DATA)); */
2107 	if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2108 	    &(ctx->ex_data))) {
2109 		free(ctx);
2110 		X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2111 		return 0;
2112 	}
2113 	return 1;
2114 }
2115 
2116 /* Set alternative lookup method: just a STACK of trusted certificates.
2117  * This avoids X509_STORE nastiness where it isn't needed.
2118  */
2119 
2120 void
2121 X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2122 {
2123 	ctx->other_ctx = sk;
2124 	ctx->get_issuer = get_issuer_sk;
2125 }
2126 
2127 void
2128 X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2129 {
2130 	if (ctx->cleanup)
2131 		ctx->cleanup(ctx);
2132 	if (ctx->param != NULL) {
2133 		if (ctx->parent == NULL)
2134 			X509_VERIFY_PARAM_free(ctx->param);
2135 		ctx->param = NULL;
2136 	}
2137 	if (ctx->tree != NULL) {
2138 		X509_policy_tree_free(ctx->tree);
2139 		ctx->tree = NULL;
2140 	}
2141 	if (ctx->chain != NULL) {
2142 		sk_X509_pop_free(ctx->chain, X509_free);
2143 		ctx->chain = NULL;
2144 	}
2145 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX,
2146 	    ctx, &(ctx->ex_data));
2147 	memset(&ctx->ex_data, 0, sizeof(CRYPTO_EX_DATA));
2148 }
2149 
2150 void
2151 X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2152 {
2153 	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2154 }
2155 
2156 void
2157 X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2158 {
2159 	X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2160 }
2161 
2162 void
2163 X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, time_t t)
2164 {
2165 	X509_VERIFY_PARAM_set_time(ctx->param, t);
2166 }
2167 
2168 void
2169 X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2170     int (*verify_cb)(int, X509_STORE_CTX *))
2171 {
2172 	ctx->verify_cb = verify_cb;
2173 }
2174 
2175 X509_POLICY_TREE *
2176 X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2177 {
2178 	return ctx->tree;
2179 }
2180 
2181 int
2182 X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2183 {
2184 	return ctx->explicit_policy;
2185 }
2186 
2187 int
2188 X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2189 {
2190 	const X509_VERIFY_PARAM *param;
2191 	param = X509_VERIFY_PARAM_lookup(name);
2192 	if (!param)
2193 		return 0;
2194 	return X509_VERIFY_PARAM_inherit(ctx->param, param);
2195 }
2196 
2197 X509_VERIFY_PARAM *
2198 X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2199 {
2200 	return ctx->param;
2201 }
2202 
2203 void
2204 X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2205 {
2206 	if (ctx->param)
2207 		X509_VERIFY_PARAM_free(ctx->param);
2208 	ctx->param = param;
2209 }
2210 
2211 IMPLEMENT_STACK_OF(X509)
2212 IMPLEMENT_ASN1_SET_OF(X509)
2213 
2214 IMPLEMENT_STACK_OF(X509_NAME)
2215 
2216 IMPLEMENT_STACK_OF(X509_ATTRIBUTE)
2217 IMPLEMENT_ASN1_SET_OF(X509_ATTRIBUTE)
2218