brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a nat block in ufw before.rules lets a VPN server share its internet connection

Ufw
~/tips/tip-ufw-before-rules-masquerade

*nat

Adds masquerading and forwarding so VPN clients can reach the internet through the server.

ufw has no command for NAT. When a WireGuard or OpenVPN server should send client traffic on to the internet, you add a small block to /etc/ufw/before.rules yourself.

Put this at the end of the file, after the COMMIT of the existing *filter section. Use your VPN subnet and your outside interface:

*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 198.51.100.0/24 -o eth0 -j MASQUERADE
COMMIT

Then turn on forwarding in /etc/ufw/sysctl.conf, which ufw reads when it starts, and allow the routed traffic:

net/ipv4/ip_forward=1
sudo ufw route allow in on wg0 out on eth0
sudo ufw reload

I find it helps to know what each part does. The masquerade line rewrites the source address of client traffic to the server’s own address, so replies find their way back. The route allow rule is needed because ufw drops forwarded traffic by default. Without it the NAT block does nothing visible.

Be careful with the file. A typo in before.rules makes the reload fail with an iptables error. Keep a copy before you edit, and run sudo ufw reload while you still have a working session. The 198.51.100.0/24 range is a documentation placeholder; use the subnet from your own VPN config.

Further reading: ufw-framework(8) manual page, ufw(8) manual page

Going deeper: Why a Tailscale device vanishes after 180 days, and how to stop it

More Ufw tips sudo ufw app update all sudo ufw show raw sudo ufw allow to 10.0.0.1 proto esp sudo ufw allow to 224.0.0.0/24 from 10.0.0.1 proto vrrp sudo ufw show listening All Ufw tips (32) All topics

Link