If you have a server with a world facing ssh server, you’ve probably seen brute force attacks in your logs. Some machine starts hammering your ssh server, trying all sorts of logins (staff, root, a, admin, etc…) over and over and over again.
This is bad on a lot of fronts.
I use two simple iptables rules to block any IP address who has made more than 3 ssh connections or attempted connections within the past 3 minutes. So your would-be brute force attacker, gets three tries, and then is locked out for a minimum of three minutes. However, since 99% of the attacks are run by an automated bot, it will either: give up after the connection is refused multiple times, or it will keep hammering away on the closed door, which keeps the running count of attempted connections in the past 3 minutes over 3, keeping the door closed.
The rules are relatively simple.
/usr/sbin/iptables -I INPUT -p tcp --dport 22 -i eth0 -m state \ --state NEW -m recent --set /usr/sbin/iptables -I INPUT -p tcp --dport 22 -i eth0 -m state \ --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
The Debian Administration site has more details on how to rate-limit connections using IPTables
If you need to see what’s being done, you may want to log these drops. You can do so by setting up a log rule and then using these rules instead.
/sbin/iptables -N LOGDROP
/sbin/iptables -A LOGDROP -j LOG
/sbin/iptables -A LOGDROP -j LOGDROP
iptables -I INPUT -p tcp –dport 22 -i eth0 -m state –state NEW -m recent –set
iptables -I INPUT -p tcp –dport 22 -i eth0 -m state –state NEW -m recent –update –seconds 60 –hitcount 4 -j LOGDROP
Are the IPTables rules effective? In short yes.
The benefit of this approach is you don’t need any added software. IPtables is likely sitting on your server already if not already in use.
This approach does not lock accounts. A slow, distributed attack could fall under the radar.
For that, you would need something that can lock user accounts after failures. PAM includes a module called pam_tally that does just this. If you fail too many times, an account is locked.