Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active June 26, 2023 04:29
Show Gist options
  • Save eusonlito/74604fc2815872b00c8b to your computer and use it in GitHub Desktop.
Save eusonlito/74604fc2815872b00c8b to your computer and use it in GitHub Desktop.
This script check netstat connected IPs with more than $limit connections. If connections continues 5 minutes after, IP will be added to iptables with DROP.
#/bin/bash
# This script check netstat connected IPs with more than $limit connections
# If connections continues 5 minutes after, IP will be added to iptables with DROP
# Execute as cron every 5 minutes
# */5 * * * * /root/shells/ddos-detect.sh >> /root/logs/ddos-detect.log 2>> /root/logs/ddos-detect.err
echo ""
echo "Start at: `date "+%Y-%m-%d %H:%M:%S"`"
echo ""
# List where store last possible attacks
list=/root/logs/ddos-detect.list
# Logs to read and detect attacks
logs=/var/www/vhosts/*/logs/access_log
# Some connected now more than this value will be considered as attack
limit=50
# Your whitelist IPs to avoid to block
whitelist="0.0.0.0\|127.0.0.1"
if [ -f "$list" ]; then
last=$(cat $list)
else
last=''
fi
echo '' > $list
netstat -ntu | awk ' $5 ~ /^(::ffff:|[0-9|])/ { gsub("::ffff:","",$5); print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | grep -v "$whitelist" | while read line; do
number=$(echo $line | awk -F' ' '{print $1}')
ip=$(echo $line | awk -F' ' '{print $2}')
if [ "$number" -lt $limit ]; then
continue
fi
if [ "$(echo $last | grep $ip)" != "" ]; then
if [ "$(grep -m 1 "$i" $logs | grep "Google\|Bing\|pagespeed\|Twitter\|Yahoo")" != "" ]; then
echo "Spider Bot detected at $ip ($number requests). Skip."
echo "---------------------------------------------"
grep -m 5 "$i" $logs | head -50
echo "---------------------------------------------"
continue
fi
echo "Added $ip to iptables DROP ($number requests)"
echo "Last webs visited:"
echo "---------------------------------------------"
grep -m 10 "$i" $logs | head -50
echo "---------------------------------------------"
/sbin/iptables -A INPUT -s "$ip" -j DROP
continue
fi
echo "Added $ip to last IP list with $number requests"
echo "$ip" >> $list
done
/sbin/iptables -L --line-numbers | while read line; do
if [ "$(echo "$line" | grep "$whitelist" | grep "DROP")" = "" ]; then
continue;
fi
echo "Unlocked Line '$line'"
/sbin/iptables -D INPUT "$(echo "$line" | awk -F' ' '{print $1}')"
done
echo ""
echo "Ended at: `date "+%Y-%m-%d %H:%M:%S"`"
echo ""
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment