TRENDING
Three Japanese emergency triage tags fanned out on a dark wooden table, with black, red, yellow and green priority bands along the bottom edge of the center tag
December 1, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
Three goats standing on top of a rusty steam locomotive boiler like winners on a podium, inside a roofed shed in Don Khon, Laos
December 1, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
A glass sugar dispenser with a steel lid beside a salt shaker and a pepper shaker with brass caps on a diner table
December 1, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year
Brass combination lock with three number wheels and a hinged latch on a black case
December 1, 2026
How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File: Run a Tamper Test, Read pip’s Hash Errors, Build a Lock That Works on Windows and Linux, and Lint It in CI
A pair of unfinished pale wooden clogs, called sabots, on a clogmaker's workbench among wood shavings and hand tools.
December 1, 2026
Anthropic Denies Claude Is Trained to Sabotage Work, and Its Documents Fit the Denial but Show a Silent Safeguard Retired After About Two Days in June, a Training Cap on Kernel and LLM-Architecture Skills With No Released-Model Score, and Viral Evidence That Cannot Tell Them Apart
01 Dec 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
A bicycle chain with a missing link lying on an open palm beside the loose pin and clip that should have joined it
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
Pale church wall with an arched window filled with a star-pattern stone lattice screen
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
A tall cardon cactus with many upright arms stands in front of a field of cardon cacti under a blue sky with white clouds in the Sonoran Desert
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 325 Posts
News 331 Posts
Learning Hub 297 Posts
Home/Learning Hub/How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
Learning Hub

How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI

Reproduce the classic certificate failures on public test sites and a local CA, build a diagnostic that says who has to fix each one, see why a Windows machine passes a chain that requests and httpx...

November 30, 2026 46 Min Read
7

Sooner or later a Python program that has worked for months stops with a long, ugly line: ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate. The error is Python refusing to talk to a server because it cannot prove who the server is. The most popular answer on the web is to pass verify=False, which makes the error disappear by switching the proof off. This tutorial shows the other route: read the error code, work out who has to fix the problem (the server’s operator, the people who run a certificate authority, or you), and apply the fix that matches.

Table Of Content

  • The ideas you need before you write any code
  • Prerequisites
  • Step 0: Set up the project
  • Step 1: See five classic failures against public test sites
  • Step 2: Read what the server really sends
  • Who has to act
  • Step 3: Find out which trust store each library reads
  • Step 4: Build a private CA and reproduce every server-side mistake
  • Step 5: Trust your own CA without breaking everything else
  • Step 6: Understand what Python 3.13 changed
  • Step 7: See what verify=False really costs
  • Step 8: Catch broken chains in CI before users do
  • Test the tools
  • Check the whole thing end to end
  • Common mistakes and how to check for them
  • Next steps
  • Sources and method

By the end you will have two tools, a test suite and a few measured surprises. certdoctor.py connects to a server, prints the certificates it sends, says what is wrong and who fixes it. certwatch.py is a check for a CI job: it verifies a host on a clean trust store and warns before a certificate expires. A 27-test suite and a check with 16 planted bugs show that both tools notice what they should. The surprises are these: a broken certificate chain that urllib accepted on my Windows machine while requests and httpx rejected it; a certificate without a subject alternative name that requests refuses and the other two accept; and four ordinary-looking private certificates that Python 3.13 rejects and Python 3.12 accepts.

No security background is assumed. If you can read a short Python function, you can follow along. Every step gives the code, the output to expect, and a plain explanation of what the code does and why it is written that way. I ran everything on Windows 11 with Python 3.13.14. The public test sites come from badssl.com, a public test site whose subdomains, such as expired, wrong.host and self-signed, each serve a certificate with one specific problem.

The ideas you need before you write any code

A TLS certificate is a signed statement that a public key belongs to a name such as shop.example.com. The signer is a certificate authority (CA). A server usually does not get its certificate straight from a root CA. A root CA signs an intermediate CA certificate, and the intermediate signs the leaf, the certificate for your site. Leaf, intermediate and root together form a chain.

The server sends the leaf and the intermediates. The client checks the signatures link by link until it reaches a root it already trusts. The list of roots a program trusts is its trust store. The TLS 1.3 standard says what the server must send: “The sender’s certificate MUST come in the first CertificateEntry in the list. Each following certificate SHOULD directly certify the one immediately preceding it.” It also says why the root can be left out: “a certificate that specifies a trust anchor MAY be omitted from the chain, provided that supported peers are known to possess any omitted certificates” (RFC 8446, section 4.4.2). Two things follow. The standard lets a sender omit only a certificate that is a trust anchor, so a server that leaves out an intermediate is relying on every client already having it. And the root is the client’s business: it comes from the trust store, not from the server.

Different libraries read different trust stores. The Python documentation says that on Windows the standard library’s default setup does this: “On Windows it loads CA certs from the CA and ROOT system stores.” The requests documentation says “Requests uses certificates from the package certifi.” The httpx documentation says “By default the certifi CA bundle is used for SSL verification.” So urllib, requests and httpx can disagree about the same server on the same machine. Step 3 shows that they do.

One more certificate field matters. Authority Information Access (AIA) can tell a client where the issuer’s certificate can be downloaded. RFC 5280 describes it like this: “The referenced CA issuers description is intended to aid certificate users in the selection of a certification path that terminates at a point trusted by the certificate user.” Web browsers and operating system libraries often follow that link to repair a chain the server left incomplete. Python’s ssl module does not: in Step 3 you will see it fail until Windows has done the download. That is how a site can work in a browser and fail in a script.

When verification fails, Python raises ssl.SSLCertVerificationError. Its documentation describes two attributes: verify_code, “A numeric error number that denotes the verification error.” and verify_message, “A human readable string of the verification error.” The number comes from OpenSSL and is the quickest way to find out what is wrong. This table lists the ones you will meet here. I reproduced every row in the lab.

Code OpenSSL’s message What it usually means Who fixes it
10 certificate has expired The server’s certificate, or one above it, is past its end date. The server’s operator renews it.
9 certificate is not yet valid The certificate starts later than your clock says, or your clock is wrong. You fix the clock, or the operator reissues.
18 self-signed certificate The server sent one certificate that signed itself. You trust that exact certificate on purpose, or the operator gets one from a CA.
19 self-signed certificate in certificate chain The chain ends in a root that is not in your trust store. You add the root (a private CA), or the operator uses a public CA.
20 unable to get local issuer certificate A link is missing between the server’s certificate and a root you trust. The operator forgot an intermediate, or you do not trust the CA.
62 Hostname mismatch The name in the URL is not in the certificate. Use the right name, or the operator reissues.
64 IP address mismatch The URL has an IP address and the certificate has no matching IP entry. Use a DNS name.
85, 86, 89 Missing Authority Key Identifier, Missing Subject Key Identifier, Basic Constraints of CA cert not marked critical A certificate breaks an RFC 5280 rule that Python 3.13 enforces by default. The owner of the private CA reissues (Step 6).

Prerequisites

  • Operating system: Windows 11. The code is portable Python. Steps 3 and 6 depend on how your operating system stores trusted certificates, and I only tested Windows. The commands that differ on macOS and Linux are the virtual environment activation and curl.exe.
  • Python: Python 3.13.14. The diagnostic uses get_unverified_chain(), which the Python documentation marks as added in 3.13. Step 6 compares against Python 3.12.16 and is optional.
  • Packages: requests 2.34.2, httpx 0.29.0, cryptography 50.0.2, certifi 2026.11.20, truststore 0.10.5 and pytest 9.2.0.
  • Network: access to badssl.com and its subdomains on port 443. No account or key is needed.
  • Access level: a normal user account. Nothing in this tutorial changes a system setting, with one exception in Step 3 that removes a cached copy of a public intermediate certificate from your own user store. Windows downloads it again by itself, and the step shows that happening.
  • Time and disk: about two hours to read and type. Every command finishes in under a minute. The virtual environment takes about 50 megabytes.
  • Knowledge: Python functions, lists and dictionaries. Nothing about certificates is assumed.

Step 0: Set up the project

Create a folder and a virtual environment, then install the pinned packages. The last command prints the Python version so you can compare it with mine.

mkdir certfail
cd certfail
python -m venv .venv
.venv\Scripts\activate
python -m pip install requests==2.34.2 httpx==0.29.0 cryptography==50.0.2 certifi==2026.11.20 truststore==0.10.5 pytest==9.2.0
python --version
Python 3.13.14

In PowerShell the activation script is .venv\Scripts\Activate.ps1. On macOS and Linux the activation line is source .venv/bin/activate. Every file you create below goes into this one folder, because the scripts import each other by name.

Step 1: See five classic failures against public test sites

Start with a small helper module. clients.py calls requests, urllib and httpx the same way and returns one short string for each. The function why() walks the exception chain, because the SSL error arrives wrapped inside other exceptions, and picks out the ssl.SSLCertVerificationError so it can print its code and message. The function all_three() hands the same trust anchor to each library the way that library expects it: a file path for requests, a cafile for the standard library, and an SSL context for httpx.

# clients.py
"""Three ways to fetch a URL. Each returns one short string: OK, or the OpenSSL verdict."""
import ssl
import urllib.request

import httpx
import requests


def why(exc):
    """Walk the exception chain to ssl.SSLCertVerificationError and return 'code: message'."""
    seen = set()
    while exc is not None and id(exc) not in seen:
        seen.add(id(exc))
        if isinstance(exc, ssl.SSLCertVerificationError):
            return f"{exc.verify_code}: {exc.verify_message}"
        exc = exc.__cause__ or exc.__context__
    return None


def short(exc):
    return why(exc) or f"{type(exc).__name__}: {str(exc)[:70]}"


def get_requests(url, verify=True):
    """verify: True (certifi bundle), False, or the path of a CA file."""
    try:
        requests.get(url, timeout=10, verify=verify).raise_for_status()
        return "OK"
    except Exception as exc:
        return "FAIL " + short(exc)


def get_urllib(url, cafile=None, context=None):
    """No cafile and no context means ssl.create_default_context(), the interpreter's own trust."""
    ctx = context or ssl.create_default_context(cafile=cafile)
    try:
        with urllib.request.urlopen(url, timeout=10, context=ctx) as resp:
            return "OK" if resp.status == 200 else f"HTTP {resp.status}"
    except Exception as exc:
        return "FAIL " + short(exc)


def get_httpx(url, verify=True):
    """verify: True (certifi bundle), False, or an ssl.SSLContext."""
    try:
        httpx.get(url, timeout=10, verify=verify).raise_for_status()
        return "OK"
    except Exception as exc:
        return "FAIL " + short(exc)


def all_three(url, cafile=None):
    """One row of the matrix: the same trust anchor handed to each library its own way."""
    if cafile is None:
        return {"requests": get_requests(url), "urllib": get_urllib(url), "httpx": get_httpx(url)}
    ctx = ssl.create_default_context(cafile=cafile)
    return {"requests": get_requests(url, verify=cafile),
            "urllib": get_urllib(url, cafile=cafile),
            "httpx": get_httpx(url, verify=ctx)}

