TLStlshttpsencryptionconfidentialityintegrity

Why TLS Exists

TCP delivers bytes reliably to an address; it says nothing about who is reading them, who is changing them, or whether the address is the server you meant — TLS is the layer that adds confidentiality, integrity and authenticated identity on top of a transport that has none.

Conceptual
Interview question
Progress

You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.

The problem

Your HTTP request leaves the laptop, crosses a café Wi-Fi network, an ISP, several transit networks and a data-centre switch before it reaches 93.184.216.34:443. Every hop can read the bytes, rewrite them, or answer in the server’s place. TCP will happily deliver the forgery in order and without loss. What has to be added, and where?

What TCP does not promise

TCP: A Reliable Ordered Byte Stream over an Unreliable Network gives you a byte stream that arrives complete and in order — and that is the entire contract. The bytes are plaintext on every link. The peer is whoever answered the SYN at that IP and port, and ARP and Neighbor Discovery: From an IP to a Local MAC, DNS: Why Names Need a Distributed Database and Internet Routing: Autonomous Systems and BGP each offer a way to make the wrong machine answer. Nothing in the segment lets the receiver tell "the server sent this" from "someone on the path sent this".

The threat model TLS was designed for has two attackers. The passive eavesdropper copies traffic and reads it: a rogue access point, a tap at an ISP, a compromised router. The active man-in-the-middle sits on the path and rewrites: it can inject a script into an HTML page, change an account number in a form post, or terminate the TCP connection itself and open its own to the real server, relaying both directions while reading everything.

The coffee-shop Wi-Fi is the canonical example because every attack is cheap there: the attacker shares your broadcast domain, can win the ARP race for the gateway’s IP, can hand out its own DNS server via DHCP, and sees every frame you send. The same attacks exist at ISP and nation-state scale; the café just makes them a laptop’s work.

  • Passive: read credentials, session cookies, API keys, the content of every page. Defeated by encryption.
  • Active: modify responses, downgrade to a weaker protocol, impersonate the server. Defeated by integrity protection plus server authentication.
  • TCP checksums and sequence numbers protect against *accidents* (bit flips, reordering), not against an adversary who recomputes them.

Deriving the four properties

Start from the attacks and each property falls out. Against reading: confidentiality — encrypt the application bytes with a symmetric cipher such as AES-GCM or ChaCha20-Poly1305, which run at gigabytes per second with hardware support. Against rewriting: integrity — every record carries an authentication tag computed with the session key; a modified record fails to verify and the connection is torn down. Modern suites combine both in one AEAD construction (authenticated encryption with associated data), so there is no separate MAC step.

Encryption is useless if the key was agreed with the attacker, which forces authentication: the server proves it holds the private key matching a public key that a trusted third party has bound to its hostname — that binding is a Certificates and the Chain of Trust. And symmetric ciphers need both ends to hold the same secret while never sending it in the clear, which forces key agreement: an asymmetric exchange (ephemeral elliptic-curve Diffie-Hellman in every modern configuration) that lets two parties derive the same secret over a public channel.

The split between asymmetric and symmetric is a performance decision, not an aesthetic one. An X25519 key agreement costs on the order of 50–100 µs of CPU; an RSA-2048 signature verification tens of microseconds; encrypting a 16 kB record with AES-GCM under AES-NI costs a few microseconds. You do the expensive asymmetric work once per connection in the The TLS Handshake and the cheap symmetric work on every byte.

Threat → property → mechanism
AttackProperty neededMechanism (TLS 1.3)
Read traffic on the pathConfidentialitySymmetric AEAD cipher (AES-128/256-GCM, ChaCha20-Poly1305) under a per-connection key
Modify or inject recordsIntegrityAEAD authentication tag on every record; failed verification aborts the connection
Impersonate the serverAuthenticationX.509 certificate chain to a trusted root plus a signature over the handshake (CertificateVerify)
Learn the key by watching key exchangeKey agreementEphemeral ECDHE (X25519, P-256) — the shared secret is never transmitted
Record now, decrypt after stealing the server keyForward secrecyEphemeral keys discarded after the handshake; static RSA key exchange removed in 1.3

