How to enable port forwarding with iptables

From Meta Makers Wiki
Jump to: navigation, search


You need to do three things on your VPN server (the Linode) to make this work:

1) You must enable IP forwarding:

   sysctl -w net.ipv4.ip_forward=1

2) Set up destination NAT (DNAT) to forward the port. You've probably already figured this out because it's standard port forwarding stuff, but for completeness:

   iptables -t nat -A PREROUTING -d x.x.x.x -p tcp --dport 6000 -j DNAT --to-dest y.y.y.100:6000

3) Set up source NAT (SNAT) so that from your VPN client's perspective, the connection is coming from the VPN server:

   iptables -t nat -A POSTROUTING -d y.y.y.100 -p tcp --dport 6000 -j SNAT --to-source y.y.y.1

The reason you need the SNAT is because otherwise your VPN client will send its return packets straight to the host which initiated the connection (z.z.z.z) via its default gateway (i.e. Verizon 3G), and not via the VPN. Thus the source IP address on the return packets will be your Verizon 3G address, and not x.x.x.x. This causes all sorts of problems, since z.z.z.z really initiated the connection to x.x.x.x.

In most port forwarding setups, the SNAT is not needed because the host performing the port forwarding is also the default gateway for the destination host (e.g. a home router).

Also note that if you want to forward port 6000 to a different port (say 7000), then the SNAT rule should match on 7000, not 6000.