Block entire countries on Ubuntu server with Xtables and GeoIP

Anyone who has administered even a moderately high traffic server will have noticed that certain unwelcome traffic such as port scans and probes tend to come from IP addresses belonging to a certain group of countries. If your application or service does not cater to users in these countries, it might be a safe bet to block these countries off entirely.

This is especially true for email servers. The average email server, based on anecdotal evidence of servers for around 20 domains, rejects about 30% of incoming email every day as spam. Some servers on some days reject up to as much as 97% of incoming email as spam. Most of these originate in a certain subset of countries. That is a lot of wasted CPU cycles being expended on scanning these undesired emails for spam and viruses. Although tools such as amavisd and spamassasin do a good job of keeping the vast majority of spam out of users’ inboxes, when the rare well crafted and targeted phishing email does get through, it wrecks havoc in the enterprise.

Fortunately, there are a number of packages available in the repositories that can be used to block traffic from entire countries. My favorite among the lot is the xtables-addons-commonpackage coupled with the xt_geoip database, because these are extensions to iptables which is already present in every Linux kernel. Installing the package on Ubuntu is as simple as running a few Aptitude commands:

sudo apt-get install xtables-addons-common

This will grab the sources, build and install xtables and all its dependencies, including the xtables-addons-common and xtables-addons-dkms packages.

The next step is to download the GeoIP list as a CSV. Create and navigate to a temporary folder, say /tmp/geoip, then run the following command:

sudo /usr/lib/xtables-addons/xt_geoip_dl

This will download two CSV files, one containing the GeoIP list for IPv4 and one for IPv6. You may have to unzip them if they have been packaged as an archive.

The final step is to import this list into xtables, so it can be used by iptables. This process requires the libtext-csv-xs-perl module to digest the CSV files into the proper format.

sudo aptitude install libtext-csv-xs-perl

Finally, create a folder to stash the converted files in, and import them into xtables:

And that’s all there is to it! To test that everything went well, run the following command:

iptables -m geoip --help

If the command executes successfully, xtables with geoip has been successfully installed into iptables. Now you can block any list of countries with a simple iptables command. To block Korea, China, India, Russia, Turkey, Vietnam, Ukraine, Brazil, Venezuela, Pakistan, Saudi Arabia, Japan, Germany and Italy for example, run: