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