TExcelTAD
Home › Network Security: Discovery, Segmentation, Firewalls, VPN & IDS › WireGuard: Keys, Peers and AllowedIPs

WireGuard: Keys, Peers and AllowedIPs

IPsec is powerful and complicated: proposals, phases, modes, dozens of options, each a chance to misconfigure. WireGuard takes the opposite approach. It has one fixed set of modern algorithms (Curve25519 for key agreement, ChaCha20-Poly1305 for encryption, BLAKE2s for hashing, built on the Noise protocol framework), no negotiation, a configuration of a handful of settings per interface and per peer, a code base of a few thousand lines, and it runs over UDP only. It is in the Linux kernel since version 5.6 and available on every major platform. For a reviewer that is good news: there is little to get wrong in the cryptography, so the review concentrates on keys and on AllowedIPs, which is where WireGuard's security policy lives.

Keys: one pair per peer

Every WireGuard interface has an X25519 key pair; peers are identified by their public keys. wg genkey makes a private key (32 random bytes, base64) and wg pubkey derives the public key. The sandbox has no wg tool, so the example does the same with Python's cryptography library. The private keys here are fixed bytes so the output is stable; real keys come from wg genkey (or os.urandom(32)), and a private key printed in a lesson is a lab key, never to be used.

python · try it yourself
import base64
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives import serialization

def keypair(seed_byte):
    raw = bytes([seed_byte]) * 32                     # LAB ONLY: real keys come from wg genkey
    priv = X25519PrivateKey.from_private_bytes(raw)
    pub = priv.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
    return base64.b64encode(raw).decode(), base64.b64encode(pub).decode(), priv

gw_priv, gw_pub, gw = keypair(0x11)
lap_priv, lap_pub, lap = keypair(0x22)
print("gateway  public:", gw_pub)
print("laptop   public:", lap_pub)

# Both sides compute the same shared secret from their private key and the other's public key.
s1 = gw.exchange(lap.public_key())
s2 = lap.exchange(gw.public_key())
print("same static-static secret on both sides:", s1 == s2, f"({len(s1)} bytes)")
print("private key length (base64 of 32 bytes):", len(gw_priv), "characters")
gateway  public: e06Qm75//kTEZaIgA31gjuNYl9Me+XLwf3SJLLD3PxM=
laptop   public: D6poTtKIZ7l/Smot7l34zpdOdrcBjj8iocTPJnhXDyA=
same static-static secret on both sides: True (32 bytes)
private key length (base64 of 32 bytes): 44 characters

The static-static secret is one ingredient of WireGuard's handshake; the handshake also mixes in fresh ephemeral keys (so sessions have forward secrecy) and, optionally, a pre-shared key per peer (PresharedKey), which adds a symmetric secret as a hedge against a future quantum computer breaking Curve25519. Session keys are replaced every two minutes or so, automatically.

Key hygiene is the first review point: private keys in files readable only by root (umask 077 when generating), one key pair per device (never copied between laptops), removal of the peer's public key from the gateway when a device is lost or a person leaves.

AllowedIPs: routing and access control in one list

A WireGuard configuration for the lab's remote-access gateway and one laptop:

text
# /etc/wireguard/wg0.conf on the gateway (10.10.200.1)
[Interface]
Address    = 10.10.200.1/24
ListenPort = 51820
PrivateKey = <gateway private key>

[Peer]   # alice-laptop
PublicKey  = <laptop public key>
AllowedIPs = 10.10.200.11/32

[Peer]   # branch router
PublicKey  = <branch public key>
AllowedIPs = 10.10.201.0/24, 10.20.0.0/16
text
# wg0.conf on alice's laptop
[Interface]
Address    = 10.10.200.11/32
PrivateKey = <laptop private key>
DNS        = 10.10.2.53

[Peer]   # the gateway
PublicKey  = <gateway public key>
Endpoint   = vpn.lab.test:51820
AllowedIPs = 10.10.0.0/16
PersistentKeepalive = 25

AllowedIPs means two things at once, which WireGuard calls cryptokey routing:

  1. Outbound: a packet to a destination inside a peer's AllowedIPs is encrypted for that peer (the list works like a routing table).
  2. Inbound: a decrypted packet from a peer is accepted only if its inner source address is inside that peer's AllowedIPs; otherwise it is dropped.

So the gateway's entry AllowedIPs = 10.10.200.11/32 for the laptop is an access rule: the laptop can only ever send packets as 10.10.200.11, which makes firewall rules on the gateway's wg0 interface meaningful per person. The program models both directions.

python · try it yourself
import ipaddress
PEERS = {   # the gateway's view: peer -> AllowedIPs
    "alice-laptop": ["10.10.200.11/32"],
    "bob-laptop":   ["10.10.200.12/32"],
    "branch":       ["10.10.201.0/24", "10.20.0.0/16"],
}
def route_out(dst):
    """Most specific AllowedIPs match wins, like a routing table."""
    best = None
    for peer, nets in PEERS.items():
        for n in map(ipaddress.ip_network, nets):
            if ipaddress.ip_address(dst) in n and (best is None or n.prefixlen > best[1].prefixlen):
                best = (peer, n)
    return f"encrypt for {best[0]} (via {best[1]})" if best else "no peer: not sent into the tunnel"

