12 min readSecurity fundamentals

TLS Handshake in HTTPS: How Browsers Negotiate Encrypted Web Connections

Explore how TLS 1.3 and 1.2 handshakes verify server identity, derive forward-secret AEAD keys, prevent downgrade attacks, and handle 0-RTT replay tradeoffs.

Technical illustration: Inside Your Browser: How HTTPS and the TLS Handshake Secure Your Webpage Connection

At 2

AM, an on-call engineer sees a sudden spike in HTTP 502 errors behind a reverse proxy while direct health checks against localhost continue to pass. The culprit is rarely the application framework itself; more often, the Transport Layer Security (TLS) handshake failed to agree on a protocol version, key-exchange group, or certificate chain before a single byte of HTTP ever crossed the wire. Most developers treat the browser padlock as a binary toggle, assuming traffic is either encrypted or plaintext, yet that padlock represents a strict cryptographic state machine that must succeed under tight latency and trust constraints.

To understand what unfolds in the 15 to 40 milliseconds before a webpage loads, picture two strangers trying to hold a confidential business meeting across a crowded, untrusted room where anyone can eavesdrop, shout forged instructions, or impersonate the host. Before exchanging sensitive numbers, they need three guarantees: proof that the host truly is who they claim to be, a shared private language no listener can decode, and a tamper-evident seal on every sentence so no bystander can alter or reorder words mid-flight. In HTTPS, HTTP supplies the conversation, while the TLS handshake runs that introductory ritual over TCP (or QUIC) before application data moves.

What Guarantees Does the TLS Handshake Establish Before HTTP Begins?

The TLS handshake establishes three distinct cryptographic properties before any HTTP request or response leaves the socket: server authentication, confidentiality through ephemeral session keys, and message integrity against tampering or truncation. Unless mutual TLS (mTLS) is explicitly configured, the handshake verifies only the server's identity to the client, leaving user identity verification to higher application layers such as cookies, tokens, or passkeys.

History shaped the modern handshake through painful cryptographic failures. Netscape's original Secure Sockets Layer (SSL 2.0 and SSL 3.0) suffered from severe flaws in padding validation, weak MAC constructions, and export-grade cipher downgrades, prompting the IETF to standardize Transport Layer Security starting with TLS 1.0. Over the following two decades, attacks targeting CBC-mode padding (such as POODLE and BEAST) and RC4 stream biases forced the deprecation of TLS 1.0 and TLS 1.1 under RFC 8996 in March 2021. Today, TLS 1.2 and TLS 1.3 are the only versions permitted on modern production endpoints, and mainstream browsers refuse legacy handshakes outright.

Crucially, the handshake separates long-term identity from short-term traffic encryption. A server holds a long-lived asymmetric private key paired with an X.509 certificate signed by a trusted Certificate Authority (CA), functioning like a verifiable passport. Rather than using that long-lived key to encrypt webpage payloads directly, modern TLS uses it only to sign a fresh, temporary key agreement. That separation ensures that even if an attacker steals the server's private key years later, previously recorded network captures remain mathematically unrecoverable.

How Does a TLS 1.3 Handshake Establish Keys in One Round Trip?

TLS 1.3 (standardized in RFC 8446) cuts handshake setup down to a single network round trip (1-RTT) by packing the client's cryptographic preferences and its ephemeral public key share into the very first message. As soon as the server replies with its own key share, both endpoints independently compute identical shared secrets and encrypt the remainder of the handshake itself.

In the first flight, the browser completes the TCP three-way handshake and immediately sends ClientHello. Inside ClientHello, the browser proposes a 32-byte random nonce, a list of supported AEAD (Authenticated Encryption with Associated Data) cipher suites such as TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, or TLS_CHACHA20_POLY1305_SHA256, and critical protocol extensions. The server_name (SNI) extension reveals which hostname the browser intends to reach so multi-tenant proxies can pick the matching certificate, while application_layer_protocol_negotiation (ALPN) negotiates h2 or http/1.1 without an extra round trip. Most importantly, supported_groups advertises acceptable Diffie-Hellman or post-quantum hybrid groups (such as x25519, prime256v1, secp384r1, or X25519MLKEM768), and key_share speculatively includes the client's freshly generated ephemeral public key for its preferred group.

In the second flight, the server processes ClientHello, picks one mutually supported cipher suite and matching group, generates its own 32-byte random nonce, and creates a fresh ephemeral key pair for that group. The server immediately writes ServerHello carrying the chosen suite and its own public key_share. At that exact boundary, both peers possess each other's ephemeral public shares and execute Elliptic Curve Diffie-Hellman (ECDHE) or hybrid key encapsulation to derive an identical raw shared secret. Passing that secret and the hash of ClientHello plus ServerHello through the HMAC-based Key Derivation Function (HKDF) yields symmetric handshake traffic keys. Consequently, every subsequent server message in Flight 2 (EncryptedExtensions, Certificate, CertificateVerify, and Finished) travels encrypted on the wire, shielding the server's certificate and identity from passive network sniffers.

