#!/bin/sh
#checklog for filtering script kiddies
#published under GNU GPL2 for asus users
#(c) by newbiefan

logfile=/opt/var/log/syslog.log
banned_file=/tmp/mnt/banned
#uncomment when called by cron
PATH=/opt/sbin:/opt/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

  if [ -e /tmp/mnt/failcounts ]; then
      oldcountsfailed=`cat /tmp/mnt/failcounts`
   else     
      touch /tmp/mnt/failcounts
      echo "0" > /tmp/mnt/failcounts
      oldcountsfailed="0"
  fi

#write how many failed logins to failcounts
   grep -ic "nonexistent user" $logfile > /tmp/mnt/failcounts

if [ $oldcountsfailed = `cat /tmp/mnt/failcounts` ] ; then   #is equal exit, nothing is changed
 exit 0  #end script
fi

     grep "nonexistent user" $logfile | cut -d" " -f11 | cut -d":" -f1 | uniq -c | awk '$1 > 2 { print $2; }' > $banned_file
 
    for ipadr in `cat $banned_file` ; do
         if [  -z "`/usr/sbin/iptables -n -L BLOCKIT | grep $ipadr`" ] ; then
            /usr/sbin/iptables -A BLOCKIT -s $ipadr/32 -j REJECT --reject-with icmp-host-unreachable
            logger checklog "IP $ipadr blocked, consider to unblock manually or reboot"
 #           echo $ipadr >> /opt/var/log/blocklist.log
         fi 
    done
#Without changing the order, nothing would happen, now return is the last entry 
  /usr/sbin/iptables -D BLOCKIT -j RETURN
  /usr/sbin/iptables -A BLOCKIT -j RETURN

