geobased IP blocking using iptables

IT admins working hard to block unwanted traffic coming from different countries which are not relevant to their business. This geobased IP blocking using iptables help you to fight against this type of situation. You can achieve this using by apache (using geo module) and iptables. It’s always best to block at Iptables itself because blocking at apache level consumes more system resources.

Here is a small shell script which performs this action.

vi ipblock.sh

#!/bin/bash
# Purpose: Block all traffic from AFGHANISTAN (af) and CHINA (CN). Use ISO code. #
# See url for more info – http://www.cyberciti.biz/faq/?p=3402
# Author: nixCraft <www.cyberciti.biz> under GPL v.2.0+
# ——————————————————————————-
ISO=”af 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

save and exit

ISO variable refers to country name. You can check a full list of the country from this link.
http://www.ipdeny.com/ipblocks/data/countries

Once done install the script as follows using crontab:
@weekly /path/to/ipblock.sh

To start blocking immediately type:
sh /path/to/ipblock.sh

And you are done with blocking the whole country from your server.

© 2018, Techrunnr. All rights reserved.

#1
#2
#3
Questions Answered
Articles Written
Overall Points

Prabhin Prabharkaran

He is Technical professional. He is a person who loves to share tricks and tips on the Internet. He Posts what he does!!

0 Comments

Leave a Reply

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.