Skip to content

Chain Validator

The chain validator inspects the full certificate chain the server presented during the TLS handshake and reports structural problems: missing intermediates, out-of-order chains, expired members, weak signature algorithms, and non-CA intermediates. It inspects the presented structure. Cryptographic signature and trust-path verification are handled separately by RootCertificate.

Opting in

The chain validator is registered but disabled by default because chain analysis is an additional policy check. Enable it by naming it explicitly:

from certmonitor import CertMonitor

with CertMonitor(
    "example.com",
    enabled_validators=["expiration", "hostname", "root_certificate", "chain"],
) as monitor:
    monitor.get_cert_info()
    result = monitor.validate()
    print(result["chain"])

Or via the environment:

export ENABLED_VALIDATORS=expiration,hostname,root_certificate,chain

User-configurable arguments

Pass via validator_args={"chain": {...}}. Each argument, its type, and its default are documented in the reference below, straight from the validator's docstring.

The default weak-signature set includes sha1WithRSAEncryption, md5WithRSAEncryption, md2WithRSAEncryption, ecdsa-with-SHA1, and dsa-with-sha1.

How it decides

The chain is fetched, each certificate is inspected, and is_valid is the AND of every structural condition. Per-certificate warnings are collected regardless; on failure the first warning becomes the top-level reason.

flowchart TD
    A[validate called] --> B{Chain fetched?<br/>retrieval API available, no error}
    B -- No --> Z["is_valid: false + reason"]
    B -- Yes --> C[Inspect each certificate:<br/>expiry, weak signature, CA flag, role]
    C --> D{All structural conditions hold?}
    D --> D1["length &ge; min_chain_length<br/>chain ordered<br/>no expired / not-yet-valid member<br/>leaf not self-signed unless allowed<br/>issuers have CA flag<br/>no weak signatures if rejected<br/>terminates in root if required"]
    D1 -- All true --> G["is_valid: true"]
    D1 -- Any false --> H["is_valid: false<br/>reason = first warning"]

Output

Illustrative historical scan, abbreviated to show only the leaf entry in certs. A complete result has one entry per certificate (three in this example).

These examples show selected fields from illustrative scans. validate() also adds status and code, described in the result contract.

{
  "is_valid": true,
  "structural_valid": true,
  "trust_verified": false,
  "chain_length": 3,
  "chain_ordered": true,
  "terminates_in_self_signed": true,
  "certs": [
    {
      "position": 0,
      "role": "leaf",
      "subject": {"commonName": "example.com"},
      "issuer": {"commonName": "Intermediate CA"},
      "not_before": "2025-01-01T00:00:00+00:00",
      "not_after": "2026-01-01T00:00:00+00:00",
      "days_to_expiry": 180,
      "is_ca": false,
      "is_self_signed": false,
      "signature_algorithm_oid": "1.2.840.113549.1.1.11",
      "subject_key_identifier": "ac33ac35b5f88ae27b06d23dc7058997d81c2443",
      "authority_key_identifier": "de1b1eed7915d43e3724c321bbec34396d42b230",
      "public_key_info": {"algorithm": "ecPublicKey", "size": 256, "curve": "secp256r1"},
      "warnings": []
    }
  ],
  "warnings": []
}

On failure, is_valid is false and a reason field is added.

How the chain is retrieved

Chain retrieval uses the available socket chain API, with private _sslobj fallbacks on older interpreters. Private APIs are implementation details and may be unavailable; retrieval failures produce structured errors. Even a method named get_verified_chain() does not establish trust on CertMonitor's permissive collection socket.

The result includes structural_valid and trust_verified: false. Non-CA issuers fail. Weak signatures also fail by default; set reject_weak_signatures=False to retain warnings without rejection. Issuer/subject equality, including the is_self_signed label, does not verify a signature.

