48d936791f38a6fea4a9dc387f1c0fea230e0aca
[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->valid
1622             && (xs != xi
1623                 || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1624             if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1625                 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1626                 ctx->current_cert = xi;
1627                 ok = (*cb) (0, ctx);
1628                 if (!ok)
1629                     goto end;
1630             } else if (X509_verify(xs, pkey) <= 0) {
1631                 ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1632                 ctx->current_cert = xs;
1633                 ok = (*cb) (0, ctx);
1634                 if (!ok)
1635                     goto end;
1636             }
1637         }
1638
1639         xs->valid = 1;
1640
1641  check_cert:
1642         ok = x509_check_cert_time(ctx, xs, 0);
1643         if (!ok)
1644             goto end;
1645
1646         /* The last error (if any) is still in the error value */
1647         ctx->current_issuer = xi;
1648         ctx->current_cert = xs;
1649         ok = (*cb) (1, ctx);
1650         if (!ok)
1651             goto end;
1652
1653         n--;
1654         if (n >= 0) {
1655             xi = xs;
1656             xs = sk_X509_value(ctx->chain, n);
1657         }
1658     }
1659     ok = 1;
1660  end:
1661     return ok;
1662 }
1663
1664 int X509_cmp_current_time(const ASN1_TIME *ctm)
1665 {
1666     return X509_cmp_time(ctm, NULL);
1667 }
1668
1669 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1670 {
1671     char *str;
1672     ASN1_TIME atm;
1673     long offset;
1674     char buff1[24], buff2[24], *p;
1675     int i, j, remaining;
1676
1677     p = buff1;
1678     remaining = ctm->length;
1679     str = (char *)ctm->data;
1680     /*
1681      * Note that the following (historical) code allows much more slack in the
1682      * time format than RFC5280. In RFC5280, the representation is fixed:
1683      * UTCTime: YYMMDDHHMMSSZ
1684      * GeneralizedTime: YYYYMMDDHHMMSSZ
1685      */
1686     if (ctm->type == V_ASN1_UTCTIME) {
1687         /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1688         int min_length = sizeof("YYMMDDHHMMZ") - 1;
1689         int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1690         if (remaining < min_length || remaining > max_length)
1691             return 0;
1692         memcpy(p, str, 10);
1693         p += 10;
1694         str += 10;
1695         remaining -= 10;
1696     } else {
1697         /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1698         int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1699         int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1700         if (remaining < min_length || remaining > max_length)
1701             return 0;
1702         memcpy(p, str, 12);
1703         p += 12;
1704         str += 12;
1705         remaining -= 12;
1706     }
1707
1708     if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1709         *(p++) = '0';
1710         *(p++) = '0';
1711     } else {
1712         /* SS (seconds) */
1713         if (remaining < 2)
1714             return 0;
1715         *(p++) = *(str++);
1716         *(p++) = *(str++);
1717         remaining -= 2;
1718         /*
1719          * Skip any (up to three) fractional seconds...
1720          * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1721          * Can we just kill them altogether?
1722          */
1723         if (remaining && *str == '.') {
1724             str++;
1725             remaining--;
1726             for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1727                 if (*str < '0' || *str > '9')
1728                     break;
1729             }
1730         }
1731
1732     }
1733     *(p++) = 'Z';
1734     *(p++) = '\0';
1735
1736     /* We now need either a terminating 'Z' or an offset. */
1737     if (!remaining)
1738         return 0;
1739     if (*str == 'Z') {
1740         if (remaining != 1)
1741             return 0;
1742         offset = 0;
1743     } else {
1744         /* (+-)HHMM */
1745         if ((*str != '+') && (*str != '-'))
1746             return 0;
1747         /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1748         if (remaining != 5)
1749             return 0;
1750         if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1751             str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1752             return 0;
1753         offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1754         offset += (str[3] - '0') * 10 + (str[4] - '0');
1755         if (*str == '-')
1756             offset = -offset;
1757     }
1758     atm.type = ctm->type;
1759     atm.flags = 0;
1760     atm.length = sizeof(buff2);
1761     atm.data = (unsigned char *)buff2;
1762
1763     if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1764         return 0;
1765
1766     if (ctm->type == V_ASN1_UTCTIME) {
1767         i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1768         if (i < 50)
1769             i += 100;           /* cf. RFC 2459 */
1770         j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1771         if (j < 50)
1772             j += 100;
1773
1774         if (i < j)
1775             return -1;
1776         if (i > j)
1777             return 1;
1778     }
1779     i = strcmp(buff1, buff2);
1780     if (i == 0)                 /* wait a second then return younger :-) */
1781         return -1;
1782     else
1783         return i;
1784 }
1785
1786 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1787 {
1788     return X509_time_adj(s, adj, NULL);
1789 }
1790
1791 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1792 {
1793     return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1794 }
1795
1796 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1797                             int offset_day, long offset_sec, time_t *in_tm)
1798 {
1799     time_t t;
1800
1801     if (in_tm)
1802         t = *in_tm;
1803     else
1804         time(&t);
1805
1806     if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1807         if (s->type == V_ASN1_UTCTIME)
1808             return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1809         if (s->type == V_ASN1_GENERALIZEDTIME)
1810             return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1811     }
1812     return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1813 }
1814
1815 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1816 {
1817     EVP_PKEY *ktmp = NULL, *ktmp2;
1818     int i, j;
1819
1820     if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1821         return 1;
1822
1823     for (i = 0; i < sk_X509_num(chain); i++) {
1824         ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1825         if (ktmp == NULL) {
1826             X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1827                     X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1828             return 0;
1829         }
1830         if (!EVP_PKEY_missing_parameters(ktmp))
1831             break;
1832     }
1833     if (ktmp == NULL) {
1834         X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1835                 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1836         return 0;
1837     }
1838
1839     /* first, populate the other certs */
1840     for (j = i - 1; j >= 0; j--) {
1841         ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1842         EVP_PKEY_copy_parameters(ktmp2, ktmp);
1843     }
1844
1845     if (pkey != NULL)
1846         EVP_PKEY_copy_parameters(pkey, ktmp);
1847     return 1;
1848 }
1849
1850 /* Make a delta CRL as the diff between two full CRLs */
1851
1852 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1853                         EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1854 {
1855     X509_CRL *crl = NULL;
1856     int i;
1857     STACK_OF(X509_REVOKED) *revs = NULL;
1858     /* CRLs can't be delta already */
1859     if (base->base_crl_number || newer->base_crl_number) {
1860         X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1861         return NULL;
1862     }
1863     /* Base and new CRL must have a CRL number */
1864     if (!base->crl_number || !newer->crl_number) {
1865         X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1866         return NULL;
1867     }
1868     /* Issuer names must match */
1869     if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
1870         X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
1871         return NULL;
1872     }
1873     /* AKID and IDP must match */
1874     if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1875         X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
1876         return NULL;
1877     }
1878     if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1879         X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
1880         return NULL;
1881     }
1882     /* Newer CRL number must exceed full CRL number */
1883     if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1884         X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
1885         return NULL;
1886     }
1887     /* CRLs must verify */
1888     if (skey && (X509_CRL_verify(base, skey) <= 0 ||
1889                  X509_CRL_verify(newer, skey) <= 0)) {
1890         X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
1891         return NULL;
1892     }
1893     /* Create new CRL */
1894     crl = X509_CRL_new();
1895     if (crl == NULL || !X509_CRL_set_version(crl, 1))
1896         goto memerr;
1897     /* Set issuer name */
1898     if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
1899         goto memerr;
1900
1901     if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer)))
1902         goto memerr;
1903     if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer)))
1904         goto memerr;
1905
1906     /* Set base CRL number: must be critical */
1907
1908     if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
1909         goto memerr;
1910
1911     /*
1912      * Copy extensions across from newest CRL to delta: this will set CRL
1913      * number to correct value too.
1914      */
1915
1916     for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
1917         X509_EXTENSION *ext;
1918         ext = X509_CRL_get_ext(newer, i);
1919         if (!X509_CRL_add_ext(crl, ext, -1))
1920             goto memerr;
1921     }
1922
1923     /* Go through revoked entries, copying as needed */
1924
1925     revs = X509_CRL_get_REVOKED(newer);
1926
1927     for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
1928         X509_REVOKED *rvn, *rvtmp;
1929         rvn = sk_X509_REVOKED_value(revs, i);
1930         /*
1931          * Add only if not also in base. TODO: need something cleverer here
1932          * for some more complex CRLs covering multiple CAs.
1933          */
1934         if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
1935             rvtmp = X509_REVOKED_dup(rvn);
1936             if (!rvtmp)
1937                 goto memerr;
1938             if (!X509_CRL_add0_revoked(crl, rvtmp)) {
1939                 X509_REVOKED_free(rvtmp);
1940                 goto memerr;
1941             }
1942         }
1943     }
1944     /* TODO: optionally prune deleted entries */
1945
1946     if (skey && md && !X509_CRL_sign(crl, skey, md))
1947         goto memerr;
1948
1949     return crl;
1950
1951  memerr:
1952     X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
1953     X509_CRL_free(crl);
1954     return NULL;
1955 }
1956
1957 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1958 {
1959     return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1960 }
1961
1962 void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1963 {
1964     return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1965 }
1966
1967 int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1968 {
1969     return ctx->error;
1970 }
1971
1972 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1973 {
1974     ctx->error = err;
1975 }
1976
1977 int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1978 {
1979     return ctx->error_depth;
1980 }
1981
1982 X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1983 {
1984     return ctx->current_cert;
1985 }
1986
1987 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1988 {
1989     return ctx->chain;
1990 }
1991
1992 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1993 {
1994     if (!ctx->chain)
1995         return NULL;
1996     return X509_chain_up_ref(ctx->chain);
1997 }
1998
1999 X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
2000 {
2001     return ctx->current_issuer;
2002 }
2003
2004 X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
2005 {
2006     return ctx->current_crl;
2007 }
2008
2009 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
2010 {
2011     return ctx->parent;
2012 }
2013
2014 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2015 {
2016     ctx->cert = x;
2017 }
2018
2019 void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2020 {
2021     ctx->untrusted = sk;
2022 }
2023
2024 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2025 {
2026     ctx->crls = sk;
2027 }
2028
2029 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2030 {
2031     return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2032 }
2033
2034 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2035 {
2036     return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2037 }
2038
2039 /*
2040  * This function is used to set the X509_STORE_CTX purpose and trust values.
2041  * This is intended to be used when another structure has its own trust and
2042  * purpose values which (if set) will be inherited by the ctx. If they aren't
2043  * set then we will usually have a default purpose in mind which should then
2044  * be used to set the trust value. An example of this is SSL use: an SSL
2045  * structure will have its own purpose and trust settings which the
2046  * application can set: if they aren't set then we use the default of SSL
2047  * client/server.
2048  */
2049
2050 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2051                                    int purpose, int trust)
2052 {
2053     int idx;
2054     /* If purpose not set use default */
2055     if (!purpose)
2056         purpose = def_purpose;
2057     /* If we have a purpose then check it is valid */
2058     if (purpose) {
2059         X509_PURPOSE *ptmp;
2060         idx = X509_PURPOSE_get_by_id(purpose);
2061         if (idx == -1) {
2062             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2063                     X509_R_UNKNOWN_PURPOSE_ID);
2064             return 0;
2065         }
2066         ptmp = X509_PURPOSE_get0(idx);
2067         if (ptmp->trust == X509_TRUST_DEFAULT) {
2068             idx = X509_PURPOSE_get_by_id(def_purpose);
2069             if (idx == -1) {
2070                 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2071                         X509_R_UNKNOWN_PURPOSE_ID);
2072                 return 0;
2073             }
2074             ptmp = X509_PURPOSE_get0(idx);
2075         }
2076         /* If trust not set then get from purpose default */
2077         if (!trust)
2078             trust = ptmp->trust;
2079     }
2080     if (trust) {
2081         idx = X509_TRUST_get_by_id(trust);
2082         if (idx == -1) {
2083             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2084                     X509_R_UNKNOWN_TRUST_ID);
2085             return 0;
2086         }
2087     }
2088
2089     if (purpose && !ctx->param->purpose)
2090         ctx->param->purpose = purpose;
2091     if (trust && !ctx->param->trust)
2092         ctx->param->trust = trust;
2093     return 1;
2094 }
2095
2096 X509_STORE_CTX *X509_STORE_CTX_new(void)
2097 {
2098     X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2099
2100     if (ctx == NULL) {
2101         X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
2102         return NULL;
2103     }
2104     return ctx;
2105 }
2106
2107 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2108 {
2109     if (!ctx)
2110         return;
2111     X509_STORE_CTX_cleanup(ctx);
2112     OPENSSL_free(ctx);
2113 }
2114
2115 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2116                         STACK_OF(X509) *chain)
2117 {
2118     int ret = 1;
2119
2120     ctx->ctx = store;
2121     ctx->current_method = 0;
2122     ctx->cert = x509;
2123     ctx->untrusted = chain;
2124     ctx->crls = NULL;
2125     ctx->num_untrusted = 0;
2126     ctx->other_ctx = NULL;
2127     ctx->valid = 0;
2128     ctx->chain = NULL;
2129     ctx->error = 0;
2130     ctx->explicit_policy = 0;
2131     ctx->error_depth = 0;
2132     ctx->current_cert = NULL;
2133     ctx->current_issuer = NULL;
2134     ctx->current_crl = NULL;
2135     ctx->current_crl_score = 0;
2136     ctx->current_reasons = 0;
2137     ctx->tree = NULL;
2138     ctx->parent = NULL;
2139     ctx->dane = NULL;
2140     ctx->bare_ta_signed = 0;
2141     /* Zero ex_data to make sure we're cleanup-safe */
2142     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2143
2144     if (store) {
2145         ctx->verify_cb = store->verify_cb;
2146         /* Seems to always be 0 in OpenSSL, else must be idempotent */
2147         ctx->cleanup = store->cleanup;
2148     } else
2149         ctx->cleanup = 0;
2150
2151     if (store && store->check_issued)
2152         ctx->check_issued = store->check_issued;
2153     else
2154         ctx->check_issued = check_issued;
2155
2156     if (store && store->get_issuer)
2157         ctx->get_issuer = store->get_issuer;
2158     else
2159         ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2160
2161     if (store && store->verify_cb)
2162         ctx->verify_cb = store->verify_cb;
2163     else
2164         ctx->verify_cb = null_callback;
2165
2166     if (store && store->verify)
2167         ctx->verify = store->verify;
2168     else
2169         ctx->verify = internal_verify;
2170
2171     if (store && store->check_revocation)
2172         ctx->check_revocation = store->check_revocation;
2173     else
2174         ctx->check_revocation = check_revocation;
2175
2176     if (store && store->get_crl)
2177         ctx->get_crl = store->get_crl;
2178     else
2179         ctx->get_crl = NULL;
2180
2181     if (store && store->check_crl)
2182         ctx->check_crl = store->check_crl;
2183     else
2184         ctx->check_crl = check_crl;
2185
2186     if (store && store->cert_crl)
2187         ctx->cert_crl = store->cert_crl;
2188     else
2189         ctx->cert_crl = cert_crl;
2190
2191     if (store && store->lookup_certs)
2192         ctx->lookup_certs = store->lookup_certs;
2193     else
2194         ctx->lookup_certs = X509_STORE_get1_certs;
2195
2196     if (store && store->lookup_crls)
2197         ctx->lookup_crls = store->lookup_crls;
2198     else
2199         ctx->lookup_crls = X509_STORE_get1_crls;
2200
2201     ctx->check_policy = check_policy;
2202
2203     ctx->param = X509_VERIFY_PARAM_new();
2204     if (ctx->param == NULL) {
2205         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2206         goto err;
2207     }
2208
2209     /*
2210      * Inherit callbacks and flags from X509_STORE if not set use defaults.
2211      */
2212     if (store)
2213         ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2214     else
2215         ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2216
2217     if (ret)
2218         ret = X509_VERIFY_PARAM_inherit(ctx->param,
2219                                         X509_VERIFY_PARAM_lookup("default"));
2220
2221     if (ret == 0) {
2222         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2223         goto err;
2224     }
2225
2226     if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2227                            &ctx->ex_data))
2228         return 1;
2229     X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2230
2231  err:
2232     /*
2233      * On error clean up allocated storage, if the store context was not
2234      * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2235      */
2236     X509_STORE_CTX_cleanup(ctx);
2237     return 0;
2238 }
2239
2240 /*
2241  * Set alternative lookup method: just a STACK of trusted certificates. This
2242  * avoids X509_STORE nastiness where it isn't needed.
2243  */
2244
2245 void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2246 {
2247     ctx->other_ctx = sk;
2248     ctx->get_issuer = get_issuer_sk;
2249     ctx->lookup_certs = lookup_certs_sk;
2250 }
2251
2252 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2253 {
2254     /*
2255      * We need to be idempotent because, unfortunately, free() also calls
2256      * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2257      * calls cleanup() for the same object twice!  Thus we must zero the
2258      * pointers below after they're freed!
2259      */
2260     /* Seems to always be 0 in OpenSSL, do this at most once. */
2261     if (ctx->cleanup != NULL) {
2262         ctx->cleanup(ctx);
2263         ctx->cleanup = NULL;
2264     }
2265     if (ctx->param != NULL) {
2266         if (ctx->parent == NULL)
2267             X509_VERIFY_PARAM_free(ctx->param);
2268         ctx->param = NULL;
2269     }
2270     X509_policy_tree_free(ctx->tree);
2271     ctx->tree = NULL;
2272     sk_X509_pop_free(ctx->chain, X509_free);
2273     ctx->chain = NULL;
2274     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2275     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2276 }
2277
2278 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2279 {
2280     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2281 }
2282
2283 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2284 {
2285     X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2286 }
2287
2288 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2289                              time_t t)
2290 {
2291     X509_VERIFY_PARAM_set_time(ctx->param, t);
2292 }
2293
2294 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2295                                   int (*verify_cb) (int, X509_STORE_CTX *))
2296 {
2297     ctx->verify_cb = verify_cb;
2298 }
2299
2300 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2301 {
2302     return ctx->tree;
2303 }
2304
2305 int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2306 {
2307     return ctx->explicit_policy;
2308 }
2309
2310 int X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx)
2311 {
2312     return ctx->num_untrusted;
2313 }
2314
2315 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2316 {
2317     const X509_VERIFY_PARAM *param;
2318     param = X509_VERIFY_PARAM_lookup(name);
2319     if (!param)
2320         return 0;
2321     return X509_VERIFY_PARAM_inherit(ctx->param, param);
2322 }
2323
2324 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2325 {
2326     return ctx->param;
2327 }
2328
2329 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2330 {
2331     X509_VERIFY_PARAM_free(ctx->param);
2332     ctx->param = param;
2333 }
2334
2335 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, struct dane_st *dane)
2336 {
2337     ctx->dane = dane;
2338 }
2339
2340 static unsigned char *dane_i2d(
2341     X509 *cert,
2342     uint8_t selector,
2343     unsigned int *i2dlen)
2344 {
2345     unsigned char *buf = NULL;
2346     int len;
2347
2348     /*
2349      * Extract ASN.1 DER form of certificate or public key.
2350      */
2351     switch (selector) {
2352     case DANETLS_SELECTOR_CERT:
2353         len = i2d_X509(cert, &buf);
2354         break;
2355     case DANETLS_SELECTOR_SPKI:
2356         len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2357         break;
2358     default:
2359         X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2360         return NULL;
2361     }
2362
2363     if (len < 0 || buf == NULL) {
2364         X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2365         return NULL;
2366     }
2367
2368     *i2dlen = (unsigned int)len;
2369     return buf;
2370 }
2371
2372 #define DANETLS_NONE 256        /* impossible uint8_t */
2373
2374 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2375 {
2376     struct dane_st *dane = (struct dane_st *)ctx->dane;
2377     unsigned usage = DANETLS_NONE;
2378     unsigned selector = DANETLS_NONE;
2379     unsigned ordinal = DANETLS_NONE;
2380     unsigned mtype = DANETLS_NONE;
2381     unsigned char *i2dbuf = NULL;
2382     unsigned int i2dlen = 0;
2383     unsigned char mdbuf[EVP_MAX_MD_SIZE];
2384     unsigned char *cmpbuf = NULL;
2385     unsigned int cmplen = 0;
2386     int i;
2387     int recnum;
2388     int matched = 0;
2389     danetls_record *t = NULL;
2390     uint32_t mask;
2391
2392     mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2393
2394     /*
2395      * The trust store is not applicable with DANE-TA(2)
2396      */
2397     if (depth >= ctx->num_untrusted)
2398         mask &= DANETLS_PKIX_MASK;
2399
2400     /*
2401      * If we've previously matched a PKIX-?? record, no need to test any
2402      * furher PKIX-?? records,  it remains to just build the PKIX chain.
2403      * Had the match been a DANE-?? record, we'd be done already.
2404      */
2405     if (dane->mdpth >= 0)
2406         mask &= ~DANETLS_PKIX_MASK;
2407
2408     /*-
2409      * https://tools.ietf.org/html/rfc7671#section-5.1
2410      * https://tools.ietf.org/html/rfc7671#section-5.2
2411      * https://tools.ietf.org/html/rfc7671#section-5.3
2412      * https://tools.ietf.org/html/rfc7671#section-5.4
2413      *
2414      * We handle DANE-EE(3) records first as they require no chain building
2415      * and no expiration or hostname checks.  We also process digests with
2416      * higher ordinals first and ignore lower priorities except Full(0) which
2417      * is always processed (last).  If none match, we then process PKIX-EE(1).
2418      *
2419      * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2420      * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2421      * priorities.  See twin comment in ssl/ssl_lib.c.
2422      *
2423      * We expect that most TLSA RRsets will have just a single usage, so we
2424      * don't go out of our way to cache multiple selector-specific i2d buffers
2425      * across usages, but if the selector happens to remain the same as switch
2426      * usages, that's OK.  Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2427      * records would result in us generating each of the certificate and public
2428      * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2429      * or multiple "3 0 1" records.
2430      *
2431      * As soon as we find a match at any given depth, we stop, because either
2432      * we've matched a DANE-?? record and the peer is authenticated, or, after
2433      * exhausing all DANE-?? records, we've matched a PKIX-?? record, which is
2434      * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2435      */
2436     recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2437     for (i = 0; matched == 0 && i < recnum; ++i) {
2438         t = sk_danetls_record_value(dane->trecs, i);
2439         if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2440             continue;
2441         if (t->usage != usage) {
2442             usage = t->usage;
2443
2444             /* Reset digest agility for each usage/selector pair */
2445             mtype = DANETLS_NONE;
2446             ordinal = dane->dctx->mdord[t->mtype];
2447         }
2448         if (t->selector != selector) {
2449             selector = t->selector;
2450
2451             /* Update per-selector state */
2452             OPENSSL_free(i2dbuf);
2453             i2dbuf = dane_i2d(cert, selector, &i2dlen);
2454             if (i2dbuf == NULL)
2455                 return -1;
2456
2457             /* Reset digest agility for each usage/selector pair */
2458             mtype = DANETLS_NONE;
2459             ordinal = dane->dctx->mdord[t->mtype];
2460         } else if (t->mtype != DANETLS_MATCHING_FULL) {
2461             /*-
2462              * Digest agility:
2463              *
2464              *     <https://tools.ietf.org/html/rfc7671#section-9>
2465              *
2466              * For a fixed selector, after processing all records with the
2467              * highest mtype ordinal, ignore all mtypes with lower ordinals
2468              * other than "Full".
2469              */
2470             if (dane->dctx->mdord[t->mtype] < ordinal)
2471                 continue;
2472         }
2473
2474         /*
2475          * Each time we hit a (new selector or) mtype, re-compute the relevant
2476          * digest, more complex caching is not worth the code space.
2477          */
2478         if (t->mtype != mtype) {
2479             const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2480             cmpbuf = i2dbuf;
2481             cmplen = i2dlen;
2482
2483             if (md != NULL) {
2484                 cmpbuf = mdbuf;
2485                 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2486                     matched = -1;
2487                     break;
2488                 }
2489             }
2490         }
2491
2492         /*
2493          * Squirrel away the certificate and depth if we have a match.  Any
2494          * DANE match is dispositive, but with PKIX we still need to build a
2495          * full chain.
2496          */
2497         if (cmplen == t->dlen &&
2498             memcmp(cmpbuf, t->data, cmplen) == 0) {
2499             if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2500                 matched = 1;
2501             if (matched || dane->mdpth < 0) {
2502                 dane->mdpth = depth;
2503                 dane->mtlsa = t;
2504                 OPENSSL_free(dane->mcert);
2505                 dane->mcert = cert;
2506                 X509_up_ref(cert);
2507             }
2508             break;
2509         }
2510     }
2511
2512     /* Clear the one-element DER cache */
2513     OPENSSL_free(i2dbuf);
2514     return matched;
2515 }
2516
2517 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2518 {
2519     struct dane_st *dane = (struct dane_st *)ctx->dane;
2520     int matched = 0;
2521     X509 *cert;
2522
2523     if (!DANETLS_HAS_TA(dane) || depth == 0)
2524         return  X509_TRUST_UNTRUSTED;
2525
2526     /*
2527      * Record any DANE trust anchor matches, for the first depth to test, if
2528      * there's one at that depth. (This'll be false for length 1 chains looking
2529      * for an exact match for the leaf certificate).
2530      */
2531     cert = sk_X509_value(ctx->chain, depth);
2532     if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2533         return  X509_TRUST_REJECTED;
2534     if (matched > 0) {
2535         ctx->num_untrusted = depth - 1;
2536         return  X509_TRUST_TRUSTED;
2537     }
2538
2539     return  X509_TRUST_UNTRUSTED;
2540 }
2541
2542 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2543 {
2544     struct dane_st *dane = (struct dane_st *)ctx->dane;
2545     danetls_record *t;
2546     int num = ctx->num_untrusted;
2547     X509 *cert = sk_X509_value(ctx->chain, num - 1);
2548     int recnum = sk_danetls_record_num(dane->trecs);
2549     int i;
2550
2551     for (i = 0; i < recnum; ++i) {
2552         t = sk_danetls_record_value(dane->trecs, i);
2553         if (t->usage != DANETLS_USAGE_DANE_TA ||
2554             t->selector != DANETLS_SELECTOR_SPKI ||
2555             t->mtype != DANETLS_MATCHING_FULL ||
2556             X509_verify(cert, t->spki) <= 0)
2557             continue;
2558
2559         /* Clear PKIX-?? matches that failed to panned out to a full chain */
2560         X509_free(dane->mcert);
2561         dane->mcert = NULL;
2562
2563         /* Record match via a bare TA public key */
2564         ctx->bare_ta_signed = 1;
2565         dane->mdpth = num - 1;
2566         dane->mtlsa = t;
2567
2568         /* Prune any excess chain certificates */
2569         num = sk_X509_num(ctx->chain);
2570         for (; num > ctx->num_untrusted; --num)
2571             X509_free(sk_X509_pop(ctx->chain));
2572
2573         return X509_TRUST_TRUSTED;
2574     }
2575
2576     return X509_TRUST_UNTRUSTED;
2577 }
2578
2579 static void dane_reset(struct dane_st *dane)
2580 {
2581     /*
2582      * Reset state to verify another chain, or clear after failure.
2583      */
2584     X509_free(dane->mcert);
2585     dane->mcert = NULL;
2586     dane->mtlsa = NULL;
2587     dane->mdpth = -1;
2588     dane->pdpth = -1;
2589 }
2590
2591 static int dane_verify(X509_STORE_CTX *ctx)
2592 {
2593     X509 *cert = ctx->cert;
2594     int (*cb)(int xok, X509_STORE_CTX *xctx) = ctx->verify_cb;
2595     struct dane_st *dane = (struct dane_st *)ctx->dane;
2596     int matched;
2597     int done;
2598
2599     dane_reset(dane);
2600
2601     matched = dane_match(ctx, ctx->cert, 0);
2602     done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2603
2604     if (done)
2605         X509_get_pubkey_parameters(NULL, ctx->chain);
2606
2607     if (matched > 0) {
2608         ctx->error_depth = 0;
2609         ctx->current_cert = cert;
2610         return cb(1, ctx);
2611     }
2612
2613     if (matched < 0) {
2614         ctx->error_depth = 0;
2615         ctx->current_cert = cert;
2616         ctx->error = X509_V_ERR_OUT_OF_MEM;
2617         return -1;
2618     }
2619
2620     if (done) {
2621         /* Fail early, TA-based success is not possible */
2622         ctx->current_cert = cert;
2623         ctx->error_depth = 0;
2624         ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2625         return cb(0, ctx);
2626     }
2627
2628     /*
2629      * Chain verification for usages 0/1/2.  TLSA record matching of depth > 0
2630      * certificates happens in-line with building the rest of the chain.
2631      */
2632     return verify_chain(ctx);
2633 }
2634
2635 static int build_chain(X509_STORE_CTX *ctx)
2636 {
2637     struct dane_st *dane = (struct dane_st *)ctx->dane;
2638     int (*cb) (int, X509_STORE_CTX *) = ctx->verify_cb;
2639     int num = sk_X509_num(ctx->chain);
2640     X509 *cert = sk_X509_value(ctx->chain, num - 1);
2641     int ss = cert_self_signed(cert);
2642     STACK_OF(X509) *sktmp = NULL;
2643     unsigned int search;
2644     int may_trusted = 0;
2645     int may_alternate = 0;
2646     int trust = X509_TRUST_UNTRUSTED;
2647     int alt_untrusted = 0;
2648     int depth;
2649     int ok = 0;
2650     int i;
2651
2652     /* Our chain starts with a single untrusted element. */
2653     OPENSSL_assert(num == 1 && ctx->num_untrusted == num);
2654
2655 #define S_DOUNTRUSTED      (1 << 0)     /* Search untrusted chain */
2656 #define S_DOTRUSTED        (1 << 1)     /* Search trusted store */
2657 #define S_DOALTERNATE      (1 << 2)     /* Retry with pruned alternate chain */
2658     /*
2659      * Set up search policy, untrusted if possible, trusted-first if enabled.
2660      * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2661      * trust_store, otherwise we might look there first.  If not trusted-first,
2662      * and alternate chains are not disabled, try building an alternate chain
2663      * if no luck with untrusted first.
2664      */
2665     search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2666     if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2667         if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2668             search |= S_DOTRUSTED;
2669         else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2670             may_alternate = 1;
2671         may_trusted = 1;
2672     }
2673
2674     /*
2675      * Shallow-copy the stack of untrusted certificates (with TLS, this is
2676      * typically the content of the peer's certificate message) so can make
2677      * multiple passes over it, while free to remove elements as we go.
2678      */
2679     if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
2680         X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2681         return 0;
2682     }
2683
2684     /* Include any untrusted full certificates from DNS */
2685     if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
2686         for (i = 0; i < sk_X509_num(dane->certs); ++i) {
2687             if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
2688                 sk_X509_free(sktmp);
2689                 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2690                 return 0;
2691             }
2692         }
2693     }
2694
2695     /*
2696      * Still absurdly large, but arithmetically safe, a lower hard upper bound
2697      * might be reasonable.
2698      */
2699     if (ctx->param->depth > INT_MAX/2)
2700         ctx->param->depth = INT_MAX/2;
2701
2702     /*
2703      * Try to Extend the chain until we reach an ultimately trusted issuer.
2704      * Build chains up to one longer the limit, later fail if we hit the limit,
2705      * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
2706      */
2707     depth = ctx->param->depth + 1;
2708
2709     while (search != 0) {
2710         X509 *x;
2711         X509 *xtmp = NULL;
2712
2713         /*
2714          * Look in the trust store if enabled for first lookup, or we've run
2715          * out of untrusted issuers and search here is not disabled.  When
2716          * we exceed the depth limit, we simulate absence of a match.
2717          */
2718         if ((search & S_DOTRUSTED) != 0) {
2719             STACK_OF(X509) *hide = ctx->chain;
2720
2721             i = num = sk_X509_num(ctx->chain);
2722             if ((search & S_DOALTERNATE) != 0) {
2723                 /*
2724                  * As high up the chain as we can, look for an alternative
2725                  * trusted issuer of an untrusted certificate that currently
2726                  * has an untrusted issuer.  We use the alt_untrusted variable
2727                  * to track how far up the chain we find the first match.  It
2728                  * is only if and when we find a match, that we prune the chain
2729                  * and reset ctx->num_untrusted to the reduced count of
2730                  * untrusted certificates.  While we're searching for such a
2731                  * match (which may never be found), it is neither safe nor
2732                  * wise to preemptively modify either the chain or
2733                  * ctx->num_untrusted.
2734                  *
2735                  * Note, like ctx->num_untrusted, alt_untrusted is a count of
2736                  * untrusted certificates, not a "depth".
2737                  */
2738                 i = alt_untrusted;
2739             }
2740             x = sk_X509_value(ctx->chain, i-1);
2741
2742             /* Suppress duplicate suppression */
2743             ctx->chain = NULL;
2744             ok = (depth < num) ? 0 : ctx->get_issuer(&xtmp, ctx, x);
2745             ctx->chain = hide;
2746
2747             if (ok < 0) {
2748                 trust = X509_TRUST_REJECTED;
2749                 search = 0;
2750                 continue;
2751             }
2752
2753             if (ok > 0) {
2754                 /*
2755                  * Alternative trusted issuer for a mid-chain untrusted cert?
2756                  * Pop the untrusted cert's successors and retry.  We might now
2757                  * be able to complete a valid chain via the trust store.  Note
2758                  * that despite the current trust-store match we might still
2759                  * fail complete the chain to a suitable trust-anchor, in which
2760                  * case we may prune some more untrusted certificates and try
2761                  * again.  Thus the S_DOALTERNATE bit may yet be turned on
2762                  * again with an even shorter untrusted chain!
2763                  *
2764                  * If in the process we threw away our matching PKIX-TA trust
2765                  * anchor, reset DANE trust.  We might find a suitable trusted
2766                  * certificate among the ones from the trust store.
2767                  */
2768                 if ((search & S_DOALTERNATE) != 0) {
2769                     OPENSSL_assert(num > i && i > 0 && ss == 0);
2770                     search &= ~S_DOALTERNATE;
2771                     for (; num > i; --num)
2772                         X509_free(sk_X509_pop(ctx->chain));
2773                     ctx->num_untrusted = num;
2774
2775                     if (DANETLS_ENABLED(dane) &&
2776                         dane->mdpth >= ctx->num_untrusted) {
2777                         dane->mdpth = -1;
2778                         X509_free(dane->mcert);
2779                         dane->mcert = NULL;
2780                     }
2781                     if (DANETLS_ENABLED(dane) &&
2782                         dane->pdpth >= ctx->num_untrusted)
2783                         dane->pdpth = -1;
2784                 }
2785
2786                 /*
2787                  * Self-signed untrusted certificates get replaced by their
2788                  * trusted matching issuer.  Otherwise, grow the chain.
2789                  */
2790                 if (ss == 0) {
2791                     if (!sk_X509_push(ctx->chain, x = xtmp)) {
2792                         X509_free(xtmp);
2793                         X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2794                         trust = X509_TRUST_REJECTED;
2795                         search = 0;
2796                         continue;
2797                     }
2798                     ss = cert_self_signed(x);
2799                 } else if (num == ctx->num_untrusted) {
2800                     /*
2801                      * We have a self-signed certificate that has the same
2802                      * subject name (and perhaps keyid and/or serial number) as
2803                      * a trust-anchor.  We must have an exact match to avoid
2804                      * possible impersonation via key substitution etc.
2805                      */
2806                     if (X509_cmp(x, xtmp) != 0) {
2807                         /* Self-signed untrusted mimic. */
2808                         X509_free(xtmp);
2809                         ok = 0;
2810                     } else {
2811                         X509_free(x);
2812                         ctx->num_untrusted = --num;
2813                         (void) sk_X509_set(ctx->chain, num, x = xtmp);
2814                     }
2815                 }
2816
2817                 /*
2818                  * We've added a new trusted certificate to the chain, recheck
2819                  * trust.  If not done, and not self-signed look deeper.
2820                  * Whether or not we're doing "trusted first", we no longer
2821                  * look for untrusted certificates from the peer's chain.
2822                  *
2823                  * At this point ctx->num_trusted and num must reflect the
2824                  * correct number of untrusted certificates, since the DANE
2825                  * logic in check_trust() depends on distinguishing CAs from
2826                  * "the wire" from CAs from the trust store.  In particular, the
2827                  * certificate at depth "num" should be the new trusted
2828                  * certificate with ctx->num_untrusted <= num.
2829                  */
2830                 if (ok) {
2831                     OPENSSL_assert(ctx->num_untrusted <= num);
2832                     search &= ~S_DOUNTRUSTED;
2833                     switch (trust = check_trust(ctx, num)) {
2834                     case X509_TRUST_TRUSTED:
2835                     case X509_TRUST_REJECTED:
2836                         search = 0;
2837                         continue;
2838                     }
2839                     if (ss == 0)
2840                         continue;
2841                 }
2842             }
2843
2844             /*
2845              * No dispositive decision, and either self-signed or no match, if
2846              * we were doing untrusted-first, and alt-chains are not disabled,
2847              * do that, by repeatedly losing one untrusted element at a time,
2848              * and trying to extend the shorted chain.
2849              */
2850             if ((search & S_DOUNTRUSTED) == 0) {
2851                 /* Continue search for a trusted issuer of a shorter chain? */
2852                 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
2853                     continue;
2854                 /* Still no luck and no fallbacks left? */
2855                 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
2856                     ctx->num_untrusted < 2)
2857                     break;
2858                 /* Search for a trusted issuer of a shorter chain */
2859                 search |= S_DOALTERNATE;
2860                 alt_untrusted = ctx->num_untrusted - 1;
2861                 ss = 0;
2862             }
2863         }
2864
2865         /*
2866          * Extend chain with peer-provided certificates
2867          */
2868         if ((search & S_DOUNTRUSTED) != 0) {
2869             num = sk_X509_num(ctx->chain);
2870             OPENSSL_assert(num == ctx->num_untrusted);
2871             x = sk_X509_value(ctx->chain, num-1);
2872             xtmp = (depth < num) ? NULL : find_issuer(ctx, sktmp, x);
2873
2874             /*
2875              * Once we run out of untrusted issuers, we stop looking for more
2876              * and start looking only in the trust store if enabled.
2877              */
2878             if (xtmp == NULL) {
2879                 search &= ~S_DOUNTRUSTED;
2880                 if (may_trusted)
2881                     search |= S_DOTRUSTED;
2882                 continue;
2883             }
2884
2885             if (!sk_X509_push(ctx->chain, x = xtmp)) {
2886                 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2887                 trust = X509_TRUST_REJECTED;
2888                 search = 0;
2889                 continue;
2890             }
2891             X509_up_ref(x);
2892             ++ctx->num_untrusted;
2893             ss = cert_self_signed(xtmp);
2894
2895             /*
2896              * Not strictly necessary, but saves cycles looking at the same
2897              * certificates over and over.
2898              */
2899             (void) sk_X509_delete_ptr(sktmp, x);
2900
2901             /*
2902              * Check for DANE-TA trust of the topmost untrusted certificate.
2903              */
2904             switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
2905             case X509_TRUST_TRUSTED:
2906             case X509_TRUST_REJECTED:
2907                 search = 0;
2908                 continue;
2909             }
2910         }
2911     }
2912     sk_X509_free(sktmp);
2913
2914     /*
2915      * Last chance to make a trusted chain, either bare DANE-TA public-key
2916      * signers, or else direct leaf PKIX trust.
2917      */
2918     num = sk_X509_num(ctx->chain);
2919     if (num <= depth) {
2920         if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
2921             trust = check_dane_pkeys(ctx);
2922         if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
2923             trust = check_trust(ctx, num);
2924     }
2925
2926     switch (trust) {
2927     case X509_TRUST_TRUSTED:
2928         return 1;
2929     case X509_TRUST_REJECTED:
2930         return 0;
2931     case X509_TRUST_UNTRUSTED:
2932     default:
2933         num = sk_X509_num(ctx->chain);
2934         ctx->current_cert = sk_X509_value(ctx->chain, num - 1);
2935         ctx->error_depth = num-1;
2936         if (num > depth)
2937             ctx->error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
2938         else if (DANETLS_ENABLED(dane) &&
2939                  (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
2940             ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2941         else if (ss && sk_X509_num(ctx->chain) == 1)
2942             ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
2943         else if (ss)
2944             ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2945         else if (ctx->num_untrusted == num)
2946             ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
2947         else
2948             ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2949         if (DANETLS_ENABLED(dane))
2950             dane_reset(dane);
2951         return cb(0, ctx);
2952     }
2953 }