SSH Access – Prevent password guessing

27 07 2010

The Risk
In my case, I want outside SSH access to my server with minimal risk. What is that risk? Password guessing by script kiddies. Many young hax0rs run a few scripts every night that randomly try thousands of different passwords on machines that are accessible over SSH.

The moment your machine is reachable on port 22, these scripts find you and your logs fill up with lines like these:

Dec 22 04:25:54 asterix sshd[19886]: reverse mapping checking getaddrinfo for 59.163.108.38.static-chennai.vsnl.net.in [59.163.108.38] failed – POSSIBLE BREAK-IN ATTEMPT!
Dec 22 04:25:54 asterix sshd[19886]: Failed password for root from 59.163.108.38 port 52523 ssh2
Dec 22 04:31:18 asterix sshd[19892]: Failed password for root from 120.105.81.155 port 55401 ssh2
Dec 22 04:31:58 asterix sshd[19918]: Invalid user oracle from 120.105.81.155
Dec 22 04:31:58 asterix sshd[19918]: Failed password for invalid user oracle from 120.105.81.155 port 58104 ssh2

If you have a strong root password, you are probably reasonably secure, however in time someone might get in. That is your risk, right there.

The Solution
So how do you stop it? Since you are running Linux, very easily, if you enter the following two iptables commands as root:

# iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –set –name SSH
# iptables -A INPUT -i eth0 -p tcp –dport 22 -m state –state NEW -m recent –update –seconds 120 –hitcount 4 –rttl –name SSH -j DROP

(You might need to change the ‘eth0’ part into your external interface, likely eth1 or ppp0 or similar. )
What does this do? Whenever someone connects to your machines more than 3 times in two minutes, they are blocked for two minutes. This will effectively stop all password guessing scripts; they usually cannot handle this and crash or hang.