ip forward using iptables (port and host redirect)

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.

Comments

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

About the Author...

Slides from LISA 2019 Linux systems troubleshooting #LISA2019 https://t.co/D4dMKflK6R Tue Oct 29 05:59:30 +0000 2019

https://t.co/AGeihMALAv configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! https://t.co/IYpRyEb7Hz #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX https://t.co/v3An0miW9L Fri Jul 12 15:06:49 +0000 2019

HTML email with plain mailer plugin on Jenkins https://t.co/Z6FSDMDjy8 Thu Jul 11 21:07:25 +0000 2019