ip forward using iptables (port and host redirect)

By thomas, 16 September, 2009
I have a server that many people are mistaking for my login (ssh) machine, so I decided to forward attempts to ssh into this machine to my real login machine. I found a few posts on this but they were all somewhat incomplete for my purposes There are two problems here, you need to enable ip_forward in the kernel, and then you need to write a nat table for iptables. I'm going to assume you don't have a nat table to begin with.

Step 1, enable ip_forward.

[root@notlogin ~]# sysctl -w net.ipv4.ip_forward=1 net.ipv4.ip_forward = 1 [root@notlogin ~]# echo net.ipv4.ip_forward=1 >>/etc/sysctl.conf
Step 2, create a nat table, you can do this command line (go commando) or edit /etc/sysconfig/iptables, your call.
*nat :PREROUTING ACCEPT [13:1035] :POSTROUTING ACCEPT [5:516] :OUTPUT ACCEPT [12:966] -A PREROUTING -p tcp -m tcp --dport 22 -j DNAT --to-destination 192.168.0.10:22 -A POSTROUTING -j MASQUERADE COMMIT
If you do this, you won't be able to get into your box via ssh anymore though, you should add an exception for yourself so you can still get into the box via ssh. In the example, the ipaddress of this host is 192.168.0.1 and my client (me) is 192.168.0.2
*nat :PREROUTING ACCEPT [13:1035] :POSTROUTING ACCEPT [5:516] :OUTPUT ACCEPT [12:966] -A PREROUTING -s 192.168.0.2 -p tcp -m tcp --dport 22 -j DNAT --to-destination 192.168.0.1:22 -A PREROUTING -p tcp -m tcp --dport 22 -j DNAT --to-destination 192.168.0.10:22 -A POSTROUTING -j MASQUERADE COMMIT
What we're saying here is that if I'm coming from 192.168.0.2, just pass me into the real machine (192.168.0.1), if I'm not, do the next rule and pass me off to 192.168.0.10. The fun thing is that you can change the port too, so you could have people trying to telnet to port 23 on 192.168.0.1 be redirected to ssh on 192.168.0.10 also.

Hope that saves someone some time.