This guide explains how to block traffic by country on Debian using iptables and GeoIP. First, install required packages and download a GeoLite2 country database. Then, compile the data for iptables to understand and load the GeoIP module. Finally, you can use iptables rules with GeoIP syntax to block traffic from specific countries, like Germany in the example.
Install required packages on Debian:
$ apt install xtables-addons-dkms
$ apt install libtext-csv-xs-perl libmoosex-types-netaddr-ip-perl pkg-config
Download GeoLite2-Country-CSV_YYYYMMDD.zip
from Maxmind.com
. You’d need a free account for that. Then compile the CSV files into a format xt_geoip
can understand using:
mkdir -p /usr/share/xt_geoip/
cd /usr/share/xt_geoip
wget <<Download Link from Maxmind>>
unzip GeoLite2-Country-CSV_20220125.zip
cd GeoLite2-Country-CSV_20220125
/usr/libexec/xtables-addons/xt_geoip_build_maxmind -D /usr/share/xt_geoip *.csv
Load the xt_geoip
module using modprobe xt_geoip
.
iptables should now be able to understand geoip syntax. For example, we can block all traffic from Germany using:
iptables -A INPUT -m geoip --src-cc DE -j DROP