Now call six hosts. The first, badssl.com, is a control with a good certificate. The other five each break one rule.

# step01_public.py
"""Step 1: reproduce the classic failures against badssl.com, a public test site."""
import sys

from clients import all_three

HOSTS = [
    "badssl.com",                      # the control: a good certificate
    "expired.badssl.com",
    "wrong.host.badssl.com",
    "self-signed.badssl.com",
    "untrusted-root.badssl.com",
    "incomplete-chain.badssl.com",
]

print(sys.version.split()[0])
for host in HOSTS:
    print(host)
    for lib, verdict in all_three(f"https://{host}/").items():
        print(f"  {lib:<9} {verdict}")
python step01_public.py
3.13.14
badssl.com
  requests  OK
  urllib    OK
  httpx     OK
expired.badssl.com
  requests  FAIL 10: certificate has expired
  urllib    FAIL 10: certificate has expired
  httpx     FAIL 10: certificate has expired
wrong.host.badssl.com
  requests  FAIL 62: Hostname mismatch, certificate is not valid for 'wrong.host.badssl.com'.
  urllib    FAIL 62: Hostname mismatch, certificate is not valid for 'wrong.host.badssl.com'.
  httpx     FAIL 62: Hostname mismatch, certificate is not valid for 'wrong.host.badssl.com'.
self-signed.badssl.com
  requests  FAIL 18: self-signed certificate
  urllib    FAIL 18: self-signed certificate
  httpx     FAIL 18: self-signed certificate
untrusted-root.badssl.com
  requests  FAIL 19: self-signed certificate in certificate chain
  urllib    FAIL 19: self-signed certificate in certificate chain
  httpx     FAIL 19: self-signed certificate in certificate chain
incomplete-chain.badssl.com
  requests  FAIL 20: unable to get local issuer certificate
  urllib    OK
  httpx     FAIL 20: unable to get local issuer certificate

Read the output group by group. The control passes in all three libraries; if yours does not, something on your machine or network (a wrong clock, a company proxy that re-signs traffic) is wrong before any of the other results matter. expired gives code 10 in all three. wrong.host gives code 62, and the message names the host you asked for. self-signed gives 18 and untrusted-root gives 19, the two ways of meeting a certificate that nobody you trust has signed. The last host is the strange one. incomplete-chain fails in requests and httpx with code 20, yet urllib prints OK. It is the same server, on the same machine, in the same second. Steps 2 and 3 explain why.

Check before moving on: you should see OK three times for the control and the same codes as above for the other hosts, apart from the odd one out in the last group.

Step 2: Read what the server really sends

An error code tells you what OpenSSL objected to, but not what the server sent. certdoctor.py fetches the certificates, runs five checks on them, and says who has to act. You will write it in four pieces. The first piece fetches the chain and asks Python for its own verdict.

# certdoctor.py
"""certdoctor: say why a TLS server's certificate fails verification, and who has to fix it."""
import datetime as dt
import ipaddress
import socket
import ssl
import sys
import warnings

import certifi
from cryptography import x509
from cryptography.utils import CryptographyDeprecationWarning
from cryptography.x509.oid import AuthorityInformationAccessOID

WARN_DAYS = 21


def fetch_chain(host, port=443, timeout=10):
    """The certificates the server sends, leaf first. Verification is OFF on purpose here:
    we only read the certificates, we never trust them."""
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    with socket.create_connection((host, port), timeout=timeout) as raw:
        with ctx.wrap_socket(raw, server_hostname=host) as tls:
            return [x509.load_der_x509_certificate(der) for der in tls.get_unverified_chain()]


def load_roots(cafile=None):
    with open(cafile or certifi.where(), "rb") as fh, warnings.catch_warnings():
        # a few old roots in the bundle have a non-positive serial number; parsing them is fine
        warnings.simplefilter("ignore", CryptographyDeprecationWarning)
        return x509.load_pem_x509_certificates(fh.read())


def python_verdict(host, port=443, cafile=None, timeout=10):
    """What OpenSSL says when Python verifies for real: None if it works, else 'code: message'."""
    ctx = ssl.create_default_context(cafile=cafile) if cafile else ssl.create_default_context()
    try:
        with socket.create_connection((host, port), timeout=timeout) as raw:
            with ctx.wrap_socket(raw, server_hostname=host):
                return None
    except ssl.SSLCertVerificationError as exc:
        return f"{exc.verify_code}: {exc.verify_message}"

Look at fetch_chain(). It sets verify_mode = ssl.CERT_NONE, which switches verification off. This is the only place in the tutorial where that happens, and it is deliberate: the function only reads the certificates the server presents. It never trusts them and sends the server no data. get_unverified_chain() returns the chain exactly as the server sent it, as a list of DER-encoded bytes. The Python documentation puts it as “Returns raw certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes.” The cryptography package parses each one. python_verdict() does the opposite: it connects for real with the default context and returns OpenSSL’s code and message, or None when the connection verifies.

The second piece holds small helpers: reading an extension safely, listing the names in a certificate, and matching a name against a pattern. name_matches() compares case-insensitively and lets a wildcard stand for the whole leftmost label only, so *.lab.test covers shop.lab.test but neither a.b.lab.test nor lab.test. The tests in Step 8 pin those cases down.

# certdoctor.py (continued)
def _ext(cert, cls):
    try:
        return cert.extensions.get_extension_for_class(cls)
    except x509.ExtensionNotFound:
        return None


def san_values(cert):
    ext = _ext(cert, x509.SubjectAlternativeName)
    if ext is None:
        return None
    return ext.value.get_values_for_type(x509.DNSName), [str(i) for i in ext.value.get_values_for_type(x509.IPAddress)]


def name_matches(pattern, host):
    """RFC 6125 matching: case-insensitive, a wildcard only as the whole leftmost label."""
    pattern, host = pattern.lower().rstrip("."), host.lower().rstrip(".")
    if pattern.startswith("*."):
        head, _, rest = host.partition(".")
        return bool(head) and rest == pattern[2:]
    return pattern == host


def common_name(cert):
    attrs = cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
    return attrs[0].value if attrs else "-"

The third piece is the heart of the tool. analyse() is a pure function: parsed certificates go in, a list of findings comes out, and nothing touches the network. That makes it easy to test. It runs five checks in order.

# certdoctor.py (continued)
def analyse(chain, host, roots, now=None):
    """Return a list of (level, text). Pure function: certificates in, findings out."""
    now = now or dt.datetime.now(dt.timezone.utc)
    out = []
    leaf = chain[0]

    # 1. Is the name we connect to inside the leaf certificate?
    sans = san_values(leaf)
    try:
        ip = str(ipaddress.ip_address(host))
    except ValueError:
        ip = None
    if sans is None:
        out.append(("warn", f"the leaf has no subjectAltName (CN={common_name(leaf)}); urllib and httpx "
                            "fall back to the CN, requests does not. Reissue it with a SAN."))
    elif ip and ip not in sans[1]:
        out.append(("error", f"the address {ip} is not in the certificate (IP names: {sans[1] or 'none'}). "
                             "Connect by a DNS name the certificate covers."))
    elif not ip and not any(name_matches(p, host) for p in sans[0]):
        out.append(("error", f"the name {host} is not in the certificate (it covers: {', '.join(sans[0])}). "
                             "Connect by a covered name or reissue the certificate."))

    # 2. Dates of every certificate the server sent.
    for i, cert in enumerate(chain):
        left = cert.not_valid_after_utc - now
        if now < cert.not_valid_before_utc:
            out.append(("error", f"certificate {i} is not valid until {cert.not_valid_before_utc:%Y-%m-%d %H:%M} UTC "
                                 "(wrong clock, or a certificate issued for later)."))
        elif left < dt.timedelta(0):
            out.append(("error", f"certificate {i} expired on {cert.not_valid_after_utc:%Y-%m-%d} UTC. Renew it on the server."))
        elif left < dt.timedelta(days=WARN_DAYS):
            out.append(("warn", f"certificate {i} expires in {left.days} days ({cert.not_valid_after_utc:%Y-%m-%d})."))

    # 3. Is each certificate issued by the next one?
    for i in range(len(chain) - 1):
        if chain[i].issuer != chain[i + 1].subject:
            out.append(("error", f"certificate {i} was not issued by certificate {i + 1}: the chain is out of order "
                                 "or has a gap. Serve leaf first, then each issuer."))

    # 4. Does the top of the chain reach a root we trust?
    top = chain[-1]
    if top.issuer == top.subject:
        if top not in roots:
            out.append(("error", f"the chain ends in a self-signed certificate ({common_name(top)}) that is not in "
                                 "the trust bundle. Unknown CA: trust its root, or use a public CA."))
    elif not any(top.issuer == r.subject for r in roots):
        aia = _ext(leaf, x509.AuthorityInformationAccess)
        urls = [d.access_location.value for d in aia.value
                if d.access_method == AuthorityInformationAccessOID.CA_ISSUERS] if aia else []
        if len(chain) == 1:
            out.append(("error", f"the server sent only the leaf. It must also send the intermediate that issued it "
                                 f"('{top.issuer.rfc4514_string()}'). Fix on the server: serve the full chain."
                                 + (f" The leaf's AIA field says that certificate lives at {urls[0]}." if urls else "")))
        else:
            out.append(("error", f"the chain stops at {common_name(top)}, whose issuer '{top.issuer.rfc4514_string()}' is "
                                 "not in the trust bundle: either the server left out one more certificate, or that CA is "
                                 "not trusted here."))

    # 5. Things Python 3.13+ refuses in strict mode (ssl.VERIFY_X509_STRICT).
    for i, cert in enumerate(chain):
        bc = _ext(cert, x509.BasicConstraints)
        is_ca = bool(bc and bc.value.ca)
        if is_ca and not bc.critical:
            out.append(("warn", f"certificate {i} is a CA but its basicConstraints is not critical (strict mode refuses it)."))
        if is_ca and _ext(cert, x509.SubjectKeyIdentifier) is None:
            out.append(("warn", f"certificate {i} is a CA without a subjectKeyIdentifier (strict mode refuses it)."))
        if cert.issuer != cert.subject and _ext(cert, x509.AuthorityKeyIdentifier) is None:
            out.append(("warn", f"certificate {i} has no authorityKeyIdentifier (strict mode refuses it)."))
    return out
  1. The name. Is the host you connected to inside the certificate? A certificate with no subject alternative name at all gets a warning, because modern clients are supposed to use that field. An IP address is only accepted if the certificate lists that address.
  2. The dates. Every certificate the server sent is checked, not only the leaf, because an expired intermediate breaks the chain just as an expired leaf does. A certificate that expires within 21 days earns a warning, so you hear about it before your users do.
  3. The links. Each certificate should have been issued by the next one in the list. If not, the chain is out of order or has a gap.
  4. The top of the chain. Does the chain reach a root in the trust bundle? If the last certificate is self-signed but not in the bundle, the CA is unknown. If it is not self-signed and its issuer is not a trusted root either, something is missing between the server and the root. When the server sent only the leaf, the message says so and prints the AIA address of the missing certificate.
  5. Strict-mode problems. These are the things Python 3.13 refuses by default: a CA certificate whose basicConstraints is not marked critical, a CA without a subjectKeyIdentifier, and a certificate that is not self-signed and has no authorityKeyIdentifier. Step 6 measures them.

