[CentOS] CentOS 6.X, iptables 1.47 and GeoLite2 Country Database

Tue Jan 15 07:43:02 UTC 2019
Phil Perry <pperry at elrepo.org>

On 15/01/2019 01:29, Jobst Schmalenbach wrote:
> On Mon, Jan 14, 2019 at 07:29:45AM +0000, Phil Perry (pperry at elrepo.org) wrote:
>> On 14/01/2019 07:09, Jobst Schmalenbach wrote:
>>> Hi
>> I use ipdeny's aggregated country lists to do the same thing:
>> http://www.ipdeny.com/ipblocks/data/aggregated/
>> I just feed this data directly into ipset/iptables via a script running on
>> my firewall (not a C6 box). ipset is a really efficient way of doing this.
> Do you create a separate table, then feed every IP address (via ipset) into this chain?
> Would you mind sharing this script?
> thx
> Jobst

Below is my script for creating/updating an ipset to block my top 10 
undesirable/abusive countries. It runs as a cron job up startup to 
initially populate it and again every X hours to update it on my 
EdgeRouter firewall device.

It can be relatively slow process creating very large sets, so we create 
a temp set and then swap the contents of the live set with the temp set 
and finally delete the temp set. This is a more efficient way of 
updating an existing set.

Once the ipset has been created, you can create rules in iptables to 
match against that set using -m set --match-set SETNAME.

Hope that helps

-- Phil

CountryList="cn ru ua kp kr br ro tr vn in"
if [ -e /tmp/countries.txt ]; then
	rm /tmp/countries.txt

for country in $CountryList; do
	curl -o /tmp/$country.txt 
	cat /tmp/$country.txt >> /tmp/countries.txt

getnetblocks() {
cat <<EOF
# Generated by ipset
-N geotmp nethash --hashsize 1024 --probes 4 --resize 20
cat /tmp/countries.txt|egrep '^[0-9]'|egrep '/' |sed -e "s/^/-A geotmp /"
getnetblocks > /tmp/cnblock.txt
sudo ipset -! -R < /tmp/cnblock.txt
sudo ipset -W geotmp COUNTRIES-BLOCK
sudo ipset -X geotmp

rm /tmp/cnblock.txt