Skip to content

Instantly share code, notes, and snippets.

@thefish
Last active December 23, 2015 03:59
Show Gist options
  • Save thefish/6577104 to your computer and use it in GitHub Desktop.
Save thefish/6577104 to your computer and use it in GitHub Desktop.
Autoban scripts for dumb DDoS (FreeBSD)
#!/bin/sh
while read count ip
do
test $count -gt 100 && echo " ipfw add deny all from $ip to me"
done
#!/bin/sh
cat /path/to/access.log | (
date=$(date -d "1 minute ago" +"%s")
while read line; do
[ "$(date -d"$(echo $line | cut -d']' -f1 | sed -e 's/.*\[//;s/\// /g;s/:/ /;')" +"%s")" -ge "$date" ] && echo $line
done)
#!/bin/sh
cat $1 |awk '{print $1}' |sort |uniq -c |sort -n | tail -n 100
@thefish
Copy link
Author

thefish commented Sep 16, 2013

These scripts were written 2 months ago during DDoS attack on our main frontend cluster. Some jokers were using quite a large botnet with IPs from Vietnam, Brazil and China to flood our servers with dumb "GET /index.php". Thanks to monitoring, we reacted quickly, and while our teamlead was negotiating DDoS protection contract, i wrote these scripts to quickly fend off most annoying bots by their IP address.

These scripts look up nginx' access.log, grab requests for last minute, sorts them by frequency and echo command to ban each ip with more than 100 requests per last minute.

Sure, our admin immediately transformed these scripts to one-liner, but it was too scary =)

//command in autoban.sh is FreeBSD-specific, you could change it if you like for your OS//

Usage:

./log-reader.sh | ./sorter.sh | ./ddos-autoban.sh | source /dev/stdin 

requires bash >=4.0 (for source from stdin)
You could add this command to crontab, for every minute execution. Offending ips will be banned automatically, just add the command to clean log, i.e. :>/path/to/access.log for example.

Do not forget to clean your ban table after attack has ended - big table slows down normal request processing a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment