I use the auto generated rules that come from OpenWRT as an example of NAT reflection (NAT loopback).
So let's pretend there's a network 192.168.1.0/24 with two hosts (+ router): 192.168.1.100 and 192.168.1.200. The router has two interfaces LAN (br-lan) and WAN (eth0). The LAN interface has an IP 192.168.1.1 and the WAN interface has an IP 82.120.11.22 (public). There's a www server on 192.168.1.200. We want to connect from 192.168.1.100 to the web server using the public IP address.
If you wanted to redirect WAN->LAN so people from the internet can visit the web server, you would add the following rules to iptables:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.200:80
I know what the rules mean. But there's also two other rules, which are responsible for NAT reflection. One of them isn't that clear to me as the ones above. So the first rule looks like this:
iptables -t nat -A PREROUTING -i br-lan -s 192.168.1.0/24 -d 82.120.11.22/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.200
And this means that all the traffic from the 192.168.1.0/24 network that is destined to the public IP to the port 80 should be sent to the local web server, which means that I type the public IP in firefox and I should get the page returned by the server, right? All the other forwarding magic in the filter
table was already done, but I still can't connect to the web server using the public IP. The packet hit the rule, but nothing happens.
We need another nat
rule in order to make the whole mechanism work:
iptables -t nat -A POSTROUTING -o br-lan -s 192.168.1.0/24 -d 192.168.1.200/32 -p tcp -m tcp --dport 80 -j SNAT --to-source 192.168.1.1
I don't know why the rule is needed. Can anyone explain what exactly the rule does?