Preventing unauthorized SSH access using Denyhosts

172

Once when I was doing a regular tail -f /var/log/messages, I came across a number of messages like these.

sshd[29924]: PAM_NAM: User donk unknown to the authentication module
sshd[29924]: Failed password for invalid user donk from ‘IP address here’ port 63410 ssh2

My SSH was under continuous attack! . Hmm.., until I found DenyHosts..

DenyHosts is a cool little python script by Phil Schwartz, which will parse the logs and identify repeated authentication failures and add the IP address of the offenders to /etc/hosts.deny, thus preventing them to connect to the server in the first place.

Installation

As the program was not available in the official repositories for SLES 10 SP1, I had to do some manual configuration. The installation steps were detailed in the ‘Readme.txt’ file within the package.

First, the python-devel package has to be installed. It is not installed by default

zypper install python-devel

Download the latest version of DenyHosts from http://denyhosts.sourceforge.net/

The version available at the time of my setup was 2.6. After uncompressing the sources

tar zxvf DenyHosts-2.6.tar.gz

cd DenyHosts-2.6

python setup.py install

The above step install the scripts and config files in /usr/share/denyhosts and in the site-packages of the python directory.

Configuration

Before proceeding the file denyhosts.cfg must be edited to suit the installation environment.The example config file is fully commented so it should be easy to follow. I had the following config

#/usr/share/denyhosts/denyhosts.cfg

SECURE_LOG = /var/log/messages
HOSTS_DENY = /etc/hosts.deny
LOCK_FILE = /var/run/denyhosts.pid

After this, I did the following step (as mentioned in the readme) to run denyhosts as a daemon during system start.

cd /usr/share/denyhosts

chmod 700 daemon-control

ln -s /usr/share/denyhosts/daemon-control /etc/init.d/denyhosts

/etc/init.d/denyhosts start

tail -f /var/log/denyhosts # will contain messages related to the start

If it is working as intended, enable it to start automatically by doing

chkconfig denyhosts on

It had happend occassionally that some valid IP’s are listed in /etc/hosts.deny. To prevent this, the genuine IPs from which users connect can be added to a file called ‘allowed-hosts’ in /usr/share/denyhosts/data. There is no specific format. Just add the IPs to the file one below the other. Also, edit denyhosts.cfg to change the following variable and restart denyhosts.

ALLOWED_HOSTS_HOSTNAME_LOOKUP=YES

That’s it..