Limit max connections per IP address and new connections per second with iptables

  • We have an Ubuntu 12.04 server with httpd on port 80 and we want to limit:

    • the maximum connections per IP address to httpd to 10
    • the maximum new connections per second to httpd to 150

    How can we do this with iptables?

  • totti

    totti Correct answer

    6 years ago
    iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 15 --connlimit-mask 32 -j REJECT --reject-with tcp-reset  
    

    This will reject connections above 15 from one source IP.

    iptables -A INPUT -m state --state RELATED,ESTABLISHED -m limit --limit 150/second --limit-burst 160 -j ACCEPT  
    

    In this 160 new connections (packets really) are allowed before the limit of 150 NEW connections (packets) per second is applied.

    Can the above be set up to work on all ports, not just port 80?

    Are you sure this is per IP?

    To set this rule for all ports, just remove the --dport 80.

    The second rule does NOT work on "new connections". It explicitly affects existing ("ESTABLISHED") connections. To do new connections, you would want --state NEW. You might also consider using `-m conntrack --ctstate` in place of `-m state --state`. conntrack is new and improved vs. state.

    How to do this in Mac? I get: -bash: iptables: command not found

    the comment above for adding the 2nd rule to `NEW` connections - do not do that - it effectively turns your `INPUT` chain into a default `accept` !!!

    Could you please add more explanations regarding the single options. For example `--connlimit-mask 32` or `--reject-with tcp-reset`

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM