Etikettarkiv: fedora

More effective CIDR-blocking

Previously we have talked about how to block certain addresses using the firewall in Linux (iptables) but if you have a large number of CIDR blocks, say whole countries like China (about 7000 blocks) this will not be keen on the CPU in the server.

Especially the script that inserts it by repeatedly calling iptables. The first few hundred calls will be quit but then is slows down as the kernel won’t process so many insertions in the iptables lists.

There is another way that is just as effective called blackholing the ip ranges you wish to block from your server. This is done by adding routes for those packest that leads nowhere.

# ip route add blackhole <ip address>

This works quite beautifully with tens of thousands of addresses of course. As before we should read the CIDR files we want in order to create the null routes that is needed.

Here is a script that will read a directory of CIDR files and null route all of them.

for f in /etc/iptables/hosts-banned/*
do
    LINES=$(wc -l $f | awk '{print $1}')
    echo -n "Processing k-line file $f with $LINES blocks... "
    date +"%H:%M:%S"
    while read p
    do
        ip route add blackhole $p
    done < $f
done

The CIDR files in this case resides in /etc/iptables/hosts-banned/ an they can be gotten from online or you may add any address ranges you want, perhaps based on automatic firewalling.

To remove a certain blacholed range or ip you can do the same thing again changin the ip route add to an ip route del command instead.

ip route del <ip address>

You can produce a script that removes them by doing the following:

ip route | grep blackhoe | awk '{ print "ip route del " $2 }' >unblock
chmod 700 unblock
./unblock

That’s it, they are all now cleared.