X509_verify_cert, X509_STORE_CTX_verify, X509_build_chain
build and verify X509 certificate chain
- Provided by: libssl-doc (Version: 4.0.3-1ubuntu1)
- Source: openssl
- Report a bug
build and verify X509 certificate chain
#include <openssl/x509_vfy.h>
int X509_verify_cert(X509_STORE_CTX *ctx);
int X509_STORE_CTX_verify(X509_STORE_CTX *ctx);
STACK_OF(X509) *X509_build_chain(const X509 *target, STACK_OF(X509) *certs,
X509_STORE *store, int with_self_signed,
OSSL_LIB_CTX *libctx, const char *propq);
X509_verify_cert() attempts to build and validate a certificate chain for the target certificate set in ctx. The verification context, of type X509_STORE_CTX, must first be constructed with X509_STORE_CTX_new(3) and initialised with X509_STORE_CTX_init(3). It carries the target certificate, the trust store, an optional stack of untrusted certificates that may assist chain construction, verification parameters such as flags and a verification purpose, an optional verification callback, and, after a call, the verification outcome.
A X509_STORE_CTX can be used for only one verification. Calling X509_verify_cert() a second time on the same context without reinitialising it fails with a negative return value, and X509_STORE_CTX_get_error(3) subsequently returns X509_V_ERR_INVALID_CALL.
When the target is a certificate, the function performs the following steps in order. The first step that fails aborts verification, except where a verification callback explicitly waives the error (see "THE VERIFICATION CALLBACK" below):
Failure to build a chain to a trust anchor yields an error such as X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, or X509_V_ERR_CERT_CHAIN_TOO_LONG.
Several X509_V_FLAG_* values modify the behaviour of these checks; representative ones are named at the relevant step above, but the list there is not exhaustive. The complete set of verification flags, the effect each one has, and the functions used to query and modify them are documented in X509_VERIFY_PARAM_set_flags(3).
Applications rarely call X509_verify_cert() directly. It is invoked internally by OpenSSL during S/MIME and CMS verification and during the TLS handshake.
X509_STORE_CTX_verify() behaves identically to X509_verify_cert() except for the selection of the target certificate: if no target has been set on ctx (see X509_STORE_CTX_set_cert(3)) and the untrusted stack is nonempty, the first certificate in the untrusted stack is adopted as the target before verification begins. If a target was set explicitly, X509_STORE_CTX_verify() uses it and does not consult the untrusted stack for this purpose.
When the verification target is a raw public key rather than a certificate (set via X509_STORE_CTX_init_rpk(3)), both functions validate the raw public key instead of a certificate chain. The set of possible checks is significantly reduced: there are no extensions, names, CRLs or signatures to verify. The raw public key can be authenticated only via DANE TLSA records, either locally synthesised or obtained by the application from DNS. Raw public key DANE TLSA records may be added via SSL_add_expected_rpk(3) or SSL_dane_tlsa_add(3).
X509_build_chain() builds a certificate chain starting from target, using the same chain-construction algorithm as X509_verify_cert() (see "X509_verify_cert and X509_STORE_CTX_verify" above). It internally uses a X509_STORE_CTX structure associated with the library context libctx and property query string propq, both of which may be NULL. The role of certs depends on store:
Because the internal X509_STORE_CTX is allocated and freed inside X509_build_chain(), search-policy flags such as X509_V_FLAG_TRUSTED_FIRST and X509_V_FLAG_NO_ALT_CHAINS and the configured depth limit always take their default values, and the specific X509_V_ERR_* code that caused chain construction to fail is not reported back: the function signals only success or failure through its return value (and, when store is NULL, may also return a partial chain).
On success the returned stack starts with a newly up-referenced target followed by the issuer certificates that were found. A self-signed certificate at the top of the chain is included in the returned stack when either with_self_signed is 1, or the chain consists solely of target (for example because target itself is self-signed or no further issuer could be found). When the chain has more than one element and with_self_signed is 0, the self-signed top is omitted from the result.
The caller is responsible for freeing the returned stack.
Each X509_STORE_CTX carries a verification callback with the signature
int (*verify_cb)(int ok, X509_STORE_CTX *ctx);
This callback is invoked by X509_verify_cert() and X509_STORE_CTX_verify() at multiple points during verification, both to report errors and to notify of progress. It is installed by X509_STORE_CTX_set_verify_cb(3) on the context, or it is inherited at X509_STORE_CTX_init(3) time from the X509_STORE (see X509_STORE_set_verify_cb_func(3)). If neither has been set, a default callback is used which simply returns its ok argument unchanged, causing every error to abort verification.
There are two distinct invocation patterns:
The callback's return value controls subsequent verification:
When the callback waives an error by returning nonzero, the underlying check is treated as passed for control-flow purposes, but the error code recorded on ctx is not reset to X509_V_OK. A subsequent successful return from X509_verify_cert() therefore does not imply that X509_STORE_CTX_get_error(3) will return X509_V_OK: it may still hold the last error code that was waived. This is intentional. Only the callback itself is permitted to overwrite the error code, via X509_STORE_CTX_set_error(3), and only at its own risk.
A verification callback that returns nonzero on an error notification has, by definition, suppressed an authentication check that OpenSSL considered necessary. Callers should treat installing a callback that waives errors as a deliberate weakening of the security guarantees of X509_verify_cert(), to be done only for specific, well-understood error codes. The following pitfalls are common:
The default callback waives nothing and is the safe choice; it is the right behaviour for almost all production uses.
X509_verify_cert() and X509_STORE_CTX_verify() return:
In all failure modes, additional information can be obtained from X509_STORE_CTX_get_error(3) and the related accessors. Applications must treat any return value <= 0 as verification not having succeeded.
X509_build_chain() returns NULL on error. Otherwise it returns a newly allocated stack of certificates that the caller must free; the stack may represent only a partial chain when store is NULL.
Several aspects of chain construction depart from the recommendations of RFC 4158 (Certification Path Building) and from strict RFC 5280 path validation. Callers should be aware of the following:
The chain search is not optimised in the manner described by RFC 4158 sections 3.1 to 3.5. Candidate issuers are not scored against the set of heuristics RFC 4158 recommends; at each step the first viable candidate is committed to, with the only preference being for a candidate whose validity period covers the current time. There is no tree-traversal backtracking: when an initial chain does not reach a trust anchor, the search is retried with progressively shorter untrusted prefixes (unless X509_V_FLAG_NO_ALT_CHAINS is set), but different candidate issuers at intermediate positions of the same chain are not tried. In simple hierarchical PKIs this is rarely an issue. In cross-certified or bridged PKI environments X509_verify_cert() may fail to find a valid certification path even when one demonstrably exists in the available certificate set.
Issuer key usage is not enforced during chain construction. RFC 5280 section 6.1.4(n) and RFC 4158 section 3.5.3 call for verifying that an issuer candidate's keyUsage extension permits certificate signing (keyCertSign) before that candidate is selected. OpenSSL defers this check to the later extension-validation pass: if two candidate issuers exist for a certificate, and the one lacking keyCertSign happens to be selected first, verification fails on the extension check rather than backing off and trying the other candidate. The misuse is ultimately caught, but a chain that would have validated through the alternative issuer is not built.
X509_V_FLAG_PARTIAL_CHAIN relaxes the trust-anchor requirement from the one defined by RFC 5280 section 6.1.1(d). With the flag set, any certificate in the trust store is acceptable as the terminator of the chain, even if it is not a self-signed root. This is an intentional and now-common deviation that supports modern practices such as pinning trust to a specific intermediate, or shortening chains by treating a sufficiently-trusted intermediate as the trust point and eliding the root above it. Callers should nevertheless be aware that the chain returned in this mode does not necessarily terminate at an RFC 5280-style trust anchor.
NAME_CONSTRAINTS_check(3) caps each per-pair check at 2**20 comparisons, but the chain orchestrator issues N(N-1)/2 such checks for an N-certificate chain. An adversary submitting a maximally constructed chain can therefore force up to approximately 6.3 million name-constraint comparisons in a four-certificate chain (one leaf and three name-constrained signers), or approximately 5.2 billion at the default chain-depth limit of 100.
NAME_CONSTRAINTS_check(3), SSL_add_expected_rpk(3), SSL_CTX_dane_enable(3), SSL_dane_tlsa_add(3), X509_STORE_CTX_new(3), X509_STORE_CTX_init(3), X509_STORE_CTX_init_rpk(3), X509_STORE_CTX_get_error(3), X509_STORE_CTX_set_verify_cb(3), X509_STORE_set_verify_cb_func(3), X509_VERIFY_PARAM_set_flags(3)
X509_build_chain() and X509_STORE_CTX_verify() were added in OpenSSL 3.0.
Copyright 2009-2026 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <https://www.openssl.org/source/license.html>.