O'Reilly logo

Linux Server Hacks by Rob Flickenger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #46. Simple IP Masquerading

Set up NAT on your gateway in ten seconds

If you have a private network that needs to share an Internet connection with one IP address, you'll want to use IP Masquerading on your gateway machine. Luckily, with iptables this is a simple two-liner:

# echo "1" > /proc/sys/net/ipv4/ip_forward
# iptables -t nat -A POSTROUTING -o $EXT_IFACE -j MASQUERADE

where $EXT_IFACE is the outside interface of your gateway. Now any machines that reside on a network on any of the other interfaces in your gateway will be able to "get out" to the Internet. As far as the Net is concerned, all traffic originates from your gateway's external IP address.

There was a time when one had to worry about miscreants on the external network sending forged packets to your gateway, claiming to be originating from the internal network. These packets would obligingly be masqueraded by the kernel, and leave your network as if they were legitimate traffic. This made it possible for anyone to launch attacks that apparently originated from your network, making very bad times for the hapless gateway owner.

I say that this was a problem, because recent kernels give you a free firewall rule to deal with exactly this problem, called rp_filter . With rp_filter enabled, if a packet that arrives on an interface has a source address that doesn't match the corresponding routing table entry, it is dropped. This effectively prevents IP spoofing and allows simple (and safe) masquerading with the example above.

In the very unlikely event that rp_filter is causing problems for you, you can deactivate it very easily:

# echo "0" > /proc/sys/net/ipv4/conf/all/rp_filter

See also:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required