iptables MASQUERADE and SNAT together

1

Good people,

I have a network having the following setup

eth0 10.216.11.41 internet facing

eth1 192.168.0.4 internal network interacting with other machines within the internal network.

Id like to use this machine as a gateway with the following requirements.

  1. All traffic from the internal network going out to yahoo.com be SNATted with a --to 10.216.11.40 through eth0
  2. Everything else to be MASQUARADed out via eth0 whose ip is 10.216.11.41

I had hoped to achieve this vis

#everything to yahoo be snatted
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 10.216.11.40 --destination yahoo.com 

#everything else be masqueraded
iptables --t nat --A POSTROUTING --o eth0 -j MASQUERADE

But alas the SNATting rule doesn't take a destination.

How can I achieve the above requirements?

artfullyContrived

Posted 2013-08-10T13:09:38.270

Reputation: 111

Answers

2

You need to put the SNAT in a new separate chain.

Then where you have the SNAT now, you need to write a rule that tests the destination IP, and if it's equvialent to the one you want to do this for, to jump to the chain you made above.


Near the beginning of your iptables file

/sbin/iptables -t nat -N SNATChain

to create a chain in the nat table called "SNATChain"

Then, replace this:

#everything to yahoo be snatted
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 10.216.11.40 --destination yahoo.com

with this:

#if the destination IP matches yahoo, throw it to SNATChain
/sbin/iptables -t nat -A POSTROUTING -o eth0 --destination yahoo.com -j SNATChain

and then populate your SNATChain with the rule you want

/sbin/iptables -t nat -A SNATChain -o eth0 -j SNAT --to 10.216.11.40

I believe that's how to do it. Been awhile since I've messed with iptables.

LawrenceC

Posted 2013-08-10T13:09:38.270

Reputation: 63 487

thanks for the prompt response. kindly provide a sample command to achieve what you have written – artfullyContrived – 2013-08-10T13:46:35.483

Try that out. Please note that Netfilter doesn't resolve IP addresses (above you're going to get whatever yahoo.com resolves to when the rules are applied), so if yahoo.com changes their IP address (or uses multiple in a CDN setup) you'll need to refresh the rules for it to work. – LawrenceC – 2013-08-10T14:18:58.750