Iptables – Restricting output to only allow localhost using iptables

firewalliptables

I would like to restrict outbound traffic to only localhost using iptables. I already have a default DROP policy on OUTPUT and a rule REJECTing all traffic. I need to add a rule above that in the OUTPUT chain.

I have seen a couple different examples for this type of rule, the most common being:

-A OUTPUT -o lo -j ACCEPT

and

-A OUTPUT -o lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT

Is there any reason to use the latter rather than the former? Can packets on lo have an address other than 127.0.0.1?

Best Answer

If your machine has multiple interfaces, and you try to communicate with the IP on one of these other interfaces, the traffic will actually go over the lo interface. Linux is smart enough to figure out this traffic is destined for itself, and not try to use the real interface.

The rule -A OUTPUT -o lo -j ACCEPT will allow this other traffic, while the rule -A OUTPUT -o lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT would reject it.

.

You can see everything the kernel will route over the loopback interface by running

ip route show type local table all

(just note the first value, which is either an IP or a network/mask)