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