Linux – Overlapping MASQUERADE and DNAT

iptableslinuxnat;networking

How can I overlap IP masquerading (PAT/Overload) with destination NAT using iptables on the internal IP space?

What I am trying to have is a private network, ie 10.0.0.0/24 where some public IPs are mapped to various address inside of it. However, if there is a connection that originates from within 10.0.0.0/24, regardless if it has a DNAT public ip or not, it will get overloaded to a specific public IP.

Best Answer

I hope I'm understanding your question, too. Your response to Luke in the comments to baumgart's answer caused me to second-guess my understanding your requirements, but I'm going to post this anyway.

What baumgart is telling you to do in his answer will work, but his last paragraph where he talks about "...will likely cause problems with client-server apps..." isn't correct. He's forgetting that Netfilter's NAT implementation is stateful. That stateful nature of the NAT engine in Netfilter is your friend here.

When the conversation between an Internet host and one of your public IPs gets DNAT'ed to a private IP address Netfilter won't "MASQUERADE" the response packets coming from the private IP back to the Internet host. That's not to say the response packets aren't NAT'ed, but they're not "MASQUERADED". Rather, Netfilter implicity "does the right thing" and SNAT's the response packets from the private IP back to the public IP address to which the Internet host initiated the conversation. It's really very slick.

Meanwhile, for conversations originating from the private IP address to the Internet (not in response to incoming requests from the Internet) the "MASQUERADE" rule will apply.

Basically, Netfilter does what you want "out of the box". I took some time and mocked this up on a test setup just to be sure, and, so long as I understand your requirements properly, it's doing exactly what you're looking for.

(Sorry about not being able to answer earlier in the day-- I was busy with some things earlier today and couldn't, ya' know, play Server Fault as much as I like to.)

Related Topic