All my servers are running SSH on non standard port (987) and I want to permanent block all IPs that try to connect to port 22.
I have now the rule iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -j DROP
but this rule do not add IP to iptables as blocked, only current connection is drop.
Can iptables add a IP as globaly blocked (disable connection on any other port) after first connection try on port 22?
Complete rules are:
iptables -N SSH
iptables -A SSH -p tcp -m tcp --dport 22 -m state --state NEW -j DROP
iptables -A SSH -p tcp -m tcp --dport 987 -m state --state NEW -m recent --rcheck --set --rsource
iptables -A SSH -p tcp -m tcp --dport 987 -m state --state NEW -m recent --rcheck --update --seconds 300 --hitcount 4 --rsource -j DROP
Thanks!
(I'm using iptables v1.8.4 (legacy))
UPDATE 1: Thanks to @A.B
Connections on port 22 managed by ipset with 86400 seconds IP block (1 day).
Connections on port 987 managed by iptables with a 300 seconds block after connection 4 tries (failed or success) in 300 seconds.
ipset create ssh22 hash:ip timeout 86400
iptables -N SSH22
iptables -A SSH22 -p tcp -m tcp --dport 22 -m state --state NEW -j SET --add-set ssh22 src
iptables -A SSH22 -m set --match-set ssh22 src -j DROP
iptables -N SSH
iptables -A SSH -p tcp -m tcp --dport 987 -m state --state NEW -m recent --name ssh --set --rsource
iptables -A SSH -m recent --name ssh --update --seconds 300 --reap --hitcount 4 --rsource -j DROP
UPDATE 2: Final iptables
working version:
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -s XXX.XXX.XXX.XXX/32 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 987 -m state --state NEW -m recent --set --name ssh --rsource
-A INPUT -m recent --update --seconds 300 --reap --hitcount 4 --name ssh --rsource -j DROP
-A INPUT -p tcp -m tcp --dport 22 -j SET --add-set ssh22 src
-A INPUT -m set --match-set ssh22 src -j LOG --log-prefix "[SSH 22] " --log-level 4
-A INPUT -m set --match-set ssh22 src -j DROP
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 987 -j ACCEPT
-A INPUT -i lo -p all -j ACCEPT
COMMIT