Welcome to My Site

So I wanted to create a simple script which I could load onto all of my Linux webservers, from Ubuntu to CentOS. Here is the code I found to work relatively well:

#remove existing rule to purge old IP's, download IP's from ipdeny.com, load IP's into "geoblocks" ipset, re-add iptables rule and re-start fail2ban
#this is to get the "geoblocks" rule at the top of the list so that it can be deleted in the next line
service iptables restart
#delete the "geoblocks" rule from iptables
iptables -D INPUT 1
#purge the "geoblocks" ipset
ipset destroy geoblocks
#re-establish the "geoblocks" ipset
ipset create geoblocks hash:net
#remove old .zone files
rm *.zone
#set variables
iso="af kp kr cn cu ir iq in jp ru tw br ro it hu tr"
#root of ip list zone files
dlroot="http://www.ipdeny.com/ipblocks/data/countries"
#download the .zone files
for c in $iso; do wget $dlroot/$c.zone; done
#load all .zone files into one
cat *.zone > blocks.zone
#load list of IP's just created into the "geoblocks" ipset
for i in $(cat blocks.zone); do ipset add geoblocks $i; done
#re-establish iptables rule
iptables -I INPUT -m set --match-set geoblocks src -j DROP
service fail2ban restart

This script of course requres iptables and ipset to be installed and working properly. Add this script in a cron job set to update once a week, and you'll always have the latest list of country's IP's blocked at the firewall level.

Note that I restart iptables at the beginning to get the geoblocks rule at the top due to fail2ban placing rules above the one that I need to remove, then the rule is deleted so we can delete the geoblocks ipset, the ipset geoblocks is deleted to flush the old IP's, and then re-loaded from source (ipdeny.com). At the end, fail2ban is restarted to re-establish all the iptables rules that it creates.

This should also work on any Linux based firewall gateway appliance. NetArmor

Published in Blog
Back to top