GeoIP restriction in Linux with xtables

From SolaceWiki
Revision as of 12:49, 25 January 2025 by Kc (talk | contribs) (Created page with "''<big>Original blog post: https://www.phreakmonkey.com/2022/01/howto-geoip-restrictions-for-amazon.html</big>'' == Background == I originally wrote about the process (above) for doing IPv4 GeoIP restriction to a host / service using [https://xtables-addons.sourceforge.net/ xtables-addons] and [https://www.maxmind.com/en/geoip-databases Maxmind's GeoIP database] with Amazon Linux 2. This approach worked but had the huge drawback of needing to update, compile, and insta...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Original blog post: https://www.phreakmonkey.com/2022/01/howto-geoip-restrictions-for-amazon.html

Background

I originally wrote about the process (above) for doing IPv4 GeoIP restriction to a host / service using xtables-addons and Maxmind's GeoIP database with Amazon Linux 2. This approach worked but had the huge drawback of needing to update, compile, and install xtables-addons manually every time there was a kernel update, which was easy to overlook - thereby leaving you suddenly with no GeoIP restrictions.


Whether GeoIP restrictions are worth it at all is a subject of debate. By and large I've abandoned the approach, as they're super easy to circumvent for a dedicated attacker anyway, and how much value to you really get by limiting opportunistic attackers via geofencing?


That said, here's an amended, easier way to do GeoIP IPv4 with Debian:

Basic steps

  • apt get xtables-addons-common
  • apt get cpan
    • cpan install
    • cpan Text::CSV Text::CSV_XS Net::CIDR::Lite
  • Download a Maxmind GeoLite2-Country-CSV database and extract it
  • mkdir /usr/share/xt_geoip
  • from the extracted GeoLite2 database directory, run /usr/libexec/xtables-addons/xt_geoip_build_maxmind -s to install the database where the kernel module can find it.


If all goes well, now you're all set-up. You can now use the -m geoip directive in iptables rules. E.g.

# iptables -A INPUT -p tcp --dport 443 -m geoip ! --source-country US -j DROP

will drop all TCP port 443 packets that originate from outside the United States.

Warnings

  • Localhost (127.0.0.0/8) is outside any known geography. Allow it before your GeoIP blocking rules
  • Some remote services aren't GeoIP friendly. LetsEncrypt / Acme Certificate Verficiation, in particular, will fail to provision new certificates if you're GeoIP restricting port 80 & 443 traffic to just the US. At the time of this writing it will renew existing certificates with the GeoIP block in place, just not provision new ones.