Introduction
After having explained on the previous article what is the Diffie Hellman key exchange protocol, in this present article I will talk about a possible attack that this protocol can suffer if no authentication of any party involved is performed.
The article will touch upon the following topics:
- what is and how it works the man in the middle attack in the context of the Diffie Hellman key exchange protocol;
- what is and how it works the parameter injection in the context of the Diffie Hellman key exchange protocol;
- what was the structure used in this prove of concept, and the results obtained;
- a quick demo of the attack taken place;
- a mitigation action to prevent this attack and why it works;
Man in the Middle Attack (MitM) explained
The Diffie Hellman key exchange protocol addresses the fundamental necessity of two independent parties to agree upon a secret key without any prior shared secret, even if their entire conversation is openly observed by an adversary.
The basic Diffie Hellman key exchange protocol, on its pure form, possesses a critical vulnerability, as it provides no inherent authentication of the parties involved.
This opens the door to a MitM attack, in such an attack, a malicious third party, often named Mallory, places itself between Alice and Bob, intercepting, passing or even altering their communications, all while each party believe they are communicating directly with each other.
Diffie Hellman (DH) key exchange quick recap
At its core, the DH key exchange protocol relies on the mathematical properties of the modular exponentiation and the computational difficulty of the Discrete Logarithm Problem (DLP), the main steps are:
-
Public agreed parameters: Alice and Bod first openly agreed on two large numbers, that are standardize [2].
- A large prime number, p.
- A generator g (a number whose powers modulo p generate a large set of number between [0, p-1] if p is a big prime number. These parameters are public and known to anyone, including the eavesdropper.
-
Private key generation: each party in this protocol uses a cryptographic secure pseudo random number generator (CSPRNG) to avoid predictability to choose a private key.
- Alice secretly chooses a large random integer number, her private key a such that 1<a<p-1.
- Bob secretly chooses a large random integer number, her private key b such that 1<b<p-1.
-
Public key generation: each party in this protocol performs the following calculation:
- Alice computes her public key: A = ga (mod p)
- Bob computes his public key: B = gb (mod p)
-
The exchange of public keys:
- Alice sends her public key A to Bob.
- Bob send his public key B to Alice. Even if a eavesdropper observes A, B, g and p, it is computationally infeasible for him to derive a and b due to the DLP difficulty.
-
Shared secret calculation:
- Alice computes the shared secret: K = Ba (mod p)
- Bob computes the shared secret: K = Ab (mod p)
They both arrive at the same exact shared secret K since:
Ba (mod p) = (gb)a (mod p) = gba (mod p) = K
Ab (mod p) = (ga)b (mod p) = gab (mod p) = K
The virtue of the DH key exchange protocol is that it provides the ability to establish a shared secret without never transmitting the secret itself. However, its main flaws is that it does not provide any mechanism for Alice to verify that she is truly exchanging keys with Bob, and on the same manner, that Bob is really exchanging keys with Alice, this is the reason why the MitM attack is possible.
Possible scenarios where the MitM attack can be executed
There are several practical scenarios where the MitM attack can be executed, here are some of them:
-
Public Wi-Fi eavesdropping:
- Scenario: A person connects to a free, open Wi-Fi newtwork in a public space.
- Attack: The attacker uses a rogue hotspot (e.g. "Free_Airport_WiFi") or is connected to the same network and uses packet sniffing tools (e.g. Wireshark or mitmproxy) to intercept unencrypted traffic.
- Result: If that person is visiting an unencrypted (non HTTPS) website, the attacker sees their persons credentials or session data.
-
SSL stripping:
- Scenario: A person is visiting a website that should be secure (HTTPS), but an attacker downgrades the connection to HTTP.
- Attack: The attacker intercepts the initial connection and removes the HTTPS encryption, forcing the user to use plain HTTP instead.
- Result: The attacker sees everything in plaintext.
-
ARP Spoofing (Local Network MitM):
- Scenario: A person is on the same local network as the attacker.
- Attack: The attacker sends fake ARP messages to associate their MAC address with the IP address of the gateway.
- Result: All the traffic of that user goes through the attacker's machine before reaching the service destination on the internet.
-
Compromised Router or internet service provider (ISP):
- Scenario: A home router is misconfigured or compromised.
- Attack: The attacker intercepts and alters the DNS queries or the HTTP traffic at the router level.
- Result: Redirected sites, credential theft or malware injection.
-
MitM in cryptography protocols (e.g.: Diffie Hellman key exchange protocol):
- Scenario: Alice and Bob are performing a key exchange protocol.
- Attack: The attacker intercepts the key exchange and establishes two independently and separated keys with Alice and Bob.
- Result: The attacker can read, modify and relay all encrypted messages between Alice and Bob.
MitM attack in Diffie Hellman key exchange protocol explained
The crucial part of this attack is that the attacker, Mallory, is able to set up two independent keys with Alice and Bob, here is a sequential walk through of the attack:
Alice initiates the Key Exchange: Alice generates her private key a and computes her public key A = ga (mod p). She sends p, g and A to Bob.
Mallory intercepts Alice's public key: Mallory intercepts Alice's message containing p, g and A to Bob.
Mallory impersonates Alice to Bob: Instead of forwarding Alice's actual public key to Bob, Mallory generates his own private key, let's consider mA. He then computes his own public key MA =gmA (mod p). Afterwards, Mallory sends p, g and MA to Bob, instead of the actual Alice's public key A.
Bob responds to Mallory (thinking it is Alice): Bob receives MA (thinking it is A instead). He generates his private key b, computes his public key B = gb(mod p), and calculates a shared secret with Mallory public key, instead of Alice's:
Kbm = (MA)b(mod p). Bob then sends his public key B back to Alice, unaware that is Mallory that is receiving it.Mallory intercepts Bob's public key: Mallory intercepts Bob's message containing B.
Mallory impersonates Bob to Alice: Instead of forwarding Bob's actual public key B to Alice, Mallory generates another private key, mB. He computes his own public key MB = gmB(mod p). Mallory them sends MB to Alice, pretending that MB is Bob's public key.
Alice completes the key exchange with Mallory (thinking it's Bob): Alice receives MB (thinking it is B). She then calculates a shared secret with Mallory instead of Bob: Kam = (MB)a (mod p).
In the end of this exchange, Mallory is in the possession of two separate shared secrets, such that:
- Alice believes she has established a shared secret Kam with Bob.
- Bob believes he has established a shared secret Kbm with Alice.
- Mallory knows both Kam and Kbm.
As Kam and Kbm are entirely different secrets, both Alice and Bob are communicating securely with Mallory instead with each other.
Attack in action
After Mallory has setup two distinct shared secrets with both Alice and Bob, he can now act as a transparent proxy, in the following manner:
Alice to Bob: When Alice encrypts a message using Kam and sends it to Bob, Mallory intercepts it and decrypts it using Kam also, reads the plaintext, and latter modifies or just pass the original message, encrypting it again now with Kbm before sending it to Bob.
Bob to Alice: When Bob encrypts a message using his symmetric key Kbm and then sends it to Alice, Mallory can intercept it and decrypt it, using Kbm. He can then read and/or potentially modify and afterwards re-encrypt it again using this time the Kam before sending it to Alice.
From both Alice and Bob's perspective, their communications seems secure and private, they have no clue that their messages are being read or potentially altered by a third party.
This complete failure on confidentiality and integrity is the consequence of MitM attack when there is no authentication on the Diffie Hellman key exchange protocol.
MitM attack with parameter injection with prime p
One variant of the MitM attack is the parameter injection, in this example with the prime p as the parameter injected. This attack forces the shared secret between the two parties to become a known and trivial value as I will try to show next.
This result is achieved by means of the properties of the modular arithmetic to fix the shared secret between Alice and Bob to zero o by injecting the prime p itself, here follows the steps with Mallory's injection strategy:
Alice initiates the Key Exchange: Alice generates her private key a and computes her public key A = ga (mod p). She sends p, g and A to Bob.
Mallory intercepts Alice's public key (A): Mallory intercepts A. Instead of him generating his own public key he performs the substitution in the next step.
Mallory injects p to Bob: Mallory sends the large prime p instead of his public key, pretending it is Alice's public key, MA = p.
Bob's shared secret calculation: Bob receives MA = p (thinking it is Alice's A). He then computes his shared secret Kbm using this private key b.
Kbm = (MA)p (mod p) <=> Kbm = pp (mod p) <=> Kbm = 0 because any positive integer power of p will always be a multiple of p.Bob's public key calculation: Bob computes his public key B = gb (mod p) and sends it towards Alice.
Mallory intercepts Bob's public key (B): Mallory intercepts B and then performs the same substitution for p instead.
Mallory injects p to Alice: Mallory sends the large prime number p itself to Alice, pretending it is Bob's public key, so Alice receives MB = p.
Alice's shared secret calculation: Alice receives MB = p (thinking it is Bob's B). She then computes his shared secret Kam using this private key a.
Kam = (MB)p (mod p) <=> Kam = pp (mod p) <=> Kam = 0 because any positive integer power of p will always be a multiple of p.
At the end of this MitM attack variant, both Alice and Bob believe they have successfully established a shared secret, however, unknown to them, that shared secret is zero, so Mallory can do the following:
- Trivial key derivation: If Alice and Bob then proceed to derived a symmetric encryption key (e.g. AES) hashing they shared secret (e.g. SHA-256(sharedSecret), they will both compute SHA-256(0) )
- Mallory's advantage: Since Mallory also knows the shared secret 0, he can also independently compute the exact same SHA-256(0) symmetric key.
- Complete compromise: Any further communication encrypted by Alice and Bob's using this derived key can be trivially decrypted so he then can read and potentially also modify and encrypt again the message.
This complete failure on confidentiality and integrity in this variant of the MitM attack is also the effect of having no authentication on the Diffie Hellman key exchange protocol.
MitM attack to the DH key exchange protocol implementation:
In this section is is presented a practical implementation of the MitM attack to the DH key exchange protocol, in this example the public parameters p and g are picked from the MODP groups present in the RFC3526 [2], each party also generates a nonce for each session created.
Mallory in this example is replacing the URL of the real server.
In a real word scenario the initial communication between the two would need to be downgraded to HTTP and Mallory would need to use a software like Wireshark or mitmproxy to catch the data between the two, change it and send it afterwards to the destiny.
The class diagram of this solution is present at figure 1:
The communication between the client and the server is done via HTTP requests and it is the client that has the initiative on this protocol.
The server exposes three endpoints:
- one to execute the DH key exchange protocol via the POST /keyExchange.
- one to retrieve all the session keys created on the server side via the GET /sessionsData.
- one to perform a secure message exchange with a client after the DH key exchange protocol has been completed via the GET /messageExchange.
The sequence diagram of this attack is shown next, figure 2, it is possible to see in detail the actions that the attacker Mallory is performing to the DH key exchange protocol in the initial POST /keyExchange endpoint and afterwards on the GET/messageExchange itself (full diagram in .svg format in the link above).
Next follows a quick demo of this attack, video 1, with the client on the left screen, Mallory's fake server in the middle screen and real server on the right. The client will try to perform the POST /keyExchange first, and as it succeeds, it will latter also perform the GET /messageExchange message, both communications will pass the client verification's, so he remains oblivious of the actions of Mallory the whole time.
All the requests from the client are relayed by the fake Mallory server to the real server, in spite of that, there is no error being triggered by the real server as is possible to see on this demo.
In figure 3 it is possible to observe the output of the GET /sessionsData after the client has done the requests, both the Mallory's fake server and the real server have the same session id and client id on their databases but the other session's data such as nonce's and derived symmetric key's are different as the communication's channel session data are entirely different between those two sessions.
How to protect against a MitM attack against the DH key exchange protocol
The MitM attack exposes a critical vulnerability in the original Diffie Hellman key exchange, namely the lack of authentication. While DH key exchange protocol was able to solve very cleverly the problem of establishing a shared secret over an insecure channel, it doesn't verify the identities of the parties involved.
To secure Diffie Hellman against MitM attacks, the messages exchanged between Alice and Bob, namely their public keys A and B, must be authenticated. This ensures that the public keys received truly belong to Alice and Bob, preventing Mallory from replacing her own keys.
The most common and effective way to authenticate public keys in a Diffie Hellman key exchange is through the use of digital signatures, often supported by a Public Key Infrastructure (PKI) and X.509 certificates.
X.509 certificates can contain the following main information:
- public key associated with the entity that is trying to authenticate, Alice or Bob in this case.
- Details about the entity, namely a domain name for a website or a user's name for a person.
- Serial number: an unique identifier to identify the certificate.
- Signature Algorithm: Indicates the cryptographic algorithm used to sign the certificate.
- Validity period: defines the start and end dates during witch the certificate is considered valid.
With this update in the protocol, here is the how the DH key exchange would look like:
-
Introduction to a Trusted Certificate Authority (CA): Before the communication starts, Alice and Bob obtain a digital certificate from the CA, this certificate binds the public key to an identity (e.g. a domain name or a person). The CA digitally sign this certificate, ensuring the identity's ownership of the public key.
Built of the certificate:
- Subject's info
- Subject's public key
- Validity dates
- Extensions info
- Issuer info
Hashes the to be signed data (TBS)
Example: digest = SHA-256(TBS_data)Signs the hash using the CA private key:
Signature = EncryptCA(digest, privateKeyCA)Attaches the signature to the certificate:
the full certificate X.509 now has the following fields:- To be signed data
- Signature algorithm (e.g.: SHA-256)
- Signature
-
Alice and Bob exchange certificates and their DH public keys:
- When Alice initiates the connection, she sends her Diffie Hellman public key (A = ga (mod p)) along with her digital certificate.
- When Bob responds, he sends his Diffie Hellman public key (B = gb (mod p)) along with his digital certificate.
-
Verification of identities and public keys:
- Receives the certificate (e.g. during TLS handshake) with the information about the other party involved.
- Extracts from the certificate the signature and the to be signed data.
- Recomputes the hash with the public key received with the signature algorithm, as an example: digest = SHA-256(to_be_signed_data)
- Decrypts de received signature using the CA's public key: decryptedDigest = decryptCA(signature, publicKeyCA)
- Compares the two digests: if digest == decryptedDigest: -> Certificate is valid and authentic, the public key is verified else: -> Certificate is invalid or tampered
This works because only the CA knows its private key, so only CA could have produced a valid signature. In the same manner, anyone with the CA's public key can verify that the certificate hasn't been forged and/or altered by some attacker.
In a real world scenario, such as TLS (HTTPS) the server sends the certificate to the client's browser, the client's browser then verifies the validity of the certificate received using for that matter the trusted CA root public key. [3]
If the certificate is verified, the client's browser trust the server's identity and public key, allowing the Diffie Hellman secure key exchange to proceed - Diffie Hellman with authentication.
References:
[1] Sousa, T. (2024, April 23). Diffie-Hellman Key Exchange Protocol. Available at LinkedIn: https://www.linkedin.com/pulse/diffie-hellman-key-exchange-protocol-tiago-sousa-tlgpf
[2] D. Kivinen and H. Krawczyk, "More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)," IETF RFC 3526, May 2003. Available at: https://datatracker.ietf.org/doc/html/rfc3526.
[3] Rescorla, E. The Transport Layer Security (TLS) Protocol Version 1.3, RFC 8446, IETF, August 2018. Available at: https://datatracker.ietf.org/doc/html/rfc8446



Top comments (0)