Limit Simultaneous Connections in Apache


Yesterday I wrote about the comment storms that were happening on my blog. Many people made some great suggestions and I plan on implementing many of them in the coming weeks. I found something, however, that was pretty simple and, so far, seems to be working beautifully.

Mod_limitipconn is a small Apache module that allows you to limit the number of simultaneous connections from any given IP address for any particular resource or mime-type. It built and installed without a hitch--within 15 minutes I was in business. Here's the configuration I'm using to limit connections to the comment CGI:

<IfModule mod_limitipconn.c>
    <Location /mt/mt-comments.cgi>
        MaxConnPerIP 1
    </Location>
</IfModule>

Be sure you se ExtendedStatus to on in your configuration file or mod_limitipconn won't do anything. Note that I'm being very picky about where I limit connections (just the mt-comments CGI), so I limit it to one simultaneous connection per IP. If you set this up on a broader resource (like your whole blog) you might need more that one simultaneous connection for images and so on. Most browsers will make multiple connections to the same site to grab various components of a page.

Now, I see lines like this in my error_log:

[Fri Dec 15 06:57:43 2006] [error] 
  [client 219.95.92.19] Rejecting client at 219.95.92.19

I decided not to ban IP numbers, although banning them in bulk isn't too hard with mod_rewrite which I use for other reasons anyway. I did put together a little shell script to tell me the IP numbers of the offenders that others might find helpful.

#/bin/bash

Y=$(date +%Y)
M=$(date +%m)
D=$(date +%d)

grep $1 /web/logs/$Y/$M/$D/access.log 
 | sort  
   | awk -F\\  '{print $1}' 
     | uniq -c 
       | sort

(Remove the newlines in the pipe if you use this.) This program produces a report like this:

[web@lynx web]$ ~/bin/find_abuse mt-comment   
      1 125.22.112.78
      1 128.178.149.52
      1 132.177.218.74
          .
          .
          .
      6 85.255.119.132
      7 195.225.177.137
      7 195.225.177.40
      7 195.225.177.46
      7 85.255.119.74
      8 213.42.21.77

The first number is the number of connections to mt-comment (specified as an argument) from that IP address. Clearly thre's still some abuse going on, but it's not happening with simultaneous connections which is what was killing me.