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

Created:

Introduction

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:

23.7.111.0/24
23.11.215.0/24
23.12.156.0/23
23.14.140.0/23
23.14.143.0/24
23.14.240.0/24
23.14.242.0/23
23.14.245.0/24
23.14.246.0/24
23.14.248.0/22
23.14.252.0/24
23.14.254.0/23
23.15.2.0/24

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 {}

Appendix

Check ufw

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

$ sudo ufw status