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.

#!/bin/bash
DROPLIST="droplist" # iptables chain name
IPT_DATA="/tmp/iptables-data.txt"
DATA_URL="http://services.ce3c.be/ciprg/?countrys=CHINA%2CRUSSIAN+FEDERATIONVIET+NAM%2CUKRAINE%2CTHAILAND%2C&format=by+input&format2=%7Bcountry%7D%20%7Bstartip%7D%20%7Bendip%7D%20%7Bnetmask%7D%0D%0A"

IPT="/sbin/iptables"
IPC="/usr/bin/ipcalc"

curl -o $IPT_DATA $DATA_URL
# 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}')
  $IPT -F $DROPLIST
  $IPT -X $DROPLIST
fi

$IPT -N $DROPLIST
$IPT -I INPUT -j $DROPLIST

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"
    $IPT -A $DROPLIST -s $NETMASK -j DROP
  done < $IPT_DATA
fi
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(2) dev(2) gems(1) howto(3) mac(1) ops(7) projects(2) script(1) tools(1) tutorial(4)

* Tags *

api(1) apple(2) aws(3) bash(1) cloud(4) cluster(1) ec2(1) elasticsearch(1) gem(1) github(1) google-authenticator(1) google-cloud(1) iptables(1) linux(2) logging(1) mac(2) opensource(1) openvpn(1) osx(2) pci-compliance(1) ruby(2) security(2) ssh(1) ubuntu(1) wykop(1) yubikey(1)
comments powered by Disqus