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