# TLS

## 1. What TLS Actually Provides

**TLS (Transport Layer Security)** sits between the transport layer (TCP) and the application protocol (HTTP, most commonly — "HTTPS" is just "HTTP over TLS"), and provides three guarantees an application otherwise wouldn't have over a plain TCP connection:

```
Confidentiality — traffic is encrypted; an eavesdropper on the network sees ciphertext, not content
Integrity       — any tampering with traffic in transit is detectable
Authentication  — the client can verify it's actually talking to who it thinks it's talking to
```

None of these exist at the plain TCP layer — TCP guarantees ordered, reliable delivery of bytes, but says nothing about who sent them or whether anyone read them along the way.

## 2. The TLS Handshake (TLS 1.2, Conceptually)

Before any application data flows, client and server perform a **handshake** to agree on encryption parameters and establish a shared secret:

```
Client                                              Server
  |------ ClientHello ------------------------------>|
  |   (TLS versions supported, cipher suites,        |
  |    a random value, SNI hostname)                 |
  |                                                    |
  |<----- ServerHello --------------------------------|
  |   (chosen TLS version, chosen cipher suite,       |
  |    a random value)                                |
  |<----- Certificate ---------------------------------|
  |   (server's certificate + chain)                  |
  |<----- ServerHelloDone ------------------------------|
  |                                                    |
  |------ ClientKeyExchange -------------------------->|
  |   (key material, encrypted with the server's      |
  |    public key from its certificate)                |
  |------ ChangeCipherSpec + Finished ----------------->|
  |<----- ChangeCipherSpec + Finished -------------------|
  |                                                    |
  |======= encrypted application data flows now =======|
```

1. **ClientHello** — the client proposes what it supports (TLS version, cipher suites, and critically the hostname it's trying to reach, via **SNI**, covered in section 4).
2. **ServerHello + Certificate** — the server picks a cipher suite and TLS version from the client's list, and sends its certificate (proving its identity — section 3).
3. **Key exchange** — client and server derive a **shared symmetric session key** without ever transmitting that key itself in the clear (the exact mechanism depends on the cipher suite — modern deployments almost always use Diffie-Hellman-based key exchange for **forward secrecy**, meaning even if the server's private key leaks later, past sessions can't be decrypted retroactively).
4. **Finished** — both sides confirm the handshake completed correctly and switch to encrypted communication using the derived session key.

Everything *after* the handshake uses fast **symmetric** encryption (the shared session key) — the slower asymmetric (public/private key) cryptography is only used during the handshake itself, to safely establish that symmetric key.

## 3. Certificates and the Chain of Trust

A **certificate** binds a public key to an identity (a hostname) and is itself signed by a **Certificate Authority (CA)** — a party both client and server implicitly trust. The client verifies the server's certificate by walking a **chain of trust**:

```
Root CA certificate (pre-installed, trusted by the OS/browser)
   |  signs
   v
Intermediate CA certificate
   |  signs
   v
Server's certificate (for example.com)
```

The client checks: does the server's certificate's signature verify against the intermediate's public key? Does the intermediate's signature verify against the root's public key? Is the root one of the CAs the client already trusts (bundled in the OS/browser's trust store)? Does the certificate's hostname match the one being connected to? Is it within its validity period, and not revoked? Only if the entire chain checks out does the client trust the server's identity.

## 4. SNI — Server Name Indication

A single IP address can host many different HTTPS sites (this is extremely common — most CDNs and reverse proxies do exactly this). But TLS has to pick *which* certificate to present *before* it knows which site the client wants, because the HTTP request itself (which would normally carry the `Host` header) is encrypted and hasn't been sent yet at that point in the handshake.

**SNI** solves this: the client includes the target hostname, in plaintext, inside the ClientHello — before encryption is established. This lets the server pick the right certificate for the right site before the handshake proceeds. (This also means the hostname itself is visible to anyone observing the handshake, even though everything after it is encrypted — a privacy gap that **Encrypted Client Hello (ECH)**, a newer extension, aims to close.)

