Learn How To Block IPs From a Country on CentOS 6

February 6, 2019

Table of Contents

Introduction

Welcome to another IT Web Services tutorial. Today we’ll be learning how to use IPTables and IP2Location to block IP addresses from certain countries. IP2Location offers databases of country IP address blocks as a free service.

Prerequisites

Before we do anything, we must make sure to have iptables and ipset installed:

yum install iptables ipset -y
service iptables start

Choose countries to block

Visit the IP2Location visitor blocker service. In this example, we’ll be blocking connections from Iceland, so we’ll select Iceland from the list.

1.png

After doing so, select “Linux IPTables” as the output format. It should look like:

2.png

Upload the file to your server with your favorite FTP client. I use FileZilla.

Blocking the IPs

Once the previous step is complete, access SSH on your server and head to the directory where the file was uploaded.

Rename the file to block.txt.

Now we will process the file of IP blocks. Create a shell script.

vi process.sh

Paste the following into the script:

#!/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 the file, and exit the text editor.

Run the script.

sh process.sh

Finally, save IPTables and reload:

service iptables save
service iptables reload

Conclusion

You have now successfully blocked a country from accessing your IT Web Services server. If you want to remove the block, simply remove the rules from IPTables.

Need help?

Do you need help setting up this on your own service?
Please contact us and we’ll provide you the best possible quote!