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