Block countries based on Geo data with UFW firewall
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 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
or
cat cidr-china.txt | awk '/^[^#]/ { print $1 }' | sudo xargs -I {} ufw deny from {} to any
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
or
cat cidr-china.txt | awk '/^[^#]/ { print $1 }' | sudo xargs -I {} ufw delete deny from {}
https://gist.github.com/jasonruyle/8870296
https://github.com/poddmo/ufw-blocklist
Add new comment