In the third flight, the browser validates the server's certificate chain, checks the CertificateVerify signature, and verifies the MAC inside the server's Finished message. If every check passes, both endpoints advance their HKDF key schedule to derive final application traffic keys. The browser emits its own encrypted Finished message and, without waiting for another server acknowledgment, immediately pipelines its first encrypted HTTP request in the same TCP flight.

sequenceDiagram participant C as "Client (Browser)" participant S as "Origin Server" C->>S: ClientHello with SNI, ALPN, AEAD suites, and key_share S->>C: ServerHello with chosen suite and server key_share Note over C,S: Both sides compute shared secret and derive handshake traffic keys S->>C: EncryptedExtensions, Certificate, CertificateVerify, Finished Note over C: Verify CA chain, SAN hostname, and transcript signature C->>S: Finished plus first encrypted HTTP request S->>C: Encrypted HTTP response

What happens when a browser speculatively sends an x25519 key share in ClientHello, but a compliance-hardened server insists on secp384r1 or X25519MLKEM768? Instead of dropping the socket, the server responds with a HelloRetryRequest (encoded as a ServerHello carrying a fixed sentinel random value) instructing the client which group from supported_groups to use. The browser then sends an updated ClientHello containing the requested key_share, trading one extra network round trip for clean negotiation while preserving every TLS 1.3 security invariant.

How Does TLS 1.2 Differ from TLS 1.3 Under the Hood?

TLS 1.2 requires two full round trips before sending application data because key exchange takes place in dedicated messages after ServerHello, and it transmits the server's certificate chain in plaintext. It also permits legacy primitives such as static RSA key transport and CBC-mode ciphers that either lack forward secrecy or invite padding-oracle side channels.

In a TLS 1.2 handshake, the client's ClientHello carries supported cipher suites and curves, but no ephemeral key share, because the client cannot yet predict which algorithm the server will pick. The server replies with ServerHello, an unencrypted Certificate message, ServerKeyExchange (containing its signed ephemeral Diffie-Hellman public parameters), and ServerHelloDone. Only during the second round trip does the client validate the certificate, transmit ClientKeyExchange, emit ChangeCipherSpec to activate symmetric encryption, and send Finished. The server must return its own ChangeCipherSpec and Finished before the first HTTP byte can move.

Those structural differences left TLS 1.2 exposed to subtle configuration hazards. Legacy TLS_RSA_* suites skipped Diffie-Hellman entirely: the client encrypted a 48-byte premaster secret under the server's public RSA key, meaning compromise of that single long-lived private key retroactively unlocked years of recorded traffic. Static Diffie-Hellman suites (TLS_DH_* and TLS_ECDH_*) failed on forward secrecy for the exact same reason. Even ephemeral finite-field Diffie-Hellman (TLS_DHE_*) introduced operational fragility in TLS 1.2: servers lacked standard parameter negotiation unless ffdhe groups from RFC 7919 were enforced, and custom or oversized primes fueled CPU exhaustion denial-of-service vulnerabilities (such as CVE-2002-20001 and CVE-2022-40735) alongside construction weaknesses highlighted in RFC 9325 Section 4.1. TLS 1.3 eliminated these entire classes of failure by removing RSA key transport, removing static DH, removing CBC ciphers, and restricting key agreement to vetted named groups.

Property Hardened TLS 1.2 TLS 1.3 (RFC 8446) Security and Operational Impact
Standard handshake latency 2-RTT before HTTP request 1-RTT (0-RTT on resumption) Cuts initial connection setup latency in half
Certificate visibility Transmitted in plaintext Encrypted after ServerHello Hides server identity and certificate metadata from passive observers
Key exchange modes RSA, static DH, DHE, ECDHE Ephemeral ECDHE or hybrid ML-KEM Guarantees forward secrecy on every connection
Cipher suites Mix of CBC and AEAD Strictly AEAD (AES-GCM, ChaCha20-Poly1305) Eliminates padding-oracle and MAC-then-encrypt flaws
Compression and renegotiation Optional (historically abused) Removed from protocol Prevents CRIME compression leaks and renegotiation flaws

How Do Certificate Verification and HKDF Prevent Impersonation and Tampering?

Encryption alone offers zero protection if your browser establishes a shared secret with an active attacker, so TLS binds key exchange to server identity through X.509 chain validation and a cryptographic signature over the entire handshake transcript. In parallel, the TLS 1.3 key schedule feeds that shared secret through HKDF alongside the transcript hash so every derived key depends on the exact negotiation messages both peers observed.

