How many instructions can be stuffed into iptables without loosing system sanity?
Say one wishes to have a list of blocked IP addresses.
I have seen the following example script:
BLOCKDB="/path/to/ip.blocked.file"
# omit comments lines
IPS=$(grep -Ev "^#" $BLOCKDB)
for i in $IPS
do
iptables -A INPUT -s $i -j DROP
iptables -A OUTPUT -d $i -j DROP
done
Is several thousand lines, which transform into several thousand iptables entries, sane?
What is the top limit, beyond which, system efficiency will gets significantly affected?
I think I have found a solution via this article and IPSet seems to be the answer
In sum:
If set of IP addresses contain thousands of items iptables performance decreases (actually, performance of netfilter, as soon as iptables is just a tool for managing firewall). Your CPU load can increase too. Fortunately there is a perfect solution – ipsets
IPSet is the perfect tool if you want to:
- Store multiple IP addresses or port numbers and match against the collection by iptables at one swoop;
- Dynamically update iptables rules against IP addresses or ports without performance penalty;
- Express complex IP address and ports based rulesets with one single iptables rule and benefit from the speed of IP sets
Installing ipset is straight forward sudo apt-get install ipset
Then run the following
ipset -N autoban iphash ––hashsize 4096 ––probes 2 ––resize 50
Add it to your iptables chain. It can differ depending on your firewall settings. Here we use ethin chain.
iptables -I ethin 2 -p tcp -m multiport ––dport 80,443 -m set ––match-set autoban src -j DROP
Now you can add all bad IP to your ipset. For instance, you have text file called bots.txt with one IP per line. So you can add them to ipset using simple bash script:
for i in $( cat /tmp/bots.txt ) ; do ipset -A autoban $i ; done
To check run:
ipset -L autoban