NAT loopback

DMZ和Virtual server做的都是DNAT,即从wan口访问router/gate-way的某服务端口,其实是向router/gate-way内部网络的某设备/pc上的相对应的服务。且只能是wan端的客户访问lan端的服务才有这种端口转发/端口映射的关系,lan端的客户以router/gate-way的wan端地址是访问不了lan端的服务的(如果要实现此功能,也即所谓的NAT loopback的功能,是完全没问题的,只不过要做一下SNAT的iptables命令)。

这里就说说 NAT loopback功能


环境说明:

router/gate-way wan interface: eth2 172.16.15.55, netmask: 255.255.224.0
router/gate-way lan interface: eth0 (briged to br0) 192.168.1.1, netmask: 192.168.1.0/24

interal device (as httpd server): 192.168.1.25

interal pc address (browser as httpd client): 192.168.1.10, gateway:192.168.1.1, netmask: 192.168.1.0/24

optional client: phone support wifi connection


注意:作为测试的lan端客户即httpd client 的gateway必须是router/gate-way lan 端的ip(也即此客户的默认路由), 否则在浏览器上输入的router/gate-way wan端的地址时,请求数据包怎么可能到达router/gate-way呢?如果客户是dhcp模式的话,确定客户确实是从该router/gate-way上获取ip的,还有手机wifi连接时确定连接的热点是该router/gate-way, 一般这两种情况客户的默认路由可以让请求数据包到达router/gate-way的。


这里用httpd server为测试对象, 为不影响router/gate-way本身网页的浏览,改用端口8000映射到内部80端口:

The following command will redirect all HTTP traffic coming from theexternaladdress(172.16.15.55:8000) to the web server at 192.168.1.25:80

iptables -t nat -A PREROUTING -i eth2 -p tcp --dport 8000 -j DNAT --to 192.168.1.25:80

iptables -I FORWARD 1 -i eth2 -p tcp -d 192.168.1.25 --dport 80 -j ACCEPT


If I attempt to access my website from a local computer using its wan address(external IP address), this rule has no effect. The requests are not coming from the external. It need a more specific rule that will redirect local http requests to the web server.The “-s 192.168.1.0/24″ option ensures that this policy only applies to local requests. just let the existing policy handle external http requests.

iptables -t nat -A PREROUTING -s 192.168.1.0/24 -d 172.16.15.55 -p tcp --dport 8000 -j DNAT --to-destination 192.168.1.25:80


Now trying to access the web server results in a “could not connect” error.

Running wireshark on my pc, I can see the HTTP requests arriving from my local web browser, but the replies appear to get lost.

picture here.

Apparently the server tries to send the reply directly back to my local pc (192.168.1.25-->192.168.1.10). This does not work because the requests were sent to external IP address ofrouter/gw (requests 192.168.1.10-->172.16.15.55:8000==>192.168.1.24:80) and the replies are expected from the same origin (replies 172.16.15.55-->192.168.1.10).

The http requests needs to be modified so that they appear to come from my external IP address(requests 192.168.1.10==>172.16.15.55-->192.168.1.25).

iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -d 192.168.1.25 -p tcp --dport 80 -j SNAT --to-source 172.16.15.55

此处也可用lan ip即br0 ip。

To sum it up, the first iptables command will redirect the http request to the web server, and the second iptables command will make it look as if the request came from the external IP address.


会存在日志问题,即log始终记录的数据包源地址为wan ip。

你可能感兴趣的:(NAT loopback)