Set up WireGuard VPN on Linux and allow a remote server to access the local network
For instructions on how to install WireGuard, check the official docs
After installing, log into the machine that is intended to be the WireGuard host for the local network.
Host configuration
Create a public and private key for the host:
umask 077; wg genkey | tee privatekey | wg pubkey > publickey
Create a configuration file for the VPN interface at /etc/wireguard/wg0.conf
:
[Interface]
Address = 10.0.0.1/24
ListenPort = 12345
PrivateKey = <host private key>
PreUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT
[Peer]
AllowedIPs = 10.0.0.2/32
PublicKey = <remote peer public key>
Next up, ensure that IP forwarding is enabled by issuing sysctl -w net.ipv4.ip_forward=1
. Make it persistent by uncommenting the same line in /etc/sysctl.d/99-sysctl.conf
.
Router configuration
Now the host is set up to allow packets to the local network to be forwarded on the host, which in this case will just use its routing table to see where to send it. But local machines will not know where to send response packets yet, since 10.0.0.0/24
is unknown to them.
Therefore, add a static route in your local network router that points 10.0.0.0/24 -> <local-ip-of-wireguard-host>
. This will allow response packets from local machines to be routed back to the WireGuard host machine and sent back across the wire.
Remember to add a port forwarding rule to your local network router for UDP port (in this example) 12345
so the remote server can connect to it.
Peer (remote server) configuration
Finally, it's time to configure the remote peer. Start by logging in to the remote host and create a private and public key for the peer:
umask 077; wg genkey | tee privatekey | wg pubkey > publickey
Create a config file for the remote peer at /etc/wireguard/wg0.conf
:
[Interface]
Address = 10.0.0.2/24
PrivateKey = <remote peer private key>
[Peer]
Endpoint = <public IP of wireguard host>:12345
AllowedIPs = 10.0.0.0/24, <local-area-network>/24
PublicKey = <wireguard host public key>
PersistentKeepalive = 25
In the above example, endpoint could be my.dyndns.com:12345
and local area network could be 192.168.1.0/24
.
PersistentKeepalive
is used to send heartbeats every 25 seconds to keep the connection alive when behind NAT.
Finally, enable and start the WireGuard host first, and then the client. Commands are identical on both machines:
systemctl enable wg-quick@wg0.service
systemctl start wg-quick@wg0.service