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