Feb 20, 2012

Block a Country to View your Website Using IPTables

If you are the owner of a website and you see a lot of unwanted and unprofitably traffic coming from some countries and you want to block those countries from accessing your website then you can use script given below.




There are two ways to block countries:

First is to configure your Apache server and
Second is to set iptables commands (Easy).

First of all download the list of IP zone files of the country which you want to block from http://www.ipdeny.com/ipblocks/
The script will not work if people of that country are using any proxy server or they have spoofed their IP address.
#!/bin/bash
### Block all traffic from AFGHANISTAN (af)
PAKISTAN (PK) and CHINA (CN). Use ISO code ###
ISO="af pk cn"

### Set PATH ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep

### No editing below ###
SPAMLIST="countrydrop"
ZONEROOT="/root/iptables"
DLROOT="http://www.ipdeny.com/ipblocks/data/countries"

cleanOldRules(){
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t mangle -F
$IPT -t mangle -X
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
}

# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT

# clean old rules
cleanOldRules

# create a new iptables list
$IPT -N $SPAMLIST

for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone

# get fresh zone file
$WGET -O $tDB $DLROOT/$c.zone

# country specific log message
SPAMDROPMSG="$c Country Drop"

# get
BADIPS=$(egrep -v "^#|^$" $tDB)
for ipblock in $BADIPS
do
$IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
$IPT -A $SPAMLIST -s $ipblock -j DROP
done
done

# Drop everything
$IPT -I INPUT -j $SPAMLIST
$IPT -I OUTPUT -j $SPAMLIST
$IPT -I FORWARD -j $SPAMLIST

# call your other iptable script
# /path/to/other/iptables.sh

exit 0
You must be logged in as a ‘root’ user to run this script. Mention the country names which you want to block in ‘ISO’.

To run the script 
# /path/block_country.sh
You can add this script to crontab so that it will run automatically.


@weekly /path/block_country.sh
Below is an another script which does the same work: 
#!/bin/bash
###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 $WORKDIR/iptables-blocklist.txt

0 comments:

Blog Archive

Total Pageviews

EARNING PRO

Never Miss Any Update From Us!

Enrich Your Inbox.[402+ Readers]


Enter your email address:

Delivered by FeedBurner | Powered By MBT


Subscribe us today and get Quality Articles for free.