Thursday, September 23, 2010

Prevent SSH bots

Before completing the LAMP tutorial I will show some important considerations if you start working on a new VPS.

If you have been running a Linux server for a while you have probably noticed SSH bots trying to access your server. These bots try to break your server passwords and compromise your system. If you have strong passwords this is not a real big threat but it's annoying to see /var/log/auth.log grow with lines like this:

Sep 21 17:24:19 localhost sshd[2638]: Failed password for invalid user root from 113.6.252.48 port 42782 ssh2
Sep 21 17:24:24 localhost sshd[2640]: User root from 113.6.252.48 not allowed because not listed in AllowUsers
Sep 21 17:24:24 localhost sshd[2640]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=113.6.252.48  user=root


The problems is most of these boxes are already hacked boxes. So it's not easy to find the originating IP. Luckily these attacks are easy to stop, there are two easy solutions:

Option 1: change the SSH port
This option simply changes the port you connect to. It's a simple solution but it works really well. Attacks went down from a lot to zero on one of my VPSes. To change the port edit /etc/ssh/sshd_config and change Port 22 to Port 1234 for example. Restart the ssh server and you are done. Remember to test the connection to your VPS on the new port first before exiting your current SSH session.
vim /etc/ssh/sshd_config
/etc/init.d/ssh restart
Option 2: block attackers
The other option to stop these attackers is to block SSH attacks after a few failed attempts. There is a tool especially designed to stop all kinds of unwanted service access. It is called denyhosts. Installation is very simple on an Ubuntu or Debian system:
apt-get install denyhosts
And you're done! Well almost, you probably want to add your home/work IP to /etc/hosts.allow. This prevents denyhosts from blocking your home IP. This can happen when you had too many failed login attempts, even in the past (denyhosts thoroughly checks your login history).

You can tweak some values if you like in /etc/denyhosts.conf . I always change the setting DENY_THRESHOLD_VALID to 5. This determines the amount of failed attempts you can make on an existing and allowed user, before you are blocked. You don't have to change this value but it is a bit risky because the threshold for invalid accounts is 10. Using this knowledge an attacker can determine what system accounts exist. If you have edited the config file restart denyhosts for the changes to take effect.
/etc/init.d/denyhosts restart

1 comment: