Jan 032010
 

Auto block IP’s with high connection counts via iptables;
via lovepig.org

netstat -npa --inet | grep :80 | sed 's/:/ /g' | awk '{print $6}' | sort | uniq -c | sort -n | while read line; do one=`echo $line | awk '{print $1}'`; two=`echo $line | awk '{print $2}'`; if [ $one -gt 100 ]; then iptables -I INPUT -s $two -j DROP; fi; done; iptables-save | grep -P '^-A INPUT' | sort | uniq -c | sort -n | while read line; do oneIp=`echo $line | awk '{print $1}'`; twoIp=`echo $line | awk '{print $5}'`; if [ $oneIp -gt 1 ]; then iptables -D INPUT -s $twoIp -j DROP; fi; done

This one-liner is quite effective when inserted into a file and run as a cronjob once per minute. Any IP with more than 100 concurrent connections – which, quite honestly, is far more than any one IP should ever have on a standard webserver – (unless you have bad code which makes to many calls) will be blocked via iptables. Running this script as a cronjob is extremely effective dealing with small-to-midsize DDoSes (too much traffic for Apache/whatever service to handle, but not saturating the pipe).

 Posted by at 5:39 pm