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