Agnus Dei (jackal) wrote,
Agnus Dei
jackal

How to do Geo Blocking using IPTables and IPSet (take 2)

This is based on another script I found online which I like better:
http://www.control-alt-del.org/blog/2015/02/13/geo-blocking-with-iptables-slash-ipset/


[geo-blocking]# cat refresh-geoblock.sh
#!/bin/bash
COUNTRYLIST="bh br cn in it kh kr pe pk ru sg tw"
GEOBLOCKBASEDIR="/etc/geo-blocking"
if [ ! -d $GEOBLOCKBASEDIR ]; then
    mkdir $GEOBLOCKBASEDIR
fi
cd $GEOBLOCKBASEDIR
for i in $COUNTRYLIST; do
    echo  ----- creating ipset for country_$i
    # ipset destroy country_$i   # it can not do this while iptables is running.
    ipset flush country_$i       # flush it instead
    ipset -N country_$i hash:net
    wget -q -N http://www.ipdeny.com/ipblocks/data/countries/$i.zone
    for k in `cat $i.zone`; do
        ipset -A country_$i $k
    done
    # if you want to save it
    # rm -f /etc/sysconfig/ipset-geoblock_$i  
    # ipset save country_$i >/etc/sysconfig/ipset-geoblock_$i
done
# Reload iptables
if [ -e /etc/sysconfig/iptables ]; then
    iptables-restore < /etc/sysconfig/iptables
fi

And then the matching rules in iptables:
[geo-blocking]# cat setup-iptables.sh
#!/bin/bash
COUNTRYLIST="bh br cn in it kh kr pe pk ru sg tw"

# Save the current iptables just in case
iptables-save > /etc/sysconfig/iptables.bk.`date +%s%3N`
 
# Flush any current rules in memory
echo  Flushing current iptables rules
iptables -F

# Loop through the countries
for i in $COUNTRYLIST; do
    echo  ----- creating iptables rules for country_$i
    iptables -A INPUT -m set --match-set country_$i src -j LOG --log-prefix "iptables: DROP domain=$i: " --log-level 6
    iptables -A INPUT -m set --match-set country_$i src -j DROP
done

# Save iptables
iptables-save > /etc/sysconfig/iptables





For the rest of the setup see this blog entry:
http://jackal.livejournal.com/2195719.html
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 0 comments