How to set up a WireGuard VPN Server on Ubuntu Server 22.04/24.04

Configurare noua (How To)

Situatie

Solutie

Step 1: Install WireGuard on the server

bash
sudo apt update
sudo apt install wireguard -y

Step 2: Generate the server’s public and private keys

bash
cd /etc/wireguard
umask 077
wg genkey | tee server_private.key | wg pubkey > server_public.key

Note down the contents of both files (server_private.key and server_public.key) — you’ll need them shortly.

Step 3: Enable IP forwarding

bash
sudo sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sudo sysctl -p

Step 4: Create the server configuration file

bash
sudo nano /etc/wireguard/wg0.conf

Add the following content, replacing SERVER_PRIVATE_KEY with the private key generated in Step 2:

ini
[Interface]
Address = 10.10.10.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

Replace eth0 with the name of your network interface (check with ip a).

Step 5: Open the port in the firewall

bash
sudo ufw allow 51820/udp
sudo ufw allow OpenSSH
sudo ufw enable

Step 6: Start the WireGuard service

bash
sudo systemctl enable wg-quick@wg0
sudo systemctl start wg-quick@wg0
sudo systemctl status wg-quick@wg0

Step 7: Generate the client keys

On the same server (or on the client machine, if WireGuard is installed there):

bash
wg genkey | tee client_private.key | wg pubkey > client_public.key

Step 8: Add the client to the server configuration

bash
sudo wg set wg0 peer CLIENT_PUBLIC_KEY allowed-ips 10.10.10.2/32
sudo wg-quick save wg0

Step 9: Create the configuration file on the client

On the client device (e.g., laptop), create a file named wg0-client.conf:

ini
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY
Address = 10.10.10.2/24
DNS = 1.1.1.1

[Peer]
PublicKey = SERVER_PUBLIC_KEY
Endpoint = SERVER_PUBLIC_IP:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

Import this file into the WireGuard app (available for Windows, macOS, Android, iOS) and activate the connection.

Step 10: Verify the connection

On the server:

bash
sudo wg show

You should see the connected peer, with a recent handshake and transferred traffic (transfer).

Additional recommendations

  • For multiple clients, repeat Steps 7-9 with different IP addresses (10.10.10.3, 10.10.10.4, etc.)
  • You can restrict AllowedIPs to only the internal subnet (e.g., 192.168.1.0/24) if you don’t want all traffic routed through the VPN (split tunneling)
  • Monitor active connections periodically with wg show, or integrate with Grafana/Prometheus for alerting.

Tip solutie

Permanent

Voteaza

(11 din 17 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?