Limiting number of connections per IP with ufw

This is a personal reminder post.

The easiest attack one can perform on a web server is opening all the connections and do nothing with it. iptables fortunately has a “connlimit” module to avoid this. If you’re using ufw like me you will want to keep your good integration with it.

In the /etc/ufw/before.rules file, after these lines:

1
2
3
4
5
6
7
# Don't delete these required lines, otherwise there will be errors
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
# End required lines

You can add this to limit the number of concurrent connections:

1
2
# Limit to 10 concurrent connections on port 80 per IP
-A ufw-before-input -p tcp --syn --dport 80 -m connlimit --connlimit-above 10 -j DROP

And this to limit the number of connections:

1
2
3
# Limit to 20 connections on port 80 per 2 seconds per IP
-A ufw-before-input -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
-A ufw-before-input -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 2 --hitcount 20 -j DROP

This second rules might create some issues with http clients that don’t support keep-alive (is there any?).
If you want to do some benchmarks (with ApacheBench for example), you need to enable the keep-alive and set the max number of keep-alive requests per connection very high (or unlimited).
In apache config it is set with:

1
MaxKeepAliveRequests 0

2 thoughts on “Limiting number of connections per IP with ufw”

Leave a Reply

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