What WireGuard is
WireGuard is a free VPN that is small, fast and uses modern encryption. Each device has a key pair, and devices that know each other's public keys can connect.
Prepare the VPS
- Choose a VPS with a data center near you and enough resources for your users. Ubuntu is a good choice.
- Connect with SSH:
ssh root@your_server_ip
- Update the packages:
sudo apt update
sudo apt upgrade
- Create a user with sudo rights (do not work as root):
sudo adduser username
sudo usermod -aG sudo username
- Secure SSH. In
/etc/ssh/sshd_config, setPermitRootLogin no(after you checked that the new user can log in), and optionally change the port:
sudo nano /etc/ssh/sshd_config
sudo systemctl restart ssh
Reconnect as the new user.
Install WireGuard
sudo apt install wireguard
Check the version:
sudo wg --version
(On a current kernel the module is built in. If you want to check, run sudo modprobe wireguard and lsmod | grep wireguard.)
Create the server keys
sudo -i
cd /etc/wireguard
umask 077
wg genkey | tee server_private.key | wg pubkey > server_public.key
Configure the server
Create /etc/wireguard/wg0.conf:
nano /etc/wireguard/wg0.conf
Add (replace the key with the contents of server_private.key, and eth0 with the name of your network interface):
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <server_private_key>
SaveConfig = true
PostUp = iptables -A 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
Addressis the IP address of the server inside the VPN.ListenPortis the UDP port.PrivateKeyis the server private key.
Turn on IP forwarding
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
Open the firewall
sudo ufw allow 51820/udp
sudo ufw allow OpenSSH
sudo ufw enable
Start WireGuard
sudo wg-quick up wg0
sudo systemctl enable wg-quick@wg0
Check it with sudo wg.
Add a client
On the client (a laptop or phone), install WireGuard and create a key pair. Then:
- Make the client config:
[Interface]
PrivateKey = <client_private_key>
Address = 10.0.0.2/24
DNS = 1.1.1.1
[Peer]
PublicKey = <server_public_key>
Endpoint = your_server_ip:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
- On the server, add the client as a peer:
sudo wg set wg0 peer <client_public_key> allowed-ips 10.0.0.2/32
Because SaveConfig = true, the peer is saved in wg0.conf when WireGuard stops.
- Turn on the tunnel on the client. Check your public IP. It should now be the one of your VPS.
Quick recap
- Install
wireguard, create keys andwg0.conf. - Turn on forwarding and open UDP 51820.
- Add each client as a peer.