Detect Possible DDOS Attack

The following bash script can be used to detect the number of http/https connections for each unique IP address. Uncomment the line for “iptables” to automatically block any IP exceeding the desired value (10 in this example) in the system firewall (Linux only).

A quick and dirty way to block unwanted request hits against your server. Make sure you’re happy with the maximum value of connections before deployment, and ensure the iptables chain name “INPUT” applies in your firewall setup (Tested on CentOS 6/7).

# Name:	connectsIP
# Purpose: Determine number of remote connections for each IP
#          Can be used for DDOS protection or notification
# Created: October 24, 2016
# Last Mod: 10/24/2016

for ip in `lsof -ni | grep httpd | grep -iv listen | awk '{print $9}'| cut -d : -f 2  | sed s/"http->"// | sort | uniq` ;
   numConnects=`lsof -ni | grep $ip | wc -l`;
   echo $ip : $numConnects ;
   if [ $numConnects -gt "10" ] ;
      echo "Possible DDOS from $ip" ;
      ## Uncomment line below to add offending IP to IPTABLES
      ## This following line causes resets to be sent to $ip when  
      ## any packets are received

      # iptables -I INPUT -s $ip -p tcp -j REJECT --reject-with tcp-reset

      # Insert other actions below if desired


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.