How to setup a VPN with Wireguard
Generate a key pair on your server:
server$ wg genkey | tee private | wg pubkey > public
And do the same on your client:
client$ wg genkey | tee private | wg pubkey > public
(There is no need to keep these files once the configuration is set up).
On the server, create
/etc/wireguard/wg0.conf with the following contents:
[Interface] Address = 10.6.0.1/24 ListenPort = 51820 PrivateKey = SERVER_PRIVATE_KEY PostUp = ufw route allow in on %i out on eth0 from 10.6.0.0/24 PostUp = ufw route allow in on eth0 out on %i to 10.6.0.0/24 PostDown = ufw route delete allow in on %i out on eth0 from 10.6.0.0/24 PostDown = ufw route delete allow in on eth0 out on %i to 10.6.0.0/24 [Peer] PublicKey = CLIENT_PUBLIC_KEY AllowedIPs = 10.6.0.2/32
SERVER_PRIVATE_KEY with the server's private key (the contents of
private on the server from above) and
CLIENT_PUBLIC_KEY with the client's
public key (the contents of
public on the client from above). In this
example, the peers on the VPN will use the subnet
10.6.0.0/24, but you can
set this to anything you want.
Now, on the server run
server# wg-quick up wg0
This will create the
wg0 network interface, assign it the IP address you
provided, and begin listening on port 51820. It will also create the firewall
rules listed in the
PostUp sections in
wg0.conf (if you are not using
then delete those lines from the configuration file).
If your client is another Linux server, then repeat the previous steps on the client. Otherwise, use the Wireguard application available for your OS to create a new configuration file. The contents of this file will be similar to the one for the server:
[Interface] Address = 10.6.0.2/24 ListenPort = 51820 PrivateKey = CLIENT_PRIVATE_KEY [Peer] PublicKey = SERVER_PUBLIC_KEY AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = vpn.example.com:51820
In the client's configuration file, we use
AllowedIps = 0.0.0.0/0, ::/0 to
route all traffic over the VPN. To only route traffic for certain IP
AllowedIPs as desired.
Endpoint option is the remote address of the VPN server.
To add more clients, simply add new
Peer sections to the server's
file (modifying the public key and
AllowedIPs setting for each client).