TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Diffie–Hellman and the Man in the Middle

Diffie–Hellman and the Man in the Middle

Two machines that have never met want a shared AES key, and everything they send can be read by an eavesdropper. Whitfield Diffie and Martin Hellman published the answer in 1976 (GCHQ's James Ellis, Clifford Cocks and Malcolm Williamson had found it secretly a few years earlier): each side sends one public number, and both end up with the same secret that the eavesdropper can't compute. Diffie–Hellman (DH) is inside virtually every TLS 1.3, SSH, IPsec and WireGuard connection. It also has one famous limitation: on its own it does not tell you who you share the secret with.

The exchange

Public parameters: a large prime pp and a generator gg. Alice picks a secret aa, Bob a secret bb.

Alice sends A=ga mod pBob sends B=gb mod pAlice computes Ba=gab mod pBob computes Ab=gab mod p\begin{aligned} \text{Alice sends } A &= g^a \bmod p \\ \text{Bob sends } B &= g^b \bmod p \\ \text{Alice computes } B^a &= g^{ab} \bmod p \\ \text{Bob computes } A^b &= g^{ab} \bmod p \end{aligned}

Both get gabg^{ab}. The eavesdropper sees pp, gg, AA and BB; to get gabg^{ab} they would need aa or bb, that is, a discrete logarithm. For well-chosen 2,048-bit groups (RFC 7919's ffdhe2048 and larger) nobody can compute it; for small groups anybody can. The theory is in Diffie–Hellman and The Discrete Logarithm.

Small numbers, then Mallory

python · try it yourself
p, g = 23, 5                      # toy group; real DH: 2048+ bit primes (RFC 7919) or X25519
a, b = 6, 15                      # Alice's and Bob's secrets (real: from a CSPRNG)
A, B = pow(g, a, p), pow(g, b, p)
print(f"Alice sends A = {A}, Bob sends B = {B}")
print("Alice computes", pow(B, a, p), " Bob computes", pow(A, b, p))
# An eavesdropper sees p, g, A, B. With p = 23, trying every exponent is instant:
a_found = next(x for x in range(p) if pow(g, x, p) == A)
print("eavesdropper's discrete log of A:", a_found, "-> key", pow(B, a_found, p))

# Active attacker Mallory in the middle, no authentication:
m = 9
M = pow(g, m, p)
print(f"Mallory replaces A and B with M = {M}")
k_alice = pow(M, a, p); k_bob = pow(M, b, p)
print(f"Alice's key {k_alice} = Mallory's {pow(A, m, p)};  Bob's key {k_bob} = Mallory's {pow(B, m, p)}")
print("Alice and Bob share a key:", k_alice == k_bob)
Alice sends A = 8, Bob sends B = 19
Alice computes 2  Bob computes 2
eavesdropper's discrete log of A: 6 -> key 2
Mallory replaces A and B with M = 11
Alice's key 9 = Mallory's 9;  Bob's key 10 = Mallory's 10
Alice and Bob share a key: False

With p=23p = 23: A=56 mod 23=8A = 5^6 \bmod 23 = 8, B=515 mod 23=19B = 5^{15} \bmod 23 = 19, and both sides compute 2. The eavesdropper breaks the toy by trying all 22 exponents; with a 2,048-bit pp that search, and every known shortcut, is out of reach.

The lab steps through the same numbers: the public p=23p = 23 and g=5g = 5 (order 22, a generator), A=8A = 8 and B=19B = 19 on the wire, both keys 2, and Eve's search, which finds x=6x = 6 after 6 tries. Turn Mallory on: with both of her secrets at 9 she sends M=11M = 11 each way, and the keys become 9 (Alice) and 10 (Bob), as in the program. Give her two different secrets and she simply holds two different keys. Two more things to try: g = 2 has order only 11 modulo 23, so it reaches just half of the possible values, and with p=997p = 997 the numbers grow but Eve's loop still ends at once.

Alicesecret a = 6Bobsecret b = 15Eve (listens)sees the wire onlypublic: p = 23, g = 5 (order of g mod p = 22, a generator)A = 5^6 mod 23 = 15625 mod 23 = 8B = 5^15 mod 23= 30517578125 mod 23 = 19A = 8B = 19receives B = 19receives A = 8s = 19^6 mod 23 = 2s = 8^15 mod 23 = 2shared secret: both have s = g^(ab) mod p = 2Eve saw p, g, A = 8, B = 19. Trying x = 1, 2, 3 … she finds g^x ≡ A at x = 6(6 tries). With a 2048-bit p that search is out of reach.A passive listener is beaten; an active one is not (turn Mallory on).

The man in the middle

The second half of the example is the real lesson. Mallory sits on the path (a rogue Wi-Fi access point, a poisoned ARP cache, a compromised router: see ARP Spoofing). She drops AA and BB and sends her own M=gmM = g^m to both. Alice now shares key 9 with Mallory, Bob shares key 10 with Mallory, and neither can tell: every value looks like a normal DH share. Mallory decrypts what Alice sends, reads or changes it, and re-encrypts it for Bob.

Alice Mallory Bob A = 8 (dropped) M = 11 M = 11 B = 19 (dropped) key 9: Alice and Mallory key 10: Mallory and Bob unauthenticated DH: each side agrees a key with the attacker

DH protects against passive eavesdroppers only. Against an active attacker the shares must be authenticated:

  • Signatures over the handshake: in TLS 1.3 the server signs the whole transcript, including both key shares, with the private key of its certificate (CertificateVerify). Mallory can't produce that signature for her own share without the server's private key.
  • Pre-known public keys: SSH's known_hosts, WireGuard's static peer keys, Signal's safety numbers.
  • A shared secret mixed in (pre-shared keys, PAKE protocols such as OPAQUE for passwords).

Group choices and their failures

  • Small or weak groups: the 2015 Logjam attack downgraded TLS to 512-bit "export" DH groups and computed discrete logs in minutes after a one-week precomputation per group; the authors estimated that a nation-state could precompute for the most widely shared 1,024-bit group.
  • Unsafe primes and unchecked shares: a peer who sends A=1A = 1, A=0A = 0 or an element of a small subgroup forces a predictable key unless the receiver validates it. Use groups with safe primes and check that 1<A<p−11 < A < p - 1.
  • Elliptic curves do the same job with much smaller numbers: ECDH on P-256 or, today mostly, X25519 (next lesson).

How weak key exchange is detected

  • TLS scans of your own servers: DH group size (openssl s_client -brief prints Server Temp Key: DH, 2048 bits or X25519), export or anonymous suites (ADH, aNULL), Logjam checks in testssl.sh.
  • SSH: ssh -Q kex lists supported algorithms; flag diffie-hellman-group1-sha1 (1,024-bit) and group14-sha1.
  • Missing authentication: protocols that run DH but don't sign the transcript or check a known key; TLS clients with verification disabled turn TLS into unauthenticated DH, exactly the toy above.
  • Network signals: an unexpected certificate or SSH host key change for a known server (WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!) is what a man in the middle looks like to an authenticated protocol.

How it is fixed

  • Use X25519 or P-256 ECDHE, or RFC 7919 finite-field groups of 2,048 bits and more; disable export, anonymous and 1,024-bit groups.
  • Always authenticate the exchange: certificate verification and host-name checks in TLS, host keys in SSH, pinned keys in internal protocols.
  • Use ephemeral keys for each session to get forward secrecy (next lesson).

Pitfalls

  • Thinking "the connection is encrypted, so it is safe": encryption with an unauthenticated key may be encryption to the attacker.
  • Accepting a host-key change prompt without checking out of band.
  • Reusing the same DH secret for months: a later compromise exposes every session that used it.

Practice

1. With $p = 23$, $g = 5$, Alice's secret $a = 4$ and Bob's $b = 3$, compute $A$, $B$ and the shared key.

A=54 mod 23=625 mod 23=4A = 5^4 \bmod 23 = 625 \bmod 23 = 4, B=53 mod 23=125 mod 23=10B = 5^3 \bmod 23 = 125 \bmod 23 = 10, key =104 mod 23=43 mod 23=18= 10^4 \bmod 23 = 4^3 \bmod 23 = 18.

2. A mobile app talks TLS to its API but sets verify=False to work around a certificate problem. Which part of this lesson describes the risk?

The man in the middle: without certificate verification, nothing authenticates the server's key share, so anyone on the network path can run the exchange with both sides and read everything.

3. Why can't Mallory simply forward Alice's real share $A$ to Bob and still read the traffic?

Then Alice and Bob would share gabg^{ab}, which Mallory can't compute from AA and BB alone. To read the traffic she must substitute her own shares, which authentication then exposes.

Test yourself

What does plain Diffie-Hellman protect against?

  1. Active man-in-the-middle attackers
  2. Passive eavesdroppers
  3. Malware on the endpoint
  4. Replay of old messages

How does TLS 1.3 stop a man in the middle from substituting key shares?

  1. It hides the key shares
  2. The server signs the handshake transcript with its certificate key
  3. It uses longer primes
  4. It encrypts the ClientHello

In the toy exchange with p=23p = 23, g=5g = 5, a=6a = 6, b=15b = 15, what is the shared key?

  1. 8
  2. 19
  3. 2
  4. 11

What did the Logjam attack exploit?

  1. A bug in AES
  2. Downgrades to weak 512-bit export DH groups and precomputation on shared groups
  3. Nonce reuse in GCM
  4. Weak RSA padding

In the lab with p = 23, g = 5, a = 6, b = 15, Mallory uses the secret 9 toward both sides. Which keys do Alice and Bob end up with?

  1. Both 2
  2. Alice 9 and Bob 10, each shared with Mallory
  3. Both 11
  4. Alice 8 and Bob 19