Written 17 Sept 2023
sudo apt-get install -y wireguard
/etc/wireguard/wg0.conf:
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
MTU = 1380
PrivateKey = [redacted]
# packet forwarding
PreUp = sysctl -w net.ipv4.ip_forward=1
PreDown = sysctl -w net.ipv4.ip_forward=0
# wireguard ingress
PreUp = iptables -I INPUT 1 -p udp --dport 51820 -j ACCEPT
PreUp = iptables -I INPUT 1 -i wg0 -j ACCEPT
PostDown = iptables -D INPUT -i wg0 -j ACCEPT
PostDown = iptables -D INPUT -p udp --dport 51820 -j ACCEPT
# Masquerading traffic
PreUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PreDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
# Router
PublicKey = [Peer pub key]
AllowedIPs = 10.0.0.2/32, 192.168.0.0/24
PresharedKey = [shared key made with wg genkey]
[Peer]
# Phone
PublicKey = [Peer pub key, generated with wg tools]
AllowedIPs = 10.0.0.3/32
PresharedKey = [Different shared key made with wg genkey]
The easiest way to mak the key pairs is using the tools wireguard includes:
wg genkey | tee /etc/wireguard/privatekey | wg pubkey | tee /etc/wireguard/publickey
Taking a closer look at the peers, you see the AllowedIPs line. For the home router, this line is AllowedIPs = 10.0.0.2/32, 192.168.0.0/24. The important thing here is that we allow both the address of the peer AND the home network. This informs wireguard it can route, and so long as the other side accepts conections, it will route like any other network. By placing the config file in /etc/wireguard, you can then use the included wireguard command wg-quick up wg0 to bring up the interface, run our PreUp instructions, and add routes to our machine. For the home router, I use OpenWRT, so I can just load a config from file with the wireguard add-on. On Android, I can do the same or it's possible to generate a qrcode if you make a config file that includes the private key of the server. The peer configuration file looks something like this:
[Interface]
Address = 10.0.0.2/32
PrivateKey = [private key we generate with wg genkey as before]
[Peer]
PublicKey = [public key of our server]
AllowedIPs = 0.0.0.0/0 # to allow untunneled traffic, use `0.0.0.0/1, 128.0.0.0/1` instead
PresharedKey = [same key we set in our server config]
Endpoint = [domain]:[port] # default port is 51820
PersistentKeepalive = 25 # Keepalive is recommended when behind a NAT
And that's it. It should just work. Typically, when it doesn't, I have fat fingered part of the config. After that, I have typically fat fingered the firewall. I like to run wg show wg0 to see how much bandwidth has been used by my peers, then run some quick pings into and out of the wireguard network; it gives me the warm fuzzies that something is happening.