Shorewall: setup Geo-IP filtering

6 April 2016

shorewall - iptables made easy

Sometimes it is neccessary to filter packets based on their geo-ip location. Shorewall can make use of the xt_geoip-module for iptables. In this article I will explain how to setup this module on Debian.

Installing the module

First of all we have to install the xt_geoip-module which is a part of the xtables-addons-common-package:

apt-get update && apt-get install xtables-addons-common

Building the GeoIp-Database

Now we need some more packages for the geoip-building-scripts:

apt-get install unzip libtext-csv-xs-perl

xtables-addons-common ships two scripts located in /usr/lib/xtables-addons:

  • xt_geoip_dl for downloading the database
  • xt_geoip_build for building the database

So let’s create and change in our temporary working-directory:

mkdir /var/tmp/geoip
cd /var/tmp/geoip

In our working-directory we will first download the csv-files:

ls -la
drwxr-xr-x 2 root root 4,0K Apr 6 08:21 .
drwxrwxrwt 4 root root 4,0K Apr 6 08:21 ..
-rw-r--r-- 1 root root 1,8M Apr 5 15:28
-rw-r--r-- 1 root root 8,5M Apr 5 08:27 GeoIPCountryWhois.csv
-rw-r--r-- 1 root root 4,2M Apr 5 15:28 GeoIPv6.csv

Iptables and shorewall will look for the database in /usr/share/xt_geoip. So we have to create this directory first:

mkdir /usr/share/xt_geoip

Finally we can build the database:

/usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip *.csv
ls -l /usr/share/xt_geoip/
drwxr-xr-x 2 root root 12K Mär 26 22:50 BE
drwxr-xr-x 2 root root 12K Mär 26 22:50 LE

Using xt_geoip

Let’s load the kernel-module and make sure that it will be loaded automatically when the system boots:

modprobe xt_geoip
echo xt_geoip >> /etc/modules

Using the module in shorewall is very simple. Let’s say we are using portforwarding for our HTTP-server and we want to block connections from USA and Russia. In that case we just have to edit /etc/shorewall:

HTTP(REJECT):info inet:^[RU,US] lan:$WEBSERVER
DNAT inet lan:$WEBSERVER tcp www

It’s important that we block before the rule for portforwarding becauses DNAT also creates an ACCEPT-rule.

Automate Geoip-Updates

We just have to keep the database on our system up2date. Therefore I wrote this little script:



# chmod this script with 700


test -d $GEOIPDIR || mkdir -p $GEOIPDIR

TMPDIR=`mktemp -d -p /tmp`


/usr/lib/xtables-addons/xt_geoip_build -D $GEOIPDIR *.csv

rm -r $TMPDIR

Now we can easily create a cronjob which runs this script daily:

@daily /usr/local/sbin/ > /dev/null

That’s it! Have fun.

[ Linux  Sysadmin  Security  Network  Firewall  Toscom  ]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 Unported License.

Copyright 2015-present Hoti