How to Set Up WireGuard VPN Server on Ubuntu 20.04
In this tutorial, we will look at the steps to set up and configure the WireGuard VPN server and client.
WireGuard installation
Install the WireGuard package on both server and client machines using this command:
System configuration
First, you need to allow incoming UDP traffic on some port for the VPN connection.
Allow kernel-level network packet redirection.
Uncomment the following line.
Apply the changes.
Private and public key pairs creation
Use this command to generate keys and make private one accessible only to the root user for security reasons.
sudo chmod 600 /etc/wireguard/server_private.key
Perform the same action on the client machine for the client_private.key and client_public.key.
To see the keys values, use the ‘cat’ command, for example:
cat /etc/wireguard/server_public.key
WireGuard server configuration
Create the WireGuard configuration file.
Fill it in with the following lines:
[Interface]
PrivateKey = oCH7Z0g+ieQ99KkkR1E5EO22Evs5q75F+ES4O4Oc93E= # The server_private.key value.
Address = 10.5.5.1/24 # Internal IP address of the VPN server.
ListenPort = 61951 # Previously, we opened this port to listen for incoming connections in the firewall.
# Change "enp0s5" to the name of your network interface in the following two settings. This commands configures iptables for WireGuard.
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o enp0s5 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o enp0s5 -j MASQUERADE
[Peer]
PublicKey = gsgfB29uYjpuFTCjC1+vHr9M7++MHJcG6Eg4rtuTu34= # client_public.key value.
AllowedIPs = 10.5.5.2/32 # Internal IP address of the VPN client.
Save and close this file. To start the WireGuard VPN server enter the command:
Configure the interface autorun after a system reboot.
WireGuard client configuration
You also need to install “resolvconf” on the client.
Now, create the WireGuard configuration file on the client machine.
Fill it in with the following lines:
[Interface]
PrivateKey = eLI6PoQf3xhLHu+wlIIME5ullpxxp8U+sYMKHGcv2VI= # The client_private.key value.
Address = 10.5.5.2/24 # IP address of the client's wg0 interface.
DNS = 8.8.8.8
[Peer]
PublicKey = tsGQ8spwOQhpJb4BbhZtunLZEJCcPxUBIaQUpniQ+z4= # The server_public.key value.
AllowedIPs = 0.0.0.0/0 # Traffic for these addresses will be routed through the VPN tunnel. In this example, all addresses are selected.
Endpoint = 82.213.236.27:61951 # Public IP address of our VPN server and port number (ListenPort in the server configuration).
PersistentKeepalive = 25
Save and close it.
Use this command to establish the VPN connection:
To view connection information use this command:
Output:
public key: gsgfB29uYjpuFTCjC1+vHr9M7++MHJcG6Eg4rtuTu34=
private key: (hidden)
listening port: 58208
endpoint: 82.213.236.27:61951
allowed ips: 0.0.0.0/0
...