## 5. TLS 1.2 vs TLS 1.3

TLS 1.3 (2018) is a significant simplification and hardening of the protocol:

```
                    TLS 1.2                      TLS 1.3
Handshake round trips   2 (full round trip)        1 (fewer messages needed)
Cipher agility          many legacy/weak ciphers    only strong, modern ciphers allowed
Forward secrecy         optional (cipher-dependent) mandatory for all connections
0-RTT resumption        not supported                supported (with caveats — a resumed
                                                       session can send data on the very
                                                       first flight, at some replay risk)
```

TLS 1.3's single-round-trip handshake directly reduces the latency cost of establishing a secure connection — meaningful at internet scale, where every new connection pays this cost once.

![TLS 1.3 handshake: ClientHello with key share, ServerHello with key share, encrypted certificate and Finished, then client Finished and application data in one round trip](diagrams/01-tls13-handshake.svg)

## 6. Where TLS Terminates

In a typical production deployment, TLS doesn't necessarily run all the way to the application server. A reverse proxy or load balancer (see the HTTP proxy/reverse-proxy topic, and the network-level load balancer topic) often **terminates** TLS — decrypting the incoming request there, then forwarding it to backend services over plain HTTP within a trusted internal network.

```
Client <--- TLS (encrypted) ---> Reverse Proxy <--- plain HTTP (internal network) ---> App Server
                                  (TLS terminates here)
```

This centralizes certificate management (one place to renew/rotate certs, instead of every backend instance), offloads the CPU cost of encryption/decryption to a layer designed for it, and lets the proxy inspect/route based on the decrypted request. The tradeoff is that traffic between the proxy and the backend is unencrypted unless a second TLS hop is deliberately added (**TLS re-encryption**, sometimes required by compliance requirements for defense-in-depth inside the network too).

## 7. Common Pitfalls

1. **Assuming HTTPS means the whole path is encrypted end-to-end** — it's encrypted client-to-terminating-proxy; anything beyond a TLS-terminating reverse proxy is only as protected as that internal network makes it, unless re-encryption is explicitly configured.
2. **Confusing certificate validity with certificate trust** — a certificate can be "valid" (well-formed, unexpired, correct hostname) while being signed by a CA the client doesn't trust (e.g. a self-signed certificate); browsers reject the latter even though nothing about the certificate's *format* is wrong.
3. **Forgetting SNI means the hostname is visible in plaintext during the handshake** — TLS hides the request content, not which site you're connecting to, unless ECH is in play.
4. **Treating TLS termination at a proxy as "the connection is secure end to end"** — it secures client-to-proxy; internal-network traffic needs its own explicit protection if that matters for the threat model.
5. **Ignoring certificate expiration until it causes an outage** — an expired certificate breaks every client's handshake with a hard trust failure; this is one of the most common, entirely preventable causes of production incidents.

## 8. Quick Reference

```
TLS provides: confidentiality + integrity + authentication, on top of plain TCP

Handshake: ClientHello -> ServerHello+Certificate -> key exchange -> Finished -> encrypted data
  Asymmetric crypto used ONLY during handshake, to establish a symmetric session key
  Forward secrecy: session key compromise later doesn't expose past sessions (DH-based exchange)

Chain of trust: server cert -> intermediate CA -> root CA (pre-trusted by OS/browser)
  Client checks: signature chain, hostname match, validity window, revocation status

SNI: hostname sent in plaintext in ClientHello, so the server knows which cert to present
  (multiple HTTPS sites can share one IP because of this)

TLS 1.3 vs 1.2: 1 round trip (not 2), mandatory forward secrecy, no legacy weak ciphers, 0-RTT resumption option

TLS termination: where encryption stops being the client's problem and becomes internal-network traffic
  (commonly at a reverse proxy/load balancer — internal hops need their own protection if required)
```
