Code with Abrar


sudo apt update -y && sudo apt upgrade -y
sudo apt install linux-headers-$(uname -r) wireguard wireguard-dkms net-tools -y
Bash
sudo nano /etc/wireguard/wg0.conf
Bash
[Interface]
Address = 10.10.0.1/24
SaveConfig = true
ListenPort = 51820
PrivateKey = SERVER_PRIVATE_KEY
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
Conf
sudo wg-quick up wg0
Bash
sudo wg show wg0
Bash
sudo systemctl enable wg-quick@wg0
Bash

For NAT to work, we need to enable IP forwarding. Open the /etc/sysctl.conf file and add or uncomment the following line

sudo nano /etc/sysctl.conf
Bash
net.ipv4.ip_forward=1
sudo sysctl -p
Bash
wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey
Bash
sudo nano /etc/wireguard/wg0.conf
Bash

For setting up IP Port forwarding, Add the subnet in AllowedIPs in wg0.conf and also:

PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; iptables -t nat -A POSTROUTING -o wg0 -j MASQUERADE
PostUp = /etc/wireguard/port-up.sh

PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; iptables -t nat -D POSTROUTING -o wg0 -j MASQUERADE
PostDown = /etc/wireguard/port-down.sh
Conf

In the port-up.sh

sudo iptables -t nat -A PREROUTING -p tcp --dport 5060 -j DNAT --to-destination 10.30.30.14:5060
Bash