0

I am struggling to forward a port via iptables. I did a lot of googling but all solutions I tried do not work.

Very simple setup with three computers on the same LAN

192.168.0.1 # destination
192.168.0.2 # redirector (only one interface)
192.168.0.3 # source

My iptables config is pretty simple as well

# iptables -L -n -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:192.168.0.1
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443 to:192.168.0.1

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination         
MASQUERADE  all  --  0.0.0.0/0            0.0.0.0/0

# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination 

# iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

According to what I read this should work. But it doesn't. I alternatively played with iptables -t nat -I POSTROUTING 1 -p tcp -d 192.168.0.1 --dport 443 -j SNAT --to-source 192.168.0.1 but doesn't work either. And yes ip_forward is enabled.

Browsing to 192.168.0.2:80/443 should return content from 192.168.0.1, no? Any ideas?

TylerDurden
  • 191
  • 1
  • 3
  • 14
  • You need a masquerade rule, and the interface that is connected to your WAN. The box that will be the router needs 2 interfaces. Something like this: /sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE /sbin/iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT /sbin/iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT – Gmck Sep 10 '16 at 16:22
  • So it cannot work on a host with a single interface? – TylerDurden Sep 10 '16 at 17:43
  • I got it working! The correct rules are `iptables -t nat -A PREROUTING -d 192.168.0.2 ! -s 192.168.0.1 -p tcp --dport 80 -j DNAT --to 192.168.0.1:80` and `iptables -t nat -A POSTROUTING -d 192.168.0.1 -p tcp --dport 80 -j SNAT --to 192.168.0.2`. Adding `-d` did the trick. – TylerDurden Sep 10 '16 at 20:05

1 Answers1

0

I got it working! The correct rules are

iptables -t nat -A PREROUTING -d 192.168.0.2 ! -s 192.168.0.1 -p tcp --dport 80 -j DNAT --to 192.168.0.1:80
iptables -t nat -A POSTROUTING -d 192.168.0.1 -p tcp --dport 80 -j SNAT --to 192.168.0.2.

Adding -d did the trick.

TylerDurden
  • 191
  • 1
  • 3
  • 14