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