This guide demonstrates how to install and compile MaxMind GeoLite2 Database for geographic-based traffic filtering using UFW on Debian 12.
1. Install required packages
sudo apt install ufw xtables-addons-common geoip-bin libtext-csv-perl libtext-csv-xs-perl libmoosex-types-netaddr-ip-perl pkg-config
2. Download MaxMind GeoLite2 Database
Signup MaxMind account at MaxMind at https://www.maxmind.com/ en/geolite2/signup
Generate license key at https://www.maxmind.com/ en/accounts/current/license-key
sudo mkdir -p /usr/share/xt_geoip/
cd /usr/share/xt_geoip/
sudo wget --content-disposition --user=[YOUR ACCOUNT ID] --password=[YOUR LICENSE KEY] 'https://download.maxmind.com/geoip/databases/GeoLite2-Country-CSV/download?suffix=zip'
ls
GeoLite2-Country-CSV_20241231.zip
3. Build GeoLite2 database
sudo unzip GeoLite2-Country-CSV_20241231.zip
cd GeoLite2-Country-CSV_20241231
ls
sudo /usr/libexec/xtables-addons/xt_geoip_build_maxmind -D /usr/share/xt_geoip *.csv
Check building result
/usr/share/xt_geoip$ ls
A1.iv4 AU.iv6 BN.iv4 CG.iv6 ......
sudo rm -rf GeoLite2-Country-CSV*
4. Verify Geoip lookup
geoiplookup 151.101.67.5
GeoIP Country Edition: US, United States
5. Load xt_geoip module
echo "xt_geoip" | sudo tee -a /etc/modules
sudo modprobe xt_geoip
lsmod | grep xt_geoip
xt_geoip 16384 0
x_tables 53248 13 xt_conntrack,nft_compat,xt_LOG,xt_tcpudp,xt_addrtype,ip6t_rt,xt_geoip,ip6_tables,ipt_REJECT,ip_tables,xt_limit,xt_hl,ip6t_REJECT
6. Configure UFW to use Geoip with GeoLite2 Database
Add customized rules to UFW configuration file (/etc/ufw/before.rules).
Examples:
Allow access to the server on port 443 from the US
sudo nano /etc/ufw/before.rules
-A ufw-before-input -p tcp --dport 443 -m geoip --src-cc UK -j ACCEPT
Deny access to the server on port 443 from the UK.
-A ufw-before-input -p tcp --dport 3000 -m geoip --src-cc UK -j DROP
Blocking or allowing during certain hours
-A ufw-before-input -p tcp --dport 443 -m time --timestart 08:00 --timestop 18:00 -m geoip --src-cc UK,US -j ACCEPT
Insert the rules at the end of the file, before the 'COMMIT' line.
Applies Changes
sudo ufw reload
Conclusion
This tutorial has demonstrated the process of integrating MaxMind GeoLite2 Database with UFW on Debian 12. By leveraging GeoIP for traffic filtering, you enhance your server's security by implementing location-based access control. This can significantly improve your server's security posture.
Comments1
Thank you for your post. …
Thank you for your post.
got error with modprobe with xt_geoip, please help,
Modprobe: FATAL: Module ip_tables not found in directory /lib/modules/