SSH Dictionary Attack Prevention with iptables
It is ideal to slow down the SSH dictionary attack when the infested host started to brute force the SSH authentication. There are many scripts/user-land daemons that perform monitoring and blocking. I prefer to use something that has less demand in memory/CPU usage. IPTables module provides a kernel level solution with little overhead.
This is what I have in my iptables rules:
iptables -N SSH_CHECK iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH_CHECK iptables -A SSH_CHECK -m recent --set --name SSH iptables -A SSH_CHECK -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
What it does is:
Create a new chain SSH_CHECK, and all incoming SSH connection (TCP port 22) will go into this chain to test the condition.
Condition is, for any source IP address there cannot be more than 3 SSH connection attempts within a 60 seconds window.
If condition has been met, then all packets from that source IP address will be dropped.
That source IP can only connect again if condition is cleared again, i.e. there has been 60 seconds of quiet time.
I found it quite effectively and dramatically reduce bot attacks on SSH port. Still, it is important to remove shell access from users that no longer require it, and choose sensible random password that is difficult to guess.
Log all iptables messages to /var/log/firewall
Add the following line to your /etc/syslog.conf file