Agnus Dei (jackal) wrote,
Agnus Dei

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 


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

# remove any old list that might exist from previous runs of this script

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

# Pull the latest IP set for China

# 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 {

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-blocking]# /etc/geo-blocking/
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 1 comment