pyhanko_certvalidator package

Subpackages

Submodules

pyhanko_certvalidator.asn1_types module

class pyhanko_certvalidator.asn1_types.Target(name=None, value=None, **kwargs)

Bases: Choice

class pyhanko_certvalidator.asn1_types.TargetCert(value=None, default=None, **kwargs)

Bases: Sequence

class pyhanko_certvalidator.asn1_types.Targets(value=None, default=None, contents=None, spec=None, **kwargs)

Bases: SequenceOf

class pyhanko_certvalidator.asn1_types.SequenceOfTargets(value=None, default=None, contents=None, spec=None, **kwargs)

Bases: SequenceOf

class pyhanko_certvalidator.asn1_types.AttrSpec(value=None, default=None, contents=None, spec=None, **kwargs)

Bases: SequenceOf

class pyhanko_certvalidator.asn1_types.AAControls(value=None, default=None, **kwargs)

Bases: Sequence

accept(attr_id: AttCertAttributeType) bool
classmethod read_extension_value(cert: Certificate) AAControls | None

pyhanko_certvalidator.authority module

class pyhanko_certvalidator.authority.TrustQualifiers(standard_parameters: PKIXValidationParams | None = None, max_path_length: int | None = None, max_aa_path_length: int | None = None)

Bases: object

Parameters that allow a trust root to be qualified.

standard_parameters: PKIXValidationParams | None = None

Standard validation parameters that will apply when initialising the PKIX validation process.

max_path_length: int | None = None

Maximal allowed path length for this trust root, excluding self-issued intermediate CA certificates. If None, any path length will be accepted.

max_aa_path_length: int | None = None

Maximal allowed path length for this trust root for the purposes of AAControls. If None, any path length will be accepted.

class pyhanko_certvalidator.authority.Authority

Bases: ABC

Added in version 0.20.0.

Abstract authority, i.e. a named key.

property name: Name

The authority’s name.

property public_key: PublicKeyInfo

The authority’s public key.

property hashable

A hashable unique identifier of the authority, used in __eq__ and __hash__.

property key_id: bytes | None

Key ID as (potentially) referenced in an authorityKeyIdentifier extension. Only used to eliminate non-matching trust anchors, never to retrieve keys or to definitively identify trust anchors.

is_potential_issuer_of(cert: Certificate) bool

Function to determine whether this trust root could potentially be an issuer of a given certificate. This function is used during path building.

Parameters:

cert – The certificate to evaluate.

class pyhanko_certvalidator.authority.TrustAnchor(authority: Authority, quals: TrustQualifiers | None = None)

Bases: object

Abstract trust root. A trust root is an authority with trust qualifiers. Equality of trust roots reduces to equality of authorities.

property authority: Authority
property trust_qualifiers: TrustQualifiers

Qualifiers for the trust root.

pyhanko_certvalidator.authority.derive_quals_from_cert(cert: Certificate) TrustQualifiers

Extract trust qualifiers from data and extensions of a certificate.

Note

Recall that any property of a trust root other than its name and public key are in principle irrelevant to the PKIX validation algorithm itself. This function is merely a helper function that allows the certificate’s other data to be conveniently gathered to populate the default validation parameters for paths deriving from that trust root.

Parameters:

cert – The certificate from which to extract qualifiers (usually a self-signed one)

Returns:

A TrustQualifiers object with the extracted qualifiers.

class pyhanko_certvalidator.authority.AuthorityWithCert(cert: Certificate)

Bases: Authority

Added in version 0.20.0.

Authority provisioned as a certificate.

Parameters:

cert – The certificate.

property name: Name

The authority’s name.

property public_key

The authority’s public key.

property hashable

A hashable unique identifier of the authority, used in __eq__ and __hash__.

property key_id: bytes | None

Key ID as (potentially) referenced in an authorityKeyIdentifier extension. Only used to eliminate non-matching trust anchors, never to retrieve keys or to definitively identify trust anchors.

property certificate: Certificate
is_potential_issuer_of(cert: Certificate)

Function to determine whether this trust root could potentially be an issuer of a given certificate. This function is used during path building.

Parameters:

cert – The certificate to evaluate.

class pyhanko_certvalidator.authority.CertTrustAnchor(cert: Certificate, quals: TrustQualifiers | None = None, derive_default_quals_from_cert: bool = False)

Bases: TrustAnchor

Added in version 0.20.0.

Trust anchor provisioned as a certificate.

Parameters:
  • cert – The certificate, usually self-signed.

  • quals – Explicit trust qualifiers.

  • derive_default_quals_from_cert – Flag indicating to derive default trust qualifiers from the certificate content if explicit ones are not provided. Defaults to False.

property certificate: Certificate
property trust_qualifiers: TrustQualifiers

Qualifiers for the trust root.

class pyhanko_certvalidator.authority.NamedKeyAuthority(entity_name: Name, public_key: PublicKeyInfo)

Bases: Authority

Authority provisioned as a named key.

Parameters:
  • entity_name – The name of the entity that controls the private key of the trust root.

  • public_key – The trust root’s public key.

property name: Name

The authority’s name.

property public_key

The authority’s public key.

property key_id: bytes | None

Key ID as (potentially) referenced in an authorityKeyIdentifier extension. Only used to eliminate non-matching trust anchors, never to retrieve keys or to definitively identify trust anchors.

property hashable

A hashable unique identifier of the authority, used in __eq__ and __hash__.

pyhanko_certvalidator.context module

class pyhanko_certvalidator.context.ACTargetDescription(validator_names: ~typing.List[~asn1crypto.x509.GeneralName] = <factory>, group_memberships: ~typing.List[~asn1crypto.x509.GeneralName] = <factory>)

Bases: object

Value type to guide attribute certificate targeting checks, for attribute certificates that use the target information extension.

As stipulated in RFC 5755, an AC targeting check passes if the information in the relevant AATargetDescription matches at least one Target in the AC’s target information extension.

validator_names: List[GeneralName]

The validating entity’s names.

This value is matched directly against any Target``s that use the ``targetName alternative.

group_memberships: List[GeneralName]

The validating entity’s group memberships.

This value is matched against any Target``s that use the ``targetGroup alternative.

class pyhanko_certvalidator.context.ValidationContext(trust_roots: Iterable[Certificate | TrustAnchor] | None = None, extra_trust_roots: Iterable[Certificate | TrustAnchor] | None = None, other_certs: Iterable[Certificate] | None = None, whitelisted_certs: Iterable[bytes | str] | None = None, moment: datetime | None = None, best_signature_time: datetime | None = None, allow_fetching: bool = False, crls: Iterable[bytes | CertificateList] | None = None, ocsps: Iterable[bytes | OCSPResponse] | None = None, revocation_mode: str = 'soft-fail', revinfo_policy: CertRevTrustPolicy | None = None, weak_hash_algos: Iterable[str] | None = None, time_tolerance: timedelta = datetime.timedelta(seconds=1), retroactive_revinfo: bool = False, fetcher_backend: FetcherBackend | None = None, acceptable_ac_targets: ACTargetDescription | None = None, poe_manager: POEManager | None = None, revinfo_manager: RevinfoManager | None = None, certificate_registry: CertificateRegistry | None = None, trust_manager: TrustManager | None = None, algorithm_usage_policy: AlgorithmUsagePolicy | None = None, fetchers: Fetchers | None = None)

Bases: object

property revinfo_manager: RevinfoManager
property revinfo_policy: CertRevTrustPolicy
property retroactive_revinfo: bool
property time_tolerance: timedelta
property moment: datetime
property best_signature_time: datetime
property fetching_allowed: bool
property crls: List[CertificateList]

A list of all cached crl.CertificateList objects

property ocsps: List[OCSPResponse]

A list of all cached ocsp.OCSPResponse objects

property soft_fail_exceptions

A list of soft-fail exceptions that were ignored during checks

is_whitelisted(cert)

Checks to see if a certificate has been whitelisted

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A bool - if the certificate is whitelisted

async async_retrieve_crls(cert)
Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A list of asn1crypto.crl.CertificateList objects

retrieve_crls(cert)

Deprecated since version 0.17.0: Use async_retrieve_crls() instead.

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A list of asn1crypto.crl.CertificateList objects

