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