How to use GeoLite2 database (mmdb) in my firewalld to block all countries except for example DE?
-
1before answering your question, it would be helpful to know which service you are trying to protect. Trying to block an entire country's allocated ip range is a resource consuming task. There are many less extreme measures you should try first. For example, if you are having trouble with ssh connections, try changing the default port or if it's apache being hit, try using modsec rules. – rcjohnson Feb 25 '19 at 19:52
2 Answers
You could get German IP addresses from RIPE (the European registry), and create an ipset with them. Then it is easy and efficient to use the ipset in iptables.
RIPE has an API and web resources to get IP addresses by country. For example, to get German IPs, this URL will list them in .json format:
https://stat.ripe.net/data/country-resource-list/data.json?v4_format=prefix&resource=de
I actually have a script (https://github.com/mivk/ip-country/blob/master/get-ripe-ips) which I call from crontab to update a list of IPs. And use that list to update an ipset.
Once you have the ipset, if you called it ipv4_de, the line in iptables would be like
-A INPUT -m set ! --match-set ipv4_de src -j DROP
That would drop any IP not in the ipv4_de set.
- 411,918
- 54
- 1,065
- 1,164
- 3,446
- 29
- 31
iptables have geoip module, which isn't included by a default in Linux.
You can install xtables addons:
apt-get install xtables-addons-common xtables-addons-dkms
- Get MaxMinds geoip database (note that those can be outdated if using free ones)
wget -O geolite2-csv.zip https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country-CSV.zip ; unzip geolite2-csv.zip
- Download gcsv2bin which will convert
csvdatabase to a binary, which can be used for lookups.
wget -O - http://people.netfilter.org/acidfu/geoip/tools/gcsv2bin.tar.gz | tar xzf -
make
- Convert actual db:
./gcsv2bin path_to_IPv4.csv
- Load
xt_geoipmodule:
sudo modprobe xt_geoip
- iptables rule:
sudo iptables -A INPUT -m geoip --src-cc DE -j DROP
Where, argument for --src-cc is CountryCode.
- 1,543
- 19
- 33