async async_retrieve_ocsps(cert, issuer)
Parameters:
  • cert – An asn1crypto.x509.Certificate object

  • issuer – An asn1crypto.x509.Certificate object of cert’s issuer

Returns:

A list of asn1crypto.ocsp.OCSPResponse objects

retrieve_ocsps(cert, issuer)

Deprecated since version 0.17.0: Use async_retrieve_ocsps() instead.

Parameters:
  • cert – An asn1crypto.x509.Certificate object

  • issuer – An asn1crypto.x509.Certificate object of cert’s issuer

Returns:

A list of asn1crypto.ocsp.OCSPResponse objects

record_validation(cert, path)

Records that a certificate has been validated, along with the path that was used for validation. This helps reduce duplicate work when validating a ceritifcate and related resources such as CRLs and OCSPs.

Parameters:
  • cert – An ans1crypto.x509.Certificate object

  • path – A pyhanko_certvalidator.path.ValidationPath object

check_validation(cert)

Checks to see if a certificate has been validated, and if so, returns the ValidationPath used to validate it.

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

None if not validated, or a pyhanko_certvalidator.path.ValidationPath object of the validation path

clear_validation(cert)

Clears the record that a certificate has been validated

Parameters:

cert – An ans1crypto.x509.Certificate object

property acceptable_ac_targets: ACTargetDescription | None
class pyhanko_certvalidator.context.ValidationDataHandlers(revinfo_manager: RevinfoManager, poe_manager: POEManager, cert_registry: CertificateRegistry)

Bases: object

Value class to hold ‘manager’/’registry’ objects. These are responsible for accumulating and exposing various data collections that are relevant for certificate validation.

revinfo_manager: RevinfoManager

The revocation information manager.

poe_manager: POEManager

The proof-of-existence record manager.

cert_registry: CertificateRegistry

The certificate registry.

Note

The certificate registry is a trustless construct. It only holds certificates, but does mark them as trusted or store information related to how the certificates fit together.

pyhanko_certvalidator.context.bootstrap_validation_data_handlers(fetchers: ~pyhanko_certvalidator.fetchers.api.Fetchers | ~pyhanko_certvalidator.fetchers.api.FetcherBackend | None = <pyhanko_certvalidator.fetchers.requests_fetchers.RequestsFetcherBackend object>, crls: ~typing.Iterable[~pyhanko_certvalidator.revinfo.archival.CRLContainer] = (), ocsps: ~typing.Iterable[~pyhanko_certvalidator.revinfo.archival.OCSPContainer] = (), certs: ~typing.Iterable[~asn1crypto.x509.Certificate] = (), poe_manager: ~pyhanko_certvalidator.ltv.poe.POEManager | None = None, nonrevoked_assertions: ~typing.Iterable[~pyhanko_certvalidator.policy_decl.NonRevokedStatusAssertion] = ()) ValidationDataHandlers

Simple bootstrapping method for a ValidationDataHandlers instance with reasonable defaults.

Parameters:
  • fetchers – Data fetcher implementation and/or backend to use. If None, remote fetching is disabled. The requests-based implementation is the default.

  • crls – Initial collection of CRLs to feed to the revocation info manager.

  • ocsps – Initial collection of OCSP responses to feed to the revocation info manager.

  • certs – Initial collection of certificates to add to the certificate registry.

  • poe_manager – Explicit POE manager. Will instantiate an empty one if left unspecified.

  • nonrevoked_assertions – Assertions about the non-revoked status of certain certificates that will be taken as true by fiat.

Returns:

A ValidationDataHandlers object.

class pyhanko_certvalidator.context.CertValidationPolicySpec(trust_manager: ~pyhanko_certvalidator.registry.TrustManager, revinfo_policy: ~pyhanko_certvalidator.policy_decl.CertRevTrustPolicy, time_tolerance: ~datetime.timedelta = datetime.timedelta(seconds=1), acceptable_ac_targets: ~pyhanko_certvalidator.context.ACTargetDescription | None = None, algorithm_usage_policy: ~pyhanko_certvalidator.policy_decl.AlgorithmUsagePolicy | None = <pyhanko_certvalidator.policy_decl.DisallowWeakAlgorithmsPolicy object>, pkix_validation_params: ~pyhanko_certvalidator.policy_decl.PKIXValidationParams | None = None)

Bases: object

Policy object describing how to validate certificates at a high level.

Note

A certificate validation policy differs from a validation context in that ValidationContext objects keep state as well. This is not the case for a certificate validation policy, which makes them suitable for reuse in complex validation workflows where the same policy needs to be applied independently in multiple steps.

Warning

While a certification policy spec is intended to be stateless, some of its fields are abstract classes. As such, the true behaviour may depend on the underlying implementation.

trust_manager: TrustManager

The trust manager that defines this policy’s trust anchors.

revinfo_policy: CertRevTrustPolicy

The policy describing how to handle certificate revocation and associated revocation information.

time_tolerance: timedelta = datetime.timedelta(seconds=1)

The time drift tolerated during validation. Defaults to one second.

acceptable_ac_targets: ACTargetDescription | None = None

Targets to accept when evaluating the scope of an attribute certificate.

algorithm_usage_policy: AlgorithmUsagePolicy | None = <pyhanko_certvalidator.policy_decl.DisallowWeakAlgorithmsPolicy object>

Policy on cryptographic algorithm usage. If left unspecified, a default will be used.

pkix_validation_params: PKIXValidationParams | None = None

The PKIX validation parameters to use, as defined in RFC 5280.

build_validation_context(timing_info: ValidationTimingInfo, handlers: ValidationDataHandlers | None) ValidationContext

Build a validation context from this policy, validation timing info and a set of validation data handlers.

Parameters:
  • timing_info – Timing settings.

  • handlers – Optionally specify validation data handlers. A reasonable default will be supplied if absent.

Returns:

A new ValidationContext reflecting the parameters.

pyhanko_certvalidator.errors module

exception pyhanko_certvalidator.errors.PathError

Bases: Exception

exception pyhanko_certvalidator.errors.PathBuildingError

Bases: PathError

exception pyhanko_certvalidator.errors.CertificateFetchError

Bases: PathBuildingError

exception pyhanko_certvalidator.errors.CRLValidationError

Bases: Exception

exception pyhanko_certvalidator.errors.CRLNoMatchesError

Bases: CRLValidationError

exception pyhanko_certvalidator.errors.CRLFetchError

Bases: CRLValidationError

exception pyhanko_certvalidator.errors.CRLValidationIndeterminateError(msg: str, failures: List[str], suspect_stale: datetime | None = None)

Bases: CRLValidationError

exception pyhanko_certvalidator.errors.OCSPValidationError

Bases: Exception

exception pyhanko_certvalidator.errors.OCSPNoMatchesError

Bases: OCSPValidationError

exception pyhanko_certvalidator.errors.OCSPValidationIndeterminateError(msg: str, failures: List[str], suspect_stale: datetime | None = None)

Bases: OCSPValidationError

exception pyhanko_certvalidator.errors.OCSPFetchError

Bases: OCSPValidationError

exception pyhanko_certvalidator.errors.ValidationError(message: str)

Bases: Exception

exception pyhanko_certvalidator.errors.PathValidationError(msg: str, *, proc_state: ValProcState)

Bases: ValidationError

classmethod from_state(msg: str, proc_state: ValProcState) TPathErr
exception pyhanko_certvalidator.errors.RevokedError(msg, reason: CRLReason, revocation_dt: datetime, proc_state: ValProcState)

Bases: PathValidationError

classmethod format(reason: CRLReason, revocation_dt: datetime, revinfo_type: str, proc_state: ValProcState)
exception pyhanko_certvalidator.errors.InsufficientRevinfoError(msg: str, *, proc_state: ValProcState)

Bases: PathValidationError

exception pyhanko_certvalidator.errors.StaleRevinfoError(msg: str, time_cutoff: datetime, proc_state: ValProcState)

Bases: InsufficientRevinfoError

classmethod format(msg: str, time_cutoff: datetime, proc_state: ValProcState)
exception pyhanko_certvalidator.errors.InsufficientPOEError(msg: str, *, proc_state: ValProcState)

