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