xref: /openbsd-src/lib/libcrypto/x509/x509_vfy.c (revision 3374c67d44f9b75b98444cbf63020f777792342e)
1 /* $OpenBSD: x509_vfy.c,v 1.110 2022/12/26 07:18:53 jmc 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_local.h"
77 #include "vpm_int.h"
78 #include "x509_internal.h"
79 
80 /* CRL score values */
81 
82 /* No unhandled critical extensions */
83 
84 #define CRL_SCORE_NOCRITICAL	0x100
85 
86 /* certificate is within CRL scope */
87 
88 #define CRL_SCORE_SCOPE		0x080
89 
90 /* CRL times valid */
91 
92 #define CRL_SCORE_TIME		0x040
93 
94 /* Issuer name matches certificate */
95 
96 #define CRL_SCORE_ISSUER_NAME	0x020
97 
98 /* If this score or above CRL is probably valid */
99 
100 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
101 
102 /* CRL issuer is certificate issuer */
103 
104 #define CRL_SCORE_ISSUER_CERT	0x018
105 
106 /* CRL issuer is on certificate path */
107 
108 #define CRL_SCORE_SAME_PATH	0x008
109 
110 /* CRL issuer matches CRL AKID */
111 
112 #define CRL_SCORE_AKID		0x004
113 
114 /* Have a delta CRL with valid times */
115 
116 #define CRL_SCORE_TIME_DELTA	0x002
117 
118 static int null_callback(int ok, X509_STORE_CTX *e);
119 static int check_issued(X509_STORE_CTX *ctx, X509 *subject, X509 *issuer);
120 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x,
121     int allow_expired);
122 static int check_chain_extensions(X509_STORE_CTX *ctx);
123 static int check_name_constraints(X509_STORE_CTX *ctx);
124 static int check_trust(X509_STORE_CTX *ctx);
125 static int check_revocation(X509_STORE_CTX *ctx);
126 static int check_cert(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, int depth);
127 static int check_policy(X509_STORE_CTX *ctx);
128 
129 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
130     unsigned int *preasons, X509_CRL *crl, X509 *x);
131 static int get_crl_delta(X509_STORE_CTX *ctx,
132     X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
133 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pcrl_score,
134     X509_CRL *base, STACK_OF(X509_CRL) *crls);
135 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
136     int *pcrl_score);
137 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
138     unsigned int *preasons);
139 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
140 static int check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
141     STACK_OF(X509) *crl_path);
142 static int X509_cmp_time_internal(const ASN1_TIME *ctm, time_t *cmp_time,
143     int clamp_notafter);
144 
145 static int internal_verify(X509_STORE_CTX *ctx);
146 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
147 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert);
148 static int verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err);
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 	int 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->num_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 satisfy 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->num_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->num_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->num_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->num_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->num_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->num_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 that the chain satisfies the security level. */
548 	ok = x509_vfy_check_security_level(ctx);
549 	if (!ok)
550 		goto end;
551 
552 	/* Check name constraints */
553 	ok = check_name_constraints(ctx);
554 	if (!ok)
555 		goto end;
556 
557 #ifndef OPENSSL_NO_RFC3779
558 	ok = X509v3_asid_validate_path(ctx);
559 	if (!ok)
560 		goto end;
561 
562 	ok = X509v3_addr_validate_path(ctx);
563 	if (!ok)
564 		goto end;
565 #endif
566 
567 	ok = check_id(ctx);
568 	if (!ok)
569 		goto end;
570 
571 	/*
572 	 * Check revocation status: we do this after copying parameters because
573 	 * they may be needed for CRL signature verification.
574 	 */
575 	ok = ctx->check_revocation(ctx);
576 	if (!ok)
577 		goto end;
578 
579 	/* At this point, we have a chain and need to verify it */
580 	if (ctx->verify != NULL)
581 		ok = ctx->verify(ctx);
582 	else
583 		ok = internal_verify(ctx);
584 	if (!ok)
585 		goto end;
586 
587 	/* If we get this far evaluate policies */
588 	if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
589 		ok = ctx->check_policy(ctx);
590 
591  end:
592 	/* Safety net, error returns must set ctx->error */
593 	if (ok <= 0 && ctx->error == X509_V_OK)
594 		ctx->error = X509_V_ERR_UNSPECIFIED;
595 
596 	return ok;
597 }
598 
599 int
600 X509_verify_cert(X509_STORE_CTX *ctx)
601 {
602 	STACK_OF(X509) *roots = NULL;
603 	struct x509_verify_ctx *vctx = NULL;
604 	int chain_count = 0;
605 
606 	if (ctx->cert == NULL) {
607 		X509error(X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
608 		ctx->error = X509_V_ERR_INVALID_CALL;
609 		return -1;
610 	}
611 	if (ctx->chain != NULL) {
612 		/*
613 		 * This X509_STORE_CTX has already been used to verify
614 		 * a cert. We cannot do another one.
615 		 */
616 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
617 		ctx->error = X509_V_ERR_INVALID_CALL;
618 		return -1;
619 	}
620 	if (ctx->param->id->poisoned) {
621 		/*
622 		 * This X509_STORE_CTX had failures setting
623 		 * up verify parameters. We can not use it.
624 		 */
625 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
626 		ctx->error = X509_V_ERR_INVALID_CALL;
627 		return -1;
628 	}
629 	if (ctx->error != X509_V_ERR_INVALID_CALL) {
630 		/*
631 		 * This X509_STORE_CTX has not been properly initialized.
632 		 */
633 		X509error(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
634 		ctx->error = X509_V_ERR_INVALID_CALL;
635 		return -1;
636 	}
637 
638 	/*
639 	 * If the certificate's public key is too weak, don't bother
640 	 * continuing.
641 	 */
642 	if (!check_key_level(ctx, ctx->cert) &&
643 	    !verify_cb_cert(ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL))
644 		return 0;
645 
646 	/*
647 	 * If flags request legacy, use the legacy verifier. If we
648 	 * requested "no alt chains" from the age of hammer pants, use
649 	 * the legacy verifier because the multi chain verifier really
650 	 * does find all the "alt chains".
651 	 *
652 	 * XXX deprecate the NO_ALT_CHAINS flag?
653 	 */
654 	if ((ctx->param->flags & X509_V_FLAG_LEGACY_VERIFY) ||
655 	    (ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
656 		return X509_verify_cert_legacy(ctx);
657 
658 	/* Use the modern multi-chain verifier from x509_verify_cert */
659 
660 	if ((vctx = x509_verify_ctx_new_from_xsc(ctx)) != NULL) {
661 		ctx->error = X509_V_OK; /* Initialize to OK */
662 		chain_count = x509_verify(vctx, NULL, NULL);
663 	}
664 	x509_verify_ctx_free(vctx);
665 
666 	sk_X509_pop_free(roots, X509_free);
667 
668 	/* if we succeed we have a chain in ctx->chain */
669 	return (chain_count > 0 && ctx->chain != NULL);
670 }
671 LCRYPTO_ALIAS(X509_verify_cert)
672 
673 /* Given a STACK_OF(X509) find the issuer of cert (if any)
674  */
675 
676 static X509 *
677 find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x,
678     int allow_expired)
679 {
680 	int i;
681 	X509 *issuer, *rv = NULL;
682 
683 	for (i = 0; i < sk_X509_num(sk); i++) {
684 		issuer = sk_X509_value(sk, i);
685 		if (ctx->check_issued(ctx, x, issuer)) {
686 			if (x509_check_cert_time(ctx, issuer, -1))
687 				return issuer;
688 			if (allow_expired)
689 				rv = issuer;
690 		}
691 	}
692 	return rv;
693 }
694 
695 /* Given a possible certificate and issuer check them */
696 
697 static int
698 check_issued(X509_STORE_CTX *ctx, X509 *subject, X509 *issuer)
699 {
700 	/*
701 	 * Yes, the arguments of X509_STORE_CTX_check_issued_fn were exposed in
702 	 * reverse order compared to the already public X509_check_issued()...
703 	 */
704 	return X509_check_issued(issuer, subject) == X509_V_OK;
705 }
706 
707 /* Alternative lookup method: look from a STACK stored in other_ctx */
708 
709 static int
710 get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
711 {
712 	*issuer = find_issuer(ctx, ctx->other_ctx, x, 1);
713 	if (*issuer) {
714 		CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
715 		return 1;
716 	} else
717 		return 0;
718 }
719 
720 /* Check a certificate chains extensions for consistency
721  * with the supplied purpose
722  */
723 
724 int
725 x509_vfy_check_chain_extensions(X509_STORE_CTX *ctx)
726 {
727 #ifdef OPENSSL_NO_CHAIN_VERIFY
728 	return 1;
729 #else
730 	int i, ok = 0, must_be_ca, plen = 0;
731 	X509 *x;
732 	int (*cb)(int xok, X509_STORE_CTX *xctx);
733 	int proxy_path_length = 0;
734 	int purpose;
735 	int allow_proxy_certs;
736 
737 	cb = ctx->verify_cb;
738 
739 	/* must_be_ca can have 1 of 3 values:
740 	   -1: we accept both CA and non-CA certificates, to allow direct
741 	       use of self-signed certificates (which are marked as CA).
742 	   0:  we only accept non-CA certificates.  This is currently not
743 	       used, but the possibility is present for future extensions.
744 	   1:  we only accept CA certificates.  This is currently used for
745 	       all certificates in the chain except the leaf certificate.
746 	*/
747 	must_be_ca = -1;
748 
749 	/* CRL path validation */
750 	if (ctx->parent) {
751 		allow_proxy_certs = 0;
752 		purpose = X509_PURPOSE_CRL_SIGN;
753 	} else {
754 		allow_proxy_certs =
755 		    !!(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
756 		purpose = ctx->param->purpose;
757 	}
758 
759 	/* Check all untrusted certificates */
760 	for (i = 0; i < ctx->num_untrusted; i++) {
761 		int ret;
762 		x = sk_X509_value(ctx->chain, i);
763 		if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
764 		    (x->ex_flags & EXFLAG_CRITICAL)) {
765 			ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
766 			ctx->error_depth = i;
767 			ctx->current_cert = x;
768 			ok = cb(0, ctx);
769 			if (!ok)
770 				goto end;
771 		}
772 		if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
773 			ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
774 			ctx->error_depth = i;
775 			ctx->current_cert = x;
776 			ok = cb(0, ctx);
777 			if (!ok)
778 				goto end;
779 		}
780 		ret = X509_check_ca(x);
781 		switch (must_be_ca) {
782 		case -1:
783 			if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
784 			    (ret != 1) && (ret != 0)) {
785 				ret = 0;
786 				ctx->error = X509_V_ERR_INVALID_CA;
787 			} else
788 				ret = 1;
789 			break;
790 		case 0:
791 			if (ret != 0) {
792 				ret = 0;
793 				ctx->error = X509_V_ERR_INVALID_NON_CA;
794 			} else
795 				ret = 1;
796 			break;
797 		default:
798 			if ((ret == 0) ||
799 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
800 			    (ret != 1))) {
801 				ret = 0;
802 				ctx->error = X509_V_ERR_INVALID_CA;
803 			} else
804 				ret = 1;
805 			break;
806 		}
807 		if (ret == 0) {
808 			ctx->error_depth = i;
809 			ctx->current_cert = x;
810 			ok = cb(0, ctx);
811 			if (!ok)
812 				goto end;
813 		}
814 		if (ctx->param->purpose > 0) {
815 			ret = X509_check_purpose(x, purpose, must_be_ca > 0);
816 			if ((ret == 0) ||
817 			    ((ctx->param->flags & X509_V_FLAG_X509_STRICT) &&
818 			    (ret != 1))) {
819 				ctx->error = X509_V_ERR_INVALID_PURPOSE;
820 				ctx->error_depth = i;
821 				ctx->current_cert = x;
822 				ok = cb(0, ctx);
823 				if (!ok)
824 					goto end;
825 			}
826 		}
827 		/* Check pathlen if not self issued */
828 		if ((i > 1) && !(x->ex_flags & EXFLAG_SI) &&
829 		    (x->ex_pathlen != -1) &&
830 		    (plen > (x->ex_pathlen + proxy_path_length + 1))) {
831 			ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
832 			ctx->error_depth = i;
833 			ctx->current_cert = x;
834 			ok = cb(0, ctx);
835 			if (!ok)
836 				goto end;
837 		}
838 		/* Increment path length if not self issued */
839 		if (!(x->ex_flags & EXFLAG_SI))
840 			plen++;
841 		/* If this certificate is a proxy certificate, the next
842 		   certificate must be another proxy certificate or a EE
843 		   certificate.  If not, the next certificate must be a
844 		   CA certificate.  */
845 		if (x->ex_flags & EXFLAG_PROXY) {
846 			if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
847 				ctx->error =
848 				    X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
849 				ctx->error_depth = i;
850 				ctx->current_cert = x;
851 				ok = cb(0, ctx);
852 				if (!ok)
853 					goto end;
854 			}
855 			proxy_path_length++;
856 			must_be_ca = 0;
857 		} else
858 			must_be_ca = 1;
859 	}
860 	ok = 1;
861 
862 end:
863 	return ok;
864 #endif
865 }
866 
867 static int
868 check_chain_extensions(X509_STORE_CTX *ctx) {
869 	return x509_vfy_check_chain_extensions(ctx);
870 }
871 
872 static int
873 check_name_constraints(X509_STORE_CTX *ctx)
874 {
875 	if (!x509_constraints_chain(ctx->chain, &ctx->error,
876 	    &ctx->error_depth)) {
877 		ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth);
878 		if (!ctx->verify_cb(0, ctx))
879 			return 0;
880 	}
881 	return 1;
882 }
883 
884 /* Given a certificate try and find an exact match in the store */
885 
886 static X509 *
887 lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
888 {
889 	STACK_OF(X509) *certs;
890 	X509 *xtmp = NULL;
891 	size_t i;
892 
893 	/* Lookup all certs with matching subject name */
894 	certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
895 	if (certs == NULL)
896 		return NULL;
897 
898 	/* Look for exact match */
899 	for (i = 0; i < sk_X509_num(certs); i++) {
900 		xtmp = sk_X509_value(certs, i);
901 		if (!X509_cmp(xtmp, x))
902 			break;
903 	}
904 
905 	if (i < sk_X509_num(certs))
906 		X509_up_ref(xtmp);
907 	else
908 		xtmp = NULL;
909 
910 	sk_X509_pop_free(certs, X509_free);
911 	return xtmp;
912 }
913 
914 X509 *
915 x509_vfy_lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
916 {
917 	if (ctx->lookup_certs == NULL || ctx->store == NULL ||
918 	    ctx->store->objs == NULL)
919 		return NULL;
920 	return lookup_cert_match(ctx, x);
921 }
922 
923 static int
924 check_trust(X509_STORE_CTX *ctx)
925 {
926 	size_t i;
927 	int ok;
928 	X509 *x = NULL;
929 	int (*cb) (int xok, X509_STORE_CTX *xctx);
930 
931 	cb = ctx->verify_cb;
932 	/* Check all trusted certificates in chain */
933 	for (i = ctx->num_untrusted; i < sk_X509_num(ctx->chain); i++) {
934 		x = sk_X509_value(ctx->chain, i);
935 		ok = X509_check_trust(x, ctx->param->trust, 0);
936 
937 		/* If explicitly trusted return trusted */
938 		if (ok == X509_TRUST_TRUSTED)
939 			return X509_TRUST_TRUSTED;
940 		/*
941 		 * If explicitly rejected notify callback and reject if not
942 		 * overridden.
943 		 */
944 		if (ok == X509_TRUST_REJECTED) {
945 			ctx->error_depth = i;
946 			ctx->current_cert = x;
947 			ctx->error = X509_V_ERR_CERT_REJECTED;
948 			ok = cb(0, ctx);
949 			if (!ok)
950 				return X509_TRUST_REJECTED;
951 		}
952 	}
953 	/*
954 	 * If we accept partial chains and have at least one trusted certificate
955 	 * return success.
956 	 */
957 	if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
958 		X509 *mx;
959 		if (ctx->num_untrusted < (int)sk_X509_num(ctx->chain))
960 			return X509_TRUST_TRUSTED;
961 		x = sk_X509_value(ctx->chain, 0);
962 		mx = lookup_cert_match(ctx, x);
963 		if (mx) {
964 			(void)sk_X509_set(ctx->chain, 0, mx);
965 			X509_free(x);
966 			ctx->num_untrusted = 0;
967 			return X509_TRUST_TRUSTED;
968 		}
969 	}
970 
971 	/*
972 	 * If no trusted certs in chain at all return untrusted and allow
973 	 * standard (no issuer cert) etc errors to be indicated.
974 	 */
975 	return X509_TRUST_UNTRUSTED;
976 }
977 
978 int
979 x509_vfy_check_trust(X509_STORE_CTX *ctx)
980 {
981 	return check_trust(ctx);
982 }
983 
984 static int
985 check_revocation(X509_STORE_CTX *ctx)
986 {
987 	int i, last, ok;
988 
989 	if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
990 		return 1;
991 	if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
992 		last = sk_X509_num(ctx->chain) - 1;
993 	else {
994 		/* If checking CRL paths this isn't the EE certificate */
995 		if (ctx->parent)
996 			return 1;
997 		last = 0;
998 	}
999 	for (i = 0; i <= last; i++) {
1000 		ok = check_cert(ctx, ctx->chain, i);
1001 		if (!ok)
1002 			return ok;
1003 	}
1004 	return 1;
1005 }
1006 
1007 int
1008 x509_vfy_check_revocation(X509_STORE_CTX *ctx)
1009 {
1010 	return check_revocation(ctx);
1011 }
1012 
1013 static int
1014 check_cert(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, int depth)
1015 {
1016 	X509_CRL *crl = NULL, *dcrl = NULL;
1017 	X509 *x;
1018 	int ok = 0, cnum;
1019 	unsigned int last_reasons;
1020 
1021 	cnum = ctx->error_depth = depth;
1022 	x = sk_X509_value(chain, cnum);
1023 	ctx->current_cert = x;
1024 	ctx->current_issuer = NULL;
1025 	ctx->current_crl_score = 0;
1026 	ctx->current_reasons = 0;
1027 	while (ctx->current_reasons != CRLDP_ALL_REASONS) {
1028 		last_reasons = ctx->current_reasons;
1029 		/* Try to retrieve relevant CRL */
1030 		if (ctx->get_crl)
1031 			ok = ctx->get_crl(ctx, &crl, x);
1032 		else
1033 			ok = get_crl_delta(ctx, &crl, &dcrl, x);
1034 		/* If error looking up CRL, nothing we can do except
1035 		 * notify callback
1036 		 */
1037 		if (!ok) {
1038 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
1039 			ok = ctx->verify_cb(0, ctx);
1040 			goto err;
1041 		}
1042 		ctx->current_crl = crl;
1043 		ok = ctx->check_crl(ctx, crl);
1044 		if (!ok)
1045 			goto err;
1046 
1047 		if (dcrl) {
1048 			ok = ctx->check_crl(ctx, dcrl);
1049 			if (!ok)
1050 				goto err;
1051 			ok = ctx->cert_crl(ctx, dcrl, x);
1052 			if (!ok)
1053 				goto err;
1054 		} else
1055 			ok = 1;
1056 
1057 		/* Don't look in full CRL if delta reason is removefromCRL */
1058 		if (ok != 2) {
1059 			ok = ctx->cert_crl(ctx, crl, x);
1060 			if (!ok)
1061 				goto err;
1062 		}
1063 
1064 		ctx->current_crl = NULL;
1065 		X509_CRL_free(crl);
1066 		X509_CRL_free(dcrl);
1067 		crl = NULL;
1068 		dcrl = NULL;
1069 		/* If reasons not updated we wont get anywhere by
1070 		 * another iteration, so exit loop.
1071 		 */
1072 		if (last_reasons == ctx->current_reasons) {
1073 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
1074 			ok = ctx->verify_cb(0, ctx);
1075 			goto err;
1076 		}
1077 	}
1078 
1079 err:
1080 	ctx->current_crl = NULL;
1081 	X509_CRL_free(crl);
1082 	X509_CRL_free(dcrl);
1083 	return ok;
1084 }
1085 
1086 /* Check CRL times against values in X509_STORE_CTX */
1087 
1088 static int
1089 check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
1090 {
1091 	time_t *ptime;
1092 	int i;
1093 
1094 	if (notify)
1095 		ctx->current_crl = crl;
1096 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1097 		ptime = &ctx->param->check_time;
1098 	else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1099 		return (1);
1100 	else
1101 		ptime = NULL;
1102 
1103 	i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
1104 	if (i == 0) {
1105 		if (!notify)
1106 			return 0;
1107 		ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
1108 		if (!ctx->verify_cb(0, ctx))
1109 			return 0;
1110 	}
1111 
1112 	if (i > 0) {
1113 		if (!notify)
1114 			return 0;
1115 		ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
1116 		if (!ctx->verify_cb(0, ctx))
1117 			return 0;
1118 	}
1119 
1120 	if (X509_CRL_get_nextUpdate(crl)) {
1121 		i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
1122 
1123 		if (i == 0) {
1124 			if (!notify)
1125 				return 0;
1126 			ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
1127 			if (!ctx->verify_cb(0, ctx))
1128 				return 0;
1129 		}
1130 		/* Ignore expiry of base CRL is delta is valid */
1131 		if ((i < 0) &&
1132 		    !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
1133 			if (!notify)
1134 				return 0;
1135 			ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
1136 			if (!ctx->verify_cb(0, ctx))
1137 				return 0;
1138 		}
1139 	}
1140 
1141 	if (notify)
1142 		ctx->current_crl = NULL;
1143 
1144 	return 1;
1145 }
1146 
1147 static int
1148 get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1149     X509 **pissuer, int *pscore, unsigned int *preasons,
1150     STACK_OF(X509_CRL) *crls)
1151 {
1152 	int i, crl_score, best_score = *pscore;
1153 	unsigned int reasons, best_reasons = 0;
1154 	X509 *x = ctx->current_cert;
1155 	X509_CRL *crl, *best_crl = NULL;
1156 	X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1157 
1158 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1159 		crl = sk_X509_CRL_value(crls, i);
1160 		reasons = *preasons;
1161 		crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1162 
1163 		if (crl_score > best_score) {
1164 			best_crl = crl;
1165 			best_crl_issuer = crl_issuer;
1166 			best_score = crl_score;
1167 			best_reasons = reasons;
1168 		}
1169 	}
1170 
1171 	if (best_crl) {
1172 		if (*pcrl)
1173 			X509_CRL_free(*pcrl);
1174 		*pcrl = best_crl;
1175 		*pissuer = best_crl_issuer;
1176 		*pscore = best_score;
1177 		*preasons = best_reasons;
1178 		CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
1179 		if (*pdcrl) {
1180 			X509_CRL_free(*pdcrl);
1181 			*pdcrl = NULL;
1182 		}
1183 		get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1184 	}
1185 
1186 	if (best_score >= CRL_SCORE_VALID)
1187 		return 1;
1188 
1189 	return 0;
1190 }
1191 
1192 /* Compare two CRL extensions for delta checking purposes. They should be
1193  * both present or both absent. If both present all fields must be identical.
1194  */
1195 
1196 static int
1197 crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1198 {
1199 	ASN1_OCTET_STRING *exta, *extb;
1200 	int i;
1201 
1202 	i = X509_CRL_get_ext_by_NID(a, nid, -1);
1203 	if (i >= 0) {
1204 		/* Can't have multiple occurrences */
1205 		if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1206 			return 0;
1207 		exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1208 	} else
1209 		exta = NULL;
1210 
1211 	i = X509_CRL_get_ext_by_NID(b, nid, -1);
1212 
1213 	if (i >= 0) {
1214 		if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1215 			return 0;
1216 		extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1217 	} else
1218 		extb = NULL;
1219 
1220 	if (!exta && !extb)
1221 		return 1;
1222 
1223 	if (!exta || !extb)
1224 		return 0;
1225 
1226 	if (ASN1_OCTET_STRING_cmp(exta, extb))
1227 		return 0;
1228 
1229 	return 1;
1230 }
1231 
1232 /* See if a base and delta are compatible */
1233 
1234 static int
1235 check_delta_base(X509_CRL *delta, X509_CRL *base)
1236 {
1237 	/* Delta CRL must be a delta */
1238 	if (!delta->base_crl_number)
1239 		return 0;
1240 	/* Base must have a CRL number */
1241 	if (!base->crl_number)
1242 		return 0;
1243 	/* Issuer names must match */
1244 	if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1245 	    X509_CRL_get_issuer(delta)))
1246 		return 0;
1247 	/* AKID and IDP must match */
1248 	if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1249 		return 0;
1250 	if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1251 		return 0;
1252 	/* Delta CRL base number must not exceed Full CRL number. */
1253 	if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1254 		return 0;
1255 	/* Delta CRL number must exceed full CRL number */
1256 	if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
1257 		return 1;
1258 	return 0;
1259 }
1260 
1261 /* For a given base CRL find a delta... maybe extend to delta scoring
1262  * or retrieve a chain of deltas...
1263  */
1264 
1265 static void
1266 get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore, X509_CRL *base,
1267     STACK_OF(X509_CRL) *crls)
1268 {
1269 	X509_CRL *delta;
1270 	int i;
1271 
1272 	if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
1273 		return;
1274 	if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
1275 		return;
1276 	for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1277 		delta = sk_X509_CRL_value(crls, i);
1278 		if (check_delta_base(delta, base)) {
1279 			if (check_crl_time(ctx, delta, 0))
1280 				*pscore |= CRL_SCORE_TIME_DELTA;
1281 			CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL);
1282 			*dcrl = delta;
1283 			return;
1284 		}
1285 	}
1286 	*dcrl = NULL;
1287 }
1288 
1289 /* For a given CRL return how suitable it is for the supplied certificate 'x'.
1290  * The return value is a mask of several criteria.
1291  * If the issuer is not the certificate issuer this is returned in *pissuer.
1292  * The reasons mask is also used to determine if the CRL is suitable: if
1293  * no new reasons the CRL is rejected, otherwise reasons is updated.
1294  */
1295 
1296 static int
1297 get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer, unsigned int *preasons,
1298     X509_CRL *crl, X509 *x)
1299 {
1300 	int crl_score = 0;
1301 	unsigned int tmp_reasons = *preasons, crl_reasons;
1302 
1303 	/* First see if we can reject CRL straight away */
1304 
1305 	/* Invalid IDP cannot be processed */
1306 	if (crl->idp_flags & IDP_INVALID)
1307 		return 0;
1308 	/* Reason codes or indirect CRLs need extended CRL support */
1309 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1310 		if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1311 			return 0;
1312 	} else if (crl->idp_flags & IDP_REASONS) {
1313 		/* If no new reasons reject */
1314 		if (!(crl->idp_reasons & ~tmp_reasons))
1315 			return 0;
1316 	}
1317 	/* Don't process deltas at this stage */
1318 	else if (crl->base_crl_number)
1319 		return 0;
1320 	/* If issuer name doesn't match certificate need indirect CRL */
1321 	if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1322 		if (!(crl->idp_flags & IDP_INDIRECT))
1323 			return 0;
1324 	} else
1325 		crl_score |= CRL_SCORE_ISSUER_NAME;
1326 
1327 	if (!(crl->flags & EXFLAG_CRITICAL))
1328 		crl_score |= CRL_SCORE_NOCRITICAL;
1329 
1330 	/* Check expiry */
1331 	if (check_crl_time(ctx, crl, 0))
1332 		crl_score |= CRL_SCORE_TIME;
1333 
1334 	/* Check authority key ID and locate certificate issuer */
1335 	crl_akid_check(ctx, crl, pissuer, &crl_score);
1336 
1337 	/* If we can't locate certificate issuer at this point forget it */
1338 
1339 	if (!(crl_score & CRL_SCORE_AKID))
1340 		return 0;
1341 
1342 	/* Check cert for matching CRL distribution points */
1343 
1344 	if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1345 		/* If no new reasons reject */
1346 		if (!(crl_reasons & ~tmp_reasons))
1347 			return 0;
1348 		tmp_reasons |= crl_reasons;
1349 		crl_score |= CRL_SCORE_SCOPE;
1350 	}
1351 
1352 	*preasons = tmp_reasons;
1353 
1354 	return crl_score;
1355 }
1356 
1357 static void
1358 crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
1359     int *pcrl_score)
1360 {
1361 	X509 *crl_issuer = NULL;
1362 	X509_NAME *cnm = X509_CRL_get_issuer(crl);
1363 	int cidx = ctx->error_depth;
1364 	int i;
1365 
1366 	if (cidx != sk_X509_num(ctx->chain) - 1)
1367 		cidx++;
1368 
1369 	crl_issuer = sk_X509_value(ctx->chain, cidx);
1370 
1371 	if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1372 		if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1373 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_ISSUER_CERT;
1374 			*pissuer = crl_issuer;
1375 			return;
1376 		}
1377 	}
1378 
1379 	for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1380 		crl_issuer = sk_X509_value(ctx->chain, cidx);
1381 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1382 			continue;
1383 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1384 			*pcrl_score |= CRL_SCORE_AKID|CRL_SCORE_SAME_PATH;
1385 			*pissuer = crl_issuer;
1386 			return;
1387 		}
1388 	}
1389 
1390 	/* Anything else needs extended CRL support */
1391 
1392 	if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1393 		return;
1394 
1395 	/* Otherwise the CRL issuer is not on the path. Look for it in the
1396 	 * set of untrusted certificates.
1397 	 */
1398 	for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1399 		crl_issuer = sk_X509_value(ctx->untrusted, i);
1400 		if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1401 			continue;
1402 		if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1403 			*pissuer = crl_issuer;
1404 			*pcrl_score |= CRL_SCORE_AKID;
1405 			return;
1406 		}
1407 	}
1408 }
1409 
1410 /* Check the path of a CRL issuer certificate. This creates a new
1411  * X509_STORE_CTX and populates it with most of the parameters from the
1412  * parent. This could be optimised somewhat since a lot of path checking
1413  * will be duplicated by the parent, but this will rarely be used in
1414  * practice.
1415  */
1416 
1417 static int
1418 check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1419 {
1420 	X509_STORE_CTX crl_ctx;
1421 	int ret;
1422 
1423 	/* Don't allow recursive CRL path validation */
1424 	if (ctx->parent)
1425 		return 0;
1426 	if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted)) {
1427 		ret = -1;
1428 		goto err;
1429 	}
1430 
1431 	crl_ctx.crls = ctx->crls;
1432 	/* Copy verify params across */
1433 	X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1434 
1435 	crl_ctx.parent = ctx;
1436 	crl_ctx.verify_cb = ctx->verify_cb;
1437 
1438 	/* Verify CRL issuer */
1439 	ret = X509_verify_cert(&crl_ctx);
1440 
1441 	if (ret <= 0)
1442 		goto err;
1443 
1444 	/* Check chain is acceptable */
1445 	ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1446 
1447 err:
1448 	X509_STORE_CTX_cleanup(&crl_ctx);
1449 	return ret;
1450 }
1451 
1452 /* RFC3280 says nothing about the relationship between CRL path
1453  * and certificate path, which could lead to situations where a
1454  * certificate could be revoked or validated by a CA not authorised
1455  * to do so. RFC5280 is more strict and states that the two paths must
1456  * end in the same trust anchor, though some discussions remain...
1457  * until this is resolved we use the RFC5280 version
1458  */
1459 
1460 static int
1461 check_crl_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *cert_path,
1462     STACK_OF(X509) *crl_path)
1463 {
1464 	X509 *cert_ta, *crl_ta;
1465 
1466 	cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1467 	crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1468 	if (!X509_cmp(cert_ta, crl_ta))
1469 		return 1;
1470 	return 0;
1471 }
1472 
1473 /* Check for match between two dist point names: three separate cases.
1474  * 1. Both are relative names and compare X509_NAME types.
1475  * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1476  * 3. Both are full names and compare two GENERAL_NAMES.
1477  * 4. One is NULL: automatic match.
1478  */
1479 
1480 static int
1481 idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1482 {
1483 	X509_NAME *nm = NULL;
1484 	GENERAL_NAMES *gens = NULL;
1485 	GENERAL_NAME *gena, *genb;
1486 	int i, j;
1487 
1488 	if (!a || !b)
1489 		return 1;
1490 	if (a->type == 1) {
1491 		if (!a->dpname)
1492 			return 0;
1493 		/* Case 1: two X509_NAME */
1494 		if (b->type == 1) {
1495 			if (!b->dpname)
1496 				return 0;
1497 			if (!X509_NAME_cmp(a->dpname, b->dpname))
1498 				return 1;
1499 			else
1500 				return 0;
1501 		}
1502 		/* Case 2: set name and GENERAL_NAMES appropriately */
1503 		nm = a->dpname;
1504 		gens = b->name.fullname;
1505 	} else if (b->type == 1) {
1506 		if (!b->dpname)
1507 			return 0;
1508 		/* Case 2: set name and GENERAL_NAMES appropriately */
1509 		gens = a->name.fullname;
1510 		nm = b->dpname;
1511 	}
1512 
1513 	/* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1514 	if (nm) {
1515 		for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1516 			gena = sk_GENERAL_NAME_value(gens, i);
1517 			if (gena->type != GEN_DIRNAME)
1518 				continue;
1519 			if (!X509_NAME_cmp(nm, gena->d.directoryName))
1520 				return 1;
1521 		}
1522 		return 0;
1523 	}
1524 
1525 	/* Else case 3: two GENERAL_NAMES */
1526 
1527 	for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1528 		gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1529 		for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1530 			genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1531 			if (!GENERAL_NAME_cmp(gena, genb))
1532 				return 1;
1533 		}
1534 	}
1535 
1536 	return 0;
1537 }
1538 
1539 static int
1540 crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1541 {
1542 	int i;
1543 	X509_NAME *nm = X509_CRL_get_issuer(crl);
1544 
1545 	/* If no CRLissuer return is successful iff don't need a match */
1546 	if (!dp->CRLissuer)
1547 		return !!(crl_score & CRL_SCORE_ISSUER_NAME);
1548 	for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1549 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1550 		if (gen->type != GEN_DIRNAME)
1551 			continue;
1552 		if (!X509_NAME_cmp(gen->d.directoryName, nm))
1553 			return 1;
1554 	}
1555 	return 0;
1556 }
1557 
1558 /* Check CRLDP and IDP */
1559 
1560 static int
1561 crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score, unsigned int *preasons)
1562 {
1563 	int i;
1564 
1565 	if (crl->idp_flags & IDP_ONLYATTR)
1566 		return 0;
1567 	if (x->ex_flags & EXFLAG_CA) {
1568 		if (crl->idp_flags & IDP_ONLYUSER)
1569 			return 0;
1570 	} else {
1571 		if (crl->idp_flags & IDP_ONLYCA)
1572 			return 0;
1573 	}
1574 	*preasons = crl->idp_reasons;
1575 	for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1576 		DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1577 		if (crldp_check_crlissuer(dp, crl, crl_score)) {
1578 			if (!crl->idp ||
1579 			    idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1580 				*preasons &= dp->dp_reasons;
1581 				return 1;
1582 			}
1583 		}
1584 	}
1585 	if ((!crl->idp || !crl->idp->distpoint) &&
1586 	    (crl_score & CRL_SCORE_ISSUER_NAME))
1587 		return 1;
1588 	return 0;
1589 }
1590 
1591 /* Retrieve CRL corresponding to current certificate.
1592  * If deltas enabled try to find a delta CRL too
1593  */
1594 
1595 static int
1596 get_crl_delta(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1597 {
1598 	int ok;
1599 	X509 *issuer = NULL;
1600 	int crl_score = 0;
1601 	unsigned int reasons;
1602 	X509_CRL *crl = NULL, *dcrl = NULL;
1603 	STACK_OF(X509_CRL) *skcrl;
1604 	X509_NAME *nm = X509_get_issuer_name(x);
1605 
1606 	reasons = ctx->current_reasons;
1607 	ok = get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons,
1608 	    ctx->crls);
1609 	if (ok)
1610 		goto done;
1611 
1612 	/* Lookup CRLs from store */
1613 	skcrl = ctx->lookup_crls(ctx, nm);
1614 
1615 	/* If no CRLs found and a near match from get_crl_sk use that */
1616 	if (!skcrl && crl)
1617 		goto done;
1618 
1619 	get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1620 
1621 	sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1622 
1623 done:
1624 
1625 	/* If we got any kind of CRL use it and return success */
1626 	if (crl) {
1627 		ctx->current_issuer = issuer;
1628 		ctx->current_crl_score = crl_score;
1629 		ctx->current_reasons = reasons;
1630 		*pcrl = crl;
1631 		*pdcrl = dcrl;
1632 		return 1;
1633 	}
1634 
1635 	return 0;
1636 }
1637 
1638 /* Check CRL validity */
1639 static int
1640 check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1641 {
1642 	X509 *issuer = NULL;
1643 	EVP_PKEY *ikey = NULL;
1644 	int ok = 0, chnum, cnum;
1645 
1646 	cnum = ctx->error_depth;
1647 	chnum = sk_X509_num(ctx->chain) - 1;
1648 	/* if we have an alternative CRL issuer cert use that */
1649 	if (ctx->current_issuer) {
1650 		issuer = ctx->current_issuer;
1651 	} else if (cnum < chnum) {
1652 		/*
1653 		 * Else find CRL issuer: if not last certificate then issuer
1654 		 * is next certificate in chain.
1655 		 */
1656 		issuer = sk_X509_value(ctx->chain, cnum + 1);
1657 	} else {
1658 		issuer = sk_X509_value(ctx->chain, chnum);
1659 		/* If not self signed, can't check signature */
1660 		if (!ctx->check_issued(ctx, issuer, issuer)) {
1661 			ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1662 			ok = ctx->verify_cb(0, ctx);
1663 			if (!ok)
1664 				goto err;
1665 		}
1666 	}
1667 
1668 	if (issuer) {
1669 		/* Skip most tests for deltas because they have already
1670 		 * been done
1671 		 */
1672 		if (!crl->base_crl_number) {
1673 			/* Check for cRLSign bit if keyUsage present */
1674 			if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1675 			    !(issuer->ex_kusage & KU_CRL_SIGN)) {
1676 				ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1677 				ok = ctx->verify_cb(0, ctx);
1678 				if (!ok)
1679 					goto err;
1680 			}
1681 
1682 			if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1683 				ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1684 				ok = ctx->verify_cb(0, ctx);
1685 				if (!ok)
1686 					goto err;
1687 			}
1688 
1689 			if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1690 				if (check_crl_path(ctx,
1691 				    ctx->current_issuer) <= 0) {
1692 					ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1693 					ok = ctx->verify_cb(0, ctx);
1694 					if (!ok)
1695 						goto err;
1696 				}
1697 			}
1698 
1699 			if (crl->idp_flags & IDP_INVALID) {
1700 				ctx->error = X509_V_ERR_INVALID_EXTENSION;
1701 				ok = ctx->verify_cb(0, ctx);
1702 				if (!ok)
1703 					goto err;
1704 			}
1705 
1706 
1707 		}
1708 
1709 		if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1710 			ok = check_crl_time(ctx, crl, 1);
1711 			if (!ok)
1712 				goto err;
1713 		}
1714 
1715 		/* Attempt to get issuer certificate public key */
1716 		ikey = X509_get_pubkey(issuer);
1717 
1718 		if (!ikey) {
1719 			ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1720 			ok = ctx->verify_cb(0, ctx);
1721 			if (!ok)
1722 				goto err;
1723 		} else {
1724 			/* Verify CRL signature */
1725 			if (X509_CRL_verify(crl, ikey) <= 0) {
1726 				ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1727 				ok = ctx->verify_cb(0, ctx);
1728 				if (!ok)
1729 					goto err;
1730 			}
1731 		}
1732 	}
1733 
1734 	ok = 1;
1735 
1736 err:
1737 	EVP_PKEY_free(ikey);
1738 	return ok;
1739 }
1740 
1741 /* Check certificate against CRL */
1742 static int
1743 cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1744 {
1745 	int ok;
1746 	X509_REVOKED *rev;
1747 
1748 	/* The rules changed for this... previously if a CRL contained
1749 	 * unhandled critical extensions it could still be used to indicate
1750 	 * a certificate was revoked. This has since been changed since
1751 	 * critical extension can change the meaning of CRL entries.
1752 	 */
1753 	if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) &&
1754 	    (crl->flags & EXFLAG_CRITICAL)) {
1755 		ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1756 		ok = ctx->verify_cb(0, ctx);
1757 		if (!ok)
1758 			return 0;
1759 	}
1760 	/* Look for serial number of certificate in CRL
1761 	 * If found make sure reason is not removeFromCRL.
1762 	 */
1763 	if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1764 		if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1765 			return 2;
1766 		ctx->error = X509_V_ERR_CERT_REVOKED;
1767 		ok = ctx->verify_cb(0, ctx);
1768 		if (!ok)
1769 			return 0;
1770 	}
1771 
1772 	return 1;
1773 }
1774 
1775 int
1776 x509_vfy_check_policy(X509_STORE_CTX *ctx)
1777 {
1778 	int ret;
1779 
1780 	if (ctx->parent)
1781 		return 1;
1782 
1783 	/* X509_policy_check always allocates a new tree. */
1784 	X509_policy_tree_free(ctx->tree);
1785 	ctx->tree = NULL;
1786 
1787 	ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1788 	    ctx->param->policies, ctx->param->flags);
1789 	if (ret == 0) {
1790 		X509error(ERR_R_MALLOC_FAILURE);
1791 		return 0;
1792 	}
1793 	/* Invalid or inconsistent extensions */
1794 	if (ret == -1) {
1795 		/* Locate certificates with bad extensions and notify
1796 		 * callback.
1797 		 */
1798 		X509 *x;
1799 		int i;
1800 		for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1801 			x = sk_X509_value(ctx->chain, i);
1802 			if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1803 				continue;
1804 			ctx->current_cert = x;
1805 			ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1806 			if (!ctx->verify_cb(0, ctx))
1807 				return 0;
1808 		}
1809 		return 1;
1810 	}
1811 	if (ret == -2) {
1812 		ctx->current_cert = NULL;
1813 		ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1814 		return ctx->verify_cb(0, ctx);
1815 	}
1816 
1817 	if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1818 		ctx->current_cert = NULL;
1819 		ctx->error = X509_V_OK;
1820 		if (!ctx->verify_cb(2, ctx))
1821 			return 0;
1822 	}
1823 
1824 	return 1;
1825 }
1826 
1827 static int
1828 check_policy(X509_STORE_CTX *ctx)
1829 {
1830 	return x509_vfy_check_policy(ctx);
1831 }
1832 
1833 /*
1834  * Inform the verify callback of an error.
1835  *
1836  * If x is not NULL it is the error cert, otherwise use the chain cert
1837  * at depth.
1838  *
1839  * If err is not X509_V_OK, that's the error value, otherwise leave
1840  * unchanged (presumably set by the caller).
1841  *
1842  * Returns 0 to abort verification with an error, non-zero to continue.
1843  */
1844 static int
1845 verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err)
1846 {
1847 	ctx->error_depth = depth;
1848 	ctx->current_cert = (x != NULL) ? x : sk_X509_value(ctx->chain, depth);
1849 	if (err != X509_V_OK)
1850 		ctx->error = err;
1851 	return ctx->verify_cb(0, ctx);
1852 }
1853 
1854 
1855 /* Mimic OpenSSL '0 for failure' ick */
1856 static int
1857 time_t_bogocmp(time_t a, time_t b)
1858 {
1859 	if (a == -1 || b == -1)
1860 		return 0;
1861 	if (a <= b)
1862 		return -1;
1863 	return 1;
1864 }
1865 
1866 /*
1867  * Check certificate validity times.
1868  *
1869  * If depth >= 0, invoke verification callbacks on error, otherwise just return
1870  * the validation status.
1871  *
1872  * Return 1 on success, 0 otherwise.
1873  */
1874 int
1875 x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1876 {
1877 	time_t ptime;
1878 	int i;
1879 
1880 	if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1881 		ptime = ctx->param->check_time;
1882 	else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1883 		return 1;
1884 	else
1885 		ptime = time(NULL);
1886 
1887 	if (x->ex_flags & EXFLAG_SET)
1888 		i = time_t_bogocmp(x->not_before, ptime);
1889 	else
1890 		i = X509_cmp_time(X509_get_notBefore(x), &ptime);
1891 
1892 	if (i >= 0 && depth < 0)
1893 		return 0;
1894 	if (i == 0 && !verify_cb_cert(ctx, x, depth,
1895 	    X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD))
1896 		return 0;
1897 	if (i > 0 && !verify_cb_cert(ctx, x, depth,
1898 	    X509_V_ERR_CERT_NOT_YET_VALID))
1899 		return 0;
1900 
1901 	if (x->ex_flags & EXFLAG_SET)
1902 		i = time_t_bogocmp(x->not_after, ptime);
1903 	else
1904 		i = X509_cmp_time_internal(X509_get_notAfter(x), &ptime, 1);
1905 
1906 	if (i <= 0 && depth < 0)
1907 		return 0;
1908 	if (i == 0 && !verify_cb_cert(ctx, x, depth,
1909 	    X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD))
1910 		return 0;
1911 	if (i < 0 && !verify_cb_cert(ctx, x, depth,
1912 	    X509_V_ERR_CERT_HAS_EXPIRED))
1913 		return 0;
1914 
1915 	return 1;
1916 }
1917 
1918 static int
1919 x509_vfy_internal_verify(X509_STORE_CTX *ctx, int chain_verified)
1920 {
1921 	int n = sk_X509_num(ctx->chain) - 1;
1922 	X509 *xi = sk_X509_value(ctx->chain, n);
1923 	X509 *xs;
1924 
1925 	if (ctx->check_issued(ctx, xi, xi))
1926 		xs = xi;
1927 	else {
1928 		if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1929 			xs = xi;
1930 			goto check_cert;
1931 		}
1932 		if (n <= 0)
1933 			return verify_cb_cert(ctx, xi, 0,
1934 			    X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1935 		n--;
1936 		ctx->error_depth = n;
1937 		xs = sk_X509_value(ctx->chain, n);
1938 	}
1939 
1940 	/*
1941 	 * Do not clear ctx->error=0, it must be "sticky", only the
1942 	 * user's callback is allowed to reset errors (at its own
1943 	 * peril).
1944 	 */
1945 	while (n >= 0) {
1946 
1947 		/*
1948 		 * Skip signature check for self signed certificates
1949 		 * unless explicitly asked for.  It doesn't add any
1950 		 * security and just wastes time.  If the issuer's
1951 		 * public key is unusable, report the issuer
1952 		 * certificate and its depth (rather than the depth of
1953 		 * the subject).
1954 		 */
1955 		if (!chain_verified && ( xs != xi ||
1956 		    (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1957 			EVP_PKEY *pkey;
1958 			if ((pkey = X509_get_pubkey(xi)) == NULL) {
1959 				if (!verify_cb_cert(ctx, xi, xi != xs ? n+1 : n,
1960 				    X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1961 					return 0;
1962 			} else if (X509_verify(xs, pkey) <= 0) {
1963 				if (!verify_cb_cert(ctx, xs, n,
1964 				    X509_V_ERR_CERT_SIGNATURE_FAILURE)) {
1965 					EVP_PKEY_free(pkey);
1966 					return 0;
1967 				}
1968 			}
1969 			EVP_PKEY_free(pkey);
1970 		}
1971 check_cert:
1972 		/* Calls verify callback as needed */
1973 		if (!chain_verified && !x509_check_cert_time(ctx, xs, n))
1974 			return 0;
1975 
1976 		/*
1977 		 * Signal success at this depth.  However, the
1978 		 * previous error (if any) is retained.
1979 		 */
1980 		ctx->current_issuer = xi;
1981 		ctx->current_cert = xs;
1982 		ctx->error_depth = n;
1983 		if (!ctx->verify_cb(1, ctx))
1984 			return 0;
1985 
1986 		if (--n >= 0) {
1987 			xi = xs;
1988 			xs = sk_X509_value(ctx->chain, n);
1989 		}
1990 	}
1991 	return 1;
1992 }
1993 
1994 static int
1995 internal_verify(X509_STORE_CTX *ctx)
1996 {
1997 	return x509_vfy_internal_verify(ctx, 0);
1998 }
1999 
2000 /*
2001  * Internal verify, but with a chain where the verification
2002  * math has already been performed.
2003  */
2004 int
2005 x509_vfy_callback_indicate_completion(X509_STORE_CTX *ctx)
2006 {
2007 	return x509_vfy_internal_verify(ctx, 1);
2008 }
2009 
2010 int
2011 X509_cmp_current_time(const ASN1_TIME *ctm)
2012 {
2013 	return X509_cmp_time(ctm, NULL);
2014 }
2015 LCRYPTO_ALIAS(X509_cmp_current_time)
2016 
2017 /*
2018  * Compare a possibly unvalidated ASN1_TIME string against a time_t
2019  * using RFC 5280 rules for the time string. If *cmp_time is NULL
2020  * the current system time is used.
2021  *
2022  * XXX NOTE that unlike what you expect a "cmp" function to do in C,
2023  * XXX this one is "special", and returns 0 for error.
2024  *
2025  * Returns:
2026  * -1 if the ASN1_time is earlier than OR the same as *cmp_time.
2027  * 1 if the ASN1_time is later than *cmp_time.
2028  * 0 on error.
2029  */
2030 static int
2031 X509_cmp_time_internal(const ASN1_TIME *ctm, time_t *cmp_time, int is_notafter)
2032 {
2033 	time_t compare, cert_time;
2034 
2035 	if (cmp_time == NULL)
2036 		compare = time(NULL);
2037 	else
2038 		compare = *cmp_time;
2039 
2040 	if ((cert_time = x509_verify_asn1_time_to_time_t(ctm, is_notafter)) ==
2041 	    -1)
2042 		return 0; /* invalid time */
2043 
2044 	if (cert_time <= compare)
2045 		return -1; /* 0 is used for error, so map same to less than */
2046 
2047 	return 1;
2048 }
2049 
2050 int
2051 X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
2052 {
2053 	return X509_cmp_time_internal(ctm, cmp_time, 0);
2054 }
2055 LCRYPTO_ALIAS(X509_cmp_time)
2056 
2057 
2058 ASN1_TIME *
2059 X509_gmtime_adj(ASN1_TIME *s, long adj)
2060 {
2061 	return X509_time_adj(s, adj, NULL);
2062 }
2063 LCRYPTO_ALIAS(X509_gmtime_adj)
2064 
2065 ASN1_TIME *
2066 X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_time)
2067 {
2068 	return X509_time_adj_ex(s, 0, offset_sec, in_time);
2069 }
2070 LCRYPTO_ALIAS(X509_time_adj)
2071 
2072 ASN1_TIME *
2073 X509_time_adj_ex(ASN1_TIME *s, int offset_day, long offset_sec, time_t *in_time)
2074 {
2075 	time_t t;
2076 	if (in_time == NULL)
2077 		t = time(NULL);
2078 	else
2079 		t = *in_time;
2080 
2081 	return ASN1_TIME_adj(s, t, offset_day, offset_sec);
2082 }
2083 LCRYPTO_ALIAS(X509_time_adj_ex)
2084 
2085 int
2086 X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
2087 {
2088 	EVP_PKEY *ktmp = NULL, *ktmp2;
2089 	int i, j;
2090 
2091 	if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
2092 		return 1;
2093 
2094 	for (i = 0; i < sk_X509_num(chain); i++) {
2095 		ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
2096 		if (ktmp == NULL) {
2097 			X509error(X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
2098 			return 0;
2099 		}
2100 		if (!EVP_PKEY_missing_parameters(ktmp))
2101 			break;
2102 		else
2103 			ktmp = NULL;
2104 	}
2105 	if (ktmp == NULL) {
2106 		X509error(X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
2107 		return 0;
2108 	}
2109 
2110 	/* first, populate the other certs */
2111 	for (j = i - 1; j >= 0; j--) {
2112 		if ((ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j))) == NULL)
2113 			return 0;
2114 		if (!EVP_PKEY_copy_parameters(ktmp2, ktmp))
2115 			return 0;
2116 	}
2117 
2118 	if (pkey != NULL)
2119 		if (!EVP_PKEY_copy_parameters(pkey, ktmp))
2120 			return 0;
2121 	return 1;
2122 }
2123 LCRYPTO_ALIAS(X509_get_pubkey_parameters)
2124 
2125 int
2126 X509_STORE_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2127     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2128 {
2129 	/* This function is (usually) called only once, by
2130 	 * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c). */
2131 	return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX,
2132 	    argl, argp, new_func, dup_func, free_func);
2133 }
2134 LCRYPTO_ALIAS(X509_STORE_CTX_get_ex_new_index)
2135 
2136 int
2137 X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2138 {
2139 	return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2140 }
2141 LCRYPTO_ALIAS(X509_STORE_CTX_set_ex_data)
2142 
2143 void *
2144 X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
2145 {
2146 	return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2147 }
2148 LCRYPTO_ALIAS(X509_STORE_CTX_get_ex_data)
2149 
2150 int
2151 X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
2152 {
2153 	return ctx->error;
2154 }
2155 LCRYPTO_ALIAS(X509_STORE_CTX_get_error)
2156 
2157 void
2158 X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2159 {
2160 	ctx->error = err;
2161 }
2162 LCRYPTO_ALIAS(X509_STORE_CTX_set_error)
2163 
2164 int
2165 X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
2166 {
2167 	return ctx->error_depth;
2168 }
2169 LCRYPTO_ALIAS(X509_STORE_CTX_get_error_depth)
2170 
2171 void
2172 X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2173 {
2174 	ctx->error_depth = depth;
2175 }
2176 LCRYPTO_ALIAS(X509_STORE_CTX_set_error_depth)
2177 
2178 X509 *
2179 X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
2180 {
2181 	return ctx->current_cert;
2182 }
2183 LCRYPTO_ALIAS(X509_STORE_CTX_get_current_cert)
2184 
2185 void
2186 X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2187 {
2188 	ctx->current_cert = x;
2189 }
2190 LCRYPTO_ALIAS(X509_STORE_CTX_set_current_cert)
2191 
2192 STACK_OF(X509) *
2193 X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
2194 {
2195 	return ctx->chain;
2196 }
2197 LCRYPTO_ALIAS(X509_STORE_CTX_get_chain)
2198 
2199 STACK_OF(X509) *
2200 X509_STORE_CTX_get0_chain(X509_STORE_CTX *xs)
2201 {
2202 	return xs->chain;
2203 }
2204 LCRYPTO_ALIAS(X509_STORE_CTX_get0_chain)
2205 
2206 STACK_OF(X509) *
2207 X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
2208 {
2209 	int i;
2210 	X509 *x;
2211 	STACK_OF(X509) *chain;
2212 
2213 	if (!ctx->chain || !(chain = sk_X509_dup(ctx->chain)))
2214 		return NULL;
2215 	for (i = 0; i < sk_X509_num(chain); i++) {
2216 		x = sk_X509_value(chain, i);
2217 		CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
2218 	}
2219 	return chain;
2220 }
2221 LCRYPTO_ALIAS(X509_STORE_CTX_get1_chain)
2222 
2223 X509 *
2224 X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
2225 {
2226 	return ctx->current_issuer;
2227 }
2228 LCRYPTO_ALIAS(X509_STORE_CTX_get0_current_issuer)
2229 
2230 X509_CRL *
2231 X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
2232 {
2233 	return ctx->current_crl;
2234 }
2235 LCRYPTO_ALIAS(X509_STORE_CTX_get0_current_crl)
2236 
2237 X509_STORE_CTX *
2238 X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
2239 {
2240 	return ctx->parent;
2241 }
2242 LCRYPTO_ALIAS(X509_STORE_CTX_get0_parent_ctx)
2243 
2244 X509_STORE *
2245 X509_STORE_CTX_get0_store(X509_STORE_CTX *xs)
2246 {
2247 	return xs->store;
2248 }
2249 LCRYPTO_ALIAS(X509_STORE_CTX_get0_store)
2250 
2251 void
2252 X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2253 {
2254 	ctx->cert = x;
2255 }
2256 LCRYPTO_ALIAS(X509_STORE_CTX_set_cert)
2257 
2258 void
2259 X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2260 {
2261 	ctx->untrusted = sk;
2262 }
2263 LCRYPTO_ALIAS(X509_STORE_CTX_set_chain)
2264 
2265 void
2266 X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2267 {
2268 	ctx->crls = sk;
2269 }
2270 LCRYPTO_ALIAS(X509_STORE_CTX_set0_crls)
2271 
2272 int
2273 X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2274 {
2275 	return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2276 }
2277 LCRYPTO_ALIAS(X509_STORE_CTX_set_purpose)
2278 
2279 int
2280 X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2281 {
2282 	return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2283 }
2284 LCRYPTO_ALIAS(X509_STORE_CTX_set_trust)
2285 
2286 /* This function is used to set the X509_STORE_CTX purpose and trust
2287  * values. This is intended to be used when another structure has its
2288  * own trust and purpose values which (if set) will be inherited by
2289  * the ctx. If they aren't set then we will usually have a default
2290  * purpose in mind which should then be used to set the trust value.
2291  * An example of this is SSL use: an SSL structure will have its own
2292  * purpose and trust settings which the application can set: if they
2293  * aren't set then we use the default of SSL client/server.
2294  */
2295 
2296 int
2297 X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2298     int purpose, int trust)
2299 {
2300 	int idx;
2301 
2302 	/* If purpose not set use default */
2303 	if (!purpose)
2304 		purpose = def_purpose;
2305 	/* If we have a purpose then check it is valid */
2306 	if (purpose) {
2307 		X509_PURPOSE *ptmp;
2308 		idx = X509_PURPOSE_get_by_id(purpose);
2309 		if (idx == -1) {
2310 			X509error(X509_R_UNKNOWN_PURPOSE_ID);
2311 			return 0;
2312 		}
2313 		ptmp = X509_PURPOSE_get0(idx);
2314 		if (ptmp->trust == X509_TRUST_DEFAULT) {
2315 			idx = X509_PURPOSE_get_by_id(def_purpose);
2316 			if (idx == -1) {
2317 				X509error(X509_R_UNKNOWN_PURPOSE_ID);
2318 				return 0;
2319 			}
2320 			ptmp = X509_PURPOSE_get0(idx);
2321 		}
2322 		/* If trust not set then get from purpose default */
2323 		if (!trust)
2324 			trust = ptmp->trust;
2325 	}
2326 	if (trust) {
2327 		idx = X509_TRUST_get_by_id(trust);
2328 		if (idx == -1) {
2329 			X509error(X509_R_UNKNOWN_TRUST_ID);
2330 			return 0;
2331 		}
2332 	}
2333 
2334 	if (purpose && !ctx->param->purpose)
2335 		ctx->param->purpose = purpose;
2336 	if (trust && !ctx->param->trust)
2337 		ctx->param->trust = trust;
2338 	return 1;
2339 }
2340 LCRYPTO_ALIAS(X509_STORE_CTX_purpose_inherit)
2341 
2342 X509_STORE_CTX *
2343 X509_STORE_CTX_new(void)
2344 {
2345 	X509_STORE_CTX *ctx;
2346 
2347 	ctx = calloc(1, sizeof(X509_STORE_CTX));
2348 	if (!ctx) {
2349 		X509error(ERR_R_MALLOC_FAILURE);
2350 		return NULL;
2351 	}
2352 	return ctx;
2353 }
2354 LCRYPTO_ALIAS(X509_STORE_CTX_new)
2355 
2356 void
2357 X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2358 {
2359 	if (ctx == NULL)
2360 		return;
2361 
2362 	X509_STORE_CTX_cleanup(ctx);
2363 	free(ctx);
2364 }
2365 LCRYPTO_ALIAS(X509_STORE_CTX_free)
2366 
2367 int
2368 X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2369     STACK_OF(X509) *chain)
2370 {
2371 	int param_ret = 1;
2372 
2373 	/*
2374 	 * Make sure everything is initialized properly even in case of an
2375 	 * early return due to an error.
2376 	 *
2377 	 * While this 'ctx' can be reused, X509_STORE_CTX_cleanup() will have
2378 	 * freed everything and memset ex_data anyway.  This also allows us
2379 	 * to safely use X509_STORE_CTX variables from the stack which will
2380 	 * have uninitialized data.
2381 	 */
2382 	memset(ctx, 0, sizeof(*ctx));
2383 
2384 	/*
2385 	 * Start with this set to not valid - it will be set to valid
2386 	 * in X509_verify_cert.
2387 	 */
2388 	ctx->error = X509_V_ERR_INVALID_CALL;
2389 
2390 	/*
2391 	 * Set values other than 0.  Keep this in the same order as
2392 	 * X509_STORE_CTX except for values that may fail.  All fields that
2393 	 * may fail should go last to make sure 'ctx' is as consistent as
2394 	 * possible even on early exits.
2395 	 */
2396 	ctx->store = store;
2397 	ctx->cert = x509;
2398 	ctx->untrusted = chain;
2399 
2400 	if (store && store->verify)
2401 		ctx->verify = store->verify;
2402 	else
2403 		ctx->verify = internal_verify;
2404 
2405 	if (store && store->verify_cb)
2406 		ctx->verify_cb = store->verify_cb;
2407 	else
2408 		ctx->verify_cb = null_callback;
2409 
2410 	if (store && store->get_issuer)
2411 		ctx->get_issuer = store->get_issuer;
2412 	else
2413 		ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2414 
2415 	if (store && store->check_issued)
2416 		ctx->check_issued = store->check_issued;
2417 	else
2418 		ctx->check_issued = check_issued;
2419 
2420 	if (store && store->check_revocation)
2421 		ctx->check_revocation = store->check_revocation;
2422 	else
2423 		ctx->check_revocation = check_revocation;
2424 
2425 	if (store && store->get_crl)
2426 		ctx->get_crl = store->get_crl;
2427 	else
2428 		ctx->get_crl = NULL;
2429 
2430 	if (store && store->check_crl)
2431 		ctx->check_crl = store->check_crl;
2432 	else
2433 		ctx->check_crl = check_crl;
2434 
2435 	if (store && store->cert_crl)
2436 		ctx->cert_crl = store->cert_crl;
2437 	else
2438 		ctx->cert_crl = cert_crl;
2439 
2440 	ctx->check_policy = check_policy;
2441 
2442 	if (store && store->lookup_certs)
2443 		ctx->lookup_certs = store->lookup_certs;
2444 	else
2445 		ctx->lookup_certs = X509_STORE_get1_certs;
2446 
2447 	if (store && store->lookup_crls)
2448 		ctx->lookup_crls = store->lookup_crls;
2449 	else
2450 		ctx->lookup_crls = X509_STORE_get1_crls;
2451 
2452 	if (store && store->cleanup)
2453 		ctx->cleanup = store->cleanup;
2454 	else
2455 		ctx->cleanup = NULL;
2456 
2457 	ctx->param = X509_VERIFY_PARAM_new();
2458 	if (!ctx->param) {
2459 		X509error(ERR_R_MALLOC_FAILURE);
2460 		return 0;
2461 	}
2462 
2463 	/* Inherit callbacks and flags from X509_STORE if not set
2464 	 * use defaults.
2465 	 */
2466 	if (store)
2467 		param_ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2468 	else
2469 		ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT|X509_VP_FLAG_ONCE;
2470 
2471 	if (param_ret)
2472 		param_ret = X509_VERIFY_PARAM_inherit(ctx->param,
2473 		    X509_VERIFY_PARAM_lookup("default"));
2474 
2475 	if (param_ret == 0) {
2476 		X509error(ERR_R_MALLOC_FAILURE);
2477 		return 0;
2478 	}
2479 
2480 	if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2481 	    &(ctx->ex_data)) == 0) {
2482 		X509error(ERR_R_MALLOC_FAILURE);
2483 		return 0;
2484 	}
2485 	return 1;
2486 }
2487 LCRYPTO_ALIAS(X509_STORE_CTX_init)
2488 
2489 /* Set alternative lookup method: just a STACK of trusted certificates.
2490  * This avoids X509_STORE nastiness where it isn't needed.
2491  */
2492 
2493 void
2494 X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2495 {
2496 	ctx->other_ctx = sk;
2497 	ctx->get_issuer = get_issuer_sk;
2498 }
2499 LCRYPTO_ALIAS(X509_STORE_CTX_trusted_stack)
2500 
2501 void
2502 X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2503 {
2504 	X509_STORE_CTX_trusted_stack(ctx, sk);
2505 }
2506 LCRYPTO_ALIAS(X509_STORE_CTX_set0_trusted_stack)
2507 
2508 void
2509 X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2510 {
2511 	if (ctx->cleanup)
2512 		ctx->cleanup(ctx);
2513 	if (ctx->param != NULL) {
2514 		if (ctx->parent == NULL)
2515 			X509_VERIFY_PARAM_free(ctx->param);
2516 		ctx->param = NULL;
2517 	}
2518 	if (ctx->tree != NULL) {
2519 		X509_policy_tree_free(ctx->tree);
2520 		ctx->tree = NULL;
2521 	}
2522 	if (ctx->chain != NULL) {
2523 		sk_X509_pop_free(ctx->chain, X509_free);
2524 		ctx->chain = NULL;
2525 	}
2526 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX,
2527 	    ctx, &(ctx->ex_data));
2528 	memset(&ctx->ex_data, 0, sizeof(CRYPTO_EX_DATA));
2529 }
2530 LCRYPTO_ALIAS(X509_STORE_CTX_cleanup)
2531 
2532 void
2533 X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2534 {
2535 	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2536 }
2537 LCRYPTO_ALIAS(X509_STORE_CTX_set_depth)
2538 
2539 void
2540 X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2541 {
2542 	X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2543 }
2544 LCRYPTO_ALIAS(X509_STORE_CTX_set_flags)
2545 
2546 void
2547 X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, time_t t)
2548 {
2549 	X509_VERIFY_PARAM_set_time(ctx->param, t);
2550 }
2551 LCRYPTO_ALIAS(X509_STORE_CTX_set_time)
2552 
2553 int
2554 (*X509_STORE_CTX_get_verify_cb(X509_STORE_CTX *ctx))(int, X509_STORE_CTX *)
2555 {
2556 	return ctx->verify_cb;
2557 }
2558 LCRYPTO_ALIAS(X509_STORE_CTX_get_verify_cb)
2559 
2560 void
2561 X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2562     int (*verify_cb)(int, X509_STORE_CTX *))
2563 {
2564 	ctx->verify_cb = verify_cb;
2565 }
2566 LCRYPTO_ALIAS(X509_STORE_CTX_set_verify_cb)
2567 
2568 int
2569 (*X509_STORE_CTX_get_verify(X509_STORE_CTX *ctx))(X509_STORE_CTX *)
2570 {
2571 	return ctx->verify;
2572 }
2573 LCRYPTO_ALIAS(X509_STORE_CTX_get_verify)
2574 
2575 void
2576 X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx, int (*verify)(X509_STORE_CTX *))
2577 {
2578 	ctx->verify = verify;
2579 }
2580 LCRYPTO_ALIAS(X509_STORE_CTX_set_verify)
2581 
2582 X509_STORE_CTX_check_issued_fn
2583 X509_STORE_get_check_issued(X509_STORE *store)
2584 {
2585 	return store->check_issued;
2586 }
2587 LCRYPTO_ALIAS(X509_STORE_get_check_issued)
2588 
2589 void
2590 X509_STORE_set_check_issued(X509_STORE *store,
2591     X509_STORE_CTX_check_issued_fn check_issued)
2592 {
2593 	store->check_issued = check_issued;
2594 }
2595 LCRYPTO_ALIAS(X509_STORE_set_check_issued)
2596 
2597 X509_STORE_CTX_check_issued_fn
2598 X509_STORE_CTX_get_check_issued(X509_STORE_CTX *ctx)
2599 {
2600 	return ctx->check_issued;
2601 }
2602 LCRYPTO_ALIAS(X509_STORE_CTX_get_check_issued)
2603 
2604 X509 *
2605 X509_STORE_CTX_get0_cert(X509_STORE_CTX *ctx)
2606 {
2607 	return ctx->cert;
2608 }
2609 LCRYPTO_ALIAS(X509_STORE_CTX_get0_cert)
2610 
2611 STACK_OF(X509) *
2612 X509_STORE_CTX_get0_untrusted(X509_STORE_CTX *ctx)
2613 {
2614 	return ctx->untrusted;
2615 }
2616 LCRYPTO_ALIAS(X509_STORE_CTX_get0_untrusted)
2617 
2618 void
2619 X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2620 {
2621 	ctx->untrusted = sk;
2622 }
2623 LCRYPTO_ALIAS(X509_STORE_CTX_set0_untrusted)
2624 
2625 void
2626 X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2627 {
2628 	sk_X509_pop_free(ctx->chain, X509_free);
2629 	ctx->chain = sk;
2630 }
2631 LCRYPTO_ALIAS(X509_STORE_CTX_set0_verified_chain)
2632 
2633 X509_POLICY_TREE *
2634 X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2635 {
2636 	return ctx->tree;
2637 }
2638 LCRYPTO_ALIAS(X509_STORE_CTX_get0_policy_tree)
2639 
2640 int
2641 X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2642 {
2643 	return ctx->explicit_policy;
2644 }
2645 LCRYPTO_ALIAS(X509_STORE_CTX_get_explicit_policy)
2646 
2647 int
2648 X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx)
2649 {
2650 	return ctx->num_untrusted;
2651 }
2652 LCRYPTO_ALIAS(X509_STORE_CTX_get_num_untrusted)
2653 
2654 int
2655 X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2656 {
2657 	const X509_VERIFY_PARAM *param;
2658 	param = X509_VERIFY_PARAM_lookup(name);
2659 	if (!param)
2660 		return 0;
2661 	return X509_VERIFY_PARAM_inherit(ctx->param, param);
2662 }
2663 LCRYPTO_ALIAS(X509_STORE_CTX_set_default)
2664 
2665 X509_VERIFY_PARAM *
2666 X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2667 {
2668 	return ctx->param;
2669 }
2670 LCRYPTO_ALIAS(X509_STORE_CTX_get0_param)
2671 
2672 void
2673 X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2674 {
2675 	if (ctx->param)
2676 		X509_VERIFY_PARAM_free(ctx->param);
2677 	ctx->param = param;
2678 }
2679 LCRYPTO_ALIAS(X509_STORE_CTX_set0_param)
2680 
2681 /*
2682  * Check if |bits| are adequate for |security level|.
2683  * Returns 1 if ok, 0 otherwise.
2684  */
2685 static int
2686 enough_bits_for_security_level(int bits, int level)
2687 {
2688 	/*
2689 	 * Sigh. OpenSSL does this silly squashing, so we will
2690 	 * too. Derp for Derp compatibility being important.
2691 	 */
2692 	if (level < 0)
2693 		level = 0;
2694 	if (level > 5)
2695 		level = 5;
2696 
2697 	switch (level) {
2698 	case 0:
2699 		return 1;
2700 	case 1:
2701 		return bits >= 80;
2702 	case 2:
2703 		return bits >= 112;
2704 	case 3:
2705 		return bits >= 128;
2706 	case 4:
2707 		return bits >= 192;
2708 	case 5:
2709 		return bits >= 256;
2710 	default:
2711 		return 0;
2712 	}
2713 }
2714 
2715 /*
2716  * Check whether the public key of |cert| meets the security level of |ctx|.
2717  *
2718  * Returns 1 on success, 0 otherwise.
2719  */
2720 static int
2721 check_key_level(X509_STORE_CTX *ctx, X509 *cert)
2722 {
2723 	EVP_PKEY *pkey;
2724 	int bits;
2725 
2726 	/* Unsupported or malformed keys are not secure */
2727 	if ((pkey = X509_get0_pubkey(cert)) == NULL)
2728 		return 0;
2729 
2730 	if ((bits = EVP_PKEY_security_bits(pkey)) <= 0)
2731 		return 0;
2732 
2733 	return enough_bits_for_security_level(bits, ctx->param->security_level);
2734 }
2735 
2736 /*
2737  * Check whether the signature digest algorithm of |cert| meets the security
2738  * level of |ctx|.  Do not check trust anchors (self-signed or not).
2739  *
2740  * Returns 1 on success, 0 otherwise.
2741  */
2742 static int
2743 check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
2744 {
2745 	const EVP_MD *md;
2746 	int bits, nid, md_nid;
2747 
2748 	if ((nid = X509_get_signature_nid(cert)) == NID_undef)
2749 		return 0;
2750 
2751 	/*
2752 	 * Look up signature algorithm digest.
2753 	 */
2754 
2755 	if (!OBJ_find_sigid_algs(nid, &md_nid, NULL))
2756 		return 0;
2757 
2758 	if (md_nid == NID_undef)
2759 		return 0;
2760 
2761 	if ((md = EVP_get_digestbynid(md_nid)) == NULL)
2762 		return 0;
2763 
2764 	/* Assume 4 bits of collision resistance for each hash octet. */
2765 	bits = EVP_MD_size(md) * 4;
2766 
2767 	return enough_bits_for_security_level(bits, ctx->param->security_level);
2768 }
2769 
2770 int
2771 x509_vfy_check_security_level(X509_STORE_CTX *ctx)
2772 {
2773 	int num = sk_X509_num(ctx->chain);
2774 	int i;
2775 
2776 	if (ctx->param->security_level <= 0)
2777 		return 1;
2778 
2779 	for (i = 0; i < num; i++) {
2780 		X509 *cert = sk_X509_value(ctx->chain, i);
2781 
2782 		/*
2783 		 * We've already checked the security of the leaf key, so here
2784 		 * we only check the security of issuer keys.
2785 		 */
2786 		if (i > 0) {
2787 			if (!check_key_level(ctx, cert) &&
2788 			    !verify_cb_cert(ctx, cert, i,
2789 			    X509_V_ERR_CA_KEY_TOO_SMALL))
2790 				return 0;
2791 		}
2792 
2793 		/*
2794 		 * We also check the signature algorithm security of all certs
2795 		 * except those of the trust anchor at index num - 1.
2796 		 */
2797 		if (i == num - 1)
2798 			break;
2799 
2800 		if (!check_sig_level(ctx, cert) &&
2801 		    !verify_cb_cert(ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK))
2802 			return 0;
2803 	}
2804 	return 1;
2805 }
2806