How to Block IPs from a Specific Country on a CentOS 6 Cloud Server Using iptables?

11-01-2024 02:42:20

If our cloud server is continuously under cyber attacks from a particular country, one measure we can take is to block all IPs originating from that country. This article explains how to use the iptables tool and the IP address database provided by IP2LOCATION to block IPs from a specific country.

Step 1: Install iptables and ipset

yum install iptables ipset -y
service iptables start

Step 2: Download the iptables Rules File

We use the IP address database provided by IP2LOCATION. For instance, if we want to block IPs from Peru, visit the following address, select the country as "Peru", choose the output format as "Linux iptables", and then download the iptables rules file.

https://www.ip2location.com/free/visitor-blocker

After downloading the iptables rules file to your local computer, upload it to the cloud server using FTP software or other methods.

Step 3: Apply the iptables Rules

Remotely access the cloud server via SSH, locate the iptables rules file you just uploaded, and rename it to block.txt. Next, we will process this rules file with a script.

Create a script file:

vi process.sh

The content of the script is as follows:

#!/bin/bash
#Script to process ip ranges to ban using IPSet and IPTables
ipset create countryblock hash:net
while read line; do ipset add countryblock $line; done < (block.txt)
iptables -I INPUT -m set --match-set countryblock src -j DROP

Save and execute the script:

sh process.sh

Finally, save and load iptables:

service iptables save
service iptables reload

With this, we have successfully blocked IPs from Peru on this cloud server. To unblock, simply delete the iptables rules generated by the script, and remember to save iptables again to make the changes permanent.