RH6: Blocking a country via host base firewall
So you have a website, mailserver, application server based on Redhat Enterprise 6.x ( can also be CentOS 6 )
and hacking attempts is driving you mad.
What to do ?
If you have a webserver like nginx you can implement GeoIP to block IP ranges that below to countries.
The thing with that is that it will cost the server relitively a lot CPU/memory to keep them out
( depending of the amount of attempts ).
Isn’t there a better way ? YES there is. We can block countries via the host based filewall using ipset
OK there we go. This is how it CAN be done ( there are several ways ).
- Install ipset
# yum -y install ipset
- Create a set called “blockcountry” which we will use with iptables later on
# ipset create blockcountry nethash
- We need to fill the set with ip ranges from the countries you need to block.To be able to know which country files to use we need to find out which country code to use.
This can be found here : http://www.ipdeny.com/ipblocks
Here we find as an example :the The Netherlands – nl
China – cn
Ukraine – ua
Russia – ru - So lets say we want to block systems from China. We now nee to fill the set “blockcountry” with
the IP Subnets from China.# for SUBNET in $(wget -O – http://www.ipdeny.com/ipblocks/data/countries/cn.zone)
do
ipset add blockcountry ${SUBNET}
done - Now we can create a firewall rule which will drop the IP packages from the specified countries :
# iptables -I INPUT -m set –set blockcountry src -j DROP
# service iptables saveOutput of iptables
# iptables -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
300 15840 DROP all — * * 0.0.0.0/0 0.0.0.0/0 match-set blockcountry src
Because the ipset which we built will be empty after reboot we need to build the set before starting the host based firewall is started.
- Save the ipset which is in memory
# ipset save > /etc/sysconfig/ipset.blockcountry
- We can restore the ipset with command
# ipset restore -! < /etc/sysconfig/ipset.blockcountry
- Create a script which will restore the ipset at boot time [ /etc/rc.local ]
# cat /usr/local/bin/ipset_restore.sh
find /etc/sysconfig -maxdepth 1 -type f -iname ipset.\* | while read SET;
do
/usr/sbin/ipset restore -! < ${SET}
if [ $? -eq 0 ]; then
logger -t ipset “succes: restore of ${SET}”
else
logger -t ipset “fail : restore of ${SET}”
fisleep 1
IPSET=${SET##*.}
/sbin/iptables -I INPUT -m set –set ${IPSET} src -j DROP
if [ $? -eq 0 ]; then
logger -t iptables “succes: add ipset ${IPSET} rule to iptables”
else
logger -t iptables “fail : add ipset ${IPSET} rule to iptables”
fi
done
Leave a comment