Registry / auth-security / certvalidator

certvalidator

JSON →
library0.11.1pypypi✓ verified 24d ago

certvalidator is a Python library for validating X.509 certificates and certificate paths according to RFC 5280. It provides robust tools for checking certificate validity, revocation status (CRL and OCSP), and trust chains. The current version is 0.11.1, and it typically sees updates every few months for minor versions, with occasional major version bumps.

pip install certvalidator
INSTALL
IMPORT
SIG · CERTVALIDATOR
C
certvalidator
auth-securitypythonv0.11.1
Install
1.8s avg
Import
218ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.11.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 20.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.218s · 21MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CertificateValidator
from certvalidator import CertificateValidator
TrustStore
from certvalidator.stores import TrustStore
errors
from certvalidator import errors

This quickstart demonstrates how to fetch a TLS server's certificate chain using `oscrypto`, load system trust anchors with `TrustStore`, and then validate the certificate path for a specific hostname using `CertificateValidator`.

from datetime import datetime from oscrypto import tls from certvalidator import CertificateValidator, errors from certvalidator.stores import TrustStore # Target host and port for certificate retrieval hostname = "google.com" port = 443 try: # Step 1: Obtain the end-entity (leaf) certificate and its chain from a TLS server. # oscrypto.tls.TLSSocket provides the full chain (peer_certificate and intermediate_certificates). # This establishes a connection to fetch the server's certificate chain. connection = tls.TLSSocket(hostname, port, timeout=5) # The attributes are oscrypto.asymmetric.Certificate objects; dump() gets their DER bytes. leaf_cert_der = connection.peer_certificate.dump() intermediate_certs_der = [c.dump() for c in connection.intermediate_certificates] connection.close() # Close the connection once certs are retrieved # Step 2: Prepare the trust anchors (root CAs). # TrustStore() by default loads system-wide trust anchors (e.g., from OS certificate store). # For custom roots, use: SimpleTrustStore([root_ca_der_bytes, ...]). trust_store = TrustStore() # Step 3: Create a CertificateValidator instance. # Arguments: leaf certificate, list of intermediate certificates, and the trust store. validator = CertificateValidator( leaf_cert_der, intermediate_certs_der, trust_store=trust_store ) # Step 4: Perform validation for a specific purpose (e.g., TLS server certificate). # validate_tls_server verifies hostname, key usage, validity period, and revocation status. # validation_time is optional, defaults to datetime.utcnow(). validation_path = validator.validate_tls_server(hostname, validation_time=datetime.utcnow()) print(f"Certificate for {hostname} is valid.") print("Validated path:") for cert_in_path in validation_path: print(f" - Subject: {cert_in_path.subject.human_friendly}") print(f" Issuer: {cert_in_path.issuer.human_friendly}") except errors.PathValidationError as e: print(f"Certificate validation failed for {hostname}: {e}") except Exception as e: print(f"An error occurred: {e}") print("Ensure network connectivity and that 'oscrypto' and 'certvalidator' are installed.")
Debug
Known issues
breakingPrior to 0.6.0, the `validation_time` parameter in `CertificateValidator` methods (e.g., `validate_tls_server`) expected a `float` (Unix timestamp). Since 0.6.0, it now exclusively accepts a `datetime.datetime` object.
fix
Convert `float` timestamps to `datetime.datetime` objects using `datetime.fromtimestamp(timestamp_float)`.
affects: <0.6.0
breakingIn version 0.7.0, the `RevocationChecker` functionality was refactored. It moved to its own class (`certvalidator.revocation_checker.RevocationChecker`), and the `CertificateValidator` constructor now expects a list of `RevocationChecker` instances via the `revocation_checkers` parameter, instead of direct arguments.
fix
Instantiate `RevocationChecker` objects (e.g., `CRLChecker()`, `OCSPChecker()`) and pass them as a list to the `revocation_checkers` argument of `CertificateValidator`.
affects: <0.7.0
gotchaValidation will fail if the provided certificate chain (the `intermediate_certs_der` argument to `CertificateValidator`) is incomplete or incorrect, meaning the path from the end-entity certificate to a trusted root cannot be constructed. Always ensure you have the full chain from the server or source.
fix
When fetching certificates from a TLS server, use mechanisms that provide the full certificate chain (e.g., `oscrypto.tls.TLSSocket`'s `peer_certificate` and `intermediate_certificates`). If loading from files, ensure all intermediate certificates are present.
affects: All
gotchaSince version 0.5.0, `certvalidator` defaults to a 'hard-fail' policy for OCSP responses. If an OCSP response cannot be fetched or is invalid, validation will fail unless explicitly configured otherwise via `OCSPChecker(soft_fail=True)`.
fix
If you prefer 'soft-fail' behavior where unresolvable OCSP issues do not halt validation, instantiate `OCSPChecker(soft_fail=True)` and include it in your `revocation_checkers` list.
affects: >=0.5.0
Errors
Common errors & fixes
certvalidator.errors.PathValidationError: The path could not be validated because...
This error occurs when the library cannot construct a valid certificate path to a trusted root, or encounters a specific issue during the validation process, such as an expired certificate, incorrect key usage, or a hostname mismatch in TLS validation.
fix
Ensure all intermediate certificates are provided to the `CertificateValidator`, configure appropriate trust roots via `ValidationContext`, verify certificate validity dates, and confirm key usage settings. For TLS, ensure the `hostname` parameter in `validate_tls()` matches the certificate's subject alternative names.
Revocation checking issues (e.g., 'Could not fetch CRL from...' or OCSP validation failures)
By default, `certvalidator` does not perform revocation checking. When enabled, issues can arise from inaccessible CRL Distribution Points (CDPs) or OCSP responders, expired CRLs, network connectivity problems, or malformed/unusable OCSP responses.
fix
Enable revocation checking by setting `validation_context.allow_fetching = True` and specifying a `revocation_mode` (e.g., 'hard-fail', 'require') in your `ValidationContext`. Ensure network access to CRL and OCSP URLs. If fetching externally, provide pre-fetched CRLs/OCSP responses to the `ValidationContext`.
TypeError: end_entity_cert must be a byte string or an instance of asn1crypto.x509.Certificate
The `end_entity_cert` (and `intermediate_certs`) parameter passed to the `CertificateValidator` constructor is not in the expected format, such as a Python string instead of bytes, or an incorrect object type.
fix
Provide the certificate data as a DER or PEM-encoded byte string, or as an already parsed `asn1crypto.x509.Certificate` object. For example, `with open('/path/to/cert.crt', 'rb') as f: end_entity_cert = f.read()`.
ModuleNotFoundError: No module named 'asn1crypto'
The `asn1crypto` library, a core dependency for `certvalidator`, is not installed in your Python environment or there's an environment path issue.
fix
Install the `asn1crypto` package using pip: `pip install asn1crypto`. If already installed, check your Python environment and ensure it's active and correctly configured.
Upgrade
Version history
0.11.1latest on PyPI · released Jul 29, 2016
Audit
Dependencies
asn1cryptorequiredLow-level ASN.1 parsing and serialization for certificates.
oscryptorequiredCryptographic operations like hashing and signature verification, and TLS socket functionality.
pyca-cryptographyrequiredProvides additional cryptographic primitives for certificate parsing and validation.
idnarequiredInternationalized Domain Names in Applications (IDNA) support for hostname validation.
urllib3requiredHTTP client for fetching CRLs and OCSP responses.
requestsrequiredHTTP client, often used for fetching CRLs and OCSP responses indirectly via urllib3.
Agent activity
20 hits · last 30 days
node
18
OpenAI (training)
1
Resources