How long does it take for an iptables rule to apply?
I use a script with the code below in an attempt to block hosts, but they don't appear to take immediately. Is there some delay, is iptables not working or is the code just plain wrong?
#!/bin/sh
echo $1 >> /etc/dropped_hosts
iptables -A INPUT -s $1 -j DROP
iptables -A OUTPUT -d $1 -j DROP
iptables
rules take effect immediately. Because your script is Appending (-A) to the INPUT and OUTPUT chains, your rules are being added to the end of those chains. If you have other terminating rules that precede these rules, then they will take effect (and later rules will not).For example, it is very common to have a
-m state --state ESTABLISHED,RELATED -j ACCEPT
rule early in INPUT/OUTPUT chains, and that rule will take effect in precedence to any rules that come after it. That rule allows established connections to continue, even if they are to/from IP addresses that you have added to your firewall via your script.If you do have an ESTABLISHED,RELATED rule in your INPUT/OUTPUT chains (or some other rule that is overriding later rules), then you'll either have to accept that your new rules many not take effect immediately, or you can have your script insert the IP-address DROP rules before the ESTABLISHED,RELATED rule. This can be accomplished by changing your script to Insert (-I) rather than Append (-A) your IP-address DROP rules, e.g.
iptables
rules take effect immediately.Since this script appends, there may be a rule before this that says to automatically allow the hosts you are trying to block. iptables reads rules top to bottom, and breaks as soon as it finds a match (so if you had something that said 'allow badhostx' and then next line was 'drop badhostx', it would never drop since the rule was already matched for that host.
If you're using the -A in a script you may want to flush your tables before (iptables --flush), to ensure that the rules are exactly as you apply them in the script ( but also make sure you have ALL the rules in that script).
Another option instead of running that script is to get the rules you want working, then do either "service iptables save" or "/etc/init.d/iptables save". Hope this helps.
You must add your rules at the beginning of filter table. So you must use -I (insert) instead of -A (append)