How a modern VPN builds an encrypted tunnel — the handshake, the routing, and a single packet's journey — stepped through one move at a time.
WireGuard is famously small (~4,000 lines in the kernel) because it throws out
negotiation. There are no cipher suites to agree on, no certificates, no
connection states to manage. Each side is configured with one thing about the other:
its static public key. Knowing a peer means knowing its public key
— plus, optionally, where to reach it (an endpoint).
WireGuard uses the Noise IK handshake pattern. In exactly two
messages, both peers authenticate each other and independently derive the same
pair of session keys. The trick: every key exchange and every field gets folded into a
running chaining key C and transcript hash H —
so if anything differs, the final keys won't match. Step through it below.
Here is WireGuard's second big idea. Each peer carries an AllowedIPs list:
the set of destination IP ranges that belong to it. To send a packet, WireGuard looks up
the destination in this table by longest-prefix match — the winning entry
names the peer, and therefore the key, to encrypt with. No match means no route:
the packet is dropped. Inbound, the same table is a filter: a decrypted packet is only
accepted if its source falls in that peer's AllowedIPs.
Your laptop's peer table. Type any destination IP (or pick one) to see where the packet goes.
| peer | endpoint | AllowedIPs |
|---|
AllowedIPs set is both the
outbound routing table (which key encrypts this packet?) and the inbound access-control
list (is this peer even allowed to claim this source IP?). That symmetry is why WireGuard
needs no separate firewall rules to enforce which peer owns which addresses.
Now put it together. A normal IP packet leaves an app on your laptop bound for
10.0.0.5 inside the tunnel. Watch it get routed to a peer, encrypted with that
session key, wrapped in an ordinary UDP datagram, sent across the public internet, and
reassembled on the far side. Press play.
receiver index tells the far side which session to use without an expensive
key lookup, and the ever-increasing counter is the AEAD nonce and the
replay-protection sequence number in one.
Because identity is a key and routing is a lookup, several properties that are bolted-on complexity in other VPNs come naturally here.
A peer is its key, not its IP. If your laptop jumps from Wi-Fi to cellular, the next valid packet simply updates the stored endpoint. The tunnel never drops.
An unauthenticated packet gets no reply at all. To a port scanner, a WireGuard endpoint is indistinguishable from a closed port — there's nothing to talk to.
An optional tiny packet every N seconds keeps NAT mappings on stateful firewalls alive, so a peer behind NAT stays reachable without re-handshaking.
The tunnel is usable after a single round-trip, and under load a cookie reply (MAC2) lets the responder stay stateless until a client proves it can receive.