Does iptables have the ability to specify first or last matching on rules? If so how?
Secondly, when rules are specified, is there an implicit drop, or does the following only provide that functionality?
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP
There are very strong performance reasons for first match. First match allows scanning to stop as soon as a packet matches. For this reason it is usual to put the ESTABLISHED,RELATED rules at the top of their chains. Without the first match rule each packet would need to matched against each rule in each applicable chain which becomes increasing expensive as the rule set grows. Busier firewalls are likely to to have larger rule sets, and could have performance problems with last match.
Reading rule sets with a last match approach can be difficult as once you find the first match you don't know if you are done or not. Again this becomes more difficult as the rule set size grows.
It is possible to add a rule after a previous rule, but have it appear ahead of the rule added earlier. This is done by using
iptables -I
to add the rule rather thaniptables -A
. Using the index of the rule you wish to bypass will keep the rules together in the chain. This approach may accomplish what you need to do if you are modifying a running set of rules. I would suggest ordering your rules so that they work with first match.I use Shorewall to build my rule sets and usually add my rules using the following order.
The built-in chains have a POLICY which can be ACCEPT, REJECT, or DROP. This applies if no rules match. User defined chains have an implict RETURN policy, which can be overridden by ending the chain with a rule with the desired action that matches all packets.
iptables operates on a first match basis I don't believe there is any way to change this. How you setup your rules depends on if you want to be inclusive or exclusive by default.
For example if you run a webserver that you want everyone to get to except for anyone on the 150.0.0.0/8 class you would setup your rules to be inclusive by default.
If you want to setup your server to be exclusive you would need to set it up like so.
And I think my rule examples should answer your question in regards to the DROP. If you add a -j DROP on the rule it will drop that match.