Home | /b/

Creating a vpn with Wireguard

Wireguard is really nice and easy to use utility to create tunnels between machines. You'll need to be able to connect from one machine to next, in atleast one direction. So if your workstation is behind NAT, you'll either need a server with publicly-routable IP address (e.g. through a VPS) or have to be on the same network.

In this article i'll assume you want a VPN from a home machine behind NAT to a VPS such that you can use it for browsing internet. Just browse www.wireguard.com for easy tutorial.

Creating the tunnel

wg genkey > /etc/wireguard/wg0.conf
# edit it to look like the following:

[Interface]
Address = 192.168.20.2/24
ListenPort = 5555
PrivateKey = IB6QwUC4t5IMl10S5RaO1KNe5BprXWyRtH7Ynhzn4Us=
Then, on the client, generate a private and public key, saving it to /etc/wireguard/wg0.conf:
wg genkey > /etc/wireguard/wg0.conf
# edit it to look like the following:
[Interface]
ListenPort = 53602
PrivateKey = OCqSh6VFf4422w8s1DxkDs0K9DDTpQ8KmRgX1R9NOWU=
Address = 192.168.20.1/24

[Peer]
PublicKey = jnLnktX/AdxxFLjqeFk2p69/69vKXTdNElJawMzst0w=
Endpoint = vps-ip:5555
AllowedIps = 0.0.0.0/0
PersistentKeepalive = 20
Then edit the server's Peer as:
[Peer]
PublicKey = aexDAkpjTnE7mj0D1nYaoaaAkDoFbs+LxJIyPiqT904=
AllowedIps = 192.168.20.1/32
Then on both client and server, run wg-quick up wg0 That's it!

Routing traffic through internet

Wireguard gets us the first part of establishing a tunnel between hosts. Now, we need to configure them such the vps can act as a NAT gateway for your workstation. On the vps:
# allow forwarding of ip that's not ours
echo 1 > /proc/sys/net/ipv4/ip_forward

# perform NAT on the forwarded packet
sudo iptables -t nat -A POSTROUTING -s 192.168.20./24 -j MASQUERADE
# we could use SNAT too but that doesn't work with modern "cloud" where the machine itself doesn't know it's own public ip address.

That's almost it! Any traffic the vpn gets is forwarded back and forth! This setup is already enough to use the wireguard vpn android app!

Extra: Forward only some traffic

I wanted to forward traffic of only one app through the vpn. While i'm sure there's a better method, i used this hack to do my bidding:

ips=(192.168.1.1 192.168.1.2 192.168.1.3)
for i in "${ips[@]}"; do
ip route add "$i" via 192.168.20.2 dev wg0
done