Agnus Dei (jackal) wrote,
Agnus Dei
jackal

How to do Geo Blocking of China using IPTables and IPSet

1- First you'll want to have a directory to do your geo-blocking in. I put mine in /etc/geo-blocking:
[geo-blocking]# mkdir /etc/geo-blocking
[geo-blocking]# cd /etc/geo-blocking



2- From there I created a script to do this:
[geo-blocking]# more geo-block-china.sh 
#!/bin/bash

GEODIR="/etc/geo-blocking"
COUNTRYZONE="cn.zone"
COUNTRYNAME="china"

# Create the ipset list
ipset -N $COUNTRYNAME hash:net


# remove any old list that might exist from previous runs of this script
rm -f $GEODIR/$COUNTRYZONE

# Flush the set name already in memory
ipset flush $COUNTRYNAME

# Pull the latest IP set for China
wget -P $GEODIR http://www.ipdeny.com/ipblocks/data/countries/$COUNTRYZONE

# Add each IP address from the downloaded list into the ipset 'china'
for i in $(cat $GEODIR/$COUNTRYZONE ); do ipset -A $COUNTRYNAME $i; done

# Restore iptables
/sbin/iptables-restore < /etc/sysconfig/iptables




3- Next you'll want to add some rules to iptables to actually log and block the IP's:
[geo-blocking]# grep china /etc/sysconfig/iptables
-A INPUT -m set --match-set china src -j LOG --log-prefix "iptables: DROP China" --log-level 6
-A INPUT -m set --match-set china src -j DROP




4- And last you'll want to put something in your rsyslog.conf to capture the logs:
[geo-blocking]# cat /etc/rsyslog.d/10-iptables.conf 
:msg, contains, "iptables:" -/var/log/iptables.log
:msg, contains, "iptables:" ~



5- Add something for log rotation:
[geo-blocking]# cat /etc/logrotate.d/iptables
/var/log/iptables.log {
    daily
}



6- Now restart rsyslog
[geo-blocking]# /etc/init.d/rsyslogd restart



7- And then run your new script for blocking china:
[geo-blocking]# chmod +x /etc/geo-blocking/geo-block-china.sh
[geo-blocking]# /etc/geo-blocking/geo-block-china.sh
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 1 comment