WireGuard – Peer to Peer VPN

Introduction

“WireGuard” is simple and quick VPN solution. Compared to the major VPN solutions (e.g. OpenVPN), WireGuard has less options but the connection speed should be faster. Good things is we can connect multiple devices (e.g., PC, mobile, tablet, router and so on). If you are interested in this topic, watch the video file below. I put the command lines I used in the video for your reference. 

Commands

1. Update and install

sudo apt update
sudo apt upgrade
sudo apt install wireguard
cd /etc/wireguard

2. Create a private and public keys

cd /etc/wireguard
umask 077; wg genkey | tee privatekey | wg pubkey > publickey

3. Contents of /etc/wireguard/wg0.conf

<blockquote>[Interface]
PrivateKey = {PRIVATE KEY of SERVER}
Address = 172.16.0.9/24
ListenPort = 51820
SaveConfig = true

PostUp = ufw route allow in on wg0 out on eth0
PostUp = iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
PreDown = ufw route delete allow in on wg0 out on eth0
PreDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

4. Comment out “net.ipv4.ip_forward=1” in /etc/sysctl.conf and refresh the settings

sudo sysctl -p

5. Firewall settings

sudo ufw allow ssh
sudo ufw allow 51280/udp
sudo ufw enable
sudo ufw status

6. Enable and start WireGuard

sudo systemctl enable wg-quick@wg0
sudo systemctl start wg-quick@wg0
sudo systemctl status wg-quick@wg0

7. Configuration in Peer (Client Machine)

[Interface]
PrivateKey = {THIS KEY WILL BE AUTO-GENERATED}
Address = 172.16.0.100/24
DNS = {DNS OF SERVER}

#Custom routing to ensure that public traffic to the system uses the default gateway
PostUp = ip route add table 200 default via {IP ADDRESS OF SERVER}:
PreDown = ip route delete table 200 default via {IP ADDRESS OF SERVER}:

[Peer]
PublicKey = {PUBLIC KEY OF SERVER}
AllowedIPs = 0.0.0.0/0 #All Traffic Over the Tunnel
Endpoint = {IP ADDRESS OF SERVER}:51820

8. Get the DNS settings of Server machine

resolvectl dns eth0

9. Add Peer (Client) information to the Server

sudo wg
wg set wg0 peer {PUBLIC KEY OF CLIENT} allowed-ips 171.1.10.100
sudo wg