Here is a pretty fancy “trick” for the ones who wants to block certain parts of the world from accessing your VPS.
first of all you need to know the netblocks for the country you want to block, this information can be found at this page, each country has their own file in CIDR format.
Then we can add those netblocks to IPTABLES and “problem solved”.
Save below script as root user to “country.block.iptables.sh” and change the ISO variable to match the country name using ISO country codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
#!/bin/bash ### Block all traffic from AFGHANISTAN (af) and CHINA (CN). Use ISO code ### 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 |
When you are done, make sure it updates atleast weekly so it inludes recently added IP, this will be done by adding the following as a cron job.
first execute:
1 2 3 |
crontab -e |
add:
1 2 3 |
@weekly /path/to/country.block.iptables.sh |
close and save.
To start blocking immediately type:
1 2 3 |
# /path/to/country.block.iptables.sh |
12 comments for “Block an entire Country with iptables”