I assume that limits (you have mentioned in 2. and 3.) are applied to allowed connections to ssh/http/https.
Also, I assume that you want to apply limit to source IP regardless to destination port (i.e. if my IP gets banned because of SSH attempts, it is also banned for HTTP/HTTPS traffic).
In that case you need:
# flush all rules
iptables -F
# delete all user-defined chains
iptables -X
# set default policies
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
# allow packets from already estabilished connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state INVALID -j DROP
# limit connection to SSH to 1 per IP
iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 1 --connlimit-mask 32 -j REJECT --reject-with tcp-reset
# dtto for http
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 1 --connlimit-mask 32 -j REJECT --reject-with tcp-reset
# dtto for https
iptables -A INPUT -p tcp --syn --dport 443 -m connlimit --connlimit-above 1 --connlimit-mask 32 -j REJECT --reject-with tcp-reset
# create new chain called "my-limited-chain"
iptables -N my-limited-chain
# set limits (allow 50 connections, erase failed attempts at a speed 50 attempts per hour), accept satisfactory traffic
iptables -A my-limited-chain -m limit --limit 50/hour --limit-burst 50 -j ACCEPT
# drop traffic over the limits
iptables -A my-limited-chain -j DROP
# redirect new SSH/HTTP/HTTPS connections to my-limited-chain
iptables -A INPUT -p tcp --dport 22,80,443 -m state --state NEW -j my-limited-chain
Pay attention to:
- limiting HTTP and HTTPS traffic to only 1 connection could bring performance degradation, since majority of HTTP/S clients are using multiple connections to speed up loading of multiple elements web pages.
- this snippet completely ignores IPv6. If you are trying to fork this solution for IPv6, be careful about
--connlimit-mask
, since in IPv6 some machines can have 1 IPv6 address (--connlimit-mask 128
), and some machines can (and should) have even as much as 2^64 IPv6 addresses (--connlimit-mask 64
).
- with this exact rules, getting banned by "50/h" limit will forbid me from estabilishing new connections, but it won't shut my already estabilished connections