When a client receives the Certificate message, it enforces four checks before accepting the key inside. First, it builds a signature path from the leaf certificate through any intermediate certificates up to a root CA trusted by the operating system or browser root store. Second, it validates that the current time sits within every certificate's notBefore and notAfter bounds and verifies revocation status and Certificate Transparency compliance. Third, it matches the target URL hostname against the leaf certificate's Subject Alternative Name (SAN) extension, rejecting valid CA-signed certificates issued to unrelated domains. Fourth, the client validates the signature inside CertificateVerify. That signature covers a context string concatenated with the cryptographic hash of all handshake messages sent so far. Because the signature binds to the running transcript hash, an active attacker cannot replay a stolen certificate from another session or tamper with ClientHello cipher preferences without breaking CertificateVerify and Finished.

Once authentication and key exchange succeed, TLS 1.3 derives isolated keys in sequential stages using HKDF-Extract and HKDF-Expand-Label. An Early Secret (used only when Pre-Shared Keys are present) feeds into the Handshake Secret, which mixes in the ephemeral shared secret to produce separate client_handshake_traffic_key and server_handshake_traffic_key values. Mixing once more yields the Master Secret, which expands into client_application_traffic_key and server_application_traffic_key. Each directional key pairs with a base initialization vector (IV) XORed with a monotonically incrementing 64-bit per-record sequence number to build a unique nonce for AES-GCM or ChaCha20-Poly1305. Because the sequence number is implicit and the TLS record header is authenticated as Additional Authenticated Data (AAD), flipping a single ciphertext bit, dropping a record, or reordering packets causes immediate AEAD authentication failure and connection termination.

flowchart TD CS["Ephemeral Shared Secret (ECDHE / X25519MLKEM768)"] --> HS["HKDF-Extract: Handshake Secret"] TH1["Transcript Hash (ClientHello + ServerHello)"] --> HS HS --> HTK["Handshake Traffic Keys (Encrypts Certificate and Finished)"] HTK --> CV["Server Signs Transcript via CertificateVerify"] CV --> VER["Client Verifies CA Chain, SAN Hostname, and Signature"] HS --> MS["HKDF-Extract: Master Secret"] TH2["Full Handshake Transcript Hash"] --> MS MS --> ATK["Application Traffic Keys (AEAD Encrypts HTTP Traffic)"] VER --> ATK

Why Do Naive TLS Clients and Server Configurations Still Fail?

Even when servers support TLS 1.3, misconfigured clients routinely disable certificate checks during local debugging and ship that bypass to production, while misconfigured servers leave downgrade vectors or incompatible post-quantum curve settings in place. Encryption stripped of strict identity validation or sound parameter negotiation creates an illusion of safety while remaining trivially exploitable.

Consider a common Node.js pitfall during local service-to-service testing. When hitting a development endpoint using a self-signed certificate on 127.0.0.1, developers often add rejectUnauthorized: false to make errors disappear. That option does far more than trust one local certificate: it disables CA chain verification and hostname matching entirely, allowing any active network attacker to intercept traffic with a forged certificate while the application logs a clean encrypted connection. The safe alternative pins the local development CA explicitly and enforces a modern minimum TLS version.

const fs = require('fs');
const https = require('https');
 
// VULNERABLE: Encrypts traffic, but disables CA and hostname checks (active MITM succeeds)
const insecureAgent = new https.Agent({
  rejectUnauthorized: false,
});
 
https.get('https://127.0.0.1:8443/health', { agent: insecureAgent }, (res) => {
  console.log('Insecure client status:', res.statusCode);
});
 
// HARDENED: Trusts explicit local CA, enforces SAN hostname match and TLS 1.3
const hardenedAgent = new https.Agent({
  ca: fs.readFileSync('./certs/local-ca.pem'),
  minVersion: 'TLSv1.3',
  servername: 'app.example',
});
 
https.get('https://127.0.0.1:8443/health', { agent: hardenedAgent }, (res) => {
  console.log('Hardened client status:', res.statusCode);
});

Server-side configurations suffer equally from legacy compatibility compromises. Leaving TLS 1.0 or TLS 1.1 active without TLS_FALLBACK_SCSV lets an active attacker force clients onto weaker handshakes, while enabling TLS compression leaks secret session cookies through chosen-plaintext compression ratios (the CRIME attack, which motivated removing compression completely in TLS 1.3). When a hard business requirement forces interoperability with end-of-life clients that cannot speak TLS 1.2 AEAD or TLS 1.3, never weaken your primary production listener. Isolate those legacy clients on a dedicated hostname and endpoint with zero access to sensitive cookies or privileged APIs.

