Tag Archives: iptables

iptables: Block traffic by country (Debian 9)

  • Install iptables module "geoip":
sudo aptitude install xtables-addons-common
  • Download and build geoip database (zipped CSV file from MaxMind):
sudo -i
mkdir /usr/share/xt_geoip/ 
cd /usr/share/xt_geoip/
/usr/lib/xtables-addons/xt_geoip_dl
/usr/lib/xtables-addons/xt_geoip_build GeoIPCountryWhois.csv

Check your iptables rules in INPUT chain. It should look something like this, if you already setup iptables:

# iptables --line-numbers -nL  INPUT

Chain INPUT (policy DROP) 
num  target     prot opt source               destination          
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
2    ACCEPT     ...
3    ACCEPT     ...
...
8    LOG        all  --  0.0.0.0/0            0.0.0.0/0            state INVALID,NEW LOG flags 0 level 4 prefix "DROP input:"
  • Add iptables rule to block all incoming traffic from e.g. Prague/Czech Republic. Make sure to insert the new rule after the RELATED/ESTABLISHED rule and before any other ACCEPT rules. In this example, the rule is inserted as line number 2.
iptables -I INPUT 2 -m geoip --src-cc CZ -j DROP
  • In the second example we block all traffic except the one that is originating from the United States. TCP traffic is not simply dropped, but spoofed by the DELUDE target.
iptables -I INPUT 2 -m geoip ! --src-cc US -j DROP
iptables -I INPUT 2 -p tcp -m geoip ! --src-cc US -j DELUDE

Important things to note:

  • You have to reinstall package "xtables-addons-common" with every new kernel version because it is compiled during package installation using the current kernel source (see /usr/src/xtables-addons-*).
  • For more information about the DELUDE target in the second example, see "man xtables-addons". It spoofs nmap scans and makes it harder for port scanners to scan the destination host. It is only valid for TCP traffic.
Share