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