To effectively block an SSH Bruteforce, we need to slow down the rate an attacker can connect to our SSH Server.
Since most attacks are automated, the bots will likely give up after experiencing consistent timeouts after failing to login.
The script below will block an IP if it connects to SSH more than 3 times in 180 seconds (three minutes).
This is effective enough to chase off most bots. For more configuration (e.g failed SSH, instead of tracking the number SSH connections) you can look at utilizing Fail2Ban. (Article coming)
# /etc/sysconfig/iptables # Put the below entries in the *filter section. -A INPUT -m recent --set --name ssh --rsource -A INPUT -m recent ! --rcheck --seconds 180 --hitcount 4 --name ssh --rsource -j ACCEPT
If you’re interested in logging the denied IP’s, you can use the below. I’ve extracted the entire config file, so as to make it easier to understand.
[[email protected] ~]# cat /etc/sysconfig/iptables *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :SSH-INPUT - [0:0] :LOGDROP - [0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j SSH-INPUT -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT -A INPUT -j DROP -A FORWARD -j DROP -A SSH-INPUT -m recent --set --name ssh --rsource -A SSH-INPUT -m recent ! --rcheck --seconds 60 --hitcount 4 --name ssh --rsource -j ACCEPT -A SSH-INPUT -j LOGDROP -A LOGDROP -j LOG -A LOGDROP -j DROP
This is a fairly simple, and effective method to filter out unwanted SSH attacks. However, it could be made a bit more granular with the addition of log analysis and dynamic blacklisting of failed authentication attempts. (Fail2Ban)