The last piece prints a readable report and sets the exit code: 0 when nothing is wrong, 1 when a problem is found, 2 when it cannot connect.

# certdoctor.py (continued)
def describe(chain):
    lines = []
    for i, cert in enumerate(chain):
        lines.append(f"  {i}  {common_name(cert)}  <- issued by {cert.issuer.rfc4514_string()}  "
                     f"until {cert.not_valid_after_utc:%Y-%m-%d}")
    return lines


def main(argv):
    if not argv:
        print("usage: python certdoctor.py HOST[:PORT] [CAFILE]")
        return 2
    host, _, port = argv[0].partition(":")
    port = int(port or 443)
    cafile = argv[1] if len(argv) > 1 else None
    try:
        chain = fetch_chain(host, port)
    except OSError as exc:
        print(f"cannot connect to {host}:{port}: {exc}")
        return 2
    print(f"{host}:{port} sends {len(chain)} certificate(s):")
    print("\n".join(describe(chain)))
    verdict = python_verdict(host, port, cafile)
    print("Python verifies it: " + ("yes" if verdict is None else f"NO ({verdict})"))
    findings = analyse(chain, host, load_roots(cafile))
    for level, text in findings:
        print(f"  {level.upper():<5} {text}")
    if not findings:
        print("  no problems found in the chain")
    if verdict is None and any("did not send" in t or "only the leaf" in t for _, t in findings):
        print("  NOTE  Python accepted it here only because this machine's store already holds the missing "
              "certificate. A clean machine or container will fail.")
    return 1 if any(level == "error" for level, _ in findings) or verdict else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Run it on the odd host from Step 1.

python certdoctor.py incomplete-chain.badssl.com
incomplete-chain.badssl.com:443 sends 1 certificate(s):
  0  *.badssl.com  <- issued by CN=YR1,O=Let's Encrypt,C=US  until 2026-12-28
Python verifies it: yes
  ERROR the server sent only the leaf. It must also send the intermediate that issued it ('CN=YR1,O=Let's Encrypt,C=US'). Fix on the server: serve the full chain. The leaf's AIA field says that certificate lives at http://yr1.i.lencr.org/.
  NOTE  Python accepted it here only because this machine's store already holds the missing certificate. A clean machine or container will fail.

The server sent one certificate and nothing else. Its issuer, an intermediate called YR1 from Let’s Encrypt, is missing, and the tool prints the address where the leaf says that certificate can be downloaded. Now read the second line: Python verifies it: yes. Python accepted this server and the tool still reports an error. The NOTE at the end explains the contradiction: this machine’s own store already holds the missing certificate. Step 3 proves it.

Try two more hosts. The first has an unknown CA, the second is expired.

python certdoctor.py untrusted-root.badssl.com
untrusted-root.badssl.com:443 sends 2 certificate(s):
  0  *.badssl.com  <- issued by CN=BadSSL Untrusted Root Certificate Authority,O=BadSSL,L=San Francisco,ST=California,C=US  until 2028-11-23
  1  BadSSL Untrusted Root Certificate Authority  <- issued by CN=BadSSL Untrusted Root Certificate Authority,O=BadSSL,L=San Francisco,ST=California,C=US  until 2036-07-02
Python verifies it: NO (19: self-signed certificate in certificate chain)
  ERROR the chain ends in a self-signed certificate (BadSSL Untrusted Root Certificate Authority) that is not in the trust bundle. Unknown CA: trust its root, or use a public CA.
  WARN  certificate 0 has no authorityKeyIdentifier (strict mode refuses it).
  WARN  certificate 1 is a CA but its basicConstraints is not critical (strict mode refuses it).
python certdoctor.py expired.badssl.com
expired.badssl.com:443 sends 3 certificate(s):
  0  *.badssl.com  <- issued by CN=COMODO RSA Domain Validation Secure Server CA,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB  until 2015-04-12
  1  COMODO RSA Domain Validation Secure Server CA  <- issued by CN=COMODO RSA Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB  until 2029-02-11
  2  COMODO RSA Certification Authority  <- issued by CN=AddTrust External CA Root,OU=AddTrust External TTP Network,O=AddTrust AB,C=SE  until 2020-05-30
Python verifies it: NO (10: certificate has expired)
  ERROR certificate 0 expired on 2015-04-12 UTC. Renew it on the server.
  ERROR certificate 2 expired on 2020-05-30 UTC. Renew it on the server.
  ERROR the chain stops at COMODO RSA Certification Authority, whose issuer 'CN=AddTrust External CA Root,OU=AddTrust External TTP Network,O=AddTrust AB,C=SE' is not in the trust bundle: either the server left out one more certificate, or that CA is not trusted here.

For untrusted-root the chain is complete and ends in a self-signed root that is not in the bundle, so Python reports code 19 and the tool says the CA is unknown. The two warnings underneath are strict-mode problems in that test certificate. They are only warnings because the chain fails on trust first. For expired the leaf’s end date is 2015-04-12, and the third certificate in the chain is a cross-signed root whose own end date is 2020-05-30. The last line shows the tool’s wording for a chain that stops below an issuer it cannot find: either the server left out one more certificate, or that CA is not trusted here. It cannot tell which, and it says so.

OpenSSL’s own command line gives a second opinion. This command works in Git Bash, which ships OpenSSL, and keeps only the lines that matter:

echo | openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com 2>&1 | grep -E "^Certificate chain|^ [0-9] s:|verify error|Verify return code"
verify error:num=20:unable to get local issuer certificate
verify error:num=21:unable to verify the first certificate
Certificate chain
 0 s:CN=*.badssl.com
    Verify return code: 21 (unable to verify the first certificate)

It shows one certificate in the chain and the same error 20 first, followed by 21. OpenSSL’s command line does not read the Windows store, so it fails here where Python succeeded.

Check before moving on: for the first host you should see one certificate, ERROR about the missing intermediate, and a NOTE only if your machine has the intermediate cached. If your Python verdict says NO (20: unable to get local issuer certificate) instead of yes, your machine does not have it cached yet, and that is the other half of the story in the next step.

Who has to act

The findings sort into three groups, and knowing the group saves hours. The server’s operator fixes an expired certificate, a missing intermediate, a chain in the wrong order and a name that is not in the certificate. You fix an unknown private CA (by trusting its root properly, Step 5), a wrong clock and the wrong choice of trust store. The owner of a private CA fixes strict-mode problems by reissuing the CA certificate (Step 6). Turning verification off fixes none of them. It only stops you from finding out.

Step 3: Find out which trust store each library reads

The next script prints what each library starts from and then tests the odd host six ways. It first shows how many certificates the standard library’s default context holds, which OpenSSL default paths exist, how many roots certifi has, and whether requests uses certifi. Then it asks one question: is the issuer of the leaf already in the standard library’s default store? Finally it fetches the odd host with each library and with truststore, a package that lets Python use the operating system’s own store.

# step03_trust_stores.py
"""Step 3: which trust store does each library read, and why one machine passes where another fails."""
import ssl
import warnings

import certifi
import requests
import truststore
from cryptography import x509

from certdoctor import fetch_chain, load_roots
from clients import get_httpx, get_requests, get_urllib

# a Windows store certificate has a non-positive serial number; cryptography warns, parsing still works
warnings.simplefilter("ignore")

default_ctx = ssl.create_default_context()
paths = ssl.get_default_verify_paths()
certifi_roots = load_roots()
print("stdlib default context :", default_ctx.cert_store_stats())
print("OpenSSL default paths  :", paths.cafile, paths.capath)
print("certifi bundle         :", len(certifi_roots), "certificates")
print("requests uses certifi  :", requests.certs.where() == certifi.where())

host = "incomplete-chain.badssl.com"
leaf = fetch_chain(host)[0]
in_system = [x509.load_der_x509_certificate(d) for d in default_ctx.get_ca_certs(binary_form=True)]
print("issuer of the leaf in the stdlib default store :", any(c.subject == leaf.issuer for c in in_system))
print("issuer of the leaf in certifi                  :", any(c.subject == leaf.issuer for c in certifi_roots))

url = f"https://{host}/"
certifi_only = ssl.create_default_context(cafile=certifi.where())
system_store = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
print("requests (certifi)         :", get_requests(url))
print("httpx    (certifi)         :", get_httpx(url))
print("urllib   (stdlib default)  :", get_urllib(url))
print("urllib   (certifi only)    :", get_urllib(url, context=certifi_only))
print("urllib   (truststore)      :", get_urllib(url, context=system_store))
print("httpx    (truststore)      :", get_httpx(url, verify=system_store))
python step03_trust_stores.py
stdlib default context : {'x509': 49, 'crl': 0, 'x509_ca': 47}
OpenSSL default paths  : None None
certifi bundle         : 113 certificates
requests uses certifi  : True
issuer of the leaf in the stdlib default store : True
issuer of the leaf in certifi                  : False
requests (certifi)         : FAIL 20: unable to get local issuer certificate
httpx    (certifi)         : FAIL 20: unable to get local issuer certificate
urllib   (stdlib default)  : OK
urllib   (certifi only)    : FAIL 20: unable to get local issuer certificate
urllib   (truststore)      : OK
httpx    (truststore)      : OK

Here is what each line tells you. The default context holds 49 certificates, loaded from the Windows system stores (the count is specific to this machine). OpenSSL’s own default paths are empty on Windows, which is why those two values are None. Certifi holds 113 roots, and requests uses it. The issuer of the odd host’s certificate is in the standard library’s store and not in certifi. That one fact predicts every row below it. requests and httpx use certifi, which has roots only, so they fail with code 20. urllib with its default context passes because the issuer is in the system store. urllib given certifi alone fails. And truststore, which uses the system store, passes with both urllib and httpx.

How did an intermediate certificate get into the store that Python reads? Test it. This small script makes one request with the standard library’s default trust and prints one line.

# one_call.py
"""One HTTPS request with the standard library's default trust. Prints one line."""
import ssl
import sys
import urllib.error
import urllib.request

try:
    with urllib.request.urlopen(sys.argv[1], timeout=10, context=ssl.create_default_context()) as resp:
        print("python urllib: OK", resp.status)
except urllib.error.URLError as exc:
    print("python urllib: FAIL", getattr(exc.reason, "verify_message", exc.reason))

And this PowerShell script runs the experiment in three phases: check the store and call Python, remove the cached copy and call Python again, then let curl.exe (the one that ships with Windows 11, which uses Windows’ own TLS library, Schannel) visit the site and call Python a third time. The removal only touches a cached copy of a public intermediate certificate in your own user store. If Step 2 showed a different issuer name for you (badssl.com renews its certificate), pass it with -Issuer.

# cache_experiment.ps1 - does Windows cache the intermediate that incomplete-chain.badssl.com leaves out?
param(
    [string]$Url = "https://incomplete-chain.badssl.com/",
    [string]$Issuer = "YR1",          # the issuer name certdoctor.py printed for that site
    [string]$Python = "python"
)

function Show-Store {
    $found = Get-ChildItem Cert:\CurrentUser\CA | Where-Object { $_.Subject -match $Issuer }
    "intermediate store holds $Issuer : " + (@($found).Count -gt 0)
}

"--- before"
Show-Store
& $Python one_call.py $Url

"--- remove the cached copy"
Get-ChildItem Cert:\CurrentUser\CA | Where-Object { $_.Subject -match $Issuer } | Remove-Item
Show-Store
& $Python one_call.py $Url

"--- let Windows (Schannel) fetch it again"
"curl.exe status: " + (& curl.exe -sS -o NUL -w "%{http_code}" $Url)
Show-Store
& $Python one_call.py $Url
powershell -ExecutionPolicy Bypass -File .\cache_experiment.ps1
--- before
intermediate store holds YR1 : True
python urllib: OK 200
--- remove the cached copy
intermediate store holds YR1 : False
python urllib: FAIL unable to get local issuer certificate
--- let Windows (Schannel) fetch it again
curl.exe status: 200
intermediate store holds YR1 : True
python urllib: OK 200

The result is the whole story in nine lines. With the intermediate in the store, Python passes. Remove it and the same Python call fails with code 20. Let curl.exe fetch the site and Windows puts the certificate back, so Python passes again. Windows fetched the missing certificate itself (the usual mechanism is the AIA address) and kept a copy in the user store; the standard library read that copy. A machine that never visited the site has no cache, and there the same program fails. This is what “it works on my machine” can mean for certificates.

You might suspect a Python 3.13 detail instead. The default context now sets VERIFY_X509_PARTIAL_CHAIN, which, according to the documentation, “instructs OpenSSL to accept intermediate CAs in the trust store to be treated as trust-anchors, in the same way as the self-signed root CA certificates.” If that flag were the reason, clearing it would break the call. This script clears it and tries again.

# step03c_partial_chain.py
"""Step 3: is the partial-chain flag the reason a cached intermediate works? Clear it and see."""
import ssl
import sys
import urllib.error
import urllib.request

URL = "https://incomplete-chain.badssl.com/"


def attempt(label, ctx):
    try:
        with urllib.request.urlopen(URL, timeout=10, context=ctx) as resp:
            print(f"{label}: OK {resp.status}")
    except urllib.error.URLError as exc:
        print(f"{label}: FAIL {getattr(exc.reason, 'verify_message', exc.reason)}")


default = ssl.create_default_context()
print(sys.version.split()[0], "- partial chain on by default:", bool(default.verify_flags & ssl.VERIFY_X509_PARTIAL_CHAIN))
attempt("default context", default)
cleared = ssl.create_default_context()
cleared.verify_flags &= ~ssl.VERIFY_X509_PARTIAL_CHAIN
attempt("flag cleared", cleared)
python step03c_partial_chain.py
3.13.14 - partial chain on by default: True
default context: OK 200
flag cleared: OK 200

The call still passes with the flag cleared. I also ran the same script on Python 3.12.16, where the flag is off by default (Step 6 shows how to set up that interpreter). It printed False on the first line and OK 200 on the other two. So the flag is not the reason: a cached intermediate in the store is enough.

Three lessons come out of this. First, a server with a missing intermediate is broken even if your laptop never complains, so do not test a certificate change only on the machine where you use a browser. Second, requests and httpx use certifi, which holds roots only, so a missing intermediate is never found for them, and they report the problem consistently. Third, truststore is worth knowing about, since its documentation lists “Fetch missing intermediate certificates” among the benefits of native system stores. I did not test it on a machine without the cached certificate, so I cannot say which route made it pass here.

Check before moving on: the first three lines of Step 3 will show your own numbers. What must match is the pattern: the issuer is in your system store but not in certifi, or it is in neither store and every library fails.

Step 4: Build a private CA and reproduce every server-side mistake

Public test sites show you failures you cannot change. To practise fixing them you need a certificate authority and a server of your own. Two small modules do that. labpki.py is a certificate factory. It makes a root CA, an intermediate CA and leaf certificates, and each function has a switch for one mistake: san=False leaves out the subject alternative name, aki=False leaves out the authority key identifier, ski=False and bc_critical=False do the same for CA certificates, and the date arguments make expired or not-yet-valid certificates. Elliptic-curve keys keep the lab fast.

# labpki.py
"""A tiny certificate factory for the lab: ECDSA P-256 keys, a root, an intermediate and leaf
certificates, with one switch for every mistake we want to reproduce."""
import datetime as dt
import ipaddress
from collections import namedtuple

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import AuthorityInformationAccessOID, ExtendedKeyUsageOID, NameOID

Issued = namedtuple("Issued", "cert key")
DAY = dt.timedelta(days=1)


def now():
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0)


