Linux Iptables Just Block By Country

Blocking traffic from specific countries using iptables can be challenging as IP addresses are not directly tied to a specific country. However, there are several services and databases that provide geo-location information about IP addresses.

One way to block traffic from specific countries using iptables is to use the xt_geoip module, which allows you to match traffic based on the country of origin. Here’s how to set it up:

  1. Install the xt_geoip module and the GeoIP database:
    sudo apt-get install xtables-addons-common xtables-addons-dkms geoip-database
  2. Load the xt_geoip kernel module:
    sudo modprobe xt_geoip
  3. Create a new chain in the iptables filter table:
    sudo iptables -N GEOIP
  4. Add a rule to the GEOIP chain that matches traffic based on the country of origin. For example, to block traffic from China:
    sudo iptables -A GEOIP -m geoip --src-cc CN -j DROP
  5. Add a rule to your INPUT chain that jumps to the GEOIP chain:
    sudo iptables -A INPUT -j GEOIP
  6. Save your iptables configuration so it will be applied on next boot:
    sudo iptables-save > /etc/iptables/rules.v4

Note that using the xt_geoip module requires updating the GeoIP database on a regular basis to ensure accuracy. You can update the database by running the following command:

sudo geoipupdate

This will download the latest version of the GeoIP database and install it on your system.

Leave a Comment