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