How to globally limit total number of TCP connections with iptables?

5,705

Solution 1

iptables -A INPUT -p tcp --syn -m connlimit --connlimit-above <your limit number> --connlimit-mask 0 -j DROP
iptables -A OUTPUT -p tcp --syn -m connlimit --connlimit-above <your limit number> --connlimit-mask 0 -j DROP

Solution 2

you can do it using iptables module "connlimit"

/sbin/iptables -A INPUT -p tcp --syn --dport $port -m connlimit --connlimit-above N -j REJECT --reject-with tcp-reset

example:

/sbin/iptables  -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
Share:
5,705
Gordon Morehouse
Author by

Gordon Morehouse

Updated on September 18, 2022

Comments

  • Gordon Morehouse
    Gordon Morehouse over 1 year

    I'm having quite a difficult time figuring out how to REJECT both inbound and outbound connections from a machine with iptables once the total number of TCP connections hits a global maximum without respect to source or destination port. All sources/destinations/ports must be included.

    Is this possible with iptables?

  • Gordon Morehouse
    Gordon Morehouse over 10 years
    I'm looking for an absolute global limit, though, for the entire machine - not just a single port.
  • Gordon Morehouse
    Gordon Morehouse over 10 years
    Thank you! I may have an opportunity to test this tonight and if it works well, I'll accept the answer! :)
  • Gordon Morehouse
    Gordon Morehouse over 10 years
    Works a treat, and (as should be obvious from the above) with iptables you can limit the total number of connections allowed in ANY chain, including input, output, and custom ones.