Blacklisting range of IPs using iptables: the quick and dirty way

Let’s suppose you have a list with IPs you want to block on your router, for example from http://www.ipdeny.com/ipblocks/data/countries/:

1.0.1.0/24
1.0.2.0/23
1.0.8.0/21
1.0.32.0/19

You can easily convert each line to an iptables command using regular expressions. On a Windows machine you can use Notepad++ for this purpose. Select Search > Replace, tick the regular expression checkbox as seen on this screenshot:

notepadpp_regex

Fill in the fields as below:

Find what: ^(.*)$
Replace with: iptables -I FORWARD -s \1 -j logdrop

After pressing Replace All, you get

iptables -I FORWARD -s 1.0.1.0/24 -j logdrop
iptables -I FORWARD -s 1.0.2.0/23 -j logdrop
iptables -I FORWARD -s 1.0.8.0/21 -j logdrop
iptables -I FORWARD -s 1.0.32.0/19 -j logdrop

As you can see, it will add a logdrop rule in the forward chain for each IP entry. In case you want to drop the packages not on your router, but on your end-point machine, change FORWARD to INPUT. Also, you can simply use drop instead of logdrop. Watch out for the last line of your text file! It must not be empty, otherwise you end up with having “iptables -I FORWARD -s -j logdrop” there. Having the commands ready, you can just copy&paste into the command line, or save it as a bash file.

Alternatively, on a Linux machine you can do all the above in the command line

wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone

To check the number of lines, you can use

wc -l cn.zone

Right now I get 4956 lines.

Run the following script to get another runnable script with all the iptables commands, as above (ip_to_script.sh):

#!/bin/ash
echo 'Generating iptables commands'
rm add_rules.sh
echo "#!/bin/ash" << add_rules.sh
while read ip; do
echo "iptables -I FORWARD -s ${ip} -j logdrop" << add_rules.sh
done <$1
chmod +x add_rules.sh

Usage example: ./ip_to_script.sh cn.zone, then ./add_rules.sh!

Have fun!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s