Forwarding ports over WireGuard manually requires a long chain of firewall commands. tun-nat replaces them with a single configuration file on top of nftables.

Step 1. Installation

Requirement: the tool works only with nftables. Check: nft --version; if the command is not found - sudo apt install nftables.

sudo git clone https://github.com/lashkinse/tun-nat.git /etc/tun-nat

No git? Run this first: sudo apt install git.

Step 2. Configuration

Open /etc/tun-nat/config.toml and adjust it to your needs:

[tunnel]
interface = "wg0"     # tunnel interface (WireGuard)
port = 51820          # WireGuard port

[external]
interface = "eth0"    # server's external interface
ip = ""               # empty = automatic mode (MASQUERADE)

# Game server: 27015 tcp + udp to 10.0.0.2
[[port_rules]]
protocol = "tcp"
target = "10.0.0.2"
ports = "27015"

[[port_rules]]
protocol = "udp"
target = "10.0.0.2"
ports = "27015"

# Web service: 8080 to 10.0.0.3
[[port_rules]]
protocol = "tcp"
target = "10.0.0.3"
ports = "8080"

A new rule is a copy of a [[port_rules]] block with your own values:

  • protocol - tcp or udp;
  • target - IP address of the device inside the tunnel;
  • ports - a single port (27015) or a range (27015-27050).

Step 3. Automatic setup with the tunnel

Add two lines to the [Interface] section of /etc/wireguard/wg0.conf:

[Interface]
# ...your existing settings...

PostUp = /etc/tun-nat/apply-nat.sh          # apply rules on start
PreDown = /etc/tun-nat/apply-nat.sh --down  # remove them on shutdown

Use PreDown, not PostDown: by the time PostDown runs, the interface is already gone, and the script won’t be able to find it to clean up the rules.

Restart the tunnel:

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

Done: traffic to the specified ports on your server is now forwarded to the devices inside the tunnel.

🔗 Source code and documentation: github.com/lashkinse/tun-nat