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