#!/bin/bash
#
# (c) fh@aixit.com 20080430
#
# /usr/sbin/detect-dos
#
# geht so (zur zeit) nicht bei ipv6
# wenn auf einem server ipv6 als kernel modul gestartet wurde
# einfach durch loeschen / umbenennen des ipv6.ko modules abschalten:
#
# mv /lib/modules/$(uname -r)/kernel/net/ipv6/ipv6.ko /lib/modules/$(uname -r)/kernel/net/ipv6/ipv6.ko.STOP
# reboot
# 
# nach dem reboot ist ipv6 aus.
#
# Damit das script auf einem server arbeitet kann die Variable LIP
# angepasst werden, sie sollte externe IP und port des apache des hosts enhalten,
# funktioniert aber auch mit dem default Wert.
#
# Jetzt einfach noch einen cron job nach /etc/cron.d/ legen oder in die /etc/crontab eintragen
#
# * * * * * root /usr/local/bin/detect-dos >> /var/log/detect-dos.log
#

# TODO
# - establish persistent drops 20080506 done fh@aixit.com
# - make ip drop rules unique 20080502 done fh@aixit.com

. /etc/detect-dos.conf
#DEBUG=true
#DOS=10

DATE=`date +%F-%H%M%S`
MINUTE=`date +%M`

if [ "$DEBUG" = "true" ]; then
	MINFLUSH=$MINUTE
fi

function debug ()
{
	if [ "$DEBUG" = "true" ]; then
		echo "    $DATE: $*"  >&2
	fi
}

function getPDROPS ()
{
	iptables -n -L INPUT |
	awk '/DROP/ {print $4}' |
	sort -u
}

function dropip ()
{
	debug "enter dropip"
	BLOCKED="no"

	echo -n "$DATE $PAT $CNT"
	for TIP in $PDROPS ; do
		debug "for $TIP = $PAT"
		if [ "$TIP" = "$PAT" ]; then
			BLOCKED="yes"
			debug "yes $TIP $PAT"
			echo ""
			return
		fi
	done

	if [ "$BLOCKED" = "no" ]; then
			echo " NEW"
                        if [ "$DEBUG" = "true" ]; then
                                debug  "iptables -A INPUT -s $PAT/$NETMASK -j DROP"
                        else
                                iptables -A INPUT -s $PAT/$NETMASK -j DROP
                        fi
        else
		echo ""
	fi
	
	debug "exit dropip"
}

function persistentDrops ()
{
	if [ -f $PDROPSCONF ]; then
		iptables-restore < $PDROPSCONF
	else
		iptables -F INPUT
		iptables-save > $PDROPSCONF
	fi
}

if [ "$MINUTE" -eq "$MINFLUSH" ]; then
	if [ "$DEBUG" = "true" ]; then
        	debug  "persistentDrops"
        else
		persistentDrops
        fi
fi

PDROPS=`getPDROPS`
debug $PDROPS

netstat -tn|
awk "/$LIP/ {print \$5}"|
awk -F':' '{print $1}'|
sort|
(
while read IP;  do
        if [ "$IP" = "$PAT" ]; then
                (( CNT++ ))
        else
                if [ "$CNT" -ge "$DOS" ]; then
                        dropip
                fi
                PAT="$IP"
                CNT=1
        fi
done;

if [ "$CNT" -ge "$DOS" ]; then
        dropip
fi
)

