Sub topic 7
How two peers agree on keys
This chapter assumes you know what encapsulation is, understand the confidentiality, integrity and authentication goals from the previous chapter, and can read a Linux command line. It explains how two machines that have never met agree on a shared secret over a network anyone can watch. It also covers how each machine knows the other is the right one.
The problem: a secret from nothing
Symmetric ciphers such as AES-GCM or ChaCha20-Poly1305 are fast, and VPNs use them to protect every data packet. Both ends need the same key. Sending that key over the network in the clear defeats the purpose, because an eavesdropper would read it.
Key exchange solves this. Two peers run a short protocol and each ends up with the same secret. An observer who recorded every message cannot compute that secret. Authentication is a separate step. A key exchange alone tells you that you share a key with someone, not with whom.
Keep two questions apart throughout this chapter:
- Key agreement: how do we derive a shared secret?
- Peer authentication: how do we know who is on the other end?
If either one is missing, the VPN is broken. Agreement without authentication lets an attacker sit in the middle. Authentication without fresh agreement means one stolen key exposes all past traffic.
Diffie-Hellman: agreeing in public
Diffie-Hellman (DH) is the classic key agreement method. Each side generates a private value and computes a public value from it. They swap the public values and each combines its own private value with the other's public value. Both get the same result.
Real implementations use elliptic curves. The common choice is Curve25519, in a variant called X25519. The principle is the same: computing the public value from the private one is easy, and reversing it is believed to be infeasible.
The exchange looks like this:
An eavesdropper sees A_pub and B_pub but has neither private value, so cannot compute the secret.
The shared secret is not used directly as a cipher key. A key derivation function (KDF), such as HKDF, turns it into one or more keys of the right length. It usually mixes in extra context, such as the handshake transcript. Separate keys are derived for each direction and each purpose.
Why the keys must be ephemeral
An ephemeral key pair is generated fresh for a session and discarded afterwards. When both sides use ephemeral DH, the session keys have forward secrecy (also called perfect forward secrecy). If an attacker later steals a long-term key, they still cannot decrypt traffic they recorded earlier, because the session keys were never derived from that long-term key and the ephemeral private values are gone.
Without forward secrecy, an adversary can store encrypted traffic today and decrypt it the day a long-term key leaks. This matters because VPN traffic is easy to capture in bulk.
Sessions are also rekeyed regularly. IPsec rekeys by time or byte count. WireGuard rekeys after a couple of minutes of use. Rekeying limits how much data any one key protects.
Authentication: who am I talking to?
Plain DH is vulnerable to a man-in-the-middle (MITM) attack. An attacker intercepts the exchange, runs one DH with A and another with B, and relays traffic between them while reading it. Neither victim notices, because each did complete a key exchange.
The fix is to authenticate the exchange. Each peer proves its identity in a way the attacker cannot forge. VPNs use three main approaches.
| Method | How the peer proves identity | Used by | Main cost |
|---|---|---|---|
| Pre-shared key (PSK) | Both sides know the same secret in advance | IPsec, OpenVPN static key mode, optional layer in WireGuard | Distributing and rotating the secret; one leak affects everyone sharing it |
| Public key, known in advance | Peer signs or uses a long-term key whose public half you already hold | WireGuard, SSH host keys | Exchanging public keys out of band |
| Certificates | A trusted certificate authority (CA) vouches that a public key belongs to a name | IPsec, TLS-based VPNs | Running a CA, issuing, expiring and revoking certificates |
Public keys
An asymmetric key pair has a private key you never share and a public key you hand out freely. A public key can be shared safely over an untrusted channel, but you still need to be sure it is the right one. If an attacker swaps in their own public key during distribution, they win. That is why public keys are verified through some channel the attacker does not control: reading a fingerprint aloud, an administrator's configuration management, or a signature from someone you already trust.
Certificates and CAs
A certificate binds a public key to an identity, such as a hostname or an employee, and carries a signature from a CA. If your device trusts the CA, it trusts any certificate the CA signed that is valid, unexpired and not revoked. This scales to thousands of peers, because you distribute one CA certificate instead of every peer's key. The price is operational: you must run the CA, protect its private key, and handle revocation when a laptop is lost.
Pre-shared keys
A PSK is the simplest method and the easiest to misuse. A weak PSK, such as a short dictionary word, can be attacked offline if the handshake exposes enough material to test guesses against. Use a long random value, generate it with a proper tool, and use a different one for each pair of peers. Do not reuse a PSK as a password for something else.
How the main VPNs apply this
The same building blocks appear in each system, arranged differently.
- IPsec (IKE): The IKE protocol runs a DH exchange, then authenticates with PSKs or certificates. It then derives the keys for ESP, the protocol that carries the data. IKE can also create further child keys for individual traffic selectors without a full new authentication.
- TLS-based VPNs: These use the TLS handshake, which has an ephemeral key exchange. The server presents a certificate. Many deployments also require a client certificate or a username and password.
- WireGuard: WireGuard uses the Noise protocol framework. Each peer has a static Curve25519 key pair, and the static public keys are the identities. A handshake combines ephemeral and static DH operations, so it provides both forward secrecy and authentication in one round trip. There are no certificates, no negotiation of algorithms, and no CA.
- SSH: The client checks the server's host key against
known_hosts, then the user authenticates with a key or other credential. The tunnel keys come from an ephemeral exchange.
Worked example: WireGuard keys
In WireGuard, the key pair is the identity. Generate one like this:
umask 077
wg genkey | tee privatekey | wg pubkey > publickeyThe umask 077 line makes the new files readable only by you. wg genkey creates a random private key. wg pubkey derives the matching public key from it, and tee writes the private key to a file while passing it along the pipe.
Each peer then puts its own private key in its [Interface] section and the other peer's public key in the [Peer] section:
[Interface]
PrivateKey = <client-private-key>
Address = 10.8.0.2/24
DNS = 10.8.0.1
[Peer]
PublicKey = <server-public-key>
Endpoint = vpn.example.com:51820
AllowedIPs = 10.8.0.0/24
PersistentKeepalive = 25The PublicKey line is the authentication step. The client will only complete a handshake with a server that holds the matching private key. A server with any other key cannot be mistaken for this peer, even if an attacker controls vpn.example.com. The server does the same check in reverse and ignores handshakes from keys it has no [Peer] entry for.
So the security of this setup depends on how you moved <server-public-key> into the file. If that value came over a channel an attacker could alter, the setup is only as strong as that channel.
WireGuard can also add an optional PresharedKey per peer. It is mixed into the handshake as an extra symmetric layer. Its purpose is to protect against a future attacker with a quantum computer who could break the elliptic-curve step, because recorded handshakes would still need the PSK to decrypt.
Common errors and gotchas
- Treating the public key as secret, or the private key as shareable. The public key is meant to be shared. If a private key is pasted into a ticket or chat, regenerate it and update the other side.
- Skipping verification. Accepting an unknown SSH host key without checking it, or turning off certificate validation in a VPN client to "make it work", removes the authentication step and invites MITM.
- Clock problems with certificates. Certificates have validity dates. A device with a wrong clock may reject a valid certificate, and a handshake failure looks like a network problem.
- Reusing one PSK across many peers. If any holder leaks it or leaves the organisation, you must rotate it for all of them.
- Weak or outdated algorithms. Old IPsec setups may offer DH groups that are too small. Choose modern groups and curves, and disable legacy options.
- Long-lived keys with no revocation plan. Decide how you will remove a lost laptop's access: revoke its certificate, or delete its public key from every peer's configuration.
- Confusing agreement with authentication. A successful handshake only means keys were agreed. Check what proved the peer's identity.
Summary of the model
- Peers use ephemeral Diffie-Hellman to agree on a shared secret over the open network.
- A KDF turns that secret into separate symmetric keys.
- Authentication, by PSK, known public key or certificate, makes sure the secret was agreed with the intended peer.
- Ephemeral keys give forward secrecy, and regular rekeying limits the exposure of any single key.
- The data packets are then protected with fast symmetric encryption and integrity checks.
Exercise
An attacker records all the traffic of a WireGuard tunnel for a year. Later they steal the server's long-term private key. Can they decrypt the recorded traffic, and which property explains the answer? Separately, what would an attacker need to do to impersonate the server to a client in the first place?
Show answer
They cannot decrypt the recorded traffic. The session keys came from ephemeral Diffie-Hellman values that were discarded after use, so stealing the long-term key later does not reveal them. This property is forward secrecy. To impersonate the server to a client, the attacker would need the server's private key (the client authenticates the server by the public key in its [Peer] section), or they would need to get the client to accept a different public key, for example by tampering with the channel used to distribute the configuration. Note that with a stolen long-term key, the attacker could impersonate the server from that point on, until the key is replaced.
Exercise
Why does plain Diffie-Hellman without authentication not stop a man-in-the-middle attack, and name two ways a VPN can add the missing authentication?
Show answer
The attacker can run a separate exchange with each side, so each victim ends up with a valid shared secret, but with the attacker rather than with each other. Plain DH gives no way to check who the other party is. A VPN can authenticate peers with a pre-shared key, with known static public keys (as in WireGuard), or with certificates signed by a trusted CA (as in IPsec and TLS-based VPNs).