What is out of scope

  • Cryptographic signature verification. Structural validation (subject(parent) == issuer(child) plus SKI/AKI matching) catches the real-world misconfigurations this validator is built for. Cryptographic trust verification runs separately in RootCertificate, using OpenSSL.
  • OCSP / CRL revocation checks. Same reasoning: network I/O and responder parsing belong in their own validator.
  • Building a path against the system trust store. Collection intentionally uses ssl.CERT_NONE so it can profile misconfigured and legacy servers. The separate root-certificate check uses the system or configured CA store.

A presented chain is not a built trust path

Servers normally omit the root. CertMonitor does not fetch missing intermediates from AIA URLs. The minimum-length rule is your structural policy: a single leaf can be sufficient for a certificate signed directly by a trusted root, even though it fails the default length of two.

Reference

certmonitor.validators.chain.ChainValidator

Bases: BaseCertValidator

Validator for the structural integrity of the TLS certificate chain.

This validator inspects the chain the server presented during the TLS handshake (leaf through root) and checks for the problems operators actually hit in production: missing intermediates, out-of-order chains, expired members, weak signature algorithms, and non-CA intermediates. It does not perform cryptographic signature verification; that is performed separately by the root_certificate trust check using Python's standard-library ssl module.

The validator ships disabled by default. Opt in via:

CertMonitor("example.com",
            enabled_validators=["expiration", "hostname",
                                "root_certificate", "chain"])

or by setting ENABLED_VALIDATORS in the environment.

Chain retrieval uses available socket APIs, with private fallbacks on older interpreters. If retrieval is unavailable, a structured error is returned.

Attributes:

Name Type Description
name str

The name of the validator.

name class-attribute instance-attribute

name: str = 'chain'

validate

validate(cert: dict[str, Any], host: str, port: int, *, min_chain_length: int = 2, require_root_in_chain: bool = False, allow_self_signed_leaf: bool = False, weak_signature_algorithms: list[str] | None = None, reject_weak_signatures: bool = True) -> ChainResult

Validate the certificate chain fetched alongside the leaf cert.

Parameters:

Name Type Description Default
cert dict[str, Any]

The cert data dict built by CertMonitor._fetch_raw_cert. Expected to contain chain_analysis (populated by the Rust certinfo.analyze_chain call) and/or chain_error.

required
host str

The hostname (unused; accepted for dispatcher compatibility).

required
port int

The port (unused; accepted for dispatcher compatibility).

required
min_chain_length int

Minimum acceptable chain length. Default 2 rejects servers that only send the leaf.

2
require_root_in_chain bool

If True, the chain must terminate in a self-signed root. Most well-configured public TLS servers do not include the root (browsers supply it from the trust store), so this defaults to False and only emits a warning.

False
allow_self_signed_leaf bool

If True, a self-signed leaf (chain length 1, subject == issuer) is accepted. Useful for internal services; default False.

False
weak_signature_algorithms list[str] | None

Override the default set of weak signature algorithm OIDs. Pass an empty list to disable the weak-signature policy entirely.

None
reject_weak_signatures bool

Reject weak signatures by default. False retains warnings while allowing structural policy to pass.

True

Returns:

Name Type Description
dict ChainResult

A structured report with per-cert details and a summary. The shape is stable and documented in docs/validators/chain.md.

