Setting Up WireGuard VPN

From Server rental store
Jump to navigation Jump to search

Setting Up WireGuard VPN

This guide provides a comprehensive, step-by-step walkthrough for setting up your own WireGuard VPN server and configuring clients to connect to it. WireGuard is a modern, fast, and secure VPN protocol that is significantly simpler to configure and manage than older protocols like OpenVPN.

Introduction

A Virtual Private Network (VPN) creates a secure, encrypted tunnel over an untrusted network, such as the internet. This allows you to access resources as if you were directly connected to the private network, enhancing security and privacy. WireGuard has gained popularity due to its simplicity, performance, and strong cryptographic primitives.

This tutorial is designed for users with basic Linux command-line experience. For optimal performance and control, consider a dedicated server from PowerVPS that offers full root access, allowing you to customize your VPN setup precisely to your needs.

Prerequisites

Before you begin, ensure you have the following:

  • A server running a recent Linux distribution (e.g., Ubuntu 20.04 LTS or later, Debian 11 or later, CentOS Stream 8 or later).
  • Root or sudo privileges on the server.
  • A basic understanding of networking concepts (IP addresses, ports, firewalls).
  • A client device (Linux, Windows, macOS, Android, iOS) that will connect to the VPN.
  • A static public IP address for your VPN server. If your server's IP address might change, you'll need to use a dynamic DNS service.

Server Setup

We will proceed with installing WireGuard on the server and generating the necessary keys.

1. Install WireGuard

First, update your package lists and install the WireGuard package.

For Debian/Ubuntu:

sudo apt update
sudo apt install wireguard

For CentOS Stream/Rocky Linux/AlmaLinux:

sudo dnf install epel-release
sudo dnf install wireguard-tools

2. Generate Server Keys

WireGuard uses public-key cryptography. You need to generate a private key and a corresponding public key for the server.

wg genkey | sudo tee /etc/wireguard/privatekey
sudo chmod 600 /etc/wireguard/privatekey
sudo cat /etc/wireguard/privatekey | sudo wg pubkey | sudo tee /etc/wireguard/publickey

Keep your `privatekey` file secure. The `publickey` will be shared with clients.

3. Create Server Configuration File

Create the WireGuard server configuration file, typically located at `/etc/wireguard/wg0.conf`.

sudo nano /etc/wireguard/wg0.conf

Paste the following configuration, replacing placeholders as noted:

