Block Geo-Region List of IPs with ufw in Linux

By | 2013/08/30

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:

http://www.ip2location.com/free/visitor-blocker

Select iptables, China (or whichever country), CIDR format, and Download.

01-block_iprange

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.

...
223.0.0.0/12
223.20.0.0/15
223.27.184.0/22
223.64.0.0/10
223.128.0.0/15
223.144.0.0/12
223.160.0.0/14
223.166.0.0/15
223.192.0.0/15
223.198.0.0/15
223.201.0.0/15
223.203.0.0/16
223.208.0.0/13
223.220.0.0/15
223.223.176.0/19
223.240.0.0/13
223.248.0.0/14
223.254.0.0/16
223.255.0.0/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.

02-block_iprange
3. When complete, you can then run the following to verify the rules are in place:

$ sudo ufw status
03-block_iprange
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