Configuring WireGuard VPN



This short post describes installation and configuration of a VPN server based on WireGuard and VPN clients.

What is WireGuard?

WireGuard is a modern, secure, and easy to mantain VPN solution.

Installing WireGuard

WireGuard installation process depends on the operating system, so for most updated instructions regarding the installation please refer to WireGuard installation page.

Generate keys for the server

execute: wg genkey | tee privatekey | wg pubkey > publickey

Now files privatekey and publickey contain private key and public key respectfuly, for the VPN server.

Configuring WireGuard server (/etc/wireguard/wg0.conf)

[Interface]
# IP address of the VPN server
Address = 10.2.0.1/24
# port (UDP) where the VPN server should listen on
ListenPort = 51820
PrivateKey = <SERVER PRIVATE KEY>
PostUp = iptables -I FORWARD -i wg0 -j ACCEPT; iptables -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

[Peer]
PublicKey = <PUBLIC KEY OF PEER 1>
# IP address that allowed to use by peer 1
AllowedIPs = 10.2.0.2/32

[Peer]
PublicKey = <PUBLIC KEY OF PEER 2>
# IP address that allowed to use by peer 2
AllowedIPs = 10.2.0.3/32

Generate keys for the client

execute: wg genkey | tee privatekey | wg pubkey > publickey

Now files privatekey and publickey contain private key and public key respectfuly, for the client.

Configuring WireGuard client (/etc/wireguard/wg0.conf)

[Interface]
# IP address that should be used by the client
Address = 10.2.0.2/24
PrivateKey = <PRIVATE KEY OF THE CLIENT>

[Peer]
PublicKey = <PUBLIC KEY OF THE VPN SERVER>
# IP addresses that should be routed via the VPN
AllowedIPs = 172.31.0.0/16, 10.2.0.0/24
# IP address and port of the VPN server
Endpoint = 52.16.183.72:51820

Start the VPN server

systemctl enable wg-quick@wg0
systemctl restart wg-quick@wg0

Start the VPN client

systemctl enable wg-quick@wg0
systemctl restart wg-quick@wg0

Enable IP forwarding on the server

cat << EOF >> /etc/sysctl.conf
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
EOF
sysctl -p

Test the connection

wg show
# run from the client
ping 10.2.0.1
# run from the server
ping 10.2.0.2