Say for instance you wish to block IP ranges by region such as blocking China. This is easy to do with one spiffy website and ufw in Ubuntu or other Linux distros. I’ll show you how!
1. First, get a list of IP address of a region you wish to block. One website that provides this is:
Select iptables, China (or whichever country), CIDR format, and Download.
The list will look something like the following, with ranges in CIDR format one on a line. Save as say, cdir-china.txt. I would also recommend testing this list out in a non-prod environment first! These are generally accurate lists but be very careful and use with caution.
... 126.96.36.199/12 188.8.131.52/15 184.108.40.206/22 220.127.116.11/10 18.104.22.168/15 22.214.171.124/12 126.96.36.199/14 188.8.131.52/15 184.108.40.206/15 220.127.116.11/15 18.104.22.168/15 22.214.171.124/16 126.96.36.199/13 188.8.131.52/15 184.108.40.206/19 220.127.116.11/13 18.104.22.168/14 22.214.171.124/16 126.96.36.199/17 ...
2. Next, carefully run the following command to block all ranges in that list:
$ while read line; do sudo ufw insert 1 deny from $line to any; done < cdir-china.txt
For a large list (say, the china list) it may take several minutes to run.
3. When complete, you can then run the following to verify the rules are in place:
$ sudo ufw status
To remove or revert these rules, keep that list of IPs! Then run a command like so to remove the rules:
$ while read line; do sudo ufw delete deny from $line; done < cdir-china.txt