TLS
TLS (Transport Layer Security) is the protocol behind the padlock in your browser. It protects HTTPS, secure email, many database connections and most APIs. It combines everything from the previous lessons: key exchange, certificates, signatures, symmetric encryption and MACs. TLS gives a connection three properties:
- Confidentiality: eavesdroppers see only encrypted bytes.
- Integrity: modified records are detected and the connection is dropped.
- Server authentication (and optionally client authentication) through certificates.
The older name SSL is still used informally, but every SSL version and TLS 1.0/1.1 are obsolete.
| Version | Status |
|---|---|
| SSL 2.0 / 3.0 | Broken, must be disabled |
| TLS 1.0 / 1.1 | Deprecated (2021), disable |
| TLS 1.2 | Acceptable with modern cipher suites |
| TLS 1.3 | Recommended: faster handshake, only strong algorithms, forward secrecy always |
The TLS 1.3 handshake
A full TLS 1.3 handshake takes one round trip before application data flows:
Client Server
ClientHello ─────────────────────────────────▶
supported versions, cipher suites,
key share (X25519 public key), SNI hostname
◀───────────── ServerHello
chosen suite, key share
{Certificate} server's chain
{CertificateVerify} signature over the handshake
{Finished} MAC over the handshake
{Finished} ──────────────────────────────────▶
[application data] ◀═══════════ encrypted ═══▶ [application data]- Both sides send ephemeral key shares and derive the same secret (Diffie-Hellman, as in the asymmetric lesson). Everything after
ServerHellois encrypted. - The server sends its certificate chain and a signature over the handshake transcript with the certificate's private key. That proves it owns the certificate and ties the key exchange to it, defeating man-in-the-middle attacks.
- Both sides send Finished messages: MACs over the whole handshake, so any tampering with the negotiation (for example a forced downgrade) is detected.
- Application data is encrypted with an AEAD cipher (AES-GCM or ChaCha20-Poly1305) using keys derived from the shared secret.
Simulating the key schedule
The core idea, both sides deriving identical traffic keys from an ephemeral exchange plus the transcript, fits in a short model. (Real TLS uses a more elaborate HKDF-based key schedule.)
import hashlib
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
client_eph = X25519PrivateKey.generate()
server_eph = X25519PrivateKey.generate()
transcript = hashlib.sha256(b"ClientHello...ServerHello...").digest()
def traffic_key(my_private, their_public, label):
shared = my_private.exchange(their_public)
return HKDF(hashes.SHA256(), 32, salt=transcript, info=label).derive(shared)
c2s_client = traffic_key(client_eph, server_eph.public_key(), b"c ap traffic")
c2s_server = traffic_key(server_eph, client_eph.public_key(), b"c ap traffic")
print("both sides derived the same key:", c2s_client == c2s_server)
record = AESGCM(c2s_client).encrypt(bytes(12), b"GET /account HTTP/1.1", None)
print("server reads:", AESGCM(c2s_server).decrypt(bytes(12), record, None).decode())both sides derived the same key: True
server reads: GET /account HTTP/1.1
The ephemeral keys are discarded after the handshake, which is what gives TLS 1.3 forward secrecy.
Auditing a TLS configuration
Most TLS problems in practice are configuration mistakes rather than broken cryptography. A scanner like the model below checks a server's settings against a policy:
POLICY_MIN_VERSION = (1, 2)
WEAK_SUITE_PARTS = ["RC4", "3DES", "NULL", "EXPORT", "MD5", "CBC_SHA"]
def audit(server):
findings = []
for version in server["versions"]:
if tuple(map(int, version.split("."))) < POLICY_MIN_VERSION:
findings.append(f"disable TLS {version}")
for suite in server["suites"]:
if any(part in suite for part in WEAK_SUITE_PARTS):
findings.append(f"remove weak suite {suite}")
if server["cert_days_left"] < 14:
findings.append(f"certificate expires in {server['cert_days_left']} days")
if not server["hsts"]:
findings.append("send a Strict-Transport-Security header")
return findings or ["OK"]
servers = {
"legacy.example": {"versions": ["1.0", "1.2"],
"suites": ["TLS_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"],
"cert_days_left": 9, "hsts": False},
"modern.example": {"versions": ["1.2", "1.3"],
"suites": ["TLS_AES_128_GCM_SHA256", "TLS_CHACHA20_POLY1305_SHA256"],
"cert_days_left": 61, "hsts": True},
}
for host, cfg in servers.items():
print(host)
for finding in audit(cfg):
print(" -", finding)legacy.example
- disable TLS 1.0
- remove weak suite TLS_RSA_WITH_3DES_EDE_CBC_SHA
- certificate expires in 9 days
- send a Strict-Transport-Security header
modern.example
- OK
Public tools such as the SSL Labs server test and testssl.sh perform this kind of audit against your own servers.
HTTPS-specific protections
- Redirect HTTP to HTTPS, but note that the very first plain-HTTP request can still be intercepted.
- HSTS (
Strict-Transport-Security: max-age=31536000; includeSubDomains) tells browsers to use HTTPS only for that site from now on. Sites can also be added to the browsers' built-in preload list. - Secure cookies: mark session cookies
Secureso they're never sent over plain HTTP. - Automate certificate renewal (ACME/Let's Encrypt). Expired certificates are a very common outage.
HTTP/1.1 301 Moved Permanently
Location: https://shop.example/
HTTP/1.1 200 OK
Strict-Transport-Security: max-age=31536000; includeSubDomains
Set-Cookie: session=…; Secure; HttpOnly; SameSite=LaxWhat TLS does not protect
TLS protects data in transit between two endpoints. It does not protect data once it arrives (a hacked server still leaks), it doesn't hide which server you connect to (IP addresses and usually the SNI hostname are visible), and a valid certificate only proves the name, not that the site is honest: phishing sites have padlocks too.
Go further: The TLS 1.3 Handshake Step by Step animates every message with its protection, including HelloRetryRequest, resumption and 0-RTT.
Test yourself
Which TLS versions should a server accept today?
- SSL 3.0 and up
- TLS 1.0 and up
- TLS 1.2 and TLS 1.3
- Only TLS 1.1
In the TLS 1.3 handshake, what proves that the server owns the private key for its certificate?
- The ClientHello
- The CertificateVerify signature over the handshake transcript
- The SNI hostname
- The HTTP response code
What does the HSTS header do?
- Encrypts cookies
- Tells browsers to always use HTTPS for the site
- Renews certificates
- Blocks JavaScript