What is a Man-in-the-Middle attack on plain Diffie-Hellman, and what is the defense?
An attacker (Mallory) intercepts the public values, completes one DH exchange with each side using her own private values, and ends up with one shared key with Alice and a different one with Bob — silently relaying (and reading) every message. The defense is authenticating the public values (typically via digital certificates).
The attack flow:
- Alice → Mallory (thinking Bob):
A = g^a mod p. - Mallory → Bob (impersonating Alice):
M_A = g^m mod p. - Bob → Mallory (thinking Alice):
B = g^b mod p. - Mallory → Alice (impersonating Bob):
M_B = g^m' mod p. - Now Alice computes
K1 = M_B^a = g^(am') mod pthinking it's a shared secret with Bob; Mallory computes the same value. - Bob computes
K2 = M_A^b = g^(bm) mod pthinking it's shared with Alice; Mallory computes the same value too. - Alice ↔ Mallory (with K1) ↔ Mallory ↔ Bob (with K2). Mallory decrypts on one side and re-encrypts on the other — totally invisible to Alice and Bob.
Why DH alone can't prevent this: the math proves "whoever sent A knows a", but says nothing about who A's sender actually is.
Defense — bind public keys to identities:
- Digital certificates (CA-signed) —
Aarrives with a signature from a trusted CA attesting "this public value belongs to Bob." - Authenticated DH variants — DH-SIG, station-to-station protocol, TLS handshake. All combine DH key exchange with a digital signature over the exchanged values.
- Trust-on-first-use + pinning (SSH model) — display the server's key fingerprint on first connect; refuse if it changes.
Tip: This is the reason TLS isn't just "open a TLS connection." TLS combines DH with certificate validation — without that, every WiFi sniffer at Starbucks could MITM your bank.