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