How to Block IP address of any country with iptables

Sometime it is necessary to block incoming connection or traffic from specific remote host. iptables is administration tool for IPv4 packet filtering and NAT under Linux kernel. Following tip will help you to block attacker or spammers IP address.

 The blocklist is create with an API I wrote and you can use wget to update the blocklist monthly.

The API to get the IP addresses to block

First you need to know the code (ISO 3166 format) of the country you would like to block. The full list is available here

Once you have the country code, you can now get the list at the following url (Afghanistan and Argentina in this example). If your browser show the data on a single line, simply view the page source code :

http://blogama.org/country_query.php?country=AF,AR

How often is data updated

During the first week of each month. Last update was on Feb11 2009.

How accurate is the data?

This is a somehow complex grouping of IP by country and CIDR of our database. While I cant guarantee the accuracy, the data is from a reliable source. If you want, try a few “tracert 123.123.123.0″ to verify the accuracy.

Automatic bash script to block those IP addresses in iptables

The following script will 1)Fetch the right IP addresses of the country you would like to block from our API and 2)Add these rules in iptables.

 

#!/bin/bash
###BLOGAMA.ORG###
 
###PUT HERE COMA SEPARATED LIST OF COUNTRY CODE###
COUNTRIES="AK,AR"
WORKDIR="/root"
#######################################
 
cd $WORKDIR
wget -c --output-document=iptables-blocklist.txt http://blogama.org/country_query.php?country=$COUNTRIES
if [ -f iptables-blocklist.txt ]; then
  iptables -F
  BLOCKDB="iptables-blocklist.txt"
  IPS=$(grep -Ev "^#" $BLOCKDB)
  for i in $IPS
  do
    iptables -A INPUT -s $i -j DROP
    iptables -A OUTPUT -d $i -j DROP
  done
fi
rm -f $WORKDIR/iptables-blocklist.txt

 

If you add this script to a crontab, I suggest doing so around the 15th of each month.

The full SQL database

For the full SQL database of this data, please read this page



Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>