← Back to Home

TLS verify: six failures and one silent downgrade

TLScertificatesPython

The same certificate gets three different answers depending on which tool you hand it to. Python's ssl module raises unable to get local issuer certificate. openssl verify prints error 20. And requests hands you a 200 with one warning in the log.

All three are the same four checks with different defaults. I built a three-tier chain on this machine (root, intermediate, leaf) and ran every failure mode I could think of. Every error string below is copied verbatim. The setup is described in the fourth section.

TL;DR:

// FLOW_01Where a missing issuer shows up5 NODES01STEP_01client trusts root02STEP_02server sends leaf03STEP_03issuer not found04STEP_04add middle cert05STEP_05handshake okEND_OF_FLOW
Where a missing issuer shows up · diagram drawn from this article
Python
Technologies referenced · icons from Simple Icons (CC0)

Verification is four checks, not one switch

People talk about certificate verification as a switch. It is four independent checks, and each one fails with its own message.

The first is the chain: can the leaf signature be traced to a root you trust. The second is the name: does the hostname you dialed appear in the SAN. The third is purpose: does the extendedKeyUsage allow serverAuth. The fourth is time: is now inside notBefore and notAfter.

Only the first needs anything missing from a chain. The other three are properties of a single certificate. That distinction is worth internalising: unable to get local issuer always means the chain, never the hostname, the purpose, or the clock.

The bench: three tiers and a real chain

Environment: Windows 11 10.0.26300, CPython 3.13.14, OpenSSL 3.5.7, requests 2.31.0, urllib3 2.5.0. I generated three certificates with the openssl CLI: a self-signed root CA (pathlen:1), an intermediate signed by that root (pathlen:0), and a leaf signed by the intermediate with DNS:localhost,IP:127.0.0.1 in its SAN.

openssl req -x509 -newkey rsa:2048 -nodes -keyout root.key -out root.pem -days 3650 \
  -subj "/CN=Lab Root CA" -addext "basicConstraints=critical,CA:TRUE,pathlen:1"
openssl req -new -newkey rsa:2048 -nodes -keyout inter.key -out inter.csr -subj "/CN=Lab Intermediate CA"
openssl x509 -req -in inter.csr -CA root.pem -CAkey root.key -CAcreateserial -out inter.pem \
  -days 1825 -extfile inter.ext

The server runs ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) on a random port on 127.0.0.1. Whatever file you hand to load_cert_chain() is what the server sends. The client always uses ssl.create_default_context(cafile=…). That way "what is sent" and "what is trusted" are two variables I can change one at a time.

Failure one: the signer is not on the chain

Server sends the leaf only, client trusts the root only. The handshake stops at verification:

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
unable to get local issuer certificate (_ssl.c:1032)

Append the intermediate to the client's trust file (cat root.pem inter.pem > bundle.pem) and the identical request returns 200. The other route works too: have the server send the intermediate along with the leaf, keep the client trusting only the root, and the handshake passes.

The command line reports the same diagnosis with a different number:

$ openssl verify -CAfile root.pem leaf.pem
error 20 at 0 depth lookup: unable to get local issuer certificate
$ openssl verify -CAfile root.pem -untrusted inter.pem leaf.pem
leaf.pem: OK

-untrusted means "this is not a root, but it may sit in the middle of the chain". It supplies exactly the missing level-zero issuer.

Sending the root again does not fix it

A common misreading of "incomplete chain" is "attach one more certificate". So people ship leaf plus root, with the intermediate still absent. The measured result is identical to doing nothing:

certificate verify failed: unable to get local issuer certificate (_ssl.c:1032)

Send all three (leaf, intermediate, root) and it passes. OpenSSL tolerates one extra root in the chain but will not accept a chain missing an intermediate. The two cases are not symmetric, so "send more, it can't hurt" is the wrong reflex when debugging.

CN without SAN passes

This one is counter-intuitive. I signed a second leaf with CN=localhost and no subjectAltName at all. The Python client connected to localhost and passed. openssl verify -verify_hostname localhost also returned OK.

Change the hostname and it fails instantly:

$ openssl verify -CAfile bundle.pem -verify_hostname other.test leaf2.pem
error 62 at 0 depth lookup: hostname mismatch

So the CN is being used as a name source. There is a trap in the documentation here: the OpenSSL man page for X509_check_host() states that by default only the subjectAltName is consulted and the subject DN is not. Python and openssl verify -verify_hostname go through X509_VERIFY_PARAM_set1_host() instead, and on this build that path does fall back to the CN. Read the manual page carefully — it describes a different entry point than the one your client uses.

The practical consequence: a script passing does not prove a browser will accept the certificate. SAN is a hard requirement in modern browsers, but that is browser policy, not something I measured here. Check the browser documentation before you make a compatibility call.

Wildcards cover one label

