How to Setup WireGuard on Ubuntu 20.04

Notes for setting up WireGuard. Assumes server and client are both Ubuntu 20.04.

Server Config

Install WireGuard

sudo apt-get install wireguard

Generate the public and private server keys. Restrict permissions on the private key.

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey
sudo chmod 600 /etc/wireguard/privatekey

Create the config file

sudo nano /etc/wireguard/wg0.conf

Edit config file with text below. CLIENT1_PUBLIC_KEY is generated in the client config below. Multiple clients can be added by copying the client block.

[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = SERVER_PRIVATE_KEY
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# Client 1
[Peer]
PublicKey = CLIENT1_PUBLIC_KEY
AllowedIPs = 10.0.0.2/32

Restrict permissions on the config file.

sudo chmod 600 /etc/wireguard/wg0.conf

Check that the config works

sudo wg-quick up wg0
sudo wg-quick down wg0

Set up networking

sudo nano /etc/sysctl.conf

Uncomment line below

net.ipv4.ip_forward=1

Open port in firewall

sudo ufw allow 51820/udp

Start WireGuard on boot

sudo systemctl enable wg-quick@wg0

Apply changes

sudo sysctl -p

Client Config

Install WireGuard

sudo apt-get install wireguard

Generate the public and private client keys. Restrict permissions on the private key.

wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey
sudo chmod 600 /etc/wireguard/privatekey

Create the config file

sudo nano /etc/wireguard/wg0.conf

Edit config file with text below. CLIENT1_PRIVATE_KEY is generated in the previous step. SERVER_PUBLIC_KEY is the public key generated on the server.

[Interface]
PrivateKey = CLIENT1_PRIVATE_KEY
Address = 10.0.0.2/24

[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_ADDRESS:51820
AllowedIPs = 0.0.0.0/0

Restrict permissions on the config file.

sudo chmod 600 /etc/wireguard/wg0.conf

Check that the config works. Bring up the interface and check IP address.

sudo wg-quick up wg0

Create two scripts wgup.sh and wgdown.sh with the command in each:

sudo wg-quick up wg0

sudo wg-quick down wg0

Add these scripts to the sudoers file so to call “sudo wgup.sh” without having to enter a password

sudo visudo

username ALL=(ALL) NOPASSWD: /path/to/wgup.sh
username ALL=(ALL) NOPASSWD: /path/to/wgdown.sh