iptables block by country

Many a time it has been mentioned in my world how much easier it would be if you could block access by country. Given the fact that iptables starts to lose its sh1t when it has more than 200 lines in a table, the concept of knowing where an AS was in the world … I had kinda written off as “the wrong tool for the job“.

Now – currently I am assuming that this does not scale very well in terms of throughput, although may add to a few chains and see what falls off next week – however, it would appear that through the use of the packages geoip and xtables installed from apt and scripting a call from those – it becomes pretty easy to block by country, or grant by country using iptables. Who knew right?

iptables update
apt install xtables-addons-common libtext-csv-xs-perl

Then create a file to update this periodically….

/usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip *.csv

… which when run will neatly download the latest set of AS and then process those into country codes for you – yay.

So we want to check that everything is good to go:

 iptables -m geoip --help

If that comes back with a help document – you can have a quick peruse – however – it is pretty much as you would expect. Here is an example:

/sbin/iptables -A INPUT -m state --state NEW -m geoip --src-cc \
/sbin/iptables -A INPUT -m state --state NEW -m geoip --src-cc \

… there is a limit on the amount you can have in a single line – however, there is nothing to stop you layering these up (short of time it takes to process the rules)… so you can continue on with a list of your usual winners with the likes of LV,RO,CO,BY … oh, and what is this – wait one – the very cherry on top of this – A1, A2 – known proxy exit points.

You may thank me later.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

%d bloggers like this:
Skip to toolbar