Bases: PathValidationError

exception pyhanko_certvalidator.errors.ExpiredError(msg, expired_dt: datetime, proc_state: ValProcState)

Bases: PathValidationError

classmethod format(*, expired_dt: datetime, proc_state: ValProcState)
exception pyhanko_certvalidator.errors.NotYetValidError(msg, valid_from: datetime, proc_state: ValProcState)

Bases: PathValidationError

classmethod format(*, valid_from: datetime, proc_state: ValProcState)
exception pyhanko_certvalidator.errors.InvalidCertificateError(message: str)

Bases: ValidationError

exception pyhanko_certvalidator.errors.DisallowedAlgorithmError(*args, banned_since: datetime | None = None, **kwargs)

Bases: PathValidationError

classmethod from_state(msg: str, proc_state: ValProcState, banned_since: datetime | None = None) DisallowedAlgorithmError
exception pyhanko_certvalidator.errors.InvalidAttrCertificateError(message: str)

Bases: InvalidCertificateError

exception pyhanko_certvalidator.errors.PSSParameterMismatch

Bases: InvalidSignature

exception pyhanko_certvalidator.errors.DSAParametersUnavailable

Bases: InvalidSignature

pyhanko_certvalidator.name_trees module

exception pyhanko_certvalidator.name_trees.NameConstraintError

Bases: ValueError

pyhanko_certvalidator.name_trees.host_tree_contains(base_host: str, other_host: str) bool
pyhanko_certvalidator.name_trees.uri_tree_contains(base: str, other: str) bool
pyhanko_certvalidator.name_trees.dns_tree_contains(base: str, other: str)
pyhanko_certvalidator.name_trees.email_tree_contains(base: str, other: str)
pyhanko_certvalidator.name_trees.dirname_tree_contains(base: Name, other: Name)
class pyhanko_certvalidator.name_trees.GeneralNameType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

OTHER_NAME = 1
RFC822_NAME = 2
DNS_NAME = 3
X400_ADDRESS = 4
DIRECTORY_NAME = 5
EDI_PARTY_NAME = 6
UNIFORM_RESOURCE_IDENTIFIER = 7
IP_ADDRESS = 8
REGISTERED_ID = 9
property check_membership: Callable[[str | Name, str | Name], bool] | None
classmethod from_choice(choice) GeneralNameType
exception pyhanko_certvalidator.name_trees.UnsupportedNameTypeError(name_type: GeneralNameType)

Bases: NotImplementedError

class pyhanko_certvalidator.name_trees.NameSubtree(name_type: pyhanko_certvalidator.name_trees.GeneralNameType, tree_base: pyhanko_certvalidator.name_trees._StringOrName | None, min: int = 0, max: int | None = None)

Bases: object

name_type: GeneralNameType
tree_base: _StringOrName | None
min: int = 0
max: int | None = None
classmethod from_name(name_type: GeneralNameType, name: str | Name)
classmethod from_general_subtree(subtree) NameSubtree
classmethod universal_tree(name_type: GeneralNameType) NameSubtree

Tree that contains all names of a given type.

Parameters:

name_type – The name type to use.

Returns:

pyhanko_certvalidator.name_trees.x509_names_to_subtrees(names: Iterable[Name]) Dict[GeneralNameType, Set[NameSubtree]]
pyhanko_certvalidator.name_trees.process_general_subtrees(subtrees: GeneralSubtrees) Dict[GeneralNameType, Set[NameSubtree]]
class pyhanko_certvalidator.name_trees.NameConstraintValidationResult(failing_name_type: GeneralNameType | None = None, failing_name: str | Name | None = None)

Bases: object

property error_message
class pyhanko_certvalidator.name_trees.PermittedSubtrees(initial_permitted_subtrees: Dict[GeneralNameType, Set[NameSubtree]])

Bases: object

intersect_with(trees: Dict[GeneralNameType, Set[NameSubtree]])
accept_name(name_type: GeneralNameType, name) bool
accept_cert(cert: Certificate) NameConstraintValidationResult
class pyhanko_certvalidator.name_trees.ExcludedSubtrees(initial_excluded_subtrees: Dict[GeneralNameType, Set[NameSubtree]])

Bases: object

union_with(trees: Dict[GeneralNameType, Set[NameSubtree]])
reject_name(name_type: GeneralNameType, name) bool
accept_cert(cert: Certificate) NameConstraintValidationResult
pyhanko_certvalidator.name_trees.default_permitted_subtrees() Dict[GeneralNameType, Set[NameSubtree]]
pyhanko_certvalidator.name_trees.default_excluded_subtrees() Dict[GeneralNameType, Set[NameSubtree]]

pyhanko_certvalidator.path module

class pyhanko_certvalidator.path.QualifiedPolicy(issuer_domain_policy_id: str, user_domain_policy_id: str, qualifiers: frozenset)

Bases: object

issuer_domain_policy_id: str

Policy OID in the issuer domain (i.e. as listed on the certificate).

user_domain_policy_id: str

Policy OID of the equivalent policy in the user domain.

qualifiers: frozenset

Set of x509.PolicyQualifierInfo objects.

class pyhanko_certvalidator.path.ValidationPath(trust_anchor: TrustAnchor, interm: Iterable[Certificate], leaf: Certificate | AttributeCertificateV2 | None)

Bases: object

Represents a path going towards an end-entity certificate or attribute certificate.

property trust_anchor: TrustAnchor
property first

Returns the current beginning of the path - for a path to be complete, this certificate should be a trust root

Warning

This is a compatibility property, and will return the first non-root certificate if the trust root is not provisioned as a certificate. If you want the trust root itself (even when it doesn’t have a certificate), use trust_anchor.

Returns:

The first asn1crypto.x509.Certificate object in the path

property leaf: Certificate | AttributeCertificateV2 | None

Returns the current leaf certificate (AC or public-key). The trust root’s certificate will be returned if there is one and there are no other certificates in the path.

If the trust root is certificate-less and there are no certificates, the result will be None.

describe_leaf() str | None
get_ee_cert_safe() Certificate | None

Returns the current leaf certificate if it is an X.509 public-key certificate, and None otherwise. :return:

property last: Certificate

Returns the last certificate in the path if it is an X.509 public-key certificate, and throws an error otherwise.

Returns:

The last asn1crypto.x509.Certificate object in the path

iter_authorities() Iterable[Authority]

Iterate over all authorities in the path, including the trust root.

find_issuing_authority(cert: Certificate | AttributeCertificateV2)

Return the issuer of the cert specified, as defined by this path

Parameters:

cert – A certificate to get the issuer of

Raises:

LookupError - when the issuer of the certificate could not be found

Returns:

An asn1crypto.x509.Certificate object of the issuer

truncate_to_and_append(cert: Certificate, new_leaf: Certificate | AttributeCertificateV2)

Remove all certificates in the path after the cert specified and return them in a new path.

Internal API.

Parameters:
  • cert – An asn1crypto.x509.Certificate object to find

  • new_leaf – A new leaf certificate to append.

Raises:

LookupError - when the certificate could not be found

Returns:

The current ValidationPath object, for chaining

truncate_to_issuer_and_append(cert: Certificate)

Remove all certificates in the path after the issuer of the cert specified, as defined by this path, and append a new one.

Internal API.

Parameters:

cert – A new leaf certificate to append.

Raises:

LookupError - when the issuer of the certificate could not be found

Returns:

The current ValidationPath object, for chaining

copy_and_append(cert: Certificate | AttributeCertificateV2)
copy_and_drop_leaf() ValidationPath

Drop the leaf cert from this path and return a new path with the last intermediate certificate set as the leaf.

qualified_policies() FrozenSet[QualifiedPolicy] | None
aa_attr_in_scope(attr_id: AttCertAttributeType) bool
property pkix_len
iter_certs(include_root: bool) Iterator[Certificate]

Iterate over the certificates in the path.

Parameters:

include_root – Include the root (if it is supplied as a certificate)

Returns:

An iterator.

pyhanko_certvalidator.policy_decl module

Added in version 0.20.0.

