Friday, January 24, 2014

My own fail to ban script for asterisk

This is script /usr/local/sbin/block_sip_ip.sh. It has some options, but i doubt if you really need all of them
you can just add it to your crontab:

*/3 * * * * /usr/local/sbin/block_sip_ip.sh -n 1000

where
-n 1000 - amount of las lines of asterisk log to parse. You need to adjust that part accordingly of intensity  of your calls. by default its only 200 lines.

-q - how many attempts allowed before IP will be banned. 3 by default

#!/bin/bash
# checking, is someone is getting "wrong password" in last 200 lines of asterisk log:
DEBUG=0
# email to notify about banned IPs
ADMIN_EMAIL="admin@domain.com"

# our internal network. First part only
LOCAL_NET="10.0.0"


# our own external IP:
OWNIP1="111.221.211.111"
LINES=200
INFO="Use: $0 -l /PATH/TO/LOG -q ATTEMPTS -n LINES"
while getopts ":dl:q:n:" optname
    do
      case "$optname" in
        "d")
             DEBUG=1
             echo "debugging is on"
          ;;
        "n")
             LINES=$OPTARG
          ;;
        "l")
             LOG_FILE=$OPTARG
          ;;
        "q")
            ATTEMPTS=$OPTARG
          ;;
        "?")
          echo "Unknown option $OPTARG"
                  echo $INFO
                  exit 0
          ;;
        ":")
          echo "No argument value for option $OPTARG"
                  echo $INFO
                  exit 0
          ;;
        *)
      echo "Unknown error while processing options"
          exit 0
          ;;
      esac
    done
if [ -z "$LOG_FILE" ]
then
  LOG_FILE="/var/log/sip_hackers_ips"
fi

[ "$DEBUG" -eq 1 ] &&  echo "logfile : $LOG_FILE"
[ "$DEBUG" -eq 1 ] &&  echo "lines : $LINES"

if [ -z "$ATTEMPTS" ]
then
    ATTEMPTS=2
fi

[ "$DEBUG" -eq 1 ] &&  echo "failed ext. allowed : $ATTEMPTS"

for i in `tail -$LINES /var/log/asterisk/full | grep -v $LOCAL_NET | grep -E '(Wrong password| failed for )' | grep -Eo '(([0-9]{1,3}\.){3}[0-9]{1,3})' | sort | uniq | grep -v "$OWNIP1"`
do
    # checking amount of attempted extensions
    EXT_CNT=$(tail -$LINES /var/log/asterisk/full | grep -oc "$i")
    # if its geater than 3, block it!!
    if [ "$EXT_CNT" -gt "$ATTEMPTS" ];
    then
       IPTABLES_CNT=$(/sbin/iptables -nvL | grep -c $i);
       if [ "$IPTABLES_CNT" -eq 0 ]; 
       then
            [ "$DEBUG" -eq 1 ] && echo "To BLOCK: $i";
            echo -n "[`date`]">> $LOG_FILE
            echo $i >> $LOG_FILE
            /sbin/iptables -I INPUT -s $i -j DROP
            /sbin/iptables -A OUTPUT -d $i -j DROP
            [ "$DEBUG" -eq 1 ] && echo "IP $i has been blocked"
            echo "VPBX: $i has been blocked" | mail -s "VPBX: $i has been blocked" $ADMIN_EMAIL
         fi
      fi
done

No comments:

Post a Comment