Much of the content for this post comes from a post by “zcat” on fadorasolved.org in 2008.

I’ve only had to do this on CentOS so if you have any pointers for Ubuntu let me know.  I don’t happen to have any externally facing Ubuntu SSH servers to lock down at the moment :P

You can run these commands to see interesting data on sshd information:
Top 5 most recently attacked accounts:
lastb | awk ‘{print $1}’ | sort | uniq -c | sort -rn | head -5

Top 5 most attacked accounts:
awk ‘gsub(“.*sshd.*Failed password for (invalid user )?”, “”) {print $1}’ /var/log/secure* | sort | uniq -c | sort -rn | head -5

* Ubuntu’s log is /var/log/auth.log so change “/var/log/secure*” to “/var/log/auth*”

Top 5 attacker IP addresses:
awk ‘gsub(“.*sshd.*Failed password for (invalid user )?”, “”) {print $3}’ /var/log/secure* | sort | uniq -c | sort -rn | head -5

* Ubuntu’s log is /var/log/auth.log so change “/var/log/secure*” to “/var/log/auth*”

Thanks to the above commands you can see how desperately you need DenyHosts!  Here’s their homepage (–> link) and the author of DenyHosts is LOOKING FOR A JOB and you’d be NUTS to pass up on that talent!  On the SourceForge page they have newer versions, I haven’t installed the newer version yet because the version I installed below works well on CentOS 5.5 Final.

Download denyhosts:
wget http://centos.karan.org/el4/extras/stable/i386/RPMS/denyhosts-2.5-1.el4.kb.noarch.rpm

Install denyhosts:
rpm -i denyhosts-2.5-1.el4.kb.noarch.rpm

Turn denyhosts “on”:
/sbin/chkconfig denyhosts on

Edit your configuration file – modify as per your requirements:
nano /etc/denyhosts.conf

* Issues with some OS’s here’s what you need to do if you get this error: ImportError: No module named DenyHosts.python_version
* You need to find out how many python packages you have but if you DON’T CARE just run the below command
mv /usr/lib/python2.3/site-packages/DenyHosts /usr/lib/python2.4/site-packages/DenyHosts

Now start denyhosts *warning* this can take a while as denyhosts seems to search through your log files and depending on how you configured it; it’ll add all the offenders to the list which is great!

/sbin/service denyhosts start

Done!

* Update here for installing denyhosts on CentOS 6 *

Open a command prompt and add the EPL repository by typing:

su -c ‘rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm’

yum install -y denyhosts

* Reference – I used “For EL6”: http://fedoraproject.org/wiki/EPEL/FAQ#How_can_I_install_the_packages_from_the_EPEL_software_repository.3F