def accept_in(peer, inner_src):
    ok = any(ipaddress.ip_address(inner_src) in ipaddress.ip_network(n) for n in PEERS[peer])
    return "accept" if ok else "DROP: source not in this peer's AllowedIPs"

for dst in ["10.10.200.11", "10.20.5.9", "10.10.2.30"]:
    print(f"out to {dst:13} -> {route_out(dst)}")
for peer, src in [("alice-laptop", "10.10.200.11"), ("alice-laptop", "10.10.200.12"),
                  ("branch", "10.20.7.7"), ("branch", "10.10.2.30")]:
    print(f"in  from {peer:12} inner src {src:13} -> {accept_in(peer, src)}")
out to 10.10.200.11  -> encrypt for alice-laptop (via 10.10.200.11/32)
out to 10.20.5.9     -> encrypt for branch (via 10.20.0.0/16)
out to 10.10.2.30    -> no peer: not sent into the tunnel
in  from alice-laptop inner src 10.10.200.11  -> accept
in  from alice-laptop inner src 10.10.200.12  -> DROP: source not in this peer's AllowedIPs
in  from branch       inner src 10.20.7.7     -> accept
in  from branch       inner src 10.10.2.30    -> DROP: source not in this peer's AllowedIPs

Alice's laptop can't pretend to be Bob (10.10.200.12), and the branch router can't inject packets claiming to come from the head office's database network. That is a property IPsec and OpenVPN give only with careful configuration; WireGuard gives it by default, as long as AllowedIPs are narrow.

Common findings

Finding Why it matters Fix
AllowedIPs = 0.0.0.0/0 for a client on the gateway the client may send packets with any source address: spoofing inside your network the client's own /32 (and its LAN only for site-to-site peers)
AllowedIPs = 0.0.0.0/0 on the client full tunnel: all the client's traffic goes through the VPN (often intended) a deliberate choice; see split tunnelling in the next lesson
no firewall on wg0 every VPN user reaches every internal system filter wg0 like any zone boundary, per user address
shared keys between devices a lost device can't be revoked alone; no accountability one key pair per device
private key world-readable, in git, in a ticket anyone with it impersonates the peer root-only files, a secrets store, rotation after exposure
PreUp/PostUp scripts they run as root from the config file review them like any root script

How WireGuard use is detected and monitored

  • wg show lists peers, their endpoints and latest handshake times and transfer counters: a peer that handshakes from an unexpected country, or a laptop key active while its owner is on holiday, is worth a question.
  • WireGuard is deliberately silent to unauthenticated packets (no reply at all without a valid handshake), so scans don't find it, and there are no failed-login logs to read. Monitoring relies on handshakes and the traffic after decryption.
  • Unapproved WireGuard on servers or workstations (a user's personal VPN, an attacker's tunnel) shows up as UDP flows to unusual ports with steady keepalives, which egress filtering should block (Egress Filtering).

Pitfalls

  • Forgetting that WireGuard has no user authentication: a key is a device credential. Combine it with device management, or put an identity-aware layer behind it for user-level policy.
  • Overlapping AllowedIPs between peers: the most specific wins, and a typo can redirect a subnet to the wrong peer.
  • Roaming: WireGuard follows the peer's latest authenticated endpoint, so a stolen key works from anywhere until it is removed.

Practice

1. In the model, what happens to a packet to 10.10.2.30 that arrives at the gateway from the LAN?

No peer's AllowedIPs contains it, so it isn't sent into the tunnel; the gateway routes it normally on the LAN.

2. Change bob's AllowedIPs to ["10.10.200.0/24"]. What changes for packets to 10.10.200.11 and from bob?

Outbound to .11 still goes to alice (her /32 is more specific than bob's /24). Inbound, bob may now send packets with any source in 10.10.200.0/24, including alice's address: he can spoof her inside the network. Keep client entries at /32.

3. Why does adding a PresharedKey help against a future quantum computer?

An attacker who records traffic today and later breaks Curve25519 still needs the symmetric pre-shared key, which is mixed into the handshake and isn't vulnerable to the same attack.

Test yourself

What does AllowedIPs on the gateway's peer entry for a laptop control?

  1. Only DNS
  2. Which destinations route to that peer and which inner source addresses are accepted from it
  3. The listen port
  4. The encryption algorithm

Which algorithms does WireGuard negotiate?

  1. Whatever both sides support
  2. None: it uses a fixed set (Curve25519, ChaCha20-Poly1305, BLAKE2s)
  3. AES-CBC with SHA-1
  4. RSA and 3DES

In the model, why was alice's packet with inner source 10.10.200.12 dropped?

  1. Wrong key
  2. The address isn't in alice's AllowedIPs (it is bob's)
  3. The tunnel was down
  4. UDP was blocked

Why don't port scans find a WireGuard endpoint easily?

  1. It uses TCP
  2. It sends no reply to packets without a valid handshake
  3. It changes port every minute
  4. It is encrypted with RSA