#!/bin/sh

# CONFIGURATION:
# LIMIT - here is the maximum allowed number of connections from one IP
LIMIT=50
# e-mail address to send alerts to
EMAILADDRESS=youremail@example.com
# 1 = send e-mails, any other value = do not
SENDEMAIL=1
# 1 = restart apache, any other value = do not
RESTARTAPACHE=1

# first we have what netstat version we happen to have:
if [ "`netstat -an | grep :ffff:`" != "" ]
then
  # Broken netstat, we have to use lsof, make sure it is installed!
  if [ "`which lsof`" == "" ]
  then
    echo "netstat in broken version, lsof not found, please install lsof"
    exit
  fi
  COMMAND='lsof -i -n | egrep '\''.*TCP [0-9\.]*:www->[0-9\.:]* \(ESTABLISHED\)'\'' | awk -F'\''[ \t:]+'\'' '\''{ print $8 }'\'''
else
  # netstat is correct and more common, let's use it
  COMMAND='netstat -n | egrep '\''tcp.*[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*:80[ ]*[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*:[0-9]*[ ]*ESTABLISHED'\'' | awk -F'\''[ \t:]+'\'' '\''{ print $6 }'\'''
fi

eval $COMMAND | sort | uniq -c | while read numconn ip
do
  if [ $numconn -gt $LIMIT ]
  then
    echo "IP $ip went over limit with $numconn connections!!!"
    /sbin/iptables -I INPUT -s $ip -j DROP
    if [ $SENDEMAIL -eq 1 ]
    then
      echo "IP $ip went over limit with $numconn connections!!!" | mail -s "slowloris DoS attack on your server with hostname `hostname`" $EMAILADDRESS
    fi
    if [ $RESTARTAPACHE -eq 1 ]
    then
      /etc/init.d/apache2 restart
    fi
  fi
done