Source code in certmonitor/validators/chain.py
def validate(
    self,
    cert: dict[str, Any],
    host: str,
    port: int,
    *,
    min_chain_length: int = 2,
    require_root_in_chain: bool = False,
    allow_self_signed_leaf: bool = False,
    weak_signature_algorithms: list[str] | None = None,
    reject_weak_signatures: bool = True,
) -> ChainResult:
    """
    Validate the certificate chain fetched alongside the leaf cert.

    Args:
        cert: The cert data dict built by `CertMonitor._fetch_raw_cert`.
            Expected to contain `chain_analysis` (populated by the Rust
            `certinfo.analyze_chain` call) and/or `chain_error`.
        host: The hostname (unused; accepted for dispatcher compatibility).
        port: The port (unused; accepted for dispatcher compatibility).
        min_chain_length: Minimum acceptable chain length. Default `2`
            rejects servers that only send the leaf.
        require_root_in_chain: If `True`, the chain must terminate in a
            self-signed root. Most well-configured public TLS servers do
            **not** include the root (browsers supply it from the trust
            store), so this defaults to `False` and only emits a
            warning.
        allow_self_signed_leaf: If `True`, a self-signed leaf (chain
            length 1, subject == issuer) is accepted. Useful for internal
            services; default `False`.
        weak_signature_algorithms: Override the default set of weak
            signature algorithm OIDs. Pass an empty list to disable the
            weak-signature policy entirely.

        reject_weak_signatures: Reject weak signatures by default. False
            retains warnings while allowing structural policy to pass.

    Returns:
        dict: A structured report with per-cert details and a summary.
            The shape is stable and documented in
            `docs/validators/chain.md`.
    """
    warnings: list[str] = []

    chain_error = cert.get("chain_error")
    if chain_error:
        return {
            "is_valid": False,
            "status": "error",
            "structural_valid": False,
            "trust_verified": False,
            "reason": chain_error,
            "chain_length": 0,
            "chain_ordered": False,
            "terminates_in_self_signed": False,
            "certs": [],
            "warnings": [chain_error],
        }

    analysis = cert.get("chain_analysis")
    if analysis is None:
        reason = (
            "Certificate chain was not fetched. This typically means the "
            "SSL handler did not populate the chain."
        )
        return {
            "is_valid": False,
            "status": "error",
            "structural_valid": False,
            "trust_verified": False,
            "reason": reason,
            "chain_length": 0,
            "chain_ordered": False,
            "terminates_in_self_signed": False,
            "certs": [],
            "warnings": [reason],
        }

    if isinstance(analysis, dict) and "error" in analysis:
        return {
            "is_valid": False,
            "status": "error",
            "structural_valid": False,
            "trust_verified": False,
            "reason": analysis["error"],
            "chain_length": 0,
            "chain_ordered": False,
            "terminates_in_self_signed": False,
            "certs": [],
            "warnings": [analysis["error"]],
        }

    weak_oids = (
        frozenset(weak_signature_algorithms)
        if weak_signature_algorithms is not None
        else _DEFAULT_WEAK_SIG_OIDS
    )

    chain_length: int = analysis["chain_length"]
    chain_ordered: bool = analysis["ordered"]
    terminates_in_self_signed: bool = analysis["terminates_in_self_signed"]
    raw_certs: list[dict[str, Any]] = list(analysis.get("certs", []))

    now = datetime.datetime.now(datetime.timezone.utc)
    invalid_ca = False
    weak_signature = False
    any_expired = False
    any_not_yet_valid = False

    cert_reports: list[dict[str, Any]] = []
    for idx, raw in enumerate(raw_certs):
        cert_warnings: list[str] = []

        not_before_ts = raw["not_before_unix"]
        not_after_ts = raw["not_after_unix"]
        not_before = datetime.datetime.fromtimestamp(
            not_before_ts, tz=datetime.timezone.utc
        )
        not_after = datetime.datetime.fromtimestamp(
            not_after_ts, tz=datetime.timezone.utc
        )
        days_to_expiry = (not_after - now).days

        if now >= not_after:
            any_expired = True
            cert_warnings.append(
                f"Certificate at position {idx} is expired "
                f"({abs(days_to_expiry)} days ago)."
            )
        elif now < not_before:
            any_not_yet_valid = True
            cert_warnings.append(
                f"Certificate at position {idx} is not yet valid "
                f"(notBefore={not_before.isoformat()})."
            )

        sig_oid = raw.get("signature_algorithm_oid", "")
        if sig_oid in weak_oids:
            weak_signature = True
            cert_warnings.append(
                f"Certificate at position {idx} uses a weak signature "
                f"algorithm ({sig_oid})."
            )

        # A cert is only labeled "root" when it is actually self-signed.
        # Servers often send a cross-signed version of a root (e.g.
        # SSL.com's ECC root cross-signed by Comodo's AAA root) as the
        # last cert in the chain. The last cert in those chains is
        # structurally an intermediate, not a root, its trust anchor
        # (the signer) lives in the client's trust store.
        if idx == 0:
            role = "leaf"
        elif raw.get("is_self_signed", False):
            role = "root"
        else:
            role = "intermediate"

        if role in ("intermediate", "root") and not raw.get("is_ca"):
            invalid_ca = True
            cert_warnings.append(
                f"Certificate at position {idx} ({role}) is not marked "
                "as a CA (BasicConstraints.cA is false)."
            )

        cert_reports.append(
            {
                "position": idx,
                "role": role,
                "subject": raw.get("subject", {}),
                "issuer": raw.get("issuer", {}),
                "not_before": _iso(not_before_ts),
                "not_after": _iso(not_after_ts),
                "days_to_expiry": days_to_expiry,
                "is_ca": raw.get("is_ca", False),
                "is_self_signed": raw.get("is_self_signed", False),
                "signature_algorithm_oid": sig_oid,
                "subject_key_identifier": raw.get("subject_key_identifier"),
                "authority_key_identifier": raw.get("authority_key_identifier"),
                "public_key_info": raw.get("public_key_info", {}),
                "warnings": cert_warnings,
            }
        )

    # Chain-level warnings and pass/fail logic.
    if chain_length < min_chain_length:
        warnings.append(
            f"Chain length {chain_length} is below the required minimum "
            f"of {min_chain_length}. The server likely failed to send "
            "one or more intermediate certificates."
        )

    if not chain_ordered:
        warnings.append(
            "Chain is not ordered correctly: the subject of each parent "
            "does not match the issuer of its child."
        )

    if any_expired:
        warnings.append("One or more certificates in the chain are expired.")

    if any_not_yet_valid:
        warnings.append("One or more certificates in the chain are not yet valid.")

    leaf_self_signed = (
        chain_length >= 1
        and raw_certs
        and raw_certs[0].get("is_self_signed", False)
    )
    if leaf_self_signed and not allow_self_signed_leaf:
        leaf_dn = _format_dn(raw_certs[0].get("subject", {}))
        warnings.append(
            f"Leaf certificate is self-signed ({leaf_dn}). "
            "Pass allow_self_signed_leaf=True to accept this."
        )

    if not terminates_in_self_signed:
        chain_warning = (
            "Chain does not terminate in a self-signed root certificate. "
            "The last cert is either a cross-signed intermediate (legitimate "
            "- the real root lives in the client's trust store) or the "
            "server is not sending the root at all (also common, browsers "
            "supply the root from their trust store)."
        )
        if require_root_in_chain:
            warnings.append(
                chain_warning + " (require_root_in_chain=True rejects this.)"
            )
        else:
            warnings.append(chain_warning)

    # Pass-through per-cert warnings at the top level so a single
    # `warnings` list gives operators everything.
    for cert_report in cert_reports:
        warnings.extend(cert_report["warnings"])

    is_valid = (
        chain_length >= min_chain_length
        and chain_length == len(raw_certs)
        and not invalid_ca
        and not (weak_signature and reject_weak_signatures)
        and chain_ordered
        and not any_expired
        and not any_not_yet_valid
        and (not leaf_self_signed or allow_self_signed_leaf)
        and (terminates_in_self_signed or not require_root_in_chain)
    )

    result: ChainResult = {
        "is_valid": bool(is_valid),
        "structural_valid": bool(is_valid),
        "trust_verified": False,
        "chain_length": chain_length,
        "chain_ordered": chain_ordered,
        "terminates_in_self_signed": terminates_in_self_signed,
        "certs": cert_reports,
        "warnings": warnings,
    }
    if not is_valid:
        result["reason"] = warnings[0] if warnings else "Chain validation failed."
    return result