These are the notes for Cybersecurity Fundamentals (defensive), episode 22. Last episode showed that HTTP is plain text: paths, cookies, even passwords. Today we invent, one problem at a time, the fix behind the little padlock in your browser: TLS and HTTPS, the TLS handshake, TLS 1.2 vs TLS 1.3, cipher suites, SNI and ALPN, server authentication, mutual TLS (mTLS), the deprecated protocols SSLv3, TLS 1.0 and TLS 1.1, downgrade attacks, testing your own TLS configuration, SSL stripping, HSTS and the HSTS preload list, session resumption, 0-RTT and its replay risk, and the trade-offs of certificate pinning. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Asha, her bank, the café and every login are made up. Every server in the demos runs on 127.0.0.1 (this machine) inside the demo process itself, and the host names bank.example, shop.example and pay.example are reserved example names, so no real website is contacted or tested. Every code sample was run with Python 3.13 and OpenSSL 3.0.13; outputs are real, copied from actual runs. Encrypted bytes (ciphertext) are different on every run, so yours will not match those exactly. Each demo writes small .pem key and certificate files, so run each one in its own empty folder.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A spy on the café Wi-Fi reads the password | Sniffing, TLS, HTTPS, record header, confidentiality, integrity, AEAD, SSL history |
| Two strangers must agree on secret keys | TLS handshake, ClientHello, ServerHello, key share, ECDHE, forward secrecy, Finished, TLS 1.2 vs 1.3, cipher suites, SNI, ALPN |
| Perfectly encrypted, to an impostor | Man-in-the-middle, server authentication, trust store, CA, subjectAltName |
| Which app is calling the bank? | Client certificates, mutual TLS (mTLS) |
| Old versions, forced down | Deprecated protocols, downgrade attacks, DOWNGRD sentinel, testing your own server |
| The first request is still http | SSL stripping, HSTS, max-age, includeSubDomains, preload list |
| Handshakes cost time | Session resumption, 0-RTT and replay, certificate pinning trade-offs |
Problem 1: a spy on the cable
Asha is at a café. She joins the free Wi-Fi and logs in to her bank. Every byte she sends passes through the café's router, and through any device that can copy traffic along the way. Copying traffic you are not meant to see is called sniffing. Think of a postcard: every postal worker who handles it can read it.
So, can they read her password? Below, a real "bank" server listens on port 9001 of this machine. Inside it there is a tap: a second handle on the raw connection (conn.dup()) that peeks at the bytes exactly as they arrive, before the bank reads them (MSG_PEEK means "look without removing"). That is exactly what a spy on the path sees. The first line makes a key and a certificate for bank.example with the openssl command (certificates were episode 16; we use them in Problem 3). There is one switch, USE_TLS. First it is False: plain HTTP style, no encryption.
Demo 1: the tap, without TLS
import os, socket, ssl, threading
os.system("openssl req -x509 -newkey ed25519 -nodes -keyout key.pem -out cert.pem"
" -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
USE_TLS = False # <- the only switch
bank = socket.create_server(("127.0.0.1", 9001))
def serve(): # the bank
conn = bank.accept()[0]
cable = conn.dup() # a tap on the raw cable
if USE_TLS:
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); tls.load_cert_chain("cert.pem", "key.pem")
conn = tls.wrap_socket(conn, server_side=True)
print("on the cable:", cable.recv(26, socket.MSG_PEEK)) # what a spy sees
print("bank reads: ", conn.recv(1024))
t = threading.Thread(target=serve); t.start()
c = socket.create_connection(("127.0.0.1", 9001)) # the browser
if USE_TLS:
ctx = ssl.create_default_context(cafile="cert.pem")
c = ctx.wrap_socket(c, server_hostname="bank.example")
c.sendall(b"user=asha&password=chai123"); t.join()
Output:
on the cable: b'user=asha&password=chai123'
bank reads: b'user=asha&password=chai123'
On the cable: user=asha&password=chai123. Anyone on the path reads it as easily as the bank does. That is the failure: plain text on a shared network.
Demo 2: the same tap, with TLS
Flip one switch: USE_TLS = True. The bank wraps its side in TLS (tls.wrap_socket(..., server_side=True)), the browser wraps its side (ctx.wrap_socket(..., server_hostname="bank.example")), and nothing else changes. Same tap.
import os, socket, ssl, threading
os.system("openssl req -x509 -newkey ed25519 -nodes -keyout key.pem -out cert.pem"
" -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
USE_TLS = True # <- the only switch
bank = socket.create_server(("127.0.0.1", 9001))
def serve(): # the bank
conn = bank.accept()[0]
cable = conn.dup() # a tap on the raw cable
if USE_TLS:
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); tls.load_cert_chain("cert.pem", "key.pem")
conn = tls.wrap_socket(conn, server_side=True)
print("on the cable:", cable.recv(26, socket.MSG_PEEK)) # what a spy sees
print("bank reads: ", conn.recv(1024))
t = threading.Thread(target=serve); t.start()
c = socket.create_connection(("127.0.0.1", 9001)) # the browser
if USE_TLS:
ctx = ssl.create_default_context(cafile="cert.pem")
c = ctx.wrap_socket(c, server_hostname="bank.example")
c.sendall(b"user=asha&password=chai123"); t.join()
Output (the bytes after the first five are different on every run):
on the cable: b'\x17\x03\x03\x00+f\x1a\x94\x9a\xf7\xc9d\xa6\xf3V\xb8i\x0f\xb3\xe1qb\x10\x1c\xaee'
bank reads: b'user=asha&password=chai123'
On the cable: random-looking bytes. The bank still reads the login perfectly, but the spy gets nothing useful. Run it again and the bytes change completely.
Look at the first five bytes, the record header. TLS cuts the data into records (sealed packets), and each one starts with a small label in plain view:
| Bytes | Meaning |
|---|---|
17 |
Content type, in hexadecimal (0x17 = 23): application data, encrypted |
03 03 |
A version number kept for old equipment (the real version is agreed inside the handshake) |
00 2b |
Length: 0x2b = 43 bytes of encrypted record follow (Python prints 0x2b as the character +) |
The 43 bytes are the 26-byte login plus a few extra bytes, mostly the authentication tag that detects any change (Practice 1 decodes this header). So the spy can see that you talk, roughly how much, and when, but not what.
What did the switch give us? A sealed courier pouch
Think of a bank courier's pouch:
| A bank courier | TLS gives you | How |
|---|---|---|
| The pouch is sealed: nobody on the way can read it | Confidentiality (secret) | Encryption |
| A torn seal shows: any change is noticed | Integrity (untouched) | Authentication tags: AEAD (authenticated encryption with associated data, episode 12). Every record carries a tag, and a changed byte breaks it |
| The courier shows a bank ID card | Server authentication (the right party) | A certificate plus a signature (episode 16) |
TLS, Transport Layer Security, is the protocol that adds these three properties to any TCP connection (episode 19). HTTPS is simply HTTP (episode 21) sent inside TLS, usually on port 443. That is what the padlock means: these three properties, for this one connection. It does not mean the website is honest or that the company behind it is safe; it means nobody between you and that server can read or change the traffic.
From SSL to TLS 1.3
You will meet these names everywhere:
| Version | Status |
|---|---|
| SSL (Secure Sockets Layer) | The older protocol TLS grew out of. Its last version, SSLv3: "SSLv3 MUST NOT be used" (RFC 7568, June 2015), because of a CBC padding flaw shown by the POODLE attack and biases in the RC4 cipher |
| TLS 1.0, TLS 1.1 | MUST NOT be used (RFC 8996, March 2021, BCP 195): their handshake depends on the weak SHA-1 and MD5 hashes, and they lack AEAD cipher suites |
| TLS 1.2 (RFC 5246) | Still acceptable when configured well |
| TLS 1.3 (RFC 8446, August 2018) | The default today; it obsoletes RFC 5246. It is what Demo 2 negotiated |
An RFC (Request for Comments) is how internet standards are published; each one has a number. People still say "SSL certificate" out of habit: they mean a TLS certificate.
Problem 2: the TLS handshake
How did the browser and the bank agree on secret keys when they had never met, with the spy watching every byte? The TLS handshake: the opening conversation before any real data. Real-life picture: two strangers on a phone line that anyone can listen to, who still end up sharing a secret.
- ClientHello (browser → bank): the TLS versions it supports, the cipher suites it supports, a key share (its half of a Diffie-Hellman exchange, episode 15), the site name (SNI) and the application protocols it speaks (ALPN).
- ServerHello (bank → browser): the version and cipher suite it picked, and its own key share. Then its certificate, and a signature proving it holds the matching private key. In TLS 1.3, everything after the ServerHello is already encrypted.
- Both compute the same keys. Each side combines its own secret with the other's key share (ECDH, elliptic-curve Diffie-Hellman) and gets the same shared secret, without the secret ever crossing the wire. In ECDHE the final E means ephemeral: fresh key shares for every connection. That gives forward secrecy: if someone steals the bank's long-term private key later, they still can't unlock traffic recorded today.
- Finished messages: each side sends a check computed over every handshake message so far. If an attacker changed even one byte of the hellos, the check fails and the connection stops. Then the encrypted data flows (the
17 03 03 ...records).
TLS 1.2 vs TLS 1.3
A round trip is one message there and the reply back (like asking a question across a room and hearing the answer).
| TLS 1.2 | TLS 1.3 | |
|---|---|---|
| Round trips before data | 2 | 1 (the key share goes in the very first message) |
| Key exchange | Allows static RSA and static DH (no forward secrecy) | Static RSA and static DH removed: every public-key exchange gives forward secrecy |
| Encryption | Allows CBC-mode ciphers and others | Only AEAD ciphers; CBC gone |
| Compression | Allowed | Removed |
| Certificate | Sent in plain view | Encrypted (it comes after the ServerHello) |
TLS 1.3 removed old options that caused real attacks, leaving a small menu of strong choices. Faster and safer.
Reading a cipher suite name
A cipher suite is a named bundle of algorithms that both sides agree to use for one connection.
TLS 1.3: TLS_AES_256_GCM_SHA384
AES_256_GCM = encryption (AEAD) SHA384 = hash used to derive keys
TLS 1.2: ECDHE-ECDSA-AES256-GCM-SHA384
ECDHE = key exchange ECDSA = certificate signature type
AES256-GCM = encryption SHA384 = hash
TLS 1.2 names are longer because they also name the key exchange and the signature type; TLS 1.3 negotiates those separately. Names to avoid: RC4, 3DES, CBC suites with SHA1, NULL (no encryption at all), EXPORT (deliberately weakened) and anon (no authentication).
Demo 3: reading a real handshake
The bank says it speaks two application protocols, h2 (HTTP/2) and http/1.1, and prints the site name the browser asks for. The browser then prints what got negotiated.
import os, socket, ssl, threading
os.system("openssl req -x509 -newkey ed25519 -nodes -keyout key.pem -out cert.pem"
" -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); tls.load_cert_chain("cert.pem", "key.pem")
tls.set_alpn_protocols(["h2", "http/1.1"]) # what the bank speaks
tls.sni_callback = lambda sock, name, ctx: print("bank sees SNI: ", name)
bank = socket.create_server(("127.0.0.1", 9001))
def serve():
conn = tls.wrap_socket(bank.accept()[0], server_side=True); conn.recv(1)
threading.Thread(target=serve).start()
ctx = ssl.create_default_context(cafile="cert.pem") # the browser
ctx.set_alpn_protocols(["h2", "http/1.1"])
print("browser offers: ", len(ctx.get_ciphers()), "cipher suites")
c = ctx.wrap_socket(socket.create_connection(("127.0.0.1", 9001)),
server_hostname="bank.example")
print("version: ", c.version())
print("cipher suite: ", c.cipher()[0])
print("ALPN picked: ", c.selected_alpn_protocol())
c.sendall(b"x")
Output:
browser offers: 17 cipher suites
bank sees SNI: bank.example
version: TLSv1.3
cipher suite: TLS_AES_256_GCM_SHA384
ALPN picked: h2
- 17 cipher suites offered by Python's default client settings (Practice 2 lists them all).
- Version TLSv1.3, cipher suite
TLS_AES_256_GCM_SHA384, ALPN pickedh2.
Two new terms:
- SNI, Server Name Indication: the browser puts the website's name in the ClientHello, because one IP address can host many websites, each with its own certificate. Like writing the flat number on a letter to a big apartment building. Notice it is sent before encryption starts, so the café can see which site you visit, just not what you do there.
- ALPN, Application-Layer Protocol Negotiation (RFC 7301, July 2014): inside the same handshake, both sides agree which protocol runs on top,
h2orhttp/1.1, without an extra round trip.
Problem 3: encrypted, to an impostor
Here's the catch. What if the café router doesn't pass Asha's connection to the bank at all, and answers itself: "I'm bank.example"? That is a man-in-the-middle (episode 10): someone secretly sitting between two parties. It runs a full TLS handshake with its own keys: perfectly encrypted, straight to the attacker, who reads everything and passes it on. Like handing your sealed pouch to a man in a courier uniform who isn't from the bank.
Encryption alone is useless if it's with the wrong party. The browser must check who holds the key.
Demo 4: the real bank, the impostor, and the wrong name
Two certificates both claim the name bank.example: one belongs to the real bank, one the impostor made itself. The browser's trust store, the list of certificates it trusts (here, cafile="bank.pem"), contains only the real bank's. Three visits: the real bank, the impostor, and the real bank asked for under a different name.
import os, socket, ssl, threading
mk = "openssl req -x509 -newkey ed25519 -nodes -keyout {0}.key -out {0}.pem -subj /CN=bank.example" \
" -addext subjectAltName=DNS:bank.example 2>/dev/null"
os.system(mk.format("bank")); os.system(mk.format("impostor")) # same name, different keys
def visit(cert, name): # a server with `cert`, a browser asks for `name`
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain(cert + ".pem", cert + ".key")
lst = socket.create_server(("127.0.0.1", 0))
def serve():
try: srv.wrap_socket(lst.accept()[0], server_side=True)
except ssl.SSLError: pass
threading.Thread(target=serve).start()
ctx = ssl.create_default_context(cafile="bank.pem") # browser trusts the real bank
try:
ctx.wrap_socket(socket.create_connection(lst.getsockname()), server_hostname=name)
print(f"{cert:8} as {name:12} -> verified")
except ssl.SSLCertVerificationError as e:
print(f"{cert:8} as {name:12} -> {e}")
visit("bank", "bank.example"); visit("impostor", "bank.example"); visit("bank", "pay.example")
Output:
bank as bank.example -> verified
impostor as bank.example -> [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1035)
bank as pay.example -> [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'pay.example'. (_ssl.c:1035)
- The real bank: verified.
- The impostor:
certificate verify failed: self-signed certificate. Its certificate is signed only by itself, not by anyone the browser trusts, so the handshake stops before a single byte of data. - The real certificate, asked for as
pay.example:Hostname mismatch. A valid certificate for the wrong name is still rejected.
Server authentication: what the browser checks
Server authentication means proving the server is who it claims to be:
- Chain: the certificate is signed by a CA (certificate authority, a trusted issuer, episode 16) in the trust store.
- Name: the host it asked for is listed in the certificate's subjectAltName (subject alternative name) field.
- Dates and revocation: not expired, not before its start date, and not revoked.
- Proof: the server signs the handshake with the private key that matches the certificate, so a copied certificate alone is worthless.
The most common mistake in real code: a developer hits a certificate error and silences it with verify=False or ssl.CERT_NONE. That doesn't fix anything. It switches off authentication, and any café router becomes the bank (Practice 4 shows it). The right fix is to trust the right CA file and use the right name.
Problem 4: mutual TLS
Normal TLS is one-way: the server proves who it is, and anyone may connect. Think of a bank's back office:
| A bank's back office | Mutual TLS |
|---|---|
| The branch shows its licence to customers | Server certificate: normal TLS |
| The vault only opens for courier vans with a permit | Client certificate: the client proves who it is |
| Every internal door checks both | mTLS between services |
In mutual TLS (mTLS), the client also presents a certificate, and the server checks it the same way the browser checked the bank's. Companies use it between their own services, such as a payments app talking to an accounts database: even inside the network, every connection proves both sides. That idea grows into zero trust (episode 35).
Demo 5: the bank demands a client certificate
The bank sets verify_mode = ssl.CERT_REQUIRED and trusts exactly one client: the payments app. First a client with no certificate connects, then the payments app with its certificate.
import os, socket, ssl, threading
mk = "openssl req -x509 -newkey ed25519 -nodes -keyout {0}.key -out {0}.pem -subj /CN={0}" \
" -addext subjectAltName=DNS:{0} 2>/dev/null"
os.system(mk.format("bank.example")); os.system(mk.format("payments-app"))
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain("bank.example.pem", "bank.example.key")
srv.verify_mode = ssl.CERT_REQUIRED # mutual TLS: the client must prove who it is,
srv.load_verify_locations("payments-app.pem") # and the only client app we trust is this one
def serve(lst):
for _ in range(2):
try: conn = srv.wrap_socket(lst.accept()[0], server_side=True)
except ssl.SSLError: continue # no valid client certificate: refused
conn.sendall(f"hello {conn.getpeercert()['subject'][0][0][1]}, balance 5000".encode())
threading.Thread(target=serve, args=[socket.create_server(("127.0.0.1", 9001))]).start()
for me in [None, "payments-app"]: # first no certificate, then the app's
ctx = ssl.create_default_context(cafile="bank.example.pem")
if me: ctx.load_cert_chain(me + ".pem", me + ".key")
c = ctx.wrap_socket(socket.create_connection(("127.0.0.1", 9001)), server_hostname="bank.example")
try: print(me, "->", c.recv(100))
except ssl.SSLError as e: print(me, "->", e)
Output:
None -> [SSL: TLSV13_ALERT_CERTIFICATE_REQUIRED] tlsv13 alert certificate required (_ssl.c:2663)
payments-app -> b'hello payments-app, balance 5000'
- No certificate:
tlsv13 alert certificate required. An alert is TLS's error message; the bank refused before sending a single byte of data. - The payments app:
hello payments-app, balance 5000. The bank knows exactly which program is calling, without any password (getpeercert()gives it the client's name).
Problem 5: old versions and downgrade attacks
The browser offers TLS 1.3 and 1.2. A man-in-the-middle edits the messages, or keeps breaking connections until the browser retries with an older version. That is a downgrade attack: forcing two strong parties to use a weak option they both still support. Like a fake waiter telling the kitchen "the customer only eats the cheap menu". If the server still speaks TLS 1.0, both fall back to it, and the attacker attacks the weak part.
TLS 1.3 fights back twice:
- The Finished check covers the hellos, so edited offers are detected.
- A TLS 1.3 server pushed down to an older version puts the bytes
44 4F 57 4E 47 52 44(ASCII forDOWNGRD) into itsServerHello.random, so a 1.3-capable client notices and stops (Practice 6). This is the DOWNGRD sentinel (a "sentinel" is a planted marker value).
But the best defence is simpler: you can't be downgraded to a version that isn't there. Don't support old versions at all.
Demo 6: testing our own server, version by version
This is how a security team checks its own servers (never anyone else's). The obvious config: "support everyone", every version since TLS 1.0, every cipher (ALL:@SECLEVEL=0 turns off OpenSSL's safety floor). Then a test client offers exactly one version at a time.
import os, socket, ssl, threading, warnings
warnings.simplefilter("ignore") # hide Python's own "TLSv1 is deprecated" warnings
os.system("openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout key.pem"
" -out cert.pem -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain("cert.pem", "key.pem")
srv.minimum_version = ssl.TLSVersion.TLSv1; srv.set_ciphers("ALL:@SECLEVEL=0") # "support everyone"
def serve(lst):
while True:
try: srv.wrap_socket(lst.accept()[0], server_side=True).recv(1)
except (ssl.SSLError, OSError): pass
threading.Thread(target=serve, args=[socket.create_server(("127.0.0.1", 9443))], daemon=True).start()
V = ssl.TLSVersion
for v in [V.TLSv1, V.TLSv1_1, V.TLSv1_2, V.TLSv1_3]: # test OUR OWN server, version by version
ctx = ssl.create_default_context(cafile="cert.pem"); ctx.set_ciphers("ALL:@SECLEVEL=0")
ctx.minimum_version = ctx.maximum_version = v # a test client that offers only v
try:
c = ctx.wrap_socket(socket.create_connection(("127.0.0.1", 9443)), server_hostname="bank.example")
print(f"{v.name:8} accepted {c.cipher()[0]}"); c.close()
except ssl.SSLError as e: print(f"{v.name:8} refused {e.reason}")
Output:
TLSv1 accepted ECDHE-ECDSA-AES256-SHA
TLSv1_1 accepted ECDHE-ECDSA-AES256-SHA
TLSv1_2 accepted ECDHE-ECDSA-AES256-GCM-SHA384
TLSv1_3 accepted TLS_AES_256_GCM_SHA384
Every version accepted. Look at the cipher for TLS 1.0 and 1.1: ECDHE-ECDSA-AES256-SHA, which means AES in CBC mode with a SHA-1 MAC, exactly what the standards banned. A downgrade has somewhere to land.
Demo 7: the one-line fix
srv.minimum_version = ssl.TLSVersion.TLSv1_2. Same test.
import os, socket, ssl, threading, warnings
warnings.simplefilter("ignore") # hide Python's own "TLSv1 is deprecated" warnings
os.system("openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout key.pem"
" -out cert.pem -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain("cert.pem", "key.pem")
srv.minimum_version = ssl.TLSVersion.TLSv1_2 # the fix: TLS 1.2 or newer only
def serve(lst):
while True:
try: srv.wrap_socket(lst.accept()[0], server_side=True).recv(1)
except (ssl.SSLError, OSError): pass
threading.Thread(target=serve, args=[socket.create_server(("127.0.0.1", 9443))], daemon=True).start()
V = ssl.TLSVersion
for v in [V.TLSv1, V.TLSv1_1, V.TLSv1_2, V.TLSv1_3]: # test OUR OWN server, version by version
ctx = ssl.create_default_context(cafile="cert.pem"); ctx.set_ciphers("ALL:@SECLEVEL=0")
ctx.minimum_version = ctx.maximum_version = v # a test client that offers only v
try:
c = ctx.wrap_socket(socket.create_connection(("127.0.0.1", 9443)), server_hostname="bank.example")
print(f"{v.name:8} accepted {c.cipher()[0]}"); c.close()
except ssl.SSLError as e: print(f"{v.name:8} refused {e.reason}")
Output:
TLSv1 refused TLSV1_ALERT_PROTOCOL_VERSION
TLSv1_1 refused TLSV1_ALERT_PROTOCOL_VERSION
TLSv1_2 accepted ECDHE-ECDSA-AES256-GCM-SHA384
TLSv1_3 accepted TLS_AES_256_GCM_SHA384
TLS 1.0 and 1.1 are now refused with a protocol version alert. Only TLS 1.2 with GCM (AEAD), and TLS 1.3, remain. Testing your own TLS configuration means doing this for every server you run, plus checking the certificate name and expiry: the mini project builds exactly that. Free online and command-line TLS testing tools run the same kind of checks, and many more, against servers you own.
Problem 6: SSL stripping and HSTS
TLS is strong, so attackers go around it. Asha types just bank.example, with no https:// in front. The browser's very first request goes out as plain http, hoping the bank redirects it to https.
The café attacker answers that plain request itself and never redirects. Moxie Marlinspike showed this at Black Hat DC 2009 ("New Tricks For Defeating SSL In Practice", with a tool called sslstrip): users reach HTTPS through plain HTTP links and redirects, and the attacker keeps the victim on HTTP. This is SSL stripping. Asha logs in over plain http while the attacker talks proper https to the real bank. There is no certificate error, because there is no TLS on Asha's side at all: just a missing padlock nobody notices.
Demo 8: a browser with HSTS memory
A browser simulation (no network). When the browser doesn't know a site, the first request is http, and at the evil café the attacker answers it. When it reaches the real bank, the bank sends the header Strict-Transport-Security: max-age=31536000; includeSubDomains. Three days, then a brand-new site.
hsts = {} # the browser's memory: host -> "always HTTPS"
PRELOAD = set() # hosts built into the browser (empty for now)
def visit(host, wifi): # the user types just "bank.example"
if host in hsts or host in PRELOAD:
scheme = "https" # HSTS: upgrade BEFORE anything leaves the laptop
else:
scheme = "http" # first request goes out in plain text...
if wifi == "evil café": # ...so an attacker can answer it and never redirect
return f"{wifi:10} http://{host} -> password sent in plain text!"
# the real bank: redirect to https, then send the HSTS header
hsts[host] = "Strict-Transport-Security: max-age=31536000; includeSubDomains"
return f"{wifi:10} https://{host} -> padlock, safe (first request: {scheme})"
print(visit("bank.example", "evil café")) # day 1, at the café
print(visit("bank.example", "home")) # day 2, at home
print(visit("bank.example", "evil café")) # day 3, the café again
print(visit("shop.example", "evil café")) # a brand-new site
PRELOAD.add("shop.example") # the fix for first visits: the preload list
print(visit("shop.example", "evil café"))
Output:
evil café http://bank.example -> password sent in plain text!
home https://bank.example -> padlock, safe (first request: http)
evil café https://bank.example -> padlock, safe (first request: https)
evil café http://shop.example -> password sent in plain text!
evil café https://shop.example -> padlock, safe (first request: https)
- Day 1 at the café: stripped, password in plain text.
- Day 2 at home: the bank redirects to https and sends the header; the browser remembers it.
- Day 3, back at the café: the browser goes straight to https before anything leaves the laptop. The attacker has nothing to strip.
- The brand-new shop is stripped on its first visit: the browser can't remember a header it never received. After adding the shop to the preload list, even the first visit is https.
HSTS and the preload list
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
- HSTS, HTTP Strict Transport Security (RFC 6797, November 2012): lets "web sites ... declare themselves accessible only via secure connections". The browser then upgrades to HTTPS by itself.
- max-age: how many seconds to remember; 31536000 seconds is about one year.
- includeSubDomains: every subdomain too (
www.bank.example,api.bank.example...). - The weak spot: the first visit is not protected. The mitigation is a pre-loaded list.
- HSTS preload: a list of HSTS sites built into the browser. Chrome's list is also used by Firefox, Safari and Edge. Requirements (hstspreload.org): a valid certificate, redirect HTTP to HTTPS, all subdomains on HTTPS, and the header with
max-ageat least 31536000,includeSubDomainsandpreload. - Warning from the list's own site: "inclusion in the preload list cannot easily be undone". If an old internal subdomain only works on http, it breaks. So: HTTPS everywhere first, then HSTS, then preload.
Problem 7: resumption, 0-RTT and pinning
Handshakes cost time, so TLS has shortcuts. Picture a hotel:
| A hotel | TLS speed-up |
|---|---|
| A guest keeps a key card: no full check-in next time | Session resumption: the server gives the client a ticket; next time they reuse the earlier secret instead of a full handshake |
| Ordering breakfast while walking in | 0-RTT ("zero round trip") early data: a returning client sends real data in its very first message (TLS 1.3) |
| A photocopied order slip: the kitchen cooks it twice | Replay risk: an attacker records that first message and sends it again |
RFC 8446 says plainly about 0-RTT: "There are no guarantees of non-replay between connections." If the early data said "transfer 500 rupees", a replay could transfer it twice. Remember idempotency from episode 21: an action with the same effect once or many times. The rule:
- 0-RTT only for safe, idempotent requests (a GET of a page).
- Never logins, payments or any POST in early data. Many servers simply leave 0-RTT off.
Certificate pinning trade-offs
Certificate pinning: an app accepts only one specific key or certificate for its server, even if a trusted CA signed another one. That blocks a wrongly issued certificate. Like a house that only opens for one particular key, not for any key the locksmith association approves.
The trade-off: if you change that key, or lose it, every installed app is locked out until users update. On the web, Chrome 72 removed HTTP-Based Public Key Pinning (HPKP), citing "very low adoption" and the risks of denial of service and hostile pinning (an attacker who briefly controls a site pinning their own key). Today, certificate transparency logs (episode 16) plus short-lived certificates do most of that job. Pinning: strong, but brittle.
The next problem
TLS protects what is inside the connection. But how did the café router get into the middle in the first place? On a local network, one device can lie about addresses ("I am the gateway"). And TLS does nothing if a flood of junk traffic means the bank can't answer anyone at all. Network attacks, and how networks defend themselves: next episode.
The whole chain
- A spy read the cable → TLS: secret, untouched, right party; HTTPS = HTTP inside TLS
- Strangers need keys → the handshake, ECDHE, forward secrecy, cipher suites
- Which site, which protocol → SNI, ALPN
- An impostor → server authentication: trusted chain + right name
- Which app is calling → mutual TLS
- Forced down → no TLS below 1.2; test your own server
- The first request is http → HSTS, preload
- Speed → session resumption, 0-RTT (replay!), pinning trade-offs
...and you just invented HTTPS, properly done.
Common mistakes (and what they print)
| Mistake | What you get | Why | Fix |
|---|---|---|---|
verify=False / ssl.CERT_NONE |
connected to the IMPOSTOR: TLSv1.3 - no error at all (Practice 4) |
Authentication switched off | Trust the right CA file (cafile=) instead |
| Certificate missing a host name | certificate verify failed: Hostname mismatch, certificate is not valid for 'pay.example'. |
The name must be in subjectAltName | Issue it for every host name the service uses |
| Trusting a certificate nobody vouches for | certificate verify failed: self-signed certificate |
Not signed by anything in the trust store | Use a CA-issued certificate, or add your own test CA to the client's trust store |
minimum_version = TLSv1 |
TLSv1 accepted ECDHE-ECDSA-AES256-SHA |
Banned versions + CBC/SHA-1 | Minimum TLS 1.2, prefer 1.3 |
| mTLS server, client sends no certificate | [SSL: TLSV13_ALERT_CERTIFICATE_REQUIRED] tlsv13 alert certificate required |
The server demands a client certificate | Load one with ctx.load_cert_chain(...) |
Forgetting server_hostname= |
ValueError: check_hostname requires server_hostname |
Without a name, nothing can be checked | Pass the host name you meant to reach |
| Speaking TLS to a plain HTTP port | [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1035) |
The reply isn't a TLS record at all | Use the right port (443 for HTTPS) |
| HTTPS but no HSTS | evil café http://shop.example -> password sent in plain text! |
The first request and redirect are plain http | Send the HSTS header, then preload |
| Allowing logins in 0-RTT | A replayed request runs twice | No replay guarantee between connections | 0-RTT only for idempotent requests |
Mini project: a TLS self-check for your own server
A small checker you can point at your own local server. It reports PASS / WARN / FAIL for: banned versions refused, best version, an AEAD cipher suite, the certificate name, and days until the certificate expires. It starts two of our own test servers on 127.0.0.1: an old, forgotten config (TLS 1.0 allowed, certificate valid 10 days) and the fixed config (TLS 1.2 minimum, 365 days).
import os, socket, ssl, threading, time, warnings
warnings.simplefilter("ignore") # hide "TLSv1 is deprecated" warnings
V = ssl.TLSVersion
def make_server(port, days, oldest): # one of OUR OWN test servers
os.system(f"openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days {days}"
f" -keyout s{port}.key -out s{port}.pem -subj /CN=bank.example"
f" -addext subjectAltName=DNS:bank.example 2>/dev/null")
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain(f"s{port}.pem", f"s{port}.key")
srv.minimum_version = oldest
if oldest < V.TLSv1_2: srv.set_ciphers("ALL:@SECLEVEL=0")
lst = socket.create_server(("127.0.0.1", port))
def serve():
while True:
try: srv.wrap_socket(lst.accept()[0], server_side=True).recv(1)
except (ssl.SSLError, OSError): pass
threading.Thread(target=serve, daemon=True).start()
def connect(port, host, version=None):
ctx = ssl.create_default_context(cafile=f"s{port}.pem"); ctx.set_ciphers("ALL:@SECLEVEL=0")
if version: ctx.minimum_version = ctx.maximum_version = version
return ctx.wrap_socket(socket.create_connection(("127.0.0.1", port)), server_hostname=host)
def check(port, host):
print(f"--- 127.0.0.1:{port} as {host}")
for v in [V.TLSv1, V.TLSv1_1]: # 1. banned versions must be refused
try: connect(port, host, v).close(); print(f"FAIL {v.name} accepted (RFC 8996: MUST NOT)")
except ssl.SSLError: print(f"PASS {v.name} refused")
try: c = connect(port, host) # 2. the normal, best connection
except ssl.SSLCertVerificationError as e:
print("FAIL certificate:", e.verify_message); return
name = c.cipher()[0]
aead = name.startswith("TLS_") or "GCM" in name or "CHACHA20" in name
print(f"{'PASS' if c.version() == 'TLSv1.3' else 'WARN'} best version {c.version()}")
print(f"{'PASS' if aead else 'FAIL'} cipher suite {name}")
days = (ssl.cert_time_to_seconds(c.getpeercert()["notAfter"]) - time.time()) / 86400
print(f"{'PASS' if days > 30 else 'WARN'} certificate expires in {days:.0f} days")
c.close()
make_server(9443, days=10, oldest=V.TLSv1) # an old, forgotten config
make_server(9444, days=365, oldest=V.TLSv1_2) # the fixed config
check(9443, "bank.example")
check(9444, "bank.example")
check(9444, "pay.example") # a name the certificate doesn't list
Output:
--- 127.0.0.1:9443 as bank.example
FAIL TLSv1 accepted (RFC 8996: MUST NOT)
FAIL TLSv1_1 accepted (RFC 8996: MUST NOT)
PASS best version TLSv1.3
PASS cipher suite TLS_AES_256_GCM_SHA384
WARN certificate expires in 10 days
--- 127.0.0.1:9444 as bank.example
PASS TLSv1 refused
PASS TLSv1_1 refused
PASS best version TLSv1.3
PASS cipher suite TLS_AES_256_GCM_SHA384
PASS certificate expires in 365 days
--- 127.0.0.1:9444 as pay.example
PASS TLSv1 refused
PASS TLSv1_1 refused
FAIL certificate: Hostname mismatch, certificate is not valid for 'pay.example'.
- The old config fails both banned-version checks and warns that its certificate expires in 10 days (an expired certificate means every visitor sees an error).
- The fixed config passes everything.
- Asked for a name the certificate doesn't list, the checker stops at the certificate (
e.verify_messageis the short reason).
Ideas to extend it: also report the cipher suite negotiated for TLS 1.2, check that the HTTP port redirects to HTTPS and sends a Strict-Transport-Security header, and run it on a schedule against every server you own.
Practice
1. Homework: decode the 17 03 03 record header.
Solution
Peek at only the first 5 bytes on the tap and split them into fields:
import os, socket, ssl, threading
os.system("openssl req -x509 -newkey ed25519 -nodes -keyout key.pem -out cert.pem"
" -subj /CN=bank.example -addext subjectAltName=DNS:bank.example 2>/dev/null")
bank = socket.create_server(("127.0.0.1", 9001))
def serve():
conn = bank.accept()[0]
cable = conn.dup() # the tap
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); tls.load_cert_chain("cert.pem", "key.pem")
conn = tls.wrap_socket(conn, server_side=True)
hdr = cable.recv(5, socket.MSG_PEEK) # just the record header
kind, major, minor = hdr[0], hdr[1], hdr[2]
length = int.from_bytes(hdr[3:5], "big")
print("header bytes:", hdr.hex(" "))
print("content type:", kind, "(0x17 = application data)" if kind == 0x17 else "")
print("version: ", f"{major}.{minor}", "(fixed value kept for old equipment)")
print("length: ", length, "bytes of encrypted record follow")
print("bank reads: ", conn.recv(1024))
t = threading.Thread(target=serve); t.start()
ctx = ssl.create_default_context(cafile="cert.pem")
c = ctx.wrap_socket(socket.create_connection(("127.0.0.1", 9001)), server_hostname="bank.example")
c.sendall(b"user=asha&password=chai123"); t.join()
Output:
header bytes: 17 03 03 00 2b
content type: 23 (0x17 = application data)
version: 3.3 (fixed value kept for old equipment)
length: 43 bytes of encrypted record follow
bank reads: b'user=asha&password=chai123'
Content type 23 (0x17) is application data; 03 03 is the fixed version label; the length is 43 bytes. The record is 17 bytes longer than the 26-byte login, mostly because of the authentication tag. A spy learns the type and size, never the content.
2. Homework: compare the cipher suites per version.
Solution
import ssl
ctx = ssl.create_default_context() # Python's default client settings
for c in ctx.get_ciphers():
print(f"{c['protocol']:8} {c['name']:32} AEAD={c['aead']}")
Output:
TLSv1.3 TLS_AES_256_GCM_SHA384 AEAD=True
TLSv1.3 TLS_CHACHA20_POLY1305_SHA256 AEAD=True
TLSv1.3 TLS_AES_128_GCM_SHA256 AEAD=True
TLSv1.2 ECDHE-ECDSA-AES256-GCM-SHA384 AEAD=True
TLSv1.2 ECDHE-RSA-AES256-GCM-SHA384 AEAD=True
TLSv1.2 ECDHE-ECDSA-AES128-GCM-SHA256 AEAD=True
TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 AEAD=True
TLSv1.2 ECDHE-ECDSA-CHACHA20-POLY1305 AEAD=True
TLSv1.2 ECDHE-RSA-CHACHA20-POLY1305 AEAD=True
TLSv1.2 ECDHE-ECDSA-AES256-SHA384 AEAD=False
TLSv1.2 ECDHE-RSA-AES256-SHA384 AEAD=False
TLSv1.2 ECDHE-ECDSA-AES128-SHA256 AEAD=False
TLSv1.2 ECDHE-RSA-AES128-SHA256 AEAD=False
TLSv1.2 DHE-RSA-AES256-GCM-SHA384 AEAD=True
TLSv1.2 DHE-RSA-AES128-GCM-SHA256 AEAD=True
TLSv1.2 DHE-RSA-AES256-SHA256 AEAD=False
TLSv1.2 DHE-RSA-AES128-SHA256 AEAD=False
These are the 17 suites from Demo 3. All 3 TLS 1.3 suites are AEAD. The TLS 1.2 list also contains suites with AEAD=False: names like ECDHE-RSA-AES256-SHA384 (no GCM or CHACHA20) are CBC mode with a separate MAC. A strict TLS 1.2 server can allow only the GCM and CHACHA20 ones.
3. Homework: make the HSTS memory expire after max-age.
Solution
now = 0 # a fake clock, in seconds
hsts = {} # host -> expiry time
def remember(host, max_age):
hsts[host] = now + max_age
def scheme(host):
if host in hsts and now < hsts[host]:
return "https (HSTS)"
hsts.pop(host, None) # expired: forget it
return "http (first request in plain text)"
remember("bank.example", 31536000) # the header: max-age=31536000
for day in [0, 200, 364, 366]:
now = day * 86400
print(f"day {day:3}: {scheme('bank.example')}")
Output:
day 0: https (HSTS)
day 200: https (HSTS)
day 364: https (HSTS)
day 366: http (first request in plain text)
After 31536000 seconds (about a year) the browser forgets, and the next first request is plain http again. That is why real sites send the header on every HTTPS response: each visit restarts the clock.
4. Comment question: why is verify=False never a fix?
Answer
Because it doesn't fix the cause of the error; it turns off the check that detected it. With verification off, the impostor from Demo 4 is accepted silently:
import os, socket, ssl, threading
mk = "openssl req -x509 -newkey ed25519 -nodes -keyout {0}.key -out {0}.pem -subj /CN=bank.example" \
" -addext subjectAltName=DNS:bank.example 2>/dev/null"
os.system(mk.format("bank")); os.system(mk.format("impostor"))
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain("impostor.pem", "impostor.key")
lst = socket.create_server(("127.0.0.1", 0))
threading.Thread(target=lambda: srv.wrap_socket(lst.accept()[0], server_side=True)).start()
ctx = ssl.create_default_context(cafile="bank.pem")
ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE # the "fix" people paste
c = ctx.wrap_socket(socket.create_connection(lst.getsockname()), server_hostname="bank.example")
print("connected to the IMPOSTOR:", c.version(), "- no error at all")
Output:
connected to the IMPOSTOR: TLSv1.3 - no error at all
The connection is still encrypted, but to the impostor. Fix the real problem instead: point cafile= at the right CA, or get a certificate that lists the right name.
5. Read a certificate's name and expiry from a live handshake. Make a certificate valid for 90 days for two names and print what the client receives.
Solution
import os, socket, ssl, threading
os.system("openssl req -x509 -newkey ed25519 -nodes -keyout key.pem -out cert.pem -days 90"
" -subj /CN=bank.example -addext subjectAltName=DNS:bank.example,DNS:www.bank.example 2>/dev/null")
srv = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER); srv.load_cert_chain("cert.pem", "key.pem")
lst = socket.create_server(("127.0.0.1", 0))
threading.Thread(target=lambda: srv.wrap_socket(lst.accept()[0], server_side=True)).start()
ctx = ssl.create_default_context(cafile="cert.pem")
c = ctx.wrap_socket(socket.create_connection(lst.getsockname()), server_hostname="www.bank.example")
cert = c.getpeercert()
print("subject: ", cert["subject"])
print("issuer: ", cert["issuer"])
print("subjectAltName:", cert["subjectAltName"])
print("valid until: ", cert["notAfter"])
Output (the date depends on the day you run it):
subject: ((('commonName', 'bank.example'),),)
issuer: ((('commonName', 'bank.example'),),)
subjectAltName: (('DNS', 'bank.example'), ('DNS', 'www.bank.example'))
valid until: Jan 31 23:33:12 2027 GMT
The subject and issuer are the same: that's what self-signed means. subjectAltName lists both names, so www.bank.example passes the name check. notAfter is the expiry date the mini project counts down to.
6. Spot the DOWNGRD sentinel.
Solution
import os
sentinel = bytes.fromhex("44 4F 57 4E 47 52 44") # from RFC 8446
print(sentinel, "=", sentinel.decode())
normal = os.urandom(32) # a normal ServerHello.random
pushed = os.urandom(25) + sentinel # a 1.3 server pushed down
for name, rnd in [("normal", normal), ("pushed down", pushed)]:
print(f"{name:12} ->", "DOWNGRD found: abort!" if sentinel in rnd else "ok")
Output:
b'DOWNGRD' = DOWNGRD
normal -> ok
pushed down -> DOWNGRD found: abort!
The 7 bytes spell DOWNGRD. A random value almost never contains them by chance, so a TLS 1.3 client that finds them in ServerHello.random knows someone pushed the connection down, and aborts.
7. Asha's banking app pins the bank's key. The bank's key is stolen and must be replaced tonight. What happens?
Answer
Every installed copy of the app refuses the new key and can't connect until users install an update with the new pin. That's the pinning trade-off: strong against wrongly issued certificates, but brittle. If you do pin, plan for key changes (for example, a backup key) before you ship.
8. Your API supports 0-RTT. Which of these may be accepted as early data: GET /rates, POST /login, POST /transfer?
Answer
Only GET /rates: it is safe and idempotent, so a replay does no harm. A replayed login or transfer could run twice, and RFC 8446 gives "no guarantees of non-replay between connections".
Quick quiz
# Asha opens https://bank.example/statement?month=10
# over TLS 1.3, on the café's Wi-Fi.
#
# Which of these can the café router still see?
A. The full URL with ?month=10
B. Her password
C. The name bank.example (SNI) and how much data
D. The bank's reply text
Answer
C. The path, the query string, her password and the bank's replies are all inside encrypted TLS records. The server name travels in the ClientHello's SNI before encryption, and the size and timing of records are visible.
Interview questions
- What three things does TLS provide? Confidentiality (encryption), integrity (AEAD tags detect changes) and server authentication (certificate plus a signature with the matching private key).
- Walk through a TLS 1.3 handshake. ClientHello (versions, cipher suites, key share, SNI, ALPN) → ServerHello (choices, key share), then encrypted certificate, signature and Finished → client Finished → application data. One round trip.
- TLS 1.2 vs TLS 1.3? 1.3 needs one round trip instead of two, removed static RSA/DH (so every exchange gives forward secrecy), allows only AEAD ciphers, removed compression and encrypts the certificate.
- What is forward secrecy? Each connection uses fresh (ephemeral) key shares, so stealing the server's long-term key later can't decrypt traffic recorded earlier.
- What does a client check to authenticate a server? A chain to a CA in its trust store, the host name in subjectAltName, validity dates and revocation, and the handshake signature by the matching private key.
- What are SNI and ALPN, and what does SNI leak? SNI carries the site name in the ClientHello; ALPN agrees the application protocol (h2 or http/1.1) in the handshake. SNI is sent before encryption, so observers see which site you visit.
- What is mutual TLS and when is it used? The client also presents a certificate that the server verifies; used for service-to-service authentication inside companies and in zero-trust designs.
- What is a downgrade attack and how do you defend against it? Forcing peers onto a weaker version or cipher they both support. Defences: disable TLS 1.0/1.1 and SSLv3, the Finished check over the handshake, and TLS 1.3's DOWNGRD sentinel.
- What is SSL stripping, and how do HSTS and preload stop it? An attacker keeps the victim on plain http by answering the first http request. HSTS makes the browser use https by itself for max-age seconds; preload protects even the first visit.
- What are the risks of 0-RTT and of certificate pinning? 0-RTT early data can be replayed, so allow only idempotent requests. Pinning can lock out every client if the key changes or is lost, which is why browsers dropped HPKP.
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Sniffing | Copying network traffic you are not meant to see | A tap on the café router |
| Plain text | Data sent readable, without encryption | b'user=asha&password=chai123' |
| Ciphertext | Encrypted data; looks random | b'\x17\x03\x03\x00+\xca...' |
| TLS | Transport Layer Security: adds confidentiality, integrity and server authentication to a TCP connection | ctx.wrap_socket(...) |
| SSL | Secure Sockets Layer: the older protocol TLS grew out of; all versions retired | "SSL certificate" (really a TLS certificate) |
| SSLv3 | The last SSL version; "MUST NOT be used" (RFC 7568) | Broken by POODLE |
| POODLE | An attack showing SSLv3's CBC padding flaw | Reason SSLv3 was banned |
| TLS 1.0 / TLS 1.1 | Old TLS versions; MUST NOT be used (RFC 8996) | TLSv1 refused after the fix |
| TLS 1.2 | Still acceptable when configured with AEAD suites (RFC 5246) | ECDHE-ECDSA-AES256-GCM-SHA384 |
| TLS 1.3 | Current version (RFC 8446): one round trip, only AEAD, forward secrecy always | TLSv1.3 in Demo 3 |
| TLS 1.2 vs TLS 1.3 | 1.3 is faster (1 vs 2 round trips) and removed static RSA/DH, CBC and compression | See the table in Problem 2 |
| Deprecated protocols | Versions that must no longer be used: SSLv3, TLS 1.0, TLS 1.1 | minimum_version = TLSv1_2 |
| HTTPS | HTTP sent inside TLS, usually on port 443 | https://bank.example |
| Padlock | The browser's sign that the page came over verified TLS | Missing after SSL stripping |
| Confidentiality | Only the two ends can read the data | Encryption |
| Integrity | Any change to the data is detected | AEAD tag |
| AEAD | Authenticated encryption with associated data: encrypts and adds a tag that detects changes | AES-GCM, ChaCha20-Poly1305 |
| Authentication tag | Extra bytes that prove a record wasn't changed | Part of the 43-byte record |
| CBC | An older encryption mode, used with a separate MAC; banned from TLS 1.3 | ECDHE-ECDSA-AES256-SHA |
| MAC | Message authentication code: a check value proving data is unchanged | SHA-1 MAC in old suites |
| Record | One sealed packet of TLS data | 17 03 03 00 2b ... |
| Record header | The first 5 plain bytes of a record: type, version, length | 17 03 03 00 2b |
| Alert | TLS's error message | tlsv13 alert certificate required |
| TLS handshake | The opening conversation that agrees version, cipher suite and keys | ClientHello → ServerHello → Finished |
| ClientHello | The client's first handshake message: versions, cipher suites, key share, SNI, ALPN | Browser → bank |
| ServerHello | The server's reply: chosen version, cipher suite, its key share | Bank → browser |
| ServerHello.random | Random bytes in the ServerHello; may carry the DOWNGRD sentinel | Practice 6 |
| Key share | One side's public half of a Diffie-Hellman exchange | Sent in the hellos |
| ECDH / ECDHE | Elliptic-curve Diffie-Hellman: both sides compute the same secret from the key shares; the E means ephemeral (fresh each time) | ECDHE- in a suite name |
| Ephemeral | Fresh for every connection, then thrown away | ECDHE keys |
| Static RSA / static DH | Old key exchanges reusing the server's long-term key; no forward secrecy; removed in TLS 1.3 | TLS 1.2 only |
| ECDSA | A signature type for certificates | ECDHE-ECDSA-... |
| Forward secrecy | Stealing the long-term key later can't decrypt traffic recorded today | Every TLS 1.3 exchange |
| Finished message | A check over all handshake messages, so edits are detected | Ends the handshake |
| Round trip | One message there and the reply back | TLS 1.3 needs one |
| Cipher suite | A named bundle of algorithms for one connection | TLS_AES_256_GCM_SHA384 |
| GCM / ChaCha20-Poly1305 | AEAD encryption modes allowed in TLS 1.3 | AES_256_GCM |
| RC4, 3DES, NULL, EXPORT, anon | Cipher names to avoid: weak, broken, no encryption, weakened, no authentication | Never in your config |
| SNI | Server Name Indication: the site name in the ClientHello, sent before encryption | bank sees SNI: bank.example |
| ALPN | Application-Layer Protocol Negotiation (RFC 7301): agree h2 or http/1.1 inside the handshake | ALPN picked: h2 |
| h2 | The ALPN name for HTTP/2 | set_alpn_protocols(["h2", "http/1.1"]) |
| Man-in-the-middle | Someone secretly between two parties, reading or changing traffic | The café router posing as the bank |
| Server authentication | Proving the server is who it claims to be | Chain + name + dates + signature |
| Certificate | A signed document binding a name to a public key | bank.pem |
| Self-signed certificate | A certificate signed by its own key, vouched for by nobody else | The impostor's |
| CA | Certificate authority: a trusted issuer that signs certificates | Issuer in the chain |
| Trust store | The list of CAs/certificates a client trusts | cafile="bank.pem" |
| Chain | The path of signatures from a certificate up to a trusted CA | Check 1 |
| subjectAltName | Certificate field listing every host name it is valid for | DNS:bank.example |
| Hostname mismatch | The certificate doesn't list the name asked for | pay.example |
| Revocation | Cancelling a certificate before it expires | A stolen key |
verify=False / CERT_NONE |
Switching off certificate checks; never a fix | Practice 4 |
| Client certificate | A certificate the client presents to prove who it is | payments-app.pem |
| Mutual TLS (mTLS) | Both server and client prove their identity with certificates | Payments app → bank |
| Zero trust | Every connection proves itself, even inside the network (episode 35) | mTLS everywhere |
| Downgrade attack | Forcing two parties onto a weaker version or cipher they both support | TLS 1.3 → TLS 1.0 |
| DOWNGRD sentinel | Bytes 44 4F 57 4E 47 52 44 a TLS 1.3 server puts in ServerHello.random when pushed to an older version |
Practice 6 |
| Protocol version alert | The refusal sent when a version isn't allowed | TLSV1_ALERT_PROTOCOL_VERSION |
| Testing your own TLS configuration | Probing your own servers for versions, ciphers, names and expiry | Demo 6, mini project |
| SSL stripping | Keeping a victim on plain http by answering the first http request | sslstrip (2009) |
| HSTS | HTTP Strict Transport Security (RFC 6797): "use only HTTPS for this site" | Strict-Transport-Security: max-age=31536000 |
| max-age | How many seconds the browser remembers HSTS | 31536000 = about one year |
| includeSubDomains | HSTS applies to every subdomain too | www.bank.example |
| HSTS preload | A list of HSTS sites built into browsers, protecting even the first visit | PRELOAD.add("shop.example") |
| Redirect | A reply telling the browser to go to another URL | http → https |
| Session resumption | Reusing a previous session's secret via a ticket, skipping the full handshake | The hotel key card |
| 0-RTT (early data) | Sending data in the very first message of a resumed TLS 1.3 connection | Ordering while walking in |
| Replay | Recording a message and sending it again | A duplicated transfer |
| 0-RTT risks | Early data can be replayed; allow only idempotent requests | GET /rates only |
| Idempotent | Same effect once or many times (episode 21) | GET, PUT |
| Certificate pinning | An app accepts only one specific key/certificate for its server | Banking app pin |
| Certificate pinning trade-offs | Blocks wrongly issued certificates, but a key change locks clients out | HPKP removed in Chrome 72 |
| HPKP | HTTP-Based Public Key Pinning: the web's pinning header, removed in Chrome 72 | — |
| Certificate transparency | Public logs of issued certificates (episode 16) | Spotting a wrong certificate |
| RFC | Request for Comments: a numbered internet standard document | RFC 8446 |
| BCP | Best Current Practice: an RFC series for operational advice | BCP 195 |
| PEM file | A text file holding a key or certificate | cert.pem, key.pem |
| openssl | A command-line tool for keys and certificates | openssl req -x509 ... |
| Port 443 | The usual port for HTTPS | https://bank.example |
Summary
- Plain HTTP is readable by anyone on the path. TLS gives a connection confidentiality, integrity and server authentication; HTTPS is HTTP inside TLS. A spy still sees the record header, sizes, timing and the SNI name.
- The TLS handshake: ClientHello, ServerHello, ECDHE key shares, certificate and signature, Finished. TLS 1.3 takes one round trip, has only AEAD suites and always gives forward secrecy.
- A cipher suite names the algorithms; avoid RC4, 3DES, CBC+SHA1, NULL, EXPORT, anon. ALPN picks the application protocol.
- Server authentication = trusted chain + right name (subjectAltName) + dates + signature. Never
verify=False. mTLS makes the client prove itself too. - SSLv3, TLS 1.0 and 1.1 MUST NOT be used. Set the minimum to TLS 1.2, prefer 1.3, and test your own servers. TLS 1.3 detects downgrades (Finished, DOWNGRD).
- SSL stripping attacks the first http request; HSTS and the preload list close that gap (HTTPS everywhere first).
- Session resumption and 0-RTT save time, but 0-RTT can be replayed: idempotent requests only. Pinning is strong but brittle.
Next episode: Network attacks conceptually, and their defences: sniffing, ARP spoofing, MAC flooding, rogue DHCP, DDoS, amplification and BGP hijacking, and the switch and router features that stop them.
Sources: RFC 8446, TLS 1.3 (E. Rescorla, Aug 2018); RFC 8996, on TLS 1.0 and TLS 1.1 (K. Moriarty, S. Farrell, Mar 2021, BCP 195); RFC 7568, on SSLv3 (R. Barnes, M. Thomson, A. Pironti, A. Langley, June 2015); RFC 7301, ALPN (July 2014); RFC 6797, HSTS (J. Hodges, C. Jackson, A. Barth, Nov 2012); hstspreload.org (submission requirements); Moxie Marlinspike, "New Tricks For Defeating SSL In Practice" (Black Hat DC 2009); developer.chrome.com, Chrome 72 deprecations (HPKP removal). Code outputs from Python 3.13 with OpenSSL 3.0.13. Fetched 2 Nov 2026.