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