NAT with iptables : super fast tutorial
posted April 2014
So I know how to use iptables, I know what a NAT is, but I don't want to learn how to exactly do it. Misery... I have to learn how to do it because I have an exam that will probably ask me how to do it in a few days. So I've been looking for a super simple tutorial, a 1 minute tutorial, on how to setup a NAT configuration with iptables in 1 minute. Couldn't really find it so here it is, if this is somewhat useful for someone, you're welcome.
For NAT to work, you have to allow forwarding on your server. Easy peasy:
$ echo 1 > /proc/sys/net/ipv4/ip_forward
Also, before adding new iptables rules, be sure to check what rules you already have
$ iptables -L
you should allow some forwarding for it to work (if the policy is default to DROP). But this not a tutorial about iptables.
I have a server with:
eth0 connected to the network
- eth1 connected to internet
Let's modify the PREROUTING part. Traffic coming from internet on our public address (@pub) and trying to reach our machine:
$ iptables -t nat -A PREROUTING -d @pub -i eth0 -j DNAT --to-destination @priv
Let's modify the table nat, append a rule to the pretrouting section : something is trying to reach @pub ? Let's put it in our input interface eth0, jump to the Destination Nat protocol, which tells us to send the packet to @priv.
Now Let's modify the POSTROUTING part. Traffic coming from inside our network and trying to reach something, somewhere on internet:
$ iptables -t nat -A POSTROUTING -s @priv -o eth1 -j SNAT --to-source @pub
If the packet is coming from @priv, let's put it on our output interface eth1 and jump to the Source Nat Protocol that will modify the packet so it has the public address (@pub) as source.
Here! You did it. One private IP address mapped to one public IP address.
Same kind of configuration but now we have several private addresses and only one public address.
$ iptables -t nat -A POSTROUTING -s @priv/mask -j MASQUERADE
We can modify every packets coming from the subnetwork @priv to get masqueraded.
$ iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
Or we can just tell all the network to get masqueraded.
And this is it. No PREROUTING Needed.
Again, you're welcome ;)