Block entire countries in the firewall

Using IP lists from ipdeny.com, you can block an entire country in the firewall.


Sometimes it’s very useful to block an entire country in the firewall, for example, if you notice that a DDoS attack mainly appears to originate from a country such as China.

In Linux, it is very easy to block an entire country. This is possible because http://ipdeny.com provides sufficiently good lists of which IP addresses belong to each region of the world. It’s worth noting that the lists are not 100 % accurate, so you may end up blocking more—or less—than you intended.

If you want to see which countries are available, you can check here for IPv4 and here for IPv6.

There are a few different firewall tools, depending on which Linux distribution (and version) you use. Here, we cover iptables, nftables, and UFW.

Command
for i in `curl http://www.ipdeny.com/ipblocks/data/countries/cn.zone |awk {'print $1'}` ; do iptables -I INPUT -s $i -j DROP ; done

The same loop for IPv6 would look like this:

Command
for i in `curl http://www.ipdeny.com/ipv6/ipaddresses/aggregated/cn-aggregated.zone |awk {'print $1'}` ; do ip6tables -I INPUT -s $i -j DROP ; done

For more information about the different firewall tools, see:

Last updated

Was this helpful?