:::: MENU ::::

Block IP addresses by country using iptables in CentOS

You can block or allow access to your server by Country, this is another layer of security you can add to your services, for example if you have to allow access to ssh port from any IP and you know that all the persons that uses ssh to this server are in Ireland, you can block any access to ssh from any country except Ireland, with that you can avoid a huge amount of security risks.

Below are the steps to implement server access control by country for centos/Redhat servers:

Environment : CentOS 6.5 / 6.6 minimum install

  • Install some indirectly necessary packages:

    yum install gcc gcc-c++ make automake unzip zip xz

  • Install the kernel-devel matching the kernel of your system

    To check your kernel version:

    uname -r

    To install the kernel-devel package:

    yum install kernel-devel

    when you install the kernel-devel you can see the version of the kernel-devel installed, in my case the kernel-devel had a higher version than kernel version of the system, from my experience it was easier to upgrade the kernel than searching for the corresponding kernel-devel matching my kernel.

    In another post I will explain how to upgrade the kernel of your server.

  • Now due to a bug explained in this post xtables-addons-error you need to do the next steps:

    In my case I have kernel-devel version 2.6.32-504.16.2.el6 (and THE KERNEL OF THE SAME VERSION), if you installed another version, take into account to change the path of the file autoconf.h

    vi /usr/src/kernels/2.6.32-504.12.2.el6.x86_64/include/linux/autoconf.h
    comment this line:
    by changing it with this line:

  • Install xtables:
    xtables is included in iptables-devel, so we install iptables-devel

    #yum install iptables-devel
  • Install xtables-addons-1.47.1 xtables-addons-1.47.1.tar:

    tar -xvf xtables-addons-1.47.1.tar.xz
    cd xtables-addons-1.47.1
    make install
  • Now we have to install GeoIP-devel and GeoIP, available in the EPEL repository:

    yum install epel-release.noarch
    yum install GeoIP-devel GeoIP
  • Now install perl-Text-CSV_XS.x86_64   ┬íKeep it up just some few more steps!

    yum install perl-Text-CSV_XS.x86_64

    Now follow the next steps:

    mkdir /usr/share/xt_geoip

    search for the location of the xt_geoip_dl in your server :

    sudo find / -name xt_geoip_dl -print

    go to that directory and run the net three commands:

    cd /usr/local/libexec/xtables-addons/
    ./xt_geoip_build -D /usr/share/xt_geoip *.csv

    WE ARE DONE, GREAT!!!!!!

    Some examples :

    Allow access to ssh port only from France and Ireland:

    iptables -I INPUT -p tcp --dport 22 -m geoip ! --src-cc FR,IE -j DROP

    Block all traffic country with code XX:

    iptables -I INPUT -m geoip --src-cc XX -j DROP

So, what do you think ?