Block countries based on Geo data with UFW firewall

I while ago, I wrote this post about how to block all network traffic from-and-to certain countries using UFW firewall based on recent Geo data. The statistics of this website show that this post is still one of the most popular posts here. Many people found their way here through Google searches like: UFW, Geo and Block. If you happen to be one of these people, welcome! You came to the right place! Please ignore my earlier post, it is outdated. Continue reading this post, because I will show you a simpler way to block specific countries, This method is super easy, and everybody can do it. So, let’s do this!!

The first step is to browse to this page here: https://www.ip2location.com/free/visitor-blocker, and scroll down until you see a pull-down menu where you can search for countries. From this list you will select the countries you want to block, and then change the output format to CIDR (see image below) and download the archive file.

Unzip the .gz file you downloaded. You will then see a text file for each country you’ve chosen. We are going to use a simple command to add the contents of the text files to our firewall rule list.

Open a terminal window and login as a user with sudo rights. Cd to the folder where the unzipped text files are stored, and use the command show below. In this example I imported the block file for China, (sorry China!), so obviously you will need to change this to whatever countries you’ve picked.

while read line; do sudo ufw deny from $line; done < china-firewall.txt

You will first see a couple of errors scroll by, just ignore them. Keep in mind that running the command may take some time to complete. It may even appear as if the terminal is crashing or has hanged. Just leave it alone, and let it do its thing for a few moments. Once it is done importing, you are also done! How easy was that? Don’t delete the downloaded files, because you may need them again in case you ever decide you want to remove the rules from your firewall rules. Use this command to remove all the rules from your firewall:

while read line; do sudo ufw delete deny from $line; done < china-firewall.txt

Giving credit where credit is due, many thanks to Jason, and for sharing it on his github.

Was this post useful for you? Do you have any thoughts, remarks, or critique? Do you want to thank me before you leave? Want to tell me what I did wrong? Feeling angry? Want to call me bad names for whatever reason? Want to let me know how handsome you find me. Or that you are secretly in love with me, but too to say anything? It doesn’t matter what reason you have, please feel free to leave a comment.

EDIT 11-10-2023: The first comment to this post is one you should read. Poddmo has created scripts that he published to Github that make it easier to add IP block lists to UFW using IP sets. Check it out here: https://github.com/poddmo/ufw-blocklist. Many thanks to Poddmo!