This guide demonstrates how to implement geographic-based traffic filtering using UFW on Debian 12. We'll explore how to leverage GeoIP databases to block or allow access requests from specific countries, enhancing your server's security posture.
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 database
sudo mkdir -p /usr/share/xt_geoip/
cd /usr/share/xt_geoip/
sudo /usr/libexec/xtables-addons/xt_geoip_dl
ls
dbip-country-lite.csv
3. Build Geoip database
sudo /usr/libexec/xtables-addons/xt_geoip_build ./
ls
AD.iv4 BA.iv4 BT.iv4 CO.iv4 ......
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 for Geo Blocking
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 GeoIP 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 reduce the risk of malicious attacks originating from specific regions.
Comments