Deploying post-quantum hybrid key exchange introduces a newer operational trap around OpenSSL versions. To defeat "harvest now, decrypt later" collection, modern browsers negotiate X25519MLKEM768, combining classical X25519 with post-quantum ML-KEM-768. However, X25519MLKEM768 and related ML-KEM groups require OpenSSL 3.5 or later. Earlier releases such as OpenSSL 3.0 do not recognize the group name: listing X25519MLKEM768 in NGINX's ssl_ecdh_curve or Apache's SSLOpenSSLConfCmd Curves causes the web server to fail startup immediately. Worse, placing X25519MLKEM768 inside an openssl.cnf Groups line on OpenSSL 3.0 causes OpenSSL to silently ignore the entire Groups directive without raising an error, leaving unintended default groups active. Always check openssl version or nginx -V before enabling ML-KEM groups across a fleet.

server {
    listen 443 ssl;
    http2 on;
    server_name app.example;
 
    ssl_certificate     /etc/ssl/certs/app.example.fullchain.pem;
    ssl_certificate_key /etc/ssl/private/app.example.key;
 
    # Enforce TLS 1.3 primary, TLS 1.2 AEAD fallback only
    ssl_protocols TLSv1.3 TLSv1.2;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;
 
    # Include X25519MLKEM768 only when linked against OpenSSL 3.5+
    ssl_ecdh_curve X25519MLKEM768:x25519:prime256v1:secp384r1;
 
    # Disable 0-RTT early data unless backend explicitly handles replay
    ssl_early_data off;
}

What Are the Operational Tradeoffs of 0-RTT Early Data and Handshake Debugging?

TLS 1.3 zero-round-trip (0-RTT) session resumption eliminates handshake wait time by attaching encrypted HTTP data directly inside Flight 1 alongside ClientHello, yet it gives up replay protection across connections. Because an active attacker on the wire can capture and replay that initial packet before fresh ephemeral entropy completes the handshake, enabling 0-RTT indiscriminately turns routine network traffic into a replay vulnerability.

During a completed 1-RTT session, a server can send a NewSessionTicket carrying a Pre-Shared Key (PSK) identifier. On return visits, the client derives an early traffic key from that PSK and transmits early HTTP data immediately. As RFC 8446 Sections 2.3 and 8 specify, 0-RTT data is neither forward-secret on its own nor protected against replay across distributed servers unless every edge node synchronizes single-use ticket strike registers, which adds prohibitive latency at scale. Although RFC 8470 Section 4 restricts clients to safe HTTP methods such as GET inside early data, real-world web applications frequently trigger side effects on GET requests, including logout links, email confirmation tokens, or OAuth state callbacks.

For most services, leaving ssl_early_data off (the default in NGINX) is the cleanest operational choice, trading one round trip on resumed sessions for complete immunity to TLS-layer replay. If latency telemetry justifies enabling 0-RTT on an edge proxy or CDN, you must surface that state downstream: configure the proxy to inject the Early-Data: 1 HTTP header and have the application reject any non-idempotent route or sensitive GET endpoint with HTTP 425 Too Early. That status tells compliant clients to wait until the 1-RTT handshake completes and retry safely. Remember that Early-Data: 1 mitigates replay only at the TLS layer and never replaces CSRF protection or idempotency keys.

function rejectUnsafeEarlyData(req, res, next) {
  const isEarlyData = req.headers['early-data'] === '1';
  const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS']);
 
  // Reject non-idempotent methods or state-changing GET routes arriving in 0-RTT
  if (isEarlyData && (!safeMethods.has(req.method) || req.path.startsWith('/auth/'))) {
    res.set('Retry-After', '0');
    return res.status(425).send('Too Early: retry after TLS handshake completes');
  }
  return next();
}

Finally, never verify TLS posture from config files alone; inspect the live handshake and instrument production telemetry. Running openssl s_client against your local loopback or staging proxy exposes the exact protocol version, cipher suite, negotiated key-exchange group, ALPN selection, and full certificate verification code before a release ships. In production, logging TLS version and cipher fields at your reverse proxy gives your security team concrete visibility into client capabilities, making it safe to retire TLS 1.2 fallbacks without breaking legitimate users.

openssl s_client -connect 127.0.0.1:8443 -servername app.example -alpn h2
# Confirm negotiated security properties in the output:
#   Protocol  : TLSv1.3
#   Cipher    : TLS_AES_256_GCM_SHA384
#   Server Temp Key: X25519, 253 bits
#   ALPN protocol: h2
#   Verify return code: 0 (ok)

References & Sources

Related Security Reads

Comments

No comments yet.

Comments are moderated before they appear.

Get new posts by email

No ads, no tracking. Just new posts, unsubscribe any time.