iptables trick to limit concurrent tcp connections

This is sort of a self-documenting post, and a self-support group about ill-behaved tomcat apps.

Sometimes, you have multiple nodes accesing your MySQL server (or any kind of server, for that matter) concurrently. Eventually, software in one or more of these nodes might do nasty things (you know who you are buddy:))

MySQL provides a built in mechanism to limit concurrent connections, but this can only be set for the whole server, or on a per user basis. Unfortunatly, most of these setups use the same database user for all their nodes, so this feature can’t be used to confine any possible damage.

Enter your good friend iptables.

This isn’t perfect, but this little trick might help you while programmers take care of their business:

iptables -A INPUT -p tcp -m recent --rcheck --seconds 60 -j REJECT
iptables -A INPUT -p tcp --dport 3306 -m connlimit --connlimit-above 2 -m recent --set -j REJECT

(The number of seconds and the concurrency limit here are examples for testing only, set them to proper values if you use them in your servers!)

This two rules create a recent ‘bad guy’ list, and send any source that exceeds two concurent connections on tcp pot 3306 to this list for 60 seconds.

If used smartly with a proper timeout value for MySQL connections, this could be useful for situations such as the one I described.

Hope it helps you!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • email
  • Facebook
  • LinkedIn
  • Technorati

3 thoughts on “iptables trick to limit concurrent tcp connections

  1. Very Nice!

    I have been trying to find a way to prevent Apache from spawning too many child processes whenever some bad robot or hacker throws a bunch of concurrent requests at our website.

    This may just do the trick…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>