Where TLS sits

Conceptual

TLS is a layer between transport and application. It takes a reliable byte stream from TCP, splits application data into records of at most 16 kB plaintext, encrypts and tags each one, and hands the peer the same byte stream it was given. The application protocol above does not change: HTTPS is ordinary HTTP written into a TLS session on port 443. The same is true of SMTP submission on 465, IMAP on 993, the PostgreSQL wire protocol with sslmode=require, gRPC (which mandates h2 over TLS in most deployments), and MQTT on 8883.

Because TLS needs an ordered stream it cannot run directly over UDP: Datagrams and the Contract You Choose; the datagram variant is DTLS, and QUIC instead embeds the TLS 1.3 handshake inside its own transport — see HTTP/3 and QUIC. Some protocols start plaintext and upgrade in-band (STARTTLS for SMTP on 587, PostgreSQL’s SSLRequest message), which is where downgrade attacks live: an active attacker strips the offer to upgrade and the client, unless configured to require TLS, continues in the clear.

HTTPS is HTTP written into a TLS session written into a TCP connection
  1. Application protocolHTTP/1.1, HTTP/2, SMTP, PostgreSQL, gRPC — unchanged by TLS
    ↓
  2. TLS record layerRecords ≤ 16 kB; each encrypted and authenticated with the session key
    ↓
  3. TCPReliable ordered byte stream; TLS assumes this and cannot run over UDP
    ↓
  4. IPAddresses and routing — all still visible to the path

What TLS does not protect

TLS protects the content of the connection, not its existence. The path still sees both IP addresses, the port, packet sizes and timing — enough to fingerprint which site or even which page is being visited. The SNI field in the Client Hello carries the hostname in plaintext so a shared server can pick a certificate; Encrypted Client Hello (ECH) is the fix and is deployed by some large CDNs and browsers but is far from universal. DNS lookups are separate and plaintext unless the resolver speaks DNS-over-HTTPS or DNS-over-TLS.

It also does not protect against a compromised endpoint (malware on the client reads the page after decryption), a misissued certificate (a CA that signs a certificate for a hostname it should not — Certificate Transparency exists to make that detectable), or a client that has been told to trust an extra root, which is exactly how corporate inspection proxies decrypt traffic legitimately and how malware does so illegitimately.

Versions matter. SSL 2/3, TLS 1.0 and 1.1 are deprecated and disabled in current browsers; TLS 1.2 is the floor and TLS 1.3 (RFC 8446, 2018) is the default. Statements about "what TLS does" in the rest of this module are made for 1.3 unless marked, with 1.2 differences called out, because the handshake shape, the set of cipher suites and the resumption mechanism all changed between them.

  • Visible despite TLS: server IP, port, SNI hostname (unless ECH), sizes, timing, DNS queries (unless DoH/DoT).
  • Not addressed by TLS at all: endpoint compromise, CA misissuance, application-level bugs (XSS, injection).
  • http:// on a public network means every property in the table above is absent. HSTS tells the browser never to try.

Key points

  • TCP guarantees delivery, not secrecy or identity; any hop on the path can read or rewrite a plaintext stream.
  • Confidentiality (symmetric AEAD), integrity (authentication tag), authentication (certificate + signature) and key agreement (ephemeral ECDHE) each answer one specific attack.
  • Asymmetric cryptography is used once per connection to agree a key; symmetric cryptography is used on every byte because it is orders of magnitude faster.
  • TLS sits between TCP and the application protocol; HTTPS is unmodified HTTP inside a TLS session, and the same applies to SMTP, database and RPC protocols.
  • TLS does not hide addresses, sizes, timing or (usually) the SNI hostname, and it does not help against a compromised endpoint or a misissued certificate.
  • Version and cipher suite change the details; TLS 1.3 is the default and TLS 1.2 the floor.

