Skip to main content

UFW - Block entire countries by IPs

If you don't want one explicit or even multiple countries, to connect to your server, you can block all their requests, by using UFW. This will, however, make your UFW status output extremely long, as well as taking some time to set up.

Doing this, is, of course, no guarantee, because it only blocks IPv4 and often enough, attackers mask/spoof their IP anyway. Moreover, this is quite a drastic step to take. You should rather control access on a different level, e.g. using a WAF.

First, you need to download a list of all the IPv4 Subnets, a country has assigned. You can download said list here and make sure to choose CIDR as output format. After that, simply run the following command (This may take a while)

cat yourList.txt | awk '/^[^#]/ { print $1 }' | sudo xargs -I {} ufw deny from {} to any

To remove all the rules, run

cat yourList.txt | awk '/^[^#]/ { print $1 }' | sudo xargs -I {} ufw delete deny from {}