Linux: How to use ufw to block visitors by country?



Sometimes you need to block traffic from certain countries (china?india?). We will cover how to block ips by geographical region. We will use Ubuntu, but since we are going to use ufw it will work in other distros.

Step 1: Get the list by country

IP2 Locations is a trusted IP geolocation solution provider. IP-Database is not free, but visitor-blocker is free.

With our example we will block India. Select the IPv version, then the country and finally the output format. We need the CIDR output format, since we are going to use ufw.

Here is an example of India ips in CIDR format:

Save the file as cidr-india.txt.

Step 2:

Now to configure ufw you need to execute ufw for each line of the cdir-india.txt.

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

The command above will skip comment lines (starting with #) and will use xargs to fetch ufw.

Remember to update the list every month. To do that, first delete all the entries with:

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


Check ufw

To check if the IPs list were loaded use the command:

$ sudo ufw status