def _name(common_name):
    return x509.Name([
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Lab"),
        x509.NameAttribute(NameOID.COMMON_NAME, common_name),
    ])


def _ca_usage():
    return x509.KeyUsage(
        digital_signature=False, content_commitment=False, key_encipherment=False,
        data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True,
        encipher_only=False, decipher_only=False)


def _leaf_usage():
    return x509.KeyUsage(
        digital_signature=True, content_commitment=False, key_encipherment=False,
        data_encipherment=False, key_agreement=False, key_cert_sign=False, crl_sign=False,
        encipher_only=False, decipher_only=False)


def make_ca(common_name, parent=None, *, ski=True, aki=True, bc_critical=True, days=365):
    """A root (parent is None) or an intermediate signed by parent. Returns an Issued pair."""
    key = ec.generate_private_key(ec.SECP256R1())
    signer = parent.key if parent else key
    issuer = parent.cert.subject if parent else _name(common_name)
    b = (x509.CertificateBuilder()
         .subject_name(_name(common_name)).issuer_name(issuer)
         .public_key(key.public_key()).serial_number(x509.random_serial_number())
         .not_valid_before(now() - DAY).not_valid_after(now() + days * DAY)
         .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=bc_critical)
         .add_extension(_ca_usage(), critical=True))
    if ski:
        b = b.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
    if aki:
        issuer_pub = parent.key.public_key() if parent else key.public_key()
        b = b.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_pub), critical=False)
    return Issued(b.sign(signer, hashes.SHA256()), key)


def make_leaf(parent, names, *, ips=(), common_name=None, san=True, aki=True, days=90,
              not_before=None, not_after=None, aia_url=None, self_signed=False):
    """A server certificate for `names` signed by parent (or by itself when self_signed)."""
    key = ec.generate_private_key(ec.SECP256R1())
    subject = _name(common_name or names[0])
    signer = key if self_signed else parent.key
    issuer = subject if self_signed else parent.cert.subject
    b = (x509.CertificateBuilder()
         .subject_name(subject).issuer_name(issuer)
         .public_key(key.public_key()).serial_number(x509.random_serial_number())
         .not_valid_before(not_before or now() - DAY).not_valid_after(not_after or now() + days * DAY)
         .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
         .add_extension(_leaf_usage(), critical=True)
         .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
         .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False))
    if san:
        entries = [x509.DNSName(n) for n in names]
        entries += [x509.IPAddress(ipaddress.ip_address(i)) for i in ips]
        b = b.add_extension(x509.SubjectAlternativeName(entries), critical=False)
    if aki and not self_signed:
        b = b.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(parent.key.public_key()),
                            critical=False)
    if aia_url:
        ca_issuers = x509.AccessDescription(AuthorityInformationAccessOID.CA_ISSUERS,
                                            x509.UniformResourceIdentifier(aia_url))
        b = b.add_extension(x509.AuthorityInformationAccess([ca_issuers]), critical=False)
    return Issued(b.sign(signer, hashes.SHA256()), key)


def cert_pem(cert):
    return cert.public_bytes(serialization.Encoding.PEM)


def key_pem(key):
    return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
                             serialization.NoEncryption())


def write_chain(path, *certs):
    """Write certificates (leaf first) into one PEM file and return the path."""
    with open(path, "wb") as fh:
        for cert in certs:
            fh.write(cert_pem(cert))
    return path


def write_key(path, key):
    with open(path, "wb") as fh:
        fh.write(key_pem(key))
    return path

labserver.py is an HTTPS server that serves whatever chain file you give it, leaf first. Two details matter. It performs the TLS handshake in the worker thread and records why clients walked away, so a client that refuses the certificate does not stop the server. And it listens on IPv4 and IPv6 together, so the name localhost connects at once whichever address the system tries first.

# labserver.py
"""A small HTTPS server for the lab. The TLS handshake runs in the worker thread, so a client
that refuses our certificate shows up in `failures` instead of stopping the accept loop."""
import http.server
import json
import socket
import ssl
import threading
import time


