For the complete documentation index, see llms.txt. This page is also available as Markdown.

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
Command
for i in `curl http://www.ipdeny.com/ipblocks/data/countries/cn.zone | awk {'print $1'}` ; do nft add rule inet filter input ip saddr $i reject ; done

And for IPv6 addresses, the command would look like this:

Command
for i in `curl http://www.ipdeny.com/ipv6/ipaddresses/aggregated/cn-aggregated.zone | awk {'print $1'}` ; do nft add rule inet filter input ip6 saddr $i reject ; done

Note that UFW isn't as fast as nftables or iptables, so it can take quite some time to block a long list of IP addresses.

Command
for i in `curl http://www.ipdeny.com/ipblocks/data/countries/cn.zone | awk {'print $1'}` ; do ufw deny from $i to any ; done

And for IPv6 addresses, the command will be:

for i in `curl http://www.ipdeny.com/ipv6/ipaddresses/aggregated/cn-aggregated.zone | awk {'print $1'}` ; do ufw deny from $i to any ; done

For more information about the different firewall tools, see:

Last updated

Was this helpful?