images

Block IP by country

Block access to your server depending on country

Sorry I haven’t done much on the site recently I’ve just got back from a trip to India and Nepal so only just making time for some updates now.

This week has been a weird, and when I mean this week I actually mean last week with lots of changes happening. Well we are looking to increase some security procedures  and one of processes that probably is going to be rolled out is blocking access to certain countries IP’s. Lets say your server is getting multiple attacks daily by China well you can stop all that by blocking China IP’s. This is done by using iptables to block and inputting the China IP’s or whatever country you desire – it works very well

The base of the script works by flushing the iptables rules and setting them up for the script – you might what to edit this depending on your firewall walls.

The variables of scripts are:

  • The iptable rule name in this case it’s BannedCountries
  • The two letter country code which you need to enter for the countries you want to block, in the script I’ve blocked China and Afghanistan
  • Location of where you are going store the download ip lists

The next part of the script is to get a list from the net of the updated public IP’s – they are quite a few of them out there i’ve chosen www.ipdeny.com as I liked the way the data was formatted and stored. I use a wget to get the ip list depending on the two letter country code which is then put through a loop to catch more then one country, the ip list is then stored in a file on the local disk i.e. cn.zone for the China IP range. I use another loop to grep the different country zone file to make sure I get the IP correctly in this case on a different line and within this loop is a ip table rule to input/output the given ip and deny this ip access to your server.

Simple you might say – well you make it even better by calling this script weekly or daily in a cron so the firewall is updated regularly with all the latest IP’s


Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>