Activities

October 2014
M T W T F S S
« Sep   Nov »
 12345
6789101112
13141516171819
20212223242526
2728293031  

IPTables : How do I block access from a country

Recently one of the server was attempted to hack from various countries especially from Ukranine, France and China even though all our customers are located in US. So we do not need to open the web access to any of these countries as they are not belonging to our customer region.

After a few Google search I found that cybercity.biz size has already implemented such mechanism using a sript. Here I’ve modified those script and customize it for my purpose. I do not need to create separate chain and I just want to block the country access towards the default INPUT chain.

You can browse the IP database from here http://www.ipdeny.com/ipblocks/data/countries

If you want to know the country code use this link http://countrycode.org/

What this script does is,

1. ipdeny.com sites provides the database of the network belonging to each country as a text
2. This script download those files and parse the ip and added it in to IPTABLES..

Here is the script,

You can download the script from here

#!/bin/bash

# Zone record of the region
ISO="af cn"
 
### Set PATH ###
IPT="$(which iptables)"
WGET="$(which wget)"
EGREP="$(which egrep)"

#Stroting Blacklist files
ZONEROOT="/root/iptables"
rm -rf $ZONEROOT/*
DLROOT="http://www.ipdeny.com/ipblocks/data/countries"

#flushing iptables
$IPT -F
 
# create a dir if it is not
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT
 

for c  in $ISO
do
    # local zone file
    tDB=$ZONEROOT/$c.zone
 
    # get fresh zone file
    $WGET -O $tDB $DLROOT/$c.zone
 
    # get
    BADIPS=$(egrep -v "^#|^$" $tDB)
    for ipblock in $BADIPS
    do
        $IPT -I INPUT -s $ipblock -j DROP
    done
        # Delete the loaded file,
        rm $tDB

done

exit 0

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>