Python · SQL · Web Dev · Java · AI/ML tracks launching soon — your one platform for all of IT

TLS/SSL

How the internet encrypts a trillion connections per day — from the math of Diffie-Hellman to the politics of certificate authorities.

28–38 min May 2026

// Chapter 1

The Eavesdropping Problem

Story

2010. You're in a coffee shop, checking your bank balance over the WiFi. You don't know it, but the person at the next table is running Wireshark. Every packet you send — login form, cookie, balance response — is plaintext HTTP, visible to anyone who cares to look. This is not theoretical. The free tool Firesheep was released that year and let anyone hijack Facebook sessions on public WiFi with a single click. A million users were compromised in days.

The web had a problem: two computers could talk to each other, but could not talk privately. HTTP, DNS, SMTP — the entire application layer was built with the assumption that the network was trustworthy. It is not.

TLS is the protocol that fixes this. It does three things at once: confidentiality (no one can read your data), integrity (no one can modify it), and authentication (you know who you're talking to). Understanding TLS means understanding one of the most mathematically elegant engineering solutions in computer science.

TLS runs below the application layer and above TCP. It is transparent to HTTP, FTP, SMTP — any protocol that needs a secure channel simply wraps its connection in TLS. The "S" in HTTPS, FTPS, SMTPS, and IMAPS is always TLS.

Why Not Just Encrypt Everything with a Password?

The fundamental challenge of secure communication is key distribution: if you encrypt data with a key, how does the other party get the key without an eavesdropper intercepting it? You can't send the key in plaintext. You can't encrypt the key with another key without infinite recursion. This seems unsolvable — and was considered an open problem in cryptography until the 1970s.

Wow

The Diffie-Hellman key exchange (1976) proved that two parties who have never communicated can establish a shared secret over a public channel, even with an eavesdropper recording every bit. This single insight made secure internet commerce possible. Whitfield Diffie and Martin Hellman received the Turing Award in 2015 for this discovery — nearly 40 years later.

The magic ingredient is mathematics: specifically, operations that are easy to compute in one direction and computationally infeasible to reverse. Discrete logarithms, elliptic curves, RSA factoring — these "trapdoor functions" let you publish information that reveals nothing about your secret.

# The Diffie-Hellman intuition (simplified, not real code):
# Agree publicly on: prime p=23, generator g=5

# Alice chooses secret a=6, sends A = g^a mod p = 5^6 mod 23 = 8
# Bob chooses secret b=15, sends B = g^b mod p = 5^15 mod 23 = 19

# Alice computes: B^a mod p = 19^6 mod 23 = 2   ← shared secret
# Bob computes:  A^b mod p = 8^15 mod 23 = 2    ← same shared secret
# Eve sees 8 and 19, but computing a from A = 5^a mod p requires
# solving the discrete log problem — infeasible for large primes

// Chapter 2

SSL to TLS: A Protocol History

SSL (Secure Sockets Layer) was invented by Netscape in 1994 to secure credit card transactions for their Netscape Commerce Server. It went through three major versions, each fixing critical flaws in the previous one. By the time SSL 3.0 was standardized, the IETF took over development and renamed it TLS (Transport Layer Security).

The Version Graveyard

SSL 2.0 (1995): Vulnerable to protocol downgrade attacks, weak MAC construction, susceptible to truncation attacks. Deprecated by RFC 6176 in 2011.

SSL 3.0 (1996): Widely deployed for years, then killed by POODLE (2014) — a padding oracle attack that allows recovery of plaintext. RFC 7568 prohibits SSL 3.0 in 2015.

TLS 1.0 (1999): RFC 2246. Essentially SSL 3.1 with minor changes. Vulnerable to BEAST (2011) and POODLE-TLS. PCI-DSS compliance required disabling it by June 2018. RFC 8996 deprecates it in 2021.

TLS 1.1 (2006): RFC 4346. Added protection against BEAST, fixed IV handling. Still deprecated by RFC 8996 in 2021 — not enough improvements to justify supporting it separately.

TLS 1.2 (2008): RFC 5246. Current baseline. Introduced AEAD cipher modes (GCM), removed MD5/SHA-1 from PRF, added elliptic curve support. Still supported and secure with modern cipher suites.

TLS 1.3 (2018): RFC 8446. Ten years in the making. Removed all broken/weak algorithms, reduced handshake from 2-RTT to 1-RTT, made forward secrecy mandatory, encrypted the certificate. The current gold standard.

Wow

TLS 1.3 development took four years and 28 drafts. The main obstacle was not technical — it was that middleboxes (corporate DPI appliances, network monitoring tools) relied on decrypting TLS traffic by knowing the server key. TLS 1.3's mandatory forward secrecy made this passive interception impossible. Enterprises lobbied heavily against adoption. The final RFC was published in August 2018.

Caution

As of 2024, TLS 1.0 and 1.1 are disabled in all major browsers. TLS 1.2 remains the minimum for broad compatibility. If you're configuring a server, set your minimum to TLS 1.2 with modern cipher suites, and prefer TLS 1.3. The ssl_protocols TLSv1.2 TLSv1.3; directive in Nginx is the standard production configuration.

# Check TLS support with openssl
openssl s_client -connect example.com:443 -tls1_3 </dev/null 2>&1 | grep "Protocol"
openssl s_client -connect example.com:443 -tls1_2 </dev/null 2>&1 | grep "Protocol"

# Check which protocols a server supports
nmap --script ssl-enum-ciphers -p 443 example.com

# Verify minimum TLS version in nginx config
grep ssl_protocols /etc/nginx/nginx.conf
# Expected: ssl_protocols TLSv1.2 TLSv1.3;

// Chapter 3

The TLS Handshake: Making a Secret in Public

Story

Imagine you need to pass a secret message to someone across a crowded room, but everyone in the room can hear everything you say. You can't whisper the key — anyone would hear it. So you do something clever: you each paint a can of paint with a public color, then add a secret color only you know. You swap the cans publicly. Then each of you adds your secret color to the can you received. Now both cans are the same color (public + Alice's secret + Bob's secret = public + Bob's secret + Alice's secret). No eavesdropper can determine the final color just by watching the exchange. This is Diffie-Hellman — and it's literally what TLS does mathematically.

The TLS handshake serves four purposes: agree on a protocol version, negotiate cipher suites, authenticate the server (and optionally the client), and derive symmetric session keys. The last point is important: TLS uses asymmetric cryptography only to establish keys, then switches to symmetric encryption (AES, ChaCha20) for data — because symmetric encryption is 1000x faster.

TLS Handshake Visualizer

Handshake latency: 1 RTT before first application byte — 0-RTT resumption is possible on subsequent connections
1.← CClientHelloRTT 1
2.S →ServerHelloRTT 1
3.S →EncryptedExtensionsRTT 1
4.S →CertificateRTT 1
5.S →CertificateVerifyRTT 1
6.S →FinishedRTT 1
7.← CFinishedRTT 2

Key Derivation: The PRF and HKDF

After the DH exchange, both sides have the same "pre-master secret." TLS mixes this with the client and server randoms through a Pseudo-Random Function (PRF) to derive distinct keys: client write key, server write key, client MAC key, server MAC key, and IVs. In TLS 1.3, this is replaced by HKDF (HMAC-based Key Derivation Function), which is cleaner and more formally analyzed.

The client and server randoms are crucial: they prevent replay attacks. Even if an attacker records a TLS session and the server's private key is later compromised, the randoms ensure that each session produces unique keys — this is Perfect Forward Secrecy.

# Watch TLS 1.3 handshake with Wireshark
# Filter: tls.handshake.type == 1  (ClientHello)
# Filter: tls.handshake.type == 2  (ServerHello)

# Decrypt TLS traffic (if you have the session key log):
# Set SSLKEYLOGFILE=/tmp/keys.log before starting browser
SSLKEYLOGFILE=/tmp/keys.log curl https://example.com
# Then in Wireshark: Edit → Preferences → TLS → (Pre)-Master-Secret log filename

# Inspect certificate with openssl
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -text -noout

// Chapter 4

TLS 1.3: Faster, Safer, Simpler

TLS 1.3 is not an incremental improvement — it's a near-complete redesign guided by a decade of cryptographic analysis. The design philosophy: remove everything that isn't provably necessary, eliminate all algorithm agility that allows downgrade attacks, and make the common case (ECDHE + AEAD) as fast as possible.

What Was Removed

TLS 1.3 eliminated: RSA key exchange (no PFS), DHE with finite-field groups (Logjam-vulnerable), CBC cipher modes (BEAST, POODLE, Lucky13, GOLDENDOODLE), RC4 (NOMORE), 3DES (SWEET32), MD5 and SHA-1 in signatures, compression (CRIME), renegotiation, non-AEAD cipher suites, and custom DH groups. The attack surface shrank dramatically.

1-RTT: The Latency Win

TLS 1.2 required 2 round trips before the first application byte could be sent. TLS 1.3 requires only 1. The trick: the ClientHello includes the key_share extension with the client's DH public key (guessing that ECDHE with P-256 or X25519 will be chosen). The server responds with its DH public key in the same flight, and both sides derive traffic keys immediately. The server can start sending encrypted application data before the client's Finished arrives.

Wow

TLS 1.3 also supports 0-RTT resumption: a returning client can send application data in the very first packet using a "pre-shared key" from a previous session. The server can process it before verifying the client Finished. This is a genuine cryptographic innovation — but comes with a tradeoff: 0-RTT data is vulnerable to replay attacks and must only be used for idempotent requests (GET, not POST).

Encrypted Extensions

In TLS 1.2, many extensions (including the server certificate) were sent in plaintext during the handshake. A passive eavesdropper could determine which certificate the server was using — revealing the site's identity. TLS 1.3 encrypts all extensions after the ServerHello, hiding the certificate from observers. This significantly improves privacy, though the server's IP and SNI (before Encrypted Client Hello) still reveal a lot.

Encrypted Client Hello (ECH, formerly ESNI) is a further extension being standardized to encrypt even the SNI in the ClientHello, hiding which hostname the client is connecting to from network observers. Cloudflare has deployed it in production for many zones.

# Check if TLS 1.3 is being used
curl -v --tls-max 1.3 https://example.com 2>&1 | grep "SSL connection"
# Expected: SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384

# Test 0-RTT support
openssl s_client -connect example.com:443 -tls1_3 -sess_out /tmp/sess.pem < /dev/null
openssl s_client -connect example.com:443 -tls1_3 -sess_in /tmp/sess.pem -early_data /dev/null

# Nginx TLS 1.3 configuration
# ssl_protocols TLSv1.2 TLSv1.3;
# ssl_early_data on;   # enables 0-RTT (add anti-replay protection!)

// Chapter 5

Certificate Chains and PKI

Story

In 2011, a Dutch certificate authority called DigiNotar was hacked. The attackers issued fraudulent certificates for *.google.com, *.mozilla.com, *.microsoft.com, and 500 other domains. Iranian users were being silently man-in-the-middled — their "secure" HTTPS connections to Gmail were actually being intercepted. By the time Mozilla and Google pushed updates to distrust DigiNotar, thousands of users had been surveilled. DigiNotar declared bankruptcy within weeks. The incident illustrates the systemic vulnerability in PKI: trust is only as strong as the weakest CA.

Public Key Infrastructure (PKI) solves the authentication problem: how does your browser know that the certificate for bank.com actually belongs to bank.com and wasn't created by an attacker? The answer is a chain of trust: a hierarchy of Certificate Authorities (CAs) whose root certificates are pre-installed in operating systems and browsers.

Certificate Chain Explorer

Root CA

CN=ISRG Root X1

signs

Intermediate CA

CN=R3

signs

Leaf Certificate

CN=example.com

Leaf Certificate — Fields

SubjectCN=example.com
IssuerR3, Let's Encrypt
Valid From2024-01-15
Valid To2024-04-15
Public KeyECDSA P-256
Key UsageDigital Signature, Key Encipherment
SANDNS: example.com, DNS: www.example.com
Self-SignedNo

Leaf cert proves server identity. 90-day validity forces regular renewal. SANs list all valid domain names.

X.509 Certificate Fields

Every TLS certificate is an X.509 v3 certificate containing: Subject (who this cert identifies), Issuer (who signed it), Validity Period (not before/not after), Public Key (the subject's public key), Extensions (Subject Alternative Names, Key Usage, Extended Key Usage, CA:TRUE/FALSE, OCSP URL), and the CA's Signature (cryptographic proof that the CA approved this certificate).

How Browsers Verify Certificates

When your browser receives a certificate chain, it:

1. Verifies each certificate's signature using the issuer's public key

2. Checks validity periods (not before/not after)

3. Confirms the chain terminates at a trusted root in the OS/browser trust store

4. Checks the certificate's subjectAltName extension includes the hostname you're connecting to

5. Checks revocation status via OCSP or CRL

6. Verifies the leaf cert has the extendedKeyUsage for TLS Web Server Authentication

Caution

Let's Encrypt certificates expire in 90 days by design — short validity forces automation and limits the damage window if a key is compromised. If you're running your own servers, use certbot or acme.sh for automatic renewal via cron. A Let's Encrypt cert expiring in production is an entirely preventable outage.

Certificate Revocation: OCSP and CRL

When a private key is compromised, the CA must revoke the certificate. Two mechanisms exist: CRL (Certificate Revocation List) — a periodically-published list of serial numbers, large and slow to download. OCSP (Online Certificate Status Protocol) — a real-time query to the CA asking "is this cert revoked?" OCSP stapling improves this: the server pre-fetches its own OCSP response and includes it in the TLS handshake, avoiding the extra round trip and privacy leak.

Wow

In 2020, Apple announced that Safari would cap certificate validity at 398 days (13 months). Any cert issued after September 1, 2020 with a longer validity would be rejected — regardless of CA. This was a unilateral policy change by Apple enforced through browser behavior, not IETF standards. The industry followed. Effective certificate maximal validity in 2024 is now 398 days across all major browsers.

// Chapter 6

Cipher Suites: Mixing Algorithms

A cipher suite is a specification of four algorithms that work together: key exchange (how to establish the shared secret), authentication (how to prove server identity), bulk encryption (how to encrypt data), and MAC (how to verify integrity). In TLS 1.2, the cipher suite bundles all four. In TLS 1.3, key exchange and authentication are decoupled — the suite only specifies the symmetric encryption and hash algorithm.

Reading a TLS 1.2 cipher suite name: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 breaks down as: protocol (TLS), key exchange (ECDHE), authentication (RSA), encryption (AES-128-GCM), MAC (SHA256). In TLS 1.3, TLS_AES_128_GCM_SHA256 omits key exchange/auth entirely — they're always ECDHE and certificate-based.

Cipher Suite Inspector

TLS_AES_128_GCM_SHA256TLS 1.3 onlyPFS
TLS_AES_256_GCM_SHA384TLS 1.3 onlyPFS
ECDHE-RSA-AES128-GCM-SHA256TLS 1.2PFS
ECDHE-RSA-CHACHA20-POLY1305TLS 1.2 / 1.3PFS
DHE-RSA-AES256-SHA256TLS 1.2PFS
RSA-AES256-SHATLS 1.0–1.2
RC4-SHATLS 1.0–1.2
EXP-RC4-MD5SSL 3.0

TLS_AES_128_GCM_SHA256

Key Exchange

ECDHE (built-in)

Auth

Certificate (separate)

Encryption

AES-128-GCM

MAC

SHA-256 (AEAD)

PFS

Yes

Strength

strong

TLS 1.3 separates key exchange from cipher suite. ECDHE always used. AEAD provides authentication.

AEAD: Authenticated Encryption with Associated Data

Traditional cipher modes (CBC, CTR) only encrypt. Integrity must be added separately with HMAC, leading to subtle vulnerabilities in the ordering of operations (encrypt-then-MAC vs MAC-then-encrypt). AEAD modes (AES-GCM, ChaCha20-Poly1305) combine encryption and authentication in a single operation, proven secure by construction. TLS 1.3 mandates AEAD-only cipher suites, eliminating a whole class of padding oracle and MAC timing attacks.

AES-GCM (Galois/Counter Mode) is the workhorse: AES in CTR mode for encryption, GHASH (Galois field multiplication) for authentication. On modern x86 CPUs with AES-NI and CLMUL hardware instructions, AES-GCM achieves 10–40 Gbps throughput per core. ChaCha20-Poly1305 achieves similar performance in software, making it ideal for ARM mobile devices without hardware AES acceleration.

# List cipher suites supported by your system
openssl ciphers -v 'ALL:COMPLEMENTOFALL' | head -30

# Test specific cipher suite against server
openssl s_client -connect example.com:443 -cipher ECDHE-RSA-AES128-GCM-SHA256

# Generate strong Nginx cipher suite configuration
# ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;
# ssl_prefer_server_ciphers off;  # Let client choose (both are strong)

# Grade your TLS configuration
# https://ssllabs.com/ssltest (Qualys) — automated cipher/cert/protocol analysis

// Chapter 7

Perfect Forward Secrecy

Story

Imagine the NSA has been recording every TLS-encrypted packet passing through a fiber optic cable since 2005. They can't decrypt any of it — yet. But they're patient. In 2010, they obtain (legally or otherwise) the private key of a major bank. Now they can decrypt every session that bank's server had from 2005 to 2010. Millions of users' login credentials, transactions, and messages — retroactively compromised. This is the threat model that Perfect Forward Secrecy (PFS) addresses.

In classic RSA key exchange, the client encrypts the pre-master secret using the server's long-term RSA public key. If the server's private key is ever compromised — by theft, legal compulsion, insider threat, or cryptanalysis — every past session can be decrypted by anyone who recorded the traffic.

Perfect Forward Secrecy (also called "forward secrecy") breaks this link. When key exchange uses ephemeral Diffie-Hellman (DHE or ECDHE), a new DH key pair is generated for every session. The session key is derived from this ephemeral key, not the long-term certificate key. The ephemeral private key is discarded after the handshake. Even if the server's certificate private key is stolen, past sessions remain secure — the ephemeral keys are gone.

ECDHE vs DHE

Elliptic Curve Diffie-Hellman Ephemeral (ECDHE) is preferred over finite-field DHE because it achieves the same security with much smaller keys. A 256-bit ECDHE key provides security equivalent to a 3072-bit RSA key. The performance difference is significant — ECDHE handshakes are roughly 10x faster than equivalent RSA key exchange for high-security key sizes. Curve X25519 (designed by Daniel Bernstein) is the preferred curve in TLS 1.3 — it's fast, formally analyzed, and avoids the NIST curve controversy.

Wow

In 2013, Edward Snowden's leaks revealed that the NSA had collected massive amounts of encrypted internet traffic. Security researchers noted that most servers at the time were using RSA key exchange (no PFS), meaning the NSA could theoretically decrypt everything retrospectively once they had the keys. This revelation accelerated the industry-wide adoption of ECDHE. By 2016, over 80% of HTTPS connections used forward secrecy. Today, TLS 1.3 makes it mandatory.

// Chapter 8

Session Resumption and 0-RTT

A full TLS handshake is expensive — especially at scale. A CDN handling 10 million TLS connections per second can't afford a full RSA/ECDHE handshake for every one. Session resumption allows previously-established sessions to be reconnected with a shorter handshake, skipping the certificate exchange and key derivation from scratch.

TLS 1.2: Session IDs and Session Tickets

Two mechanisms existed in TLS 1.2. Session IDs: the server assigns a session ID and stores the session state; the client presents it on reconnect. Problem: server-side state doesn't scale across server clusters. Session Tickets (RFC 5077): the server encrypts the session state with a server-side ticket key and sends it to the client. On reconnect, the client sends the ticket, the server decrypts it and resumes. Scales horizontally — but the ticket encryption key becomes a long-term secret that must be rotated.

TLS 1.3: PSK and 0-RTT

TLS 1.3 uses Pre-Shared Key (PSK) resumption. After a session, the server sends a NewSessionTicket message with a PSK identity and ticket. On reconnect, the client includes the PSK in the ClientHello, and the server can resume in 1-RTT. With 0-RTT Early Data, the client can send application data in the very first flight — before the handshake completes — using keys derived from the PSK.

Caution

0-RTT data is not protected against replay attacks. An attacker can replay the 0-RTT data to make the server process a request twice. Only use 0-RTT for idempotent requests (HTTP GET). Never use it for POST, PUT, DELETE, payment flows, or anything with side effects. HTTP/3 (QUIC + TLS 1.3) disables 0-RTT by default for non-safe HTTP methods. Server-side replay protection using a token database is required for safe 0-RTT in high-security contexts.

// Chapter 9

Certificate Transparency

Story

2015. Google discovered that Symantec had issued EV certificates for google.com domains without Google's knowledge — as a test, Symantec said. Google was not amused. They threatened to distrust Symantec's entire root unless CT logging became mandatory for all certificates. Symantec ultimately lost its CA status in 2018 (absorbed by DigiCert). The incident proved that without a public, tamper-evident log of every certificate issued, rogue CA behavior was undetectable until the damage was done.

Certificate Transparency (CT) is a mechanism where every publicly-trusted certificate must be logged in a public, append-only, cryptographically-verifiable log before browsers will accept it. Chrome has required CT since April 2018 — any certificate without a Signed Certificate Timestamp (SCT) is rejected.

The logs are public: anyone can query them and discover certificates issued for their domain. This means domain owners get automatic notification if someone (a rogue CA, a compromised CA) issues a certificate for their domain. Google's certificate search at crt.sh indexes all CT logs and is invaluable for security auditing.

How CT Works

A CA submits a pre-certificate (identical to the final cert but with a poison extension) to multiple CT logs. Each log returns a Signed Certificate Timestamp (SCT) — a cryptographic promise to include the cert within a merge delay (usually 24 hours). The CA embeds these SCTs in the final certificate. Your browser verifies the SCTs during the TLS handshake, confirming the certificate is in the public logs.

# Query CT logs for certificates issued for a domain
curl -s "https://crt.sh/?q=%.example.com&output=json" | jq '.[0:5]'

# Check CT SCTs in a certificate
openssl x509 -in cert.pem -text -noout | grep -A 20 "CT Precertificate SCTs"

# Monitor for new certs issued for your domain
# Use certspotter, ct-monitor, or Facebook's Certificate Transparency Monitoring
# (available at developers.facebook.com/tools/ct)

// Chapter 10

SNI and Virtual Hosting

Before SNI existed, HTTPS and virtual hosting were incompatible. A server could only have one certificate per IP address — because the TLS handshake happens before the HTTP Host header is sent. If you put multiple HTTPS sites on one IP, the server had no way to know which certificate to present before the encrypted connection was established. The result: each HTTPS site needed its own IP address.

Server Name Indication (SNI), defined in RFC 6066, solves this by adding a server_name extension to the ClientHello. The client announces which hostname it's trying to reach before encryption begins, allowing the server to select the correct certificate. This enabled CDNs, shared hosting, and modern cloud infrastructure — a single IP can now serve thousands of HTTPS sites.

The SNI Privacy Problem

SNI is sent in plaintext. Any observer on the network path (your ISP, a coffee shop router, a government firewall) can see which hostname you're connecting to, even on HTTPS. China's Great Firewall uses SNI inspection to block specific HTTPS sites. This is why Encrypted Client Hello (ECH) is being developed — it encrypts the inner ClientHello (including SNI) using the server's public key, revealed only in DNS. ECH requires DNS-over-HTTPS (DoH) for the public key retrieval to be secure.

Wow

Cloudflare serves over 25 million domains from roughly 1,500 IP addresses. Without SNI (or with only one cert per IP), they would need 25 million IP addresses — the entire IPv4 space is only ~4.3 billion addresses, with less than 100 million available. SNI is the technology that makes CDN-scale HTTPS economically feasible.

// Chapter 11

mTLS: Client Authentication

Standard TLS authenticates only the server. The client remains anonymous — the server has no cryptographic proof of who the client is. For most web applications this is fine; identity is established via credentials (passwords, OAuth tokens) sent over the encrypted channel after the handshake.

But for machine-to-machine communication — microservices, API gateways, service mesh, IoT devices — passwords are awkward. Mutual TLS (mTLS) extends the handshake: the server requests a certificate from the client, and the client presents one. Both parties authenticate each other before any application data flows.

mTLS in Modern Infrastructure

Service mesh (Istio, Linkerd): automatically provisions mTLS certificates for every pod in a Kubernetes cluster, with zero application code changes. All inter-service traffic is mutually authenticated and encrypted.

Zero-trust networking: every service proves identity before any request is accepted. No implicit trust based on being "inside the network."

API security: payment processors, cloud APIs, and banking APIs use mTLS to authenticate calling services, preventing request forgery from other services in a compromised environment.

IoT device authentication: devices carry a certificate burned at manufacturing time; the server validates it to confirm device identity before accepting telemetry or firmware updates.

# Generate CA, client cert, server cert for mTLS testing
openssl genrsa -out ca.key 4096
openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -subj "/CN=TestCA"

openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=my-client"
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365

# Test mTLS with curl
curl --cert client.crt --key client.key --cacert ca.crt https://mtls-server.example.com

# Nginx mTLS configuration
# ssl_client_certificate /etc/nginx/ca.crt;
# ssl_verify_client on;

// Chapter 12

TLS Attack History

TLS has been attacked relentlessly since its invention. Each attack exploited either a design flaw, an implementation flaw, or a negotiation flaw that allowed downgrade to a weaker mode. Understanding the attack history is not just academic — it's why TLS 1.3 made the choices it did.

BEAST (2011)

Browser Exploit Against SSL/TLS. Exploited a CBC mode flaw in TLS 1.0/SSL — the IV for each record was predictable (the previous record's last block). Allowed chosen-plaintext attacks to decrypt specific bytes (e.g., session cookies). Mitigated by 1/n-1 record splitting, and ultimately by migrating to TLS 1.2 with RC4 (then later AEAD). RC4 was enabled widely as a BEAST workaround — introducing the next problem.

CRIME (2012) and BREACH (2013)

Compression oracle attacks. CRIME (Compression Ratio Info-leak Made Easy): if TLS compression is enabled, an attacker who can inject data into requests can determine secret bytes by watching compression ratios. BREACH (Browser Reconnaissance and Exfiltration via Adaptive Compression of Hypertext): same attack but against HTTP compression. Mitigated by: never using TLS compression (disabled by all major implementations), never compressing pages that contain secrets alongside user-controlled content, or randomizing the secret position.

HEARTBLEED (2014)

Not a protocol vulnerability — an implementation bug in OpenSSL's heartbeat extension. The heartbeat message includes a payload length; OpenSSL failed to validate that the actual payload matched the claimed length. An attacker could send a 1-byte payload claiming 64KB length and receive 64KB of server memory — potentially including private keys, passwords, session tokens. The most widespread security vulnerability in internet history — affecting an estimated 17% of all HTTPS servers at disclosure.

POODLE (2014)

Padding Oracle On Downgraded Legacy Encryption. SSL 3.0 uses CBC mode without proper MAC verification before padding removal. An attacker who can insert themselves on the network and force connection retries can force a TLS 1.x → SSL 3.0 downgrade, then exploit the padding oracle. Mitigation: disable SSL 3.0 entirely. TLS_FALLBACK_SCSV (a new cipher suite value signaling "this is my minimum version") prevents the downgrade.

FREAK (2015) and Logjam (2015)

Both exploited export-grade cryptography residue — the 40-bit and 512-bit keys required by 1990s US export controls, still present in server implementations. FREAK (Factoring RSA Export Keys): force downgrade to RSA-512, factor it in hours. Logjam: force downgrade to DHE-512 (discrete log in a finite field), precompute the discrete logs for common 512-bit groups. Both attacks required MitM position but exploited server misconfiguration. Mitigated by removing all export cipher support.

DROWN (2016)

Decrypting RSA with Obsolete and Weakened eNcryption. If a server supports SSLv2 (even on a different port or service) using the same certificate/key as an HTTPS server, an attacker can use SSLv2 as an oracle to decrypt TLS sessions targeting that key. Affected 33% of all HTTPS servers. Mitigated by: disable SSLv2 everywhere, never reuse keys across protocols.

# Check for POODLE, BEAST, CRIME, HEARTBLEED vulnerabilities
testssl.sh example.com              # comprehensive TLS vulnerability scanner
# Or use nmap scripts:
nmap --script ssl-poodle -p 443 example.com
nmap --script ssl-heartbleed -p 443 example.com
nmap --script ssl-dh-params -p 443 example.com   # Logjam / Weak DH

# Check for export cipher support (FREAK)
nmap --script ssl-enum-ciphers -p 443 example.com | grep -i export

// Chapter 13

Common Misconceptions

Misconception — HTTPS means the site is safe

HTTPS means the connection between your browser and the server is encrypted. It says nothing about whether the server is trustworthy, whether the site is a phishing page, or whether the content is legitimate. A phishing site can have a valid TLS certificate (Let's Encrypt issues them free to anyone). The padlock icon means "encrypted," not "trustworthy." Phishing sites on HTTPS have been standard practice since 2017 when free CA adoption exploded.

Misconception — TLS protects against server compromise

TLS secures the communication channel. If the server itself is compromised, the attacker has access to the plaintext data before it's encrypted for transmission. A server-side breach bypasses TLS entirely — the attacker sees what the server sees. TLS is not a substitute for server hardening, secure coding, and access controls.

Misconception — Self-signed certificates are equivalent to CA-signed ones for security

Self-signed certificates provide the same cryptographic strength for encryption. But they provide no authentication — a browser warning appears because there's no third party vouching that the certificate actually belongs to who it claims to belong to. An attacker could create their own self-signed certificate claiming to be your bank. For public-facing services, always use a trusted CA. For internal services where you control the trust store, a private CA is acceptable.

Misconception — TLS 1.2 with AES-256 is more secure than TLS 1.3 with AES-128

The AES key size is not the limiting security factor. A 128-bit symmetric key provides 2^128 security, which is computationally infeasible to brute-force. The weaker elements in TLS 1.2 are the protocol design (more attack surface, potential downgrade vectors), older cipher modes (CBC instead of AEAD), and less rigorous key derivation. TLS 1.3 with AES-128-GCM is more secure in practice than TLS 1.2 with AES-256-CBC, even though 256 >128.

Misconception — Certificate pinning always improves security

Certificate pinning (hardcoding the expected certificate or public key in a client application) was popular in mobile security, but has largely been deprecated. When a pinned certificate expires or is rotated, the app breaks for all users — causing outages. Google removed HPKP (HTTP Public Key Pinning) from Chrome in 2018 because the operational risk outweighed the security benefit. Certificate Transparency provides similar protection (detecting rogue cert issuance) without the operational fragility.

Misconception — Wildcard certificates are always appropriate

A wildcard cert (*.example.com) is convenient but dangerous at scale. If the wildcard private key is compromised, every subdomain is compromised. Wildcard certs cannot be scoped to specific subdomains — if you have 500 services sharing a wildcard, a compromise of any one potentially exposes all 500. For high-security services, individual per-service certificates (with automated issuance via ACME) are safer. Wildcards should not be used for two-level wildcards or for wildcard plus other names on the same key.

// Chapter 14

IQ Depth Check

IQ — Beginner

TLS encrypts the connection between your browser and a server so that no one in the middle can read your data. When you see a padlock in your browser, it means the connection is encrypted using TLS. HTTPS is HTTP running over TLS. The server has a certificate that proves its identity, issued by a Certificate Authority that your browser trusts.

IQ — Intermediate

TLS 1.3 requires exactly 1 RTT for a full handshake (vs TLS 1.2's 2 RTT), mandatory ECDHE key exchange for forward secrecy, and AEAD cipher suites only. The certificate is encrypted during the handshake. Session resumption via PSK enables 0-RTT for returning clients, but 0-RTT data is replay-vulnerable and must be limited to idempotent operations. SNI allows multiple HTTPS sites per IP but leaks the target hostname to network observers. mTLS enables mutual authentication for service-to-service communication.

IQ — Senior

TLS 1.3 key schedule uses HKDF with separate handshake and application traffic secrets. The transcript hash binds all messages; the Finished message is an HMAC over the transcript using the finished_key derived from the handshake secret. Forward secrecy is achieved by deleting ephemeral ECDHE key pairs immediately after key derivation. 0-RTT security properties: anti-replay requires server-side nonce tracking (within the ticket lifetime window). ECH encrypts the inner ClientHello using the Encrypted Client Hello config published in DNS HTTPS records. Certificate Transparency requires SCTs from at least two independent logs (per Chrome CT policy). OCSP Must-Staple extension forces servers to include a stapled OCSP response or browsers reject the certificate entirely.

IQ — PhD

TLS 1.3 formal security proofs (Dowling et al., 2017; JKSS 2018) establish that the TLS 1.3 handshake achieves multi-stage key exchange security under the modular computational model — specifically: stage-0 (0-RTT) achieves forward secrecy under the PRF-ODH assumption only for forward-secret mode; stage-1/2 (1-RTT) achieves full FS under PRF-ODH. The HKDF Extract/Expand construction satisfies the KDF security notion when the input key material is pseudorandom. The Diffie-Hellman key exchange over Curve25519 (X25519) is proven secure under the Decisional Diffie-Hellman (DDH) assumption in the generic group model, with constant-time implementation to prevent timing side-channels. ChaCha20-Poly1305's security reduction to the unpredictability of Poly1305 over GF(2^130-5) is tight. The formal security of TLS 1.3's record protocol under AEAD nonce-misuse resistance has been analyzed in the RO+UC framework. Known open problems: side-channel timing attacks on ECDSA signing (partially mitigated by EdDSA/Ed25519), the assumption that browsers properly validate CT consistency proofs (gossip protocol not yet widely deployed), and the security of PSK-only mode (without (EC)DHE) against quantum adversaries — post-quantum TLS using CRYSTALS-Kyber is currently in IETF draft standardization (hybrid X25519Kyber768).

🎯 Key Takeaways

  • TLS provides confidentiality, integrity, and authentication using a combination of asymmetric (handshake) and symmetric (record) cryptography.
  • TLS 1.3 reduces handshake latency to 1-RTT (vs 2-RTT for TLS 1.2), makes forward secrecy mandatory, and removes all non-AEAD cipher suites.
  • Diffie-Hellman key exchange (ECDHE in modern TLS) allows two parties to establish a shared secret over a public channel with no prior coordination.
  • Perfect Forward Secrecy means a compromise of the server's long-term key does not compromise past sessions — because ephemeral session keys are discarded immediately.
  • Certificate chains create a hierarchy of trust: browsers trust root CAs pre-installed in the OS, which sign intermediate CAs, which sign leaf certificates.
  • Certificate Transparency logs every public certificate in tamper-evident, append-only logs, allowing domain owners to detect rogue certificate issuance.
  • Cipher suites specify the algorithms for key exchange, authentication, bulk encryption, and MAC. TLS 1.3 mandates AEAD modes (AES-GCM or ChaCha20-Poly1305).
  • SNI allows multiple HTTPS sites per IP but exposes the target hostname in plaintext; Encrypted Client Hello (ECH) addresses this privacy gap.
  • mTLS extends TLS to authenticate both parties, enabling zero-trust service-to-service communication without passwords.
  • TLS 1.0, 1.1, SSL 3.0, and SSL 2.0 are all deprecated and broken. The minimum acceptable version is TLS 1.2 with ECDHE and AEAD cipher suites.
Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...