class pyhanko_certvalidator.policy_decl.RevocationCheckingRule(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Rules determining in what circumstances revocation data has to be checked, and what kind.

CRL_REQUIRED = 'clrcheck'

Check CRLs.

OCSP_REQUIRED = 'ocspcheck'

Check OCSP.

CRL_AND_OCSP_REQUIRED = 'bothcheck'

Check CRL and OCSP.

CRL_OR_OCSP_REQUIRED = 'eithercheck'

Check CRL or OCSP.

NO_CHECK = 'nocheck'

Do not check.

CHECK_IF_DECLARED = 'ifdeclaredcheck'

Check revocation information if declared in the certificate.

Warning

This is not an ESI check type, but is preserved for compatibility with the ‘hard-fail’ mode in certvalidator.

Note

In this mode, cached CRLs will _not_ be checked if the certificate does not list any distribution points.

CHECK_IF_DECLARED_SOFT = 'ifdeclaredsoftcheck'

Check revocation information if declared in the certificate, but do not fail validation if the check fails.

Warning

This is not an ESI check type, but is preserved for compatibility with the ‘soft-fail’ mode in certvalidator.

Note

In this mode, cached CRLs will _not_ be checked if the certificate does not list any distribution points.

property strict: bool
property tolerant: bool
property crl_mandatory: bool
property crl_relevant: bool
property ocsp_mandatory: bool
property ocsp_relevant: bool
class pyhanko_certvalidator.policy_decl.RevocationCheckingPolicy(ee_certificate_rule: RevocationCheckingRule, intermediate_ca_cert_rule: RevocationCheckingRule)

Bases: object

Class describing a revocation checking policy based on the types defined in the ETSI TS 119 172 series.

ee_certificate_rule: RevocationCheckingRule

Revocation rule applied to end-entity certificates.

intermediate_ca_cert_rule: RevocationCheckingRule

Revocation rule applied to certificates further up the path.

classmethod from_legacy(policy: str)
property essential: bool
class pyhanko_certvalidator.policy_decl.FreshnessReqType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Freshness requirement type.

DEFAULT = 1

The default freshness policy, i.e. the certvalidator legacy policy. This policy considers revocation info valid between its thisUpdate and nextUpdate times, but not outside of that window.

MAX_DIFF_REVOCATION_VALIDATION = 2

Freshness policy requiring that the validation time, if later than the issuance date of the revocation info, be sufficiently close to that issuance date.

TIME_AFTER_SIGNATURE = 3

Freshness policy requiring that the revocation info be issued after a predetermined “cooldown period” after the certificate was used to produce a signature.

class pyhanko_certvalidator.policy_decl.CertRevTrustPolicy(revocation_checking_policy: RevocationCheckingPolicy, freshness: timedelta | None = None, freshness_req_type: FreshnessReqType = FreshnessReqType.DEFAULT, expected_post_expiry_revinfo_time: timedelta | None = None, retroactive_revinfo: bool = False)

Bases: object

Class describing conditions for trusting revocation info. Based on CertificateRevTrust in ETSI TS 119 172-3.

revocation_checking_policy: RevocationCheckingPolicy

The revocation checking policy requirements.

freshness: timedelta | None = None

Freshness interval. If not specified, this defaults to the distance between thisUpdate and nextUpdate for the given piece of revocation information. If the nextUpdate field is not present, then the effective default is 30 minutes.

freshness_req_type: FreshnessReqType = 1

Controls whether the freshness requirement applies relatively to the signing time or to the validation time.

expected_post_expiry_revinfo_time: timedelta | None = None

Duration for which the issuing CA is expected to supply status information after a certificate expires.

retroactive_revinfo: bool = False

Treat revocation info as retroactively valid, i.e. ignore the this_update field in CRLs and OCSP responses. This parameter is not taken into account for freshness policies other than FreshnessReqType.DEFAULT, and is False by default in those cases.

Warning

Be careful with this option, since it will cause incorrect behaviour for CAs that make use of certificate holds or other reversible revocation methods.

class pyhanko_certvalidator.policy_decl.PKIXValidationParams(user_initial_policy_set: frozenset = frozenset({'any_policy'}), initial_policy_mapping_inhibit: bool = False, initial_explicit_policy: bool = False, initial_any_policy_inhibit: bool = False, initial_permitted_subtrees: Dict[pyhanko_certvalidator.name_trees.GeneralNameType, Set[pyhanko_certvalidator.name_trees.NameSubtree]] | None = None, initial_excluded_subtrees: Dict[pyhanko_certvalidator.name_trees.GeneralNameType, Set[pyhanko_certvalidator.name_trees.NameSubtree]] | None = None)

Bases: object

user_initial_policy_set: frozenset = frozenset({'any_policy'})

Set of policies that the user is willing to accept. By default, any policy is acceptable.

When setting this parameter to a non-default value, you probably want to set initial_explicit_policy as well.

Note

These are specified in the policy domain of the trust root(s), and subject to policy mapping by intermediate certificate authorities.

initial_policy_mapping_inhibit: bool = False

Flag indicating whether policy mapping is forbidden along the entire certification chains. By default, policy mapping is permitted.

Note

Policy constraints on intermediate certificates may force policy mapping to be inhibited from some point onwards.

initial_explicit_policy: bool = False

Flag indicating whether path validation must terminate with at least one permissible policy; see user_initial_policy_set. By default, no such requirement is imposed.

Note

If user_initial_policy_set is set to its default value of {'any_policy'}, the effect is that the path validation must accept at least one policy, without specifying which.

Warning

Due to widespread mis-specification of policy extensions in the wild, many real-world certification chains terminate with an empty set (or rather, tree) of valid policies. Therefore, this flag is set to False by default.

initial_any_policy_inhibit: bool = False

Flag indicating whether anyPolicy should be left unprocessed when it appears in a certificate. By default, anyPolicy is always processed when it appears.

initial_permitted_subtrees: Dict[GeneralNameType, Set[NameSubtree]] | None = None

Set of permitted subtrees for each name type, indicating restrictions to impose on subject names (and alternative names) in the certification path.

By default, all names are permitted. This behaviour can be modified by name constraints on intermediate CA certificates.

initial_excluded_subtrees: Dict[GeneralNameType, Set[NameSubtree]] | None = None

Set of excluded subtrees for each name type, indicating restrictions to impose on subject names (and alternative names) in the certification path.

By default, no names are excluded. This behaviour can be modified by name constraints on intermediate CA certificates.

merge(other: PKIXValidationParams) PKIXValidationParams

Combine the conditions of these PKIX validation params with another set of parameters, producing the most lenient set of parameters that is stricter than both inputs.

Parameters:

other – Another set of PKIX validation parameters.

Returns:

A combined set of PKIX validation parameters.

class pyhanko_certvalidator.policy_decl.AlgorithmUsageConstraint(allowed: bool, not_allowed_after: datetime | None = None, failure_reason: str | None = None)

Bases: object

Expression of a constraint on the usage of an algorithm (possibly with parameter choices).

allowed: bool

Flag indicating whether the algorithm can be used.

not_allowed_after: datetime | None = None

Date indicating when the algorithm became unavailable (given the relevant choice of parameters, if applicable).

failure_reason: str | None = None

A human-readable description of the failure reason, if applicable.

class pyhanko_certvalidator.policy_decl.AlgorithmUsagePolicy

Bases: ABC

Abstract interface defining a usage policy for cryptographic algorithms.

digest_algorithm_allowed(algo: DigestAlgorithm, moment: datetime | None) AlgorithmUsageConstraint

Determine if the indicated digest algorithm can be used at the point in time indicated.

Parameters:
  • algo – A digest algorithm description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

signature_algorithm_allowed(algo: SignedDigestAlgorithm, moment: datetime | None, public_key: PublicKeyInfo | None) AlgorithmUsageConstraint

Determine if the indicated signature algorithm (including the associated digest function and any parameters, if applicable) can be used at the point in time indicated.

Parameters:
  • algo – A signature mechanism description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

  • public_key

    The public key associated with the operation, if available.

    Note

    This parameter can be used to enforce key size limits or to filter out keys with known structural weaknesses.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

class pyhanko_certvalidator.policy_decl.DisallowWeakAlgorithmsPolicy(weak_hash_algos=frozenset({'md2', 'md5', 'sha1'}), weak_signature_algos=frozenset({}), rsa_key_size_threshold=2048, dsa_key_size_threshold=3192)

Bases: AlgorithmUsagePolicy

Primitive usage policy that forbids a list of user-specified “weak” algorithms and allows everything else. It also ignores the time parameter completely.

Note

This denial-based strategy is supplied to provide a backwards-compatible default. In many scenarios, an explicit allow-based strategy is more appropriate. Users with specific security requirements are encouraged to implement AlgorithmUsagePolicy themselves.

Parameters:
  • weak_hash_algos – The list of digest algorithms considered weak. Defaults to DEFAULT_WEAK_HASH_ALGOS.

  • weak_signature_algos – The list of digest algorithms considered weak. Defaults to the empty set.

  • rsa_key_size_threshold – The key length threshold for RSA keys, in bits.

  • dsa_key_size_threshold – The key length threshold for DSA keys, in bits.

digest_algorithm_allowed(algo: DigestAlgorithm, moment: datetime | None) AlgorithmUsageConstraint

Determine if the indicated digest algorithm can be used at the point in time indicated.

Parameters:
  • algo – A digest algorithm description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

signature_algorithm_allowed(algo: SignedDigestAlgorithm, moment: datetime | None, public_key: PublicKeyInfo | None) AlgorithmUsageConstraint

Determine if the indicated signature algorithm (including the associated digest function and any parameters, if applicable) can be used at the point in time indicated.

Parameters:
  • algo – A signature mechanism description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

  • public_key

    The public key associated with the operation, if available.

    Note

    This parameter can be used to enforce key size limits or to filter out keys with known structural weaknesses.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

class pyhanko_certvalidator.policy_decl.AcceptAllAlgorithms

Bases: AlgorithmUsagePolicy

digest_algorithm_allowed(algo: DigestAlgorithm, moment: datetime | None) AlgorithmUsageConstraint

Determine if the indicated digest algorithm can be used at the point in time indicated.

Parameters:
  • algo – A digest algorithm description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

signature_algorithm_allowed(algo: SignedDigestAlgorithm, moment: datetime | None, public_key: PublicKeyInfo | None) AlgorithmUsageConstraint

Determine if the indicated signature algorithm (including the associated digest function and any parameters, if applicable) can be used at the point in time indicated.

Parameters:
  • algo – A signature mechanism description in ASN.1 form.

  • moment – The point in time at which the algorithm should be usable. If None, then the returned judgment applies at all times.

  • public_key

    The public key associated with the operation, if available.

    Note

    This parameter can be used to enforce key size limits or to filter out keys with known structural weaknesses.

Returns:

A AlgorithmUsageConstraint expressing the judgment.

class pyhanko_certvalidator.policy_decl.NonRevokedStatusAssertion(cert_sha256: bytes, at: datetime)

Bases: object

Assert that a certificate was not revoked at some given date.

cert_sha256: bytes

SHA-256 hash of the certificate.

at: datetime

Moment in time at which the assertion is to be considered valid.

pyhanko_certvalidator.policy_decl.DEFAULT_WEAK_HASH_ALGOS = frozenset({'md2', 'md5', 'sha1'})

Digest algorithms considered weak by default.

pyhanko_certvalidator.policy_decl.REQUIRE_REVINFO = RevocationCheckingPolicy(ee_certificate_rule=<RevocationCheckingRule.CRL_OR_OCSP_REQUIRED: 'eithercheck'>, intermediate_ca_cert_rule=<RevocationCheckingRule.CRL_OR_OCSP_REQUIRED: 'eithercheck'>)

Policy indicating that revocation information is always required, but either OCSP or CRL-based revocation information is OK.

pyhanko_certvalidator.policy_decl.NO_REVOCATION = RevocationCheckingPolicy(ee_certificate_rule=<RevocationCheckingRule.NO_CHECK: 'nocheck'>, intermediate_ca_cert_rule=<RevocationCheckingRule.NO_CHECK: 'nocheck'>)

Policy indicating that revocation information is never required.

pyhanko_certvalidator.policy_tree module

pyhanko_certvalidator.policy_tree.update_policy_tree(certificate_policies, valid_policy_tree: PolicyTreeRoot, depth: int, any_policy_uninhibited: bool) PolicyTreeRoot | None

Internal method to update the policy tree during RFC 5280 validation.

pyhanko_certvalidator.policy_tree.enumerate_policy_mappings(mappings: Iterable[PolicyMapping], proc_state: ValProcState)

Internal function to process policy mapping extension values into a Python dictionary mapping issuer domain policies to the corresponding policies in the subject policy domain.

pyhanko_certvalidator.policy_tree.apply_policy_mapping(policy_map, valid_policy_tree, depth: int, policy_mapping_uninhibited: bool)

Internal function to apply the policy mapping to the current policy tree in accordance with the algorithm in RFC 5280.

pyhanko_certvalidator.policy_tree.prune_unacceptable_policies(path_length, valid_policy_tree, acceptable_policies) PolicyTreeRoot | None
class pyhanko_certvalidator.policy_tree.PolicyTreeRoot

Bases: object

A generic policy tree node, used for the root node in the tree

classmethod init_policy_tree(valid_policy, qualifier_set, expected_policy_set)

Accepts values for a PolicyTreeNode that will be created at depth 0

Parameters:
  • valid_policy – A unicode string of a policy name or OID

  • qualifier_set – An instance of asn1crypto.x509.PolicyQualifierInfos

  • expected_policy_set – A set of unicode strings containing policy names or OIDs

add_child(valid_policy, qualifier_set, expected_policy_set)

Creates a new PolicyTreeNode as a child of this node

Parameters:
  • valid_policy – A unicode string of a policy name or OID

  • qualifier_set – An instance of asn1crypto.x509.PolicyQualifierInfos

  • expected_policy_set – A set of unicode strings containing policy names or OIDs

remove_child(child)

Removes a child from this node

Parameters:

child – An instance of PolicyTreeNode

at_depth(depth) Iterable[PolicyTreeNode]

Returns a generator yielding all nodes in the tree at a specific depth

Parameters:

depth – An integer >= 0 of the depth of nodes to yield

Returns:

A generator yielding PolicyTreeNode objects

walk_up(depth)

Returns a generator yielding all nodes in the tree at a specific depth, or above. Yields nodes starting with leaves and traversing up to the root.

Parameters:

depth – An integer >= 0 of the depth of nodes to walk up from

Returns:

A generator yielding PolicyTreeNode objects

nodes_in_current_domain() Iterable[PolicyTreeNode]

Returns a generator yielding all nodes in the tree that are children of an any_policy node.

class pyhanko_certvalidator.policy_tree.PolicyTreeNode(valid_policy: str, qualifier_set: PolicyQualifierInfos, expected_policy_set: Set[str])

Bases: PolicyTreeRoot

A policy tree node that is used for all nodes but the root

path_to_root()

pyhanko_certvalidator.registry module

class pyhanko_certvalidator.registry.CertificateCollection

Bases: ABC

Abstract base class for read-only access to a collection of certificates.

retrieve_by_key_identifier(key_identifier: bytes)

Retrieves a cert via its key identifier

Parameters:

key_identifier – A byte string of the key identifier

Returns:

None or an asn1crypto.x509.Certificate object

retrieve_many_by_key_identifier(key_identifier: bytes)

Retrieves possibly multiple certs via the corresponding key identifiers

Parameters:

key_identifier – A byte string of the key identifier

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_name(name: Name)

Retrieves a list certs via their subject name

Parameters:

name – An asn1crypto.x509.Name object

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_issuer_serial(issuer_serial)

Retrieve a certificate by its issuer_serial value.

Parameters:

issuer_serial – The issuer_serial value of the certificate.

Returns:

The certificate corresponding to the issuer_serial key passed in.

Returns:

None or an asn1crypto.x509.Certificate object

class pyhanko_certvalidator.registry.CertificateStore

Bases: CertificateCollection, ABC

register(cert: Certificate) bool

Register a single certificate.

Parameters:

cert – Certificate to add.

Returns:

True if the certificate was added, False if it already existed in this store.

register_multiple(certs: Iterable[Certificate])

Register multiple certificates.

Parameters:

certs – Certificates to register.

Returns:

True if at least one certificate was added, False if all certificates already existed in this store.

class pyhanko_certvalidator.registry.SimpleCertificateStore

Bases: CertificateStore

Simple trustless certificate store.

classmethod from_certs(certs)
register(cert: Certificate) bool

Register a single certificate.

Parameters:

cert – Certificate to add.

Returns:

True if the certificate was added, False if it already existed in this store.

retrieve_many_by_key_identifier(key_identifier: bytes)

Retrieves possibly multiple certs via the corresponding key identifiers

Parameters:

key_identifier – A byte string of the key identifier

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_name(name: Name)

Retrieves a list certs via their subject name

Parameters:

name – An asn1crypto.x509.Name object

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_issuer_serial(issuer_serial)

Retrieve a certificate by its issuer_serial value.

Parameters:

issuer_serial – The issuer_serial value of the certificate.

Returns:

The certificate corresponding to the issuer_serial key passed in.

Returns:

None or an asn1crypto.x509.Certificate object

class pyhanko_certvalidator.registry.TrustManager

Bases: object

Abstract trust manager API.

is_root(cert: Certificate) bool

Checks if a certificate is in the list of trust roots in this registry

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A boolean - if the certificate is in the CA list

find_potential_issuers(cert: Certificate) Iterator[TrustAnchor]

Find potential issuers that might have (directly) issued a particular certificate.

Parameters:

cert – Issued certificate.

Returns:

An iterator with potentially relevant trust anchors.

class pyhanko_certvalidator.registry.SimpleTrustManager

Bases: TrustManager

Trust manager backed by a list of trust roots, possibly in addition to the system trust list.

classmethod build(trust_roots: Iterable[Certificate | TrustAnchor] | None = None, extra_trust_roots: Iterable[Certificate | TrustAnchor] | None = None) SimpleTrustManager
Parameters:
  • trust_roots – If the operating system’s trust list should not be used, instead pass a list of asn1crypto.x509.Certificate objects. These certificates will be used as the trust roots for the path being built.

  • extra_trust_roots – If the operating system’s trust list should be used, but augmented with one or more extra certificates. This should be a list of asn1crypto.x509.Certificate objects.

Returns:

is_root(cert: Certificate)

Checks if a certificate is in the list of trust roots in this registry

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A boolean - if the certificate is in the CA list

iter_certs() Iterator[Certificate]
find_potential_issuers(cert: Certificate) Iterator[TrustAnchor]

Find potential issuers that might have (directly) issued a particular certificate.

Parameters:

cert – Issued certificate.

Returns:

An iterator with potentially relevant trust anchors.

class pyhanko_certvalidator.registry.CertificateRegistry(*, cert_fetcher: CertificateFetcher | None = None)

Bases: SimpleCertificateStore

Contains certificate lists used to build validation paths, and is also capable of fetching missing certificates if a certificate fetcher is supplied.

classmethod build(certs: Iterable[Certificate] = (), *, cert_fetcher: CertificateFetcher | None = None)

Convenience method to set up a certificate registry and import certs into it.

Parameters:
  • certs – Initial list of certificates to import.

  • cert_fetcher – Certificate fetcher to handle retrieval of missing certificates (in situations where that is possible).

Returns:

A populated certificate registry.

retrieve_by_name(name: Name, first_certificate: Certificate | None = None)

Retrieves a list certs via their subject name

Parameters:
  • name – An asn1crypto.x509.Name object

  • first_certificate – An asn1crypto.x509.Certificate object that if found, should be placed first in the result list

Returns:

A list of asn1crypto.x509.Certificate objects

find_potential_issuers(cert: Certificate, trust_manager: TrustManager) Iterator[TrustAnchor | Certificate]
async fetch_missing_potential_issuers(cert: Certificate)
class pyhanko_certvalidator.registry.PathBuilder(trust_manager: TrustManager, registry: CertificateRegistry)

Bases: object

Class to handle path building.

build_paths(end_entity_cert)

Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate

Note

This is a synchronous equivalent of async_build_paths() that calls the latter in a new event loop. As such, it can’t be used from within asynchronous code.

Parameters:

end_entity_cert – A byte string of a DER or PEM-encoded X.509 certificate, or an instance of asn1crypto.x509.Certificate

Returns:

A list of pyhanko_certvalidator.path.ValidationPath objects that represent the possible paths from the end-entity certificate to one of the CA certs.

async async_build_paths(end_entity_cert: Certificate)

Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate, returning all paths in a single list.

Parameters:

end_entity_cert – A byte string of a DER or PEM-encoded X.509 certificate, or an instance of asn1crypto.x509.Certificate

Returns:

A list of pyhanko_certvalidator.path.ValidationPath objects that represent the possible paths from the end-entity certificate to one of the CA certs.

async_build_paths_lazy(end_entity_cert: Certificate) CancelableAsyncIterator[ValidationPath]

Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate, and emit them as an asynchronous generator.

Parameters:

end_entity_cert – A byte string of a DER or PEM-encoded X.509 certificate, or an instance of asn1crypto.x509.Certificate

Returns:

An asynchronous iterator that yields pyhanko_certvalidator.path.ValidationPath objects that represent the possible paths from the end-entity certificate to one of the CA certs, and raises PathBuildingError if no paths could be built

class pyhanko_certvalidator.registry.LazyPathIterator(walker: _PathWalker, cert: Certificate)

Bases: CancelableAsyncIterator[ValidationPath]

async cancel()
class pyhanko_certvalidator.registry.LayeredCertificateStore(stores: List[CertificateCollection])

Bases: CertificateCollection

Trustless certificate store that looks up certificates in other stores in a specific order.

retrieve_many_by_key_identifier(key_identifier: bytes)

Retrieves possibly multiple certs via the corresponding key identifiers

Parameters:

key_identifier – A byte string of the key identifier

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_name(name: Name)

Retrieves a list certs via their subject name

Parameters:

name – An asn1crypto.x509.Name object

Returns:

A list of asn1crypto.x509.Certificate objects

retrieve_by_issuer_serial(issuer_serial)

Retrieve a certificate by its issuer_serial value.

Parameters:

issuer_serial – The issuer_serial value of the certificate.

Returns:

The certificate corresponding to the issuer_serial key passed in.

Returns:

None or an asn1crypto.x509.Certificate object

pyhanko_certvalidator.util module

pyhanko_certvalidator.util.extract_dir_name(names: GeneralNames, err_msg_prefix: str) Name
pyhanko_certvalidator.util.extract_ac_issuer_dir_name(attr_cert: AttributeCertificateV2) Name
pyhanko_certvalidator.util.get_issuer_dn(cert: Certificate | AttributeCertificateV2) Name
pyhanko_certvalidator.util.issuer_serial(cert: Certificate | AttributeCertificateV2) bytes
pyhanko_certvalidator.util.get_ac_extension_value(attr_cert: AttributeCertificateV2, ext_name: str)
pyhanko_certvalidator.util.get_relevant_crl_dps(cert: Certificate | AttributeCertificateV2, *, use_deltas) List[DistributionPoint]
pyhanko_certvalidator.util.get_ocsp_urls(cert: Certificate | AttributeCertificateV2)
pyhanko_certvalidator.util.get_declared_revinfo(cert: Certificate | AttributeCertificateV2)
pyhanko_certvalidator.util.validate_sig(signature: bytes, signed_data: bytes, public_key_info: PublicKeyInfo, sig_algo: str, hash_algo: str, parameters=None)
class pyhanko_certvalidator.util.ConsList(head: 'Optional[ListElem]', tail: 'Optional[ConsList[ListElem]]' = None)

Bases: Generic[ListElem]

head: ListElem | None
tail: ConsList[ListElem] | None = None
static empty() ConsList[ListElem]
static sing(value: ListElem) ConsList[ListElem]
property last: ListElem | None
cons(head: ListElem) ConsList[ListElem]
class pyhanko_certvalidator.util.CancelableAsyncIterator

Bases: ABC, AsyncIterator[T]

async cancel()

pyhanko_certvalidator.validate module

pyhanko_certvalidator.validate.validate_path(validation_context, path, parameters: PKIXValidationParams | None = None)

Validates the path using the algorithm from https://tools.ietf.org/html/rfc5280#section-6.1.

Critical extensions on the end-entity certificate are not validated and are left up to the consuming application to process and/or fail on.

Note

This is a synchronous equivalent of async_validate_path() that calls the latter in a new event loop. As such, it can’t be used from within asynchronous code.

Parameters:
  • validation_context – A pyhanko_certvalidator.context.ValidationContext object to use for configuring validation behavior

  • path – A pyhanko_certvalidator.path.ValidationPath object of the path to validate

  • parameters – Additional input parameters to the PKIX validation algorithm. These are not used when validating CRLs and OCSP responses.

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked

Returns:

The final certificate in the path - an instance of asn1crypto.x509.Certificate

async pyhanko_certvalidator.validate.async_validate_path(validation_context: ValidationContext, path: ValidationPath, parameters: PKIXValidationParams | None = None)

Validates the path using the algorithm from https://tools.ietf.org/html/rfc5280#section-6.1.

Critical extensions on the end-entity certificate are not validated and are left up to the consuming application to process and/or fail on.

Parameters:
  • validation_context – A pyhanko_certvalidator.context.ValidationContext object to use for configuring validation behavior

  • path – A pyhanko_certvalidator.path.ValidationPath object of the path to validate

  • parameters – Additional input parameters to the PKIX validation algorithm. These are not used when validating CRLs and OCSP responses.

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked

Returns:

The final certificate in the path - an instance of asn1crypto.x509.Certificate

pyhanko_certvalidator.validate.validate_tls_hostname(validation_context: ValidationContext, cert: Certificate, hostname: str)

Validates the end-entity certificate from a pyhanko_certvalidator.path.ValidationPath object to ensure that the certificate is valid for the hostname provided and that the certificate is valid for the purpose of a TLS connection.

THE CERTIFICATE PATH MUST BE VALIDATED SEPARATELY VIA validate_path()!

Parameters:
  • validation_context – A pyhanko_certvalidator.context.ValidationContext object to use for configuring validation behavior

  • cert – An asn1crypto.x509.Certificate object returned from validate_path()

  • hostname – A unicode string of the TLS server hostname

Raises:

pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname

pyhanko_certvalidator.validate.validate_usage(validation_context: ValidationContext, cert: Certificate, key_usage: Set[str], extended_key_usage: Set[str], extended_optional: bool)

Validates the end-entity certificate from a pyhanko_certvalidator.path.ValidationPath object to ensure that the certificate is valid for the key usage and extended key usage purposes specified.

THE CERTIFICATE PATH MUST BE VALIDATED SEPARATELY VIA validate_path()!

Parameters:
  • validation_context – A pyhanko_certvalidator.context.ValidationContext object to use for configuring validation behavior

  • cert – An asn1crypto.x509.Certificate object returned from validate_path()

  • key_usage – A set of unicode strings of the required key usage purposes

  • extended_key_usage – A set of unicode strings of the required extended key usage purposes

  • extended_optional – A bool - if the extended_key_usage extension may be omitted and still considered valid

Raises:

pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified

pyhanko_certvalidator.validate.validate_aa_usage(validation_context: ValidationContext, cert: Certificate, extended_key_usage: Set[str] | None = None)

Validate AA certificate profile conditions in RFC 5755 § 4.5

Parameters:
  • validation_context

  • cert

  • extended_key_usage

Returns:

pyhanko_certvalidator.validate.check_ac_holder_match(holder_cert: Certificate, holder: Holder)

Match a candidate holder certificate against the holder entry of an attribute certificate.

Parameters:
  • holder_cert – Candidate holder certificate.

  • holder – Holder value to match against.

Returns:

Return the parts of the holder entry that mismatched as a set. Possible values are ‘base_certificate_id’, ‘entity_name’ and ‘object_digest_info’. If the returned set is empty, all entries in the holder entry matched the information in the certificate.

class pyhanko_certvalidator.validate.ACValidationResult(attr_cert: AttributeCertificateV2, aa_cert: Certificate, aa_path: ValidationPath, approved_attributes: Dict[str, AttCertAttribute])

Bases: object

The result of a successful attribute certificate validation.

attr_cert: AttributeCertificateV2

The attribute certificate that was validated.

aa_cert: Certificate

The attribute authority that issued the certificate.

aa_path: ValidationPath

The validation path of the attribute authority’s certificate.

approved_attributes: Dict[str, AttCertAttribute]

Approved attributes in the attribute certificate, possibly filtered by AA controls.

async pyhanko_certvalidator.validate.async_validate_ac(attr_cert: AttributeCertificateV2, validation_context: ValidationContext, aa_pkix_params: PKIXValidationParams = PKIXValidationParams(user_initial_policy_set=frozenset({'any_policy'}), initial_policy_mapping_inhibit=False, initial_explicit_policy=False, initial_any_policy_inhibit=False, initial_permitted_subtrees=None, initial_excluded_subtrees=None), holder_cert: Certificate | None = None) ACValidationResult

Validate an attribute certificate with respect to a given validation context.

Parameters:
  • attr_cert – The attribute certificate to validate.

  • validation_context – The validation context to validate against.

  • aa_pkix_params – PKIX validation parameters to supply to the path validation algorithm applied to the attribute authority’s certificate.

  • holder_cert

    Certificate of the presumed holder to match against the AC’s holder entry. If not provided, the holder check is left to the caller to perform.

    Note

    This is a convenience option in case there’s only one reasonable candidate holder certificate (e.g. when the attribute certificates are part of a CMS SignedData value with only a single signer).

Returns:

An ACValidationResult detailing the validation result, if successful.

async pyhanko_certvalidator.validate.intl_validate_path(validation_context: ValidationContext, path: ValidationPath, proc_state: ValProcState, parameters: PKIXValidationParams | None = None)

Internal copy of validate_path() that allows overriding the name of the end-entity certificate as used in exception messages. This functionality is used during chain validation when dealing with indirect CRLs issuer or OCSP responder certificates.

Parameters:
  • validation_context – A pyhanko_certvalidator.context.ValidationContext object to use for configuring validation behavior

  • path – A pyhanko_certvalidator.path.ValidationPath object of the path to validate

  • proc_state – Internal state for error reporting and policy application decisions.

  • parameters – Additional input parameters to the PKIX validation algorithm. These are not used when validating CRLs and OCSP responses.

Returns:

The final certificate in the path - an instance of asn1crypto.x509.Certificate

pyhanko_certvalidator.version module

Module contents

class pyhanko_certvalidator.CertificateValidator(end_entity_cert: Certificate, intermediate_certs: Iterable[Certificate] | None = None, validation_context: ValidationContext | None = None, pkix_params: PKIXValidationParams | None = None)

Bases: object

property certificate
async async_validate_path() ValidationPath

Builds possible certificate paths and validates them until a valid one is found, or all fail.

Raises:

pyhanko_certvalidator.errors.PathBuildingError - when an error occurs building the path pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked

validate_usage(key_usage, extended_key_usage=None, extended_optional=False)

Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified.

Deprecated since version 0.17.0: Use async_validate_usage() instead.

Parameters:
  • key_usage

    A set of unicode strings of the required key usage purposes. Valid values include:

    • ”digital_signature”

    • ”non_repudiation”

    • ”key_encipherment”

    • ”data_encipherment”

    • ”key_agreement”

    • ”key_cert_sign”

    • ”crl_sign”

    • ”encipher_only”

    • ”decipher_only”

  • extended_key_usage

    A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes:

    • ”server_auth”

    • ”client_auth”

    • ”code_signing”

    • ”email_protection”

    • ”ipsec_end_system”

    • ”ipsec_tunnel”

    • ”ipsec_user”

    • ”time_stamping”

    • ”ocsp_signing”

    • ”wireless_access_points”

    An example of a dotted number OID:

    • ”1.3.6.1.5.5.7.3.1”

  • extended_optional – A bool - if the extended_key_usage extension may be ommited and still considered valid

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified

Returns:

A pyhanko_certvalidator.path.ValidationPath object of the validated certificate validation path

async async_validate_usage(key_usage, extended_key_usage=None, extended_optional=False)

Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified.

Parameters:
  • key_usage

    A set of unicode strings of the required key usage purposes. Valid values include:

    • ”digital_signature”

    • ”non_repudiation”

    • ”key_encipherment”

    • ”data_encipherment”

    • ”key_agreement”

    • ”key_cert_sign”

    • ”crl_sign”

    • ”encipher_only”

    • ”decipher_only”

  • extended_key_usage

    A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes:

    • ”server_auth”

    • ”client_auth”

    • ”code_signing”

    • ”email_protection”

    • ”ipsec_end_system”

    • ”ipsec_tunnel”

    • ”ipsec_user”

    • ”time_stamping”

    • ”ocsp_signing”

    • ”wireless_access_points”

    An example of a dotted number OID:

    • ”1.3.6.1.5.5.7.3.1”

  • extended_optional – A bool - if the extended_key_usage extension may be ommited and still considered valid

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified

Returns:

A pyhanko_certvalidator.path.ValidationPath object of the validated certificate validation path

validate_tls(hostname)

Validates the certificate path, that the certificate is valid for the hostname provided and that the certificate is valid for the purpose of a TLS connection.

Deprecated since version 0.17.0: Use async_validate_tls() instead.

Parameters:

hostname – A unicode string of the TLS server hostname

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname

Returns:

A pyhanko_certvalidator.path.ValidationPath object of the validated certificate validation path

async async_validate_tls(hostname)

Validates the certificate path, that the certificate is valid for the hostname provided and that the certificate is valid for the purpose of a TLS connection.

Parameters:

hostname – A unicode string of the TLS server hostname

Raises:

pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname

Returns:

A pyhanko_certvalidator.path.ValidationPath object of the validated certificate validation path

class pyhanko_certvalidator.ValidationContext(trust_roots: Iterable[Certificate | TrustAnchor] | None = None, extra_trust_roots: Iterable[Certificate | TrustAnchor] | None = None, other_certs: Iterable[Certificate] | None = None, whitelisted_certs: Iterable[bytes | str] | None = None, moment: datetime | None = None, best_signature_time: datetime | None = None, allow_fetching: bool = False, crls: Iterable[bytes | CertificateList] | None = None, ocsps: Iterable[bytes | OCSPResponse] | None = None, revocation_mode: str = 'soft-fail', revinfo_policy: CertRevTrustPolicy | None = None, weak_hash_algos: Iterable[str] | None = None, time_tolerance: timedelta = datetime.timedelta(seconds=1), retroactive_revinfo: bool = False, fetcher_backend: FetcherBackend | None = None, acceptable_ac_targets: ACTargetDescription | None = None, poe_manager: POEManager | None = None, revinfo_manager: RevinfoManager | None = None, certificate_registry: CertificateRegistry | None = None, trust_manager: TrustManager | None = None, algorithm_usage_policy: AlgorithmUsagePolicy | None = None, fetchers: Fetchers | None = None)

Bases: object

property revinfo_manager: RevinfoManager
property revinfo_policy: CertRevTrustPolicy
property retroactive_revinfo: bool
property time_tolerance: timedelta
property moment: datetime
property best_signature_time: datetime
property fetching_allowed: bool
property crls: List[CertificateList]

A list of all cached crl.CertificateList objects

property ocsps: List[OCSPResponse]

A list of all cached ocsp.OCSPResponse objects

property soft_fail_exceptions

A list of soft-fail exceptions that were ignored during checks

is_whitelisted(cert)

Checks to see if a certificate has been whitelisted

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A bool - if the certificate is whitelisted

async async_retrieve_crls(cert)
Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A list of asn1crypto.crl.CertificateList objects

retrieve_crls(cert)

Deprecated since version 0.17.0: Use async_retrieve_crls() instead.

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

A list of asn1crypto.crl.CertificateList objects

async async_retrieve_ocsps(cert, issuer)
Parameters:
  • cert – An asn1crypto.x509.Certificate object

  • issuer – An asn1crypto.x509.Certificate object of cert’s issuer

Returns:

A list of asn1crypto.ocsp.OCSPResponse objects

retrieve_ocsps(cert, issuer)

Deprecated since version 0.17.0: Use async_retrieve_ocsps() instead.

Parameters:
  • cert – An asn1crypto.x509.Certificate object

  • issuer – An asn1crypto.x509.Certificate object of cert’s issuer

Returns:

A list of asn1crypto.ocsp.OCSPResponse objects

record_validation(cert, path)

Records that a certificate has been validated, along with the path that was used for validation. This helps reduce duplicate work when validating a ceritifcate and related resources such as CRLs and OCSPs.

Parameters:
  • cert – An ans1crypto.x509.Certificate object

  • path – A pyhanko_certvalidator.path.ValidationPath object

check_validation(cert)

Checks to see if a certificate has been validated, and if so, returns the ValidationPath used to validate it.

Parameters:

cert – An asn1crypto.x509.Certificate object

Returns:

None if not validated, or a pyhanko_certvalidator.path.ValidationPath object of the validation path

clear_validation(cert)

Clears the record that a certificate has been validated

Parameters:

cert – An ans1crypto.x509.Certificate object

property acceptable_ac_targets: ACTargetDescription | None
class pyhanko_certvalidator.PKIXValidationParams(user_initial_policy_set: frozenset = frozenset({'any_policy'}), initial_policy_mapping_inhibit: bool = False, initial_explicit_policy: bool = False, initial_any_policy_inhibit: bool = False, initial_permitted_subtrees: Dict[pyhanko_certvalidator.name_trees.GeneralNameType, Set[pyhanko_certvalidator.name_trees.NameSubtree]] | None = None, initial_excluded_subtrees: Dict[pyhanko_certvalidator.name_trees.GeneralNameType, Set[pyhanko_certvalidator.name_trees.NameSubtree]] | None = None)

Bases: object

user_initial_policy_set: frozenset = frozenset({'any_policy'})

Set of policies that the user is willing to accept. By default, any policy is acceptable.

When setting this parameter to a non-default value, you probably want to set initial_explicit_policy as well.

Note

These are specified in the policy domain of the trust root(s), and subject to policy mapping by intermediate certificate authorities.

initial_policy_mapping_inhibit: bool = False

Flag indicating whether policy mapping is forbidden along the entire certification chains. By default, policy mapping is permitted.

Note

Policy constraints on intermediate certificates may force policy mapping to be inhibited from some point onwards.

initial_explicit_policy: bool = False

Flag indicating whether path validation must terminate with at least one permissible policy; see user_initial_policy_set. By default, no such requirement is imposed.

Note

If user_initial_policy_set is set to its default value of {'any_policy'}, the effect is that the path validation must accept at least one policy, without specifying which.

Warning

Due to widespread mis-specification of policy extensions in the wild, many real-world certification chains terminate with an empty set (or rather, tree) of valid policies. Therefore, this flag is set to False by default.

initial_any_policy_inhibit: bool = False

Flag indicating whether anyPolicy should be left unprocessed when it appears in a certificate. By default, anyPolicy is always processed when it appears.

initial_permitted_subtrees: Dict[GeneralNameType, Set[NameSubtree]] | None = None

Set of permitted subtrees for each name type, indicating restrictions to impose on subject names (and alternative names) in the certification path.

By default, all names are permitted. This behaviour can be modified by name constraints on intermediate CA certificates.

initial_excluded_subtrees: Dict[GeneralNameType, Set[NameSubtree]] | None = None

Set of excluded subtrees for each name type, indicating restrictions to impose on subject names (and alternative names) in the certification path.

By default, no names are excluded. This behaviour can be modified by name constraints on intermediate CA certificates.

merge(other: PKIXValidationParams) PKIXValidationParams

Combine the conditions of these PKIX validation params with another set of parameters, producing the most lenient set of parameters that is stricter than both inputs.

Parameters:

other – Another set of PKIX validation parameters.

Returns:

A combined set of PKIX validation parameters.

async pyhanko_certvalidator.find_valid_path(certificate: Certificate, paths: CancelableAsyncIterator[ValidationPath], validation_context: ValidationContext, pkix_validation_params: PKIXValidationParams | None = None)