Build a three-level PKI with openssl, break it eight ways, time TLS 1.2 against 1.3, set up mutual TLS, and verify a certificate chain by hand.
TLS answers two questions before any application data flows: am I talking to the right server, and can anyone else read or change what we say? The second is mostly solved by modern cryptography and good defaults. The first is where real outages come from: expired certificates, missing intermediates, wrong hostnames, a trust store that doesn't include the right root, or a client clock set to 2019.
This article builds a private PKI with the openssl command line, serves deliberately broken certificates to a normal TLS client, times TLS 1.2 against TLS 1.3 on a 50 ms path, sets up mutual TLS between services, and verifies a certificate chain by hand. Everything ran on OpenSSL 3.0.13 and Python 3.12.
Thinking Like a Systems Engineer used a small Root CA in passing; What Happens When You Type a URL showed a real certificate chain. Here we take the machinery apart.
TLS combines three kinds of cryptography, each solving one problem:
| Problem | Tool | In TLS 1.3 |
|---|---|---|
| Agree on a secret key over a public network | Key exchange (Diffie-Hellman) | ECDHE, usually X25519; increasingly the post-quantum hybrid X25519MLKEM768 |
| Prove who you are | Digital signatures and certificates | ECDSA, RSA-PSS or Ed25519 signatures over the handshake |
| Encrypt and protect the data | Authenticated encryption (AEAD) | AES-GCM or ChaCha20-Poly1305 |
The key point most people miss: key exchange alone isn't secure. Diffie-Hellman gives two parties a shared secret, but it doesn't say who the other party is. An attacker in the middle can run one exchange with you and another with the server, and relay everything. Authentication is what stops that, and authentication is what certificates are for.
A certificate is a signed statement: "the public key K belongs to api.lab.test, valid from this date to that date, signed, Lab Issuing CA 1". Here's the one built for this article, with the important parts kept:
Certificate:
Data:
Version: 3 (0x2)
Signature Algorithm: ecdsa-with-SHA256
Issuer: O = Lab, CN = Lab Issuing CA 1
Validity
Not Before: Dec 1 18:48:29 2026 GMT
Not After : Mar 1 18:48:29 2027 GMT
Subject: CN = api.lab.test
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
NIST CURVE: P-256
X509v3 extensions:
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage: critical
Digital Signature
X509v3 Extended Key Usage:
TLS Web Server Authentication
X509v3 Subject Alternative Name:
DNS:api.lab.test, DNS:localhost, IP Address:127.0.0.1
X509v3 Subject Key Identifier:
D9:76:7D:D9:EB:60:44:16:AE:07:95:60:40:C8:33:50:8B:63:0D:73
X509v3 Authority Key Identifier:
5C:E7:44:7B:1F:B9:23:11:85:8F:56:8E:5D:D0:BD:E4:B8:C4:53:33
Signature Algorithm: ecdsa-with-SHA256
The fields that matter in practice:
CA:TRUE) and how many CA levels may sit below it (pathlen).Data section.Notice what's not in the certificate: the private key. The certificate is public; the server proves it owns the matching private key during the handshake, by signing the handshake transcript.
A realistic hierarchy has three levels: a root CA kept offline, an intermediate CA that issues day-to-day certificates, and the end-entity (leaf) certificates. If the intermediate's key leaks, you revoke the intermediate and issue a new one; the root, which is baked into every client's trust store, stays put.
#!/bin/sh
# A three-level PKI with the openssl CLI: root CA -> intermediate CA -> server and client certificates.
set -e
ecparam() { openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$1"; }
# 1. Root CA: self-signed, allowed to sign one more level of CA below it
ecparam root.key
openssl req -x509 -new -key root.key -sha256 -days 3650 -subj "/O=Lab/CN=Lab Root CA" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:1" \
-addext "keyUsage=critical,keyCertSign,cRLSign" -out root.pem
# 2. Intermediate CA, signed by the root, may only sign end-entity certificates
ecparam inter.key
openssl req -new -key inter.key -subj "/O=Lab/CN=Lab Issuing CA 1" -out inter.csr
openssl x509 -req -in inter.csr -CA root.pem -CAkey root.key -CAcreateserial -sha256 -days 1825 \
-extfile /dev/stdin -out inter.pem <<X
basicConstraints=critical,CA:TRUE,pathlen:0
keyUsage=critical,keyCertSign,cRLSign
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
X
# 3. Server certificate for api.lab.test, valid 90 days
ecparam server.key
openssl req -new -key server.key -subj "/CN=api.lab.test" -out server.csr
openssl x509 -req -in server.csr -CA inter.pem -CAkey inter.key -CAcreateserial -sha256 -days 90 \
-extfile /dev/stdin -out server.pem <<X
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
extendedKeyUsage=serverAuth
subjectAltName=DNS:api.lab.test,DNS:localhost,IP:127.0.0.1
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
X
# 4. Client certificate for mutual TLS: identity "service-a"
ecparam client.key
openssl req -new -key client.key -subj "/O=Lab/CN=service-a" -out client.csr
openssl x509 -req -in client.csr -CA inter.pem -CAkey inter.key -CAcreateserial -sha256 -days 30 \
-extfile /dev/stdin -out client.pem <<X
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
extendedKeyUsage=clientAuth
subjectAltName=URI:spiffe://lab.test/ns/default/sa/service-a
X
cat server.pem inter.pem > server-chain.pem
The output:
root subject=O = Lab, CN = Lab Root CA issuer=O = Lab, CN = Lab Root CA notAfter=Nov 28 18:48:29 2036 GMT
inter subject=O = Lab, CN = Lab Issuing CA 1 issuer=O = Lab, CN = Lab Root CA notAfter=Nov 30 18:48:29 2031 GMT
server subject=CN = api.lab.test issuer=O = Lab, CN = Lab Issuing CA 1 notAfter=Mar 1 18:48:29 2027 GMT
client subject=O = Lab, CN = service-a issuer=O = Lab, CN = Lab Issuing CA 1 notAfter=Dec 31 18:48:30 2026 GMT
The last line of the script matters: the server must send its own certificate followed by the intermediate. It should not send the root: the client must already have that, and a root sent by the server is ignored for trust anyway.
ECDSA P-256 keys are used throughout. They're much smaller and faster than RSA-2048 for the same security, and every current client supports them.
"Verifying a certificate" sounds mysterious. It's a short list of checks, and the cryptographic part is one function call per link:
"""What 'verifying a chain' means: check each signature with the issuer's public key, then the rules."""
import datetime as dt
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec
load = lambda p: x509.load_pem_x509_certificate(open(p, "rb").read())
leaf, inter, root = load("server.pem"), load("inter.pem"), load("root.pem")
def check_signature(cert, issuer):
issuer.public_key().verify(cert.signature, cert.tbs_certificate_bytes, ec.ECDSA(cert.signature_hash_algorithm))
for cert, issuer in ((leaf, inter), (inter, root), (root, root)):
check_signature(cert, issuer) # raises InvalidSignature if anything was altered
print(f"signature OK: '{cert.subject.rfc4514_string()}' was signed by '{issuer.subject.rfc4514_string()}'")
now = dt.datetime.now(dt.timezone.utc)
for c in (leaf, inter, root):
assert c.not_valid_before_utc <= now <= c.not_valid_after_utc
for c in (inter, root):
bc = c.extensions.get_extension_for_class(x509.BasicConstraints).value
print(f"'{c.subject.rfc4514_string()}' is a CA: {bc.ca}, path length limit: {bc.path_length}")
san = leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
print("leaf is valid for:", san.get_values_for_type(x509.DNSName))
# Flip one bit in the signed part of the leaf and verify again
tampered = bytearray(leaf.tbs_certificate_bytes); tampered[-40] ^= 1
try:
inter.public_key().verify(leaf.signature, bytes(tampered), ec.ECDSA(leaf.signature_hash_algorithm))
except Exception as e:
print("after flipping one bit:", type(e).__name__)
signature OK: 'CN=api.lab.test' was signed by 'CN=Lab Issuing CA 1,O=Lab'
signature OK: 'CN=Lab Issuing CA 1,O=Lab' was signed by 'CN=Lab Root CA,O=Lab'
signature OK: 'CN=Lab Root CA,O=Lab' was signed by 'CN=Lab Root CA,O=Lab'
'CN=Lab Issuing CA 1,O=Lab' is a CA: True, path length limit: 0
'CN=Lab Root CA,O=Lab' is a CA: True, path length limit: 1
leaf is valid for: ['api.lab.test', 'localhost']
after flipping one bit: InvalidSignature
The root's signature verifies with its own key: it's self-signed, which proves nothing about who owns it. A root is trusted only because it's in your trust store. That's the whole model: trust is anchored in a list of roots that someone chose (your OS vendor, your browser vendor, or you), and every other certificate earns trust by a chain of signatures back to one of them.
Don't write this code for production. Real validators also handle path building with cross-signed certificates, name constraints, policy constraints, critical extensions they don't understand, and revocation. Use your platform's verifier; this is to show what it does.
Pick a scenario and watch where validation stops. The certificates match the ones built above:
Real verifiers don't all check in exactly this order (OpenSSL checks the dates while it walks the chain, for example), but every one of these checks happens, and any failure aborts the handshake.
Each scenario from the widget, served for real. A Python TLS server presents the certificates; a normal client trusting only the lab root connects to api.lab.test:
good (leaf + intermediate) -> OK, TLSv1.3, TLS_AES_256_GCM_SHA384
leaf only, no intermediate -> FAIL: unable to get local issuer certificate
expired -> FAIL: certificate has expired
not yet valid -> FAIL: certificate is not yet valid
self-signed -> FAIL: self-signed certificate
wrong hostname -> FAIL: Hostname mismatch, certificate is not valid for 'api.lab.test'.
signed by a non-CA cert -> FAIL: invalid CA certificate
chains to an unknown root -> FAIL: unable to get local issuer certificate
Look at the second and last lines: a missing intermediate and an untrusted root produce the same error. Both mean "I couldn't build a path to anything I trust". When you see it, check both: does the server send its intermediate, and does this client trust the root?
The missing intermediate is the most common certificate bug in production, and it's sneaky: it often works in browsers. Chrome, Edge and Safari can download a missing intermediate using a URL in the leaf (the Authority Information Access extension), and Firefox ships a list of known intermediates. curl, Python, Java, Go and most other non-browser clients don't. The site works when you check it in your browser and fails from every service that calls it.
The same checks from the command line:
openssl verify -CAfile root.pem -untrusted inter.pem server.pem # OK
openssl verify -CAfile root.pem server.pem # no intermediate
openssl verify -CAfile inter.pem server.pem # trusting only the intermediate
openssl verify -CAfile root.pem -untrusted inter.pem -verify_hostname evil.lab.test server.pem
openssl verify -CAfile root.pem -untrusted inter.pem -purpose sslserver client.pem
server.pem: OK
error 20 at 0 depth lookup: unable to get local issuer certificate
error 2 at 1 depth lookup: unable to get issuer certificate
error 62 at 0 depth lookup: hostname mismatch
error 26 at 0 depth lookup: unsupported certificate purpose
The third result surprises people. Trusting only the intermediate isn't enough by default: OpenSSL keeps walking up and fails when it can't find the root. To anchor trust at an intermediate (sometimes done for internal CAs), you need -partial_chain, or X509_V_FLAG_PARTIAL_CHAIN in code.
TLS 1.3 (2018) took a round-trip out of the handshake. On a path with 50 ms of round-trip time, here's when the client sees each handshake message:
TLS 1.3 handshake messages seen by the client:
50.5 ms client → server CLIENT_HELLO
101.3 ms server → client SERVER_HELLO
101.7 ms server → client ENCRYPTED_EXTENSIONS
101.7 ms server → client CERTIFICATE
102.6 ms server → client CERTIFICATE_VERIFY
102.7 ms server → client FINISHED
102.7 ms client → server FINISHED
153.9 ms server → client NEWSESSION_TICKET
153.9 ms server → client NEWSESSION_TICKET
TLS 1.2 handshake messages seen by the client:
50.5 ms client → server CLIENT_HELLO
101.1 ms server → client SERVER_HELLO
101.2 ms server → client CERTIFICATE
101.9 ms server → client SERVER_KEY_EXCHANGE
102.1 ms server → client SERVER_DONE
102.2 ms client → server CLIENT_KEY_EXCHANGE
102.2 ms client → server FINISHED
152.9 ms server → client NEWSESSION_TICKET
153.0 ms server → client FINISHED
(The first 50 ms is the TCP handshake.) In TLS 1.3 the client sends its key share in the very first message, guessing which group the server will pick. The server answers with its own share and can encrypt everything after SERVER_HELLO straight away, including the certificate. After one round-trip the client is done and can send its request with its FINISHED.
In TLS 1.2 the client must wait for the server's FINISHED at 153 ms before it can send application data: two round-trips. And the certificate travels in the clear, so anyone watching can see which site you visited (the hostname also leaks in the SNI field of CLIENT_HELLO in both versions; Encrypted Client Hello is the fix being deployed now).
Total time to the first response byte, with TCP_NODELAY on both sides:
TLS 1.2 full : TCP 51.6 ms | TLS handshake 104.1 ms | first response after 207.9 ms
TLS 1.2 resumed : TCP 53.9 ms | TLS handshake 52.9 ms | first response after 157.6 ms | reused=True
TLS 1.3 full : TCP 50.3 ms | TLS handshake 52.0 ms | first response after 152.9 ms
TLS 1.3 resumed : TCP 50.3 ms | TLS handshake 51.2 ms | first response after 152.2 ms | reused=True
That's four round-trips for TLS 1.2 (TCP, two for TLS, the request) and three for TLS 1.3. On a 150 ms transatlantic path, TLS 1.3 saves 150 ms on every new connection.
Without TCP_NODELAY, the first run of this test showed TLS 1.3 taking 294 ms: the session tickets and the response were held back by Nagle's algorithm and delayed ACKs, the exact 40 ms trap from TCP/IP from First Principles. Layers interact.
After a handshake the server sends session tickets (the NEWSESSION_TICKET messages above). A client that reconnects can present one and skip authentication. In TLS 1.2 that also cuts a round-trip, as the table shows. In TLS 1.3 the full handshake is already one round-trip, so resumption doesn't save time on the wire, but it does save CPU. Measured over 300 handshakes on loopback, with client and server in one process:
TLSv1_2 full : 1.27 ms per connection, 1.29 ms CPU (client + server, both in this process)
TLSv1_2 resumed : 0.45 ms per connection, 0.51 ms CPU (client + server, both in this process)
TLSv1_3 full : 1.33 ms per connection, 1.41 ms CPU (client + server, both in this process)
TLSv1_3 resumed : 0.76 ms per connection, 0.86 ms CPU (client + server, both in this process)
TLS 1.3 resumption saves less than TLS 1.2's because it still does a fresh ECDHE key exchange by default. That's deliberate: it keeps forward secrecy, so a stolen ticket key can't decrypt recorded past sessions. What it skips is the certificate signature and chain verification.
A millisecond of CPU per handshake sounds tiny until you multiply it. Even if the server's share is only half of the 1.4 ms measured here, a service accepting 5,000 new TLS connections per second spends three or four CPU cores on handshakes alone. That's why load balancers terminate TLS, why connection pooling matters between services, and why the estimation of a high-traffic system should count handshakes, not just requests.
TLS 1.3 also has 0-RTT early data: a resuming client sends its request with its very first message. It saves a round-trip, but an attacker can replay that early data, so servers should only accept it for idempotent requests like GET, or not at all.
Normally only the server proves its identity. With mutual TLS (mTLS) the server also asks for a client certificate, and the client proves it owns the matching key. It's the standard way for services to authenticate each other inside a platform: Istio, Linkerd and Consul do it for every service-to-service call, and the identity is often a SPIFFE ID in the URI SAN, like the client certificate built above.
The server needs two lines more than usual:
sctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
sctx.load_cert_chain("server-chain.pem", "server.key")
sctx.load_verify_locations("root.pem") # which CA may issue client certificates
sctx.verify_mode = ssl.CERT_REQUIRED # no certificate, no connection
Four clients try to connect:
1. client presents service-a certificate with its intermediate
server: verified client CN=service-a SAN=['spiffe://lab.test/ns/default/sa/service-a']
client: got b'hello service-a'
2. client presents only its leaf certificate
client: SSLError: TLSV1_ALERT_UNKNOWN_CA
server: rejected handshake: CERTIFICATE_VERIFY_FAILED
3. client presents no certificate
client: SSLError: TLSV13_ALERT_CERTIFICATE_REQUIRED
server: rejected handshake: PEER_DID_NOT_RETURN_A_CERTIFICATE
4. client presents a server certificate (wrong extended key usage)
client: SSLError: SSLV3_ALERT_UNSUPPORTED_CERTIFICATE
server: rejected handshake: CERTIFICATE_VERIFY_FAILED
UNKNOWN_CA, CERTIFICATE_REQUIRED). The detailed reason is in the server's logs. When debugging mTLS, always look at the side doing the verifying.wrap_socket call can succeed before the server has checked the client certificate; the failure shows up on the first read. Code that treats a completed handshake as proof of acceptance gets this wrong.service-a may call this endpoint. That's the same split as authentication and authorisation in OAuth 2.0 and OIDC.What happens when a private key leaks? The CA can revoke the certificate, but clients have to find out:
The industry is moving away from OCSP. Let's Encrypt, the largest CA, removed OCSP URLs from its certificates in May 2025 and shut its OCSP responders down in August 2025, keeping CRLs only. Browsers mostly use their own compressed revocation feeds instead (Chrome's CRLSets, Firefox's CRLite).
The bigger answer to revocation is short lifetimes: a certificate that expires soon needs revoking less. The CA/Browser Forum's ballot SC-081 limits public TLS certificates to 200 days from March 15, 2026, 100 days from March 15, 2027, and 47 days from March 15, 2029. Manual renewal stops being viable; automation with ACME (Let's Encrypt, cert-manager, Caddy, certbot) becomes required. #0012 sets up cert-manager on Kubernetes.
Certificate Transparency (CT) makes mis-issuance visible. Every publicly trusted certificate must be logged in public, append-only CT logs, and browsers reject certificates without proof of logging. You can search the logs for your domains (for example at crt.sh) and get alerts when anyone, including a misbehaving CA, issues a certificate for them. Private CAs like the lab one don't log to CT.
For internal services you'll usually run your own CA: cert-manager with a CA issuer, HashiCorp Vault's PKI engine, AWS Private CA, or a service mesh's built-in CA. The hard part isn't issuing certificates; it's distributing the root to every client that needs to trust it.
Every runtime has its own idea of where the trust store is:
| Client | Default trust store |
|---|---|
curl, wget, Python ssl, Go |
The operating system's bundle (/etc/ssl/certs on Debian and Ubuntu) |
Python requests |
The certifi package's bundle, not the OS store, unless told otherwise |
| Java | The JDK's cacerts keystore |
| Node.js | A bundle compiled into Node (or the OS store with --use-system-ca on recent versions) |
| Browsers | The browser vendor's root program, or the OS store |
This is why "it works with curl but not from my Python service" is common behind a corporate TLS-inspecting proxy: the proxy's root was added to the OS store, but requests uses certifi. Point it at the right bundle (REQUESTS_CA_BUNDLE, or verify= per call) rather than turning verification off.
Never "fix" a certificate error with verify=False, -k or InsecureSkipVerify: true in anything that ships. It turns off the authentication half of TLS: the connection is still encrypted, but to whoever answered.
Most TLS failures are one of a handful. The commands:
# What does the server actually send? (-servername sets SNI; without it you may get a default cert)
openssl s_client -connect api.example.com:443 -servername api.example.com -showcerts </dev/null
# Just the leaf's names and dates
openssl s_client -connect api.example.com:443 -servername api.example.com </dev/null 2>/dev/null \
| openssl x509 -noout -subject -issuer -dates -ext subjectAltName
# Does the chain verify against a given root?
openssl verify -CAfile root.pem -untrusted chain.pem leaf.pem
# Verbose handshake from curl, using a custom CA
curl -v --cacert root.pem https://api.example.com/
# Does a key match a certificate? The two hashes must be equal.
openssl x509 -in cert.pem -noout -pubkey | openssl sha256
openssl pkey -in key.pem -pubout | openssl sha256
And the error-to-cause table:
| Error | Usual cause |
|---|---|
unable to get local issuer certificate |
Server doesn't send its intermediate, or the client doesn't trust the root |
certificate has expired |
Renewal failed, or a renewed certificate wasn't reloaded by the server |
certificate is not yet valid |
Client clock wrong (common on fresh VMs and IoT devices) or a just-issued cert and clock skew |
Hostname mismatch |
Name missing from SAN; connecting by IP or an internal alias; wrong SNI |
self-signed certificate in certificate chain |
A private CA the client doesn't trust, often a TLS-inspecting proxy |
unsupported certificate purpose |
Wrong Extended Key Usage, such as a client certificate used on a server |
alert unknown ca (on the client) |
In mTLS, the server doesn't trust your client certificate's issuer |
alert certificate required |
In mTLS, the client didn't send a certificate |
wrong version number |
Speaking TLS to a plain HTTP port, or the other way round |
And three operational rules: