#!/bin/bash
# IP BAN v. 1.0.0
WORK_DIR='/root/ddos'
IGNORE_IP_LIST="$WORK_DIR/ignoreip"
BLOCKED_IP_LIST="$WORK_DIR/blockedip"
LOG_FILE="$WORK_DIR/ban.log"
NO_OF_CONNECTIONS=20
APF_BAN=0
KILL=1
add__cron()
{
set="$(readlink -f "$0")"
if [ ! -f $WORK_DIR/ddos.sh ]; then
# mkdir /root/ddos >/dev/null 2>&1
cp $set $WORK_DIR/ddos.sh
chmod +x $WORK_DIR/ddos.sh
fi
if [ ! -f /etc/cron.d/check_ddos ]; then
echo "* * * * * root $WORK_DIR/ddos.sh >/dev/null 2>&1" > /etc/cron.d/check_ddos
fi
}
mk_ignore()
{
if [ ! -d "$WORK_DIR" ]; then
mkdir $WORK_DIR
fi
if [ ! -f $WORK_DIR/systemip ]; then
ip addr show | grep -w inet | awk '{ print $2 }' | cut -d"/" -f1 > $WORK_DIR/systemip
echo "0.0.0.0" >> $WORK_DIR/systemip
fi
}
prog_check()
{
if ! which netstat >/dev/null; then
apt-get install net-tools
fi
}
prog_check
mk_ignore
add__cron
TMP_PREFIX='/tmp/ddos'
TMP_FILE=`mktemp $TMP_PREFIX.XXXXXXXX`
SYSIP="$WORK_DIR/systemip"
BAD_IP_LIST="$TMP_FILE"
netstat -an | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | sort | uniq -c | sort -nr > $BAD_IP_LIST
if [ $KILL -eq 1 ]; then
IP_BAN_NOW=0
while read line; do
CURR_LINE_CONN=$(echo $line | cut -d" " -f1)
CURR_LINE_IP=$(echo $line | cut -d" " -f2)
if [ $CURR_LINE_CONN -lt $NO_OF_CONNECTIONS ]; then
break
fi
IGNORE_BAN=`grep -c $CURR_LINE_IP $IGNORE_IP_LIST`
IGNORE_BAN2=`grep -c $CURR_LINE_IP $SYSIP`
IGNORE_BAN3=`grep -c $CURR_LINE_IP $BLOCKED_IP_LIST`
if [[ $IGNORE_BAN -ge 1 || $IGNORE_BAN2 -ge 1 || $IGNORE_BAN3 -ge 1 ]] ; then
continue
fi
IP_BAN_NOW=1
dt=$(date '+%Y/%m/%d %H:%M:%S');
echo "$CURR_LINE_IP was blocked at $dt" >> $LOG_FILE
echo $CURR_LINE_IP >> $BLOCKED_IP_LIST
if [ $APF_BAN -eq 1 ]; then
$APF -d $CURR_LINE_IP
else
echo $CURR_LINE_IP
/sbin/iptables -I INPUT 1 -s $CURR_LINE_IP -j DROP
/sbin/iptables -I OUTPUT 1 -d $CURR_LINE_IP -j DROP
fi
done < $BAD_IP_LIST
fi
rm -f $TMP_PREFIX.*