Why Wireguard and How does it work?

  • Simple (one config file on server and client and one command to run)
  • Small codebase (5000 LOC) unlike OpenVPN and IPSEC
  • Scheduled to be merged into Linux kernel soon

Wireguard works by creating a tunnel to the server using a separate network interface on your machine. You do not need to worry about Proxy settings and all your applications will work without issue.

Installation and Key Generation

Do this on both server and client machines

#Installation: For both machines
sudo apt install wireguard wireguard-tools openresolv
# openresolv is in case you are using systemd-resolved which is default for DNS resolution on Ubuntu
# Generate private and public key pair : For both machines
umask 077
wg genkey | tee privatekey | wg pubkey > publickey

Configure Server

Create file called /etc/wireguard/wg0.conf

[Interface]
PrivateKey = <Private Key>
ListenPort = <UDP Port to listen on, by default it is 51820>
Address = 192.168.2.1/24, fd86:ea04:1115::1/64
ListenPort = 51820
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
SaveConfig = true

[Peer]
PublicKey = <Client Public Key>
AllowedIPs = 192.168.2.2/32

Note that you have to paste the contents of the private key in the conf file, not the path. The PostUp sets up forwarding rules when the wiregaurd interface is started. PostDown deletes the rules when the interface is shutdown. Packet forwarding is essential if you want to use your server as a VPN to the general internet. Enable it on your server by adding the following to /etc/sysctl.conf and run sudo sysctl -p to reload the configuration changes.

# Add to end of /etc/sysctl.conf
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1

Whitelist the UDP port so that it is reachable by client

sudo ufw allow 51820/udp
sudo ufw enable

Configure Client

Create file called /etc/wireguard/wg0.conf

[Interface]
PrivateKey = <Private Key>
Address = 192.168.2.2/32
SaveConfig = true

[Peer]
PublicKey = <Server Public Key>
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = <Server Public IP: Port e.g 23.23.23.23:2323>

Note that the Address in interface part of client must be within range of AllowedIPs in server’s config. If you are not using the server as a VPN, you can restrict the AllowedIPs section of client.

Start Server and Client

Run sudo wg-quick up wg0 Enable it to run as service on system startup using sudo systemctl enable wg-quick@wg0 If you want to stop, use sudo wg-quick down wg0

Test connection

# Ping Google
ping -c3 8.8.8.8
sudo wg # shows tyou status of the wireguard connection

Resources