Stop DDOS. Shell script to find IPs with connections higher than 80 and block in firewall & Also send notification mails with the blocked IP(s).
#!/bin/bash
###################################################
# Script Name : StopDdosAttack
# Created By : Jino Joseph
# Created Date : 20-Mar-2013
# Last Modified : 21-Mar-2013
# Purpose : Finds the IPs with connections higher than 80 and block in firewall &
# Also send notification mails with the blocked IP(s).
###################################################
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -5 | sed -e 's/^[ \t]*//' | sed -e 's/ /#/g' > result.txt
CSF=/usr/sbin/csf
FIREWALL=0
IPCOUNT=`cat result.txt | wc -l`
ITERATION=0 # Key to check if the loop is finished for restarting the firewall
for i in `cat result.txt`;
do
echo $i > temp.txt;
No=$(cat temp.txt | gawk -F '#' '{print $1}');
IP=$(cat temp.txt | gawk -F '#' '{print $2}');
Num=${No/\.*}
if [ $Num -gt 80 ] && [ $IP != '127.0.0.1' ]
then
$CSF -d $IP # Adding the ip in firewall rule.
FIREWALL=1 # This is a key to confirm that the firewall rule is added.
echo -e " $IP : $Num \n " >> /tmp/ips.txt
else
echo "Normal connections : $Num";
fi
ITERATION=`expr $ITERATION + 1`
# Check whether rule is added in the firewall && also check all the ips are checked for exceeding threshold.
if [ $FIREWALL == 1 ] && [ $ITERATION == $IPCOUNT ]
then
$CSF -r # Restart Firewall
echo "Restart Firewall & Sending Mail";
#######################
# Mail Sending Section
#######################
# email subject
SUBJECT="IPs are Blocked in Server!!"
# Email To ?
EMAIL="example@example.com"
# Email text/message
BLOCKEDIPS="`cat /tmp/ips.txt`"
EMAILMESSAGE="/tmp/emailmessage.txt"
echo "Hi Team, " > $EMAILMESSAGE
echo " " >> $EMAILMESSAGE
echo " " >> $EMAILMESSAGE
echo -e "The Blocked IPs are \n \n$BLOCKEDIPS">> $EMAILMESSAGE
echo -e "\n This is a notification. Please close it." >>$EMAILMESSAGE
echo " " >> $EMAILMESSAGE
echo " " >> $EMAILMESSAGE
echo "Regards," >> $EMAILMESSAGE
echo "System Admin" >> $EMAILMESSAGE
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
cat /dev/null > /tmp/ips.txt
## End of Mail###
fi
done
If you want to send the mail with smtp auth , use the below command:
echo $EMAILMESSAGE | mailx -s "DDOS Attack IP Blocked" -S smtp=smtp://xyz.net:587 -S smtp-auth=login -S smtp-auth-user=alerts@xyz.net -S smtp-auth-password=9879ljouhkh888 -S from="DDOS Attack IP Blocked
Comments