How to block traffic from other countries in linux

Preventing site attacks from offending countries

It’s a sad fact that the majority of malicious web traffic to US sites originates from the same handful of foreign countries. If your site doesn’t benefit from actual users living in those countries, you may resolve to block them from accessing your site entirely in order to prevent repeated attacks. Here’s how to blacklist entire countries under linux using iptables and ipset.

Step 1

The first step is to identify which countries you want to block. You can do this by analyzing traffic logs and processing the IP’s against a GeoIP lookup service to see which countries are generating the most malicious traffic, a popular and free tool for doing this is AWStats. If you’re using Wordpress, you can install a plugin that will show you your active visitors along with their country of origin.

Step 2

Once you know the countries you want to block, the next step is to obtain a list of IP ranges which belong to those countries. Unfortunately these lists can be hard to come by as the sources for them seem to come and go frequently. The once standard site has not had complete IP data since September 2013 and can no longer be used for new blocking efforts. My recommendation is to use the IP2Location visitor blocker tool to obtain the data. Ctrl+Click each country you want to block from the country list and set the Output Format to “Linux IPtables” and download the file. This will give you a list of IP ranges for those countries.


Step 3

Now that you have your list of IP’s to block, upload the file to your server. On your Linux server, install the IPSet package using yum or aptitude if it’s not already installed.

apt-get install ipset

Step 4

Finally we need to process the list of IP ranges into an IPSet and apply that set to an IPTables rule telling the server to drop those connections. I’ve created a bash script to help you accomplish this. This script assumes that your list of IP ranges to block are in a text file named blocklist.txt. You can adjust to suit.

Once you save that script to your server, execute it to create the banned IPSet and apply a DROP rule in your server’s IPTables.

If you ever want to disable the ban, simply remove the rule from your IPTables.

Read more of Matthew Mombrea's ByteStream blog and follow Matt on Twitter (@mombrea) and Google+. For the latest IT news, analysis and how-tos, follow ITworld on Twitter and Facebook.

This story, "How to block traffic from other countries in linux" was originally published by ITworld.

Copyright © 2013 IDG Communications, Inc.

Shop Tech Products at Amazon