Why does this exist?

Mechanisms are answers to constraints. Open each question before reading the answer.

▸Why not just encrypt at the IP layer for everything?

IPsec exists and does exactly that, but it is configured per host or per tunnel by administrators, not per connection by applications. TLS lets an application decide it needs protection and prove the identity of a specific service, which is what HTTPS needs: the browser must know it reached bank.example, not merely that the packets were encrypted to *some* peer.

▸Why does TLS need certificates when it already has encryption?

Key agreement over a public channel resists eavesdropping but not impersonation: an active attacker can run the agreement with both sides and hold two keys. Authentication ties the agreed key to a proven identity, and a certificate is the portable, verifiable form of "this public key belongs to this hostname".

▸Why use two kinds of cryptography instead of one?

Asymmetric operations cost tens to hundreds of microseconds each and would cap a server at a few thousand kilobytes per second; symmetric AEAD costs nanoseconds per byte. Using asymmetric crypto to agree a symmetric key gives the security of the former at the throughput of the latter.

▸Why is forward secrecy a separate property?

Without it, an attacker who records traffic today and steals the server’s long-term private key next year can decrypt everything recorded. Ephemeral per-connection keys that are discarded after the handshake make stolen long-term keys useless against old captures — which is why TLS 1.3 removed the non-ephemeral RSA key exchange entirely.

How it fails

What the failure looks like from inside real software.
Reference · show
  • Plain http:// API calls from a mobile app: credentials and session tokens are readable by anyone on the same Wi-Fi; the fix is TLS plus certificate validation actually left enabled.
  • A client that "works" only because it disabled verification (verify=False, NODE_TLS_REJECT_UNAUTHORIZED=0, -k): it is encrypted to whoever answers, which is precisely the man-in-the-middle case TLS exists to prevent.
  • STARTTLS downgrade: an SMTP client configured to "use TLS if offered" is silently kept in plaintext by an on-path attacker who strips the STARTTLS capability.
  • Believing TLS hides which sites are visited: SNI and destination IP are visible to the network operator and to any middlebox doing SNI-based filtering.
  • Terminating TLS at a load balancer and forwarding plaintext across a shared network segment because "it is internal" — the threat model reappears inside the data centre.

