TLS in Practice: Handshake on the Wire, Certificates & Chains, SNI/ALPN, mkcert, openssl s_client, Certs in Docker & Kubernetes
"If sslmode is set to verify-full, libpq will also verify that the server host name matches the name stored in the server certificate." — PostgreSQL documentation, Secure TCP/IP Connections with SSL
Summary: TLS gives a connection three things (a private channel, tamper detection, and proof of who the server is); in practice every failure you meet is about the third one, certificates and trust. Focus: The TLS 1.3 and 1.2 handshakes as real records, X.509 certificates and chains, SNI and ALPN, trust stores, Let's Encrypt, mkcert, openssl s_client, and where certificates live in Docker and Kubernetes. Learning goal: Read a handshake and a certificate, name the exact reason a connection fails, and fix it in Go, PHP/Laravel, Docker and Kubernetes without ever reaching for -k.
This chapter is the wire and the operator view of TLS: what the bytes look like, what the certificate files contain, and which command tells you what is wrong. The primitives underneath (AES-GCM, X25519, signatures, HKDF) are in Cryptography Fundamentals; password storage and token signing are in Password Hashing & Signed Tokens. PKI design (who runs the CA, key ceremonies, secret storage) belongs to Cryptography, TLS, PKI & Secrets, and mutual TLS between services to mTLS & Service Security. For the Go server and client API in depth see HTTP/2, HTTPS, TLS & mTLS in Go; for how a connection gets to the server in the first place, Network Models, DNS Resolution, Ports, Sockets & Connections, Docker Networking, Kubernetes Networking and the Network Troubleshooting Playbook. Database encryption layers are in Encryption at Rest, in Transit & in Use.
All outputs below were produced on 2026-11-25 on macOS with Homebrew OpenSSL 3.6.4 (the system /usr/bin/openssl is LibreSSL and prints different text), Go 1.27.4, curl 8.7.1 (LibreSSL 3.3.6) on the host, and containers on Docker Desktop. Where a result depends on the platform, the tool and platform are named.
Page map
| If you are looking for | Go to |
|---|---|
| The whole handshake in one table, and an error-to-cause table | Everything in one minute |
| What TLS promises and what it does not | Why TLS exists |
| SSL 3.0 to TLS 1.3, RFC numbers, deprecations | Where it comes from |
| TLS 1.3 handshake record by record | The TLS 1.3 handshake |
| ClientHello fields: SNI, ALPN, key_share, cipher suites, with a hex dump | Inside the ClientHello |
| What changed from TLS 1.2 and why it is deprecated | TLS 1.2 and why 1.3 replaced it |
TLS_AES_128_GCM_SHA256 vs TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | Cipher suite names |
| Tickets, PSK, 0-RTT | Session resumption and 0-RTT |
Certificate fields, PEM vs DER, openssl x509 -text | X.509 certificates decoded |
| Leaf, intermediate, root; missing intermediates; AIA; bundle order | Chains |
| OS, browser, Go, PHP/cURL, Docker image trust stores | Trust stores |
| SAN vs CN, wildcards, IP addresses | Hostname verification |
| Self-signed vs private CA vs public CA | Kinds of CA |
| ACME, HTTP-01, DNS-01, TLS-ALPN-01, rate limits, 90 days | Let's Encrypt and ACME |
| Trusted HTTPS on your laptop | mkcert |
| HSTS, OCSP stapling, Certificate Transparency | HSTS, OCSP stapling, CT |
| Who sees what at the load balancer, proxy and app | Where TLS terminates |
s_client, curl -v, -k, Wireshark, the error table | Mechanics: tools, knobs and errors |
| Certificates in Compose and Dockerfiles | TLS in Docker |
| Secrets, cert-manager, Ingress, Gateway API | TLS in Kubernetes |
Go crypto/tls and Laravel/PHP code for each fix | Solving the classic problems |
| Which option for which situation | Choosing |
| Monolith to microservices to many regions | In architecture |
| Reproduce everything on your machine | Lab |
| Wrong beliefs, cheat sheet, questions, terms, sources | Misconceptions, Cheat sheet, Self-check, Glossary, References |
Everything in one minute
The TLS 1.3 handshake, one row per message (details in the handshake).
| # | Message | From | What it carries | Encrypted? |
|---|---|---|---|---|
| 1 | ClientHello | client | SNI, ALPN list, supported versions, cipher suites, signature algorithms, key_share (an X25519 public key) | No |
| 2 | ServerHello | server | Chosen cipher suite, server key_share | No |
| 3 | EncryptedExtensions | server | ALPN result and other extensions | Yes (handshake keys) |
| 4 | Certificate | server | Leaf plus intermediates | Yes |
| 5 | CertificateVerify | server | Signature over the handshake transcript, proving the server holds the private key | Yes |
| 6 | Finished | server | MAC over the transcript | Yes |
| 7 | Finished | client | MAC over the transcript; application data may follow | Yes |
| 8 | NewSessionTicket | server | A resumption ticket (PSK) for next time | Yes |
Which file is which.
| File / extension | Usually contains | Secret? | Command to look |
|---|---|---|---|
.pem, .crt, .cer | One or more certificates in PEM text (-----BEGIN CERTIFICATE-----) | No | openssl x509 -in f.pem -noout -text |
.key, -key.pem | A private key (PKCS#8 BEGIN PRIVATE KEY or BEGIN EC PRIVATE KEY) | Yes, guard it | openssl pkey -in f.key -noout -text |
.csr | Certificate signing request: public key plus the names you want | No | openssl req -in f.csr -noout -text |
.der | Binary ASN.1 form of one certificate | No | openssl x509 -inform DER -in f.der -noout -text |
.p12, .pfx | PKCS#12: certificate, key and chain in one password-protected file | Yes | openssl pkcs12 -in f.p12 -info -noout |
fullchain.pem | Leaf first, then intermediates (what servers should send) | No | grep -c BEGIN fullchain.pem |
ca-certificates.crt | Many roots concatenated (a trust store as one file) | No | awk '/BEGIN/{n++} END{print n}' |
Symptom to first command (full table in the error table).
| What you see | Almost always means | First command |
|---|---|---|
x509: certificate signed by unknown authority | Client does not trust the root, or the server omitted the intermediate | openssl s_client -connect h:443 -servername h -showcerts |
x509: certificate is valid for a.test, not b.test | Name in the URL is not in the SAN list | openssl x509 -noout -ext subjectAltName |
certificate has expired | Renewal job failed | openssl x509 -noout -dates |
SSL_ERROR_SYSCALL, unexpected eof | Server closed during the handshake (wrong port, plaintext port, ALPN or version mismatch) | openssl s_client -connect h:p -msg |
| Default certificate for the wrong site | Client sent no SNI, or the server does not route by SNI | openssl s_client -servername wanted.example |
Why TLS exists
TCP delivers bytes in order, but everyone on the path can read and rewrite them: Wi-Fi, the ISP, the corporate proxy, the cloud load balancer, a compromised router. TLS wraps the TCP stream so that the two ends get a confidential, tamper-evident channel with an authenticated server (and, optionally, an authenticated client). RFC 8446 lists exactly these properties: authentication (server always, client optionally), confidentiality, and integrity. It does not hide who you talk to (the IP address is visible, and the SNI is visible unless Encrypted Client Hello is used) or how much data you send.
| Without TLS | With TLS |
|---|---|
| Anyone on the path reads passwords and cookies | Only the endpoints read the data |
| Anyone can inject ads, scripts or redirects | Modification is detected and the connection is dropped |
| You cannot tell the real server from an impostor | The server proves it owns a certificate your client trusts for that name |
| Zero setup | Certificates to issue, renew, distribute and trust |
| No handshake latency | One round trip (TLS 1.3), cheaper on resumption |
The analogy we reuse on this page: a sealed courier with a passport office. The courier (the TLS record layer) carries sealed envelopes, and the seal breaks if someone opens one. Before any envelope moves, the courier shows a passport (the certificate) issued by an office (the CA) that you already know. The passport lists the name it is valid for (SAN), when it was issued and until when (validity), and what it may be used for (key usage). A courier with a perfect seal and a forged passport is still delivering to the wrong house.
Three common misunderstandings, up front
- “HTTPS means the site is safe.” It means the connection to that name is private and untampered. A phishing site can have a perfectly valid certificate for its own name.
- “The padlock error means the encryption is broken.” Nearly every TLS error is a trust or naming error (unknown CA, wrong name, expired date, missing intermediate). The cipher is almost never the problem.
- “
-k/verify=falseis just for testing, so it is harmless.” It turns an authenticated channel into an encrypted channel to an unknown party. It also tends to ship to production in the same commit.
Where it comes from
| Year | Version / document | What changed |
|---|---|---|
| 1990s | SSL 2.0, SSL 3.0 (Netscape) | First widely deployed secure sockets; both are long broken and prohibited |
| 1999 | TLS 1.0 (RFC 2246) | IETF standardisation of SSL 3.0 |
| 2006 | TLS 1.1 (RFC 4346) | Fixes for CBC attacks |
| 2008 | TLS 1.2 (RFC 5246, August 2008) | AEAD suites, SHA-2, signature algorithm negotiation; the workhorse for a decade |
| 2018 | TLS 1.3 (RFC 8446, August 2018) | Obsoletes RFC 5246; 1-RTT, forward secrecy always, encrypted handshake, 0-RTT option |
| 2021 | RFC 8996 (March 2021) | Formally deprecates TLS 1.0 and 1.1: "TLS 1.0 MUST NOT be used." |
| 2022 | RFC 9325 (November 2022, BCP 195) | Current recommendations: TLS 1.2 and 1.3 only, no static RSA key transport |
| 2024 onward | Hybrid post-quantum key exchange (X25519MLKEM768) | Go's crypto/tls offers it by default from Go 1.24; OpenSSL 3.6 negotiated it in our lab |
The certificate side has its own standards: X.509 and the Internet PKI profile in RFC 5280 (May 2008), hostname matching in RFC 6125 (March 2011), Server Name Indication in RFC 6066 (January 2011), ALPN in RFC 7301 (July 2014), Certificate Transparency in RFC 9162 (December 2021), and the ACME protocol in RFC 8555 (March 2019) with the TLS-ALPN-01 challenge in RFC 8737 (February 2020). PEM textual encoding is RFC 7468.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, the precise definition, a sequence you can compare with a real capture, scenarios, a per-product table, and the fix with Go and PHP/Laravel code in Solving the classic problems.
The TLS 1.3 handshake, record by record Must-know
In plain words: the client says what it can do and sends half of a key agreement; the server answers with its half and a chosen suite; from that moment both can derive keys, so everything else (including the certificate) travels encrypted; the server proves its identity with a signature, both sides confirm with a MAC, and data flows after one round trip.
Common misunderstanding: “TLS first sends the certificate, then agrees on a key.” In TLS 1.3 the key agreement happens in the first flight (key_share in both hellos), and the certificate is sent afterwards, encrypted. A passive observer sees the SNI and the sizes, not the certificate. (In TLS 1.2 the certificate is sent in clear.)
Definition: a TLS 1.3 full handshake is ClientHello, ServerHello, EncryptedExtensions, Certificate, CertificateVerify, Finished (server), Finished (client), carried in TLS records. RFC 8446 section 1.2 lists the differences from 1.2: all handshake messages after the ServerHello are encrypted, static RSA and static Diffie-Hellman are gone so all key exchange gives forward secrecy, and ChangeCipherSpec survives only for middlebox compatibility.
# Client Server
1 ClientHello ───────────────────────────────▶ (SNI=a.test, ALPN=h2,http/1.1,
supported_versions=1.3, key_share=X25519)
2 ◀─────────────────────────────── ServerHello (cipher=TLS_AES_128_GCM_SHA256, key_share)
both derive handshake traffic keys (HKDF)
3 ◀─────────────────────────────── {EncryptedExtensions} ALPN result
4 ◀─────────────────────────────── {Certificate} leaf + intermediate
5 ◀─────────────────────────────── {CertificateVerify} signature over transcript
6 ◀─────────────────────────────── {Finished}
7 {Finished} ───────────────────────────────▶ client verified chain, name, signature first
8 [application data] ◀──────────────────────────▶ [application data]
9 ◀─────────────────────────────── [NewSessionTicket] for resumption
{ } = encrypted with handshake keys [ ] = encrypted with application keysThe real thing, captured with openssl s_client -msg against the Go server of the lab (Homebrew OpenSSL 3.6.4, macOS; lines trimmed to the handshake records):
>>> TLS 1.3, Handshake [length 00e1], ClientHello
<<< TLS 1.3, Handshake [length 007a], ServerHello
<<< TLS 1.3, ChangeCipherSpec [length 0001] <- compatibility only, carries one byte: 01
<<< TLS 1.3, Handshake [length 000a], EncryptedExtensions
<<< TLS 1.3, Handshake [length 03cc], Certificate <- 972 bytes: leaf + intermediate
<<< TLS 1.3, Handshake [length 004f], CertificateVerify
<<< TLS 1.3, Handshake [length 0024], Finished
>>> TLS 1.3, ChangeCipherSpec [length 0001]
>>> TLS 1.3, Handshake [length 0024], Finished
<<< TLS 1.3, Handshake [length 007a], NewSessionTicket
>>> TLS 1.3, Alert [length 0002], warning close_notifyThe ServerHello in hex (the same capture; 02 is the handshake type, 00 00 76 the length, 03 03 the legacy version, then 32 bytes of random, a 32-byte echoed session id, 13 01 the suite, extensions 00 2b 00 02 03 04 supported_versions=1.3 and 00 33 00 24 00 1d 00 20 ... a 32-byte X25519 key_share):
02 00 00 76 03 03 65 0d c2 1e 81 6c 65 ff 7a 2b 8f 90 51 a0 1b 59 31 83 d3 4c 4a 3b 18 a0 f6 27
74 1c 51 20 9a e2 20 fc 40 3c ca dc d0 5e 12 0b dd e3 ea 30 3d 28 7a 38 b0 04 c3 cc 8a 34 b7 af
1d 54 5a 30 d7 3f e9 13 01 00 00 2e 00 2b 00 02 03 04 00 33 00 24 00 1d 00 20 f1 a4 bb 48 fd 9a
4a 43 63 bf 29 b6 b0 0d cf 56 3b 43 ac 90 1c 82 eb 9f c2 42 06 6f 7f b8 54 1eReal scenarios: (1) a mobile app on a high-latency link: TLS 1.3 saves one round trip per new connection versus 1.2. (2) A corporate middlebox that drops "unknown" records breaks handshakes; the compatibility ChangeCipherSpec and the 32-byte session id exist because of such boxes. (3) A packet capture of a TLS 1.3 site shows no certificate, which surprises people who used to read it in Wireshark. (4) Latency budgets: DNS + TCP (1 RTT) + TLS 1.3 (1 RTT) before the first HTTP byte.
| Client / server | TLS 1.3 support | Notes |
|---|---|---|
| OpenSSL | 1.1.1 and later | -tls1_3, -ciphersuites for 1.3 suites, -cipher for 1.2 |
LibreSSL (macOS /usr/bin/openssl) | 3.2 and later | Output format differs from OpenSSL 3 |
Go crypto/tls | On by default since Go 1.13 | The 1.3 suites are not configurable |
| PHP (openssl extension, streams) | Follows the linked OpenSSL | Needs OpenSSL 1.1.1+ |
| curl | With a TLS 1.3 capable backend | --tlsv1.3, --tls-max 1.2 |
| nginx, Caddy, Traefik, Envoy, HAProxy | Yes in current releases | Caddy and Traefik default to 1.2+ |
Fix / how to use it: you rarely “use” the handshake; you observe it. openssl s_client -connect host:443 -servername host -tls1_3 -msg shows the records, curl -v shows the same stages in words, and the Go tlsdial tool prints what was negotiated.
Inside the ClientHello: SNI, ALPN, key_share, cipher suites Must-know
In plain words: the first message is plaintext and tells the server which hostname the client wants (SNI), which application protocol it wants to speak (ALPN), which TLS versions and suites it supports, and carries the client's half of the key agreement.
Common misunderstanding: “The server knows the hostname from the HTTP Host header.” That header is inside the encrypted stream; the server needs the name before it can choose a certificate. That is the job of Server Name Indication (RFC 6066): without SNI, one IP address can only present one certificate (the default one).
Definition: the ClientHello is a handshake message (type 1) with a legacy version field, 32 bytes of random, a session id, a list of cipher suites, compression methods (null only) and a list of extensions, each type(2) length(2) data. The record that carries it has a 5-byte header: content type 22 (handshake), a legacy version, and a 2-byte length.
// Command clienthello shows what a TLS client sends first.
// It listens on a local TCP port, lets a real crypto/tls client connect,
// reads the first TLS record WITHOUT answering, and decodes it byte by byte.
package main
import (
"context"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"net"
"os"
"time"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer ln.Close()
// The "client" is a normal Go TLS client; it sends a ClientHello and then waits.
go func() {
cfg := &tls.Config{ServerName: "example.test", NextProtos: []string{"h2", "http/1.1"}}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
d := tls.Dialer{Config: cfg}
_, _ = d.DialContext(ctx, "tcp", ln.Addr().String()) // times out, which is fine
}()
conn, err := ln.Accept()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer conn.Close()
hdr := make([]byte, 5)
if _, err := io.ReadFull(conn, hdr); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
n := int(binary.BigEndian.Uint16(hdr[3:5]))
body := make([]byte, n)
if _, err := io.ReadFull(conn, body); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("record header : %s (type=%d handshake, legacy_version=0x%04x, length=%d)\n",
hex.EncodeToString(hdr), hdr[0], binary.BigEndian.Uint16(hdr[1:3]), n)
decodeClientHello(body)
}
// reader is a tiny cursor over a byte slice.
type reader struct {
b []byte
p int
}
func (r *reader) u8() int { v := int(r.b[r.p]); r.p++; return v }
func (r *reader) u16() int { v := int(binary.BigEndian.Uint16(r.b[r.p:])); r.p += 2; return v }
func (r *reader) u24() int {
v := int(r.b[r.p])<<16 | int(r.b[r.p+1])<<8 | int(r.b[r.p+2])
r.p += 3
return v
}
func (r *reader) take(n int) []byte { v := r.b[r.p : r.p+n]; r.p += n; return v }
func decodeClientHello(b []byte) {
r := &reader{b: b}
fmt.Printf("handshake type: %d (1 = client_hello)\n", r.u8())
fmt.Printf("handshake len : %d\n", r.u24())
fmt.Printf("legacy_version: 0x%04x (TLS 1.3 clients still write 0x0303 here)\n", r.u16())
fmt.Printf("random : %s\n", hex.EncodeToString(r.take(32)))
sid := r.take(r.u8())
fmt.Printf("session_id : %d bytes (TLS 1.3 clients send 32 random bytes for middlebox compatibility)\n", len(sid))
suites := r.take(r.u16())
fmt.Printf("cipher_suites : %d suites\n", len(suites)/2)
for i := 0; i+1 < len(suites); i += 2 {
id := binary.BigEndian.Uint16(suites[i:])
fmt.Printf(" 0x%04x %s\n", id, tls.CipherSuiteName(id))
}
fmt.Printf("compression : %x (null only)\n", r.take(r.u8()))
ext := &reader{b: r.take(r.u16())}
fmt.Println("extensions :")
for ext.p < len(ext.b) {
typ := ext.u16()
data := ext.take(ext.u16())
fmt.Printf(" type %-5d %-24s %3d bytes %s\n", typ, extName(typ), len(data), extDetail(typ, data))
}
}
func extName(t int) string {
names := map[int]string{
0: "server_name (SNI)", 10: "supported_groups", 11: "ec_point_formats",
13: "signature_algorithms", 16: "ALPN", 43: "supported_versions",
45: "psk_key_exchange_modes", 51: "key_share", 65281: "renegotiation_info",
5: "status_request (OCSP)", 18: "signed_cert_timestamp", 23: "extended_master_secret",
50: "signature_algs_cert",
}
if n, ok := names[t]; ok {
return n
}
return "other"
}
func extDetail(t int, d []byte) string {
r := &reader{b: d}
switch t {
case 0: // server_name_list length, name type, name length, name
r.u16()
r.u8()
return fmt.Sprintf("host_name=%q", r.take(r.u16()))
case 16: // ALPN: list length, then length-prefixed protocol names
end := r.u16() + 2
out := ""
for r.p < end {
out += fmt.Sprintf("%q ", r.take(r.u8()))
}
return out
case 43: // supported_versions in a ClientHello: 1-byte list length
end := r.u8() + 1
out := ""
for r.p < end {
out += fmt.Sprintf("0x%04x ", r.u16())
}
return out
case 51: // key_share: list length, then group + length-prefixed key
end := r.u16() + 2
out := ""
for r.p < end {
g := r.u16()
k := r.take(r.u16())
out += fmt.Sprintf("group=0x%04x keylen=%d ", g, len(k))
}
return out
}
return ""
}Our clienthello tool (Go, above) starts a TCP listener, lets a normal Go TLS client connect with ServerName: "example.test" and NextProtos: h2, http/1.1, reads the first record without answering, and decodes it. Real output (Go 1.27.4, macOS; random trimmed):
record header : 16030105f3 (type=22 handshake, legacy_version=0x0301, length=1523)
handshake type: 1 (1 = client_hello)
handshake len : 1519
legacy_version: 0x0303 (TLS 1.3 clients still write 0x0303 here)
random : 5dbb2f48d1797658...5606fea2b38e40a2 (trimmed; different on every run)
session_id : 32 bytes (TLS 1.3 clients send 32 random bytes for middlebox compatibility)
cipher_suites : 13 suites
0xc02b TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
0xc02f TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
... (8 more TLS 1.2 suites: ECDHE only, AES-GCM and ChaCha20 first, then CBC)
0x1301 TLS_AES_128_GCM_SHA256
0x1302 TLS_AES_256_GCM_SHA384
0x1303 TLS_CHACHA20_POLY1305_SHA256
compression : 00 (null only)
extensions :
type 0 server_name (SNI) 17 bytes host_name="example.test"
type 11 ec_point_formats 2 bytes
type 65281 renegotiation_info 1 bytes
type 23 extended_master_secret 0 bytes
type 18 signed_cert_timestamp 0 bytes
type 5 status_request (OCSP) 5 bytes
type 10 supported_groups 12 bytes
type 13 signature_algorithms 32 bytes
type 50 signature_algs_cert 26 bytes
type 16 ALPN 14 bytes "h2" "http/1.1"
type 43 supported_versions 5 bytes 0x0304 0x0303
type 51 key_share 1258 bytes group=0x11ec keylen=1216 group=0x001d keylen=32Read it like this. The record is 1,523 bytes, far over the 300 bytes of a classic ClientHello, because Go 1.24 and later offers the hybrid group X25519MLKEM768 (0x11ec, a 1,216-byte public value) and plain X25519 (0x001d, 32 bytes). The OpenSSL capture in the previous block used -curves X25519 and produced a 225-byte ClientHello, with SNI as 00 00 00 0b 00 09 00 00 06 61 2e 74 65 73 74 (extension 0, length 11, list length 9, type host_name 0, name length 6, then a.test), 00 2b 00 03 02 03 04 (supported_versions, one entry 0x0304) and 00 33 00 26 00 24 00 1d 00 20 ... (key_share, group X25519, 32-byte key).
ClientHello (OpenSSL 3.6.4, -curves X25519, first 64 bytes)
01 00 00 dd 03 03 40 0b cf 76 56 cc 9c c5 c6 e5 67 a7 f8 47 f5 78 e9 66 2d 63 bd 7f c2 1c 53 1d
db 30 3d 96 22 14 20 6f c7 83 d0 a1 88 3e 5c 5b 9e 16 89 0d ba 20 42 54 a9 8e b4 e7 06 e2 69 95
| | | |-- 32 bytes random ... 20 = session id length (32) ...
| | legacy_version 03 03
| length 0x0000dd = 221 bytes
handshake type 01 = client_helloA large ClientHello has a side effect: it can exceed one TCP segment or a path MTU limit, and some old middleboxes mishandle the split (see Network Troubleshooting Playbook).
| Field | What it decides | Seen by the network? | What breaks when wrong |
|---|---|---|---|
SNI (server_name, ext 0) | Which certificate and which virtual host | Yes (plaintext), unless Encrypted Client Hello is used | Missing: the default certificate is served, a hostname-mismatch error follows |
| ALPN (ext 16) | Application protocol: h2, http/1.1, h3, acme-tls/1 | Yes in the ClientHello; the answer is encrypted in TLS 1.3 | Server lacks h2 and the client requires it: handshake alert no_application_protocol (gRPC clients fail) |
supported_versions (ext 43) | 1.3 vs 1.2 | Yes | Server speaks only TLS 1.0/1.1: protocol version alert |
key_share (ext 51) | Client's public value for ECDH | Yes | Server wants a group the client did not send: HelloRetryRequest, one extra round trip |
signature_algorithms (ext 13) | Which signature types the client accepts for the certificate | Yes | Server certificate uses an algorithm the client lacks: handshake failure |
| cipher suites | AEAD algorithm + hash (1.3) or full suite (1.2) | Yes | No common suite: handshake_failure |
status_request (ext 5) | “Please staple an OCSP response” | Yes | Nothing breaks; stapling is simply skipped |
session_ticket/psk_key_exchange_modes | Resumption support | Yes | Resumption silently falls back to a full handshake |
Real scenarios: (1) A reverse proxy serving 200 domains from one IP routes by SNI. (2) A gRPC call fails with “no application protocol” because a proxy in front only speaks http/1.1. (3) A health check that connects by IP address sends no SNI (an IP is not a valid host_name) and gets the default certificate, so its hostname check fails. (4) Let's Encrypt's TLS-ALPN-01 validation connects with ALPN acme-tls/1.
Fix / how to use it: to see exactly what your client sends, run clienthello or openssl s_client -connect h:p -servername h -alpn h2 -msg; to test a server for a given name use -servername, never just the IP. For a server that must serve several hostnames see the Go SNI server.
TLS 1.2 and why TLS 1.3 replaced it Important
In plain words: TLS 1.2 needs two round trips because the key exchange happens after the server's hello and certificate, it sends the certificate in clear, and it still allows old options (static RSA key transport, CBC modes, compression, renegotiation) that caused a decade of attacks.
Common misunderstanding: “TLS 1.2 is broken, so we must disable it.” TLS 1.2 with ECDHE and AEAD suites is still acceptable (RFC 9325 allows 1.2 and 1.3). What is deprecated is TLS 1.0 and 1.1 (RFC 8996), and within 1.2 the static-RSA, CBC and RC4/3DES suites.
Definition: the 1.2 flow is ClientHello, ServerHello, Certificate, ServerKeyExchange, ServerHelloDone, ClientKeyExchange, ChangeCipherSpec, Finished, ChangeCipherSpec, Finished. Captured with openssl s_client -tls1_2 -msg against the same lab server (ECDHE-ECDSA-AES128-GCM-SHA256):
# Client Server
1 ClientHello ─────────────────────────────▶
2 ◀──────────────────────────── ServerHello (length 0x43)
3 ◀──────────────────────────── Certificate (length 0x3c7, in clear)
4 ◀──────────────────────────── ServerKeyExchange (ECDHE params + signature)
5 ◀──────────────────────────── ServerHelloDone
6 ClientKeyExchange (client ECDHE public value)
7 ChangeCipherSpec, Finished ──────────────▶
8 ◀──────────────────────────── NewSessionTicket, ChangeCipherSpec, Finished
two round trips before the first application byte| Aspect | TLS 1.2 | TLS 1.3 |
|---|---|---|
| Round trips before data | 2 (full), 1 (resumed) | 1 (full), 0 (0-RTT resumed) |
| Key exchange | RSA key transport or (EC)DHE, chosen by suite | Always (EC)DHE or PSK-DHE: forward secrecy |
| Certificate visible to observers | Yes | No (encrypted) |
| Cipher suites | About 300 combinations, some weak | 5 AEAD suites (key exchange and signature negotiated separately) |
| Renegotiation, compression | Exist (CRIME, Triple Handshake) | Removed |
| Signature of the handshake | Server signs only the key exchange params | CertificateVerify signs the whole transcript |
Static RSA (TLS_RSA_WITH_*) | Possible | Removed; RFC 9325 says implementations should not negotiate cipher suites based on RSA key transport |
Why static RSA matters: with TLS_RSA_WITH_AES_128_GCM_SHA256 the client encrypts the pre-master secret to the server's RSA public key. Anyone who records the traffic today and obtains the private key later (a leak, a court order, a future quantum computer) can decrypt every recorded session. With ECDHE the per-connection secrets are ephemeral and discarded: forward secrecy.
Real scenarios: PCI-DSS style audits flag TLS 1.0/1.1 and RSA key transport; an old Java 7 client or an embedded device that only speaks TLS 1.0 fails against a modern server with a protocol-version alert (OpenSSL: no protocols available when the local library also refuses 1.0).
| Product | Minimum version you should set |
|---|---|
| Go server/client | tls.Config{MinVersion: tls.VersionTLS12} (Go's default minimum is already 1.2; set it explicitly so it is visible) |
| nginx | ssl_protocols TLSv1.2 TLSv1.3; |
| Caddy | Defaults to TLS 1.2 minimum; protocols tls1.2 tls1.3 in the tls block |
| Traefik | minVersion: VersionTLS12 in a TLS option |
| PHP streams | crypto_method => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT (or let the OpenSSL default decide) |
| PostgreSQL | ssl_min_protocol_version = 'TLSv1.2' |
Fix: set a floor of TLS 1.2, prefer 1.3, and disable RSA key transport and CBC suites unless a named legacy client needs them.
Cipher suite names, decoded Must-know
In plain words: a cipher suite name is a recipe. In TLS 1.2 the name lists every ingredient; in TLS 1.3 it lists only the bulk encryption and the hash, because key exchange and signatures are negotiated separately.
Common misunderstanding: “AES_128 is weaker than AES_256 in any way that matters.” Both are far beyond brute force; the choice matters for compliance and for performance on hardware without AES instructions (ChaCha20-Poly1305 is faster there). The key exchange part of the name matters much more than the key length.
Definition and decoding:
| Suite name | Version | Key exchange | Authentication | Bulk cipher | Hash / PRF |
|---|---|---|---|---|---|
TLS_AES_128_GCM_SHA256 (0x1301) | 1.3 | negotiated separately (X25519, P-256, ML-KEM hybrid) | certificate signature (RSA-PSS, ECDSA, Ed25519) | AES-128-GCM (AEAD) | SHA-256 for HKDF and Finished |
TLS_AES_256_GCM_SHA384 (0x1302) | 1.3 | as above | as above | AES-256-GCM | SHA-384 |
TLS_CHACHA20_POLY1305_SHA256 (0x1303) | 1.3 | as above | as above | ChaCha20-Poly1305 | SHA-256 |
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f) | 1.2 | ECDHE (ephemeral) | RSA certificate | AES-128-GCM | SHA-256 |
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b) | 1.2 | ECDHE | ECDSA certificate | AES-128-GCM | SHA-256 |
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8) | 1.2 | ECDHE | RSA certificate | ChaCha20-Poly1305 | SHA-256 |
TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) | 1.2 | RSA key transport, no forward secrecy | RSA | AES-128-GCM | SHA-256 |
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013) | 1.2 | ECDHE | RSA | AES-128-CBC + HMAC-SHA1 | SHA-1 (MAC) |
Reading TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 left to right: protocol TLS, key exchange ECDHE, authentication RSA, WITH, bulk cipher AES with a 128-bit key in GCM mode (authenticated encryption), hash SHA-256 (used in the PRF). OpenSSL uses different spellings: openssl ciphers -stdname -v maps them (OpenSSL 3.6.4):
TLS_AES_128_GCM_SHA256 TLSv1.3 Kx=any Au=any Enc=AESGCM(128) Mac=AEAD
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD
TLS_RSA_WITH_AES_128_GCM_SHA256 AES128-GCM-SHA256 TLSv1.2 Kx=RSA Au=RSA Enc=AESGCM(128) Mac=AEAD| Library | Naming style | How to restrict |
|---|---|---|
| IANA / RFCs / Go / Wireshark | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 | tls.Config.CipherSuites (TLS 1.0 to 1.2 only; 1.3 suites are fixed) |
| OpenSSL / nginx / curl | ECDHE-RSA-AES128-GCM-SHA256 | -cipher, ssl_ciphers, --ciphers; TLS 1.3 uses -ciphersuites |
| NSS / Firefox | IANA style | policy files |
| Mozilla "intermediate" profile | Lists exactly the ECDHE + AEAD set above | use a generated config instead of a hand-made list |
Real scenarios: an audit demands “no CBC”; a Go service must keep TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for an old load balancer; HSM-backed keys that only do RSA need the ECDHE-RSA family rather than ECDHE-ECDSA.
Fix: do not hand-tune suites unless a policy forces you. Set the version floor and let the library's secure defaults choose; in Go that means leaving CipherSuites empty.
Session resumption: tickets, PSK and 0-RTT Important
In plain words: after a successful handshake the server hands the client a “ticket”; next time the client shows it and both sides skip the expensive certificate work. With 0-RTT the client can even send the first request in its very first flight.
Common misunderstanding: “0-RTT is just faster TLS, enable it everywhere.” Early data has no replay protection at the TLS layer: an attacker who captures it can send it again. Only idempotent requests (a GET of a static page) are safe; POST /payments is not.
Definition: in TLS 1.3 a resumed handshake uses a PSK (pre-shared key) derived from the previous session, carried in a pre_shared_key extension together with psk_key_exchange_modes (usually psk_dhe_ke, which still does a fresh ECDHE for forward secrecy). The server issues a NewSessionTicket with a ticket_lifetime of at most 7 days (604,800 seconds, RFC 8446 section 4.6.1). TLS 1.2 uses session ids or stateless session tickets (RFC 5077) for the same purpose.
# Client Server
1 ClientHello + psk_identity(ticket) + [early_data, 0-RTT request] ──▶
2 ◀────────────────────────── ServerHello + pre_shared_key, {EncryptedExtensions, Finished}
3 {Finished} ──────────────────────────────▶ no Certificate / CertificateVerify: authentication is the PSK
4 [1-RTT application data] ◀─────────────────▶ [application data]
0-RTT data in step 1 can be replayed by an attacker who recorded itReal resumption check (OpenSSL 3.6.4 against the lab server; first connection saves the session with -sess_out, the second reuses it with -sess_in):
$ echo | openssl s_client -connect 127.0.0.1:8443 -servername a.test -CAfile root.pem -sess_in sess.pem
Reused, TLSv1.3, Cipher is TLS_AES_128_GCM_SHA256
Protocol : TLSv1.3
Resumption PSK: 75B0DC3B5D3239797CDC51FFCC07110C5D5EBF4B84695D5734C23FA53D5D2F83| Product | Tickets / resumption | 0-RTT |
|---|---|---|
Go crypto/tls | On by default; SessionTicketsDisabled turns it off; ticket keys rotate automatically | Not exposed for TCP (the documentation has no early-data API; the QUICConn interface carries early encryption levels for HTTP/3 libraries) |
OpenSSL (s_client) | -sess_out, -sess_in; -early_data file sends 0-RTT | Supported (server must enable it) |
| nginx | ssl_session_tickets, ssl_session_cache shared:SSL:10m | ssl_early_data on; and pass Early-Data: 1 upstream so the app can reject non-idempotent requests |
| Caddy | Session tickets on, keys rotated automatically | Off by default |
| curl / browsers | Cache sessions in memory; browsers may use 0-RTT for GET | Browser decision |
| PHP | A new process per request does not share sessions; PHP-FPM clients re-handshake unless the stream is reused | Not used |
| Multi-instance servers | All instances need the same ticket keys, or resumption falls back to a full handshake | Same, plus a shared anti-replay store |
Real scenarios: a load-balanced fleet where each pod rotates its own ticket key shows a 5 percent resumption rate instead of 90 percent; a mobile API gateway enables 0-RTT only for GET and forwards Early-Data: 1.
Fix / how to use it: keep tickets enabled; share ticket keys across replicas of the same hostname (or accept full handshakes); enable 0-RTT only when the application can reject replays, and never for requests with side effects.
X.509 certificates, decoded Must-know
In plain words: a certificate is a signed card that says “this public key belongs to these names, valid between these dates, for these purposes”, signed by the issuer. Everything you need to debug is printed on the card.
Common misunderstanding: “The certificate contains the secret.” It contains only the public key. The private key never leaves the server; the handshake proves possession with the CertificateVerify signature.
Definition: X.509 v3 (RFC 5280) is an ASN.1 structure TBSCertificate (version, serial number, signature algorithm, issuer, validity, subject, public key, extensions) plus the issuer's signature over it. It is stored as DER (binary) and usually shown as PEM: the DER bytes in Base64 between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- lines (RFC 7468). The leaf of the lab (openssl x509 -in a.test-leaf.pem -noout -text, OpenSSL 3.6.4, trimmed):
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 4d:4a:b3:c6:52:3e:4d:d7:26:63:6d:07:fd:c2:ab:ec:a4:4a:fb:04
Signature Algorithm: ecdsa-with-SHA256
Issuer: O=Academy Lab, CN=Academy Lab Issuing CA
Validity
Not Before: Nov 25 17:13:27 2026 GMT
Not After : Feb 23 17:13:27 2027 GMT
Subject: CN=a.test
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey (P-256, 65-byte uncompressed point)
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:a.test, DNS:www.a.test
X509v3 Subject Key Identifier: 83:00:16:A0:...:0B:8A:69
X509v3 Authority Key Identifier: FA:5D:69:B4:...:E6:3D
Signature Algorithm: ecdsa-with-SHA256
Signature Value: 30:45:02:21:00:f1:db:42:...| Field | Meaning | What goes wrong |
|---|---|---|
| Subject | Who the certificate is for; for TLS servers a legacy CN is optional | Relying on CN: modern clients ignore it |
| Subject Alternative Name (SAN) | The authoritative list of DNS names and IP addresses | Name used in the URL is not listed: hostname mismatch |
| Issuer | Subject of the CA that signed this certificate | Issuer unknown to the client: unknown authority |
Validity (notBefore, notAfter) | The window in which the certificate is acceptable | Expired, or “not yet valid” when the client clock is wrong |
| Serial number | Unique per CA; used by revocation (CRL, OCSP) | Duplicate serials from a buggy private CA confuse some clients |
| Key Usage / Extended Key Usage | digitalSignature, keyEncipherment; serverAuth, clientAuth | A client-auth-only certificate used as a server certificate (or the reverse) fails |
| Basic Constraints | CA:TRUE and optional pathlen; a leaf must be CA:FALSE | An intermediate without CA:TRUE cannot sign; pathlen:0 forbids further intermediates |
| Subject / Authority Key Identifier | Link a certificate to its issuer's key | Helps build the chain when names are ambiguous |
| Authority Information Access (AIA) | caIssuers URL for the issuer certificate, OCSP responder URL | Not fetched by openssl, curl or Go (see Chains) |
| SCT list (CT) | Proof the certificate was logged in Certificate Transparency | Browsers may reject a public certificate without SCTs |
| Signature algorithm | How the issuer signed | SHA-1 or MD5 signatures are rejected |
| Public key | RSA 2048/3072 or ECDSA P-256/P-384 or Ed25519 | RSA below 2048 is rejected |
PEM versus DER, for the same certificate (484 bytes of DER):
$ head -3 a.test-leaf.pem
-----BEGIN CERTIFICATE-----
MIIB4DCCAYagAwIBAgIUTUqzxlI+TdcmY20H/cKr7KRK+wQwCgYIKoZIzj0EAwIw
NzEUMBIGA1UECgwLQWNhZGVteSBMYWIxHzAdBgNVBAMMFkFjYWRlbXkgTGFiIElz
$ openssl x509 -in a.test-leaf.pem -outform DER -out a.der && xxd a.der | head -3
00000000: 3082 01e0 3082 0186 a003 0201 0202 144d 0...0..........M
00000010: 4ab3 c652 3e4d d726 636d 07fd c2ab eca4 J..R>M.&cm......
00000020: 4afb 0430 0a06 082a 8648 ce3d 0403 0230 J..0...*.H.=...030 82 01 e0 is an ASN.1 SEQUENCE of length 0x01e0 = 480 bytes (plus the 4-byte header makes 484); MIIB4D... is exactly those bytes in Base64 (30 82 01 e0 encodes to MIIB4D). The version, a0 03 02 01 02, means v3. A file may hold several PEM blocks (a chain); a DER file holds exactly one certificate. openssl x509 -noout -ext subjectAltName,extendedKeyUsage -in f.pem prints only the fields you care about, and our Go tool inspectcert prints the same fields for every block in a bundle (the Go side of the same job; real output for the lab bundle a.test.pem):
--- certificate 0 (DER 484 bytes) ---
subject : CN=a.test
issuer : CN=Academy Lab Issuing CA,O=Academy Lab
serial : 4d4ab3c6523e4dd726636d07fdc2abeca44afb04
valid : 2026-11-25 -> 2027-02-23 (90 days left)
SAN dns : [a.test www.a.test] ip: []
is CA : false (pathlen -1)
key usage : 0b1 ext key usage: [serverAuth]
--- certificate 1 (DER 470 bytes) ---
subject : CN=Academy Lab Issuing CA,O=Academy Lab
issuer : CN=Academy Lab Root CA,O=Academy Lab
is CA : true (pathlen 0)
key usage : 0b1100000 ext key usage: []// Command inspectcert prints the fields of every certificate in a PEM file,
// like `openssl x509 -text -noout`, plus the days left until expiry.
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"time"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: inspectcert bundle.pem")
os.Exit(2)
}
data, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
n := 0
for {
var block *pem.Block
block, data = pem.Decode(data)
if block == nil {
break
}
if block.Type != "CERTIFICATE" {
continue
}
c, err := x509.ParseCertificate(block.Bytes) // block.Bytes is the DER encoding
if err != nil {
fmt.Fprintln(os.Stderr, "parse:", err)
os.Exit(1)
}
fmt.Printf("--- certificate %d (DER %d bytes) ---\n", n, len(block.Bytes))
fmt.Printf("subject : %s\n", c.Subject)
fmt.Printf("issuer : %s\n", c.Issuer)
fmt.Printf("serial : %x\n", c.SerialNumber)
fmt.Printf("valid : %s -> %s (%.0f days left)\n",
c.NotBefore.Format("2006-01-02"), c.NotAfter.Format("2006-01-02"), time.Until(c.NotAfter).Hours()/24)
fmt.Printf("SAN dns : %v ip: %v\n", c.DNSNames, c.IPAddresses)
fmt.Printf("is CA : %v (pathlen %d)\n", c.IsCA, c.MaxPathLen)
fmt.Printf("key usage : %#b ext key usage: %v\n", c.KeyUsage, c.ExtKeyUsage)
fmt.Printf("sig alg : %s pubkey: %s\n", c.SignatureAlgorithm, c.PublicKeyAlgorithm)
fmt.Printf("AIA issuer : %v OCSP: %v\n", c.IssuingCertificateURL, c.OCSPServer)
n++
}
if n == 0 {
fmt.Fprintln(os.Stderr, "no CERTIFICATE blocks found")
os.Exit(1)
}
}Real scenarios: (1) a certificate expires at 03:00 on a Sunday because the renewal cron died silently; (2) a service certificate was issued with clientAuth only and the server rejects it; (3) a wildcard *.example.com was issued but the client opens https://example.com (not covered) or https://a.b.example.com (two levels, not covered); (4) a laptop with the wrong date says “not yet valid”.
| Tool | Show the fields |
|---|---|
| OpenSSL | openssl x509 -in f.pem -noout -text, or -subject -issuer -dates -serial -fingerprint -sha256 -ext subjectAltName |
| Go | x509.ParseCertificate(block.Bytes) after pem.Decode; fields DNSNames, IPAddresses, NotAfter, KeyUsage, ExtKeyUsage, IsCA |
| PHP | openssl_x509_parse(file_get_contents('f.pem')); keys subject, issuer, validTo_time_t, extensions['subjectAltName'] |
| curl | curl -v prints subject, issuer, start and expire date, and the SAN match; --cert-status asks for OCSP stapling |
| Browser | Padlock, “Connection is secure”, “Certificate is valid” |
| Windows / macOS | certutil -dump, Keychain Access |
Fix / how to use it: make “read the certificate” the first debugging step: dates, SAN, issuer, key usage, then the chain. The PHP side lives in CertInspector.php.
Chains: leaf, intermediate, root Must-know
In plain words: your server's certificate was signed by a small “issuing” CA, which was signed by a bigger one, up to a root that your device already trusts. The server must hand over the leaf and every intermediate, and the client checks each link.
Common misunderstanding: “If it works in my browser it is configured correctly.” Browsers cache intermediates and some can fetch missing ones from the AIA URL; curl, OpenSSL, Go, Java and most HTTP libraries cannot, so a server that omits the intermediate works in Chrome and fails everywhere else.
Definition: a chain is a path where each certificate's issuer equals the next certificate's subject and its signature verifies with the next certificate's key, ending in a trust anchor (a root in the client's store). The root is not sent: the client already has it, and sending it only costs bytes. Servers send leaf, intermediate(s) in that order; the PEM file is conventionally called fullchain.pem.
# Verification steps in the client
1 leaf.issuer == intermediate.subject ? check signature(leaf) with intermediate.publicKey
2 leaf: dates ok, SAN matches the name, EKU has serverAuth, not a CA
3 intermediate: dates ok, CA:TRUE, keyCertSign, pathlen not exceeded
4 intermediate.issuer == a root in the trust store ? check signature with root.publicKey
5 revocation, CT, name constraints (where enforced) ──▶ accept, or fail with the first errorA real chain from a public site, as returned by the Go tool tlsdial inside a container (Alpine ca-certificates, 2026-11-25): four certificates, including a cross-signed root.
cert[0] : subject="CN=example.com" issuer="CN=Cloudflare TLS Issuing ECC CA 3,O=SSL Corporation,C=US" notAfter=2027-02-22T23:53:08Z
cert[1] : subject="CN=Cloudflare TLS Issuing ECC CA 3,..." issuer="CN=SSL.com TLS Transit ECC CA R2,..."
cert[2] : subject="CN=SSL.com TLS Transit ECC CA R2,..." issuer="CN=SSL.com TLS ECC Root CA 2022,..."
cert[3] : subject="CN=SSL.com TLS ECC Root CA 2022,..." issuer="CN=AAA Certificate Services,O=Comodo CA Limited,..."
verified chains: 1What breaks when an intermediate is missing. We served the lab leaf without its intermediate (Go server on port 8444, leaf only) and asked three clients:
$ openssl s_client -connect 127.0.0.1:8444 -servername a.test -CAfile root.pem (OpenSSL 3.6.4)
verify error:num=20:unable to get local issuer certificate
verify error:num=21:unable to verify the first certificate
Verify return code: 21 (unable to verify the first certificate)
$ curl --resolve a.test:8444:127.0.0.1 --cacert root.pem https://a.test:8444/ (curl 8.7.1, LibreSSL)
curl: (60) SSL certificate problem: unable to get local issuer certificate
$ tlsdial -connect 127.0.0.1:8444 -servername a.test -CAfile root.pem (Go 1.27.4, macOS)
handshake failed: tls: failed to verify certificate: x509: certificate signed by unknown authorityAIA does not rescue you. RFC 5280 defines the Authority Information Access extension with a caIssuers method (a URL where the issuer certificate can be fetched). We issued a leaf with authorityInfoAccess=caIssuers;URI:http://127.0.0.1:8099/int.cer, served the intermediate from a local HTTP server, and asked again: OpenSSL (unable to get local issuer certificate), curl (error 60) and Go on macOS and in a Linux container (unknown authority) all failed. None of them fetched the AIA URL. Some browsers do, which is exactly why “works in Chrome” proves nothing. The fix is always on the server: send the full chain.
Order in the PEM bundle: leaf first, then the intermediate that signed it, then the next intermediate, and (optionally) not the root. The lab file a.test.pem was built with cat a.test-leaf.pem int.pem > a.test.pem. Go's tls.LoadX509KeyPair takes the first certificate as the leaf and sends the rest. (Go's own documentation for ListenAndServeTLS says the file should be the server certificate, any intermediates and the CA's certificate; the extra root is harmless and unnecessary.) Out-of-order bundles work with some servers and fail with others, so keep the order. Let's Encrypt's fullchain.pem already has this shape; cert.pem alone is only the leaf.
| Component | What it needs |
|---|---|
| nginx | ssl_certificate fullchain.pem; (leaf + intermediates), ssl_certificate_key privkey.pem; |
| Apache | SSLCertificateFile fullchain.pem (Apache 2.4.8+) |
| Caddy, Traefik, certbot | Serve the full chain automatically |
| Go | tls.LoadX509KeyPair("fullchain.pem", "privkey.pem") |
| HAProxy | One PEM file: leaf, intermediates, then key |
| Cloud LBs (ACM, GCP, Azure) | Upload leaf and chain separately; check that the chain field is filled |
Real scenarios: the classic outage after a manual renewal: the new certificate was uploaded without the chain, the website still works in the CEO's browser, and the mobile app and the webhook callers fail; a CA rotates its intermediate and your pinned copy no longer matches.
Fix: openssl s_client -connect host:443 -servername host -showcerts must list at least the leaf and every intermediate (Certificate chain shows 0 s: and 1 s: entries); Verify return code: 0 (ok) with the OS trust store (-CApath /etc/ssl/certs or just no option on a configured system) is the acceptance test.
Trust stores: who decides what is trusted Must-know
In plain words: trust is a list of root certificates stored somewhere on the client. A server certificate is trusted if its chain ends at one of them. Different software looks at different lists.
Common misunderstanding: “If I installed the CA on my laptop, my container and my Go program trust it.” Each program picks its own store: the OS list, a bundled file, or a directory. A container has its own filesystem and starts without your laptop's roots.
Definition: a trust store is a set of trust anchors. Platform stores are managed by the OS vendor; browsers and Java ship their own; language runtimes reuse the OS store or bundle one.
| Client | Where its roots come from | Add a private CA | Observed / documented behaviour |
|---|---|---|---|
| macOS apps, Safari, Chrome | Keychain (System Roots) | Keychain Access or mkcert -install | |
| Windows apps, Edge, Chrome | Windows certificate store | certutil -addstore, Group Policy | |
| Debian / Ubuntu | /etc/ssl/certs/ca-certificates.crt and /etc/ssl/certs/*.pem | Copy ca.crt to /usr/local/share/ca-certificates/, run update-ca-certificates | Package ca-certificates |
| RHEL / Fedora | /etc/pki/tls/certs/ca-bundle.crt | Copy to /etc/pki/ca-trust/source/anchors/, run update-ca-trust | |
| Alpine | /etc/ssl/certs/ca-certificates.crt | apk add ca-certificates; copy to /usr/local/share/ca-certificates/, update-ca-certificates | alpine:3 already contains the bundle (ls -l /etc/ssl/certs shows 178,791 bytes); scratch has nothing |
| Firefox | Its own NSS store | mkcert needs nss tools; or Settings, Certificates | Ignores the OS store by default |
| Java | cacerts keystore in the JRE | keytool -importcert -cacerts | mkcert handles it when JAVA_HOME is set |
| Node.js | Bundled Mozilla list | NODE_EXTRA_CA_CERTS=/path/rootCA.pem | README of mkcert shows this |
| Go on Linux | System files and directories | SSL_CERT_FILE, SSL_CERT_DIR | x509.SystemCertPool(); see below |
| Go on macOS and Windows | The platform verifier | OS store | Since Go 1.27, setting SSL_CERT_FILE or SSL_CERT_DIR switches off the platform APIs unless x509sslcertoverrideplatform=0 is set in GODEBUG |
| curl | A CA bundle file (OpenSSL builds) or the OS store (Schannel, some Apple builds) | --cacert f.pem, CURL_CA_BUNDLE, SSL_CERT_FILE, SSL_CERT_DIR | curl docs: SSL CA certificates |
PHP streams, file_get_contents | openssl.cafile, then openssl.capath, else OpenSSL defaults | php.ini | Docs: if cafile is not found, capath is searched |
| PHP cURL ext | curl.cainfo (default for CURLOPT_CAINFO) | php.ini | Typical Windows-development fix |
Guzzle / Laravel Http | verify: true (system bundle), a path, or false | Http::withOptions(['verify' => '/path/ca.pem']) | Guzzle request options |
Docker image scratch | None | COPY a bundle | See below |
Python requests | certifi bundle | REQUESTS_CA_BUNDLE |
Real, reproduced in Docker. A static Go binary (our tlsdial, built with CGO_ENABLED=0 GOOS=linux) in two images, both connecting to example.com:443:
$ docker run --rm tls-scratch -connect example.com:443 (FROM scratch, no /etc/ssl)
handshake failed: tls: failed to verify certificate: x509: certificate signed by unknown authority
$ docker run --rm tls-withca -connect example.com:443 (FROM scratch + /etc/ssl/certs/ca-certificates.crt copied from alpine)
version : TLS 1.3
cipher suite : TLS_AES_128_GCM_SHA256
ALPN : "h2"
verified chains: 1The same program, same binary, same site: the only difference is a file. That error string is the single most common TLS question in containers.
Go and SSL_CERT_FILE, as measured. In the Alpine-based image (with /etc/ssl/certs populated): SSL_CERT_FILE=/nonexistent still verified example.com successfully, because Go replaces only the default file list; the default directories are still read. Setting SSL_CERT_FILE=/root.pem made the lab server (signed by the lab root) verify, and so did SSL_CERT_FILE=/root.pem together with SSL_CERT_DIR=/nonexistent. So the variables point Go at where roots live; they do not disable the other location. Do not use them as “trust only this CA” switches; build a x509.CertPool in code for that.
| Mistake | Symptom | Right way |
|---|---|---|
FROM scratch without a CA bundle | x509: certificate signed by unknown authority on every public HTTPS call | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ or use a base image with ca-certificates |
apt-get install in a minimal Debian or Ubuntu image (these often omit ca-certificates; check ls /etc/ssl/certs) | curl: (60) SSL certificate problem | apt-get install -y --no-install-recommends ca-certificates |
| Installing the private CA on the host only | Containers still fail | Mount or COPY the CA into the image and update the store, or set SSL_CERT_FILE |
curl -k in healthchecks | Everything “works” | Healthcheck over plain HTTP on localhost, or --cacert |
Fix: decide which store each program uses, add the private root to that store, and verify with the program itself (tlsdial, curl -v, php -r), not with the browser.
Hostname verification: SAN, CN, wildcards, IP addresses Must-know
In plain words: after the signature checks pass, the client asks the last question: “is this certificate for the name I typed?” It looks the name up in the certificate's SAN list.
Common misunderstanding: “The CN is the hostname.” RFC 6125 (section 6.4.4) says a client must not look at the CN when a DNS name is present in the SAN and may use it only as a last resort when no such identifiers exist; the RFC 2818 text it quotes in Appendix B.2 already called CN use deprecated and urged CAs to use the dNSName SAN. Go ignores the legacy Common Name entirely (its documentation says so), and Chrome removed CN matching years ago. A certificate with CN=a.test and no SAN fails in Go and in browsers.
Definition: the client compares the name from the URL with the certificate's dNSName entries (or iPAddress entries for an IP URL), case-insensitively, using wildcard rules: * may be only the whole left-most label and matches exactly one label. RFC 6125 describes the matching rules. The name checked is the URL name, never the DNS-resolved IP and never the SNI the client was told to send separately.
| URL host | Certificate SAN | Match? | Why |
|---|---|---|---|
a.test | DNS:a.test | Yes | Exact |
www.a.test | DNS:*.a.test | Yes | Wildcard covers one label |
a.test | DNS:*.a.test | No | The wildcard does not cover the bare domain; list both |
x.y.a.test | DNS:*.a.test | No | Wildcards go one level deep (mkcert prints exactly this warning) |
127.0.0.1 | DNS:localhost | No | An IP needs an IP Address: SAN |
127.0.0.1 | IP Address:127.0.0.1 | Yes | |
SHOP.Example.com | DNS:shop.example.com | Yes | Case-insensitive |
a.test | CN=a.test, no SAN | No (Go, browsers); curl and OpenSSL clients may still accept | Do not rely on CN |
The OpenSSL gotcha, measured. openssl s_client does not check the hostname unless you ask. Against the lab server asked for nope.test (which falls back to the a.test certificate):
$ openssl s_client -connect 127.0.0.1:8443 -servername nope.test -CAfile root.pem
Verification: OK <- chain valid, name NOT checked
$ openssl s_client -connect 127.0.0.1:8443 -servername nope.test -CAfile root.pem -verify_hostname nope.test
verify error:num=62:hostname mismatch
Verify return code: 62 (hostname mismatch)-servername only chooses what is sent in the SNI; -verify_hostname (or -verify_ip) chooses what is checked. curl and Go check the URL name by default, as the real runs show:
$ curl --resolve c.test:8443:127.0.0.1 --cacert root.pem https://c.test:8443/
curl: (60) SSL: no alternative certificate subject name matches target host name 'c.test'
$ clientroots https://localhost:8444/ root.pem (Go, macOS; the leaf-only server of the lab)
diagnosis : hostname mismatch: x509: certificate is valid for a.test, www.a.test, not localhostReal scenarios: (1) Kubernetes service called by payments.shop.svc while the certificate lists only payments.shop.svc.cluster.local; (2) code that connects to https://10.0.0.5 and the certificate has only DNS names; (3) a staging certificate used on staging.shop.example.com, covered by the wildcard *.shop.example.com but not by *.example.com; (4) PostgreSQL sslmode=verify-full against a host alias (libpq: "If sslmode is set to verify-full, libpq will also verify that the server host name matches the name stored in the server certificate.").
Fix: put every name clients will use in the SAN (service short names, FQDNs, IPs if needed); when a client must call a name that is not in the certificate, set the verification name explicitly (tls.Config.ServerName in Go, peer_name in PHP streams, --connect-to or --resolve in curl) instead of disabling verification.
Self-signed, private CA and public CA Important
In plain words: a self-signed certificate vouches for itself; a private CA vouches for your own services and you distribute its root; a public CA is already trusted by everyone's devices because it passed audits.
Common misunderstanding: “Self-signed is the same as insecure.” It is exactly as secure as the way you distribute and pin it. The problem is operational: every client must be told to trust that certificate, and one self-signed certificate per server means trusting dozens of unrelated leaves instead of one root.
| Kind | Who issues | Trusted by default? | Best for | Cost |
|---|---|---|---|---|
| Self-signed leaf | The server's own key | No (browsers show a warning; clients need pinning) | One-off tests | Pin or -k: avoid |
| Private (internal) CA | Your own CA: openssl, mkcert, step-ca, Vault PKI, cert-manager CA issuer, AWS Private CA | Only after you install its root | Service-to-service TLS, internal hostnames, mTLS, development | You run the CA and rotate roots |
| Public CA | Let's Encrypt, ZeroSSL, DigiCert, Sectigo, cloud-provider CAs | Yes (roots are in OS and browser stores) | Anything reachable by the public | Domain validation; public names land in CT logs |
Why a private CA instead of self-signed leaves: one root to distribute, many short-lived leaves signed from it, and rotation without touching clients. The design of that PKI (offline root, intermediates per environment, name constraints) is in Cryptography, TLS, PKI & Secrets; the service-to-service use is in mTLS & Service Security. The lab builds a three-level private PKI (root, issuing CA, leaves) with openssl in a few commands.
Real scenarios: public hostnames use a public CA via ACME; .internal, *.svc.cluster.local and localhost cannot get a public certificate (public CAs only validate names you can prove you control on the public DNS), so they need a private CA; a developer laptop uses mkcert.
Fix: public names: ACME. Internal names: a small private CA with automated issuance (cert-manager, Vault, step-ca). Laptops: mkcert. Never ship a self-signed leaf to production and tell clients to disable verification.
Let's Encrypt and ACME Important
In plain words: ACME is the protocol where your server proves to a CA that it controls a domain and then receives a certificate, with no human in the loop. Let's Encrypt is the free public CA that made this normal; Caddy, certbot, Traefik and cert-manager are ACME clients.
Common misunderstanding: “Let's Encrypt certificates are a one-time setup that lasts 90 days.” The certificate lasts 90 days today, and the point is that renewal is automated: the client renews roughly two thirds of the way through. And the lifetime is shrinking.
Definition: ACME (RFC 8555, March 2019) has an account key, an order for identifiers (DNS names or IPs), one authorization per identifier proved by a challenge, then a CSR is finalised and the certificate downloaded. The CA validates from several vantage points.
# ACME client (Caddy/certbot/cert-manager) Let's Encrypt
1 newAccount (account key) ──────────────────────────────▶
2 newOrder [shop.example.com] ───────────────────────────▶ authorization + challenges offered
3 ◀─────────────────────────────────────────────────────── token for http-01 / dns-01 / tls-alpn-01
4 serve http://shop.example.com/.well-known/acme-challenge/TOKEN = TOKEN.thumbprint
5 "ready" ───────────────────────────────────────────────▶ CA fetches the URL from several places
6 ◀─────────────────────────────────────────────────────── authorization valid
7 finalize(CSR) ─────────────────────────────────────────▶
8 ◀─────────────────────────────────────────────────────── certificate (fullchain.pem), 90 days
9 renew at about 2/3 of lifetime, repeat 2-8| Challenge | How you prove control | Port / place | Wildcard? | Works behind | Notes |
|---|---|---|---|---|---|
| HTTP-01 | Serve a token file at /.well-known/acme-challenge/<TOKEN> | Port 80 only; follows up to 10 redirects, only to ports 80 or 443 | No | A public web server | Default for most clients; all servers behind a DNS name must answer |
| DNS-01 | Publish a TXT record _acme-challenge.<domain> | Public DNS | Yes | Private networks, no inbound access | Needs DNS-provider API credentials; scope them narrowly or delegate via CNAME to a validation zone |
| TLS-ALPN-01 | Answer a TLS handshake with ALPN acme-tls/1 and a special certificate (RFC 8737, February 2020) | Port 443 | No | When port 80 is closed | Mostly for TLS-terminating proxies; limited client support |
Let's Encrypt's own advice, when unsure, is to go with your client's defaults or with HTTP-01.
Lifetimes, from the CA's own announcement (2025-12-02). Let's Encrypt wrote: "We currently issue certificates valid for 90 days, which will be cut in half to 45 days by 2028." The timeline: opt-in tlsserver profile with 45 days from 2026-05-13, the default classic profile moving to 64 days from 2027-02-10, and to 45 days from 2028-02-16; authorization reuse falls from 30 days to 7 hours. So today (2026-11-25) the default is still 90 days, but a client that renews on a hard-coded 60-day timer will break; use ARI (ACME Renewal Information) or renew at about two thirds of the lifetime.
Rate limits (Let's Encrypt, from their documentation). Use the staging endpoint (https://acme-staging-v02.api.letsencrypt.org/directory) while testing: its limits are far higher.
| Limit | Value | Refill | Why you hit it |
|---|---|---|---|
| New certificates per registered domain | 50 per 7 days | 1 per 202 minutes | Issuing one certificate per tenant subdomain |
| New certificates per exact set of identifiers | 5 per 7 days | 1 per 34 hours | A deployment script that deletes the ACME state and re-requests every time |
| New orders per account | 300 per 3 hours | 1 per 36 seconds | Mass issuance from one account |
| Authorization failures per identifier per account | 5 per hour | 1 per 12 minutes | Firewall blocks port 80, DNS typo |
| Consecutive authorization failures | 1,152 | 1 per day | A loop of failing validations; issuance is then paused |
Per-client reality.
| Client | Where it runs | How it gets certificates | Where state lives |
|---|---|---|---|
| Caddy | Reverse proxy, automatic HTTPS for any hostname in the Caddyfile | HTTP-01 or TLS-ALPN-01 by default; DNS-01 with a plugin; public CAs Let's Encrypt and ZeroSSL; tls internal uses its own local CA | /data volume: keep it, or you re-request and hit rate limits |
| certbot | A CLI on the host | certbot certonly --webroot -w /var/www/html -d shop.example.com (webroot, standalone, DNS plugins); renewal timer | /etc/letsencrypt/live/<name>/fullchain.pem and privkey.pem (symlinks to archive/) |
| Traefik | Reverse proxy with certificatesResolvers | httpChallenge, tlsChallenge or dnsChallenge; routers opt in with tls.certresolver | acme.json (the storage setting): persist it |
| cert-manager | Kubernetes controller | ClusterIssuer of type acme with an http01 or dns01 solver; reconciles Certificate resources | A Secret per certificate |
acme.sh, lego, Go autocert | Scripts and libraries | Same protocol | Files or a cache directory |
Real scenarios: (1) a SaaS issues one certificate per customer subdomain and hits 50 per week: use a wildcard (DNS-01) or a custom-domain flow with a few SAN certificates; (2) a redeploy that wipes the Caddy /data volume re-registers an account and re-requests the same certificate on every deploy: the 5-per-week limit hits at the sixth deploy; (3) a Kubernetes cluster behind a corporate firewall can only use DNS-01.
Fix / how to use it: public hostnames: let Caddy or cert-manager do it, keep the state volume, test against staging first, monitor expiry with an alert at 14 days (the cheapest incident insurance there is).
Local HTTPS with mkcert Important
In plain words: mkcert makes a tiny private CA on your laptop, installs it in your trust stores, and mints certificates for localhost or myapp.test that your browser and curl accept without warnings.
Common misunderstanding: “mkcert is a way to get a real certificate for local development.” It is a local CA: the certificates are only trusted on machines where its root was installed. And the root key it creates is powerful. The README says: "Warning: the rootCA-key.pem file that mkcert automatically generates gives complete power to intercept secure requests from your machine. Do not share it."
Definition: mkcert -install creates the CA (in the directory printed by mkcert -CAROOT) and installs rootCA.pem into the system store, the Firefox NSS store and Java (when JAVA_HOME is set); mkcert names... issues a leaf. We ran it with CAROOT pointing to a throw-away directory and without -install, so your trust store stays untouched (real output, identity redacted):
$ CAROOT=$PWD/caroot mkcert -cert-file a.test.pem -key-file a.test-key.pem a.test "*.a.test" localhost 127.0.0.1 ::1
Created a new local CA 💥
Note: the local CA is not installed in the system trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️
Created a new certificate valid for the following names 📜
- "a.test"
- "*.a.test"
- "localhost"
- "127.0.0.1"
- "::1"
Reminder: X.509 wildcards only go one level deep, so this won't match a.b.a.test ℹ️
The certificate is at "a.test.pem" and the key at "a.test-key.pem" ✅
It will expire on 25 February 2029 🗓
$ openssl x509 -in a.test.pem -noout -subject -issuer -ext subjectAltName,keyUsage,extendedKeyUsage -dates
subject=O=mkcert development certificate, OU=dev@laptop
issuer=O=mkcert development CA, OU=dev@laptop, CN=mkcert dev@laptop
X509v3 Key Usage: critical Digital Signature, Key Encipherment
X509v3 Extended Key Usage: TLS Web Server Authentication
X509v3 Subject Alternative Name: DNS:a.test, DNS:*.a.test, DNS:localhost, IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1
notBefore=Nov 25 17:14:30 2026 GMT notAfter=Feb 25 17:14:30 2029 GMT
$ openssl x509 -in caroot/rootCA.pem -noout -ext basicConstraints -dates
X509v3 Basic Constraints: critical CA:TRUE, pathlen:0 notAfter=Nov 25 17:14:30 2036 GMTThe leaf lasts 27 months, the root 10 years, and the root has pathlen:0: mkcert signs leaves directly from the root. Trusting it for other runtimes:
| Runtime | Make it trust the mkcert root |
|---|---|
| Browsers, curl on macOS/Linux | mkcert -install (system store, plus Firefox if nss tools exist) |
| Node.js | export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem" (from the README) |
| Go on Linux | SSL_CERT_FILE=$(mkcert -CAROOT)/rootCA.pem (adds it; see trust stores) |
| Docker container | Mount rootCA.pem read-only and set SSL_CERT_FILE, or COPY it in a dev-only image |
| PHP / Laravel | Http::withOptions(['verify' => '/path/rootCA.pem']) or openssl.cafile in the dev php.ini |
| Phones / other machines | Install rootCA.pem as a trusted profile (README: the file printed by mkcert -CAROOT) |
Real scenarios: HTTPS in local development so Secure cookies, service workers and SameSite=None behave like production; a docker-compose dev stack with https://api.local.test; sharing a dev certificate via the repository is a bug, share the instructions.
Fix / how to use it: one mkcert -install per developer machine, certificates under .gitignore, never copy rootCA-key.pem to a server or CI image. When you need an internal CA that several machines or pods use, build a real one (Kinds of CA, the cert-manager CA issuer in Kubernetes).
HSTS, OCSP stapling and Certificate Transparency Good to know
In plain words: three extras around the certificate. HSTS tells browsers “never talk to me over plain HTTP”. OCSP stapling lets the server attach a fresh “this certificate is not revoked” note. Certificate Transparency is a public log of issued certificates so wrongly issued ones are noticed.
Common misunderstanding: “Revocation protects me if my key leaks.” Clients mostly do not check revocation online (soft-fail), and short lifetimes are replacing revocation as the practical defence: that is part of why certificates are getting shorter.
| Mechanism | What it does | How you use it | Observed in the lab |
|---|---|---|---|
| HSTS (RFC 6797) | Browser remembers to use HTTPS only | Strict-Transport-Security: max-age=31536000; includeSubDomains; preload on HTTPS responses | Caddy redirects HTTP to HTTPS with 308 Permanent Redirect; HSTS itself is added by you |
| OCSP stapling | Server staples a signed “good” response | nginx ssl_stapling on;; Caddy does it automatically; client asks with ext 5 status_request; openssl s_client -status | example.com: OCSP Response Status: successful, Cert Status: good |
| OCSP Must-Staple | Certificate requires stapling | A TLS feature extension in the certificate | Let's Encrypt ended it |
| CRLs | Signed lists of revoked serials | CA publishes; clients fetch rarely | Let's Encrypt moved to CRLs only |
| Certificate Transparency (RFC 9162, SCTs) | Public append-only logs of every public certificate | Embedded SCTs in the certificate; search crt.sh for your domain | example.com and letsencrypt.org leaves carry CT Precertificate SCTs |
Let's Encrypt announced on 2024-12-05 that it would drop OCSP URLs from certificates on 2025-05-07 and move to CRLs; in the lab the letsencrypt.org leaf indeed has an AIA CA Issuers entry but no OCSP responder.
Real scenarios: a site that enabled HSTS with includeSubDomains; preload and then needs an HTTP-only internal subdomain is stuck for the preload lifetime; a security team watches CT logs for unexpected certificates on the company domain; a cache miss on the OCSP responder used to add latency to the first connection, which stapling removes.
Fix / how to use it: start HSTS with a small max-age (for example 300 seconds), raise it once everything is HTTPS, add preload last; staple OCSP when the CA still offers it; subscribe to CT monitoring for your domains.
Where TLS terminates: load balancer, proxy, app, mesh Must-know
In plain words: “Terminate” means: the place where the encrypted bytes become readable. Behind that point traffic is plaintext unless you encrypt it again. Choose the point deliberately.
Common misunderstanding: “HTTPS at the load balancer means the data is encrypted all the way.” Only up to the load balancer. Between the balancer and the app the data may be plaintext on a shared network; and the app only learns about the original scheme from headers the proxy chooses to send.
| Layout | Who holds the certificate | What the proxy sees | What the app sees | Typical use |
|---|---|---|---|---|
| A. Terminate at the edge, plaintext behind | LB / proxy (ACM on an ALB, Caddy, nginx, Cloudflare) | Full HTTP (headers, bodies) | Plain HTTP, X-Forwarded-Proto: https, X-Forwarded-For | Simple stacks; same trusted network |
| B. Terminate, re-encrypt to the backend | Proxy has cert A (public), app has cert B (private CA) | Full HTTP | TLS from the proxy; client IP only via headers | Compliance (“encrypted in transit inside the VPC”) |
| C. Passthrough (SNI routing) | The app | Only the ClientHello (SNI) and byte counts | The real TLS handshake, the real client certificate | mTLS to the app, gateways that must not see traffic; Gateway API tls.mode: Passthrough |
| D. Service mesh sidecars | Sidecar proxies, issued by the mesh CA | n/a | Plain HTTP on localhost; mTLS between sidecars | Zero-trust inside the cluster, identity per workload |
| E. App terminates itself | Go ListenAndServeTLS / Octane --https | n/a | Everything | Single binary, small deployments, gRPC services |
What each point can and cannot do: only a terminating point can route by path, rewrite headers, cache, run a WAF, compress, or log URLs. A passthrough point can route only by SNI and cannot even tell HTTP/1.1 from HTTP/2 in the hello (ALPN is visible; the answer is not in 1.3). Client IP and original scheme must travel in headers (X-Forwarded-*, Forwarded) or the PROXY protocol, and the app must trust only the proxy that sets them (the Laravel trustProxies call in Solving).
# Browser ──TLS(cert A)──▶ Edge proxy ──plaintext──▶ App (layout A)
1 ClientHello SNI=shop.example.com reads SNI, picks cert A, terminates
2 GET /cart (encrypted) decrypts, sees /cart, adds X-Forwarded-Proto: https
3 forwards GET /cart over HTTP to app:8080
4 app sees scheme=http unless it trusts X-Forwarded-Proto ──▶ generates http:// links, redirects loopReal scenarios: an app behind an ALB generates http:// asset URLs and the browser blocks mixed content; a mobile-banking API forces layout B because the audit says “no plaintext inside the network”; a gRPC service with client certificates cannot sit behind a terminating HTTP/1.1-only proxy (use C or E).
Fix / how to use it: pick the layout from the requirement (who must see plaintext, who must prove identity), then set trusted-proxy configuration in the app, and test with curl -v from outside and curl from inside the network.
Mechanics: tools, knobs and errors
openssl s_client: the first tool to reach for
openssl s_client opens a TCP connection, does the handshake, prints what it found and then waits for input (so pipe echo | or press Ctrl-D). The manual page (OpenSSL 3.0) lists the options you need. Use OpenSSL 3 (brew install openssl@3); the macOS system binary is LibreSSL with a different output format.
| Option | What it does | Use it for |
|---|---|---|
-connect host:port | Where to connect | Always |
-servername name | Sends SNI | Every virtual-hosted server; -noservername to test the default certificate |
-showcerts | Prints every certificate the server sent, as PEM | Checking that the intermediate is present |
-CAfile f.pem, -CApath dir | Trust anchors for this run | Private CAs |
-verify_hostname name, -verify_ip ip | Check the name against the SAN | The check that s_client does not do by default |
-verify_return_error | Abort on a verification error | Scripts |
-brief | Short summary | Quick checks |
-tls1_2, -tls1_3, -cipher, -ciphersuites | Force version and suites | Protocol and suite testing |
-alpn h2,http/1.1 | Offer ALPN | HTTP/2 and gRPC checks |
-status | Request an OCSP staple | Stapling |
-msg, -trace | Dump handshake messages (hex, decoded) | Learning, protocol bugs |
-sess_out, -sess_in, -early_data | Save and reuse a session; send 0-RTT | Resumption tests |
-starttls smtp|imap|ftp|postgres | Upgrade a plaintext protocol first | SMTP, IMAP, PostgreSQL |
-proxy, -connect + -servername | Test through a proxy or by IP with a name | Debugging LBs |
The essential commands, with real output from the lab (OpenSSL 3.6.4):
$ openssl s_client -connect 127.0.0.1:8443 -servername a.test -CAfile root.pem -showcerts </dev/null
depth=2 O=Academy Lab, CN=Academy Lab Root CA verify return:1
depth=1 O=Academy Lab, CN=Academy Lab Issuing CA verify return:1
depth=0 CN=a.test verify return:1
Certificate chain
0 s:CN=a.test
i:O=Academy Lab, CN=Academy Lab Issuing CA
a:PKEY: EC, (prime256v1); sigalg: ecdsa-with-SHA256
v:NotBefore: Nov 25 17:13:27 2026 GMT; NotAfter: Feb 23 17:13:27 2027 GMT
1 s:O=Academy Lab, CN=Academy Lab Issuing CA
i:O=Academy Lab, CN=Academy Lab Root CA
Negotiated TLS1.3 group: X25519MLKEM768
SSL handshake has read 2405 bytes and written 1601 bytes
Verification: OK
New, TLSv1.3, Cipher is TLS_AES_128_GCM_SHA256
No ALPN negotiated <- no -alpn offered
Verify return code: 0 (ok)Read it: depth=0 is the leaf, higher numbers go toward the root (the root is checked locally, not sent); Negotiated TLS1.3 group: X25519MLKEM768 is the hybrid post-quantum key exchange chosen by the OpenSSL 3.6 client and the Go 1.27 server; read 2405 bytes is the server's flight, mostly the key share and certificates. The most useful one-liner to read a certificate from a live server:
echo | openssl s_client -connect shop.example.com:443 -servername shop.example.com 2>/dev/null \
| openssl x509 -noout -subject -issuer -dates -ext subjectAltNamecurl -v, --cacert, --resolve, and the danger of -k
curl -v prints the handshake in words. From the lab and from a Caddy container (curl 8.23.0, OpenSSL backend inside Docker):
* ALPN: curl offers h2,http/1.1
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_128_GCM_SHA256 / X25519MLKEM768 / id-ecPublicKey
* ALPN: server accepted h2
* start date: Nov 25 17:17:41 2026 GMT
* expire date: Nov 26 05:17:41 2026 GMT
* issuer: CN=Caddy Local Authority - ECC Intermediate
* subjectAltName: "app.lab.test" matches cert's "app.lab.test"
* SSL certificate verified via OpenSSL.| curl option | Effect | Remember |
|---|---|---|
--cacert f.pem | Use this file instead of the default bundle | The right fix for a private CA |
--capath dir | Directory of hashed certificates | Rarely needed |
--resolve name:443:ip | Pretend DNS returned ip, keep the real name for SNI and verification | Test a server before DNS points to it |
--connect-to | Redirect host:port while keeping the URL name | Same idea, with ports |
--cert, --key | Client certificate (mTLS) | |
--tlsv1.3, --tls-max 1.2 | Version bounds | |
--cert-status | Require a stapled OCSP response | |
-k, --insecure | Skip all verification | See below |
--ssl-no-revoke | Skip revocation (Windows) | |
SSLKEYLOGFILE=path | Write session secrets for Wireshark | Debug only |
Why -k is dangerous: it removes both the chain check and the hostname check, so any certificate for any name is accepted. Everything encrypted to an attacker is still “encrypted”. It also hides the real error: the lab shows three different faults, each fixable in one line, all reduced to a silent success by -k:
$ curl -sS --resolve a.test:8443:127.0.0.1 https://a.test:8443/ curl: (60) SSL certificate problem: unable to get local issuer certificate
$ curl -sS --resolve c.test:8443:127.0.0.1 --cacert root.pem https://c.test:8443/ curl: (60) SSL: no alternative certificate subject name matches target host name 'c.test'
$ curl -sS --resolve a.test:8445:127.0.0.1 --cacert root.pem https://a.test:8445/ curl: (60) SSL certificate problem: certificate has expired
$ curl -sk --resolve a.test:8443:127.0.0.1 https://a.test:8443/ host=a.test:8443 proto=HTTP/2.0 tls=TLS 1.3 alpn="h2" sni="a.test"Reading TLS in Wireshark
Wireshark decodes the handshake. TLS 1.3 encrypts everything after the ServerHello, so the certificate is invisible unless you give Wireshark the session secrets. The Wireshark wiki explains that applications write them to a key log file: "The key log file is a text file generated by applications such as Firefox, Chrome and curl when the SSLKEYLOGFILE environment variable is set." Then set the file under Preferences, Protocols, TLS, (Pre)-Master-Secret log filename.
| What | How |
|---|---|
| Capture a lab connection | sudo tcpdump -i lo0 -w tls.pcap port 8443 (macOS loopback), then open in Wireshark; tshark is the CLI |
| Only the ClientHellos | Display filter tls.handshake.type == 1 |
| Show the SNI | Column or filter tls.handshake.extensions_server_name |
| Show ALPN | tls.handshake.extensions_alpn_str |
| Alerts | tls.alert_message (fatal alerts name the reason: bad_certificate, unknown_ca, protocol_version, no_application_protocol) |
| Decrypt 1.3 | export SSLKEYLOGFILE=$HOME/keys.log then start curl or the browser; in Go set tls.Config.KeyLogWriter (documented as debugging only) |
| Safari, Edge | The Wireshark wiki (written in 2019) says they do not support SSLKEYLOGFILE because their TLS libraries (SecureTransport, Schannel) do not; check current versions |
Never enable key logging in production: the log is enough to decrypt any recorded session.
Debugging from code: a Go tlsdial and a PHP inspector
When the tool you need is not installed (a minimal container, a CI runner), a few lines of Go do the job. tls.Dial (here tls.DialWithDialer, to set a timeout) performs the handshake and ConnectionState() reports the result. Our tlsdial prints version, suite, ALPN, SNI, resumption, every certificate and the number of verified chains; it takes -servername, -CAfile, -alpn and -insecure.
// Command tlsdial is a tiny "openssl s_client" written with crypto/tls.
// It connects, completes the handshake, and prints what was negotiated
// and every certificate the server sent.
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"net"
"os"
"strings"
"time"
)
func main() {
addr := flag.String("connect", "example.com:443", "host:port")
sni := flag.String("servername", "", "SNI and verification name (default: host part of -connect)")
ca := flag.String("CAfile", "", "PEM file with trusted roots (default: system roots)")
alpn := flag.String("alpn", "h2,http/1.1", "comma-separated ALPN offer")
insecure := flag.Bool("insecure", false, "skip verification, like curl -k (print the result anyway)")
flag.Parse()
host, _, err := net.SplitHostPort(*addr)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if *sni == "" {
*sni = host
}
cfg := &tls.Config{ServerName: *sni, NextProtos: strings.Split(*alpn, ","), InsecureSkipVerify: *insecure}
if *ca != "" {
pem, err := os.ReadFile(*ca)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
fmt.Fprintln(os.Stderr, "no certificates found in", *ca)
os.Exit(2)
}
cfg.RootCAs = pool
}
d := &net.Dialer{Timeout: 5 * time.Second}
conn, err := tls.DialWithDialer(d, "tcp", *addr, cfg)
if err != nil {
fmt.Fprintln(os.Stderr, "handshake failed:", err)
os.Exit(1)
}
defer conn.Close()
st := conn.ConnectionState()
fmt.Printf("version : %s\n", tls.VersionName(st.Version))
fmt.Printf("cipher suite : %s\n", tls.CipherSuiteName(st.CipherSuite))
fmt.Printf("ALPN : %q\n", st.NegotiatedProtocol)
fmt.Printf("SNI sent : %q\n", st.ServerName)
fmt.Printf("resumed : %v\n", st.DidResume)
for i, c := range st.PeerCertificates {
fmt.Printf("cert[%d] : subject=%q issuer=%q notAfter=%s dns=%v\n",
i, c.Subject.String(), c.Issuer.String(), c.NotAfter.Format(time.RFC3339), c.DNSNames)
}
fmt.Printf("verified chains: %d\n", len(st.VerifiedChains))
}Real runs: tlsdial -connect 127.0.0.1:8443 -servername a.test -CAfile root.pem printed TLS 1.3, TLS_AES_128_GCM_SHA256, ALPN "h2", two certificates and verified chains: 1; without -CAfile it printed handshake failed: tls: failed to verify certificate: x509: “Academy Lab Issuing CA” certificate is not trusted on macOS (the platform verifier's wording) and certificate signed by unknown authority on Linux. The PHP counterpart is in Solving: PHP inspector.
Common errors: message, cause, fix
| Message (client) | Cause | Fix |
|---|---|---|
Go: x509: certificate signed by unknown authority | No trust anchor for the chain (missing CA in the image, private CA) or the server omitted the intermediate | Add the CA to the store or RootCAs; send fullchain.pem |
Go (macOS): x509: “X” certificate is not trusted | Same, macOS platform verifier wording | Same |
Go: x509: certificate is valid for a.test, www.a.test, not localhost | Name not in the SAN | Reissue with the right SAN, or set ServerName |
Go: x509: certificate has expired or is not yet valid: current time ... is after ... | Expired, or wrong clock | Renew; check NTP |
Go: tls: first record does not look like a TLS handshake | Client speaks TLS to a plaintext port | Fix the port or scheme |
Go: http: server gave HTTP response to HTTPS client | HTTPS client to a plaintext HTTP server | Use http:// or enable TLS on the server |
Go server side: http: TLS handshake error from ...: remote error: tls: bad certificate | The client rejected the server certificate (seen in the httptest run) | Fix the client trust or the certificate |
curl (60) unable to get local issuer certificate | Unknown CA or missing intermediate | --cacert; server sends the chain |
curl (60) no alternative certificate subject name matches target host name | Hostname mismatch | SAN |
curl (60) certificate has expired | Expired | Renew |
curl (35) tlsv1 alert internal error | The server refused the SNI (Caddy with unknown name) | Use the configured name; add the host |
curl (35) tlsv1 alert protocol version or unexpected eof | Plaintext port, or version mismatch | Check the port; --tlsv1.2 |
OpenSSL verify error:num=20 | unable to get local issuer certificate | As above |
OpenSSL num=21 | unable to verify the first certificate: only the leaf was sent | Send intermediates |
OpenSSL num=18 / num=19 | Self-signed certificate / in chain | Trust that root explicitly |
OpenSSL num=10 / num=9 | Expired / not yet valid | Renew; check the clock |
OpenSSL num=62 | Hostname mismatch (only with -verify_hostname) | SAN |
OpenSSL error:0A00010B ... wrong version number | Plaintext server answered | Port or scheme |
OpenSSL alert no application protocol (alert 120) | Client offered ALPN values the server does not support (we offered h3 to an h2, http/1.1 server) | Align NextProtos / -alpn |
OpenSSL no protocols available | Local library refuses the forced version (-tls1_1) | Use a version both support |
PHP/Guzzle: cURL error 60: SSL certificate problem: unable to get local issuer certificate | PHP's CA bundle lacks the CA (curl.cainfo, openssl.cafile) | verify => CA file, or set the ini values |
PHP streams: SSL operation failed with code 1 ... certificate verify failed | Same, stream wrapper | ssl.cafile, openssl.cafile |
Browser: NET::ERR_CERT_AUTHORITY_INVALID / ERR_CERT_COMMON_NAME_INVALID / ERR_CERT_DATE_INVALID | Unknown CA / name / dates | Same causes as above |
Browser: ERR_SSL_PROTOCOL_ERROR, SSL_ERROR_NO_CYPHER_OVERLAP | No common version or suite | Raise the server's protocol set |
| Wrong site's certificate appears | No SNI sent, or the server has no SNI routing and serves the default | -servername; configure per-host certificates (server logs in the lab: no SNI match for "nope.test") |
The TLS knobs per product
| Setting | Go (tls.Config) | nginx | Caddy | PHP stream / cURL | PostgreSQL client (libpq) |
|---|---|---|---|---|---|
| Minimum version | MinVersion | ssl_protocols | protocols in tls | crypto_method, CURLOPT_SSLVERSION | ssl_min_protocol_version (server setting and connection parameter) |
| Cipher suites | CipherSuites (1.0 to 1.2 only) | ssl_ciphers | ciphers | ciphers context option | server-side ssl_ciphers |
| Certificate + key | Certificates, GetCertificate | ssl_certificate, ssl_certificate_key | tls cert key | local_cert, local_pk / cert, ssl_key | sslcert, sslkey |
| Trusted CAs | RootCAs, ClientCAs | ssl_trusted_certificate, ssl_client_certificate | see the Caddy reverse_proxy transport options | cafile, capath / verify | sslrootcert |
| Verify hostname | Default on; ServerName | proxy_ssl_verify on for upstream | default | verify_peer_name, peer_name | sslmode=verify-full |
| ALPN | NextProtos | enable HTTP/2 on the listener (http2 parameter or directive) | automatic | n/a | n/a |
| Client certificate (mTLS) | ClientAuth + ClientCAs | ssl_verify_client on | client_auth | local_cert | sslcert/sslkey |
| Skip verification (debug only) | InsecureSkipVerify | proxy_ssl_verify off | see the Caddy reverse_proxy transport options | verify_peer => false / CURLOPT_SSL_VERIFYPEER | sslmode=require (encrypts, does not verify) |
PostgreSQL deserves its own line. libpq's documentation: "verify-full is recommended in most security-sensitive environments", and sslmode=require encrypts but does not authenticate the server (unless a root CA file exists, which the docs say not to rely on). To check from SQL that the connection is really using TLS:
-- PostgreSQL: is MY connection encrypted, and which protocol and suite?
SELECT pid, ssl, version, cipher, bits, client_dn
FROM pg_stat_ssl
WHERE pid = pg_backend_pid();
-- version = TLSv1.3, cipher = TLS_AES_256_GCM_SHA384 means TLS; ssl = false means plaintext.
-- Compiled, not run in this lab: no PostgreSQL server was started for this chapter.TLS in Docker
A container is a separate filesystem and a separate trust store. TLS in Docker is about four things: where the certificate and key come from, who can read them, which CAs the process trusts, and who terminates TLS. The network side (why a container reaches another by name, published ports) is in Docker Networking.
Certificates and keys into a container Important
In plain words: give the container its key as a read-only file that is not part of the image, readable only by the process that needs it; never bake it into a layer and avoid environment variables.
Common misunderstanding: “An environment variable is a fine place for a PEM.” The Docker Compose documentation says: "Environment variables are often available to all processes, and it can be difficult to track access. They can also be printed in logs when debugging errors without your knowledge." They are also visible in docker inspect. Compose secrets are mounted as files at /run/secrets/<secret_name>.
| Method | Good for | Weakness |
|---|---|---|
Bind mount ./certs:/certs:ro | Development, a single host | The file mode of the host file decides who can read; key must be readable by the container user (often a non-root UID) |
Compose secrets: (file based) | Compose stacks | Mounted at /run/secrets/name; in Compose it is a bind mount of the source file, not encrypted storage |
| Docker Swarm secrets | Swarm | Encrypted in the Raft log; mode and uid settings apply |
COPY into the image | Public certificates only | A private key in a layer lives forever in docker history and in every registry copy |
| Environment variable with the PEM | Nothing | Leaks through inspect, /proc/<pid>/environ, logs, child processes |
| Orchestrator injection (Vault agent, cert-manager, ACM) | Production | Needs the platform |
| Let the proxy own it (Caddy, Traefik) | Public sites | The proxy needs its state volume |
Practical details: set the key file to mode 0400, owned by the UID the container runs as (user: "10001:10001" in Compose); a TLS key readable by root only fails with a permission error in a non-root container; mount certificates :ro; restart or reload the process when a mounted file changes (a plain Go server reads files once at startup, see the reloading server in Solving).
A Compose file for your own certificates and for trusting an internal CA on outgoing calls (an illustration with a placeholder image; it was not run):
# Mounting your own certificate and key as Compose secrets (files, not environment variables).
services:
api:
image: ghcr.io/example/api:1.0 # placeholder image
environment:
TLS_CERT: /run/secrets/api_cert
TLS_KEY: /run/secrets/api_key
secrets:
- source: api_cert
- source: api_key
mode: 0400 # honoured by Swarm; Compose bind-mounts the file as-is
volumes:
- ./certs/internal-ca.pem:/etc/ssl/certs/internal-ca.pem:ro # extra trusted root for outgoing calls
secrets:
api_cert:
file: ./certs/api.pem
api_key:
file: ./certs/api-key.pemAuto-TLS with Caddy in Compose Important
In plain words: put Caddy in front of the app. Caddy obtains and renews the certificate, redirects HTTP to HTTPS, and speaks plain HTTP to your container.
Common misunderstanding: “Caddy certificates work for any name.” For a public name Caddy uses ACME (needs ports 80/443 reachable from the internet and DNS pointing at it). For localhost, internal names and IP addresses it uses its own local CA (tls internal), whose root you must trust.
# Caddy obtains and renews certificates by itself.
# "tls internal" uses Caddy's own local CA (good for Compose and development).
# For a real public hostname, delete the tls line: Caddy then uses ACME (Let's Encrypt / ZeroSSL).
{
# Uncomment while testing a public name, so you do not burn production rate limits:
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
app.lab.test {
tls internal
reverse_proxy app:80
}services:
caddy:
image: caddy:2-alpine
ports:
- "443:443"
- "80:80"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data # certificates, ACME account key, local CA: keep this volume!
- caddy_config:/config
depends_on: [app]
networks:
default:
aliases:
- app.lab.test # other containers reach Caddy under the public name
app:
image: traefik/whoami # plain HTTP backend; it never sees TLS
expose: ["80"]
# A second container that trusts Caddy's local root, to prove service-to-service HTTPS works.
probe:
image: curlimages/curl
user: root # the Caddy data volume is owned by root
entrypoint: ["sleep", "3600"]
volumes:
- caddy_data:/caddy-data:ro
volumes:
caddy_data:
caddy_config:We ran this stack (Docker Engine 29.8.1 in Docker Desktop, caddy:2-alpine, host ports remapped). Real results:
$ docker compose exec probe curl -sS https://app.lab.test/ (no trust)
curl: (60) SSL certificate OpenSSL verify result: unable to get local issuer certificate (20)
$ docker compose exec probe curl -sS --cacert /caddy-data/caddy/pki/authorities/local/root.crt https://app.lab.test/
Hostname: ab6f9ea4db1b RemoteAddr: 172.19.0.4:52288 GET / HTTP/1.1 <- the app saw plain HTTP
$ docker compose exec probe curl -sI http://app.lab.test/
HTTP/1.1 308 Permanent Redirect Location: https://app.lab.test/ Server: Caddy
$ docker compose exec probe curl -sS --cacert .../root.crt https://caddy/ (name not configured)
curl: (35) TLS connect error: error:0A000438:SSL routines::tlsv1 alert internal error
$ ls /caddy-data/caddy/pki/authorities/local/ /caddy-data/caddy/certificates/local/app.lab.test/
intermediate.crt intermediate.key root.crt root.key app.lab.test.crt app.lab.test.json app.lab.test.keyDetails worth knowing: the issued internal leaf had a 12-hour lifetime (notBefore 17:17:41, notAfter 05:17:41 next day) and no subject, only a SAN, and an intermediate called Caddy Local Authority - ECC Intermediate; the log line installing root certificate (you might be prompted for password) shows Caddy trying to add its root to the container's trust store, which does not help other containers (the probe container mounted the data volume and passed --cacert). A hostname that Caddy has no site for gets a TLS internal error alert instead of a default certificate (a contrast with the Go server in the lab, which serves its first certificate). Names ending in .localhost resolve to loopback inside the curl container, which is why the lab uses app.lab.test with a network alias.
| Proxy | Auto-TLS | State to persist | Internal CA |
|---|---|---|---|
| Caddy | Built in (ACME); automatic redirect | /data | tls internal |
| Traefik | certificatesResolvers.<name>.acme with httpChallenge, tlsChallenge or dnsChallenge; storage acme.json | The acme.json file or volume | Provide your own cert files via the file provider |
| nginx | Not built in; use certbot or nginx-proxy + acme-companion | /etc/letsencrypt | Manual |
| HAProxy | Not built in; external ACME client | Cert directory | Manual |
Internal CA for service-to-service in Compose: mkcert for a developer stack (one root, mounted read-only into each container and trusted via SSL_CERT_FILE); step-ca or Vault PKI for something longer lived; Caddy's tls internal when Caddy is the only TLS endpoint. The design questions (who may issue what, identities per service) are in mTLS & Service Security.
Fix / how to use it: dev: Caddy with tls internal or mkcert; production single host: Caddy or Traefik with a persisted state volume and a public hostname; containers that call each other with TLS: mount the CA bundle and verify with it, never InsecureSkipVerify.
TLS in Kubernetes
Kubernetes adds three layers: where the certificate bytes live (Secrets), who creates and renews them (cert-manager or the cloud), and who terminates TLS (Ingress, Gateway API, a mesh). Pod networking and Services are in Kubernetes Networking. Everything in this section was parsed as YAML but not applied: the machine had no cluster (no kind, k3d or Docker Desktop Kubernetes). kubectl apply --dry-run=client also needs API discovery, so it could not validate either; treat the manifests as compile-only and test them in a scratch cluster.
TLS Secrets, mounting, and rotation Must-know
In plain words: a certificate and key live in a Secret of type kubernetes.io/tls; Pods mount it as files or an Ingress references it by name; when something renews it, the mounted files change in place.
Common misunderstanding: “Secrets are encrypted in Kubernetes.” The Kubernetes documentation says Secrets are by default stored unencrypted in the API server's data store, etcd, and: "Anyone with API access can retrieve or modify a Secret, and so can anyone with access to etcd." Base64 is encoding, and the docs say so: it is "obscured but not secret". Enable encryption at rest and RBAC.
Definition: the kubernetes.io/tls Secret type requires the keys tls.crt and tls.key (the API server does not validate the values). cert-manager also writes ca.crt. Updating the Secret updates mounted files automatically, except when the Secret is mounted with subPath (the documentation notes that a subPath mount does not receive updates), and environment variables never update.
# cert-manager Kubernetes App pod
1 Certificate "api-internal" created ─▶ Issuer signs (CA / ACME)
2 writes Secret api-internal-tls (tls.crt, tls.key, ca.crt)
3 kubelet refreshes the mounted volume (symlink swap)
4 reloadcert sees a newer modtime, re-reads, serves new cert
5 at renewBefore (e.g. 30 days) cert-manager renews, repeat 2-4# A TLS Secret by hand (cert-manager normally creates this for you):
# kubectl create secret tls api-tls --cert=api.pem --key=api-key.pem -n shop
# and a ConfigMap holding extra trusted roots for outgoing calls:
# kubectl create configmap internal-ca --from-file=ca.crt=root.pem -n shop
apiVersion: v1
kind: Pod
metadata:
name: api
namespace: shop
spec:
containers:
- name: api
image: ghcr.io/example/api:1.0 # placeholder image
env:
- name: TLS_CERT
value: /tls/tls.crt
- name: TLS_KEY
value: /tls/tls.key
- name: SSL_CERT_FILE # Go on Linux and OpenSSL-based tools read this (see the trust-store notes)
value: /etc/ssl/internal/ca.crt
volumeMounts:
- name: tls
mountPath: /tls
readOnly: true # updated in place by the kubelet when the Secret changes
- name: internal-ca
mountPath: /etc/ssl/internal
readOnly: true
volumes:
- name: tls
secret:
secretName: api-tls
defaultMode: 0400
- name: internal-ca
configMap:
name: internal-caOur reloadcert server (Go) shows the application half: GetCertificate returns the current in-memory certificate, a ticker compares the modtime of the resolved file and re-loads it, and a failed reload keeps the old certificate.
cert-manager: Issuer, ClusterIssuer, Certificate Important
In plain words: you describe the certificate you want (names, duration, which issuer); cert-manager obtains it, stores it in a Secret and renews it.
Common misunderstanding: “cert-manager is only for Let's Encrypt.” It has issuers for ACME, a private CA (ca), self-signed, Vault and cloud CAs; a self-signed bootstrap plus a CA issuer is the standard way to get an internal CA in a cluster.
| Resource | Scope | Purpose |
|---|---|---|
Issuer | One namespace | A way to get certificates: acme, ca, selfSigned, vault |
ClusterIssuer | Whole cluster | Same, usable from any namespace (a ca ClusterIssuer reads its Secret from the cert-manager namespace) |
Certificate | Namespace | What you want: secretName, dnsNames, duration (default 90 days), renewBefore or renewBeforePercentage (recommended), usages, issuerRef |
CertificateRequest, Order, Challenge | Generated | The intermediate objects you read when issuance is stuck |
| ingress-shim | Annotation cert-manager.io/cluster-issuer on an Ingress | Creates the Certificate from the tls: block for you |
| Gateway annotation | cert-manager.io/cluster-issuer on a Gateway | Same for Gateway API listeners |
Documented defaults and rules: spec.duration defaults to 90 days; renewBefore and duration are Go duration strings (2160h, not 90d); the minimum duration is 1 hour; since cert-manager v1.18 the private key rotationPolicy defaults to Always (a new key per renewal); with ACME the Secret has no ca.crt because the CA is unknown.
# Requires cert-manager installed in the cluster (CRDs: Issuer, ClusterIssuer, Certificate).
# 1) A private CA for internal traffic: a self-signed bootstrap issuer signs a CA certificate,
# and a CA issuer then signs leaf certificates with that CA.
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: selfsigned-bootstrap
spec:
selfSigned: {}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: internal-ca
namespace: cert-manager # ClusterIssuers read the CA secret from this namespace
spec:
isCA: true
commonName: Academy Internal CA
secretName: internal-ca-secret
duration: 87600h # 10 years for the root
privateKey:
algorithm: ECDSA
size: 256
issuerRef:
name: selfsigned-bootstrap
kind: ClusterIssuer
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: internal-ca
spec:
ca:
secretName: internal-ca-secret
---
# 2) A public CA via ACME HTTP-01 (Let's Encrypt). Use the staging URL first.
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-staging
spec:
acme:
server: https://acme-staging-v02.api.letsencrypt.org/directory
email: ops@example.com
privateKeySecretRef:
name: letsencrypt-staging-account-key
solvers:
- http01:
ingress:
ingressClassName: nginx
---
# 3) A Certificate: cert-manager writes the key pair into the Secret named by secretName
# (type kubernetes.io/tls, keys tls.crt, tls.key, ca.crt) and renews it before it expires.
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: api-internal
namespace: shop
spec:
secretName: api-internal-tls
dnsNames:
- api.shop.svc.cluster.local
- api.shop.svc
duration: 2160h # 90 days
renewBefore: 720h # start renewing 30 days before expiry
privateKey:
algorithm: ECDSA
size: 256
rotationPolicy: Always # generate a new key on every renewal
usages:
- digital signature
- server auth
issuerRef:
name: internal-ca
kind: ClusterIssuerDebugging order when a certificate never becomes Ready: kubectl describe certificate, then certificaterequest, order, challenge (cert-manager's own chain of resources), then the ingress controller logs; an HTTP-01 challenge needs the Ingress to be reachable on port 80 from the internet.
Ingress tls, Gateway API listeners, and CA bundles Important
In plain words: the Ingress (or Gateway) names the Secret to serve for a host; the controller loads it and terminates TLS at the edge. For the hop to the Pod you choose: plaintext, re-encryption, or passthrough.
Common misunderstanding: “Adding tls: to an Ingress encrypts traffic to the Pod.” It encrypts client to controller only. The Kubernetes docs: the tls.secretName Secret must contain tls.crt and tls.key, and the host in tls.hosts should match the rule host.
# Option A: Ingress with a tls block. cert-manager's ingress-shim creates the Certificate
# from the annotation, writes the Secret named in secretName, and the controller serves it.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
namespace: shop
annotations:
cert-manager.io/cluster-issuer: letsencrypt-staging
spec:
ingressClassName: nginx
tls:
- hosts:
- shop.example.com
secretName: shop-example-com-tls
rules:
- host: shop.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
---
# Option B: Gateway API (use this INSTEAD of option A for a given host, not together).
# cert-manager needs Gateway API support enabled (Helm value config.gatewayAPI.enabled=true) and the
# Gateway API CRDs installed. The Gateway listener terminates TLS with the Secret.
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: edge
namespace: shop
annotations:
cert-manager.io/cluster-issuer: letsencrypt-staging
spec:
gatewayClassName: nginx
listeners:
- name: https
hostname: api.example.com
port: 443
protocol: HTTPS
tls:
mode: Terminate # use Passthrough to forward the TLS stream untouched
certificateRefs:
- kind: Secret
name: api-example-com-tls
allowedRoutes:
namespaces:
from: SameThe Kubernetes documentation notes that the project recommends Gateway over Ingress and that the Ingress API is frozen (still supported, no new features), so new designs lean toward the Gateway API. cert-manager's Gateway support needs the Gateway API CRDs and an explicit setting (config.gatewayAPI.enabled=true in the Helm values); use option A or option B for a host, not both. The Gateway API documents the listener TLS modes: Terminate (the Gateway decrypts, certificateRefs point at Secrets) and Passthrough (the session from the client passes through untouched, so no TLS settings on the listener take effect). Re-encrypting to the backend after terminating is BackendTLSPolicy.
| Layer | Terminates? | Config |
|---|---|---|
| Ingress (ingress-nginx, Traefik, HAProxy, cloud) | Yes, at the controller | spec.tls[].secretName; controller-specific annotations for backend HTTPS (nginx.ingress.kubernetes.io/backend-protocol: "HTTPS") |
Gateway API listener HTTPS + Terminate | Yes | listeners[].tls.certificateRefs |
Gateway API TLS + Passthrough with TLSRoute | No; routes by SNI | tls.mode: Passthrough |
| Cloud load balancer (ALB with ACM, GCP managed certs) | Yes, at the cloud edge | Certificate ARN or managed-certificate resource |
| Service mesh (Istio, Linkerd, Cilium) | Sidecar or node proxy does mTLS between workloads | Mesh CA, automatic rotation |
Mounting a CA bundle for outgoing calls: put the CA certificate in a ConfigMap (it is public), mount it read-only, and point the runtime at it with SSL_CERT_FILE for Go, NODE_EXTRA_CA_CERTS for Node, or the Guzzle verify path for PHP (as in tls-secret-and-mounts.yaml).
Rotation checklist: is the cert mounted without subPath? does the app re-read the files (or does a reloader restart it)? is renewBefore at least a couple of days longer than your worst response time? does an alert fire when notAfter is under 14 days (cert-manager reports each certificate's expiry in its status, kubectl get certificate -A shows READY)? do all ticket keys and replicas agree?
Fix / how to use it: public hostnames: Ingress or Gateway plus a cert-manager ACME ClusterIssuer. Internal service TLS: a ca ClusterIssuer and Certificate resources per service, mounted without subPath, with an app that reloads. Do not copy tls.key between namespaces by hand.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Several hostnames on one IP and port | SNI routing with GetCertificate (Go) or per-host server blocks | Pick the certificate by ClientHelloInfo.ServerName | One listener, many names | Clients without SNI get the default certificate |
unknown authority for an internal service | Trust the private CA explicitly | RootCAs (Go), verify => path (Guzzle), --cacert (curl), SSL_CERT_FILE | Verification stays on | You must distribute the CA file |
unknown authority in a minimal container | Ship a CA bundle in the image | COPY ca-certificates.crt or use a base with it | Public HTTPS works | Image size (about 200 KB) |
| Missing intermediate | Serve fullchain.pem | Leaf first, then intermediates | Works for every client | None |
| Hostname mismatch | Fix the SAN, or set the verification name | Reissue; ServerName, peer_name, --resolve | Verification stays on | Reissue needed |
App generates http:// links behind a TLS proxy | Trust the proxy's forwarded headers | trustProxies in Laravel; X-Forwarded-Proto | Correct URLs and secure cookies | Trust only the proxy's address range |
| Certificate renewed but the process still serves the old one | Reload the certificate | GetCertificate with reload; SIGHUP; reloader sidecar | No downtime | Code or a reloader |
| Expiry surprises | Monitor notAfter | Alert at 14 days; synthetic check | Cheap and effective | One more alert |
| gRPC / HTTP/2 fails behind a proxy | Offer and accept ALPN h2 end to end | NextProtos: h2; proxy with HTTP/2 upstream | gRPC works | Proxy must support HTTP/2 upstream |
| Tests need HTTPS | httptest.NewTLSServer | Throwaway certificate; srv.Client() trusts it | No files | Test-only |
Serve two hostnames with SNI (Go)
GetCertificate runs for every new handshake and receives the ClientHelloInfo with ServerName (the SNI), the offered ALPN protocols and versions. The lab server loads a.test.pem and b.test.pem (leaf then intermediate), picks by name, and falls back to the first host for unknown or missing SNI, logging it. The NextProtos list is the server's ALPN offer; h2 first.
// Command sniserver serves two hostnames from one TLS listener.
// GetCertificate picks the certificate by the SNI name the client sent;
// an unknown or missing name falls back to the first host (the "default cert").
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
"path/filepath"
)
func main() {
addr := flag.String("addr", ":8443", "listen address")
dir := flag.String("certs", "certs", "directory with <host>.pem and <host>-key.pem")
hosts := []string{"a.test", "b.test"}
flag.Parse()
certs := map[string]*tls.Certificate{}
for _, h := range hosts {
c, err := tls.LoadX509KeyPair(filepath.Join(*dir, h+".pem"), filepath.Join(*dir, h+"-key.pem"))
if err != nil {
log.Fatalf("load %s: %v", h, err)
}
certs[h] = &c
}
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
NextProtos: []string{"h2", "http/1.1"}, // ALPN offer, in server preference order
GetCertificate: func(hi *tls.ClientHelloInfo) (*tls.Certificate, error) {
if c, ok := certs[hi.ServerName]; ok {
return c, nil
}
log.Printf("no SNI match for %q, serving default certificate", hi.ServerName)
return certs[hosts[0]], nil
},
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "host=%s proto=%s tls=%s alpn=%q sni=%q\n",
r.Host, r.Proto, tls.VersionName(r.TLS.Version), r.TLS.NegotiatedProtocol, r.TLS.ServerName)
})
srv := &http.Server{Addr: *addr, Handler: mux, TLSConfig: cfg}
log.Printf("listening on %s", *addr)
// Empty file names: certificates come from TLSConfig.GetCertificate.
log.Fatal(srv.ListenAndServeTLS("", ""))
}Real behaviour of this server (OpenSSL 3.6.4 and curl as clients; server log below):
$ openssl s_client -connect 127.0.0.1:8443 -servername b.test -CAfile root.pem subject=CN=b.test Verification: OK
$ openssl s_client -connect 127.0.0.1:8443 -servername nope.test -CAfile root.pem subject=CN=a.test (default cert)
$ openssl s_client -connect 127.0.0.1:8443 -noservername -CAfile root.pem subject=CN=a.test (default cert)
$ curl -s --resolve a.test:8443:127.0.0.1 --cacert root.pem https://a.test:8443/
host=a.test:8443 proto=HTTP/2.0 tls=TLS 1.3 alpn="h2" sni="a.test"
server log: no SNI match for "nope.test", serving default certificate
no SNI match for "", serving default certificateThe fallback is a policy choice. Returning an error (as Caddy does for names it has no site for, producing the tlsv1 alert internal error we saw) is stricter and avoids leaking a certificate name to scanners; returning a default is friendlier to legacy clients and to health checks that connect by IP.
Trust a private CA in Go
x509.SystemCertPool() returns a copy of the system roots, to which you can add your CA; an empty x509.NewCertPool() would drop every public CA (a classic bug that breaks calls to public APIs). Clone http.DefaultTransport so proxies, timeouts and HTTP/2 stay enabled. The typed errors x509.UnknownAuthorityError, x509.HostnameError and x509.CertificateInvalidError let you log the real reason.
// Command clientroots shows the three ways an HTTPS client in Go can trust a
// private CA, and how to read the typed certificate errors.
package main
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"os"
"time"
)
// poolWithExtra returns the system roots plus one extra PEM file.
// Using SystemCertPool keeps public sites working; an empty NewCertPool would not.
func poolWithExtra(path string) (*x509.CertPool, error) {
pool, err := x509.SystemCertPool()
if err != nil || pool == nil {
pool = x509.NewCertPool()
}
pem, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if !pool.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("no PEM certificates in %s", path)
}
return pool, nil
}
// explain maps a failed request to the cause an operator needs.
func explain(err error) string {
var unknown x509.UnknownAuthorityError
var host x509.HostnameError
var inval x509.CertificateInvalidError
switch {
case errors.As(err, &unknown):
return "unknown authority: the chain does not end in a trusted root (missing CA or missing intermediate)"
case errors.As(err, &host):
return "hostname mismatch: " + host.Error()
case errors.As(err, &inval):
return fmt.Sprintf("certificate invalid (reason code %d): expired, not yet valid, wrong key usage ...", inval.Reason)
}
return err.Error()
}
func main() {
url := "https://localhost:8443/"
if len(os.Args) > 1 {
url = os.Args[1]
}
cfg := &tls.Config{MinVersion: tls.VersionTLS12}
if len(os.Args) > 2 { // optional: path to a private CA bundle
pool, err := poolWithExtra(os.Args[2])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
cfg.RootCAs = pool
}
// Clone the default transport so proxies, timeouts and HTTP/2 stay on.
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = cfg
client := &http.Client{Transport: tr, Timeout: 10 * time.Second}
resp, err := client.Get(url)
if err != nil {
fmt.Println("request failed:", err)
fmt.Println("diagnosis :", explain(err))
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println(resp.Status, resp.Proto, tls.VersionName(resp.TLS.Version))
}Never reach for InsecureSkipVerify. The crypto/tls documentation says it itself: with it set, crypto/tls accepts any certificate the server presents and any host name in it, so TLS is open to machine-in-the-middle attacks unless you add custom verification. The legitimate cases are custom verification (VerifyConnection, VerifyPeerCertificate) and tests.
Test TLS code with httptest
httptest.NewTLSServer starts an HTTPS server with a throwaway certificate (our test connects to 127.0.0.1 and verifies it), and srv.Client() is configured to trust it. With NewUnstartedServer, EnableHTTP2 = true and StartTLS() you get ALPN h2. A second test shows the failure a default client sees (unknown authority), which documents the contract. Both pass (go test ./httptestdemo -v): TestTLSServerAndClient and TestDefaultClientRejectsTestCert, the latter logging tls: failed to verify certificate: x509: certificate signed by unknown authority.
package httptestdemo
import (
"io"
"net/http"
"net/http/httptest"
"testing"
)
// httptest.NewTLSServer starts an HTTPS server with a throwaway certificate
// valid for 127.0.0.1, example.com and ::1. srv.Client() already trusts it.
func TestTLSServerAndClient(t *testing.T) {
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, r.TLS.NegotiatedProtocol)
}))
srv.EnableHTTP2 = true // negotiate h2 via ALPN
srv.StartTLS()
defer srv.Close()
resp, err := srv.Client().Get(srv.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if string(body) != "h2" || resp.ProtoMajor != 2 {
t.Fatalf("want h2, got ALPN %q proto %s", body, resp.Proto)
}
}
// A client that does NOT trust the test CA must fail: this documents the
// "unknown authority" error you meet when a service calls a private CA.
func TestDefaultClientRejectsTestCert(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer srv.Close()
_, err := http.Get(srv.URL) // http.DefaultClient uses system roots only
if err == nil {
t.Fatal("expected a certificate error")
}
t.Log(err)
}Reload certificates without a restart
// Command reloadcert serves HTTPS and re-reads its certificate when the files
// change on disk, so cert-manager or certbot renewals need no restart.
// Kubernetes updates a mounted Secret by swapping a symlink, so we compare modtimes
// of the resolved files instead of watching inodes.
package main
import (
"crypto/tls"
"log"
"net/http"
"os"
"sync"
"time"
)
type reloader struct {
certFile, keyFile string
mu sync.RWMutex
cert *tls.Certificate
loaded time.Time
}
func (r *reloader) load() error {
c, err := tls.LoadX509KeyPair(r.certFile, r.keyFile)
if err != nil {
return err
}
r.mu.Lock()
r.cert, r.loaded = &c, time.Now()
r.mu.Unlock()
return nil
}
// GetCertificate is called for every new handshake; existing connections keep their old cert.
func (r *reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.cert, nil
}
func (r *reloader) watch(every time.Duration) {
for range time.Tick(every) {
st, err := os.Stat(r.certFile) // Stat follows the symlink to the real file
if err != nil {
log.Printf("stat: %v", err)
continue
}
r.mu.RLock()
changed := st.ModTime().After(r.loaded)
r.mu.RUnlock()
if !changed {
continue
}
if err := r.load(); err != nil {
log.Printf("reload failed, keeping the old certificate: %v", err)
continue
}
log.Printf("certificate reloaded")
}
}
func main() {
r := &reloader{certFile: "/tls/tls.crt", keyFile: "/tls/tls.key"}
if v := os.Getenv("TLS_CERT"); v != "" {
r.certFile = v
}
if v := os.Getenv("TLS_KEY"); v != "" {
r.keyFile = v
}
if err := r.load(); err != nil {
log.Fatal(err)
}
go r.watch(30 * time.Second)
srv := &http.Server{
Addr: ":8443",
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, GetCertificate: r.GetCertificate},
Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) }),
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}Two details matter. GetCertificate is called per handshake, so existing connections keep the old certificate until they close (that is fine). And Kubernetes (or certbot's symlinks) change which file a path points to, so the reloader compares Stat modification times of the resolved path instead of assuming an inotify event on a fixed inode. Alternatives: kill -HUP handling (nginx nginx -s reload, Caddy reloads on its own), or a restart triggered by a hash annotation on the Deployment.
mTLS server configuration in Go
The only TLS-specific additions for mutual TLS are ClientAuth and ClientCAs; the design of identities, SANs for clients, rotation and authorization is in mTLS & Service Security and the Go walkthrough in HTTP/2, HTTPS, TLS & mTLS in Go.
// Command mtlsconfig shows the crypto/tls knobs that turn a TLS server into an
// mTLS server. The design of mTLS between services lives in system-design.
package main
import (
"crypto/tls"
"crypto/x509"
"log"
"net/http"
"os"
)
func main() {
caPEM, err := os.ReadFile("clients-ca.pem") // the CA that signs CLIENT certificates
if err != nil {
log.Fatal(err)
}
clients := x509.NewCertPool()
clients.AppendCertsFromPEM(caPEM)
srv := &http.Server{
Addr: ":9443",
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
ClientAuth: tls.RequireAndVerifyClientCert, // ask for, require and verify a client cert
ClientCAs: clients,
NextProtos: []string{"h2", "http/1.1"},
},
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// r.TLS.PeerCertificates[0] is the verified client leaf.
w.Write([]byte("hello " + r.TLS.PeerCertificates[0].Subject.CommonName + "\n"))
}),
}
log.Fatal(srv.ListenAndServeTLS("server.pem", "server-key.pem"))
}Laravel behind a TLS-terminating proxy
The problem, from the Laravel docs: "When running your applications behind a load balancer that terminates TLS / SSL certificates, you may notice your application sometimes does not generate HTTPS links when using the url helper." The cause is layout A: the app only sees HTTP. The fix is to enable and configure TrustProxies in bootstrap/app.php so Laravel believes X-Forwarded-Proto, and optionally force the scheme.
<?php
// bootstrap/app.php (Laravel 13): the app sits behind a proxy that terminates TLS.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Trust only the proxy's address range, never '*' on an app that is also reachable directly.
// Then X-Forwarded-Proto=https makes $request->isSecure() true and url() generate https links.
$middleware->trustProxies(
at: ['10.0.0.0/8', '172.16.0.0/12'],
headers: Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO,
);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();<?php
declare(strict_types=1);
namespace App\Providers;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Fallback when the proxy does not send X-Forwarded-Proto: force https links in production.
// The real fix is trusting the proxy (bootstrap/app.php); this only changes generated URLs,
// it does not make $request->isSecure() true or fix secure-cookie decisions.
if ($this->app->isProduction()) {
URL::forceScheme('https');
}
}
}The difference: trustProxies makes $request->isSecure(), url(), redirects and secure-cookie decisions correct because the proxy said so; URL::forceScheme('https') only rewrites generated URLs. trustProxies(at: '*') is documented too, and is acceptable only when nothing except the proxy can reach the app (otherwise anyone can forge X-Forwarded-Proto and X-Forwarded-For). On Octane: the docs say that by default links are generated with an http:// prefix unless OCTANE_HTTPS is true in config/octane.php; in production the recommended shape is Octane behind Nginx or Apache, which "manage your SSL certificate termination"; with FrankenPHP (which is built on Caddy), the Sail example starts octane:start --https, and a custom --caddyfile is supported.
Calling a private-CA service from Laravel/PHP
Laravel's Http client wraps Guzzle; Guzzle's verify request option is true (system bundle), a string (path to a CA bundle) or false (no verification), and Http::withOptions([...]) passes it through. Client certificates use cert and ssl_key.
<?php
declare(strict_types=1);
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
/**
* Calling an internal HTTPS service whose certificate comes from a private CA.
* "verify" is a Guzzle request option: true = system bundle, string = CA file, false = no checks.
*/
final class OutboundHttps
{
/** Trust ONE private CA file for this client only; hostname and expiry are still verified. */
public function internalClient(): PendingRequest
{
return Http::withOptions([
'verify' => config('services.internal.ca_file', '/etc/ssl/internal/ca.crt'),
])->baseUrl('https://billing.internal.example.com')
->timeout(5)
->acceptJson();
}
/** Mutual TLS: present a client certificate (the service-to-service design is in system-design). */
public function mtlsClient(): PendingRequest
{
return Http::withOptions([
'verify' => '/etc/ssl/internal/ca.crt',
'cert' => '/etc/ssl/client/tls.crt',
'ssl_key' => '/etc/ssl/client/tls.key',
])->baseUrl('https://ledger.internal.example.com');
}
/**
* Local development only. Never ship this: it accepts ANY certificate, so a man in the middle
* is invisible. Prefer trusting the local CA (mkcert) over switching verification off.
*/
public function insecureForLocalOnly(): PendingRequest
{
abort_if(app()->isProduction(), 500, 'TLS verification must not be disabled in production');
return Http::withOptions(['verify' => false]);
}
}For PHP as a whole, set the trust once instead of per call:
; php.ini: used by the openssl extension and streams (file_get_contents, fsockopen ssl://)
openssl.cafile=/etc/ssl/certs/ca-certificates.crt
; openssl.capath=/etc/ssl/certs ; searched if cafile is not specified or does not match
; used by the cURL extension (and therefore by Guzzle's default handler)
curl.cainfo=/etc/ssl/certs/ca-certificates.crtThe PHP manual says that if cafile is not specified or the certificate is not found there, the directory in capath is searched. The Guzzle documentation adds that a CA bundle on disk plus openssl.cafile lets you omit the verify option. In a Docker image for PHP, the ca-certificates package and update-ca-certificates usually give you both.
A PHP certificate inspector
<?php
declare(strict_types=1);
namespace App\Support;
use RuntimeException;
/**
* A tiny "openssl s_client" in PHP: connect, send SNI, capture the chain the server presented.
* Needs the openssl extension. Verification is switched OFF on purpose, because the goal is to
* LOOK at a possibly broken certificate; never use this result to decide whether to trust a peer.
*/
final class CertInspector
{
/** @return list<array{subject: string, issuer: string, valid_to: string, san: string}> */
public function chain(string $host, int $port = 443, ?string $sni = null): array
{
$ctx = stream_context_create(['ssl' => [
'peer_name' => $sni ?? $host, // sent as SNI and used for hostname checks
'SNI_enabled' => true,
'verify_peer' => false,
'verify_peer_name' => false,
'capture_peer_cert_chain' => true,
]]);
$errno = 0;
$errstr = '';
$socket = @stream_socket_client(
"ssl://{$host}:{$port}", $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $ctx
);
if ($socket === false) {
throw new RuntimeException("connect failed: {$errstr} ({$errno})");
}
$params = stream_context_get_params($socket);
fclose($socket);
$out = [];
foreach ($params['options']['ssl']['peer_certificate_chain'] ?? [] as $cert) {
$info = openssl_x509_parse($cert);
$out[] = [
'subject' => $info['name'] ?? '',
'issuer' => implode(',', array_map(
fn ($k, $v) => "{$k}={$v}", array_keys($info['issuer'] ?? []), $info['issuer'] ?? []
)),
'valid_to' => date('Y-m-d', $info['validTo_time_t'] ?? 0),
'san' => $info['extensions']['subjectAltName'] ?? '',
];
}
return $out;
}
}It uses the stream context options peer_name (sent as SNI and used for name checks), verify_peer and verify_peer_name (off, because this tool inspects), and capture_peer_cert_chain, then openssl_x509_parse. These PHP files were reviewed by reading, not executed: php is not installed on this machine and the php:8.4-cli image could not be pulled during the run.
Expiry monitoring
# exit 0 if the certificate is valid for at least 14 more days, else exit 1 (works in any cron or CI job)
echo | openssl s_client -connect shop.example.com:443 -servername shop.example.com 2>/dev/null \
| openssl x509 -noout -checkend $((14*24*3600))-checkend N prints “Certificate will expire” and exits 1 when the certificate expires within N seconds. The Go tool inspectcert prints days left per certificate; Prometheus users run the blackbox_exporter TLS probe (probe_ssl_earliest_cert_expiry).
HTTP/2 and gRPC: the ALPN mismatch
HTTP/2 over TLS needs ALPN h2; gRPC always does. If the server (or a proxy in front) does not list h2, the client fails with an alert, measured here: a client offering only h3 to the lab server gets tlsv1 alert no application protocol (alert 120) and No ALPN negotiated; HTTP/1.1-only proxies make gRPC fail the same way. Check with openssl s_client -alpn h2 ... | grep ALPN and in Go with NextProtos on both sides. In Go's net/http, ListenAndServeTLS enables HTTP/2 by itself; the documentation of Server.TLSNextProto says that if it is not nil, HTTP/2 is not enabled automatically (newer Go versions also have Server.Protocols), and when you wrap your own listener with tls.NewListener you must put h2 in NextProtos yourself.
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Public website, single host | Caddy (auto-TLS) or certbot + nginx | Alert at 14 days to expiry; HSTS after it is stable | Automation removes the human |
| Public site on Kubernetes | Ingress or Gateway + cert-manager ACME | Staging issuer first; renewBefore of a third of the lifetime | Declarative, renewals visible |
| Wildcard names or no inbound port 80 | DNS-01 | Narrow API token or CNAME delegation | HTTP-01 cannot do wildcards |
| Internal services inside a cluster | Private CA (cert-manager ca issuer, Vault, step-ca) | Short-lived leaves, automatic reload, mTLS | Public CAs cannot issue internal names |
| Developer laptop | mkcert | Never share the root key; .gitignore the certs | Zero warnings, no ACME |
| Container calling HTTPS APIs | Base image with ca-certificates | Verify with the container's own tool | Fixes unknown authority at the source |
| gRPC or client-certificate requirement | End-to-end TLS (layout C or E) or a mesh | ALPN h2, ClientAuth | A terminating HTTP/1.1 proxy breaks it |
| Compliance wants encryption inside the VPC | Terminate and re-encrypt (layout B) or mesh | Internal CA, short lifetimes | The hop to the app is encrypted too |
| Latency-sensitive mobile API | TLS 1.3, tickets, shared ticket keys | 0-RTT only for idempotent GETs | Fewer round trips |
| Database connections | TLS with verify-full and a CA file | ssl_min_protocol_version, pg_stat_ssl check | require does not authenticate the server |
| Quick debugging against a self-signed server | --cacert with that server's cert or CA | Not -k | Keeps name and chain checks |
In architecture: from a single process to a distributed system
Monolith (one process, one host) Important
Everyday example: a small Laravel shop on one VPS. Caddy on the same machine takes ports 80 and 443, gets a Let's Encrypt certificate for shop.example.com, redirects HTTP, and proxies to PHP-FPM or Octane on localhost. TLS terminates at Caddy (layout A); the app trusts X-Forwarded-Proto from 127.0.0.1 only. State to protect: Caddy's /data directory. Production example: a Go API with ListenAndServeTLS behind a cloud load balancer that terminates with an ACM certificate (layout A) while the instance itself serves a private certificate on the internal port (layout B) for the “encrypted in transit” audit.
Failure modes here: forgotten renewal (alert on expiry), the proxy trusted too broadly, and curl -k in the deploy script.
Modular monolith and several processes Good to know
Everyday example: the same shop now has a web process, a queue worker and a scheduler in separate containers. Only the web process faces the internet, so only it needs a public certificate; workers call the payment provider over public HTTPS and need a CA bundle in the image. Production example: an internal admin module on admin.shop.internal with a certificate from the company's private CA. Everything that calls it (the monolith's HTTP client, a reporting job in Go) must trust that root: a single internal-ca.pem mounted into every image, referenced as verify in Guzzle and RootCAs in Go, instead of per-service copies. Boundaries: one owner for the CA file, one place to rotate it.
Microservices Important
Everyday example: web, payments and inventory services in Kubernetes. Each has a Certificate from the internal-ca ClusterIssuer, a tls Secret mounted without subPath, reloadcert-style reloading, and calls peers as https://payments.shop.svc.cluster.local (the name is in the SAN, see Hostname verification). Production example: a payments platform with mTLS between services: ClientAuth: RequireAndVerifyClientCert, client certificates with clientAuth EKU, 24-hour lifetimes, SPIFFE-style identities in the SAN, and authorization decisions made from the verified peer certificate. The request flow: edge Gateway terminates the public certificate (layout A or B), the sidecar or the app does mTLS to the next hop, every hop re-verifies. The design questions (identity, rotation, revocation) are in mTLS & Service Security and Cryptography, TLS, PKI & Secrets; this chapter gives you the wire view to debug them: which side sent which certificate, which ALPN was negotiated, why the handshake failed.
What does not survive a service boundary: a client's original certificate when an intermediate proxy terminates TLS (carry the identity in a signed header or use passthrough), and plaintext assumptions (X-Forwarded-* from an untrusted peer).
Distributed: replicas, caches, regions, CDNs Important
Everyday example: the shop sits behind a CDN. The CDN terminates the visitor's TLS with its own certificate and opens a second TLS connection to the origin (layout B). The origin certificate can come from a private CA or a short-lived origin certificate, and "Full (strict)" style modes mean the CDN verifies it. Production example: several regions behind anycast edges; each region's load balancers share session ticket keys so a client that reconnects to another region resumes instead of doing a full handshake, and 0-RTT is limited to idempotent GETs with a shared or per-region anti-replay policy. Database replicas are reached with sslmode=verify-full and a CA file; replicas and caches (Redis with TLS) need their own certificates with SANs for every name clients use (including headless service names).
Where it breaks: clock drift (a node with a wrong date reports “not yet valid”), certificates renewed in one region but not another, CT or ACME rate limits when many regions request the same names (use one issuing cluster and distribute, or a wildcard), and connection storms after a certificate change (full handshakes at once: stagger restarts).
Scaling path
| Scale | TLS design | What to add |
|---|---|---|
| 1x: one host | Caddy or certbot, public CA | Expiry alert; state volume backup |
| 10x: a few hosts and a load balancer | Cloud LB or proxy terminates; app behind it | Trusted-proxy config; shared ticket keys; health checks with SNI |
| 100x: Kubernetes, many services | cert-manager, private CA for internal, public CA at the edge | Reloading apps, mesh or mTLS, Certificate Transparency monitoring, rate-limit planning (wildcards, one issuer) |
| Multi-region or many tenants | Per-tenant certificates via ACME on demand, edge termination, regional ticket-key sharing | A certificate inventory, staged rollouts of CA rotation, short lifetimes (45 days is coming) |
Lab
Everything below was run on 2026-11-25 on macOS with Homebrew OpenSSL 3.6.4, Go 1.27.4, mkcert and Docker Desktop (steps 1 to 6; step 7 was not applied). Use openssl from Homebrew (/opt/homebrew/opt/openssl@3/bin/openssl), not the system LibreSSL. Snippets live in docs/snippets/foundations/tls-in-practice/.
1. Build a private CA and two leaves with openssl
mkdir pki && cd pki && export PKI=$PWD # every later step refers to $PKI
openssl ecparam -name prime256v1 -genkey -noout -out root-key.pem
openssl req -x509 -new -key root-key.pem -sha256 -days 3650 -subj "/O=Academy Lab/CN=Academy Lab Root CA" \
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out root.pem
openssl ecparam -name prime256v1 -genkey -noout -out int-key.pem
openssl req -new -key int-key.pem -subj "/O=Academy Lab/CN=Academy Lab Issuing CA" -out int.csr
printf 'basicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n' > int.ext
openssl x509 -req -in int.csr -CA root.pem -CAkey root-key.pem -CAcreateserial -days 1825 -sha256 -extfile int.ext -out int.pem
for h in a b; do
openssl ecparam -name prime256v1 -genkey -noout -out $h.test-key.pem
openssl req -new -key $h.test-key.pem -subj "/CN=$h.test" -out $h.csr
printf "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:$h.test,DNS:www.$h.test\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n" > $h.ext
openssl x509 -req -in $h.csr -CA int.pem -CAkey int-key.pem -CAcreateserial -days 90 -sha256 -extfile $h.ext -out $h.test-leaf.pem
cat $h.test-leaf.pem int.pem > $h.test.pem # leaf first, then the intermediate
done
openssl verify -CAfile root.pem -untrusted int.pem a.test-leaf.pem # a.test-leaf.pem: OK
openssl verify -CAfile root.pem a.test-leaf.pem # error 20 ... unable to get local issuer certificateExpected: a.test-leaf.pem: OK with the intermediate supplied, and error 20 at 0 depth lookup: unable to get local issuer certificate without it. That second command is the missing-intermediate failure in one line.
2. The same with mkcert (without touching your trust store)
go install filippo.io/mkcert@latest
mkdir -p mk/caroot && cd mk && export CAROOT=$PWD/caroot
mkcert -cert-file a.test.pem -key-file a.test-key.pem a.test "*.a.test" localhost 127.0.0.1 ::1
openssl x509 -in a.test.pem -noout -subject -issuer -ext subjectAltName -dates
# add `mkcert -install` only when you really want your OS and browsers to trust it3. Run the Go SNI server for two hosts and inspect it
cd docs/snippets/foundations/tls-in-practice/go
go run ./sniserver -addr 127.0.0.1:8443 -certs $PKI & # directory with a.test.pem, a.test-key.pem, b.test.pem, ...
sleep 2
openssl s_client -connect 127.0.0.1:8443 -servername a.test -CAfile $PKI/root.pem -showcerts </dev/null | head -40
openssl s_client -connect 127.0.0.1:8443 -servername b.test -CAfile $PKI/root.pem </dev/null | grep subject= # subject=CN=b.test
openssl s_client -connect 127.0.0.1:8443 -servername nope.test -CAfile $PKI/root.pem -verify_hostname nope.test </dev/null | grep -E "verify error|Verify return"
curl -v --resolve a.test:8443:127.0.0.1 --cacert $PKI/root.pem https://a.test:8443/
go run ./tlsdial -connect 127.0.0.1:8443 -servername a.test -CAfile $PKI/root.pem
go run ./clienthelloExpected: subject=CN=b.test for the second; verify error:num=62:hostname mismatch for the third; curl prints ALPN: server accepted h2 and host=a.test:8443 proto=HTTP/2.0 tls=TLS 1.3 alpn="h2" sni="a.test"; tlsdial prints TLS 1.3, two certificates and verified chains: 1; clienthello prints a record of about 1,500 bytes with host_name="example.test".
4. Break the chain and read the error
export BROKEN=$PKI/../broken && mkdir -p $BROKEN
cp $PKI/a.test-leaf.pem $BROKEN/a.test.pem && cp $PKI/a.test-key.pem $BROKEN/a.test-key.pem
cp $PKI/b.test-leaf.pem $BROKEN/b.test.pem && cp $PKI/b.test-key.pem $BROKEN/b.test-key.pem
go run ./sniserver -addr 127.0.0.1:8444 -certs $BROKEN &
sleep 2
openssl s_client -connect 127.0.0.1:8444 -servername a.test -CAfile $PKI/root.pem </dev/null | grep -E "verify error|Verify return"
# verify error:num=20:unable to get local issuer certificate / num=21:unable to verify the first certificate
curl --resolve a.test:8444:127.0.0.1 --cacert $PKI/root.pem https://a.test:8444/ # curl: (60) ... unable to get local issuer certificate
go run ./tlsdial -connect 127.0.0.1:8444 -servername a.test -CAfile $PKI/root.pem # x509: certificate signed by unknown authority
# fix: put the intermediate back (cat leaf int > a.test.pem) and restart; Verify return code: 0 (ok)
# also try an expired certificate: openssl x509 -req ... -not_before 20260101000000Z -not_after 20260201000000Z5. Caddy auto-TLS in Compose
cd docs/snippets/foundations/tls-in-practice/deploy
docker compose up -d # caddy + whoami + a curl probe; publishes host ports 443 and 80, so change them if those are taken
docker compose exec probe curl -sS https://app.lab.test/ # (60) unable to get local issuer certificate
docker compose exec probe curl -sS --cacert /caddy-data/caddy/pki/authorities/local/root.crt https://app.lab.test/
docker compose exec probe curl -sI http://app.lab.test/ # 308 Permanent Redirect to https
docker compose down -vExpected: the first fails with error 60, the second returns the whoami text with GET / HTTP/1.1 (the app saw plaintext), the third shows the redirect. The compose file publishes 443 and 80; on a machine where they are used, change them to other host ports (the lab used 18443 and 18080).
6. Static Go binary in scratch versus with a CA bundle
cd docs/snippets/foundations/tls-in-practice/go
mkdir -p /tmp/tlsimg && CGO_ENABLED=0 GOOS=linux go build -o /tmp/tlsimg/tlsdial ./tlsdial # add GOARCH=amd64 on an Intel host
cat > /tmp/tlsimg/Dockerfile.scratch <<'EOF'
FROM scratch
COPY tlsdial /tlsdial
ENTRYPOINT ["/tlsdial"]
EOF
cat > /tmp/tlsimg/Dockerfile.ca <<'EOF'
FROM alpine:3 AS certs
RUN apk add --no-cache ca-certificates
FROM scratch
COPY --from=certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY tlsdial /tlsdial
ENTRYPOINT ["/tlsdial"]
EOF
docker build -f /tmp/tlsimg/Dockerfile.scratch -t tls-scratch /tmp/tlsimg && docker run --rm tls-scratch -connect example.com:443
# handshake failed: tls: failed to verify certificate: x509: certificate signed by unknown authority
docker build -f /tmp/tlsimg/Dockerfile.ca -t tls-withca /tmp/tlsimg && docker run --rm tls-withca -connect example.com:443
# version : TLS 1.3 ... verified chains: 17. cert-manager manifests (compile-only here)
deploy/cert-manager.yaml, ingress-tls.yaml and tls-secret-and-mounts.yaml were checked with a YAML parser only (Ruby YAML.load_stream listed the expected kinds), not applied: no Kubernetes cluster was available. To run them: create a kind cluster, install cert-manager, kubectl apply -f cert-manager.yaml, then kubectl get certificate -A and kubectl describe certificate api-internal -n shop; kubectl get secret api-internal-tls -n shop -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -subject -dates -ext subjectAltName shows what was issued.
Clean up background servers when you finish (pkill -f sniserver).
Common misconceptions
| Belief | Reality |
|---|---|
| HTTPS means the site is trustworthy | It means the channel to that name is private and authenticated; the site's intent is not checked |
| The padlock error means weak encryption | It almost always means a trust, name or date problem |
| It works in Chrome, so the server is fine | Browsers cache and sometimes fetch intermediates; curl, Go and OpenSSL do not (we tested AIA) |
-k is only for testing, so it is safe | It removes the chain and the hostname check and tends to reach production |
| The CN is the hostname | Clients match the SAN; Go ignores the CN, and RFC 6125 allows the CN only as a last resort when there is no SAN |
| A certificate contains the secret | It contains the public key; the private key never leaves the server |
| TLS hides which site I visit | The IP and the SNI are visible unless Encrypted Client Hello is used |
| Installing the CA on my laptop makes my containers trust it | Each container has its own trust store |
| Self-signed is insecure by definition | It is as secure as the distribution of the pin; the issue is operations |
| Let's Encrypt certificates are valid for 90 days forever | 90 days today; 64 days from 2027-02-10 and 45 days from 2028-02-16 per the CA's announcement |
| TLS 1.2 is broken | 1.2 with ECDHE and AEAD is acceptable; 1.0 and 1.1 are deprecated (RFC 8996) |
| 0-RTT is free speed | Early data can be replayed; only idempotent requests are safe |
| Kubernetes Secrets are encrypted | By default they are stored unencrypted in etcd, base64 is encoding |
| Terminating at the load balancer means encrypted end to end | Only up to the balancer, unless you re-encrypt |
SSL_CERT_FILE means “trust only this file” in Go | It changes where roots are read from; directories are still read, as measured |
Cheat sheet
| Topic | What to remember |
|---|---|
| Handshake 1.3 | ClientHello (SNI, ALPN, key_share) then ServerHello; everything after is encrypted; 1 RTT |
| Handshake 1.2 | Two round trips; certificate in clear; ECDHE for forward secrecy; static RSA is deprecated |
| Cipher suite name | 1.2: TLS_<kx>_<auth>_WITH_<cipher>_<hash>; 1.3: only cipher and hash |
| Certificate | Subject, SAN, issuer, validity, key usage, EKU, serial, signature; match names against SAN |
| PEM vs DER | PEM = Base64 DER between BEGIN/END lines; openssl x509 -text decodes both |
| Chain | Send leaf then intermediates (fullchain.pem); never rely on AIA or the browser |
| Trust store | Each client has its own: OS, Firefox NSS, Java cacerts, Go on Linux files and dirs, PHP openssl.cafile and curl.cainfo |
| Docker | scratch needs a CA bundle; secrets as files, not env vars; keys not in layers |
| Kubernetes | kubernetes.io/tls Secret with tls.crt/tls.key; cert-manager renews; no subPath for rotation |
| ACME | HTTP-01 (port 80), DNS-01 (wildcards), TLS-ALPN-01 (port 443); staging first; 50/week/domain, 5/week/same set |
| Lifetimes | 90 days now, 64 from 2027-02-10, 45 from 2028-02-16 (Let's Encrypt classic); renew at two thirds |
| mkcert | Local CA; mkcert -install once; root key is a skeleton key |
| Debug | openssl s_client -connect h:443 -servername h -showcerts; add -verify_hostname; curl -v --cacert |
| Errors | unknown authority = trust or missing intermediate; hostname mismatch = SAN; expired = renewal |
| Behind a proxy | Trust forwarded headers (Laravel trustProxies); URL::forceScheme only fixes links |
| Never | -k, InsecureSkipVerify, verify => false outside tests; private keys in git or images |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Which TLS 1.3 messages are sent in plaintext, and which are encrypted? Good to know
Answer
Answer: ClientHello and ServerHello are plaintext. EncryptedExtensions, Certificate, CertificateVerify and both Finished messages (and later NewSessionTicket) are encrypted. That is why a passive observer sees the SNI but not the certificate.
2 — Why does a server need SNI to choose a certificate, and what is served when the client sends none? Important
Answer
Answer: The HTTP Host header is inside the encrypted stream, so the server needs the name in the first message. With no SNI (or an unknown one) it serves its default certificate, which then fails the hostname check, as our lab server showed with nope.test and -noservername.
3 — Decode TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 and say what is different in TLS_AES_128_GCM_SHA256. Good to know
Answer
Answer: ECDHE key exchange, RSA certificate authentication, AES-128 in GCM mode for the data, SHA-256 for the PRF. The TLS 1.3 name carries only the AEAD cipher and the hash; key exchange and signatures are negotiated separately.
4 — A site works in Chrome but curl says unable to get local issuer certificate. What is the likely cause and the test? Must-know
Answer
Answer: The server omits the intermediate. openssl s_client -connect host:443 -servername host -showcerts shows only the leaf (Verify return code: 21). The fix is to serve fullchain.pem; AIA fetching is not done by curl, OpenSSL or Go, as we measured.
5 — Why does openssl s_client print Verification: OK for a wrong hostname, and how do you make it check? Important
Answer
Answer: It validates the chain but not the name unless you pass -verify_hostname name (or -verify_ip). Then it fails with num=62:hostname mismatch.
6 — A static Go binary in FROM scratch fails every HTTPS call. Why, and what are two fixes? Important
Answer
Answer: The image has no trust store (x509: certificate signed by unknown authority). Copy ca-certificates.crt into /etc/ssl/certs/ in the image, or use a base image that includes it; building a pool in code with x509.NewCertPool and AppendCertsFromPEM from an embedded file also works.
7 — Which ACME challenge do you need for *.example.com, and which port does HTTP-01 use? Important
Answer
Answer: DNS-01 (HTTP-01 and TLS-ALPN-01 cannot issue wildcards). HTTP-01 uses port 80 only.
8 — What does 0-RTT risk, and what must the server do? Good to know
Answer
Answer: Early data can be replayed by an attacker who captured it and has no forward secrecy. Only accept it for idempotent requests, pass Early-Data: 1 upstream, and keep it off for anything with side effects.
9 — Your Laravel app behind an ALB generates http:// links. What do you configure, and what does URL::forceScheme not fix? Must-know
Answer
Answer: Enable trustProxies for the balancer's address range with X-Forwarded-Proto. URL::forceScheme('https') only changes generated URLs; isSecure() and cookie behaviour still depend on trusted proxies.
10 — Why must a Kubernetes TLS Secret not be mounted with subPath if you rely on rotation, and how does the app notice a new file? Important
Answer
Answer: The kubelet updates Secret volumes in place but a subPath mount does not receive updates. The app should re-read the files (for example GetCertificate with a modtime check, as in reloadcert) or be restarted by a reloader.
11 — Which Let's Encrypt limit do you hit by redeploying and re-requesting the same certificate six times in a week? Good to know
Answer
Answer: New certificates per exact set of identifiers: 5 per 7 days (refill 1 per 34 hours). Persist the ACME state and test against staging.
Glossary
| Term | Meaning |
|---|---|
| TLS (Transport Layer Security) | Protocol that gives a TCP connection confidentiality, integrity and an authenticated server |
| Handshake | The messages that agree versions, suites and keys and authenticate the server |
| ClientHello / ServerHello | First two handshake messages: client offers, server chooses |
| Record | The unit TLS sends: a 5-byte header (type, legacy version, length) plus payload |
| SNI (Server Name Indication) | ClientHello extension 0 carrying the requested hostname (RFC 6066) |
| ALPN | Extension 16 to negotiate the application protocol: h2, http/1.1, acme-tls/1 (RFC 7301) |
| key_share | Extension carrying the client's (and server's) ephemeral public key for the key exchange |
| ECDHE / X25519 | Ephemeral elliptic-curve Diffie-Hellman; X25519 is the common curve |
| X25519MLKEM768 | Hybrid post-quantum key exchange (group 0x11ec) offered by current Go, OpenSSL 3.6 and browsers |
| Forward secrecy | Past sessions stay secret even if the long-term key leaks later |
| Cipher suite | The named combination of algorithms negotiated for a connection |
| AEAD | Authenticated encryption with associated data, such as AES-GCM and ChaCha20-Poly1305 |
| PSK / session ticket | Pre-shared key from a previous session, carried in a ticket for resumption |
| 0-RTT / early data | Application data sent in the first flight on resumption; replayable |
| X.509 | The certificate format (RFC 5280) |
| SAN (Subject Alternative Name) | The list of DNS names and IP addresses a certificate is valid for |
| CN (Common Name) | Legacy subject field; ignored by modern clients for hostname checks |
| Issuer / Subject | Who signed the certificate / who the certificate is for |
| Key Usage / EKU | Allowed operations (signing, key encipherment) / allowed roles (serverAuth, clientAuth) |
| Basic Constraints / pathlen | Whether the certificate may sign others and how deep a chain may go |
| PEM / DER | Base64 text with BEGIN/END lines / the binary ASN.1 encoding |
| CSR | Certificate signing request: public key and requested names, signed by the key holder |
| Leaf / Intermediate / Root | End-entity certificate / issuing CA below the root / self-signed trust anchor |
| Chain / fullchain.pem | Leaf plus intermediates in order; what a server should send |
| AIA | Authority Information Access: URLs for the issuer certificate and OCSP |
| Trust store | The set of root certificates a client trusts |
| Trust anchor | A certificate trusted directly, normally a root |
| Self-signed | A certificate signed by its own key |
| Private CA | A CA you run and distribute yourself |
| ACME | Protocol (RFC 8555) to prove domain control and obtain certificates automatically |
| HTTP-01 / DNS-01 / TLS-ALPN-01 | The ACME challenge types |
| ARI | ACME Renewal Information: the CA tells clients when to renew |
| Rate limit | CA-side cap on issuance, such as 50 certificates per registered domain per week |
| mkcert | Tool that creates a local CA and trusted development certificates |
| HSTS | Header that makes browsers use HTTPS only for a site (RFC 6797) |
| OCSP / stapling | Online revocation check / the server attaching a fresh signed response |
| CT / SCT | Certificate Transparency logs / the signed timestamp embedded in a certificate (RFC 9162) |
| Termination / passthrough | Decrypting TLS at a proxy / forwarding the TLS stream untouched |
| mTLS | Mutual TLS: the client also presents a certificate |
| cert-manager | Kubernetes controller that issues and renews certificates via Issuer and Certificate resources |
kubernetes.io/tls | Secret type holding tls.crt and tls.key |
References
Fetched and read on 2026-11-25; every link below returned HTTP 200 on that date.
- RFC 8446, The Transport Layer Security (TLS) Protocol Version 1.3: https://www.rfc-editor.org/rfc/rfc8446
- RFC 5246, TLS 1.2: https://www.rfc-editor.org/rfc/rfc5246
- RFC 8996, Deprecating TLS 1.0 and TLS 1.1: https://www.rfc-editor.org/rfc/rfc8996
- RFC 9325, Recommendations for Secure Use of TLS and DTLS: https://www.rfc-editor.org/rfc/rfc9325
- RFC 6066, TLS Extensions (SNI): https://www.rfc-editor.org/rfc/rfc6066
- RFC 7301, ALPN: https://www.rfc-editor.org/rfc/rfc7301
- RFC 5280, Internet X.509 PKI Certificate and CRL Profile: https://www.rfc-editor.org/rfc/rfc5280
- RFC 6125, Representation and Verification of Domain-Based Application Service Identity: https://www.rfc-editor.org/rfc/rfc6125
- RFC 7468, Textual Encodings of PKIX Structures (PEM): https://www.rfc-editor.org/rfc/rfc7468
- RFC 8555, ACME: https://www.rfc-editor.org/rfc/rfc8555
- RFC 8737, ACME TLS-ALPN-01: https://www.rfc-editor.org/rfc/rfc8737
- RFC 6797, HSTS: https://www.rfc-editor.org/rfc/rfc6797
- RFC 9162, Certificate Transparency Version 2.0: https://www.rfc-editor.org/rfc/rfc9162
- OpenSSL
s_clientmanual: https://docs.openssl.org/3.0/man1/openssl-s_client/ - mkcert README: https://github.com/FiloSottile/mkcert
- Go source and documentation (read with
go doc crypto/tls,go doc crypto/x509,go doc net/http/httptest; pkg.go.dev refuses plaincurl): https://github.com/golang/go/tree/master/src/crypto/tls, https://github.com/golang/go/tree/master/src/crypto/x509, https://github.com/golang/go/tree/master/src/net/http/httptest - Let's Encrypt: Rate limits, Challenge types, Decreasing Certificate Lifetimes to 45 Days, Ending OCSP Support in 2025
- Caddy Automatic HTTPS: https://caddyserver.com/docs/automatic-https ; certbot: https://eff-certbot.readthedocs.io/en/stable/using.html; Traefik ACME: https://doc.traefik.io/traefik/reference/install-configuration/tls/certificate-resolvers/acme/
- curl SSL CA certificates: https://curl.se/docs/sslcerts.html; everything curl, SSLKEYLOGFILE: https://everything.curl.dev/usingcurl/tls/sslkeylogfile.html; Wireshark TLS: https://wiki.wireshark.org/TLS
- PHP
openssl.cafile: https://www.php.net/manual/en/openssl.configuration.php;curl.cainfo: https://www.php.net/manual/en/curl.configuration.php; Guzzle request options: https://docs.guzzlephp.org/en/stable/request-options.html - Laravel 13: HTTP client, Requests (trusting proxies), URL generation, Octane; API: UrlGenerator
- Kubernetes: Secrets, Ingress; Gateway API TLS; cert-manager: Certificate, ACME, Ingress, Gateway
- Docker Compose secrets: https://docs.docker.com/compose/how-tos/use-secrets/
- PostgreSQL: libpq SSL support, pg_stat_ssl
- Siblings: Cryptography Fundamentals, Network Models, Docker Networking, Kubernetes Networking, Cryptography, TLS, PKI & Secrets, mTLS & Service Security, HTTP/2, HTTPS, TLS & mTLS in Go