Port forwarding on a firewall via NAT
When a service running on a private address needs to be reachable from the internet, the answer is forwarding a port on the firewall via NAT.
Example: port 8080 of the public IP leads to a web server at 192.168.1.10:80.
- Rewrite the destination of the incoming connection in the
nattable:
iptables -t nat -A PREROUTING -i $WAN -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
- In
FORWARD, allow new connections only to the forwarded service plus established traffic, and drop all other new incoming connections from the external interface. The order matters – the accept rules must come before the drop:
iptables -A FORWARD -i $WAN -p tcp -d 192.168.1.10 --dport 80 -m conntrack --ctstate NEW -j ACCEPT iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT iptables -A FORWARD -i $WAN -m conntrack --ctstate NEW -j DROP
Return traffic needs no rule of its own in POSTROUTING: connection tracking (conntrack) translates the reply back. POSTROUTING with MASQUERADE is only needed for outbound traffic from the internal network to the internet.
Only the specific service on the private IP is reachable from the internet; the rest stays behind the firewall.
_Originally published in Czech in May 2010._