Rate limiting connections with iptables and hashlimit (BASH)

It's sometimes desirable to limit the rate at which connections can be established with a server - whether to act as a defense against simpler DDoS's or simply to enforce usage limits

This snippet details how to use the hashlimit module to limit connection rates

Details

  • Language: BASH

Snippet

# This will limit everything that hits this chain to the chosen rate as one pool, rather than per client
iptables -N limitchain
iptables -A limitchain -m hashlimit --hashlimit-upto 50/sec --hashlimit-burst 20 --hashlimit-name pooled_conn_rate_limit --jump ACCEPT
iptables -A limitchain -j DROP

# This will enforce the limit on a per-ip basis (more useful really)
iptables -N limit-by-ip-chain
iptables -A limit-by-ip-chain -m hashlimit --hashlimit-mode srcip --hashlimit-upto 50/sec --hashlimit-burst 20 --hashlimit-name per_ip_conn_rate_limit --jump ACCEPT
iptables -A limit-by-ip-chain -j DROP

# Send new HTTPS connections into the per-ip rate limiting chain
#
# we only match new connections
iptables -I INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -j limit-by-ip-chain

# Make a subnet share a limit between them
iptables -I INPUT -p tcp --dport 443 -s 46.32.254.0/24 -m conntrack --ctstate NEW -j limitchain