Auto-iptables off IPs with high connection counts

via Paul (

[code lang=”bash”]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[/code]

This one-liner is quite effective when tossed 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 — will be blocked via iptables. 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).


  • Paul R

    February 7, 2010

    So my question is, what can be done to automate what should be done next?

    I’m thinking along the lines of something that would wait N minutes, bring the site back up, see if there’s still a problem, bring it back down if so, and loop.

  • kale

    February 7, 2010

    This is not something that should be automated so quickly, as it can very easily ban legitimate traffic in addition to malicious requests. In the past I’ve put the script into cron once a minute and kept close tabs on the server. Most (D)DoSes will end shortly after they receive too many timeouts from their target. The provided script is a stop-gap measure to help return some stability in the face of certain types of (D)DoSes (HTTP request-based, specifically). It will prove useless against other types of attacks.

    Apache has no part in this situation and may stay up the entire time if you so wish. I would only stop Apache in the face of a (D)DoS if the target site is extraordinarily resource intensive and will OOM if hit over and over (bad code).

Leave a Reply