Iptables :: priority of rules

John DeDourek dedourek at unb.ca
Fri Feb 23 12:44:28 UTC 2007


Luc MAIGNAN wrote:
> Hi all,
> 
> I don't understand how the priority of the rules of iptables is set.
> 
> My problem : I want to allow ssh from my local network(1), and from 
> outside only for an IP(2)
> 
> So i Wrote :
> 
> (1) : iptables -I INPUT -p tcp -s 192.168.0.0/24 --dport ssh -j ACCEPT
> (2) : iptables -I INPUT -p tcp -s ! x.x.x.x --dport ssh -j DROP
> 
> The result is that I can ssh only from the ousided IP, not from local 
> network. If I switch the two rules, the result is the same.
> 
> Can anyone help me to understand ?
> 
> BR
There is a list of rules in the kernel.  An arriving packet is
matched against the list IN THE ORDER OF THE LIST; the first
ACCEPT or DROP rule that matches will determine the fate of
the packet.

The "-I" option of iptables puts a rule at the BEGINNING of the
list; the "-A" option puts a rule at the end of the list.

Since you used "-I" in both of your iptables invocations,
the second rule gets inserted at the beginning of the list
ahead of the first rule, and therefore
you created a rule list with the rules in the order:

    match -s ! x.x.x.x  action DROP
    match -s 192.168.0.0/24  action ACCEPT

If a packet happens to match both of those rules, the first one
would take effect.

I suppose you could have changed the "-I" to "-A" to
put the rules in at the end of the list in the order

    match -s 192.168.0.0/24  action ACCEPT
    match -s ! x.x.x.x  action DROP

HOWEVER, you didn't say whether there were other rules in
the list already.  For example, the default Redhat firewall
would already have a rule in the INPUT list (I know, the
implementer calls the lists "chains") that matches all
packets, so your rules would then not be effective.

Your quickest fix is just to interchange the order of your
two iptables invocations and leave the "-I".  This would be

iptables -I INPUT -p tcp -s ! x.x.x.x --dport ssh -j DROP
iptables -I INPUT -p tcp -s 192.168.0.0/24 --dport ssh -j ACCEPT

This would first insert the x.x.x.x rule into the INPUT list,
and then insert the 192.168.0.0 into the INPUT rule ahead of
the x.x.x.x rule.  I know that is counter-intuitive, but that's
the way it actually works.




More information about the users mailing list