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