Tonight, with my wife away, I sat down and had a look at my firewall configuration, (I know, Saturday night…) and thought about ways to improve the static blocking I had been using until now. With the help of the useful info on ipdeny.com, and the use of iptables, ipset and cron, I’m able to create a script that on reboot of the server will grab the latest country level IP block information, then cycle through it and configure the firewall to drop any attempt at a connection from those countries. However, I don’t for a moment pretend that this is a way to secure your server. Any attacker worth their salt can, and will, pivot through some deniable infrastructure, and in most cases that will intentionally be in a country most would consider “safe”. However, where this sort of script is handy is in providing some protection against being the “low hanging fruit”. Consider the scenario when a remote code execution vulnerability is discovered in Apache or PHP or WordPress. Rest assured that within minutes, a script will have been written in China that will scan the entire 32 bit IPV4 address space for vulnerable machines and attempt to exploit them. At the very least, by dropping any Chinese connections, you can buy yourself some time to patch the vulnerability.
Anyway, the code is available here.
Version one is very linear and clunky. Version 1.1 will be focused on moving the process into a single iterative for loop that takes the country name and digram from an array. It should significantly cut down on the number of lines of code, and make for a much easier system to administer.