2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include "internal/deprecated.h"
17 #include "crypto/ctype.h"
18 #include "internal/cryptlib.h"
19 #include <openssl/crypto.h>
20 #include <openssl/buffer.h>
21 #include <openssl/evp.h>
22 #include <openssl/asn1.h>
23 #include <openssl/x509.h>
24 #include <openssl/x509v3.h>
25 #include <openssl/objects.h>
26 #include "internal/dane.h"
27 #include "crypto/x509.h"
28 #include "x509_local.h"
30 /* CRL score values */
32 #define CRL_SCORE_NOCRITICAL 0x100 /* No unhandled critical extensions */
33 #define CRL_SCORE_SCOPE 0x080 /* certificate is within CRL scope */
34 #define CRL_SCORE_TIME 0x040 /* CRL times valid */
35 #define CRL_SCORE_ISSUER_NAME 0x020 /* Issuer name matches certificate */
36 #define CRL_SCORE_VALID /* If this score or above CRL is probably valid */ \
37 (CRL_SCORE_NOCRITICAL | CRL_SCORE_TIME | CRL_SCORE_SCOPE)
38 #define CRL_SCORE_ISSUER_CERT 0x018 /* CRL issuer is certificate issuer */
39 #define CRL_SCORE_SAME_PATH 0x008 /* CRL issuer is on certificate path */
40 #define CRL_SCORE_AKID 0x004 /* CRL issuer matches CRL AKID */
41 #define CRL_SCORE_TIME_DELTA 0x002 /* Have a delta CRL with valid times */
43 static int build_chain(X509_STORE_CTX *ctx);
44 static int verify_chain(X509_STORE_CTX *ctx);
45 static int dane_verify(X509_STORE_CTX *ctx);
46 static int null_callback(int ok, X509_STORE_CTX *e);
47 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
48 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
49 static int check_chain(X509_STORE_CTX *ctx);
50 static int check_name_constraints(X509_STORE_CTX *ctx);
51 static int check_id(X509_STORE_CTX *ctx);
52 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
53 static int check_revocation(X509_STORE_CTX *ctx);
54 static int check_cert(X509_STORE_CTX *ctx);
55 static int check_policy(X509_STORE_CTX *ctx);
56 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
57 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
58 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert);
59 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert);
60 static int check_curve(X509 *cert);
62 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
63 unsigned int *preasons, X509_CRL *crl, X509 *x);
64 static int get_crl_delta(X509_STORE_CTX *ctx,
65 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
66 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
67 int *pcrl_score, X509_CRL *base,
68 STACK_OF(X509_CRL) *crls);
69 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
71 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
72 unsigned int *preasons);
73 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
74 static int check_crl_chain(X509_STORE_CTX *ctx,
75 STACK_OF(X509) *cert_path,
76 STACK_OF(X509) *crl_path);
78 static int internal_verify(X509_STORE_CTX *ctx);
80 static int null_callback(int ok, X509_STORE_CTX *e)
86 * Return 1 if given cert is considered self-signed, 0 if not, or -1 on error.
87 * This actually verifies self-signedness only if requested.
88 * It calls X509v3_cache_extensions()
89 * to match issuer and subject names (i.e., the cert being self-issued) and any
90 * present authority key identifier to match the subject key identifier, etc.
92 int X509_self_signed(X509 *cert, int verify_signature)
96 if ((pkey = X509_get0_pubkey(cert)) == NULL) { /* handles cert == NULL */
97 ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
100 if (!x509v3_cache_extensions(cert))
102 if ((cert->ex_flags & EXFLAG_SS) == 0)
104 if (!verify_signature)
106 return X509_verify(cert, pkey);
109 /* Given a certificate try and find an exact match in the store */
110 static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
112 STACK_OF(X509) *certs;
116 /* Lookup all certs with matching subject name */
118 certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
122 /* Look for exact match */
123 for (i = 0; i < sk_X509_num(certs); i++) {
124 xtmp = sk_X509_value(certs, i);
125 if (!X509_cmp(xtmp, x))
129 if (xtmp != NULL && !X509_up_ref(xtmp))
131 sk_X509_pop_free(certs, X509_free);
136 * Inform the verify callback of an error.
137 * If 'x' is not NULL it is the error cert, otherwise use the chain cert at
139 * If 'err' is not X509_V_OK, that's the error value, otherwise leave
140 * unchanged (presumably set by the caller).
142 * Returns 0 to abort verification with an error, non-zero to continue.
144 static int verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err)
146 ctx->error_depth = depth;
147 ctx->current_cert = (x != NULL) ? x : sk_X509_value(ctx->chain, depth);
148 if (err != X509_V_OK)
150 return ctx->verify_cb(0, ctx);
153 #define CB_FAIL_IF(cond, ctx, cert, depth, err) \
154 if ((cond) && verify_cb_cert(ctx, cert, depth, err) == 0) \
158 * Inform the verify callback of an error, CRL-specific variant. Here, the
159 * error depth and certificate are already set, we just specify the error
162 * Returns 0 to abort verification with an error, non-zero to continue.
164 static int verify_cb_crl(X509_STORE_CTX *ctx, int err)
167 return ctx->verify_cb(0, ctx);
170 static int check_auth_level(X509_STORE_CTX *ctx)
173 int num = sk_X509_num(ctx->chain);
175 if (ctx->param->auth_level <= 0)
178 for (i = 0; i < num; ++i) {
179 X509 *cert = sk_X509_value(ctx->chain, i);
182 * We've already checked the security of the leaf key, so here we only
183 * check the security of issuer keys.
185 CB_FAIL_IF(i > 0 && !check_key_level(ctx, cert),
186 ctx, cert, i, X509_V_ERR_CA_KEY_TOO_SMALL);
188 * We also check the signature algorithm security of all certificates
189 * except those of the trust anchor at index num-1.
191 CB_FAIL_IF(i < num - 1 && !check_sig_level(ctx, cert),
192 ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK);
197 static int verify_chain(X509_STORE_CTX *ctx)
203 * Before either returning with an error, or continuing with CRL checks,
204 * instantiate chain public key parameters.
206 if ((ok = build_chain(ctx)) == 0 ||
207 (ok = check_chain(ctx)) == 0 ||
208 (ok = check_auth_level(ctx)) == 0 ||
209 (ok = check_id(ctx)) == 0 || 1)
210 X509_get_pubkey_parameters(NULL, ctx->chain);
211 if (ok == 0 || (ok = ctx->check_revocation(ctx)) == 0)
214 err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
216 CB_FAIL_IF(err != X509_V_OK, ctx, NULL, ctx->error_depth, err);
218 /* Verify chain signatures and expiration times */
219 ok = ctx->verify != NULL ? ctx->verify(ctx) : internal_verify(ctx);
223 if ((ok = check_name_constraints(ctx)) == 0)
226 #ifndef OPENSSL_NO_RFC3779
227 /* RFC 3779 path validation, now that CRL check has been done */
228 if ((ok = X509v3_asid_validate_path(ctx)) == 0)
230 if ((ok = X509v3_addr_validate_path(ctx)) == 0)
234 /* If we get this far evaluate policies */
235 if (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)
236 ok = ctx->check_policy(ctx);
240 int X509_verify_cert(X509_STORE_CTX *ctx)
242 SSL_DANE *dane = ctx->dane;
245 if (ctx->cert == NULL) {
246 ERR_raise(ERR_LIB_X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
247 ctx->error = X509_V_ERR_INVALID_CALL;
251 if (ctx->chain != NULL) {
253 * This X509_STORE_CTX has already been used to verify a cert. We
254 * cannot do another one.
256 ERR_raise(ERR_LIB_X509, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
257 ctx->error = X509_V_ERR_INVALID_CALL;
261 if (!X509_add_cert_new(&ctx->chain, ctx->cert, X509_ADD_FLAG_UP_REF)) {
262 ctx->error = X509_V_ERR_OUT_OF_MEM;
265 ctx->num_untrusted = 1;
267 /* If the peer's public key is too weak, we can stop early. */
268 CB_FAIL_IF(!check_key_level(ctx, ctx->cert),
269 ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL);
271 ret = DANETLS_ENABLED(dane) ? dane_verify(ctx) : verify_chain(ctx);
274 * Safety-net. If we are returning an error, we must also set ctx->error,
275 * so that the chain is not considered verified should the error be ignored
276 * (e.g. TLS with SSL_VERIFY_NONE).
278 if (ret <= 0 && ctx->error == X509_V_OK)
279 ctx->error = X509_V_ERR_UNSPECIFIED;
283 static int sk_X509_contains(STACK_OF(X509) *sk, X509 *cert)
285 int i, n = sk_X509_num(sk);
287 for (i = 0; i < n; i++)
288 if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
294 * Find in given STACK_OF(X509) |sk| an issuer cert (if any) of given cert |x|.
295 * The issuer must not yet be in |ctx->chain|, yet allowing the exception that
296 * |x| is self-issued and |ctx->chain| has just one element.
297 * Prefer the first non-expired one, else take the most recently expired one.
299 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
302 X509 *issuer, *rv = NULL;
304 for (i = 0; i < sk_X509_num(sk); i++) {
305 issuer = sk_X509_value(sk, i);
306 if (ctx->check_issued(ctx, x, issuer)
307 && (((x->ex_flags & EXFLAG_SI) != 0 && sk_X509_num(ctx->chain) == 1)
308 || !sk_X509_contains(ctx->chain, issuer))) {
309 if (x509_check_cert_time(ctx, issuer, -1))
311 if (rv == NULL || ASN1_TIME_compare(X509_get0_notAfter(issuer),
312 X509_get0_notAfter(rv)) > 0)
319 /* Check that the given certificate 'x' is issued by the certificate 'issuer' */
320 static int check_issued(ossl_unused X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
322 return x509_likely_issued(issuer, x) == X509_V_OK;
325 /* Alternative lookup method: look from a STACK stored in other_ctx */
326 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
328 *issuer = find_issuer(ctx, ctx->other_ctx, x);
329 if (*issuer != NULL && X509_up_ref(*issuer))
336 static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx,
339 STACK_OF(X509) *sk = NULL;
343 for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
344 x = sk_X509_value(ctx->other_ctx, i);
345 if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
346 if (!X509_add_cert_new(&sk, x, X509_ADD_FLAG_UP_REF)) {
347 sk_X509_pop_free(sk, X509_free);
348 ctx->error = X509_V_ERR_OUT_OF_MEM;
357 * Check EE or CA certificate purpose. For trusted certificates explicit local
358 * auxiliary trust can be used to override EKU-restrictions.
360 static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth,
363 int tr_ok = X509_TRUST_UNTRUSTED;
366 * For trusted certificates we want to see whether any auxiliary trust
367 * settings trump the purpose constraints.
369 * This is complicated by the fact that the trust ordinals in
370 * ctx->param->trust are entirely independent of the purpose ordinals in
371 * ctx->param->purpose!
373 * What connects them is their mutual initialization via calls from
374 * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets
375 * related values of both param->trust and param->purpose. It is however
376 * typically possible to infer associated trust values from a purpose value
377 * via the X509_PURPOSE API.
379 * Therefore, we can only check for trust overrides when the purpose we're
380 * checking is the same as ctx->param->purpose and ctx->param->trust is
383 if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
384 tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
387 case X509_TRUST_TRUSTED:
389 case X509_TRUST_REJECTED:
392 switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
398 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
404 return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE);
407 /* Check extensions of a cert chain for consistency with the supplied purpose */
408 static int check_chain(X509_STORE_CTX *ctx)
410 int i, must_be_ca, plen = 0;
412 int ret, proxy_path_length = 0;
413 int purpose, allow_proxy_certs, num = sk_X509_num(ctx->chain);
416 * must_be_ca can have 1 of 3 values:
417 * -1: we accept both CA and non-CA certificates, to allow direct
418 * use of self-signed certificates (which are marked as CA).
419 * 0: we only accept non-CA certificates. This is currently not
420 * used, but the possibility is present for future extensions.
421 * 1: we only accept CA certificates. This is currently used for
422 * all certificates in the chain except the leaf certificate.
426 /* CRL path validation */
427 if (ctx->parent != NULL) {
428 allow_proxy_certs = 0;
429 purpose = X509_PURPOSE_CRL_SIGN;
432 (ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS) != 0;
433 purpose = ctx->param->purpose;
436 for (i = 0; i < num; i++) {
437 x = sk_X509_value(ctx->chain, i);
438 CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
439 && (x->ex_flags & EXFLAG_CRITICAL) != 0,
440 ctx, x, i, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION);
441 CB_FAIL_IF(!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY) != 0,
442 ctx, x, i, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED);
443 ret = X509_check_ca(x);
444 switch (must_be_ca) {
446 CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
447 && ret != 1 && ret != 0,
448 ctx, x, i, X509_V_ERR_INVALID_CA);
451 CB_FAIL_IF(ret != 0, ctx, x, i, X509_V_ERR_INVALID_NON_CA);
454 /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */
457 || (ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0)
458 && ret != 1), ctx, x, i, X509_V_ERR_INVALID_CA);
462 /* Check for presence of explicit elliptic curve parameters */
463 ret = check_curve(x);
464 CB_FAIL_IF(ret < 0, ctx, x, i, X509_V_ERR_UNSPECIFIED);
465 CB_FAIL_IF(ret == 0, ctx, x, i, X509_V_ERR_EC_KEY_EXPLICIT_PARAMS);
468 * Do the following set of checks only if strict checking is requested
469 * and not for self-issued (including self-signed) EE (non-CA) certs
470 * because RFC 5280 does not apply to them according RFC 6818 section 2.
472 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
475 * !(i == 0 && (x->ex_flags & EXFLAG_CA) == 0
476 * && (x->ex_flags & EXFLAG_SI) != 0)
478 /* Check Basic Constraints according to RFC 5280 section 4.2.1.9 */
479 if (x->ex_pathlen != -1) {
480 CB_FAIL_IF((x->ex_flags & EXFLAG_CA) == 0,
481 ctx, x, i, X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA);
482 CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) == 0, ctx,
483 x, i, X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN);
485 CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0
486 && (x->ex_flags & EXFLAG_BCONS) != 0
487 && (x->ex_flags & EXFLAG_BCONS_CRITICAL) == 0,
488 ctx, x, i, X509_V_ERR_CA_BCONS_NOT_CRITICAL);
489 /* Check Key Usage according to RFC 5280 section 4.2.1.3 */
490 if ((x->ex_flags & EXFLAG_CA) != 0) {
491 CB_FAIL_IF((x->ex_flags & EXFLAG_KUSAGE) == 0,
492 ctx, x, i, X509_V_ERR_CA_CERT_MISSING_KEY_USAGE);
494 CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) != 0, ctx, x, i,
495 X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA);
497 /* Check issuer is non-empty acc. to RFC 5280 section 4.1.2.4 */
498 CB_FAIL_IF(X509_NAME_entry_count(X509_get_issuer_name(x)) == 0,
499 ctx, x, i, X509_V_ERR_ISSUER_NAME_EMPTY);
500 /* Check subject is non-empty acc. to RFC 5280 section 4.1.2.6 */
501 CB_FAIL_IF(((x->ex_flags & EXFLAG_CA) != 0
502 || (x->ex_kusage & KU_CRL_SIGN) != 0
503 || x->altname == NULL)
504 && X509_NAME_entry_count(X509_get_subject_name(x)) == 0,
505 ctx, x, i, X509_V_ERR_SUBJECT_NAME_EMPTY);
506 CB_FAIL_IF(X509_NAME_entry_count(X509_get_subject_name(x)) == 0
507 && x->altname != NULL
508 && (x->ex_flags & EXFLAG_SAN_CRITICAL) == 0,
509 ctx, x, i, X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL);
510 /* Check SAN is non-empty according to RFC 5280 section 4.2.1.6 */
511 CB_FAIL_IF(x->altname != NULL
512 && sk_GENERAL_NAME_num(x->altname) <= 0,
513 ctx, x, i, X509_V_ERR_EMPTY_SUBJECT_ALT_NAME);
514 /* TODO add more checks on SAN entries */
515 /* Check sig alg consistency acc. to RFC 5280 section 4.1.1.2 */
516 CB_FAIL_IF(X509_ALGOR_cmp(&x->sig_alg, &x->cert_info.signature) != 0,
517 ctx, x, i, X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY);
518 CB_FAIL_IF(x->akid != NULL
519 && (x->ex_flags & EXFLAG_AKID_CRITICAL) != 0,
520 ctx, x, i, X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL);
521 CB_FAIL_IF(x->skid != NULL
522 && (x->ex_flags & EXFLAG_SKID_CRITICAL) != 0,
523 ctx, x, i, X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL);
524 if (X509_get_version(x) >= 2) { /* at least X.509v3 */
525 /* Check AKID presence acc. to RFC 5280 section 4.2.1.1 */
526 CB_FAIL_IF(i + 1 < num /*
527 * this means not last cert in chain,
528 * taken as "generated by conforming CAs"
530 && (x->akid == NULL || x->akid->keyid == NULL), ctx,
531 x, i, X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER);
532 /* Check SKID presence acc. to RFC 5280 section 4.2.1.2 */
533 CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0 && x->skid == NULL,
534 ctx, x, i, X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER);
536 CB_FAIL_IF(sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0,
537 ctx, x, i, X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3);
541 /* check_purpose() makes the callback as needed */
542 if (purpose > 0 && !check_purpose(ctx, x, purpose, i, must_be_ca))
544 /* Check path length */
545 CB_FAIL_IF(i > 1 && x->ex_pathlen != -1
546 && plen > x->ex_pathlen + proxy_path_length,
547 ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED);
548 /* Increment path length if not a self-issued intermediate CA */
549 if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0)
552 * If this certificate is a proxy certificate, the next certificate
553 * must be another proxy certificate or a EE certificate. If not,
554 * the next certificate must be a CA certificate.
556 if (x->ex_flags & EXFLAG_PROXY) {
558 * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint
559 * is less than max_path_length, the former should be copied to
560 * the latter, and 4.1.4 (a) stipulates that max_path_length
561 * should be verified to be larger than zero and decrement it.
563 * Because we're checking the certs in the reverse order, we start
564 * with verifying that proxy_path_length isn't larger than pcPLC,
565 * and copy the latter to the former if it is, and finally,
566 * increment proxy_path_length.
568 if (x->ex_pcpathlen != -1) {
569 CB_FAIL_IF(proxy_path_length > x->ex_pcpathlen,
570 ctx, x, i, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED);
571 proxy_path_length = x->ex_pcpathlen;
582 static int has_san_id(X509 *x, int gtype)
586 GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
591 for (i = 0; i < sk_GENERAL_NAME_num(gs); i++) {
592 GENERAL_NAME *g = sk_GENERAL_NAME_value(gs, i);
594 if (g->type == gtype) {
599 GENERAL_NAMES_free(gs);
603 static int check_name_constraints(X509_STORE_CTX *ctx)
607 /* Check name constraints for all certificates */
608 for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
609 X509 *x = sk_X509_value(ctx->chain, i);
612 /* Ignore self-issued certs unless last in chain */
613 if (i != 0 && (x->ex_flags & EXFLAG_SI) != 0)
617 * Proxy certificates policy has an extra constraint, where the
618 * certificate subject MUST be the issuer with a single CN entry
620 * (RFC 3820: 3.4, 4.1.3 (a)(4))
622 if ((x->ex_flags & EXFLAG_PROXY) != 0) {
623 X509_NAME *tmpsubject = X509_get_subject_name(x);
624 X509_NAME *tmpissuer = X509_get_issuer_name(x);
625 X509_NAME_ENTRY *tmpentry = NULL;
628 int last_loc = X509_NAME_entry_count(tmpsubject) - 1;
630 /* Check that there are at least two RDNs */
632 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
633 goto proxy_name_done;
637 * Check that there is exactly one more RDN in subject as
638 * there is in issuer.
640 if (X509_NAME_entry_count(tmpsubject)
641 != X509_NAME_entry_count(tmpissuer) + 1) {
642 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
643 goto proxy_name_done;
647 * Check that the last subject component isn't part of a
650 if (X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject, last_loc))
651 == X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
653 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
654 goto proxy_name_done;
658 * Check that the last subject RDN is a commonName, and that
659 * all the previous RDNs match the issuer exactly
661 tmpsubject = X509_NAME_dup(tmpsubject);
662 if (tmpsubject == NULL) {
663 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
664 ctx->error = X509_V_ERR_OUT_OF_MEM;
668 tmpentry = X509_NAME_delete_entry(tmpsubject, last_loc);
669 last_nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(tmpentry));
671 if (last_nid != NID_commonName
672 || X509_NAME_cmp(tmpsubject, tmpissuer) != 0) {
673 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
676 X509_NAME_ENTRY_free(tmpentry);
677 X509_NAME_free(tmpsubject);
680 CB_FAIL_IF(err != X509_V_OK, ctx, x, i, err);
684 * Check against constraints for all certificates higher in chain
685 * including trust anchor. Trust anchor not strictly speaking needed
686 * but if it includes constraints it is to be assumed it expects them
689 for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
690 NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
693 int rv = NAME_CONSTRAINTS_check(x, nc);
695 /* If EE certificate check commonName too */
696 if (rv == X509_V_OK && i == 0
697 && (ctx->param->hostflags
698 & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) == 0
699 && ((ctx->param->hostflags
700 & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) != 0
701 || !has_san_id(x, GEN_DNS)))
702 rv = NAME_CONSTRAINTS_check_CN(x, nc);
707 case X509_V_ERR_OUT_OF_MEM:
710 CB_FAIL_IF(1, ctx, x, i, rv);
719 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
721 return verify_cb_cert(ctx, ctx->cert, 0, errcode);
724 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
727 int n = sk_OPENSSL_STRING_num(vpm->hosts);
730 if (vpm->peername != NULL) {
731 OPENSSL_free(vpm->peername);
732 vpm->peername = NULL;
734 for (i = 0; i < n; ++i) {
735 name = sk_OPENSSL_STRING_value(vpm->hosts, i);
736 if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
742 static int check_id(X509_STORE_CTX *ctx)
744 X509_VERIFY_PARAM *vpm = ctx->param;
747 if (vpm->hosts != NULL && check_hosts(x, vpm) <= 0) {
748 if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
751 if (vpm->email != NULL
752 && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) {
753 if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
756 if (vpm->ip != NULL && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) {
757 if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
763 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
768 SSL_DANE *dane = ctx->dane;
769 int num = sk_X509_num(ctx->chain);
773 * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2)
774 * match, we're done, otherwise we'll merely record the match depth.
776 if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) {
777 switch (trust = check_dane_issuer(ctx, num_untrusted)) {
778 case X509_TRUST_TRUSTED:
779 case X509_TRUST_REJECTED:
785 * Check trusted certificates in chain at depth num_untrusted and up.
786 * Note, that depths 0..num_untrusted-1 may also contain trusted
787 * certificates, but the caller is expected to have already checked those,
788 * and wants to incrementally check just any added since.
790 for (i = num_untrusted; i < num; i++) {
791 x = sk_X509_value(ctx->chain, i);
792 trust = X509_check_trust(x, ctx->param->trust, 0);
793 /* If explicitly trusted return trusted */
794 if (trust == X509_TRUST_TRUSTED)
796 if (trust == X509_TRUST_REJECTED)
801 * If we are looking at a trusted certificate, and accept partial chains,
802 * the chain is PKIX trusted.
804 if (num_untrusted < num) {
805 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
807 return X509_TRUST_UNTRUSTED;
810 if (num_untrusted == num && ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
812 * Last-resort call with no new trusted certificates, check the leaf
813 * for a direct trust store match.
816 x = sk_X509_value(ctx->chain, i);
817 mx = lookup_cert_match(ctx, x);
819 return X509_TRUST_UNTRUSTED;
822 * Check explicit auxiliary trust/reject settings. If none are set,
823 * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
825 trust = X509_check_trust(mx, ctx->param->trust, 0);
826 if (trust == X509_TRUST_REJECTED) {
831 /* Replace leaf with trusted match */
832 (void)sk_X509_set(ctx->chain, 0, mx);
834 ctx->num_untrusted = 0;
839 * If no trusted certs in chain at all return untrusted and allow
840 * standard (no issuer cert) etc errors to be indicated.
842 return X509_TRUST_UNTRUSTED;
845 return verify_cb_cert(ctx, x, i, X509_V_ERR_CERT_REJECTED) == 0
846 ? X509_TRUST_REJECTED : X509_TRUST_UNTRUSTED;
849 if (!DANETLS_ENABLED(dane))
850 return X509_TRUST_TRUSTED;
852 dane->pdpth = num_untrusted;
853 /* With DANE, PKIX alone is not trusted until we have both */
854 if (dane->mdpth >= 0)
855 return X509_TRUST_TRUSTED;
856 return X509_TRUST_UNTRUSTED;
859 static int check_revocation(X509_STORE_CTX *ctx)
861 int i = 0, last = 0, ok = 0;
863 if ((ctx->param->flags & X509_V_FLAG_CRL_CHECK) == 0)
865 if ((ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) != 0) {
866 last = sk_X509_num(ctx->chain) - 1;
868 /* If checking CRL paths this isn't the EE certificate */
873 for (i = 0; i <= last; i++) {
874 ctx->error_depth = i;
875 ok = check_cert(ctx);
882 static int check_cert(X509_STORE_CTX *ctx)
884 X509_CRL *crl = NULL, *dcrl = NULL;
886 int cnum = ctx->error_depth;
887 X509 *x = sk_X509_value(ctx->chain, cnum);
889 ctx->current_cert = x;
890 ctx->current_issuer = NULL;
891 ctx->current_crl_score = 0;
892 ctx->current_reasons = 0;
894 if ((x->ex_flags & EXFLAG_PROXY) != 0)
897 while (ctx->current_reasons != CRLDP_ALL_REASONS) {
898 unsigned int last_reasons = ctx->current_reasons;
900 /* Try to retrieve relevant CRL */
901 if (ctx->get_crl != NULL)
902 ok = ctx->get_crl(ctx, &crl, x);
904 ok = get_crl_delta(ctx, &crl, &dcrl, x);
905 /* If error looking up CRL, nothing we can do except notify callback */
907 ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
910 ctx->current_crl = crl;
911 ok = ctx->check_crl(ctx, crl);
916 ok = ctx->check_crl(ctx, dcrl);
919 ok = ctx->cert_crl(ctx, dcrl, x);
926 /* Don't look in full CRL if delta reason is removefromCRL */
928 ok = ctx->cert_crl(ctx, crl, x);
938 * If reasons not updated we won't get anywhere by another iteration,
941 if (last_reasons == ctx->current_reasons) {
942 ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
950 ctx->current_crl = NULL;
954 /* Check CRL times against values in X509_STORE_CTX */
955 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
961 ctx->current_crl = crl;
962 if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
963 ptime = &ctx->param->check_time;
964 else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
969 i = X509_cmp_time(X509_CRL_get0_lastUpdate(crl), ptime);
973 if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD))
980 if (!verify_cb_crl(ctx, X509_V_ERR_CRL_NOT_YET_VALID))
984 if (X509_CRL_get0_nextUpdate(crl)) {
985 i = X509_cmp_time(X509_CRL_get0_nextUpdate(crl), ptime);
990 if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD))
993 /* Ignore expiration of base CRL is delta is valid */
994 if (i < 0 && (ctx->current_crl_score & CRL_SCORE_TIME_DELTA) == 0) {
995 if (!notify || !verify_cb_crl(ctx, X509_V_ERR_CRL_HAS_EXPIRED))
1001 ctx->current_crl = NULL;
1006 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1007 X509 **pissuer, int *pscore, unsigned int *preasons,
1008 STACK_OF(X509_CRL) *crls)
1010 int i, crl_score, best_score = *pscore;
1011 unsigned int reasons, best_reasons = 0;
1012 X509 *x = ctx->current_cert;
1013 X509_CRL *crl, *best_crl = NULL;
1014 X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1016 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1017 crl = sk_X509_CRL_value(crls, i);
1018 reasons = *preasons;
1019 crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1020 if (crl_score < best_score || crl_score == 0)
1022 /* If current CRL is equivalent use it if it is newer */
1023 if (crl_score == best_score && best_crl != NULL) {
1026 if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl),
1027 X509_CRL_get0_lastUpdate(crl)) == 0)
1030 * ASN1_TIME_diff never returns inconsistent signs for |day|
1033 if (day <= 0 && sec <= 0)
1037 best_crl_issuer = crl_issuer;
1038 best_score = crl_score;
1039 best_reasons = reasons;
1042 if (best_crl != NULL) {
1043 X509_CRL_free(*pcrl);
1045 *pissuer = best_crl_issuer;
1046 *pscore = best_score;
1047 *preasons = best_reasons;
1048 X509_CRL_up_ref(best_crl);
1049 X509_CRL_free(*pdcrl);
1051 get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1054 if (best_score >= CRL_SCORE_VALID)
1061 * Compare two CRL extensions for delta checking purposes. They should be
1062 * both present or both absent. If both present all fields must be identical.
1064 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1066 ASN1_OCTET_STRING *exta = NULL, *extb = NULL;
1067 int i = X509_CRL_get_ext_by_NID(a, nid, -1);
1070 /* Can't have multiple occurrences */
1071 if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1073 exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1076 i = X509_CRL_get_ext_by_NID(b, nid, -1);
1078 if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1080 extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1083 if (exta == NULL && extb == NULL)
1086 if (exta == NULL || extb == NULL)
1089 return ASN1_OCTET_STRING_cmp(exta, extb) == 0;
1092 /* See if a base and delta are compatible */
1093 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
1095 /* Delta CRL must be a delta */
1096 if (delta->base_crl_number == NULL)
1098 /* Base must have a CRL number */
1099 if (base->crl_number == NULL)
1101 /* Issuer names must match */
1102 if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1103 X509_CRL_get_issuer(delta)) != 0)
1105 /* AKID and IDP must match */
1106 if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1108 if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1110 /* Delta CRL base number must not exceed Full CRL number. */
1111 if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1113 /* Delta CRL number must exceed full CRL number */
1114 return ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0;
1118 * For a given base CRL find a delta... maybe extend to delta scoring or
1119 * retrieve a chain of deltas...
1121 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
1122 X509_CRL *base, STACK_OF(X509_CRL) *crls)
1127 if ((ctx->param->flags & X509_V_FLAG_USE_DELTAS) == 0)
1129 if (((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST) == 0)
1131 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1132 delta = sk_X509_CRL_value(crls, i);
1133 if (check_delta_base(delta, base)) {
1134 if (check_crl_time(ctx, delta, 0))
1135 *pscore |= CRL_SCORE_TIME_DELTA;
1136 X509_CRL_up_ref(delta);
1145 * For a given CRL return how suitable it is for the supplied certificate
1146 * 'x'. The return value is a mask of several criteria. If the issuer is not
1147 * the certificate issuer this is returned in *pissuer. The reasons mask is
1148 * also used to determine if the CRL is suitable: if no new reasons the CRL
1149 * is rejected, otherwise reasons is updated.
1151 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1152 unsigned int *preasons, X509_CRL *crl, X509 *x)
1155 unsigned int tmp_reasons = *preasons, crl_reasons;
1157 /* First see if we can reject CRL straight away */
1159 /* Invalid IDP cannot be processed */
1160 if ((crl->idp_flags & IDP_INVALID) != 0)
1162 /* Reason codes or indirect CRLs need extended CRL support */
1163 if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) {
1164 if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1166 } else if ((crl->idp_flags & IDP_REASONS) != 0) {
1167 /* If no new reasons reject */
1168 if ((crl->idp_reasons & ~tmp_reasons) == 0)
1171 /* Don't process deltas at this stage */
1172 else if (crl->base_crl_number != NULL)
1174 /* If issuer name doesn't match certificate need indirect CRL */
1175 if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl)) != 0) {
1176 if ((crl->idp_flags & IDP_INDIRECT) == 0)
1179 crl_score |= CRL_SCORE_ISSUER_NAME;
1182 if ((crl->flags & EXFLAG_CRITICAL) == 0)
1183 crl_score |= CRL_SCORE_NOCRITICAL;
1185 /* Check expiration */
1186 if (check_crl_time(ctx, crl, 0))
1187 crl_score |= CRL_SCORE_TIME;
1189 /* Check authority key ID and locate certificate issuer */
1190 crl_akid_check(ctx, crl, pissuer, &crl_score);
1192 /* If we can't locate certificate issuer at this point forget it */
1193 if ((crl_score & CRL_SCORE_AKID) == 0)
1196 /* Check cert for matching CRL distribution points */
1197 if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1198 /* If no new reasons reject */
1199 if ((crl_reasons & ~tmp_reasons) == 0)
1201 tmp_reasons |= crl_reasons;
1202 crl_score |= CRL_SCORE_SCOPE;
1205 *preasons = tmp_reasons;
1211 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1212 X509 **pissuer, int *pcrl_score)
1214 X509 *crl_issuer = NULL;
1215 const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1216 int cidx = ctx->error_depth;
1219 if (cidx != sk_X509_num(ctx->chain) - 1)
1222 crl_issuer = sk_X509_value(ctx->chain, cidx);
1224 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1225 if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1226 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1227 *pissuer = crl_issuer;
1232 for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1233 crl_issuer = sk_X509_value(ctx->chain, cidx);
1234 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1236 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1237 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1238 *pissuer = crl_issuer;
1243 /* Anything else needs extended CRL support */
1244 if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0)
1248 * Otherwise the CRL issuer is not on the path. Look for it in the set of
1249 * untrusted certificates.
1251 for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1252 crl_issuer = sk_X509_value(ctx->untrusted, i);
1253 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm) != 0)
1255 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1256 *pissuer = crl_issuer;
1257 *pcrl_score |= CRL_SCORE_AKID;
1264 * Check the path of a CRL issuer certificate. This creates a new
1265 * X509_STORE_CTX and populates it with most of the parameters from the
1266 * parent. This could be optimised somewhat since a lot of path checking will
1267 * be duplicated by the parent, but this will rarely be used in practice.
1269 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1271 X509_STORE_CTX crl_ctx;
1274 /* Don't allow recursive CRL path validation */
1275 if (ctx->parent != NULL)
1277 if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted))
1280 crl_ctx.crls = ctx->crls;
1281 /* Copy verify params across */
1282 X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1284 crl_ctx.parent = ctx;
1285 crl_ctx.verify_cb = ctx->verify_cb;
1287 /* Verify CRL issuer */
1288 ret = X509_verify_cert(&crl_ctx);
1292 /* Check chain is acceptable */
1293 ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1295 X509_STORE_CTX_cleanup(&crl_ctx);
1300 * RFC3280 says nothing about the relationship between CRL path and
1301 * certificate path, which could lead to situations where a certificate could
1302 * be revoked or validated by a CA not authorized to do so. RFC5280 is more
1303 * strict and states that the two paths must end in the same trust anchor,
1304 * though some discussions remain... until this is resolved we use the
1307 static int check_crl_chain(X509_STORE_CTX *ctx,
1308 STACK_OF(X509) *cert_path,
1309 STACK_OF(X509) *crl_path)
1311 X509 *cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1312 X509 *crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1314 return X509_cmp(cert_ta, crl_ta) == 0;
1318 * Check for match between two dist point names: three separate cases.
1319 * 1. Both are relative names and compare X509_NAME types.
1320 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1321 * 3. Both are full names and compare two GENERAL_NAMES.
1322 * 4. One is NULL: automatic match.
1324 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1326 X509_NAME *nm = NULL;
1327 GENERAL_NAMES *gens = NULL;
1328 GENERAL_NAME *gena, *genb;
1331 if (a == NULL || b == NULL)
1334 if (a->dpname == NULL)
1336 /* Case 1: two X509_NAME */
1338 if (b->dpname == NULL)
1340 return X509_NAME_cmp(a->dpname, b->dpname) == 0;
1342 /* Case 2: set name and GENERAL_NAMES appropriately */
1344 gens = b->name.fullname;
1345 } else if (b->type == 1) {
1346 if (b->dpname == NULL)
1348 /* Case 2: set name and GENERAL_NAMES appropriately */
1349 gens = a->name.fullname;
1353 /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1355 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1356 gena = sk_GENERAL_NAME_value(gens, i);
1357 if (gena->type != GEN_DIRNAME)
1359 if (X509_NAME_cmp(nm, gena->d.directoryName) == 0)
1365 /* Else case 3: two GENERAL_NAMES */
1367 for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1368 gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1369 for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1370 genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1371 if (GENERAL_NAME_cmp(gena, genb) == 0)
1380 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1383 const X509_NAME *nm = X509_CRL_get_issuer(crl);
1385 /* If no CRLissuer return is successful iff don't need a match */
1386 if (dp->CRLissuer == NULL)
1387 return (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1388 for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1389 GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1391 if (gen->type != GEN_DIRNAME)
1393 if (X509_NAME_cmp(gen->d.directoryName, nm) == 0)
1399 /* Check CRLDP and IDP */
1400 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1401 unsigned int *preasons)
1405 if ((crl->idp_flags & IDP_ONLYATTR) != 0)
1407 if ((x->ex_flags & EXFLAG_CA) != 0) {
1408 if ((crl->idp_flags & IDP_ONLYUSER) != 0)
1411 if ((crl->idp_flags & IDP_ONLYCA) != 0)
1414 *preasons = crl->idp_reasons;
1415 for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1416 DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1418 if (crldp_check_crlissuer(dp, crl, crl_score)) {
1419 if (crl->idp == NULL
1420 || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1421 *preasons &= dp->dp_reasons;
1426 return (crl->idp == NULL || crl->idp->distpoint == NULL)
1427 && (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1431 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1432 * to find a delta CRL too
1434 static int get_crl_delta(X509_STORE_CTX *ctx,
1435 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1438 X509 *issuer = NULL;
1440 unsigned int reasons;
1441 X509_CRL *crl = NULL, *dcrl = NULL;
1442 STACK_OF(X509_CRL) *skcrl;
1443 const X509_NAME *nm = X509_get_issuer_name(x);
1445 reasons = ctx->current_reasons;
1446 ok = get_crl_sk(ctx, &crl, &dcrl,
1447 &issuer, &crl_score, &reasons, ctx->crls);
1451 /* Lookup CRLs from store */
1452 skcrl = ctx->lookup_crls(ctx, nm);
1454 /* If no CRLs found and a near match from get_crl_sk use that */
1455 if (skcrl == NULL && crl != NULL)
1458 get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1460 sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1463 /* If we got any kind of CRL use it and return success */
1465 ctx->current_issuer = issuer;
1466 ctx->current_crl_score = crl_score;
1467 ctx->current_reasons = reasons;
1475 /* Check CRL validity */
1476 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1478 X509 *issuer = NULL;
1479 EVP_PKEY *ikey = NULL;
1480 int cnum = ctx->error_depth;
1481 int chnum = sk_X509_num(ctx->chain) - 1;
1483 /* If we have an alternative CRL issuer cert use that */
1484 if (ctx->current_issuer != NULL) {
1485 issuer = ctx->current_issuer;
1487 * Else find CRL issuer: if not last certificate then issuer is next
1488 * certificate in chain.
1490 } else if (cnum < chnum) {
1491 issuer = sk_X509_value(ctx->chain, cnum + 1);
1493 issuer = sk_X509_value(ctx->chain, chnum);
1494 /* If not self-issued, can't check signature */
1495 if (!ctx->check_issued(ctx, issuer, issuer) &&
1496 !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
1504 * Skip most tests for deltas because they have already been done
1506 if (crl->base_crl_number == NULL) {
1507 /* Check for cRLSign bit if keyUsage present */
1508 if ((issuer->ex_flags & EXFLAG_KUSAGE) != 0 &&
1509 (issuer->ex_kusage & KU_CRL_SIGN) == 0 &&
1510 !verify_cb_crl(ctx, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN))
1513 if ((ctx->current_crl_score & CRL_SCORE_SCOPE) == 0 &&
1514 !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
1517 if ((ctx->current_crl_score & CRL_SCORE_SAME_PATH) == 0 &&
1518 check_crl_path(ctx, ctx->current_issuer) <= 0 &&
1519 !verify_cb_crl(ctx, X509_V_ERR_CRL_PATH_VALIDATION_ERROR))
1522 if ((crl->idp_flags & IDP_INVALID) != 0 &&
1523 !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
1527 if ((ctx->current_crl_score & CRL_SCORE_TIME) == 0 &&
1528 !check_crl_time(ctx, crl, 1))
1531 /* Attempt to get issuer certificate public key */
1532 ikey = X509_get0_pubkey(issuer);
1534 !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1538 int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1540 if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
1542 /* Verify CRL signature */
1543 if (X509_CRL_verify(crl, ikey) <= 0 &&
1544 !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
1550 /* Check certificate against CRL */
1551 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1556 * The rules changed for this... previously if a CRL contained unhandled
1557 * critical extensions it could still be used to indicate a certificate
1558 * was revoked. This has since been changed since critical extensions can
1559 * change the meaning of CRL entries.
1561 if ((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
1562 && (crl->flags & EXFLAG_CRITICAL) != 0 &&
1563 !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
1566 * Look for serial number of certificate in CRL. If found, make sure
1567 * reason is not removeFromCRL.
1569 if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1570 if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1572 if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
1579 static int check_policy(X509_STORE_CTX *ctx)
1586 * With DANE, the trust anchor might be a bare public key, not a
1587 * certificate! In that case our chain does not have the trust anchor
1588 * certificate as a top-most element. This comports well with RFC5280
1589 * chain verification, since there too, the trust anchor is not part of the
1590 * chain to be verified. In particular, X509_policy_check() does not look
1591 * at the TA cert, but assumes that it is present as the top-most chain
1592 * element. We therefore temporarily push a NULL cert onto the chain if it
1593 * was verified via a bare public key, and pop it off right after the
1594 * X509_policy_check() call.
1596 if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
1597 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
1598 ctx->error = X509_V_ERR_OUT_OF_MEM;
1601 ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1602 ctx->param->policies, ctx->param->flags);
1603 if (ctx->bare_ta_signed)
1604 (void)sk_X509_pop(ctx->chain);
1606 if (ret == X509_PCY_TREE_INTERNAL) {
1607 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
1608 ctx->error = X509_V_ERR_OUT_OF_MEM;
1611 /* Invalid or inconsistent extensions */
1612 if (ret == X509_PCY_TREE_INVALID) {
1615 /* Locate certificates with bad extensions and notify callback. */
1616 for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1617 X509 *x = sk_X509_value(ctx->chain, i);
1619 CB_FAIL_IF((x->ex_flags & EXFLAG_INVALID_POLICY) != 0,
1620 ctx, x, i, X509_V_ERR_INVALID_POLICY_EXTENSION);
1624 if (ret == X509_PCY_TREE_FAILURE) {
1625 ctx->current_cert = NULL;
1626 ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1627 return ctx->verify_cb(0, ctx);
1629 if (ret != X509_PCY_TREE_VALID) {
1630 ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
1634 if ((ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) != 0) {
1635 ctx->current_cert = NULL;
1637 * Verification errors need to be "sticky", a callback may have allowed
1638 * an SSL handshake to continue despite an error, and we must then
1639 * remain in an error state. Therefore, we MUST NOT clear earlier
1640 * verification errors by setting the error to X509_V_OK.
1642 if (!ctx->verify_cb(2, ctx))
1650 * Check certificate validity times.
1651 * If depth >= 0, invoke verification callbacks on error, otherwise just return
1652 * the validation status.
1654 * Return 1 on success, 0 otherwise.
1656 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1661 if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
1662 ptime = &ctx->param->check_time;
1663 else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
1668 i = X509_cmp_time(X509_get0_notBefore(x), ptime);
1669 if (i >= 0 && depth < 0)
1671 CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
1672 CB_FAIL_IF(i > 0, ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID);
1674 i = X509_cmp_time(X509_get0_notAfter(x), ptime);
1675 if (i <= 0 && depth < 0)
1677 CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
1678 CB_FAIL_IF(i < 0, ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED);
1682 /* verify the issuer signatures and cert times of ctx->chain */
1683 static int internal_verify(X509_STORE_CTX *ctx)
1685 int n = sk_X509_num(ctx->chain) - 1;
1686 X509 *xi = sk_X509_value(ctx->chain, n);
1689 ctx->error_depth = n;
1690 if (ctx->bare_ta_signed) {
1692 * With DANE-verified bare public key TA signatures,
1693 * on the top certificate we check only the timestamps.
1694 * We report the issuer as NULL because all we have is a bare key.
1697 } else if (!ctx->check_issued(ctx, xi, xi)
1698 /* exceptional case: last cert in the chain is not self-issued */
1699 && ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0)) {
1702 ctx->error_depth = n;
1703 xs = sk_X509_value(ctx->chain, n);
1705 CB_FAIL_IF(1, ctx, xi, 0,
1706 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1709 * The below code will certainly not do a
1710 * self-signature check on xi because it is not self-issued.
1715 * Do not clear ctx->error = 0, it must be "sticky",
1716 * only the user's callback is allowed to reset errors (at its own peril).
1720 * For each iteration of this loop:
1721 * n is the subject depth
1722 * xs is the subject cert, for which the signature is to be checked
1723 * xi is NULL for DANE-verified bare public key TA signatures
1724 * else the supposed issuer cert containing the public key to use
1725 * Initially xs == xi if the last cert in the chain is self-issued.
1728 * Do signature check for self-signed certificates only if explicitly
1729 * asked for because it does not add any security and just wastes time.
1733 || ((ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)
1734 && (xi->ex_flags & EXFLAG_SS) != 0))) {
1737 * If the issuer's public key is not available or its key usage
1738 * does not support issuing the subject cert, report the issuer
1739 * cert and its depth (rather than n, the depth of the subject).
1741 int issuer_depth = n + (xs == xi ? 0 : 1);
1743 * According to https://tools.ietf.org/html/rfc5280#section-6.1.4
1744 * step (n) we must check any given key usage extension in a CA cert
1745 * when preparing the verification of a certificate issued by it.
1746 * According to https://tools.ietf.org/html/rfc5280#section-4.2.1.3
1747 * we must not verify a certificate signature if the key usage of
1748 * the CA certificate that issued the certificate prohibits signing.
1749 * In case the 'issuing' certificate is the last in the chain and is
1750 * not a CA certificate but a 'self-issued' end-entity cert (i.e.,
1751 * xs == xi && !(xi->ex_flags & EXFLAG_CA)) RFC 5280 does not apply
1752 * (see https://tools.ietf.org/html/rfc6818#section-2) and thus
1753 * we are free to ignore any key usage restrictions on such certs.
1755 int ret = xs == xi && (xi->ex_flags & EXFLAG_CA) == 0
1756 ? X509_V_OK : x509_signing_allowed(xi, xs);
1758 CB_FAIL_IF(ret != X509_V_OK, ctx, xi, issuer_depth, ret);
1759 if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1760 CB_FAIL_IF(1, ctx, xi, issuer_depth,
1761 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
1763 CB_FAIL_IF(X509_verify(xs, pkey) <= 0,
1764 ctx, xs, n, X509_V_ERR_CERT_SIGNATURE_FAILURE);
1768 /* in addition to RFC 5280, do also for trusted (root) cert */
1769 /* Calls verify callback as needed */
1770 if (!x509_check_cert_time(ctx, xs, n))
1774 * Signal success at this depth. However, the previous error (if any)
1777 ctx->current_issuer = xi;
1778 ctx->current_cert = xs;
1779 ctx->error_depth = n;
1780 if (!ctx->verify_cb(1, ctx))
1785 xs = sk_X509_value(ctx->chain, n);
1791 int X509_cmp_current_time(const ASN1_TIME *ctm)
1793 return X509_cmp_time(ctm, NULL);
1796 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1798 static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
1799 static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
1800 ASN1_TIME *asn1_cmp_time = NULL;
1801 int i, day, sec, ret = 0;
1802 #ifdef CHARSET_EBCDIC
1803 const char upper_z = 0x5A;
1805 const char upper_z = 'Z';
1809 * Note that ASN.1 allows much more slack in the time format than RFC5280.
1810 * In RFC5280, the representation is fixed:
1811 * UTCTime: YYMMDDHHMMSSZ
1812 * GeneralizedTime: YYYYMMDDHHMMSSZ
1814 * We do NOT currently enforce the following RFC 5280 requirement:
1815 * "CAs conforming to this profile MUST always encode certificate
1816 * validity dates through the year 2049 as UTCTime; certificate validity
1817 * dates in 2050 or later MUST be encoded as GeneralizedTime."
1819 switch (ctm->type) {
1820 case V_ASN1_UTCTIME:
1821 if (ctm->length != (int)(utctime_length))
1824 case V_ASN1_GENERALIZEDTIME:
1825 if (ctm->length != (int)(generalizedtime_length))
1833 * Verify the format: the ASN.1 functions we use below allow a more
1834 * flexible format than what's mandated by RFC 5280.
1835 * Digit and date ranges will be verified in the conversion methods.
1837 for (i = 0; i < ctm->length - 1; i++) {
1838 if (!ascii_isdigit(ctm->data[i]))
1841 if (ctm->data[ctm->length - 1] != upper_z)
1845 * There is ASN1_UTCTIME_cmp_time_t but no
1846 * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
1847 * so we go through ASN.1
1849 asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
1850 if (asn1_cmp_time == NULL)
1852 if (ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time) == 0)
1856 * X509_cmp_time comparison is <=.
1857 * The return value 0 is reserved for errors.
1859 ret = (day >= 0 && sec >= 0) ? -1 : 1;
1862 ASN1_TIME_free(asn1_cmp_time);
1867 * Return 0 if time should not be checked or reference time is in range,
1868 * or else 1 if it is past the end, or -1 if it is before the start
1870 int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
1871 const ASN1_TIME *start, const ASN1_TIME *end)
1874 time_t *time = NULL;
1875 unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
1877 if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
1878 ref_time = X509_VERIFY_PARAM_get_time(vpm);
1880 } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
1881 return 0; /* this means ok */
1882 } /* else reference time is the current time */
1884 if (end != NULL && X509_cmp_time(end, time) < 0)
1886 if (start != NULL && X509_cmp_time(start, time) > 0)
1891 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1893 return X509_time_adj(s, adj, NULL);
1896 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1898 return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1901 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1902 int offset_day, long offset_sec, time_t *in_tm)
1911 if (s != NULL && (s->flags & ASN1_STRING_FLAG_MSTRING) == 0) {
1912 if (s->type == V_ASN1_UTCTIME)
1913 return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1914 if (s->type == V_ASN1_GENERALIZEDTIME)
1915 return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1917 return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1920 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1922 EVP_PKEY *ktmp = NULL, *ktmp2;
1925 if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1928 for (i = 0; i < sk_X509_num(chain); i++) {
1929 ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1931 ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1934 if (!EVP_PKEY_missing_parameters(ktmp))
1938 ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1942 /* first, populate the other certs */
1943 for (j = i - 1; j >= 0; j--) {
1944 ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1945 EVP_PKEY_copy_parameters(ktmp2, ktmp);
1949 EVP_PKEY_copy_parameters(pkey, ktmp);
1953 /* Make a delta CRL as the difference between two full CRLs */
1954 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1955 EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1957 X509_CRL *crl = NULL;
1960 STACK_OF(X509_REVOKED) *revs = NULL;
1961 /* CRLs can't be delta already */
1962 if (base->base_crl_number != NULL || newer->base_crl_number != NULL) {
1963 ERR_raise(ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA);
1966 /* Base and new CRL must have a CRL number */
1967 if (base->crl_number == NULL || newer->crl_number == NULL) {
1968 ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_NUMBER);
1971 /* Issuer names must match */
1972 if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1973 X509_CRL_get_issuer(newer)) != 0) {
1974 ERR_raise(ERR_LIB_X509, X509_R_ISSUER_MISMATCH);
1977 /* AKID and IDP must match */
1978 if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1979 ERR_raise(ERR_LIB_X509, X509_R_AKID_MISMATCH);
1982 if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1983 ERR_raise(ERR_LIB_X509, X509_R_IDP_MISMATCH);
1986 /* Newer CRL number must exceed full CRL number */
1987 if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1988 ERR_raise(ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER);
1991 /* CRLs must verify */
1992 if (skey != NULL && (X509_CRL_verify(base, skey) <= 0 ||
1993 X509_CRL_verify(newer, skey) <= 0)) {
1994 ERR_raise(ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE);
1997 /* Create new CRL */
1998 crl = X509_CRL_new();
1999 if (crl == NULL || !X509_CRL_set_version(crl, 1))
2001 /* Set issuer name */
2002 if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
2005 if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer)))
2007 if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer)))
2010 /* Set base CRL number: must be critical */
2011 if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
2015 * Copy extensions across from newest CRL to delta: this will set CRL
2016 * number to correct value too.
2018 for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2019 X509_EXTENSION *ext = X509_CRL_get_ext(newer, i);
2021 if (!X509_CRL_add_ext(crl, ext, -1))
2025 /* Go through revoked entries, copying as needed */
2026 revs = X509_CRL_get_REVOKED(newer);
2028 for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2029 X509_REVOKED *rvn, *rvtmp;
2031 rvn = sk_X509_REVOKED_value(revs, i);
2033 * Add only if not also in base. TODO: need something cleverer here
2034 * for some more complex CRLs covering multiple CAs.
2036 if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2037 rvtmp = X509_REVOKED_dup(rvn);
2040 if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2041 X509_REVOKED_free(rvtmp);
2046 /* TODO: optionally prune deleted entries */
2048 if (skey != NULL && md != NULL && !X509_CRL_sign(crl, skey, md))
2054 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2059 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2061 return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2064 void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2066 return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2069 int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2074 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2079 int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2081 return ctx->error_depth;
2084 void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2086 ctx->error_depth = depth;
2089 X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2091 return ctx->current_cert;
2094 void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2096 ctx->current_cert = x;
2099 STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2104 STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2106 if (ctx->chain == NULL)
2108 return X509_chain_up_ref(ctx->chain);
2111 X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2113 return ctx->current_issuer;
2116 X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2118 return ctx->current_crl;
2121 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2126 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2131 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2136 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2139 * XXX: Why isn't this function always used to set the associated trust?
2140 * Should there even be a VPM->trust field at all? Or should the trust
2141 * always be inferred from the purpose by X509_STORE_CTX_init().
2143 return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2146 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2149 * XXX: See above, this function would only be needed when the default
2150 * trust for the purpose needs an override in a corner case.
2152 return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2156 * This function is used to set the X509_STORE_CTX purpose and trust values.
2157 * This is intended to be used when another structure has its own trust and
2158 * purpose values which (if set) will be inherited by the ctx. If they aren't
2159 * set then we will usually have a default purpose in mind which should then
2160 * be used to set the trust value. An example of this is SSL use: an SSL
2161 * structure will have its own purpose and trust settings which the
2162 * application can set: if they aren't set then we use the default of SSL
2166 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2167 int purpose, int trust)
2171 /* If purpose not set use default */
2173 purpose = def_purpose;
2174 /* If we have a purpose then check it is valid */
2178 idx = X509_PURPOSE_get_by_id(purpose);
2180 ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2183 ptmp = X509_PURPOSE_get0(idx);
2184 if (ptmp->trust == X509_TRUST_DEFAULT) {
2185 idx = X509_PURPOSE_get_by_id(def_purpose);
2187 * XXX: In the two callers above def_purpose is always 0, which is
2188 * not a known value, so idx will always be -1. How is the
2189 * X509_TRUST_DEFAULT case actually supposed to be handled?
2192 ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2195 ptmp = X509_PURPOSE_get0(idx);
2197 /* If trust not set then get from purpose default */
2199 trust = ptmp->trust;
2202 idx = X509_TRUST_get_by_id(trust);
2204 ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_TRUST_ID);
2209 if (ctx->param->purpose == 0 && purpose != 0)
2210 ctx->param->purpose = purpose;
2211 if (ctx->param->trust == 0 && trust != 0)
2212 ctx->param->trust = trust;
2216 X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
2218 X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2221 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2225 ctx->libctx = libctx;
2226 if (propq != NULL) {
2227 ctx->propq = OPENSSL_strdup(propq);
2228 if (ctx->propq == NULL) {
2230 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2238 X509_STORE_CTX *X509_STORE_CTX_new(void)
2240 return X509_STORE_CTX_new_ex(NULL, NULL);
2243 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2248 X509_STORE_CTX_cleanup(ctx);
2250 /* libctx and propq survive X509_STORE_CTX_cleanup() */
2251 OPENSSL_free(ctx->propq);
2255 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2256 STACK_OF(X509) *chain)
2262 ctx->untrusted = chain;
2264 ctx->num_untrusted = 0;
2265 ctx->other_ctx = NULL;
2269 ctx->explicit_policy = 0;
2270 ctx->error_depth = 0;
2271 ctx->current_cert = NULL;
2272 ctx->current_issuer = NULL;
2273 ctx->current_crl = NULL;
2274 ctx->current_crl_score = 0;
2275 ctx->current_reasons = 0;
2279 ctx->bare_ta_signed = 0;
2280 /* Zero ex_data to make sure we're cleanup-safe */
2281 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2283 /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2285 ctx->cleanup = store->cleanup;
2289 if (store != NULL && store->check_issued != NULL)
2290 ctx->check_issued = store->check_issued;
2292 ctx->check_issued = check_issued;
2294 if (store != NULL && store->get_issuer != NULL)
2295 ctx->get_issuer = store->get_issuer;
2297 ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2299 if (store != NULL && store->verify_cb != NULL)
2300 ctx->verify_cb = store->verify_cb;
2302 ctx->verify_cb = null_callback;
2304 if (store != NULL && store->verify != NULL)
2305 ctx->verify = store->verify;
2307 ctx->verify = internal_verify;
2309 if (store != NULL && store->check_revocation != NULL)
2310 ctx->check_revocation = store->check_revocation;
2312 ctx->check_revocation = check_revocation;
2314 if (store != NULL && store->get_crl != NULL)
2315 ctx->get_crl = store->get_crl;
2317 ctx->get_crl = NULL;
2319 if (store != NULL && store->check_crl != NULL)
2320 ctx->check_crl = store->check_crl;
2322 ctx->check_crl = check_crl;
2324 if (store != NULL && store->cert_crl != NULL)
2325 ctx->cert_crl = store->cert_crl;
2327 ctx->cert_crl = cert_crl;
2329 if (store != NULL && store->check_policy != NULL)
2330 ctx->check_policy = store->check_policy;
2332 ctx->check_policy = check_policy;
2334 if (store != NULL && store->lookup_certs != NULL)
2335 ctx->lookup_certs = store->lookup_certs;
2337 ctx->lookup_certs = X509_STORE_CTX_get1_certs;
2339 if (store != NULL && store->lookup_crls != NULL)
2340 ctx->lookup_crls = store->lookup_crls;
2342 ctx->lookup_crls = X509_STORE_CTX_get1_crls;
2344 ctx->param = X509_VERIFY_PARAM_new();
2345 if (ctx->param == NULL) {
2346 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2350 /* Inherit callbacks and flags from X509_STORE if not set use defaults. */
2352 ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2354 ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2357 ret = X509_VERIFY_PARAM_inherit(ctx->param,
2358 X509_VERIFY_PARAM_lookup("default"));
2361 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2366 * XXX: For now, continue to inherit trust from VPM, but infer from the
2367 * purpose if this still yields the default value.
2369 if (ctx->param->trust == X509_TRUST_DEFAULT) {
2370 int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2371 X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2374 ctx->param->trust = X509_PURPOSE_get_trust(xp);
2377 if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2380 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2384 * On error clean up allocated storage, if the store context was not
2385 * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2387 X509_STORE_CTX_cleanup(ctx);
2392 * Set alternative lookup method: just a STACK of trusted certificates. This
2393 * avoids X509_STORE nastiness where it isn't needed.
2395 void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2397 ctx->other_ctx = sk;
2398 ctx->get_issuer = get_issuer_sk;
2399 ctx->lookup_certs = lookup_certs_sk;
2402 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2405 * We need to be idempotent because, unfortunately, free() also calls
2406 * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2407 * calls cleanup() for the same object twice! Thus we must zero the
2408 * pointers below after they're freed!
2410 /* Seems to always be 0 in OpenSSL, do this at most once. */
2411 if (ctx->cleanup != NULL) {
2413 ctx->cleanup = NULL;
2415 if (ctx->param != NULL) {
2416 if (ctx->parent == NULL)
2417 X509_VERIFY_PARAM_free(ctx->param);
2420 X509_policy_tree_free(ctx->tree);
2422 sk_X509_pop_free(ctx->chain, X509_free);
2424 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2425 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2428 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2430 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2433 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2435 X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2438 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2441 X509_VERIFY_PARAM_set_time(ctx->param, t);
2444 X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
2449 STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
2451 return ctx->untrusted;
2454 void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2456 ctx->untrusted = sk;
2459 void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2461 sk_X509_pop_free(ctx->chain, X509_free);
2465 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2466 X509_STORE_CTX_verify_cb verify_cb)
2468 ctx->verify_cb = verify_cb;
2471 X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
2473 return ctx->verify_cb;
2476 void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
2477 X509_STORE_CTX_verify_fn verify)
2479 ctx->verify = verify;
2482 X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
2487 X509_STORE_CTX_get_issuer_fn
2488 X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
2490 return ctx->get_issuer;
2493 X509_STORE_CTX_check_issued_fn
2494 X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
2496 return ctx->check_issued;
2499 X509_STORE_CTX_check_revocation_fn
2500 X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
2502 return ctx->check_revocation;
2505 X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
2507 return ctx->get_crl;
2510 X509_STORE_CTX_check_crl_fn
2511 X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
2513 return ctx->check_crl;
2516 X509_STORE_CTX_cert_crl_fn
2517 X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
2519 return ctx->cert_crl;
2522 X509_STORE_CTX_check_policy_fn
2523 X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
2525 return ctx->check_policy;
2528 X509_STORE_CTX_lookup_certs_fn
2529 X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
2531 return ctx->lookup_certs;
2534 X509_STORE_CTX_lookup_crls_fn
2535 X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
2537 return ctx->lookup_crls;
2540 X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
2542 return ctx->cleanup;
2545 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
2550 int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
2552 return ctx->explicit_policy;
2555 int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
2557 return ctx->num_untrusted;
2560 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2562 const X509_VERIFY_PARAM *param;
2564 param = X509_VERIFY_PARAM_lookup(name);
2567 return X509_VERIFY_PARAM_inherit(ctx->param, param);
2570 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
2575 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2577 X509_VERIFY_PARAM_free(ctx->param);
2581 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
2586 static unsigned char *dane_i2d(X509 *cert, uint8_t selector,
2587 unsigned int *i2dlen)
2589 unsigned char *buf = NULL;
2593 * Extract ASN.1 DER form of certificate or public key.
2596 case DANETLS_SELECTOR_CERT:
2597 len = i2d_X509(cert, &buf);
2599 case DANETLS_SELECTOR_SPKI:
2600 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2603 ERR_raise(ERR_LIB_X509, X509_R_BAD_SELECTOR);
2607 if (len < 0 || buf == NULL) {
2608 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2612 *i2dlen = (unsigned int)len;
2616 #define DANETLS_NONE 256 /* impossible uint8_t */
2618 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2620 SSL_DANE *dane = ctx->dane;
2621 unsigned usage = DANETLS_NONE;
2622 unsigned selector = DANETLS_NONE;
2623 unsigned ordinal = DANETLS_NONE;
2624 unsigned mtype = DANETLS_NONE;
2625 unsigned char *i2dbuf = NULL;
2626 unsigned int i2dlen = 0;
2627 unsigned char mdbuf[EVP_MAX_MD_SIZE];
2628 unsigned char *cmpbuf = NULL;
2629 unsigned int cmplen = 0;
2633 danetls_record *t = NULL;
2636 mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2638 /* The trust store is not applicable with DANE-TA(2) */
2639 if (depth >= ctx->num_untrusted)
2640 mask &= DANETLS_PKIX_MASK;
2643 * If we've previously matched a PKIX-?? record, no need to test any
2644 * further PKIX-?? records, it remains to just build the PKIX chain.
2645 * Had the match been a DANE-?? record, we'd be done already.
2647 if (dane->mdpth >= 0)
2648 mask &= ~DANETLS_PKIX_MASK;
2651 * https://tools.ietf.org/html/rfc7671#section-5.1
2652 * https://tools.ietf.org/html/rfc7671#section-5.2
2653 * https://tools.ietf.org/html/rfc7671#section-5.3
2654 * https://tools.ietf.org/html/rfc7671#section-5.4
2656 * We handle DANE-EE(3) records first as they require no chain building
2657 * and no expiration or hostname checks. We also process digests with
2658 * higher ordinals first and ignore lower priorities except Full(0) which
2659 * is always processed (last). If none match, we then process PKIX-EE(1).
2661 * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2662 * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2663 * priorities. See twin comment in ssl/ssl_lib.c.
2665 * We expect that most TLSA RRsets will have just a single usage, so we
2666 * don't go out of our way to cache multiple selector-specific i2d buffers
2667 * across usages, but if the selector happens to remain the same as switch
2668 * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2669 * records would result in us generating each of the certificate and public
2670 * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2671 * or multiple "3 0 1" records.
2673 * As soon as we find a match at any given depth, we stop, because either
2674 * we've matched a DANE-?? record and the peer is authenticated, or, after
2675 * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
2676 * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2678 recnum = (dane->umask & mask) != 0 ? sk_danetls_record_num(dane->trecs) : 0;
2679 for (i = 0; matched == 0 && i < recnum; ++i) {
2680 t = sk_danetls_record_value(dane->trecs, i);
2681 if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2683 if (t->usage != usage) {
2686 /* Reset digest agility for each usage/selector pair */
2687 mtype = DANETLS_NONE;
2688 ordinal = dane->dctx->mdord[t->mtype];
2690 if (t->selector != selector) {
2691 selector = t->selector;
2693 /* Update per-selector state */
2694 OPENSSL_free(i2dbuf);
2695 i2dbuf = dane_i2d(cert, selector, &i2dlen);
2699 /* Reset digest agility for each usage/selector pair */
2700 mtype = DANETLS_NONE;
2701 ordinal = dane->dctx->mdord[t->mtype];
2702 } else if (t->mtype != DANETLS_MATCHING_FULL) {
2706 * <https://tools.ietf.org/html/rfc7671#section-9>
2708 * For a fixed selector, after processing all records with the
2709 * highest mtype ordinal, ignore all mtypes with lower ordinals
2710 * other than "Full".
2712 if (dane->dctx->mdord[t->mtype] < ordinal)
2717 * Each time we hit a (new selector or) mtype, re-compute the relevant
2718 * digest, more complex caching is not worth the code space.
2720 if (t->mtype != mtype) {
2721 const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2728 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2736 * Squirrel away the certificate and depth if we have a match. Any
2737 * DANE match is dispositive, but with PKIX we still need to build a
2740 if (cmplen == t->dlen &&
2741 memcmp(cmpbuf, t->data, cmplen) == 0) {
2742 if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2744 if (matched || dane->mdpth < 0) {
2745 dane->mdpth = depth;
2747 OPENSSL_free(dane->mcert);
2755 /* Clear the one-element DER cache */
2756 OPENSSL_free(i2dbuf);
2760 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2762 SSL_DANE *dane = ctx->dane;
2766 if (!DANETLS_HAS_TA(dane) || depth == 0)
2767 return X509_TRUST_UNTRUSTED;
2770 * Record any DANE trust anchor matches, for the first depth to test, if
2771 * there's one at that depth. (This'll be false for length 1 chains looking
2772 * for an exact match for the leaf certificate).
2774 cert = sk_X509_value(ctx->chain, depth);
2775 if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2776 return X509_TRUST_REJECTED;
2778 ctx->num_untrusted = depth - 1;
2779 return X509_TRUST_TRUSTED;
2782 return X509_TRUST_UNTRUSTED;
2785 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2787 SSL_DANE *dane = ctx->dane;
2789 int num = ctx->num_untrusted;
2790 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2791 int recnum = sk_danetls_record_num(dane->trecs);
2794 for (i = 0; i < recnum; ++i) {
2795 t = sk_danetls_record_value(dane->trecs, i);
2796 if (t->usage != DANETLS_USAGE_DANE_TA ||
2797 t->selector != DANETLS_SELECTOR_SPKI ||
2798 t->mtype != DANETLS_MATCHING_FULL ||
2799 X509_verify(cert, t->spki) <= 0)
2802 /* Clear any PKIX-?? matches that failed to extend to a full chain */
2803 X509_free(dane->mcert);
2806 /* Record match via a bare TA public key */
2807 ctx->bare_ta_signed = 1;
2808 dane->mdpth = num - 1;
2811 /* Prune any excess chain certificates */
2812 num = sk_X509_num(ctx->chain);
2813 for (; num > ctx->num_untrusted; --num)
2814 X509_free(sk_X509_pop(ctx->chain));
2816 return X509_TRUST_TRUSTED;
2819 return X509_TRUST_UNTRUSTED;
2822 static void dane_reset(SSL_DANE *dane)
2824 /* Reset state to verify another chain, or clear after failure. */
2825 X509_free(dane->mcert);
2832 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
2834 int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
2836 CB_FAIL_IF(err != X509_V_OK, ctx, cert, 0, err);
2840 static int dane_verify(X509_STORE_CTX *ctx)
2842 X509 *cert = ctx->cert;
2843 SSL_DANE *dane = ctx->dane;
2850 * When testing the leaf certificate, if we match a DANE-EE(3) record,
2851 * dane_match() returns 1 and we're done. If however we match a PKIX-EE(1)
2852 * record, the match depth and matching TLSA record are recorded, but the
2853 * return value is 0, because we still need to find a PKIX trust anchor.
2854 * Therefore, when DANE authentication is enabled (required), we're done
2856 * + matched < 0, internal error.
2857 * + matched == 1, we matched a DANE-EE(3) record
2858 * + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
2859 * DANE-TA(2) or PKIX-TA(0) to test.
2861 matched = dane_match(ctx, ctx->cert, 0);
2862 done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2865 X509_get_pubkey_parameters(NULL, ctx->chain);
2868 /* Callback invoked as needed */
2869 if (!check_leaf_suiteb(ctx, cert))
2871 /* Callback invoked as needed */
2872 if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 &&
2875 /* Bypass internal_verify(), issue depth 0 success callback */
2876 ctx->error_depth = 0;
2877 ctx->current_cert = cert;
2878 return ctx->verify_cb(1, ctx);
2882 ctx->error_depth = 0;
2883 ctx->current_cert = cert;
2884 ctx->error = X509_V_ERR_OUT_OF_MEM;
2889 /* Fail early, TA-based success is not possible */
2890 if (!check_leaf_suiteb(ctx, cert))
2892 return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
2896 * Chain verification for usages 0/1/2. TLSA record matching of depth > 0
2897 * certificates happens in-line with building the rest of the chain.
2899 return verify_chain(ctx);
2902 /* Get issuer, without duplicate suppression */
2903 static int get_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
2905 STACK_OF(X509) *saved_chain = ctx->chain;
2909 ok = ctx->get_issuer(issuer, ctx, cert);
2910 ctx->chain = saved_chain;
2915 static int build_chain(X509_STORE_CTX *ctx)
2917 SSL_DANE *dane = ctx->dane;
2918 int num = sk_X509_num(ctx->chain);
2919 X509 *curr = sk_X509_value(ctx->chain, num - 1); /* current end of chain */
2920 int self_signed = X509_self_signed(curr, 0); /* always refers to curr */
2921 STACK_OF(X509) *sk_untrusted = NULL;
2922 unsigned int search;
2923 int may_trusted = 0;
2924 int may_alternate = 0;
2925 int trust = X509_TRUST_UNTRUSTED;
2926 int alt_untrusted = 0;
2931 /* Our chain starts with a single untrusted element. */
2932 if (!ossl_assert(num == 1 && ctx->num_untrusted == num))
2934 if (self_signed < 0)
2937 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
2938 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
2939 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
2941 * Set up search policy, untrusted if possible, trusted-first if enabled.
2942 * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2943 * trust_store, otherwise we might look there first. If not trusted-first,
2944 * and alternate chains are not disabled, try building an alternate chain
2945 * if no luck with untrusted first.
2947 search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2948 if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2949 if (search == 0 || (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) != 0)
2950 search |= S_DOTRUSTED;
2951 else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2957 * Shallow-copy the stack of untrusted certificates (with TLS, this is
2958 * typically the content of the peer's certificate message) so can make
2959 * multiple passes over it, while free to remove elements as we go.
2961 if ((sk_untrusted = sk_X509_dup(ctx->untrusted)) == NULL) {
2962 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2963 ctx->error = X509_V_ERR_OUT_OF_MEM;
2968 * If we got any "DANE-TA(2) Cert(0) Full(0)" trust anchors from DNS, add
2969 * them to our working copy of the untrusted certificate stack. Since the
2970 * caller of X509_STORE_CTX_init() may have provided only a leaf cert with
2971 * no corresponding stack of untrusted certificates, we may need to create
2972 * an empty stack first. [ At present only the ssl library provides DANE
2973 * support, and ssl_verify_cert_chain() always provides a non-null stack
2974 * containing at least the leaf certificate, but we must be prepared for
2977 if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
2978 if (sk_untrusted == NULL && (sk_untrusted = sk_X509_new_null()) == NULL) {
2979 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
2980 ctx->error = X509_V_ERR_OUT_OF_MEM;
2983 if (!X509_add_certs(sk_untrusted, dane->certs, X509_ADD_FLAG_DEFAULT)) {
2984 sk_X509_free(sk_untrusted);
2985 ctx->error = X509_V_ERR_OUT_OF_MEM;
2991 * Still absurdly large, but arithmetically safe, a lower hard upper bound
2992 * might be reasonable.
2994 if (ctx->param->depth > INT_MAX / 2)
2995 ctx->param->depth = INT_MAX / 2;
2998 * Try to extend the chain until we reach an ultimately trusted issuer.
2999 * Build chains up to one longer the limit, later fail if we hit the limit,
3000 * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3002 depth = ctx->param->depth + 1;
3004 while (search != 0) {
3005 X509 *issuer = NULL;
3008 * Look in the trust store if enabled for first lookup, or we've run
3009 * out of untrusted issuers and search here is not disabled. When we
3010 * reach the depth limit, we stop extending the chain, if by that point
3011 * we've not found a trust anchor, any trusted chain would be too long.
3013 * The error reported to the application verify callback is at the
3014 * maximal valid depth with the current certificate equal to the last
3015 * not ultimately-trusted issuer. For example, with verify_depth = 0,
3016 * the callback will report errors at depth=1 when the immediate issuer
3017 * of the leaf certificate is not a trust anchor. No attempt will be
3018 * made to locate an issuer for that certificate, since such a chain
3019 * would be a-priori too long.
3021 if ((search & S_DOTRUSTED) != 0) {
3022 i = num = sk_X509_num(ctx->chain);
3023 if ((search & S_DOALTERNATE) != 0) {
3025 * As high up the chain as we can, look for an alternative
3026 * trusted issuer of an untrusted certificate that currently
3027 * has an untrusted issuer. We use the alt_untrusted variable
3028 * to track how far up the chain we find the first match. It
3029 * is only if and when we find a match, that we prune the chain
3030 * and reset ctx->num_untrusted to the reduced count of
3031 * untrusted certificates. While we're searching for such a
3032 * match (which may never be found), it is neither safe nor
3033 * wise to preemptively modify either the chain or
3034 * ctx->num_untrusted.
3036 * Note, like ctx->num_untrusted, alt_untrusted is a count of
3037 * untrusted certificates, not a "depth".
3041 curr = sk_X509_value(ctx->chain, i - 1);
3043 ok = depth < num ? 0 : get_issuer(&issuer, ctx, curr);
3046 trust = X509_TRUST_REJECTED;
3047 ctx->error = X509_V_ERR_STORE_LOOKUP;
3053 * Alternative trusted issuer for a mid-chain untrusted cert?
3054 * Pop the untrusted cert's successors and retry. We might now
3055 * be able to complete a valid chain via the trust store. Note
3056 * that despite the current trust store match we might still
3057 * fail complete the chain to a suitable trust anchor, in which
3058 * case we may prune some more untrusted certificates and try
3059 * again. Thus the S_DOALTERNATE bit may yet be turned on
3060 * again with an even shorter untrusted chain!
3062 * If in the process we threw away our matching PKIX-TA trust
3063 * anchor, reset DANE trust. We might find a suitable trusted
3064 * certificate among the ones from the trust store.
3066 if ((search & S_DOALTERNATE) != 0) {
3067 if (!ossl_assert(num > i && i > 0 && !self_signed)) {
3068 ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
3070 trust = X509_TRUST_REJECTED;
3071 ctx->error = X509_V_ERR_UNSPECIFIED;
3074 search &= ~S_DOALTERNATE;
3075 for (; num > i; --num)
3076 X509_free(sk_X509_pop(ctx->chain));
3077 ctx->num_untrusted = num;
3079 if (DANETLS_ENABLED(dane) &&
3080 dane->mdpth >= ctx->num_untrusted) {
3082 X509_free(dane->mcert);
3085 if (DANETLS_ENABLED(dane) &&
3086 dane->pdpth >= ctx->num_untrusted)
3091 * Self-signed untrusted certificates get replaced by their
3092 * trusted matching issuer. Otherwise, grow the chain.
3096 if ((self_signed = X509_self_signed(curr, 0)) < 0)
3098 if (!sk_X509_push(ctx->chain, curr)) {
3100 ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
3101 trust = X509_TRUST_REJECTED;
3102 ctx->error = X509_V_ERR_OUT_OF_MEM;
3105 } else if (num == ctx->num_untrusted) {
3107 * We have a self-signed certificate that has the same
3108 * subject name (and perhaps keyid and/or serial number) as
3109 * a trust anchor. We must have an exact match to avoid
3110 * possible impersonation via key substitution etc.
3112 if (X509_cmp(curr, issuer) != 0) {
3113 /* Self-signed untrusted mimic. */
3116 } else { /* curr "==" issuer */
3118 ctx->num_untrusted = --num;
3119 (void)sk_X509_set(ctx->chain, num, issuer);
3121 /* no need to update self_signed */
3126 * We've added a new trusted certificate to the chain, re-check
3127 * trust. If not done, and not self-signed look deeper.
3128 * Whether or not we're doing "trusted first", we no longer
3129 * look for untrusted certificates from the peer's chain.
3131 * At this point ctx->num_trusted and num must reflect the
3132 * correct number of untrusted certificates, since the DANE
3133 * logic in check_trust() depends on distinguishing CAs from
3134 * "the wire" from CAs from the trust store. In particular, the
3135 * certificate at depth "num" should be the new trusted
3136 * certificate with ctx->num_untrusted <= num.
3139 if (!ossl_assert(ctx->num_untrusted <= num))
3141 search &= ~S_DOUNTRUSTED;
3142 trust = check_trust(ctx, num);
3143 if (trust == X509_TRUST_TRUSTED
3144 || trust == X509_TRUST_REJECTED)
3152 * No dispositive decision, and either self-signed or no match, if
3153 * we were doing untrusted-first, and alt-chains are not disabled,
3154 * do that, by repeatedly losing one untrusted element at a time,
3155 * and trying to extend the shorted chain.
3157 if ((search & S_DOUNTRUSTED) == 0) {
3158 /* Continue search for a trusted issuer of a shorter chain? */
3159 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3161 /* Still no luck and no fallbacks left? */
3162 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
3163 ctx->num_untrusted < 2)
3165 /* Search for a trusted issuer of a shorter chain */
3166 search |= S_DOALTERNATE;
3167 alt_untrusted = ctx->num_untrusted - 1;
3173 * Extend chain with peer-provided untrusted certificates
3175 if ((search & S_DOUNTRUSTED) != 0) {
3176 num = sk_X509_num(ctx->chain);
3177 if (!ossl_assert(num == ctx->num_untrusted))
3179 curr = sk_X509_value(ctx->chain, num - 1);
3180 issuer = (self_signed || depth < num) ?
3181 NULL : find_issuer(ctx, sk_untrusted, curr);
3182 if (issuer == NULL) {
3184 * Once we have reached a self-signed cert or num exceeds depth
3185 * or can't find an issuer in the untrusted list we stop looking
3186 * there and start looking only in the trust store if enabled.
3188 search &= ~S_DOUNTRUSTED;
3190 search |= S_DOTRUSTED;
3194 /* Drop this issuer from future consideration */
3195 (void)sk_X509_delete_ptr(sk_untrusted, issuer);
3197 if (!X509_add_cert(ctx->chain, issuer, X509_ADD_FLAG_UP_REF))
3200 ++ctx->num_untrusted;
3202 if ((self_signed = X509_self_signed(curr, 0)) < 0)
3205 /* Check for DANE-TA trust of the topmost untrusted certificate. */
3206 trust = check_dane_issuer(ctx, ctx->num_untrusted - 1);
3207 if (trust == X509_TRUST_TRUSTED || trust == X509_TRUST_REJECTED)
3211 sk_X509_free(sk_untrusted);
3214 * Last chance to make a trusted chain, either bare DANE-TA public-key
3215 * signers, or else direct leaf PKIX trust.
3217 num = sk_X509_num(ctx->chain);
3219 if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3220 trust = check_dane_pkeys(ctx);
3221 if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3222 trust = check_trust(ctx, num);
3226 case X509_TRUST_TRUSTED:
3228 case X509_TRUST_REJECTED:
3229 /* Callback already issued */
3231 case X509_TRUST_UNTRUSTED:
3233 num = sk_X509_num(ctx->chain);
3234 CB_FAIL_IF(num > depth,
3235 ctx, NULL, num - 1, X509_V_ERR_CERT_CHAIN_TOO_LONG);
3236 CB_FAIL_IF(DANETLS_ENABLED(dane)
3237 && (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0),
3238 ctx, NULL, num - 1, X509_V_ERR_DANE_NO_MATCH);
3240 return verify_cb_cert(ctx, NULL, num - 1,
3241 sk_X509_num(ctx->chain) == 1
3242 ? X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
3243 : X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
3244 return verify_cb_cert(ctx, NULL, num - 1,
3245 ctx->num_untrusted < num
3246 ? X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
3247 : X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
3251 sk_X509_free(sk_untrusted);
3252 ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
3253 ctx->error = X509_V_ERR_UNSPECIFIED;
3257 static const int minbits_table[] = { 80, 112, 128, 192, 256 };
3258 static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
3261 * Check whether the public key of `cert` meets the security level of `ctx`.
3262 * Returns 1 on success, 0 otherwise.
3264 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert)
3266 EVP_PKEY *pkey = X509_get0_pubkey(cert);
3267 int level = ctx->param->auth_level;
3270 * At security level zero, return without checking for a supported public
3271 * key type. Some engines support key types not understood outside the
3272 * engine, and we only need to understand the key when enforcing a security
3278 /* Unsupported or malformed keys are not secure */
3282 if (level > NUM_AUTH_LEVELS)
3283 level = NUM_AUTH_LEVELS;
3285 return EVP_PKEY_security_bits(pkey) >= minbits_table[level - 1];
3289 * Check whether the public key of ``cert`` does not use explicit params
3290 * for an elliptic curve.
3292 * Returns 1 on success, 0 if check fails, -1 for other errors.
3294 static int check_curve(X509 *cert)
3296 #ifndef OPENSSL_NO_EC
3297 EVP_PKEY *pkey = X509_get0_pubkey(cert);
3299 /* Unsupported or malformed key */
3303 if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
3306 ret = EC_KEY_decoded_from_explicit_params(EVP_PKEY_get0_EC_KEY(pkey));
3307 return ret < 0 ? ret : !ret;
3315 * Check whether the signature digest algorithm of ``cert`` meets the security
3316 * level of ``ctx``. Should not be checked for trust anchors (whether
3317 * self-signed or otherwise).
3319 * Returns 1 on success, 0 otherwise.
3321 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
3324 int level = ctx->param->auth_level;
3328 if (level > NUM_AUTH_LEVELS)
3329 level = NUM_AUTH_LEVELS;
3331 if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
3334 return secbits >= minbits_table[level - 1];