Linux – iptables: what the difference between filter and mangle

iprouteiptableslinuxrouting

I am using iptables to to mark the package and want to route based on the marks.

First I added the ip rule:

sudo ip rule add fwmark 1 prohibit

(The "prohibit" is just for test, I will change it to some route table later.)

Then I began to mark the packages:

sudo iptables -A OUTPUT -d 192.168.1.0/24 -j MARK --set-mark 1

But the computer can still access the 192.168.1.0/24 networks.

After a long time's googling and struggling, I tried:

sudo iptables -t mangle -A OUTPUT -d 192.168.1.0/24 -j MARK --set-mark 1

It works and the connection was blocked.

In the first case, the default table of filter is used. So my question is what is the difference between mangle table and filter table? Which one should be used in what cases? As my understanding, all these tables will be consulted before the routing policy, then why the filter table doesn't work properly?

Best Answer

mangle is for mangling (modifying) packets, while filter is intended to just filter packets.

A consequence of this, is that in LOCAL_OUT, after traversing the tables and getting the filtering decision, mangle may try to redo the routing decision, assuming the filtering decision is not to drop or otherwise take control of the packet, by calling ip_route_me_harder, while filter just returns the filtering decision.

Details at net/ipv4/netfilter/iptable_mangle.c and net/ipv4/netfilter/iptable_filter.c.

Related Question