DenyHosts is a log-based intrusion prevention security tool for SSH servers written in Python. It is designed to prevent brute-force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses using /etc/hosts.deny and sbin/iptables on Linux server. In this tutorial, you will learn how to install DenyHosts a python program that automatically blocks ssh attacks by adding entries to /etc/hosts.deny file.
The tutorial is tested on Ubuntu 17.04 server installation.
1. First lets install the software:
$ sudo apt-get install denyhosts
Code language: JavaScript (javascript)
2. Add your addresses to hosts.allow to ensure that they are not blocked.
sudo pico /etc/hosts.allow
Example of how to add more than one address:
sshd: 212.22.112.113 , 10.20.133.3 , 192.168.0.1 , 127.0.0.1
Code language: CSS (css)
3. Now lets configure the denyhosts configuration file:
$ sudo pico /etc/denyhosts.conf
Make sure SECURE_LOG set as follows:
SECURE_LOG = /var/log/auth.log
HOSTS_DENY set as follows:
HOSTS_DENY = /etc/hosts.deny
Block only sshd:
BLOCK_SERVICE = sshd
Deny threshold limit for login attempts:
DENY_THRESHOLD_INVALID = 5
DENY_THRESHOLD_VALID = 10
DENY_THRESHOLD_ROOT = 1
DENY_THRESHOLD_RESTRICTED = 1
Block incoming connections using the Linux firewall IPTABLES:
IPTABLES = /sbin/iptables
Code language: PHP (php)
4. ENABLE DenyHosts service:
$ sudo systemctl enable denyhosts.service
You will se something like this:
Executing /lib/systemd/systemd-sysv-install enable denyhosts
5. Restart DenyHosts service:
sudo /etc/init.d/denyhosts restart
6. Some commands to check if all is working and to list addresses added to blocklist:
$ sudo grep 'something' /var/log/denyhosts
$ sudo tail -f /var/log/denyhosts
$ sudo cat /etc/hosts.deny
sudo iptables -L INPUT -n -v | grep DROP
Code language: JavaScript (javascript)
Attention:
Please note that the DenyHosts is restricted to connections using IPv4. It does not work with IPv6 based IP address. Another option is to use the iptables command to see blocked IP address:
Enable centralized synchronization support?
The DenyHosts version 2.0 and above support centralized synchronization, so that repeat offenders are blocked from many computers. The site xmlrpc.denyhosts.net gathers statistics from computers running the software. Synchronization disabled by default. To enable synchronization, enter:
$ sudo pico /etc/denyhosts.conf
Then add:
SYNC_SERVER = http://xmlrpc.denyhosts.net:9911
Code language: JavaScript (javascript)
And restart:
$ sudo /etc/init.d/denyhosts restart