0

Say we have a Linux based router with WAN interface eth0 ip addr 4.3.2.1 (w/ whatever gw ip) and LAN interface eth1 ip addr 192.168.51.1/24, which means we need an iptables rule below to make the router or nat gateway to work (together with ipv4 forwarding enabled in sysctl):

iptables -t nat -A POSTROUTING -s 192.168.51.0/24 -j MASQUERADE

Then we've got a new device connected on the LAN interface, with ip addr 192.168.51.2/24 and gw 192.168.51.1, so it could connect to public internet through the gw as expected.

Now the device want to access a web server on 1.1.1.1, the http request traffic should be from src like 192.168.51.2:40960 (a random src port) to dst 1.1.1.1:80, and when the traffic goes thru the router, it should be changed to src like 4.3.2.1:50961 (another random src port selected and recorded on the Network Translation Port Table) to dst 1.1.1.1:80, right?

Then when the response heads back, the packet with dst 4.3.2.1:50961 will be reversed back to 192.168.51.2:40960 based on the NAPT and well received. Everything's working so far so well.


Now the Problem comes, we want to setup the device 192.168.51.2 as a DMZ host. We add one more iptables rule like:

iptables -t nat -A PREROUTING -i eth0 -j DNAT --to 192.168.51.2

Now let's imagine the device want to access the same web service again. This time when the response comes back from 1.1.1.1:80 to dst 4.3.2.1:50961, we need to know which path it should go - either 192.168.51.2:50961 according to the DNAT rule we just set, or the 192.168.51.2:40960 based on the NAPT record when the traffic went out from the WAN?

Which one has... let's say - higher priority... to process the packets of the response?

Thanks in advance.

2
  • Btw, MASQUERADE works in the POSTROUTING chain, not PREROUTING.
    – Tom Yan
    Sep 27 at 4:52
  • Thanks @TomYan for reminding me that, that's clearly wrong which I should correct. Sep 27 at 5:49

1 Answer 1

1

Existing conntrack states (the "NAPT records") always have priority over any -t nat rules.

If you remember, the -t nat table is only visited by one packet per connection – that's because any packet (whether forward or reply) that matches an existing conntrack state is processed according to stored values in that state, without consulting the iptables NAT rules at all.

1
  • Appreciate your instant and clear answer, @u1686_grawity. And experiments show same behavior as you asserted. So would you mind to let me know where to get manual or articles as you mentioned "if you remember" - which I don't - since I've used conntrack features like NEW or ESTABLISHED but not enough in depth. Sep 27 at 6:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .