raczylo.com blog ~ #

Blocking whole countries ranges with iptables

Created on 2014-10-10 in categories ops , script
Tagged as: bash , iptables , linux , security

Block rogue traffic to your servers with this simple script

There we are. Rogue chinese hackers trying to steal your holidays pictures? NSA spying on your hamster? Russians.. Being Russians? Next time when you’ll be like “I don’t have nothing to do with this country and someone tried to bruteforce my SSH last night” try to repeat following steps

Downloading data

First of all - visit this website: http://services.ce3c.be/ciprg/, pick your favourite countries which you’d like to avoid and change formatting to:

{country} {startip} {endip} {netmask}

… and click on generate button. Copy full url into DATA_URL variable into my script.

Your porn should be safe now.

DROPLIST="droplist" # iptables chain name


# quick check for old iptables rule
if [ $($IPT -L INPUT | grep -c $DROPLIST) -gt 0 ]; then
  # Cleaning up old chain
  $IPT -D INPUT $($IPT -L INPUT --line-numbers | grep $DROPLIST | awk '{print $1}')


if [ -f $IPC ]; then
  # only if ipcalc package has been installed to prevent null values
  while read BADIP_LINE; do
    IP=`echo $BADIP_LINE | awk '{print $2}'`
    NM=`echo $BADIP_LINE | awk '{print $4}'`
    NETMASK=`/usr/bin/ipcalc $IP $NM | grep Network | awk '{print $2}'`
    $IPT -A $DROPLIST -s $NETMASK -j LOG --log-prefix "Country ban: $NETMASK"
  done < $IPT_DATA
exit 0

Set a crontab for weekly refresh like:

@weekly /root/hide-my-porn.sh

* Table of contents *

* Check other posts *

* Categories *

aws(1) cloud(3) dev(3) gems(1) howto(3) insights(1) internet(1) learning(1) lesson(1) mac(1) ops(8) post(1) projects(3) script(1) social(1) tools(1) tutorial(5)

* Tags *

api(2) apple(2) aws(3) bash(1) cloud(5) cluster(1) devices(1) docker(1) ec2(1) elasticsearch(1) gcp(1) gem(1) github(2) go(1) golang(2) google-authenticator(1) google-cloud(3) internet(1) iptables(1) kubernetes(1) linux(2) littleguardian(1) logging(1) mac(2) netgear(1) network(1) opensource(1) openvpn(1) osx(2) pci-compliance(1) review(1) ruby(2) security(2) ssh(1) tethering(1) tplink(1) ubuntu(1) wykop(1) yubikey(1)
comments powered by Disqus