2 * Copyright 1995-2020 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
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"
28 /* CRL score values */
30 /* No unhandled critical extensions */
32 #define CRL_SCORE_NOCRITICAL 0x100
34 /* certificate is within CRL scope */
36 #define CRL_SCORE_SCOPE 0x080
40 #define CRL_SCORE_TIME 0x040
42 /* Issuer name matches certificate */
44 #define CRL_SCORE_ISSUER_NAME 0x020
46 /* If this score or above CRL is probably valid */
48 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
50 /* CRL issuer is certificate issuer */
52 #define CRL_SCORE_ISSUER_CERT 0x018
54 /* CRL issuer is on certificate path */
56 #define CRL_SCORE_SAME_PATH 0x008
58 /* CRL issuer matches CRL AKID */
60 #define CRL_SCORE_AKID 0x004
62 /* Have a delta CRL with valid times */
64 #define CRL_SCORE_TIME_DELTA 0x002
66 static int build_chain(X509_STORE_CTX *ctx);
67 static int verify_chain(X509_STORE_CTX *ctx);
68 static int dane_verify(X509_STORE_CTX *ctx);
69 static int null_callback(int ok, X509_STORE_CTX *e);
70 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
71 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
72 static int check_chain_extensions(X509_STORE_CTX *ctx);
73 static int check_name_constraints(X509_STORE_CTX *ctx);
74 static int check_id(X509_STORE_CTX *ctx);
75 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
76 static int check_revocation(X509_STORE_CTX *ctx);
77 static int check_cert(X509_STORE_CTX *ctx);
78 static int check_policy(X509_STORE_CTX *ctx);
79 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
80 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
81 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert);
82 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert);
84 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
85 unsigned int *preasons, X509_CRL *crl, X509 *x);
86 static int get_crl_delta(X509_STORE_CTX *ctx,
87 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
88 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
89 int *pcrl_score, X509_CRL *base,
90 STACK_OF(X509_CRL) *crls);
91 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
93 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
94 unsigned int *preasons);
95 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
96 static int check_crl_chain(X509_STORE_CTX *ctx,
97 STACK_OF(X509) *cert_path,
98 STACK_OF(X509) *crl_path);
100 static int internal_verify(X509_STORE_CTX *ctx);
102 static int null_callback(int ok, X509_STORE_CTX *e)
107 /* Return 1 is a certificate is self signed, 0 if not, or -1 on error */
108 static int cert_self_signed(X509_STORE_CTX *ctx, X509 *x)
110 if (!X509v3_cache_extensions(x, ctx->libctx, ctx->propq))
113 if (x->ex_flags & EXFLAG_SS)
119 /* Given a certificate try and find an exact match in the store */
121 static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
123 STACK_OF(X509) *certs;
126 /* Lookup all certs with matching subject name */
127 certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
130 /* Look for exact match */
131 for (i = 0; i < sk_X509_num(certs); i++) {
132 xtmp = sk_X509_value(certs, i);
133 if (!X509_cmp(xtmp, x))
136 if (i < sk_X509_num(certs))
140 sk_X509_pop_free(certs, X509_free);
145 * Inform the verify callback of an error.
146 * If B<x> is not NULL it is the error cert, otherwise use the chain cert at
148 * If B<err> is not X509_V_OK, that's the error value, otherwise leave
149 * unchanged (presumably set by the caller).
151 * Returns 0 to abort verification with an error, non-zero to continue.
153 static int verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err)
155 ctx->error_depth = depth;
156 ctx->current_cert = (x != NULL) ? x : sk_X509_value(ctx->chain, depth);
157 if (err != X509_V_OK)
159 return ctx->verify_cb(0, ctx);
163 * Inform the verify callback of an error, CRL-specific variant. Here, the
164 * error depth and certificate are already set, we just specify the error
167 * Returns 0 to abort verification with an error, non-zero to continue.
169 static int verify_cb_crl(X509_STORE_CTX *ctx, int err)
172 return ctx->verify_cb(0, ctx);
175 static int check_auth_level(X509_STORE_CTX *ctx)
178 int num = sk_X509_num(ctx->chain);
180 if (ctx->param->auth_level <= 0)
183 for (i = 0; i < num; ++i) {
184 X509 *cert = sk_X509_value(ctx->chain, i);
187 * We've already checked the security of the leaf key, so here we only
188 * check the security of issuer keys.
190 if (i > 0 && !check_key_level(ctx, cert) &&
191 verify_cb_cert(ctx, cert, i, X509_V_ERR_CA_KEY_TOO_SMALL) == 0)
194 * We also check the signature algorithm security of all certificates
195 * except those of the trust anchor at index num-1.
197 if (i < num - 1 && !check_sig_level(ctx, cert) &&
198 verify_cb_cert(ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK) == 0)
204 static int verify_chain(X509_STORE_CTX *ctx)
210 * Before either returning with an error, or continuing with CRL checks,
211 * instantiate chain public key parameters.
213 if ((ok = build_chain(ctx)) == 0 ||
214 (ok = check_chain_extensions(ctx)) == 0 ||
215 (ok = check_auth_level(ctx)) == 0 ||
216 (ok = check_id(ctx)) == 0 || 1)
217 X509_get_pubkey_parameters(NULL, ctx->chain);
218 if (ok == 0 || (ok = ctx->check_revocation(ctx)) == 0)
221 err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
223 if (err != X509_V_OK) {
224 if ((ok = verify_cb_cert(ctx, NULL, ctx->error_depth, err)) == 0)
228 /* Verify chain signatures and expiration times */
229 ok = (ctx->verify != NULL) ? ctx->verify(ctx) : internal_verify(ctx);
233 if ((ok = check_name_constraints(ctx)) == 0)
236 #ifndef OPENSSL_NO_RFC3779
237 /* RFC 3779 path validation, now that CRL check has been done */
238 if ((ok = X509v3_asid_validate_path(ctx)) == 0)
240 if ((ok = X509v3_addr_validate_path(ctx)) == 0)
244 /* If we get this far evaluate policies */
245 if (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)
246 ok = ctx->check_policy(ctx);
250 int X509_verify_cert(X509_STORE_CTX *ctx)
252 SSL_DANE *dane = ctx->dane;
255 if (ctx->cert == NULL) {
256 X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
257 ctx->error = X509_V_ERR_INVALID_CALL;
261 if (ctx->chain != NULL) {
263 * This X509_STORE_CTX has already been used to verify a cert. We
264 * cannot do another one.
266 X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
267 ctx->error = X509_V_ERR_INVALID_CALL;
272 * first we make sure the chain we are going to build is present and that
273 * the first entry is in place
275 if (((ctx->chain = sk_X509_new_null()) == NULL) ||
276 (!sk_X509_push(ctx->chain, ctx->cert))) {
277 X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
278 ctx->error = X509_V_ERR_OUT_OF_MEM;
281 X509_up_ref(ctx->cert);
282 ctx->num_untrusted = 1;
284 /* If the peer's public key is too weak, we can stop early. */
285 if (!check_key_level(ctx, ctx->cert) &&
286 !verify_cb_cert(ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL))
289 if (DANETLS_ENABLED(dane))
290 ret = dane_verify(ctx);
292 ret = verify_chain(ctx);
295 * Safety-net. If we are returning an error, we must also set ctx->error,
296 * so that the chain is not considered verified should the error be ignored
297 * (e.g. TLS with SSL_VERIFY_NONE).
299 if (ret <= 0 && ctx->error == X509_V_OK)
300 ctx->error = X509_V_ERR_UNSPECIFIED;
305 * Given a STACK_OF(X509) find the issuer of cert (if any)
307 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
310 X509 *issuer, *rv = NULL;
312 for (i = 0; i < sk_X509_num(sk); i++) {
313 issuer = sk_X509_value(sk, i);
314 if (ctx->check_issued(ctx, x, issuer)) {
316 if (x509_check_cert_time(ctx, rv, -1))
323 /* Given a possible certificate and issuer check them */
325 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
331 ss = cert_self_signed(ctx, x);
337 ret = X509_check_issued(issuer, x);
338 if (ret == X509_V_OK) {
342 ss = cert_self_signed(ctx, x);
346 /* Special case: single self signed certificate */
347 if (ss > 0 && sk_X509_num(ctx->chain) == 1)
349 for (i = 0; i < sk_X509_num(ctx->chain); i++) {
350 ch = sk_X509_value(ctx->chain, i);
351 if (ch == issuer || !X509_cmp(ch, issuer)) {
352 ret = X509_V_ERR_PATH_LOOP;
358 return (ret == X509_V_OK);
361 /* Alternative lookup method: look from a STACK stored in other_ctx */
363 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
365 *issuer = find_issuer(ctx, ctx->other_ctx, x);
367 X509_up_ref(*issuer);
373 static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx,
376 STACK_OF(X509) *sk = NULL;
380 for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
381 x = sk_X509_value(ctx->other_ctx, i);
382 if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
384 sk = sk_X509_new_null();
385 if (sk == NULL || sk_X509_push(sk, x) == 0) {
386 sk_X509_pop_free(sk, X509_free);
387 X509err(X509_F_LOOKUP_CERTS_SK, ERR_R_MALLOC_FAILURE);
388 ctx->error = X509_V_ERR_OUT_OF_MEM;
398 * Check EE or CA certificate purpose. For trusted certificates explicit local
399 * auxiliary trust can be used to override EKU-restrictions.
401 static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth,
404 int tr_ok = X509_TRUST_UNTRUSTED;
407 * For trusted certificates we want to see whether any auxiliary trust
408 * settings trump the purpose constraints.
410 * This is complicated by the fact that the trust ordinals in
411 * ctx->param->trust are entirely independent of the purpose ordinals in
412 * ctx->param->purpose!
414 * What connects them is their mutual initialization via calls from
415 * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets
416 * related values of both param->trust and param->purpose. It is however
417 * typically possible to infer associated trust values from a purpose value
418 * via the X509_PURPOSE API.
420 * Therefore, we can only check for trust overrides when the purpose we're
421 * checking is the same as ctx->param->purpose and ctx->param->trust is
424 if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
425 tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
428 case X509_TRUST_TRUSTED:
430 case X509_TRUST_REJECTED:
433 switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
439 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
445 return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE);
449 * Check a certificate chains extensions for consistency with the supplied
453 static int check_chain_extensions(X509_STORE_CTX *ctx)
455 int i, must_be_ca, plen = 0;
457 int proxy_path_length = 0;
459 int allow_proxy_certs;
460 int num = sk_X509_num(ctx->chain);
463 * must_be_ca can have 1 of 3 values:
464 * -1: we accept both CA and non-CA certificates, to allow direct
465 * use of self-signed certificates (which are marked as CA).
466 * 0: we only accept non-CA certificates. This is currently not
467 * used, but the possibility is present for future extensions.
468 * 1: we only accept CA certificates. This is currently used for
469 * all certificates in the chain except the leaf certificate.
473 /* CRL path validation */
475 allow_proxy_certs = 0;
476 purpose = X509_PURPOSE_CRL_SIGN;
479 ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
480 purpose = ctx->param->purpose;
483 for (i = 0; i < num; i++) {
485 x = sk_X509_value(ctx->chain, i);
486 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
487 && (x->ex_flags & EXFLAG_CRITICAL)) {
488 if (!verify_cb_cert(ctx, x, i,
489 X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION))
492 if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
493 if (!verify_cb_cert(ctx, x, i,
494 X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED))
497 ret = X509_check_ca(x);
498 switch (must_be_ca) {
500 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
501 && (ret != 1) && (ret != 0)) {
503 ctx->error = X509_V_ERR_INVALID_CA;
510 ctx->error = X509_V_ERR_INVALID_NON_CA;
515 /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */
517 || ((i + 1 < num || ctx->param->flags & X509_V_FLAG_X509_STRICT)
520 ctx->error = X509_V_ERR_INVALID_CA;
525 if ((x->ex_flags & EXFLAG_CA) == 0
526 && x->ex_pathlen != -1
527 && (ctx->param->flags & X509_V_FLAG_X509_STRICT)) {
528 ctx->error = X509_V_ERR_INVALID_EXTENSION;
531 if (ret == 0 && !verify_cb_cert(ctx, x, i, X509_V_OK))
533 /* check_purpose() makes the callback as needed */
534 if (purpose > 0 && !check_purpose(ctx, x, purpose, i, must_be_ca))
537 if ((i > 1) && (x->ex_pathlen != -1)
538 && (plen > (x->ex_pathlen + proxy_path_length))) {
539 if (!verify_cb_cert(ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED))
542 /* Increment path length if not a self issued intermediate CA */
543 if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0)
546 * If this certificate is a proxy certificate, the next certificate
547 * must be another proxy certificate or a EE certificate. If not,
548 * the next certificate must be a CA certificate.
550 if (x->ex_flags & EXFLAG_PROXY) {
552 * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint
553 * is less than max_path_length, the former should be copied to
554 * the latter, and 4.1.4 (a) stipulates that max_path_length
555 * should be verified to be larger than zero and decrement it.
557 * Because we're checking the certs in the reverse order, we start
558 * with verifying that proxy_path_length isn't larger than pcPLC,
559 * and copy the latter to the former if it is, and finally,
560 * increment proxy_path_length.
562 if (x->ex_pcpathlen != -1) {
563 if (proxy_path_length > x->ex_pcpathlen) {
564 if (!verify_cb_cert(ctx, x, i,
565 X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED))
568 proxy_path_length = x->ex_pcpathlen;
578 static int has_san_id(X509 *x, int gtype)
582 GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
587 for (i = 0; i < sk_GENERAL_NAME_num(gs); i++) {
588 GENERAL_NAME *g = sk_GENERAL_NAME_value(gs, i);
590 if (g->type == gtype) {
595 GENERAL_NAMES_free(gs);
599 static int check_name_constraints(X509_STORE_CTX *ctx)
603 /* Check name constraints for all certificates */
604 for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
605 X509 *x = sk_X509_value(ctx->chain, i);
608 /* Ignore self issued certs unless last in chain */
609 if (i && (x->ex_flags & EXFLAG_SI))
613 * Proxy certificates policy has an extra constraint, where the
614 * certificate subject MUST be the issuer with a single CN entry
616 * (RFC 3820: 3.4, 4.1.3 (a)(4))
618 if (x->ex_flags & EXFLAG_PROXY) {
619 X509_NAME *tmpsubject = X509_get_subject_name(x);
620 X509_NAME *tmpissuer = X509_get_issuer_name(x);
621 X509_NAME_ENTRY *tmpentry = NULL;
622 int last_object_nid = 0;
624 int last_object_loc = X509_NAME_entry_count(tmpsubject) - 1;
626 /* Check that there are at least two RDNs */
627 if (last_object_loc < 1) {
628 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
629 goto proxy_name_done;
633 * Check that there is exactly one more RDN in subject as
634 * there is in issuer.
636 if (X509_NAME_entry_count(tmpsubject)
637 != X509_NAME_entry_count(tmpissuer) + 1) {
638 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
639 goto proxy_name_done;
643 * Check that the last subject component isn't part of a
646 if (X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
648 == X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
649 last_object_loc - 1))) {
650 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
651 goto proxy_name_done;
655 * Check that the last subject RDN is a commonName, and that
656 * all the previous RDNs match the issuer exactly
658 tmpsubject = X509_NAME_dup(tmpsubject);
659 if (tmpsubject == NULL) {
660 X509err(X509_F_CHECK_NAME_CONSTRAINTS, ERR_R_MALLOC_FAILURE);
661 ctx->error = X509_V_ERR_OUT_OF_MEM;
666 X509_NAME_delete_entry(tmpsubject, last_object_loc);
668 OBJ_obj2nid(X509_NAME_ENTRY_get_object(tmpentry));
670 if (last_object_nid != NID_commonName
671 || X509_NAME_cmp(tmpsubject, tmpissuer) != 0) {
672 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
675 X509_NAME_ENTRY_free(tmpentry);
676 X509_NAME_free(tmpsubject);
680 && !verify_cb_cert(ctx, x, i, err))
685 * Check against constraints for all certificates higher in chain
686 * including trust anchor. Trust anchor not strictly speaking needed
687 * but if it includes constraints it is to be assumed it expects them
690 for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
691 NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
694 int rv = NAME_CONSTRAINTS_check(x, nc);
696 /* If EE certificate check commonName too */
697 if (rv == X509_V_OK && i == 0
698 && (ctx->param->hostflags
699 & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) == 0
700 && ((ctx->param->hostflags
701 & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) != 0
702 || !has_san_id(x, GEN_DNS)))
703 rv = NAME_CONSTRAINTS_check_CN(x, nc);
708 case X509_V_ERR_OUT_OF_MEM:
711 if (!verify_cb_cert(ctx, x, i, rv))
721 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
723 return verify_cb_cert(ctx, ctx->cert, 0, errcode);
726 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
729 int n = sk_OPENSSL_STRING_num(vpm->hosts);
732 if (vpm->peername != NULL) {
733 OPENSSL_free(vpm->peername);
734 vpm->peername = NULL;
736 for (i = 0; i < n; ++i) {
737 name = sk_OPENSSL_STRING_value(vpm->hosts, i);
738 if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
744 static int check_id(X509_STORE_CTX *ctx)
746 X509_VERIFY_PARAM *vpm = ctx->param;
748 if (vpm->hosts && check_hosts(x, vpm) <= 0) {
749 if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
752 if (vpm->email && 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 && 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 if (!verify_cb_cert(ctx, x, i, X509_V_ERR_CERT_REJECTED))
846 return X509_TRUST_REJECTED;
847 return X509_TRUST_UNTRUSTED;
850 if (!DANETLS_ENABLED(dane))
851 return X509_TRUST_TRUSTED;
853 dane->pdpth = num_untrusted;
854 /* With DANE, PKIX alone is not trusted until we have both */
855 if (dane->mdpth >= 0)
856 return X509_TRUST_TRUSTED;
857 return X509_TRUST_UNTRUSTED;
860 static int check_revocation(X509_STORE_CTX *ctx)
862 int i = 0, last = 0, ok = 0;
863 if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
865 if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
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)
897 while (ctx->current_reasons != CRLDP_ALL_REASONS) {
898 unsigned int last_reasons = ctx->current_reasons;
900 /* Try to retrieve relevant CRL */
902 ok = ctx->get_crl(ctx, &crl, x);
904 ok = get_crl_delta(ctx, &crl, &dcrl, x);
906 * If error looking up CRL, nothing we can do except notify callback
909 ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
912 ctx->current_crl = crl;
913 ok = ctx->check_crl(ctx, crl);
918 ok = ctx->check_crl(ctx, dcrl);
921 ok = ctx->cert_crl(ctx, dcrl, x);
927 /* Don't look in full CRL if delta reason is removefromCRL */
929 ok = ctx->cert_crl(ctx, crl, x);
939 * If reasons not updated we won't get anywhere by another iteration,
942 if (last_reasons == ctx->current_reasons) {
943 ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
951 ctx->current_crl = NULL;
955 /* Check CRL times against values in X509_STORE_CTX */
957 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
963 ctx->current_crl = crl;
964 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
965 ptime = &ctx->param->check_time;
966 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
971 i = X509_cmp_time(X509_CRL_get0_lastUpdate(crl), ptime);
975 if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD))
982 if (!verify_cb_crl(ctx, X509_V_ERR_CRL_NOT_YET_VALID))
986 if (X509_CRL_get0_nextUpdate(crl)) {
987 i = X509_cmp_time(X509_CRL_get0_nextUpdate(crl), ptime);
992 if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD))
995 /* Ignore expiry of base CRL is delta is valid */
996 if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
999 if (!verify_cb_crl(ctx, X509_V_ERR_CRL_HAS_EXPIRED))
1005 ctx->current_crl = NULL;
1010 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1011 X509 **pissuer, int *pscore, unsigned int *preasons,
1012 STACK_OF(X509_CRL) *crls)
1014 int i, crl_score, best_score = *pscore;
1015 unsigned int reasons, best_reasons = 0;
1016 X509 *x = ctx->current_cert;
1017 X509_CRL *crl, *best_crl = NULL;
1018 X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1020 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1021 crl = sk_X509_CRL_value(crls, i);
1022 reasons = *preasons;
1023 crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1024 if (crl_score < best_score || crl_score == 0)
1026 /* If current CRL is equivalent use it if it is newer */
1027 if (crl_score == best_score && best_crl != NULL) {
1029 if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl),
1030 X509_CRL_get0_lastUpdate(crl)) == 0)
1033 * ASN1_TIME_diff never returns inconsistent signs for |day|
1036 if (day <= 0 && sec <= 0)
1040 best_crl_issuer = crl_issuer;
1041 best_score = crl_score;
1042 best_reasons = reasons;
1046 X509_CRL_free(*pcrl);
1048 *pissuer = best_crl_issuer;
1049 *pscore = best_score;
1050 *preasons = best_reasons;
1051 X509_CRL_up_ref(best_crl);
1052 X509_CRL_free(*pdcrl);
1054 get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1057 if (best_score >= CRL_SCORE_VALID)
1064 * Compare two CRL extensions for delta checking purposes. They should be
1065 * both present or both absent. If both present all fields must be identical.
1068 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1070 ASN1_OCTET_STRING *exta, *extb;
1072 i = X509_CRL_get_ext_by_NID(a, nid, -1);
1074 /* Can't have multiple occurrences */
1075 if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1077 exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1081 i = X509_CRL_get_ext_by_NID(b, nid, -1);
1085 if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1087 extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1097 if (ASN1_OCTET_STRING_cmp(exta, extb))
1103 /* See if a base and delta are compatible */
1105 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
1107 /* Delta CRL must be a delta */
1108 if (!delta->base_crl_number)
1110 /* Base must have a CRL number */
1111 if (!base->crl_number)
1113 /* Issuer names must match */
1114 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
1116 /* AKID and IDP must match */
1117 if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1119 if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1121 /* Delta CRL base number must not exceed Full CRL number. */
1122 if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1124 /* Delta CRL number must exceed full CRL number */
1125 if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
1131 * For a given base CRL find a delta... maybe extend to delta scoring or
1132 * retrieve a chain of deltas...
1135 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
1136 X509_CRL *base, STACK_OF(X509_CRL) *crls)
1140 if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
1142 if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
1144 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1145 delta = sk_X509_CRL_value(crls, i);
1146 if (check_delta_base(delta, base)) {
1147 if (check_crl_time(ctx, delta, 0))
1148 *pscore |= CRL_SCORE_TIME_DELTA;
1149 X509_CRL_up_ref(delta);
1158 * For a given CRL return how suitable it is for the supplied certificate
1159 * 'x'. The return value is a mask of several criteria. If the issuer is not
1160 * the certificate issuer this is returned in *pissuer. The reasons mask is
1161 * also used to determine if the CRL is suitable: if no new reasons the CRL
1162 * is rejected, otherwise reasons is updated.
1165 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1166 unsigned int *preasons, X509_CRL *crl, X509 *x)
1170 unsigned int tmp_reasons = *preasons, crl_reasons;
1172 /* First see if we can reject CRL straight away */
1174 /* Invalid IDP cannot be processed */
1175 if (crl->idp_flags & IDP_INVALID)
1177 /* Reason codes or indirect CRLs need extended CRL support */
1178 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1179 if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1181 } else if (crl->idp_flags & IDP_REASONS) {
1182 /* If no new reasons reject */
1183 if (!(crl->idp_reasons & ~tmp_reasons))
1186 /* Don't process deltas at this stage */
1187 else if (crl->base_crl_number)
1189 /* If issuer name doesn't match certificate need indirect CRL */
1190 if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1191 if (!(crl->idp_flags & IDP_INDIRECT))
1194 crl_score |= CRL_SCORE_ISSUER_NAME;
1196 if (!(crl->flags & EXFLAG_CRITICAL))
1197 crl_score |= CRL_SCORE_NOCRITICAL;
1200 if (check_crl_time(ctx, crl, 0))
1201 crl_score |= CRL_SCORE_TIME;
1203 /* Check authority key ID and locate certificate issuer */
1204 crl_akid_check(ctx, crl, pissuer, &crl_score);
1206 /* If we can't locate certificate issuer at this point forget it */
1208 if (!(crl_score & CRL_SCORE_AKID))
1211 /* Check cert for matching CRL distribution points */
1213 if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1214 /* If no new reasons reject */
1215 if (!(crl_reasons & ~tmp_reasons))
1217 tmp_reasons |= crl_reasons;
1218 crl_score |= CRL_SCORE_SCOPE;
1221 *preasons = tmp_reasons;
1227 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1228 X509 **pissuer, int *pcrl_score)
1230 X509 *crl_issuer = NULL;
1231 const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1232 int cidx = ctx->error_depth;
1235 if (cidx != sk_X509_num(ctx->chain) - 1)
1238 crl_issuer = sk_X509_value(ctx->chain, cidx);
1240 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1241 if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1242 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1243 *pissuer = crl_issuer;
1248 for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1249 crl_issuer = sk_X509_value(ctx->chain, cidx);
1250 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1252 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1253 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1254 *pissuer = crl_issuer;
1259 /* Anything else needs extended CRL support */
1261 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1265 * Otherwise the CRL issuer is not on the path. Look for it in the set of
1266 * untrusted certificates.
1268 for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1269 crl_issuer = sk_X509_value(ctx->untrusted, i);
1270 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1272 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1273 *pissuer = crl_issuer;
1274 *pcrl_score |= CRL_SCORE_AKID;
1281 * Check the path of a CRL issuer certificate. This creates a new
1282 * X509_STORE_CTX and populates it with most of the parameters from the
1283 * parent. This could be optimised somewhat since a lot of path checking will
1284 * be duplicated by the parent, but this will rarely be used in practice.
1287 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1289 X509_STORE_CTX crl_ctx;
1292 /* Don't allow recursive CRL path validation */
1295 if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted))
1298 crl_ctx.crls = ctx->crls;
1299 /* Copy verify params across */
1300 X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1302 crl_ctx.parent = ctx;
1303 crl_ctx.verify_cb = ctx->verify_cb;
1305 /* Verify CRL issuer */
1306 ret = X509_verify_cert(&crl_ctx);
1310 /* Check chain is acceptable */
1311 ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1313 X509_STORE_CTX_cleanup(&crl_ctx);
1318 * RFC3280 says nothing about the relationship between CRL path and
1319 * certificate path, which could lead to situations where a certificate could
1320 * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1321 * strict and states that the two paths must end in the same trust anchor,
1322 * though some discussions remain... until this is resolved we use the
1326 static int check_crl_chain(X509_STORE_CTX *ctx,
1327 STACK_OF(X509) *cert_path,
1328 STACK_OF(X509) *crl_path)
1330 X509 *cert_ta, *crl_ta;
1331 cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1332 crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1333 if (!X509_cmp(cert_ta, crl_ta))
1339 * Check for match between two dist point names: three separate cases.
1340 * 1. Both are relative names and compare X509_NAME types.
1341 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1342 * 3. Both are full names and compare two GENERAL_NAMES.
1343 * 4. One is NULL: automatic match.
1346 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1348 X509_NAME *nm = NULL;
1349 GENERAL_NAMES *gens = NULL;
1350 GENERAL_NAME *gena, *genb;
1357 /* Case 1: two X509_NAME */
1361 if (!X509_NAME_cmp(a->dpname, b->dpname))
1366 /* Case 2: set name and GENERAL_NAMES appropriately */
1368 gens = b->name.fullname;
1369 } else if (b->type == 1) {
1372 /* Case 2: set name and GENERAL_NAMES appropriately */
1373 gens = a->name.fullname;
1377 /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1379 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1380 gena = sk_GENERAL_NAME_value(gens, i);
1381 if (gena->type != GEN_DIRNAME)
1383 if (!X509_NAME_cmp(nm, gena->d.directoryName))
1389 /* Else case 3: two GENERAL_NAMES */
1391 for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1392 gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1393 for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1394 genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1395 if (!GENERAL_NAME_cmp(gena, genb))
1404 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1407 const X509_NAME *nm = X509_CRL_get_issuer(crl);
1408 /* If no CRLissuer return is successful iff don't need a match */
1410 return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1411 for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1412 GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1413 if (gen->type != GEN_DIRNAME)
1415 if (!X509_NAME_cmp(gen->d.directoryName, nm))
1421 /* Check CRLDP and IDP */
1423 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1424 unsigned int *preasons)
1427 if (crl->idp_flags & IDP_ONLYATTR)
1429 if (x->ex_flags & EXFLAG_CA) {
1430 if (crl->idp_flags & IDP_ONLYUSER)
1433 if (crl->idp_flags & IDP_ONLYCA)
1436 *preasons = crl->idp_reasons;
1437 for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1438 DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1439 if (crldp_check_crlissuer(dp, crl, crl_score)) {
1440 if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1441 *preasons &= dp->dp_reasons;
1446 if ((!crl->idp || !crl->idp->distpoint)
1447 && (crl_score & CRL_SCORE_ISSUER_NAME))
1453 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1454 * to find a delta CRL too
1457 static int get_crl_delta(X509_STORE_CTX *ctx,
1458 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1461 X509 *issuer = NULL;
1463 unsigned int reasons;
1464 X509_CRL *crl = NULL, *dcrl = NULL;
1465 STACK_OF(X509_CRL) *skcrl;
1466 const X509_NAME *nm = X509_get_issuer_name(x);
1468 reasons = ctx->current_reasons;
1469 ok = get_crl_sk(ctx, &crl, &dcrl,
1470 &issuer, &crl_score, &reasons, ctx->crls);
1474 /* Lookup CRLs from store */
1476 skcrl = ctx->lookup_crls(ctx, nm);
1478 /* If no CRLs found and a near match from get_crl_sk use that */
1482 get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1484 sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1487 /* If we got any kind of CRL use it and return success */
1489 ctx->current_issuer = issuer;
1490 ctx->current_crl_score = crl_score;
1491 ctx->current_reasons = reasons;
1499 /* Check CRL validity */
1500 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1502 X509 *issuer = NULL;
1503 EVP_PKEY *ikey = NULL;
1504 int cnum = ctx->error_depth;
1505 int chnum = sk_X509_num(ctx->chain) - 1;
1507 /* if we have an alternative CRL issuer cert use that */
1508 if (ctx->current_issuer)
1509 issuer = ctx->current_issuer;
1511 * Else find CRL issuer: if not last certificate then issuer is next
1512 * certificate in chain.
1514 else if (cnum < chnum)
1515 issuer = sk_X509_value(ctx->chain, cnum + 1);
1517 issuer = sk_X509_value(ctx->chain, chnum);
1518 /* If not self signed, can't check signature */
1519 if (!ctx->check_issued(ctx, issuer, issuer) &&
1520 !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
1528 * Skip most tests for deltas because they have already been done
1530 if (!crl->base_crl_number) {
1531 /* Check for cRLSign bit if keyUsage present */
1532 if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1533 !(issuer->ex_kusage & KU_CRL_SIGN) &&
1534 !verify_cb_crl(ctx, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN))
1537 if (!(ctx->current_crl_score & CRL_SCORE_SCOPE) &&
1538 !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
1541 if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH) &&
1542 check_crl_path(ctx, ctx->current_issuer) <= 0 &&
1543 !verify_cb_crl(ctx, X509_V_ERR_CRL_PATH_VALIDATION_ERROR))
1546 if ((crl->idp_flags & IDP_INVALID) &&
1547 !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
1551 if (!(ctx->current_crl_score & CRL_SCORE_TIME) &&
1552 !check_crl_time(ctx, crl, 1))
1555 /* Attempt to get issuer certificate public key */
1556 ikey = X509_get0_pubkey(issuer);
1559 !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1563 int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1565 if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
1567 /* Verify CRL signature */
1568 if (X509_CRL_verify(crl, ikey) <= 0 &&
1569 !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
1575 /* Check certificate against CRL */
1576 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1581 * The rules changed for this... previously if a CRL contained unhandled
1582 * critical extensions it could still be used to indicate a certificate
1583 * was revoked. This has since been changed since critical extensions can
1584 * change the meaning of CRL entries.
1586 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
1587 && (crl->flags & EXFLAG_CRITICAL) &&
1588 !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
1591 * Look for serial number of certificate in CRL. If found, make sure
1592 * reason is not removeFromCRL.
1594 if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1595 if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1597 if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
1604 static int check_policy(X509_STORE_CTX *ctx)
1611 * With DANE, the trust anchor might be a bare public key, not a
1612 * certificate! In that case our chain does not have the trust anchor
1613 * certificate as a top-most element. This comports well with RFC5280
1614 * chain verification, since there too, the trust anchor is not part of the
1615 * chain to be verified. In particular, X509_policy_check() does not look
1616 * at the TA cert, but assumes that it is present as the top-most chain
1617 * element. We therefore temporarily push a NULL cert onto the chain if it
1618 * was verified via a bare public key, and pop it off right after the
1619 * X509_policy_check() call.
1621 if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
1622 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1623 ctx->error = X509_V_ERR_OUT_OF_MEM;
1626 ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1627 ctx->param->policies, ctx->param->flags);
1628 if (ctx->bare_ta_signed)
1629 sk_X509_pop(ctx->chain);
1631 if (ret == X509_PCY_TREE_INTERNAL) {
1632 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1633 ctx->error = X509_V_ERR_OUT_OF_MEM;
1636 /* Invalid or inconsistent extensions */
1637 if (ret == X509_PCY_TREE_INVALID) {
1640 /* Locate certificates with bad extensions and notify callback. */
1641 for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1642 X509 *x = sk_X509_value(ctx->chain, i);
1644 if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1646 if (!verify_cb_cert(ctx, x, i,
1647 X509_V_ERR_INVALID_POLICY_EXTENSION))
1652 if (ret == X509_PCY_TREE_FAILURE) {
1653 ctx->current_cert = NULL;
1654 ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1655 return ctx->verify_cb(0, ctx);
1657 if (ret != X509_PCY_TREE_VALID) {
1658 X509err(X509_F_CHECK_POLICY, ERR_R_INTERNAL_ERROR);
1662 if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1663 ctx->current_cert = NULL;
1665 * Verification errors need to be "sticky", a callback may have allowed
1666 * an SSL handshake to continue despite an error, and we must then
1667 * remain in an error state. Therefore, we MUST NOT clear earlier
1668 * verification errors by setting the error to X509_V_OK.
1670 if (!ctx->verify_cb(2, ctx))
1678 * Check certificate validity times.
1679 * If depth >= 0, invoke verification callbacks on error, otherwise just return
1680 * the validation status.
1682 * Return 1 on success, 0 otherwise.
1684 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1689 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1690 ptime = &ctx->param->check_time;
1691 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1696 i = X509_cmp_time(X509_get0_notBefore(x), ptime);
1697 if (i >= 0 && depth < 0)
1699 if (i == 0 && !verify_cb_cert(ctx, x, depth,
1700 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD))
1702 if (i > 0 && !verify_cb_cert(ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID))
1705 i = X509_cmp_time(X509_get0_notAfter(x), ptime);
1706 if (i <= 0 && depth < 0)
1708 if (i == 0 && !verify_cb_cert(ctx, x, depth,
1709 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD))
1711 if (i < 0 && !verify_cb_cert(ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED))
1716 static int internal_verify(X509_STORE_CTX *ctx)
1718 int n = sk_X509_num(ctx->chain) - 1;
1719 X509 *xi = sk_X509_value(ctx->chain, n);
1723 * With DANE-verified bare public key TA signatures, it remains only to
1724 * check the timestamps of the top certificate. We report the issuer as
1725 * NULL, since all we have is a bare key.
1727 if (ctx->bare_ta_signed) {
1733 if (ctx->check_issued(ctx, xi, xi))
1736 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1741 return verify_cb_cert(ctx, xi, 0,
1742 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1744 ctx->error_depth = n;
1745 xs = sk_X509_value(ctx->chain, n);
1749 * Do not clear ctx->error=0, it must be "sticky", only the user's callback
1750 * is allowed to reset errors (at its own peril).
1756 * Skip signature check for self signed certificates unless explicitly
1757 * asked for. It doesn't add any security and just wastes time. If
1758 * the issuer's public key is unusable, report the issuer certificate
1759 * and its depth (rather than the depth of the subject).
1761 if (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)) {
1762 if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1763 if (!verify_cb_cert(ctx, xi, xi != xs ? n+1 : n,
1764 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1766 } else if (X509_verify_ex(xs, pkey, ctx->libctx, ctx->propq) <= 0) {
1767 if (!verify_cb_cert(ctx, xs, n,
1768 X509_V_ERR_CERT_SIGNATURE_FAILURE))
1774 /* Calls verify callback as needed */
1775 if (!x509_check_cert_time(ctx, xs, n))
1779 * Signal success at this depth. However, the previous error (if any)
1782 ctx->current_issuer = xi;
1783 ctx->current_cert = xs;
1784 ctx->error_depth = n;
1785 if (!ctx->verify_cb(1, ctx))
1790 xs = sk_X509_value(ctx->chain, n);
1796 int X509_cmp_current_time(const ASN1_TIME *ctm)
1798 return X509_cmp_time(ctm, NULL);
1801 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1803 static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
1804 static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
1805 ASN1_TIME *asn1_cmp_time = NULL;
1806 int i, day, sec, ret = 0;
1807 #ifdef CHARSET_EBCDIC
1808 const char upper_z = 0x5A;
1810 const char upper_z = 'Z';
1813 * Note that ASN.1 allows much more slack in the time format than RFC5280.
1814 * In RFC5280, the representation is fixed:
1815 * UTCTime: YYMMDDHHMMSSZ
1816 * GeneralizedTime: YYYYMMDDHHMMSSZ
1818 * We do NOT currently enforce the following RFC 5280 requirement:
1819 * "CAs conforming to this profile MUST always encode certificate
1820 * validity dates through the year 2049 as UTCTime; certificate validity
1821 * dates in 2050 or later MUST be encoded as GeneralizedTime."
1823 switch (ctm->type) {
1824 case V_ASN1_UTCTIME:
1825 if (ctm->length != (int)(utctime_length))
1828 case V_ASN1_GENERALIZEDTIME:
1829 if (ctm->length != (int)(generalizedtime_length))
1837 * Verify the format: the ASN.1 functions we use below allow a more
1838 * flexible format than what's mandated by RFC 5280.
1839 * Digit and date ranges will be verified in the conversion methods.
1841 for (i = 0; i < ctm->length - 1; i++) {
1842 if (!ascii_isdigit(ctm->data[i]))
1845 if (ctm->data[ctm->length - 1] != upper_z)
1849 * There is ASN1_UTCTIME_cmp_time_t but no
1850 * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
1851 * so we go through ASN.1
1853 asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
1854 if (asn1_cmp_time == NULL)
1856 if (!ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time))
1860 * X509_cmp_time comparison is <=.
1861 * The return value 0 is reserved for errors.
1863 ret = (day >= 0 && sec >= 0) ? -1 : 1;
1866 ASN1_TIME_free(asn1_cmp_time);
1871 * Return 0 if time should not be checked or reference time is in range,
1872 * or else 1 if it is past the end, or -1 if it is before the start
1874 int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
1875 const ASN1_TIME *start, const ASN1_TIME *end)
1878 time_t *time = NULL;
1879 unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
1881 if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
1882 ref_time = X509_VERIFY_PARAM_get_time(vpm);
1884 } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
1885 return 0; /* this means ok */
1886 } /* else reference time is the current time */
1888 if (end != NULL && X509_cmp_time(end, time) < 0)
1890 if (start != NULL && X509_cmp_time(start, time) > 0)
1895 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1897 return X509_time_adj(s, adj, NULL);
1900 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1902 return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1905 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1906 int offset_day, long offset_sec, time_t *in_tm)
1915 if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1916 if (s->type == V_ASN1_UTCTIME)
1917 return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1918 if (s->type == V_ASN1_GENERALIZEDTIME)
1919 return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1921 return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1924 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1926 EVP_PKEY *ktmp = NULL, *ktmp2;
1929 if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1932 for (i = 0; i < sk_X509_num(chain); i++) {
1933 ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1935 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1936 X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1939 if (!EVP_PKEY_missing_parameters(ktmp))
1943 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1944 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1948 /* first, populate the other certs */
1949 for (j = i - 1; j >= 0; j--) {
1950 ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1951 EVP_PKEY_copy_parameters(ktmp2, ktmp);
1955 EVP_PKEY_copy_parameters(pkey, ktmp);
1959 /* Make a delta CRL as the diff between two full CRLs */
1961 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1962 EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1964 X509_CRL *crl = NULL;
1966 STACK_OF(X509_REVOKED) *revs = NULL;
1967 /* CRLs can't be delta already */
1968 if (base->base_crl_number || newer->base_crl_number) {
1969 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1972 /* Base and new CRL must have a CRL number */
1973 if (!base->crl_number || !newer->crl_number) {
1974 X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1977 /* Issuer names must match */
1978 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
1979 X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
1982 /* AKID and IDP must match */
1983 if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1984 X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
1987 if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1988 X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
1991 /* Newer CRL number must exceed full CRL number */
1992 if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1993 X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
1996 /* CRLs must verify */
1997 if (skey && (X509_CRL_verify(base, skey) <= 0 ||
1998 X509_CRL_verify(newer, skey) <= 0)) {
1999 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
2002 /* Create new CRL */
2003 crl = X509_CRL_new();
2004 if (crl == NULL || !X509_CRL_set_version(crl, 1))
2006 /* Set issuer name */
2007 if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
2010 if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer)))
2012 if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer)))
2015 /* Set base CRL number: must be critical */
2017 if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
2021 * Copy extensions across from newest CRL to delta: this will set CRL
2022 * number to correct value too.
2025 for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2026 X509_EXTENSION *ext;
2027 ext = X509_CRL_get_ext(newer, i);
2028 if (!X509_CRL_add_ext(crl, ext, -1))
2032 /* Go through revoked entries, copying as needed */
2034 revs = X509_CRL_get_REVOKED(newer);
2036 for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2037 X509_REVOKED *rvn, *rvtmp;
2038 rvn = sk_X509_REVOKED_value(revs, i);
2040 * Add only if not also in base. TODO: need something cleverer here
2041 * for some more complex CRLs covering multiple CAs.
2043 if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2044 rvtmp = X509_REVOKED_dup(rvn);
2047 if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2048 X509_REVOKED_free(rvtmp);
2053 /* TODO: optionally prune deleted entries */
2055 if (skey && md && !X509_CRL_sign(crl, skey, md))
2061 X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
2066 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2068 return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2071 void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2073 return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2076 int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2081 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2086 int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2088 return ctx->error_depth;
2091 void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2093 ctx->error_depth = depth;
2096 X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2098 return ctx->current_cert;
2101 void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2103 ctx->current_cert = x;
2106 STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2111 STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2115 return X509_chain_up_ref(ctx->chain);
2118 X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2120 return ctx->current_issuer;
2123 X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2125 return ctx->current_crl;
2128 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2133 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2138 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2143 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2146 * XXX: Why isn't this function always used to set the associated trust?
2147 * Should there even be a VPM->trust field at all? Or should the trust
2148 * always be inferred from the purpose by X509_STORE_CTX_init().
2150 return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2153 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2156 * XXX: See above, this function would only be needed when the default
2157 * trust for the purpose needs an override in a corner case.
2159 return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2163 * This function is used to set the X509_STORE_CTX purpose and trust values.
2164 * This is intended to be used when another structure has its own trust and
2165 * purpose values which (if set) will be inherited by the ctx. If they aren't
2166 * set then we will usually have a default purpose in mind which should then
2167 * be used to set the trust value. An example of this is SSL use: an SSL
2168 * structure will have its own purpose and trust settings which the
2169 * application can set: if they aren't set then we use the default of SSL
2173 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2174 int purpose, int trust)
2177 /* If purpose not set use default */
2179 purpose = def_purpose;
2180 /* If we have a purpose then check it is valid */
2183 idx = X509_PURPOSE_get_by_id(purpose);
2185 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2186 X509_R_UNKNOWN_PURPOSE_ID);
2189 ptmp = X509_PURPOSE_get0(idx);
2190 if (ptmp->trust == X509_TRUST_DEFAULT) {
2191 idx = X509_PURPOSE_get_by_id(def_purpose);
2193 * XXX: In the two callers above def_purpose is always 0, which is
2194 * not a known value, so idx will always be -1. How is the
2195 * X509_TRUST_DEFAULT case actually supposed to be handled?
2198 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2199 X509_R_UNKNOWN_PURPOSE_ID);
2202 ptmp = X509_PURPOSE_get0(idx);
2204 /* If trust not set then get from purpose default */
2206 trust = ptmp->trust;
2209 idx = X509_TRUST_get_by_id(trust);
2211 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2212 X509_R_UNKNOWN_TRUST_ID);
2217 if (purpose && !ctx->param->purpose)
2218 ctx->param->purpose = purpose;
2219 if (trust && !ctx->param->trust)
2220 ctx->param->trust = trust;
2224 X509_STORE_CTX *X509_STORE_CTX_new_with_libctx(OPENSSL_CTX *libctx,
2227 X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2230 X509err(0, ERR_R_MALLOC_FAILURE);
2234 ctx->libctx = libctx;
2235 if (propq != NULL) {
2236 ctx->propq = OPENSSL_strdup(propq);
2237 if (ctx->propq == NULL) {
2239 X509err(0, ERR_R_MALLOC_FAILURE);
2247 X509_STORE_CTX *X509_STORE_CTX_new(void)
2249 return X509_STORE_CTX_new_with_libctx(NULL, NULL);
2253 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2258 X509_STORE_CTX_cleanup(ctx);
2260 /* libctx and propq survive X509_STORE_CTX_cleanup() */
2261 OPENSSL_free(ctx->propq);
2266 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2267 STACK_OF(X509) *chain)
2273 ctx->untrusted = chain;
2275 ctx->num_untrusted = 0;
2276 ctx->other_ctx = NULL;
2280 ctx->explicit_policy = 0;
2281 ctx->error_depth = 0;
2282 ctx->current_cert = NULL;
2283 ctx->current_issuer = NULL;
2284 ctx->current_crl = NULL;
2285 ctx->current_crl_score = 0;
2286 ctx->current_reasons = 0;
2290 ctx->bare_ta_signed = 0;
2291 /* Zero ex_data to make sure we're cleanup-safe */
2292 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2294 /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2296 ctx->cleanup = store->cleanup;
2300 if (store && store->check_issued)
2301 ctx->check_issued = store->check_issued;
2303 ctx->check_issued = check_issued;
2305 if (store && store->get_issuer)
2306 ctx->get_issuer = store->get_issuer;
2308 ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2310 if (store && store->verify_cb)
2311 ctx->verify_cb = store->verify_cb;
2313 ctx->verify_cb = null_callback;
2315 if (store && store->verify)
2316 ctx->verify = store->verify;
2318 ctx->verify = internal_verify;
2320 if (store && store->check_revocation)
2321 ctx->check_revocation = store->check_revocation;
2323 ctx->check_revocation = check_revocation;
2325 if (store && store->get_crl)
2326 ctx->get_crl = store->get_crl;
2328 ctx->get_crl = NULL;
2330 if (store && store->check_crl)
2331 ctx->check_crl = store->check_crl;
2333 ctx->check_crl = check_crl;
2335 if (store && store->cert_crl)
2336 ctx->cert_crl = store->cert_crl;
2338 ctx->cert_crl = cert_crl;
2340 if (store && store->check_policy)
2341 ctx->check_policy = store->check_policy;
2343 ctx->check_policy = check_policy;
2345 if (store && store->lookup_certs)
2346 ctx->lookup_certs = store->lookup_certs;
2348 ctx->lookup_certs = X509_STORE_CTX_get1_certs;
2350 if (store && store->lookup_crls)
2351 ctx->lookup_crls = store->lookup_crls;
2353 ctx->lookup_crls = X509_STORE_CTX_get1_crls;
2355 ctx->param = X509_VERIFY_PARAM_new();
2356 if (ctx->param == NULL) {
2357 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2362 * Inherit callbacks and flags from X509_STORE if not set use defaults.
2365 ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2367 ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2370 ret = X509_VERIFY_PARAM_inherit(ctx->param,
2371 X509_VERIFY_PARAM_lookup("default"));
2374 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2379 * XXX: For now, continue to inherit trust from VPM, but infer from the
2380 * purpose if this still yields the default value.
2382 if (ctx->param->trust == X509_TRUST_DEFAULT) {
2383 int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2384 X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2387 ctx->param->trust = X509_PURPOSE_get_trust(xp);
2390 if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2393 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2397 * On error clean up allocated storage, if the store context was not
2398 * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2400 X509_STORE_CTX_cleanup(ctx);
2405 * Set alternative lookup method: just a STACK of trusted certificates. This
2406 * avoids X509_STORE nastiness where it isn't needed.
2408 void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2410 ctx->other_ctx = sk;
2411 ctx->get_issuer = get_issuer_sk;
2412 ctx->lookup_certs = lookup_certs_sk;
2415 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2418 * We need to be idempotent because, unfortunately, free() also calls
2419 * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2420 * calls cleanup() for the same object twice! Thus we must zero the
2421 * pointers below after they're freed!
2423 /* Seems to always be 0 in OpenSSL, do this at most once. */
2424 if (ctx->cleanup != NULL) {
2426 ctx->cleanup = NULL;
2428 if (ctx->param != NULL) {
2429 if (ctx->parent == NULL)
2430 X509_VERIFY_PARAM_free(ctx->param);
2433 X509_policy_tree_free(ctx->tree);
2435 sk_X509_pop_free(ctx->chain, X509_free);
2437 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2438 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2441 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2443 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2446 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2448 X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2451 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2454 X509_VERIFY_PARAM_set_time(ctx->param, t);
2457 X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
2462 STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
2464 return ctx->untrusted;
2467 void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2469 ctx->untrusted = sk;
2472 void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2474 sk_X509_pop_free(ctx->chain, X509_free);
2478 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2479 X509_STORE_CTX_verify_cb verify_cb)
2481 ctx->verify_cb = verify_cb;
2484 X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
2486 return ctx->verify_cb;
2489 void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
2490 X509_STORE_CTX_verify_fn verify)
2492 ctx->verify = verify;
2495 X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
2500 X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
2502 return ctx->get_issuer;
2505 X509_STORE_CTX_check_issued_fn
2506 X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
2508 return ctx->check_issued;
2511 X509_STORE_CTX_check_revocation_fn
2512 X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
2514 return ctx->check_revocation;
2517 X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
2519 return ctx->get_crl;
2522 X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
2524 return ctx->check_crl;
2527 X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
2529 return ctx->cert_crl;
2532 X509_STORE_CTX_check_policy_fn
2533 X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
2535 return ctx->check_policy;
2538 X509_STORE_CTX_lookup_certs_fn
2539 X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
2541 return ctx->lookup_certs;
2544 X509_STORE_CTX_lookup_crls_fn
2545 X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
2547 return ctx->lookup_crls;
2550 X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
2552 return ctx->cleanup;
2555 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
2560 int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
2562 return ctx->explicit_policy;
2565 int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
2567 return ctx->num_untrusted;
2570 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2572 const X509_VERIFY_PARAM *param;
2574 param = X509_VERIFY_PARAM_lookup(name);
2577 return X509_VERIFY_PARAM_inherit(ctx->param, param);
2580 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
2585 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2587 X509_VERIFY_PARAM_free(ctx->param);
2591 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
2596 static unsigned char *dane_i2d(
2599 unsigned int *i2dlen)
2601 unsigned char *buf = NULL;
2605 * Extract ASN.1 DER form of certificate or public key.
2608 case DANETLS_SELECTOR_CERT:
2609 len = i2d_X509(cert, &buf);
2611 case DANETLS_SELECTOR_SPKI:
2612 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2615 X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2619 if (len < 0 || buf == NULL) {
2620 X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2624 *i2dlen = (unsigned int)len;
2628 #define DANETLS_NONE 256 /* impossible uint8_t */
2630 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2632 SSL_DANE *dane = ctx->dane;
2633 unsigned usage = DANETLS_NONE;
2634 unsigned selector = DANETLS_NONE;
2635 unsigned ordinal = DANETLS_NONE;
2636 unsigned mtype = DANETLS_NONE;
2637 unsigned char *i2dbuf = NULL;
2638 unsigned int i2dlen = 0;
2639 unsigned char mdbuf[EVP_MAX_MD_SIZE];
2640 unsigned char *cmpbuf = NULL;
2641 unsigned int cmplen = 0;
2645 danetls_record *t = NULL;
2648 mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2651 * The trust store is not applicable with DANE-TA(2)
2653 if (depth >= ctx->num_untrusted)
2654 mask &= DANETLS_PKIX_MASK;
2657 * If we've previously matched a PKIX-?? record, no need to test any
2658 * further PKIX-?? records, it remains to just build the PKIX chain.
2659 * Had the match been a DANE-?? record, we'd be done already.
2661 if (dane->mdpth >= 0)
2662 mask &= ~DANETLS_PKIX_MASK;
2665 * https://tools.ietf.org/html/rfc7671#section-5.1
2666 * https://tools.ietf.org/html/rfc7671#section-5.2
2667 * https://tools.ietf.org/html/rfc7671#section-5.3
2668 * https://tools.ietf.org/html/rfc7671#section-5.4
2670 * We handle DANE-EE(3) records first as they require no chain building
2671 * and no expiration or hostname checks. We also process digests with
2672 * higher ordinals first and ignore lower priorities except Full(0) which
2673 * is always processed (last). If none match, we then process PKIX-EE(1).
2675 * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2676 * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2677 * priorities. See twin comment in ssl/ssl_lib.c.
2679 * We expect that most TLSA RRsets will have just a single usage, so we
2680 * don't go out of our way to cache multiple selector-specific i2d buffers
2681 * across usages, but if the selector happens to remain the same as switch
2682 * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2683 * records would result in us generating each of the certificate and public
2684 * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2685 * or multiple "3 0 1" records.
2687 * As soon as we find a match at any given depth, we stop, because either
2688 * we've matched a DANE-?? record and the peer is authenticated, or, after
2689 * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
2690 * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2692 recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2693 for (i = 0; matched == 0 && i < recnum; ++i) {
2694 t = sk_danetls_record_value(dane->trecs, i);
2695 if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2697 if (t->usage != usage) {
2700 /* Reset digest agility for each usage/selector pair */
2701 mtype = DANETLS_NONE;
2702 ordinal = dane->dctx->mdord[t->mtype];
2704 if (t->selector != selector) {
2705 selector = t->selector;
2707 /* Update per-selector state */
2708 OPENSSL_free(i2dbuf);
2709 i2dbuf = dane_i2d(cert, selector, &i2dlen);
2713 /* Reset digest agility for each usage/selector pair */
2714 mtype = DANETLS_NONE;
2715 ordinal = dane->dctx->mdord[t->mtype];
2716 } else if (t->mtype != DANETLS_MATCHING_FULL) {
2720 * <https://tools.ietf.org/html/rfc7671#section-9>
2722 * For a fixed selector, after processing all records with the
2723 * highest mtype ordinal, ignore all mtypes with lower ordinals
2724 * other than "Full".
2726 if (dane->dctx->mdord[t->mtype] < ordinal)
2731 * Each time we hit a (new selector or) mtype, re-compute the relevant
2732 * digest, more complex caching is not worth the code space.
2734 if (t->mtype != mtype) {
2735 const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2741 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2749 * Squirrel away the certificate and depth if we have a match. Any
2750 * DANE match is dispositive, but with PKIX we still need to build a
2753 if (cmplen == t->dlen &&
2754 memcmp(cmpbuf, t->data, cmplen) == 0) {
2755 if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2757 if (matched || dane->mdpth < 0) {
2758 dane->mdpth = depth;
2760 OPENSSL_free(dane->mcert);
2768 /* Clear the one-element DER cache */
2769 OPENSSL_free(i2dbuf);
2773 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2775 SSL_DANE *dane = ctx->dane;
2779 if (!DANETLS_HAS_TA(dane) || depth == 0)
2780 return X509_TRUST_UNTRUSTED;
2783 * Record any DANE trust-anchor matches, for the first depth to test, if
2784 * there's one at that depth. (This'll be false for length 1 chains looking
2785 * for an exact match for the leaf certificate).
2787 cert = sk_X509_value(ctx->chain, depth);
2788 if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2789 return X509_TRUST_REJECTED;
2791 ctx->num_untrusted = depth - 1;
2792 return X509_TRUST_TRUSTED;
2795 return X509_TRUST_UNTRUSTED;
2798 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2800 SSL_DANE *dane = ctx->dane;
2802 int num = ctx->num_untrusted;
2803 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2804 int recnum = sk_danetls_record_num(dane->trecs);
2807 for (i = 0; i < recnum; ++i) {
2808 t = sk_danetls_record_value(dane->trecs, i);
2809 if (t->usage != DANETLS_USAGE_DANE_TA ||
2810 t->selector != DANETLS_SELECTOR_SPKI ||
2811 t->mtype != DANETLS_MATCHING_FULL ||
2812 X509_verify_ex(cert, t->spki, ctx->libctx, ctx->propq) <= 0)
2815 /* Clear any PKIX-?? matches that failed to extend to a full chain */
2816 X509_free(dane->mcert);
2819 /* Record match via a bare TA public key */
2820 ctx->bare_ta_signed = 1;
2821 dane->mdpth = num - 1;
2824 /* Prune any excess chain certificates */
2825 num = sk_X509_num(ctx->chain);
2826 for (; num > ctx->num_untrusted; --num)
2827 X509_free(sk_X509_pop(ctx->chain));
2829 return X509_TRUST_TRUSTED;
2832 return X509_TRUST_UNTRUSTED;
2835 static void dane_reset(SSL_DANE *dane)
2838 * Reset state to verify another chain, or clear after failure.
2840 X509_free(dane->mcert);
2847 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
2849 int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
2851 if (err == X509_V_OK)
2853 return verify_cb_cert(ctx, cert, 0, err);
2856 static int dane_verify(X509_STORE_CTX *ctx)
2858 X509 *cert = ctx->cert;
2859 SSL_DANE *dane = ctx->dane;
2866 * When testing the leaf certificate, if we match a DANE-EE(3) record,
2867 * dane_match() returns 1 and we're done. If however we match a PKIX-EE(1)
2868 * record, the match depth and matching TLSA record are recorded, but the
2869 * return value is 0, because we still need to find a PKIX trust-anchor.
2870 * Therefore, when DANE authentication is enabled (required), we're done
2872 * + matched < 0, internal error.
2873 * + matched == 1, we matched a DANE-EE(3) record
2874 * + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
2875 * DANE-TA(2) or PKIX-TA(0) to test.
2877 matched = dane_match(ctx, ctx->cert, 0);
2878 done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2881 X509_get_pubkey_parameters(NULL, ctx->chain);
2884 /* Callback invoked as needed */
2885 if (!check_leaf_suiteb(ctx, cert))
2887 /* Callback invoked as needed */
2888 if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 &&
2891 /* Bypass internal_verify(), issue depth 0 success callback */
2892 ctx->error_depth = 0;
2893 ctx->current_cert = cert;
2894 return ctx->verify_cb(1, ctx);
2898 ctx->error_depth = 0;
2899 ctx->current_cert = cert;
2900 ctx->error = X509_V_ERR_OUT_OF_MEM;
2905 /* Fail early, TA-based success is not possible */
2906 if (!check_leaf_suiteb(ctx, cert))
2908 return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
2912 * Chain verification for usages 0/1/2. TLSA record matching of depth > 0
2913 * certificates happens in-line with building the rest of the chain.
2915 return verify_chain(ctx);
2918 /* Get issuer, without duplicate suppression */
2919 static int get_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
2921 STACK_OF(X509) *saved_chain = ctx->chain;
2925 ok = ctx->get_issuer(issuer, ctx, cert);
2926 ctx->chain = saved_chain;
2931 static int build_chain(X509_STORE_CTX *ctx)
2933 SSL_DANE *dane = ctx->dane;
2934 int num = sk_X509_num(ctx->chain);
2935 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2937 STACK_OF(X509) *sktmp = NULL;
2938 unsigned int search;
2939 int may_trusted = 0;
2940 int may_alternate = 0;
2941 int trust = X509_TRUST_UNTRUSTED;
2942 int alt_untrusted = 0;
2947 /* Our chain starts with a single untrusted element. */
2948 if (!ossl_assert(num == 1 && ctx->num_untrusted == num)) {
2949 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
2950 ctx->error = X509_V_ERR_UNSPECIFIED;
2954 ss = cert_self_signed(ctx, cert);
2956 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
2957 ctx->error = X509_V_ERR_UNSPECIFIED;
2961 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
2962 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
2963 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
2965 * Set up search policy, untrusted if possible, trusted-first if enabled.
2966 * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2967 * trust_store, otherwise we might look there first. If not trusted-first,
2968 * and alternate chains are not disabled, try building an alternate chain
2969 * if no luck with untrusted first.
2971 search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2972 if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2973 if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2974 search |= S_DOTRUSTED;
2975 else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2981 * Shallow-copy the stack of untrusted certificates (with TLS, this is
2982 * typically the content of the peer's certificate message) so can make
2983 * multiple passes over it, while free to remove elements as we go.
2985 if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
2986 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2987 ctx->error = X509_V_ERR_OUT_OF_MEM;
2992 * If we got any "DANE-TA(2) Cert(0) Full(0)" trust-anchors from DNS, add
2993 * them to our working copy of the untrusted certificate stack. Since the
2994 * caller of X509_STORE_CTX_init() may have provided only a leaf cert with
2995 * no corresponding stack of untrusted certificates, we may need to create
2996 * an empty stack first. [ At present only the ssl library provides DANE
2997 * support, and ssl_verify_cert_chain() always provides a non-null stack
2998 * containing at least the leaf certificate, but we must be prepared for
3001 if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
3002 if (sktmp == NULL && (sktmp = sk_X509_new_null()) == NULL) {
3003 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3004 ctx->error = X509_V_ERR_OUT_OF_MEM;
3007 for (i = 0; i < sk_X509_num(dane->certs); ++i) {
3008 if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
3009 sk_X509_free(sktmp);
3010 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3011 ctx->error = X509_V_ERR_OUT_OF_MEM;
3018 * Still absurdly large, but arithmetically safe, a lower hard upper bound
3019 * might be reasonable.
3021 if (ctx->param->depth > INT_MAX/2)
3022 ctx->param->depth = INT_MAX/2;
3025 * Try to Extend the chain until we reach an ultimately trusted issuer.
3026 * Build chains up to one longer the limit, later fail if we hit the limit,
3027 * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3029 depth = ctx->param->depth + 1;
3031 while (search != 0) {
3036 * Look in the trust store if enabled for first lookup, or we've run
3037 * out of untrusted issuers and search here is not disabled. When we
3038 * reach the depth limit, we stop extending the chain, if by that point
3039 * we've not found a trust-anchor, any trusted chain would be too long.
3041 * The error reported to the application verify callback is at the
3042 * maximal valid depth with the current certificate equal to the last
3043 * not ultimately-trusted issuer. For example, with verify_depth = 0,
3044 * the callback will report errors at depth=1 when the immediate issuer
3045 * of the leaf certificate is not a trust anchor. No attempt will be
3046 * made to locate an issuer for that certificate, since such a chain
3047 * would be a-priori too long.
3049 if ((search & S_DOTRUSTED) != 0) {
3050 i = num = sk_X509_num(ctx->chain);
3051 if ((search & S_DOALTERNATE) != 0) {
3053 * As high up the chain as we can, look for an alternative
3054 * trusted issuer of an untrusted certificate that currently
3055 * has an untrusted issuer. We use the alt_untrusted variable
3056 * to track how far up the chain we find the first match. It
3057 * is only if and when we find a match, that we prune the chain
3058 * and reset ctx->num_untrusted to the reduced count of
3059 * untrusted certificates. While we're searching for such a
3060 * match (which may never be found), it is neither safe nor
3061 * wise to preemptively modify either the chain or
3062 * ctx->num_untrusted.
3064 * Note, like ctx->num_untrusted, alt_untrusted is a count of
3065 * untrusted certificates, not a "depth".
3069 x = sk_X509_value(ctx->chain, i-1);
3071 ok = (depth < num) ? 0 : get_issuer(&xtmp, ctx, x);
3074 trust = X509_TRUST_REJECTED;
3075 ctx->error = X509_V_ERR_STORE_LOOKUP;
3082 * Alternative trusted issuer for a mid-chain untrusted cert?
3083 * Pop the untrusted cert's successors and retry. We might now
3084 * be able to complete a valid chain via the trust store. Note
3085 * that despite the current trust-store match we might still
3086 * fail complete the chain to a suitable trust-anchor, in which
3087 * case we may prune some more untrusted certificates and try
3088 * again. Thus the S_DOALTERNATE bit may yet be turned on
3089 * again with an even shorter untrusted chain!
3091 * If in the process we threw away our matching PKIX-TA trust
3092 * anchor, reset DANE trust. We might find a suitable trusted
3093 * certificate among the ones from the trust store.
3095 if ((search & S_DOALTERNATE) != 0) {
3096 if (!ossl_assert(num > i && i > 0 && ss == 0)) {
3097 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3099 trust = X509_TRUST_REJECTED;
3100 ctx->error = X509_V_ERR_UNSPECIFIED;
3104 search &= ~S_DOALTERNATE;
3105 for (; num > i; --num)
3106 X509_free(sk_X509_pop(ctx->chain));
3107 ctx->num_untrusted = num;
3109 if (DANETLS_ENABLED(dane) &&
3110 dane->mdpth >= ctx->num_untrusted) {
3112 X509_free(dane->mcert);
3115 if (DANETLS_ENABLED(dane) &&
3116 dane->pdpth >= ctx->num_untrusted)
3121 * Self-signed untrusted certificates get replaced by their
3122 * trusted matching issuer. Otherwise, grow the chain.
3125 if (!sk_X509_push(ctx->chain, x = xtmp)) {
3127 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3128 trust = X509_TRUST_REJECTED;
3129 ctx->error = X509_V_ERR_OUT_OF_MEM;
3133 ss = cert_self_signed(ctx, x);
3135 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3136 ctx->error = X509_V_ERR_UNSPECIFIED;
3139 } else if (num == ctx->num_untrusted) {
3141 * We have a self-signed certificate that has the same
3142 * subject name (and perhaps keyid and/or serial number) as
3143 * a trust-anchor. We must have an exact match to avoid
3144 * possible impersonation via key substitution etc.
3146 if (X509_cmp(x, xtmp) != 0) {
3147 /* Self-signed untrusted mimic. */
3152 ctx->num_untrusted = --num;
3153 (void) sk_X509_set(ctx->chain, num, x = xtmp);
3158 * We've added a new trusted certificate to the chain, recheck
3159 * trust. If not done, and not self-signed look deeper.
3160 * Whether or not we're doing "trusted first", we no longer
3161 * look for untrusted certificates from the peer's chain.
3163 * At this point ctx->num_trusted and num must reflect the
3164 * correct number of untrusted certificates, since the DANE
3165 * logic in check_trust() depends on distinguishing CAs from
3166 * "the wire" from CAs from the trust store. In particular, the
3167 * certificate at depth "num" should be the new trusted
3168 * certificate with ctx->num_untrusted <= num.
3171 if (!ossl_assert(ctx->num_untrusted <= num)) {
3172 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3173 trust = X509_TRUST_REJECTED;
3174 ctx->error = X509_V_ERR_UNSPECIFIED;
3178 search &= ~S_DOUNTRUSTED;
3179 switch (trust = check_trust(ctx, num)) {
3180 case X509_TRUST_TRUSTED:
3181 case X509_TRUST_REJECTED:
3191 * No dispositive decision, and either self-signed or no match, if
3192 * we were doing untrusted-first, and alt-chains are not disabled,
3193 * do that, by repeatedly losing one untrusted element at a time,
3194 * and trying to extend the shorted chain.
3196 if ((search & S_DOUNTRUSTED) == 0) {
3197 /* Continue search for a trusted issuer of a shorter chain? */
3198 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3200 /* Still no luck and no fallbacks left? */
3201 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
3202 ctx->num_untrusted < 2)
3204 /* Search for a trusted issuer of a shorter chain */
3205 search |= S_DOALTERNATE;
3206 alt_untrusted = ctx->num_untrusted - 1;
3212 * Extend chain with peer-provided certificates
3214 if ((search & S_DOUNTRUSTED) != 0) {
3215 num = sk_X509_num(ctx->chain);
3216 if (!ossl_assert(num == ctx->num_untrusted)) {
3217 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3218 trust = X509_TRUST_REJECTED;
3219 ctx->error = X509_V_ERR_UNSPECIFIED;
3223 x = sk_X509_value(ctx->chain, num-1);
3226 * Once we run out of untrusted issuers, we stop looking for more
3227 * and start looking only in the trust store if enabled.
3229 xtmp = (ss || depth < num) ? NULL : find_issuer(ctx, sktmp, x);
3231 search &= ~S_DOUNTRUSTED;
3233 search |= S_DOTRUSTED;
3237 /* Drop this issuer from future consideration */
3238 (void) sk_X509_delete_ptr(sktmp, xtmp);
3240 if (!sk_X509_push(ctx->chain, xtmp)) {
3241 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3242 trust = X509_TRUST_REJECTED;
3243 ctx->error = X509_V_ERR_OUT_OF_MEM;
3248 X509_up_ref(x = xtmp);
3249 ++ctx->num_untrusted;
3250 ss = cert_self_signed(ctx, xtmp);
3252 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3253 ctx->error = X509_V_ERR_UNSPECIFIED;
3258 * Check for DANE-TA trust of the topmost untrusted certificate.
3260 switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
3261 case X509_TRUST_TRUSTED:
3262 case X509_TRUST_REJECTED:
3268 sk_X509_free(sktmp);
3271 * Last chance to make a trusted chain, either bare DANE-TA public-key
3272 * signers, or else direct leaf PKIX trust.
3274 num = sk_X509_num(ctx->chain);
3276 if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3277 trust = check_dane_pkeys(ctx);
3278 if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3279 trust = check_trust(ctx, num);
3283 case X509_TRUST_TRUSTED:
3285 case X509_TRUST_REJECTED:
3286 /* Callback already issued */
3288 case X509_TRUST_UNTRUSTED:
3290 num = sk_X509_num(ctx->chain);
3292 return verify_cb_cert(ctx, NULL, num-1,
3293 X509_V_ERR_CERT_CHAIN_TOO_LONG);
3294 if (DANETLS_ENABLED(dane) &&
3295 (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
3296 return verify_cb_cert(ctx, NULL, num-1, X509_V_ERR_DANE_NO_MATCH);
3297 if (ss && sk_X509_num(ctx->chain) == 1)
3298 return verify_cb_cert(ctx, NULL, num-1,
3299 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
3301 return verify_cb_cert(ctx, NULL, num-1,
3302 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
3303 if (ctx->num_untrusted < num)
3304 return verify_cb_cert(ctx, NULL, num-1,
3305 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
3306 return verify_cb_cert(ctx, NULL, num-1,
3307 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
3311 static const int minbits_table[] = { 80, 112, 128, 192, 256 };
3312 static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
3315 * Check whether the public key of ``cert`` meets the security level of
3318 * Returns 1 on success, 0 otherwise.
3320 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert)
3322 EVP_PKEY *pkey = X509_get0_pubkey(cert);
3323 int level = ctx->param->auth_level;
3326 * At security level zero, return without checking for a supported public
3327 * key type. Some engines support key types not understood outside the
3328 * engine, and we only need to understand the key when enforcing a security
3334 /* Unsupported or malformed keys are not secure */
3338 if (level > NUM_AUTH_LEVELS)
3339 level = NUM_AUTH_LEVELS;
3341 return EVP_PKEY_security_bits(pkey) >= minbits_table[level - 1];
3345 * Check whether the signature digest algorithm of ``cert`` meets the security
3346 * level of ``ctx``. Should not be checked for trust anchors (whether
3347 * self-signed or otherwise).
3349 * Returns 1 on success, 0 otherwise.
3351 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
3354 int level = ctx->param->auth_level;
3358 if (level > NUM_AUTH_LEVELS)
3359 level = NUM_AUTH_LEVELS;
3361 if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
3364 return secbits >= minbits_table[level - 1];