Monday, January 4, 2016

Linux: How to port forwarding with iptables between 2 hosts on different networks?



I'm almost desperate... I've been reading for about 2 days iptables forwarding examples and I cannot do a simple port forwarding. I got 2 machines on different networks. server1 (S1 with ip 195.21.2.41) is at my house and server2 (s2 with ip 10.234.141.126) is at Amazon EC2.




I need to forward all the traffic that goes to s2 to s1. I tried this:



flushing all rules, activate kernel parameter to forward, add a postrouting and prerouting rule



iptables -F -t nat
iptables -F
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -d 195.21.2.41 -j MASQUERADE
iptables -t nat -A PREROUTING -i eth0 -d 10.234.141.126 -p tcp --dport 80 -j DNAT --to 195.21.2.41



optionally i also added:



iptables -A FORWARD -p tcp -i eth0 -d 195.21.2.41 --dport 80 -j ACCEPT


Then i tried:



telnet 10.234.141.126 80



But didn't work. Why the hell this isnt working?



UPDATE: take a look at some tests:



[root@ip-10-234-141-216 ~]# telnet 195.21.2.41 80
Trying 195.21.2.41...
Connected to 195.21.2.41.
Escape character is '^]'.

[root@ip-10-234-141-216 ~]# iptables -F -t nat
[root@ip-10-234-141-216 ~]# iptables -F
[root@ip-10-234-141-216 ~]# echo 1 > /proc/sys/net/ipv4/ip_forward
[root@ip-10-234-141-216 ~]# /sbin/iptables -t nat -A PREROUTING -i eth0 -p tcp -d 10.234.141.126 --dport 80 -j DNAT --to-destination 195.21.2.41
[root@ip-10-234-141-226 ~]# /sbin/iptables -t nat -A POSTROUTING -j MASQUERADE
[root@ip-10-234-141-216 ~]# /sbin/iptables -A FORWARD -i eth0 -p tcp --dport 80 -j ACCEPT
[root@ip-10-234-141-216 ~]#
[root@ip-10-234-141-216 ~]# telnet 10.234.141.126 80
Trying 10.234.141.126...
telnet: connect to address 10.234.141.126: Connection refused



UPDATE 2 route output:



[root@ip-10-234-141-216 ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.234.141.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0
169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0
0.0.0.0 10.234.141.1 0.0.0.0 UG 0 0 0 eth0


Answer



If you just need to redirect all incoming traffic to a specified port forwarded to your another machine try rinetd instead of iptables. It's a traffic redirection server.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...