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