VPNs
A VPN (Virtual Private Network) creates an encrypted tunnel across an untrusted network, usually the Internet. Packets that enter the tunnel are encrypted and wrapped inside new packets addressed to the other end of the tunnel; there they're unwrapped and delivered as if the two sides were on the same private network.
Kinds of VPN
| Kind | Connects | Typical technology |
|---|---|---|
| Site-to-site | two office networks, or an office and a cloud VPC | IPsec, WireGuard |
| Remote access | one laptop to the company network | WireGuard, OpenVPN, IPsec IKEv2, SSL VPN |
| Consumer "privacy" VPN | your device to a provider's server, then the Internet | WireGuard, OpenVPN |
| Zero-trust / mesh | each device directly to the services it may use | WireGuard-based meshes |
Tunnelling: a packet inside a packet
The core idea is encapsulation again. The inner packet (private addresses) becomes the encrypted payload of an outer packet (public addresses):
outer IP header | outer UDP header | VPN header | encrypted( inner IP header | TCP | data ) | auth tag
203.0.113.7 -> 198.51.100.1 counter 10.8.0.6 -> 10.20.0.15import hashlib
import hmac
import socket
import struct
KEY = hashlib.sha256(b"shared tunnel key (from a key exchange)").digest()
def keystream(key, counter, length):
out = b""
block = 0
while len(out) < length:
out += hashlib.sha256(key + struct.pack("!QI", counter, block)).digest()
block += 1
return out[:length]
def seal(inner_packet, counter):
encrypted = bytes(a ^ b for a, b in zip(inner_packet, keystream(KEY, counter, len(inner_packet))))
header = struct.pack("!Q", counter)
tag = hmac.new(KEY, header + encrypted, hashlib.sha256).digest()[:16]
return header + encrypted + tag
def open_sealed(blob):
header, encrypted, tag = blob[:8], blob[8:-16], blob[-16:]
expected = hmac.new(KEY, header + encrypted, hashlib.sha256).digest()[:16]
if not hmac.compare_digest(tag, expected):
raise ValueError("authentication failed: packet dropped")
(counter,) = struct.unpack("!Q", header)
return bytes(a ^ b for a, b in zip(encrypted, keystream(KEY, counter, len(encrypted))))
inner = (socket.inet_aton("10.8.0.6") + socket.inet_aton("10.20.0.15") + b"GET /payroll HTTP/1.1")
sealed = seal(inner, counter=1)
print("inner packet :", inner[:8].hex(" "), inner[8:])
print("on the wire :", sealed[8:30].hex(" "), "...")
print("decrypted ok :", open_sealed(sealed) == inner)
tampered = bytearray(sealed)
tampered[12] ^= 0x01
try:
open_sealed(bytes(tampered))
except ValueError as err:
print("tampered :", err)inner packet : 0a 08 00 06 0a 14 00 0f b'GET /payroll HTTP/1.1'
on the wire : 0d fc 29 66 1b 89 a1 98 f5 64 f3 08 53 6c 04 bd bd 0f 73 cc 09 af ...
decrypted ok : True
tampered : authentication failed: packet dropped
(This toy construction only illustrates the structure. Real VPNs use vetted AEAD ciphers: WireGuard uses ChaCha20-Poly1305, IPsec usually AES-GCM.) An eavesdropper on the Internet sees only the two public tunnel endpoints and encrypted bytes: not the inner addresses, ports or data.
The overhead and the MTU problem
Every tunnelled packet carries extra headers, so less room is left for the inner packet. If nobody accounts for that, large packets get fragmented or dropped:
OVERHEAD = {
"WireGuard over IPv4": 20 + 8 + 32, # IP + UDP + WireGuard header/tag
"WireGuard over IPv6": 40 + 8 + 32,
"IPsec ESP (AES-GCM, tunnel mode, IPv4)": 20 + 8 + 8 + 16 + 20 + 2, # + inner IP, padding etc. approx
"GRE over IPv4": 20 + 4,
}
link_mtu = 1500
for name, extra in OVERHEAD.items():
inner_mtu = link_mtu - extra
print(f"{name:<40} overhead {extra:>3} B -> tunnel MTU {inner_mtu}, TCP MSS {inner_mtu - 40}")WireGuard over IPv4 overhead 60 B -> tunnel MTU 1440, TCP MSS 1400
WireGuard over IPv6 overhead 80 B -> tunnel MTU 1420, TCP MSS 1380
IPsec ESP (AES-GCM, tunnel mode, IPv4) overhead 74 B -> tunnel MTU 1426, TCP MSS 1386
GRE over IPv4 overhead 24 B -> tunnel MTU 1476, TCP MSS 1436
That's why WireGuard interfaces default to MTU 1420 (enough room even for an IPv6 outer header), and why VPN gateways often clamp the TCP MSS in passing SYN packets so both ends choose segments that fit.
Split tunnel vs full tunnel
A remote-access VPN client changes the laptop's routing table. In a full tunnel, the default route goes through the VPN, so all traffic does. In a split tunnel, only company prefixes do:
import ipaddress
def route(dest, table):
ip = ipaddress.ip_address(dest)
best = max((r for r in table if ip in ipaddress.ip_network(r[0])),
key=lambda r: ipaddress.ip_network(r[0]).prefixlen)
return best[1]
split = [("0.0.0.0/0", "wlan0 (home Wi-Fi)"), ("10.20.0.0/16", "wg0 (VPN)"), ("172.16.0.0/12", "wg0 (VPN)")]
full = [("0.0.0.0/0", "wg0 (VPN)"), ("10.20.0.0/16", "wg0 (VPN)"), ("198.51.100.1/32", "wlan0 (home Wi-Fi)")]
for dest in ["10.20.0.15", "172.20.4.4", "93.184.215.14", "198.51.100.1"]:
print(f"{dest:<14} split: {route(dest, split):<20} full: {route(dest, full)}")10.20.0.15 split: wg0 (VPN) full: wg0 (VPN)
172.20.4.4 split: wg0 (VPN) full: wg0 (VPN)
93.184.215.14 split: wlan0 (home Wi-Fi) full: wg0 (VPN)
198.51.100.1 split: wlan0 (home Wi-Fi) full: wlan0 (home Wi-Fi)
In the full tunnel, the route to the VPN server itself (198.51.100.1/32) must stay on the real interface; otherwise the encrypted packets would try to go into the tunnel they are.
WireGuard configuration
# /etc/wireguard/wg0.conf on the laptop
[Interface]
PrivateKey = <laptop private key>
Address = 10.8.0.6/32
DNS = 10.20.0.53
[Peer]
PublicKey = <gateway public key>
Endpoint = vpn.example.com:51820
AllowedIPs = 10.20.0.0/16, 172.16.0.0/12 # split tunnel; 0.0.0.0/0 for a full tunnel
PersistentKeepalive = 25sudo wg-quick up wg0
sudo wg showSample output:
interface: wg0
public key: kX3e...Qm8=
listening port: 51820
peer: Hn2T...Zx4=
endpoint: 198.51.100.1:51820
allowed ips: 10.20.0.0/16, 172.16.0.0/12
latest handshake: 12 seconds ago
transfer: 1.24 MiB received, 310.52 KiB sentNote: A VPN protects traffic between you and the VPN server. Beyond that server, traffic is as exposed as ever, and the VPN provider can see everything you send through it. A consumer VPN moves trust from your ISP to the VPN provider; it doesn't remove the need for HTTPS.
Go further: WireGuard: Keys, Peers and AllowedIPs reviews real configurations for the common findings.
Test yourself
What does an eavesdropper on the Internet see of a VPN tunnel's traffic?
- The inner IP addresses and data
- Only the outer tunnel endpoints, sizes and timing
- Nothing at all, not even packets
- The user's passwords
Why is a VPN interface's MTU smaller than the physical link's?
- VPNs compress data
- The tunnel's extra headers take up space in each packet
- Encryption needs smaller packets
- It isn't; they're equal
In a split-tunnel VPN, which traffic goes through the tunnel?
- All traffic
- Only traffic to the prefixes routed into the tunnel (e.g. company networks)
- Only DNS
- Only traffic to the VPN server