Iptables block country

From vpsget wiki
Revision as of 17:47, 15 April 2015 by Ndi (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Tested on Centos 6.6

HOW IT WORKS:

We will install xt_geoip module for iptables and connect it with Maxmind geoip database.
Iptables will mark all incoming packets with geoip information and block or allow them to pass depending on your needs.

Let's check the kernel version first:

uname -r

In our case it is 2.6.32-504.8.1.el6.x86_64

For kernels below 3.7 we should use xtables version 1.x.

Make sure you have the following packages installed:

yum -y install gcc gcc-c++ make automake unzip zip xz kernel-devel-`uname -r` iptables-devel

Add rpmforge repository:

rpm -i http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm

Install perl-Text-CSV_XS

yum -y install perl-Text-CSV_XS

Download xtables-addons:

wget http://sourceforge.net/projects/xtables-addons/files/Xtables-addons/1.47/xtables-addons-1.47.1.tar.xz

Extract and install xtables-addons:

tar xvf xtables-addons-1.47.1.tar.xz
cd xtables-addons-1.47.1
./configure
make
make install

Setting up geoip module. These commands will download and install Maxmind databases:

cd geoip
./xt_geoip_dl
./xt_geoip_build GeoIPCountryWhois.csv
mkdir -p /usr/share/xt_geoip/
cp -r {BE,LE} /usr/share/xt_geoip/

Now we can add some firewall rules.
For example, if you want to block China:

iptables -I INPUT -m geoip --src-cc CN -j DROP
iptables-save >/etc/sysconfig/iptables
service iptables restart
chkconfig iptables on

Another example. If you want to allow Canada and block the others:

iptables -P INPUT DROP
iptables -I INPUT -m geoip --src-cc CA -j ACCEPT
iptables-save >/etc/sysconfig/iptables
service iptables restart


NOTE: It's also possible to block countries with CFS. It's really simple. Just install CSF and login to WebGUI to find this options. But you should note that CSF could create a thouthands lines of iptables rules (depending on country size and how many countries you will block or allow ) it will be not so comfortable to manage iptables with such big rules amount and also this may impact on the server performance *(especially CPU load)