If you are the target of DDoS attacks or bots, it can be interesting to block IP addresses by country to block the attacker, for example by banning Chinese IPs, often source of bots network. In this guide, we will see how to proceed on a Linux VPS under Debian, Ubuntu or CentOS.

Install IPSET

To ban the IP addresses of the countries we want, we will use ipset available in the package manager. You must be root administrator of your VPS.

IPSET installation on Debian

apt update && apt install ipset

IPSET installation on Ubuntu

sudo apt update && sudo apt install ipset

IPSET installation on CentOS

sudo yum install ipset

Ban countries with IPSET

Now that ipset is present on our operating system, we are going to configure it to ban the IP addresses of the countries we want.

First of all, we will create a set that will contain the countries whose IP addresses we want to ban.

ipset create countries hash:net,port

You can check the creation with ipset list which should return you:

Name: countries
Type: hash:net,port
Revision: 7
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 448
References: 0
Number of entries: 0
Members:

Now we add the IP addresses of the countries we want with the following script. This script will get the list of all the IP addresses of the countries we want.

Create a ban-ip-countries.sh file in /root/ipset and give it the execution rights:

mkdir /root/ipset
cd /root/ipset
touch /root/ipset/ban-ip-countries.sh
chmod +x /root/ipset/ban-ip-countries.sh

Now we just need to create the script to recover the IPs to be banned.

Now add the following content with the command nano /root/ipset/ban-ip-countries.sh. Edit the table in the COUNTRIES section if you want to ban other countries. You must specify the ISO format code of the country, see official site.

In this example, the variable COUNTRIES contains the countries: China, Russia, Taiwan, Brazil

COUNTRIES=('cn' 'tw' 'ru' 'in' 'br')

ipset flush countries

for i in "${COUNTRIES[@]}"; do
    echo "Ban IP of country ${i}"

    for IP in $(wget -O - https://www.ipdeny.com/ipblocks/data/countries/${i}.zone)
    do
        ipset add countries $IP,22
    done
done

Press CTRL + X to exit the editor and save the file.

Now we just have to execute the script:

bash ban-ip-countries.sh

Now that we have the list of IPs to ban, we just need to link them to the firewall iptables. Create a file /root/iptables.sh :

touch /root/iptables.sh
chmod +x /root/iptables.sh

Edit the file with nano /root/iptables.sh and add the following content:

# On vide les règles iptables précédentes
iptables -F
iptables -X

iptables -I INPUT   -m set --match-set countries src -j DROP
iptables -I FORWARD -m set --match-set countries src -j DROP

Press CTRL + X to exit the editor and save the file.

Last step, we need to run this last script:

bash /root/iptables.sh

And that's it, IPs are banned!