With DNS:*.local.test in the SAN, dialing x.local.test passes and a.b.local.test fails:

certificate verify failed: Hostname mismatch, certificate is not valid for
'a.b.local.test'. (_ssl.c:1032)

OpenSSL documents this as "wildcards … match only in the left-most label" by default. The same certificate also permits partial wildcards such as w*.local.test and *w.local.test. Crossing a label boundary requires X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS. The gap between the * you wrote and the scope you imagined is usually exactly one level.

Wrong purpose and wrong time are different errors

Switch the leaf's extendedKeyUsage from serverAuth to clientAuth. The server starts fine, and the client reports:

certificate verify failed: unsuitable certificate purpose (_ssl.c:1032)

Time failures come in two opposite directions. I signed one certificate with notBefore in 2020 and notAfter in 2021:

certificate verify failed: certificate has expired (_ssl.c:1032)

Move notBefore to 2030 and the same chain says:

certificate verify failed: certificate is not yet valid (_ssl.c:1032)

Two messages, two completely different investigations. Expired means renew. Not yet valid usually means the local clock is fast, or a container never synced time. When you see not yet valid, check the clock first and the certificate second. That is unrelated to the monotonic-versus-system time split I covered in the clock piece.

The dangerous one: PROTOCOL_TLS verifies nothing

Everything above is a verification failure. This section is the absence of verification.

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
print(ctx.verify_mode, ctx.check_hostname)   # 0 False

verify_mode=0 is CERT_NONE. Point that context at the server that sends a leaf and trusts nothing, and the result is OK: handshake completes, response arrives, zero certificates checked. No warning, no exception.

The defaults side by side:

Constantverify_modecheck_hostname
PROTOCOL_TLS0 (CERT_NONE)False
PROTOCOL_TLS_CLIENT2 (CERT_REQUIRED)True
PROTOCOL_TLS_SERVER0 (CERT_NONE)False

PROTOCOL_TLS has been deprecated since 3.10 and emits a DeprecationWarning, but it is still what SSLContext() uses when you pass no protocol argument. The old line ssl.SSLContext(ssl.PROTOCOL_TLS) does not fail and does not reach your log. It simply stops verifying anything.

verify_mode and check_hostname are order sensitive

Turning verification off by hand will bite you on ordering. On a default context, the direct assignment is refused:

ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.

Set check_hostname to False first and the assignment goes through. Turn check_hostname back on afterwards and there is no error and no hint — verify_mode is silently raised back to 2:

c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
c.check_hostname = False
c.verify_mode = ssl.CERT_NONE     # 0
c.check_hostname = True           # no exception
print(c.verify_mode)              # 2

"Turn it off, then turn it back on" is not idempotent. You think you restored hostname checking and you restored full chain validation with it. If you build a relaxed context for tests, assert on both attributes afterwards.

cafile replaces, it does not add

create_default_context(cafile=…) loads only the file you name and drops the default trust set:

ssl.create_default_context().cert_store_stats()               # {'x509': 221, 'crl': 0, 'x509_ca': 219}
ssl.create_default_context(cafile="root.pem").cert_store_stats()  # {'x509': 1, 'crl': 0, 'x509_ca': 1}

That is a 99.5% drop in trusted certificates from one keyword argument. To append instead, call load_verify_locations() yourself:

ctx = ssl.create_default_context()
ctx.load_default_certs()
ctx.load_verify_locations("root.pem")
print(ctx.cert_store_stats()["x509"])   # 226

221 plus 1 gives 226 rather than 222 because the default path already contains duplicates that OpenSSL dedupes by subject. The exact number does not matter. What matters is that trusting one internal CA through cafile also throws away the 221 public ones, so the next external HTTPS call is the one that fails, and you will be debugging the internal certificate while looking at the wrong error.

requests routes its verify argument through the same logic. All three outcomes, measured:

[verify=False]        status 200  warning: InsecureRequestWarning
[verify=root.pem]     SSLError    (missing intermediate)
[verify=bundle.pem]   status 200

verify=False only emits a warning; the request succeeds. This is the same failure shape I described in the cache headers piece: a failure demoted to a notice, with exit code 0. In a batch job it is the worst possible form, because nothing ever turns red.

Where those 221 certificates come from

ssl.get_default_verify_paths() hands you a path under C:\Program Files\Common Files\SSL\cert.pem, and that file does not exist on this machine. Concluding "no default certificates" from that would be wrong:

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.cert_store_stats()["x509"]        # 0
ctx.load_default_certs()
ctx.cert_store_stats()["x509"]        # 221
len(ssl.enum_certificates("ROOT"))    # 226
len(ssl.enum_certificates("CA"))      # 33

The Python docs are explicit: "On Windows it loads CA certs from the CA and ROOT system stores." So the 221 come from the Windows certificate stores, not from that cert.pem path. And create_default_context() calls this loader whenever cafile, capath and cadata are all None, which is why the default context arrives with 221.