Check yourself

Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.

  1. Walk me through a TLS handshake. What does each side learn, how many round trips does it cost, and what changed between TLS 1.2 and TLS 1.3?

    Show a strong answer

    A handshake has to do three things before a byte of HTTP flows: authenticate the server (prove the public key in its certificate belongs to the name the client asked for — see Certificates and the Chain of Trust), agree on a shared secret that no observer can derive, and negotiate algorithms (key exchange, signature, symmetric cipher) plus extras such as the application protocol via ALPN (h2, http/1.1) and the hostname via SNI so one IP can serve many certificates. Everything before the shared secret exists is in the clear.

    TLS 1.2 takes two round trips. ClientHello (versions, cipher suites, random, SNI, ALPN) → ServerHello + Certificate + ServerKeyExchange (its ephemeral ECDHE public value, signed with the certificate’s key) + ServerHelloDone → ClientKeyExchange (the client’s ECDHE value) + ChangeCipherSpec + Finished → server ChangeCipherSpec + Finished. Both sides derive the same secret from the ECDHE exchange; the Finished messages are MACs over the whole transcript, so any tampering with the negotiation is detected. 1.2 also allowed RSA key exchange (client encrypts a secret to the server’s public key), which has no forward secrecy — compromise the key later, decrypt every recorded session.

    TLS 1.3 takes one round trip because the client *guesses*: its ClientHello already carries a key_share for a likely group (usually X25519). The server replies with ServerHello + its own key_share, and from that point everything — EncryptedExtensions, Certificate, CertificateVerify (a signature over the transcript proving possession of the private key), Finished — is already encrypted. The client sends Finished and application data in the same flight. If the guess was wrong the server sends HelloRetryRequest and it costs a second round trip. 1.3 also removed RSA key exchange, static DH, renegotiation, compression and every non-AEAD cipher, so the negotiation surface is small enough that downgrade tricks have little to attack. With a resumption PSK, 1.3 can send 0-RTT data in the first flight — replayable, so only for idempotent requests.

    The cost compounds with TCP: one RTT for the handshake (The Three-Way Handshake), plus one (1.3) or two (1.2), so a cold HTTPS request across a 150 ms path spends 300–450 ms before the first HTTP byte. That is why keep-alive, session resumption and TLS termination close to the user matter more than the cipher choice. Failures are legible: an alert such as handshake_failure (no common cipher/version) or protocol_version, a certificate alert after the Certificate message (client rejected it), a hostname mismatch when SNI was missing and the server presented a default certificate, or a silent hang when a middlebox drops something it does not understand. See The TLS Handshake and TLS Debugging: Why the Certificate Is "Invalid".

    Full interview question, with follow-ups and red flags →
  2. When your browser connects to a site over HTTPS, how does it decide that the server’s certificate is trustworthy? What can make that check fail even though the certificate is genuine?

    Show a strong answer

    A certificate is a signed statement: *this public key belongs to these names, valid between these dates, according to this issuer*. The client does not trust the statement because it is well-formed; it trusts it because it can build a path from it to a root it already holds. The server sends its leaf and the intermediate(s); the root is *not* sent — it must already be in the client’s trust store (the OS store, or the browser’s own, e.g. Mozilla’s for Firefox and the Chrome Root Program). For each link the client verifies the signature with the issuer’s public key, checks the issuer is allowed to issue (basicConstraints: CA, path length, key usage), and stops when it reaches a trusted root. See Certificates and the Chain of Trust.

    Then the leaf itself: the requested hostname must match a Subject Alternative Name (browsers ignore the Common Name); the current time must fall between notBefore and notAfter; the extended key usage must include server authentication; the signature algorithm and key size must be acceptable (SHA-1 and RSA-1024 are rejected); and the certificate must not be revoked — checked via OCSP, an OCSP response stapled by the server, or the browser’s own summary (CRLSets in Chrome, CRLite in Firefox). Chrome and Safari also require proof the certificate was logged in Certificate Transparency logs. Finally the handshake proves the server holds the *private* key: CertificateVerify in TLS 1.3, or the key exchange itself in 1.2 (The TLS Handshake). A stolen certificate without the key is useless.

    A genuine certificate fails in ways that are all about the *client’s* view. Missing intermediate: the server sends only the leaf; browsers often recover by fetching the issuer from the AIA URL or from cache, so the site "works in Chrome" while curl, Java, Python and Go fail with unable to get local issuer certificate. Unknown root: a corporate or private CA not installed on this machine, or a *new* public root missing from an old trust store — when Let’s Encrypt’s cross-sign from DST Root CA X3 expired in 2021, old Android devices and old OpenSSL 1.0 clients rejected perfectly valid chains. Clock skew: a device with the wrong date sees "not yet valid" or "expired". Hostname mismatch: the right certificate on the wrong vhost, a missing SNI so the default certificate is presented, or api.example.com reached via an IP address. Expired: the most common outage of all — Let’s Encrypt certificates last 90 days, and automation that silently stops renewing shows up exactly 90 days later.

    Full interview question, with follow-ups and red flags →
  3. Why can the server encrypt its certificate in TLS 1.3 but not in 1.2?

    Show a strong answer

    In 1.3 both key shares are exchanged in the first two messages, so a shared secret exists before the certificate is sent; in 1.2 the key exchange completes only after the certificate.

    Full interview question, with follow-ups and red flags →