Rate limiting connections with iptables and hashlimit

Published: 2020-10-02 16:46:34 +0000
Categories: 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


# 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 -m conntrack --ctstate NEW -j limitchain


iptables, firewall, rate, limit, rate-limit,

Latest Posts

Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter