Simple port forwarding with Iptables in linux

One of the most common question I received from my customers is how to setup a simple port forwarding on top of their existing iptables firewall rules. Most of my customers are using Centos 5 and only uses the standard iptables provided by default upon operating system installation. For a more complicated setup I usually recommend existing iptables manipulation interface/packages (my favorite is Vuurmuur), but for those who just need one simple rule the the guide below should be enough to handle them.

Assumptions:

  • Only use IPV4
  • Two unit of machines involved, the linux machine that will act as the gateway/forwarder (IP: 192.168.0.1) and the destination machine (IP: 192.168.0.100)
  • The port to be forwarded is 5901 (Change to whatever port you want)
  • This guide is based on linux Centos 5, some other distros could also use the same setup but some other might need additional modification
  • Iptables service is turned on, and SELinux is turned off

Firstly, we have to make sure that the kernel allow port forwarding. Edit /etc/sysctl.conf and make the amendment below

net.ipv4.ip_forward = 1

To activate the rule above immediately without a reboot, run

sysctl -p /etc/sysctl.conf

Then run each of the commands below

To allow forwarding rule specifically to machine 192.168.0.100 in the FORWARD chain

iptables -I FORWARD -p tcp -d 192.168.0.100 --dport 5901 -j ACCEPT

The actual port forwarding rule

iptables -t nat -A PREROUTING -i lo -p tcp --dport 5901 -j DNAT --to-destination 192.168.0.100:5901

To masquerade the routed connection so that the firewall will treat it as local connection.

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

The port forwarding rules should be ready by now, you can test it by using some common tools like telnet.

To view the current rules, run

/etc/init.d/iptables status

Bear in mind that the iptables modification above will only effective on this boot session. It will be destroyed/reverted back to original setup after reboot. To make the rules permanent, make sure you backup your existing iptables template first. Simply copy /etc/sysconfig/iptables to another place or name.

After that, just run command

service iptables save

This will store your modified iptables rules into /etc/sysconfig/iptables thus making it persist even after reboot.

  • Jim

    DUDE!
    After banging my head for 3 days, I found this, and BINGO! it worked.
    Step-by-step was perfect!

    The ONLY change I had to make was to change it from hogging the entire public NIC to just 1 IP address I had free on the public NIC.

    But it worked great!
    Thanks!