For comparison: the certifi bundle that requests depends on holds 146 certificates on this machine. Two trust sets, not the same set, and not guaranteed to stay in sync. Which one you want depends on which side you need to agree with.

Troubleshooting: six errors, six places to look

All six are written as error text, what it means, and where to look first, ordered by how often they show up in the field.

One, unable to get local issuer certificate

A chain problem, not a name problem. Count what the server actually sends: openssl s_client -connect host:443 -showcerts and count BEGIN CERTIFICATE lines. When my server sent two certificates (leaf plus intermediate), that same command reported Verify return code: 20 (unable to get local issuer certificate) — because it does not trust my local root by default. That is the point: the code is about reaching a trusted anchor, not about who you are.

Two, Hostname mismatch, certificate is not valid for 'xxx'

A name problem. Dump the SAN, not just the CN. Remember the wildcard covers one label only.

Three, certificate has expired

Read notAfter. Expired certificates are rejected during the handshake, so a packet capture shows only an alert.

Four, certificate is not yet valid

Read notBefore, then read the local clock. This is the one message that is usually not the certificate's fault.

Five, unsuitable certificate purpose

Read extendedKeyUsage. A certificate issued for client auth used as a server certificate has a valid signature and a valid chain, and still fails this check.

Six, [SSL: CERTIFICATE_VERIFY_FAILED] … (_ssl.c:1032) with no idea which check failed

Print verify_mode. If it is 0, skip the five above; nothing is being verified. This class of bug never appears in a log, only in the postmortem of "we rotated the certificate and nobody noticed".

Three commands before you read any code

Run these before opening the client source.

openssl s_client -connect example.com:443 -showcerts -servername example.com
openssl x509 -in leaf.pem -noout -subject -issuer -dates -ext subjectAltName
openssl verify -CAfile root.pem -untrusted inter.pem -verify_hostname example.com leaf.pem

The first shows what the server really sends, the second prints the four fields that matter on one certificate, the third validates chain and name locally without starting a service. Do not drop -servername; it decides which certificate the server hands you.

One more: ssl.match_hostname() no longer exists in 3.13 (hasattr(ssl, "match_hostname") is False here). The docs record that hostname matching moved into OpenSSL during the handshake as of 3.7, and the pure-Python implementation went with it. Plenty of "custom hostname check" snippets online still call it; on 3.12 and later they raise AttributeError immediately.

FAQ

Q: I installed the root into the system store. Why does Python still fail?

Because create_default_context(cafile=…) never reads the system store once you pass an argument. Either pass nothing, or append with load_verify_locations().

Q: Should the trust file hold the root or the intermediate?

The root, as the anchor. The intermediate is what connects the leaf to it. Holding both is the least fragile option, at the cost of updating the file whenever the intermediate rotates.

Q: Why does a request with verify=False still succeed?

Because at the TLS layer it drops verify_mode to CERT_NONE, which means "do not verify, keep going". requests emits InsecureRequestWarning and returns the status. The pip build artifact piece covers the same shape: the success signal decoupled from the real state.

Q: How do I make Python accept an internal self-signed certificate?

Pass the issuing CA as the anchor through cafile, and make sure the SAN contains the name you dial — an IP dial needs an IP SAN. CN-only passes in Python, but you still have browsers and other clients to satisfy.

Q: How is this different from a TCP connection failure?

With a TLS verification failure the TCP handshake already succeeded; the port is open. The liveness layer is covered in the TCP piece. Certificate errors all sit in the TLS handshake, one layer up.

What I did not test

This article contains no affiliate links and no product recommendations.

Whether a browser fetches a missing intermediate through AIA is not something I measured, and I have not treated it as a conclusion. Check browser and OS documentation for that call.

Revocation (CRL and OCSP) is not covered. Python's ssl does not check revocation by default; the relevant switches are VERIFY_CRL_CHECK_LEAF and OCSP stapling, and that deserves its own article.

The server-side half of mutual TLS — verifying a client certificate — is not covered either, and its error strings do not map one to one onto the client side described here. iOS and Android trust policies, roots pushed by enterprise MDM, and the effect of TLS 1.3 session resumption on verification are all outside this round as well.

👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference

👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation

📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews

🔗 Recommended Tools

These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:

As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.

☁️ DigitalOcean Cloud ⚡ Vultr VPS 🤖 QoderWork CN (Refer & Earn) ☁️ Aliyun AI Products 📚 WordPress Books 🧠 AI & LLM Books 🏗️ System Design Books 🐳 Docker & K8s Books 🐧 Linux Admin Books 🐍 Python Books 🗄️ Database Books 🚀 DevOps & SRE Books 🤖 Xiaomi MiMo Platform
← Back to Home