class _Handler(http.server.BaseHTTPRequestHandler):
    def setup(self):
        try:
            self.request = self.server.tls.wrap_socket(self.request, server_side=True)
        except OSError as exc:
            self.server.failures.append(getattr(exc, "reason", None) or str(exc))
            raise
        super().setup()

    def do_GET(self):
        body = json.dumps({"server": self.server.label, "path": self.path}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


class _Server(http.server.ThreadingHTTPServer):
    address_family = socket.AF_INET6
    daemon_threads = True

    def server_bind(self):
        # Accept IPv4 and IPv6, so "localhost" connects at once whichever address it picks first.
        self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
        super().server_bind()

    def handle_error(self, request, client_address):
        pass  # a refused handshake is expected in this lab; setup() already recorded it


class LabServer:
    """Serve the certificate chain in chain_pem (leaf first) with the key in key_pem."""

    def __init__(self, chain_pem, key_pem, label="lab", port=0):
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.load_cert_chain(chain_pem, key_pem)
        self.httpd = _Server(("::", port), _Handler)
        self.httpd.tls, self.httpd.label, self.httpd.failures = ctx, label, []
        self.failures = self.httpd.failures
        self.port = self.httpd.server_address[1]
        threading.Thread(target=self.httpd.serve_forever, daemon=True).start()

    def wait_for_failure(self, contains="ALERT", timeout=1.0):
        """Give the worker thread a moment to record why a client walked away; return what matches."""
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            hits = [f for f in self.failures if contains in str(f)]
            if hits:
                return hits
            time.sleep(0.02)
        return []

    def close(self):
        self.httpd.shutdown()
        self.httpd.server_close()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()

Now the scenario script. Every certificate is issued for the name localhost, the ports are chosen by the system, and each scenario changes one thing. The first two scenarios use the default trust, where our CA is unknown. The rest give each library our root certificate as its trust anchor, so the only problems left are the ones the scenario plants.

# step04_private_ca.py
"""Step 4: our own CA, a local HTTPS server, and one mistake per scenario."""
import os
import sys

import labpki as pki
from clients import all_three
from labserver import LabServer

os.makedirs("certs", exist_ok=True)
root = pki.make_ca("Lab Root CA")
issuing = pki.make_ca("Lab Issuing CA", root)
pki.write_chain("certs/root.pem", root.cert)

good = pki.make_leaf(issuing, ["localhost"])
other = pki.make_leaf(issuing, ["shop.lab.test"])
cn_only = pki.make_leaf(issuing, ["localhost"], san=False)
expired = pki.make_leaf(issuing, ["localhost"], not_before=pki.now() - 30 * pki.DAY,
                        not_after=pki.now() - pki.DAY)
early = pki.make_leaf(issuing, ["localhost"], not_before=pki.now() + pki.DAY,
                      not_after=pki.now() + 30 * pki.DAY)

# (label, certificates sent leaf first, leaf key, host in the URL, trust anchor file or None)
SCENARIOS = [
    ("default trust: our CA is not known yet", [good.cert, issuing.cert], good.key, "localhost", None),
    ("default trust, server also sends the root", [good.cert, issuing.cert, root.cert], good.key, "localhost", None),
    ("trust root.pem: chain complete", [good.cert, issuing.cert], good.key, "localhost", "certs/root.pem"),
    ("trust root.pem: server forgot the intermediate", [good.cert], good.key, "localhost", "certs/root.pem"),
    ("trust root.pem: name not in the certificate", [other.cert, issuing.cert], other.key, "localhost", "certs/root.pem"),
    ("trust root.pem: CN only, no subjectAltName", [cn_only.cert, issuing.cert], cn_only.key, "localhost", "certs/root.pem"),
    ("trust root.pem: URL uses the IP address", [good.cert, issuing.cert], good.key, "127.0.0.1", "certs/root.pem"),
    ("trust root.pem: certificate expired yesterday", [expired.cert, issuing.cert], expired.key, "localhost", "certs/root.pem"),
    ("trust root.pem: certificate not valid until tomorrow", [early.cert, issuing.cert], early.key, "localhost", "certs/root.pem"),
]

print(sys.version.split()[0])
for label, chain, key, host, cafile in SCENARIOS:
    pki.write_chain("certs/server.pem", *chain)
    pki.write_key("certs/server.key", key)
    with LabServer("certs/server.pem", "certs/server.key") as srv:
        print(label)
        for lib, verdict in all_three(f"https://{host}:{srv.port}/", cafile).items():
            print(f"  {lib:<9} {verdict}")
        if label.startswith("default trust: our CA"):
            print(f"  what the server logged: {', '.join(sorted(set(map(str, srv.wait_for_failure()))))}")
python step04_private_ca.py
3.13.14
default trust: our CA is not known yet
  requests  FAIL 20: unable to get local issuer certificate
  urllib    FAIL 20: unable to get local issuer certificate
  httpx     FAIL 20: unable to get local issuer certificate
  what the server logged: TLSV1_ALERT_UNKNOWN_CA
default trust, server also sends the root
  requests  FAIL 19: self-signed certificate in certificate chain
  urllib    FAIL 19: self-signed certificate in certificate chain
  httpx     FAIL 19: self-signed certificate in certificate chain
trust root.pem: chain complete
  requests  OK
  urllib    OK
  httpx     OK
trust root.pem: server forgot the intermediate
  requests  FAIL 20: unable to get local issuer certificate
  urllib    FAIL 20: unable to get local issuer certificate
  httpx     FAIL 20: unable to get local issuer certificate
trust root.pem: name not in the certificate
  requests  FAIL 62: Hostname mismatch, certificate is not valid for 'localhost'.
  urllib    FAIL 62: Hostname mismatch, certificate is not valid for 'localhost'.
  httpx     FAIL 62: Hostname mismatch, certificate is not valid for 'localhost'.
trust root.pem: CN only, no subjectAltName
  requests  FAIL 62: Hostname mismatch, certificate is not valid for 'localhost'.
  urllib    OK
  httpx     OK
trust root.pem: URL uses the IP address
  requests  FAIL 64: IP address mismatch, certificate is not valid for '127.0.0.1'.
  urllib    FAIL 64: IP address mismatch, certificate is not valid for '127.0.0.1'.
  httpx     FAIL 64: IP address mismatch, certificate is not valid for '127.0.0.1'.
trust root.pem: certificate expired yesterday
  requests  FAIL 10: certificate has expired
  urllib    FAIL 10: certificate has expired
  httpx     FAIL 10: certificate has expired
trust root.pem: certificate not valid until tomorrow
  requests  FAIL 9: certificate is not yet valid
  urllib    FAIL 9: certificate is not yet valid
  httpx     FAIL 9: certificate is not yet valid

Take the rows in turn.

  • Default trust. All three fail with code 20, because none of them knows our CA. The server’s log shows TLSV1_ALERT_UNKNOWN_CA: the client sent an alert and hung up. That is all the operator ever sees, which is why a client-side error is easy to miss on the server.
  • The server also sends the root. The code becomes 19, “self-signed certificate in certificate chain”. Sending the root does not make clients trust it. It only changes which message you get.
  • Chain complete, root trusted. All three pass. This is the control.
  • The server forgot the intermediate. Even with our root trusted, all three fail with code 20. This is the same failure as the public odd host, and you cannot fix it on the client side without adding the intermediate yourself. The operator has to send it.
  • The name is not in the certificate. Code 62, in all three.
  • Common name only, no subject alternative name. Here the libraries disagree. requests fails with code 62, while urllib and httpx pass, because they still fall back to the certificate’s common name. I found the reason in the installed urllib3 2.8.0, which sets context.hostname_checks_common_name = False in urllib3/util/ssl_.py (line 319). A certificate like this works with two libraries and breaks with the third, so reissue it with a proper subject alternative name.
  • The URL uses an IP address. Code 64. A certificate for a DNS name does not cover the address behind it.
  • Expired and not yet valid. Codes 10 and 9. Notice that the not-yet-valid certificate is exactly what a wrong clock on the client produces, so always check the date before blaming the server.

Check before moving on: your output should match the codes above. The only line that can differ is the server log line in the first scenario if your timing is unusual.

Step 5: Trust your own CA without breaking everything else

The right fix for an unknown private CA is to trust its root certificate and nothing wider. There are two ways: pass the root to the library in code, or set an environment variable. Libraries read different variables, so measure them. This script starts the server once and runs a fresh Python process for each setting, so each process starts clean.

# step05_env_vars.py
"""Step 5: which environment variable does each library read? Our CA is unknown to all of them."""
import os
import subprocess
import sys

import labpki as pki
from labserver import LabServer

os.makedirs("certs", exist_ok=True)
root = pki.make_ca("Lab Root CA")
issuing = pki.make_ca("Lab Issuing CA", root)
leaf = pki.make_leaf(issuing, ["localhost"])
pki.write_chain("certs/root.pem", root.cert)
pki.write_chain("certs/server.pem", leaf.cert, issuing.cert)
pki.write_key("certs/server.key", leaf.key)

CHILD = ("import sys; from clients import all_three; r = all_three(sys.argv[1]); "
         "print('  '.join(k + '=' + ('OK' if v == 'OK' else 'FAIL') for k, v in r.items()))")
CASES = [
    {},
    {"SSL_CERT_FILE": "certs/root.pem"},
    {"REQUESTS_CA_BUNDLE": "certs/root.pem"},
    {"CURL_CA_BUNDLE": "certs/root.pem"},
]
NAMES = ("SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE")

print(sys.version.split()[0])
with LabServer("certs/server.pem", "certs/server.key") as srv:
    url = f"https://localhost:{srv.port}/"
    for extra in CASES:
        env = {k: v for k, v in os.environ.items() if k not in NAMES}
        env.update(extra)
        done = subprocess.run([sys.executable, "-c", CHILD, url], env=env, capture_output=True, text=True)
        label = " ".join(extra) or "nothing set"
        print(f"{label:<20} {done.stdout.strip() or done.stderr.strip()[-120:]}")
python step05_env_vars.py
3.13.14
nothing set          requests=FAIL  urllib=FAIL  httpx=FAIL
SSL_CERT_FILE        requests=FAIL  urllib=OK  httpx=OK
REQUESTS_CA_BUNDLE   requests=OK  urllib=FAIL  httpx=FAIL
CURL_CA_BUNDLE       requests=OK  urllib=FAIL  httpx=FAIL

With nothing set, all three fail. SSL_CERT_FILE fixes urllib and httpx but not requests. REQUESTS_CA_BUNDLE fixes requests only, and so does CURL_CA_BUNDLE, which requests uses as a fallback. The documentation says the same: “This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable. If REQUESTS_CA_BUNDLE is not set, CURL_CA_BUNDLE will be used as fallback.” And for httpx: “httpx does respect the SSL_CERT_FILE and SSL_CERT_DIR environment variables by default.” I did not test SSL_CERT_DIR. If a script uses several libraries, setting one variable is not enough; passing the root in code, as the Step 4 helper does, is more predictable.

There is a trap on the other side. If you point a variable or a verify= argument at a file that holds only your private root, public sites stop verifying, because none of their roots are in the file. The next script measures the three choices against our server and a public site, then shows the fix: a bundle that holds certifi’s public roots with your root added.

# step05b_bundle.py
"""Step 5, second half: trust our own CA without losing the public ones: certifi plus our root in one bundle."""
import os
import ssl

import certifi

import labpki as pki
from clients import all_three
from labserver import LabServer

os.makedirs("certs", exist_ok=True)
root = pki.make_ca("Lab Root CA")
issuing = pki.make_ca("Lab Issuing CA", root)
leaf = pki.make_leaf(issuing, ["localhost"])
pki.write_chain("certs/root.pem", root.cert)
pki.write_chain("certs/server.pem", leaf.cert, issuing.cert)
pki.write_key("certs/server.key", leaf.key)

with open("certs/bundle.pem", "wb") as out:           # every public root, then our own
    out.write(open(certifi.where(), "rb").read().rstrip() + b"\n")
    out.write(open("certs/root.pem", "rb").read())

TRUST = [("certifi alone", certifi.where()), ("our root alone", "certs/root.pem"),
         ("certifi + our root", "certs/bundle.pem")]
with LabServer("certs/server.pem", "certs/server.key") as srv:
    sites = [("our server", f"https://localhost:{srv.port}/"), ("a public site", "https://badssl.com/")]
    for label, cafile in TRUST:
        print(label)
        for site, url in sites:
            row = all_three(url, cafile)
            print(f"  {site:<14}", "  ".join(f"{lib}={'OK' if v == 'OK' else 'FAIL'}" for lib, v in row.items()))

# the same idea in code, without a file: load the public roots, then add ours on top
ctx = ssl.create_default_context(cafile=certifi.where())
ctx.load_verify_locations("certs/root.pem")
print("stores in one context:", ctx.cert_store_stats())
python step05b_bundle.py
certifi alone
  our server     requests=FAIL  urllib=FAIL  httpx=FAIL
  a public site  requests=OK  urllib=OK  httpx=OK
our root alone
  our server     requests=OK  urllib=OK  httpx=OK
  a public site  requests=FAIL  urllib=FAIL  httpx=FAIL
certifi + our root
  our server     requests=OK  urllib=OK  httpx=OK
  a public site  requests=OK  urllib=OK  httpx=OK
stores in one context: {'x509': 114, 'crl': 0, 'x509_ca': 114}

Certifi alone verifies the public site and not our server. Our root alone verifies our server and not the public site, in all three libraries. The combined bundle verifies both. The last line shows the same idea without a file: load certifi’s roots into a context, then call load_verify_locations() to add yours on top. It holds 114 certificates, certifi’s 113 plus one. Hand that context to urllib or httpx, or give requests the bundle file.

Check before moving on: the middle block must show the public site failing for our root alone. If it does not, your environment already contains a variable that widens trust, and the experiment is not clean.

Step 6: Understand what Python 3.13 changed

You may meet a failure that only appears after upgrading Python. The documentation explains it: “The default settings for this context include VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT. These make the underlying OpenSSL implementation behave more like a conforming implementation of RFC 5280, in exchange for a small amount of incompatibility with older X.509 certificates.” The 3.13 release notes add a warning: “VERIFY_X509_STRICT may reject pre-RFC 5280 or malformed certificates that the underlying OpenSSL implementation might otherwise accept.”

OpenSSL’s documentation of its -x509_strict option lists what strict mode checks. Three of its rules matter here: “The basicConstraints of CA certificates must be marked critical.” “The authorityKeyIdentifier must be given for X.509v3 certs unless they are self-signed.” “The subjectKeyIdentifier must be given for all X.509v3 CA certs.” Private CAs made with older or hand-rolled tools often break them. This script builds five chains, one well formed and four that each break one of those rules, and tests each with all three libraries. It also tests two contexts built by hand: one with the strict flag cleared, which is the escape hatch the documentation describes, and one with it set.

# step06_strict.py
"""Step 6: certificates that older Python accepts and Python 3.13+ refuses (VERIFY_X509_STRICT)."""
import os
import ssl
import sys

import labpki as pki
from clients import all_three, get_urllib
from labserver import LabServer

os.makedirs("certs", exist_ok=True)
root = pki.make_ca("Lab Root CA")
old_root = pki.make_ca("Old Root CA", ski=False, aki=False)       # a root without key identifiers
issuing = pki.make_ca("Lab Issuing CA", root)
old_sub = pki.make_ca("Old Sub CA", old_root)
bare = pki.make_ca("Bare Issuing CA", root, ski=False, aki=False)
soft = pki.make_ca("Soft Issuing CA", root, bc_critical=False)

# (label, trust anchor, issuing CA sent with the leaf, leaf)
SCENARIOS = [
    ("well-formed chain", root, issuing, pki.make_leaf(issuing, ["localhost"])),
    ("root has no key identifiers", old_root, old_sub, pki.make_leaf(old_sub, ["localhost"])),
    ("issuing CA has no key identifiers", root, bare, pki.make_leaf(bare, ["localhost"])),
    ("issuing CA basicConstraints not critical", root, soft, pki.make_leaf(soft, ["localhost"])),
    ("leaf has no authorityKeyIdentifier", root, issuing, pki.make_leaf(issuing, ["localhost"], aki=False)),
]

strict = bool(ssl.create_default_context().verify_flags & ssl.VERIFY_X509_STRICT)
print(sys.version.split()[0], "OpenSSL", ssl.OPENSSL_VERSION.split()[1], "- strict by default:", strict)
for label, anchor, inter, leaf in SCENARIOS:
    pki.write_chain("certs/trust.pem", anchor.cert)
    pki.write_chain("certs/server.pem", leaf.cert, inter.cert)
    pki.write_key("certs/server.key", leaf.key)
    with LabServer("certs/server.pem", "certs/server.key") as srv:
        url = f"https://localhost:{srv.port}/"
        print(label)
        for lib, verdict in all_three(url, "certs/trust.pem").items():
            print(f"  {lib:<9} {verdict}")
        # the documented escape hatch, for an old private CA you cannot reissue today
        relaxed = ssl.create_default_context(cafile="certs/trust.pem")
        relaxed.verify_flags &= ~ssl.VERIFY_X509_STRICT
        print(f"  urllib with the strict flag cleared: {get_urllib(url, context=relaxed)}")
        tight = ssl.create_default_context(cafile="certs/trust.pem")
        tight.verify_flags |= ssl.VERIFY_X509_STRICT
        print(f"  urllib with the strict flag set    : {get_urllib(url, context=tight)}")
python step06_strict.py
3.13.14 OpenSSL 3.0.21 - strict by default: True
well-formed chain
  requests  OK
  urllib    OK
  httpx     OK
  urllib with the strict flag cleared: OK
  urllib with the strict flag set    : OK
root has no key identifiers
  requests  FAIL 86: Missing Subject Key Identifier
  urllib    FAIL 86: Missing Subject Key Identifier
  httpx     FAIL 86: Missing Subject Key Identifier
  urllib with the strict flag cleared: OK
  urllib with the strict flag set    : FAIL 86: Missing Subject Key Identifier
issuing CA has no key identifiers
  requests  FAIL 85: Missing Authority Key Identifier
  urllib    FAIL 85: Missing Authority Key Identifier
  httpx     FAIL 85: Missing Authority Key Identifier
  urllib with the strict flag cleared: OK
  urllib with the strict flag set    : FAIL 85: Missing Authority Key Identifier
issuing CA basicConstraints not critical
  requests  FAIL 89: Basic Constraints of CA cert not marked critical
  urllib    FAIL 89: Basic Constraints of CA cert not marked critical
  httpx     FAIL 89: Basic Constraints of CA cert not marked critical
  urllib with the strict flag cleared: OK
  urllib with the strict flag set    : FAIL 89: Basic Constraints of CA cert not marked critical
leaf has no authorityKeyIdentifier
  requests  FAIL 85: Missing Authority Key Identifier
  urllib    FAIL 85: Missing Authority Key Identifier
  httpx     FAIL 85: Missing Authority Key Identifier
  urllib with the strict flag cleared: OK
  urllib with the strict flag set    : FAIL 85: Missing Authority Key Identifier

On Python 3.13.14 the well-formed chain passes everywhere and each of the four broken chains fails in all three libraries, with code 86 for the missing subject key identifier, 85 for the missing authority key identifier (twice) and 89 for the non-critical basic constraints. So requests and httpx enforce strict mode too, not only urllib. In every case clearing the strict flag makes the chain pass. Now run the same file with Python 3.12.16. The commands below install the uv tool, let it download that Python, create a second environment and run the script in it.

python -m pip install uv
uv python install 3.12
uv venv --python 3.12 .venv312
uv pip install --python .venv312\Scripts\python.exe requests==2.34.2 httpx==0.29.0 cryptography==50.0.2 certifi==2026.11.20
.venv312\Scripts\python.exe step06_strict.py

The first line of its output reads 3.12.16 OpenSSL 3.5.9 - strict by default: False. All five chains pass in all three libraries, including the four that Python 3.13 rejects. To check that the flag and not the OpenSSL version causes the difference, look at the line that sets the flag by hand: on Python 3.12 it fails with the same three codes, 86, 85 and 89, as Python 3.13 does without any help. The table sums it up.

Chain Python 3.13.14 (strict by default) Python 3.12.16 (default) Python 3.12.16 with the flag set
Well formed OK OK OK
Root without key identifiers 86 Missing Subject Key Identifier OK 86
Issuing CA without key identifiers 85 Missing Authority Key Identifier OK 85
Issuing CA with non-critical basicConstraints 89 Basic Constraints of CA cert not marked critical OK 89
Leaf without authorityKeyIdentifier 85 Missing Authority Key Identifier OK 85

What should you do about it? The right fix is to reissue the CA certificate with the extensions included. make_ca() in labpki.py shows which ones: a subject key identifier, an authority key identifier and a critical basic constraints extension. Until you can do that, the documentation’s escape hatch is available: “While disabling this is not recommended”, you can clear the flag with ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT on a context you create yourself, as the script does. Treat it as a stopgap, and note in your code why it is there. The Step 2 tool flags these problems before they bite, as the WARN lines for untrusted-root.badssl.com showed.

Check before moving on: on Python 3.13 the four broken chains must show codes 86, 85, 89 and 85. If you see OK everywhere, your Python is older than 3.13 or a package changed the default context.

Step 7: See what verify=False really costs

This step answers the question people ask last and should ask first: what is the harm in turning verification off? The requests documentation is direct about it: “Note that when verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks.” The script makes that concrete. It starts two servers that both claim to be localhost: the real service, signed by our CA, and an impostor signed by a CA we never heard of. In real life the impostor is a device on the network path or a hijacked DNS record. Each server says who it is in its answer.

# step07_verify_false.py
"""Step 7: what verify=False really costs. Two servers answer for the same name: the real one and an impostor."""
import os
import warnings

import requests

import labpki as pki
from clients import short
from labserver import LabServer

os.makedirs("certs", exist_ok=True)
root = pki.make_ca("Lab Root CA")
issuing = pki.make_ca("Lab Issuing CA", root)
real = pki.make_leaf(issuing, ["localhost"])
evil_root = pki.make_ca("Evil Root CA")
evil_issuing = pki.make_ca("Evil Issuing CA", evil_root)
fake = pki.make_leaf(evil_issuing, ["localhost"])
pki.write_chain("certs/root.pem", root.cert)
pki.write_chain("certs/real.pem", real.cert, issuing.cert)
pki.write_key("certs/real.key", real.key)
pki.write_chain("certs/fake.pem", fake.cert, evil_issuing.cert)
pki.write_key("certs/fake.key", fake.key)

with LabServer("certs/real.pem", "certs/real.key", label="the real service") as good, \
        LabServer("certs/fake.pem", "certs/fake.key", label="an impostor") as evil:
    cases = [
        ("real server,  verify=root.pem", good.port, "certs/root.pem"),
        ("impostor,     verify=root.pem", evil.port, "certs/root.pem"),
        ("impostor,     verify=False   ", evil.port, False),
    ]
    for label, port, verify in cases:
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always")
            try:
                who = requests.get(f"https://localhost:{port}/", verify=verify, timeout=10).json()["server"]
                print(f"{label} -> answered by {who}")
            except Exception as exc:
                print(f"{label} -> FAIL {short(exc)}")
        for w in caught:
            if w.category.__name__ == "InsecureRequestWarning":
                print("   warning:", str(w.message).split(" See:")[0])
python step07_verify_false.py
real server,  verify=root.pem -> answered by the real service
impostor,     verify=root.pem -> FAIL 20: unable to get local issuer certificate
impostor,     verify=False    -> answered by an impostor
   warning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised.

With the root pinned, the real server answers and the impostor is refused with code 20. With verify=False the program talks to the impostor and reads its answer as if it were genuine, and the only trace is a warning that is easy to miss in logs. Imagine that answer is a price, a password-reset link or a software update. The correct fix is the one in the middle row: trust the right root and keep verification on.

Check before moving on: the impostor row with verify=root.pem must fail and the one with verify=False must be answered by the impostor.

Step 8: Catch broken chains in CI before users do

The last tool turns what you learned into a check you can schedule. certwatch.py connects to each host with a clean trust store: certifi’s roots, or the file you pass with --cafile, never the machine’s own store. That choice is deliberate, because Step 3 showed that your own machine’s store can hide a missing intermediate. The function returns fail for any verification error with the OpenSSL code in the message, warn when the certificate verifies but expires within 21 days, and ok otherwise. The exit code is 1 if any host is not ok, so a CI job turns red before the certificate expires.

# certwatch.py
"""certwatch: fail a CI job when a host's certificate will not verify on a clean machine, or expires soon."""
import datetime as dt
import socket
import ssl
import sys

import certifi
from cryptography import x509


def check(host, port=443, cafile=None, warn_days=21, timeout=10):
    """Return (status, message). Trust comes from cafile or certifi only, never from this machine's store,
    so a missing intermediate that your own laptop has cached still shows up."""
    ctx = ssl.create_default_context(cafile=cafile or certifi.where())
    try:
        with socket.create_connection((host, port), timeout=timeout) as raw:
            with ctx.wrap_socket(raw, server_hostname=host) as tls:
                leaf = x509.load_der_x509_certificate(tls.getpeercert(binary_form=True))
    except ssl.SSLCertVerificationError as exc:
        return "fail", f"{exc.verify_code}: {exc.verify_message}"
    except OSError as exc:
        return "fail", f"cannot connect: {exc}"
    days = (leaf.not_valid_after_utc - dt.datetime.now(dt.timezone.utc)).days
    if days < warn_days:
        return "warn", f"verifies, but expires in {days} days"
    return "ok", f"verifies, {days} days left"


def main(argv):
    cafile, warn_days, hosts = None, 21, []
    args = iter(argv)
    for arg in args:
        if arg == "--cafile":
            cafile = next(args)
        elif arg == "--warn-days":
            warn_days = int(next(args))
        else:
            hosts.append(arg)
    if not hosts:
        print("usage: python certwatch.py [--cafile FILE] [--warn-days N] HOST[:PORT] ...")
        return 2
    bad = 0
    for item in hosts:
        host, _, port = item.partition(":")
        status, message = check(host, int(port or 443), cafile, warn_days)
        print(f"{status.upper():<4} {item}: {message}")
        bad += status != "ok"
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
python certwatch.py badssl.com incomplete-chain.badssl.com expired.badssl.com
OK   badssl.com: verifies, 27 days left
FAIL incomplete-chain.badssl.com: 20: unable to get local issuer certificate
FAIL expired.badssl.com: 10: certificate has expired

The odd host fails here with code 20 even though urllib passed it on my machine in Step 1. That is the point: a CI runner starts without your cached intermediate, and this check behaves like the runner. The days-left number changes every day, so yours will differ. To check a private CA, add --cafile root.pem.

Test the tools

Tools that decide whether a connection is safe deserve tests. The first file tests the pure analysis with certificates built in memory, so it needs no network. It covers a good chain, a root that is sent and trusted, a leaf-only chain, a gap in the middle, an unknown root, a chain that stops below an untrusted issuer, a wrong name, six cases of name matching, an IP address, a common-name-only certificate, expired and not-yet-valid certificates, the expiry warning, the now parameter, the three strict-mode findings and the AIA address. One of these tests exists because my first version blamed the server whenever a chain stopped below an unknown issuer; test_chain_stops_below_an_untrusted_issuer pins down the wording that admits the tool cannot tell the two cases apart.

# test_certdoctor.py
import datetime as dt

import pytest

import certdoctor as cd
import labpki as pki

ROOT = pki.make_ca("Test Root CA")
ISSUER = pki.make_ca("Test Issuing CA", ROOT)
ROOTS = [ROOT.cert]


def run(chain, host="shop.test", roots=ROOTS, now=None):
    return cd.analyse([c.cert if hasattr(c, "cert") else c for c in chain], host, roots, now)


def texts(findings, level=None):
    return " | ".join(t for lv, t in findings if level in (None, lv))


def good_leaf(**kw):
    return pki.make_leaf(ISSUER, kw.pop("names", ["shop.test"]), **kw)


def test_good_chain_has_no_findings():
    assert run([good_leaf(), ISSUER]) == []


def test_root_sent_and_trusted_is_fine():
    assert run([good_leaf(), ISSUER, ROOT]) == []


def test_leaf_only_means_missing_intermediate():
    found = run([good_leaf()])
    assert [lv for lv, _ in found] == ["error"]
    assert "sent only the leaf" in found[0][1]


def test_gap_in_the_middle():
    other = pki.make_ca("Other CA", ROOT)
    found = run([good_leaf(), other, ROOT])
    assert "was not issued by certificate 1" in texts(found, "error")


def test_unknown_self_signed_root():
    rogue = pki.make_ca("Rogue Root")
    leaf = pki.make_leaf(rogue, ["shop.test"])
    assert "not in the trust bundle" in texts(run([leaf, rogue]), "error")


def test_chain_stops_below_an_untrusted_issuer():
    other_root = pki.make_ca("Other Root")
    mid = pki.make_ca("Other Mid", other_root)
    leaf = pki.make_leaf(mid, ["shop.test"])
    assert "chain stops at Other Mid" in texts(run([leaf, mid]), "error")


def test_name_mismatch():
    assert "shop.test is not in the certificate" in texts(run([good_leaf(names=["www.other.test"]), ISSUER]), "error")


@pytest.mark.parametrize("pattern,host,ok", [
    ("*.lab.test", "shop.lab.test", True),
    ("*.lab.test", "a.b.lab.test", False),
    ("*.lab.test", "lab.test", False),
    ("Shop.Lab.Test", "shop.lab.test", True),
    ("shop.lab.test.", "shop.lab.test", True),
    ("shop.lab.test", "shop.lab.test.evil.test", False),
])
def test_name_matching_rules(pattern, host, ok):
    assert cd.name_matches(pattern, host) is ok


def test_ip_address_needs_an_ip_san():
    assert "address 127.0.0.1 is not in the certificate" in texts(run([good_leaf(), ISSUER], host="127.0.0.1"), "error")
    with_ip = good_leaf(ips=["127.0.0.1"])
    assert run([with_ip, ISSUER], host="127.0.0.1") == []


def test_cn_only_certificate_is_a_warning():
    found = run([good_leaf(san=False), ISSUER])
    assert [lv for lv, _ in found] == ["warn"]
    assert "no subjectAltName" in found[0][1]


def test_expired_and_not_yet_valid():
    now = pki.now()
    old = good_leaf(not_before=now - 60 * pki.DAY, not_after=now - pki.DAY)
    early = good_leaf(not_before=now + pki.DAY, not_after=now + 30 * pki.DAY)
    assert "expired on" in texts(run([old, ISSUER]), "error")
    assert "is not valid until" in texts(run([early, ISSUER]), "error")


def test_expiry_warning_uses_the_threshold():
    soon = good_leaf(days=10)
    assert "expires in 9 days" in texts(run([soon, ISSUER]), "warn") or "expires in 10 days" in texts(run([soon, ISSUER]), "warn")
    assert run([good_leaf(days=60), ISSUER]) == []


def test_now_parameter_is_respected():
    later = pki.now() + 200 * pki.DAY
    assert "expired on" in texts(run([good_leaf(days=90), ISSUER], now=later), "error")


def test_strict_mode_findings():
    no_ski = pki.make_ca("No SKI CA", ROOT, ski=False)
    soft = pki.make_ca("Soft CA", ROOT, bc_critical=False)
    assert "subjectKeyIdentifier" in texts(run([pki.make_leaf(no_ski, ["shop.test"]), no_ski]), "warn")
    assert "not critical" in texts(run([pki.make_leaf(soft, ["shop.test"]), soft]), "warn")
    assert "no authorityKeyIdentifier" in texts(run([good_leaf(aki=False), ISSUER]), "warn")


def test_aia_url_is_reported():
    leaf = good_leaf(aia_url="http://ca.test/issuer.cer")
    assert "http://ca.test/issuer.cer" in texts(run([leaf]), "error")

The second file tests certwatch.py against real local servers from labserver.py: a good server, a missing intermediate, an expired certificate, a certificate that expires soon, an unknown CA, a refused connection and the exit codes.

# test_certwatch.py
import pytest

import certwatch
import labpki as pki
from labserver import LabServer


@pytest.fixture(scope="module")
def ca(tmp_path_factory):
    folder = tmp_path_factory.mktemp("pki")
    root = pki.make_ca("Watch Root CA")
    issuing = pki.make_ca("Watch Issuing CA", root)
    pki.write_chain(str(folder / "root.pem"), root.cert)
    return root, issuing, str(folder / "root.pem"), folder


def serve(ca, leaf, send_issuer=True):
    root, issuing, root_pem, folder = ca
    chain = [leaf.cert] + ([issuing.cert] if send_issuer else [])
    pki.write_chain(str(folder / "server.pem"), *chain)
    pki.write_key(str(folder / "server.key"), leaf.key)
    return LabServer(str(folder / "server.pem"), str(folder / "server.key"))


def test_good_server_is_ok(ca):
    with serve(ca, pki.make_leaf(ca[1], ["localhost"])) as srv:
        status, msg = certwatch.check("localhost", srv.port, cafile=ca[2])
    assert status == "ok" and msg.startswith("verifies, 8")


def test_missing_intermediate_fails_with_code_20(ca):
    with serve(ca, pki.make_leaf(ca[1], ["localhost"]), send_issuer=False) as srv:
        status, msg = certwatch.check("localhost", srv.port, cafile=ca[2])
    assert status == "fail" and msg.startswith("20: ")


def test_expired_fails_with_code_10(ca):
    leaf = pki.make_leaf(ca[1], ["localhost"], not_before=pki.now() - 30 * pki.DAY, not_after=pki.now() - pki.DAY)
    with serve(ca, leaf) as srv:
        status, msg = certwatch.check("localhost", srv.port, cafile=ca[2])
    assert status == "fail" and msg.startswith("10: ")


def test_expiring_soon_warns(ca):
    with serve(ca, pki.make_leaf(ca[1], ["localhost"], days=10)) as srv:
        status, msg = certwatch.check("localhost", srv.port, cafile=ca[2], warn_days=21)
        assert status == "warn" and "expires in" in msg
        assert certwatch.check("localhost", srv.port, cafile=ca[2], warn_days=5)[0] == "ok"


def test_unknown_ca_fails_without_cafile(ca):
    with serve(ca, pki.make_leaf(ca[1], ["localhost"])) as srv:
        status, msg = certwatch.check("localhost", srv.port)
    assert status == "fail" and msg.startswith("20: ")


def test_connection_refused_fails():
    status, msg = certwatch.check("localhost", 1, timeout=2)
    assert status == "fail" and msg.startswith("cannot connect")


def test_main_exit_codes(ca, capsys):
    with serve(ca, pki.make_leaf(ca[1], ["localhost"])) as srv:
        assert certwatch.main(["--cafile", ca[2], f"localhost:{srv.port}"]) == 0
        assert certwatch.main([f"localhost:{srv.port}"]) == 1
    assert certwatch.main([]) == 2
python -m pytest -q
...........................                                                                  [100%]
27 passed in 8.15s

Passing tests only matter if they can fail. The last script plants one bug at a time in certdoctor.py or certwatch.py, such as a wildcard that spans several labels, an expiry check that never fires or a --cafile option that is ignored, and runs the tests against each. A bug that the tests miss is reported as SURVIVED.

# mutants.py
"""Plant one bug at a time in certdoctor.py or certwatch.py and check that the tests notice."""
import pathlib
import shutil
import subprocess
import sys
import tempfile

HERE = pathlib.Path(__file__).parent
FILES = ["labpki.py", "labserver.py", "certdoctor.py", "certwatch.py", "test_certdoctor.py", "test_certwatch.py"]

MUTANTS = [
    ("certdoctor.py", "wildcard spans several labels", 'return bool(head) and rest == pattern[2:]', 'return host.endswith(pattern[1:])'),
    ("certdoctor.py", "name match is case sensitive", 'pattern, host = pattern.lower().rstrip("."), host.lower().rstrip(".")', 'pattern, host = pattern.rstrip("."), host.rstrip(".")'),
    ("certdoctor.py", "IP check removed", 'elif ip and ip not in sans[1]:', 'elif False:'),
    ("certdoctor.py", "missing SAN not reported", 'if sans is None:', 'if False:'),
    ("certdoctor.py", "expired never reported", 'elif left < dt.timedelta(0):', 'elif False:'),
    ("certdoctor.py", "not-yet-valid never reported", 'if now < cert.not_valid_before_utc:', 'if False:'),
    ("certdoctor.py", "expiry warning off", 'WARN_DAYS = 21', 'WARN_DAYS = 0'),
    ("certdoctor.py", "gaps in the chain ignored", 'if chain[i].issuer != chain[i + 1].subject:', 'if False:'),
    ("certdoctor.py", "unknown self-signed root accepted", 'if top not in roots:', 'if False:'),
    ("certdoctor.py", "missing intermediate ignored", 'elif not any(top.issuer == r.subject for r in roots):', 'elif False:'),
    ("certdoctor.py", "missing SKI on a CA ignored", 'if is_ca and _ext(cert, x509.SubjectKeyIdentifier) is None:', 'if False:'),
    ("certdoctor.py", "missing AKI check inverted", 'if cert.issuer != cert.subject and _ext(cert, x509.AuthorityKeyIdentifier) is None:', 'if cert.issuer == cert.subject and _ext(cert, x509.AuthorityKeyIdentifier) is None:'),
    ("certwatch.py", "certwatch ignores --cafile", 'ssl.create_default_context(cafile=cafile or certifi.where())', 'ssl.create_default_context()'),
    ("certwatch.py", "expiry threshold ignored", 'if days < warn_days:', 'if False:'),
    ("certwatch.py", "verify errors reported as connect errors", 'except ssl.SSLCertVerificationError as exc:', 'except ZeroDivisionError as exc:'),
    ("certwatch.py", "failures give exit code 0", 'return 1 if bad else 0', 'return 0'),
]


def run_tests(folder):
    done = subprocess.run([sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider"],
                          cwd=folder, capture_output=True, text=True)
    return done.returncode == 0


def main():
    caught = 0
    with tempfile.TemporaryDirectory() as tmp:
        for name in FILES:
            shutil.copy(HERE / name, tmp)
        print("control (no bug planted):", "tests pass" if run_tests(tmp) else "TESTS FAIL")
        for target, label, old, new in MUTANTS:
            path = pathlib.Path(tmp) / target
            original = (HERE / target).read_text(encoding="utf-8")
            assert original.count(old) == 1, (label, original.count(old))
            path.write_text(original.replace(old, new), encoding="utf-8")
            killed = not run_tests(tmp)
            caught += killed
            print(f"{'caught  ' if killed else 'SURVIVED'} {label}")
            path.write_text(original, encoding="utf-8")
    print(f"{caught} of {len(MUTANTS)} planted bugs caught")


if __name__ == "__main__":
    main()
python mutants.py
control (no bug planted): tests pass
caught   wildcard spans several labels
caught   name match is case sensitive
caught   IP check removed
caught   missing SAN not reported
caught   expired never reported
caught   not-yet-valid never reported
caught   expiry warning off
caught   gaps in the chain ignored
caught   unknown self-signed root accepted
caught   missing intermediate ignored
caught   missing SKI on a CA ignored
caught   missing AKI check inverted
caught   certwatch ignores --cafile
caught   expiry threshold ignored
caught   verify errors reported as connect errors
caught   failures give exit code 0
16 of 16 planted bugs caught

All 16 planted bugs are caught. One of the planted bugs shows why the certwatch tests assert that a message starts with the OpenSSL code (20: ) instead of merely containing the right words: a verification failure mislabelled as a connection error would still contain those words, and only the start of the message tells the two apart.

Check the whole thing end to end

To confirm that everything works, run these four commands in order from the project folder, each against something you own or one of the test hosts.

  1. python certdoctor.py YOUR-HOST should print your chain, Python verifies it: yes and no ERROR lines.
  2. python certwatch.py YOUR-HOST should print OK and end with exit code 0 (in PowerShell, check $LASTEXITCODE).
  3. python -m pytest -q should print 27 passed.
  4. python certwatch.py incomplete-chain.badssl.com should print FAIL with code 20 whatever your own store holds, as long as badssl.com keeps that host broken, which shows the check does not depend on your own store.

Common mistakes and how to check for them

  • Turning verification off globally. It hides every failure in this tutorial and lets an impostor in (Step 7). Pass a trust anchor instead.
  • Pointing a variable or verify= at only your private root. Public sites then fail (Step 5). Use a bundle that has both.
  • Trusting your laptop as the test. A cached intermediate can hide a broken server (Step 3). Run certwatch.py or test from a clean machine.
  • Serving only the leaf. Concatenate the leaf and then each intermediate into one file, leaf first, the way write_chain() does in labpki.py.
  • Using an IP address or a name the certificate does not list. Codes 62 and 64. Fix the URL or reissue the certificate with the right subject alternative names.
  • A certificate with only a common name. requests refuses it, other libraries do not (Step 4).
  • An old private CA on Python 3.13 or later. Reissue it. Clearing the strict flag is a temporary workaround (Step 6).
  • A wrong clock. It produces code 9 or 10 on a perfectly good certificate. Check the date first.
  • Assuming other tools follow Python’s rules. Tools such as pip, git and Node have their own settings for trusted certificates. I did not test them for this tutorial, so check each tool’s documentation.

Next steps

  • Run certwatch.py against every host you depend on, on a schedule in your CI system, and fail the job on any non-zero exit code.
  • Read section 4.4.2 of RFC 8446 and section 4.2.2.1 of RFC 5280, the two passages quoted above, for the exact wording of what a server sends and what AIA means.
  • If you run a private CA, build one from scratch and add mutual TLS in How to Build a Private Certificate Authority and Enforce Mutual TLS in Python, and compare its certificate extensions with make_ca() here.
  • Once connections are safe, check what you download over them with How to Verify a Download Before You Run It and How to Lock Python Dependencies With Hashes So pip Refuses a Swapped File.
  • Repeat Steps 3 and 5 on Linux and macOS and compare the trust stores. I only measured Windows.

Sources and method

  • Python documentation: the ssl module (create_default_context, load_default_certs, VERIFY_X509_PARTIAL_CHAIN, SSLCertVerificationError, get_unverified_chain) and What’s New in Python 3.13.
  • Requests, advanced usage (SSL certificate verification and CA certificates) and HTTPX, SSL.
  • truststore documentation (version 0.10.5).
  • OpenSSL verification options, the -x509_strict option.
  • RFC 8446, section 4.4.2, and RFC 5280, section 4.2.2.1.
  • badssl.com, the public test hosts expired, wrong.host, self-signed, untrusted-root and incomplete-chain.
  • Method and dates: all measurements were run on November 30, 2026 on Windows 11 with Python 3.13.14 (OpenSSL 3.0.21), Python 3.12.16 (OpenSSL 3.5.9, Step 6 only), requests 2.34.2, urllib3 2.8.0, httpx 0.29.0, cryptography 50.0.2, certifi 2026.11.20, truststore 0.10.5 and pytest 9.2.0. The public hosts, their certificates and the days-left numbers belong to that day and will change. The certificate store counts are specific to my machine. I did not test macOS, Linux, pip, git, Node, SSL_CERT_DIR or a machine with no cached intermediate.

Tags:

Certificate AuthoritiesHTTPXPKIPythonPython SecurityRequestsTLStruststore

Share

Pale church wall with an arched window filled with a star-pattern stone lattice screen
Previous Post

The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
30 Nov
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
30 Nov
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
Trending
November 30, 2026
How to Fix SSL CERTIFICATE_VERIFY_FAILED in Python Without Turning Verification Off: Read the Error Code, Find Who Has to Fix It, Trust Your Own CA, and Catch Broken Chains in CI
November 30, 2026
The Unpublished Lattice Paper Attributed to Anthropic Reached the Public as Two Title Hashes That Match One Guessable String, the Coverage Splits on What It Breaks Because the Title Names Quantum Algorithms, Not a Key Recovery, and 21 of 24 Sites We Tested Still Pair ML-KEM With X25519
November 30, 2026
Cacti’s 4HTTP2SHELL Chain Drew 1,793 Attack Attempts on One Honeypot Sensor in Four Days, but the Fix Is Still Only Source Patches With No 1.2.32 Release or CVE ID, the Advisory Calls It “Authenticated,” and on Our Reading of the Code the Guest Route Hinges on One Setting That Ships as “No User”
November 30, 2026
How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
November 30, 2026
The Register Gives China Mobile Credit for the “Most Capable” All-Domestic Open-Weight Model, but It Is China Telecom’s Xing4.1-Preview, Its Report Has No Capability Scores, the 4.68x Is a Simulation, and the Model Card’s Own Table Has It First or Tied for First on 2 of 18 Rows
November 30, 2026
easyDNS Says Customer Records, Stored AWS Keys and Unsalted Mailbox Password Hashes Were Exposed, but the Public Notice Gives No Counts, the Entry Point Appears Only in the CEO’s Comments to a Reporter, and It Is the Second Security Incident Its Blog Has Posted This Year

Related Posts

A laptop wrapped in a chain and padlock, illustrating least-privilege controls for AI agents.
Learning Hub

How to Secure Tool-Using AI Agents Before They Touch Production

June 8, 2026
Colorful sticky notes arranged on an office wall, symbolizing governance checklists and planning.
Learning Hub

AI Governance for Agentic Apps: A Practical Checklist for Builders

June 8, 2026
A technician connects green fiber optic cables at a data center, representing a private production inference endpoint.
Learning Hub

How to Deploy a Fine-Tuned LLM Behind a Private Production Inference Endpoint

June 8, 2026
Narrow aisle behind black supercomputer racks in a data center
Learning Hub

Kubernetes SELinux Volume Labeling: What Cluster Operators Should Audit Before v1.37

June 8, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026