December 27, 2013, 8:00 AM — 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.
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.
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 IPDeny.com 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.
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
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.