[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = YOUR_SERVER_PRIVATE_KEY

# SaveConfig = true # Uncomment this line if you want WireGuard to automatically save configuration changes (e.g., adding peers)
  • `Address`: This is the IP address and subnet that your WireGuard VPN will use internally. `10.0.0.1/24` is a common choice.
  • `ListenPort`: The UDP port WireGuard will listen on. `51820` is the default.
  • `PrivateKey`: Paste the content of your `/etc/wireguard/privatekey` file here.

To get your server's private key:

sudo cat /etc/wireguard/privatekey

4. Enable IP Forwarding

For the server to route traffic from clients to the internet (or other networks), you need to enable IP forwarding.

Edit `/etc/sysctl.conf`:

sudo nano /etc/sysctl.conf

Uncomment or add the following line:

net.ipv4.ip_forward=1

Apply the changes immediately:

sudo sysctl -p

5. Configure Firewall (iptables/ufw)

You need to allow traffic on your chosen WireGuard port and set up Network Address Translation (NAT) to allow clients to access the internet through the VPN server.

Using ufw (Uncomplicated Firewall):

First, allow WireGuard traffic:

sudo ufw allow 51820/udp

Next, configure NAT. Edit the `ufw` configuration file:

sudo nano /etc/ufw/before.rules

Add the following lines at the top of the file, before the `*filter` section:

# START WIREGUARD RULES
# NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]
# Allow traffic from WireGuard clients to eth0 (change eth0 to your server's public network interface)
-A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
COMMIT
# END WIREGUARD RULES

Replace `eth0` with your server's primary public network interface (e.g., `ens3`, `eth0`, `eno1`). You can find your interface name using `ip a`.

Finally, enable ufw if it's not already running and allow SSH to avoid locking yourself out:

sudo ufw allow OpenSSH
sudo ufw enable

Using iptables:

If you are not using `ufw`, you can use `iptables` directly.

Allow WireGuard traffic:

sudo iptables -A INPUT -i eth0 -p udp --dport 51820 -j ACCEPT
sudo iptables -A FORWARD -i wg0 -j ACCEPT
sudo iptables -A FORWARD -i wg0 -j ACCEPT -m state --state RELATED,ESTABLISHED
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Remember to replace `eth0` with your server's public network interface.

To make `iptables` rules persistent across reboots, you'll need to install and configure `iptables-persistent`:

sudo apt install iptables-persistent # For Debian/Ubuntu
sudo netfilter-persistent save

For CentOS Stream/Rocky Linux/AlmaLinux, `firewalld` is the default. You would typically add services and ports to `firewalld` and ensure the masquerade is enabled.

6. Start and Enable WireGuard

Start the WireGuard interface:

sudo wg-quick up wg0

Check the status:

sudo wg show

You should see information about your interface, including its public key.

Enable WireGuard to start on boot:

sudo systemctl enable wg-quick@wg0

Client Configuration

Now, let's configure a client to connect to your WireGuard server. This process involves generating client keys and creating a configuration file for the client.

1. Generate Client Keys

On your client device (or on the server and then securely transfer the private key), generate a key pair for the client.

On the client device (if it's Linux):

wg genkey | tee client_privatekey
wg pubkey < client_privatekey | tee client_publickey

Securely transfer the `client_privatekey` to your client device where WireGuard is installed. The `client_publickey` will be added to the server's configuration.

2. Add Client as a Peer on the Server

On your WireGuard server, you need to add the client's public key as a "peer". You can do this by editing the `/etc/wireguard/wg0.conf` file.

First, get the client's public key (e.g., `CLIENT_PUBLIC_KEY`).

Edit the server's configuration file:

sudo nano /etc/wireguard/wg0.conf

Add the following section under the `[Interface]` section:

[Peer]
PublicKey = CLIENT_PUBLIC_KEY
AllowedIPs = 10.0.0.2/32
  • `PublicKey`: This is the client's public key generated in the previous step.
  • `AllowedIPs`: This is the IP address assigned to this specific client within the VPN's internal network. Use a unique IP from your VPN subnet (e.g., `10.0.0.2/32` for the first client). The `/32` indicates a single IP address.

After saving the changes to `wg0.conf`, you need to reload the WireGuard interface for the new peer to be recognized:

sudo wg-quick down wg0
sudo wg-quick up wg0

Alternatively, if you uncommented `SaveConfig = true` in your `wg0.conf`, you can simply add the peer using the `wg set` command:

sudo wg set wg0 peer CLIENT_PUBLIC_KEY allowed-ips 10.0.0.2/32

If `SaveConfig = true` is set, this change will be written to `/etc/wireguard/wg0.conf`.

3. Create Client Configuration File

On your client device, create a configuration file (e.g., `client.conf`).

[Interface]
PrivateKey = YOUR_CLIENT_PRIVATE_KEY
Address = 10.0.0.2/24 # Or the IP assigned to this client
DNS = 1.1.1.1 # Optional: specify DNS servers

[Peer]
PublicKey = YOUR_SERVER_PUBLIC_KEY
Endpoint = YOUR_SERVER_PUBLIC_IP:51820
AllowedIPs = 0.0.0.0/0 # Route all traffic through the VPN
# AllowedIPs = 10.0.0.0/24 # Route only VPN internal traffic through the VPN
# AllowedIPs = 192.168.1.0/24, 10.0.0.0/24 # Route specific subnets and VPN internal traffic
PersistentKeepalive = 25 # Optional: helps keep connection alive through NAT
  • `PrivateKey`: Paste the content of your `client_privatekey` file here.
  • `Address`: The IP address assigned to this client within the VPN network (e.g., `10.0.0.2/24`). The `/24` is often used here for the client's local network context.
  • `DNS`: Specifies which DNS servers the client should use when connected to the VPN.
  • `PublicKey`: Paste the content of your server's public key file (`/etc/wireguard/publickey`).
  • `Endpoint`: Your server's public IP address and the WireGuard port.
  • `AllowedIPs`: This is crucial.
   *   `0.0.0.0/0` means all internet traffic from the client will be routed through the VPN.
   *   Specify internal network ranges (e.g., `192.168.1.0/24`) if you only want to access specific networks.
  • `PersistentKeepalive`: Sends a UDP packet every 25 seconds to keep the connection alive, useful if the client is behind NAT.

To get your server's public key:

sudo cat /etc/wireguard/publickey

4. Connect the Client

The method for connecting varies by operating system:

  • **Linux:** Save the `client.conf` file and run:
sudo wg-quick up client.conf
   To disconnect:
sudo wg-quick down client.conf
  • **Windows/macOS:** Download the WireGuard client application. Import the `client.conf` file.
  • **Android/iOS:** Download the WireGuard app. Create a new tunnel by scanning a QR code (you can generate one from your `client.conf` using online tools or by printing it) or by manually entering the configuration.

5. Verify Connection

On the client, check your public IP address (e.g., by visiting whatismyip.com). If `AllowedIPs = 0.0.0.0/0` is set on the client, your public IP should now be your server's public IP address.

On the server, you can check the status of connected peers:

sudo wg show

You should see the client listed with its handshake time.

Managing Multiple Clients

To add more clients, repeat the process:

1. Generate a new key pair for each client. 2. On the server, add a new `[Peer]` section in `/etc/wireguard/wg0.conf` for each client, assigning them a unique IP address from the VPN subnet (e.g., `10.0.0.3/32`, `10.0.0.4/32`, etc.). Remember to reload the WireGuard interface on the server after modifying `wg0.conf`. 3. Create a unique `client.conf` file for each client, ensuring they use their assigned IP address and the server's public key.

Troubleshooting

  • **No connection:**
   *   Check firewall rules on the server (UDP port 51820 must be open).
   *   Verify that WireGuard is running on the server (`sudo systemctl status wg-quick@wg0`).
   *   Ensure `net.ipv4.ip_forward=1` is set and applied.
   *   Double-check that public and private keys are correctly copied and match between server and client.
   *   Confirm the `Endpoint` IP address and port in the client config are correct.
  • **Can't access the internet:**
   *   Ensure NAT (MASQUERADE rule) is correctly configured in your firewall.
   *   Check `AllowedIPs` on the client configuration. `0.0.0.0/0` is needed for full internet access.
   *   Verify IP forwarding is enabled on the server.
  • **Client handshake not showing:**
   *   This often indicates a connectivity issue or incorrect keys. Review the steps above.
   *   On the server, run `sudo wg show` to see if any handshake has occurred.
  • **Server IP changes:** If your server's public IP address changes and you are not using a dynamic DNS service, you'll need to update the `Endpoint` in all client configurations.

Further Reading and Related Articles