How to block all root login attempts using denyhosts and or fail2ban?

Solution 1:

Depending on your distribution, edit /etc/fail2ban/jail.conf Update the [ssh] section to show something like this

[ssh]

enabled = true
port    = ssh
filter  = sshd
logpath  = /var/log/auth.log
bantime = 3600
maxretry = 3

Change the parameters as required. It won't specifically block root, but every attempt that fails. Be careful with maxretry and the bantime. If you fail with your own password, while maxtretry set to low, you block yourself for the bantime. Restart fail2ban.

I wouldn't try to block the IP forever as a lot of attempts come from dynamic IPs which could block some legitim users at a later point of time.

(Some distributions offer a jail.options file for your modifications. This is the preferred place to put your changes to as it shouldn't be affected by updates overwriting the conf.)

Solution 2:

Copy this code into a new file /etc/fail2ban/filter.d/sshd-root.conf:

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Definition]

_daemon = sshd

failregex = ^%(__prefix_line)sFailed (?:password|publickey) for root from <HOST>(?: port \d*)?(?: ssh\d*)?$

ignoreregex = 

PLEASE BE AWARE that you may have to edit the failregex to accurately identify failing root login attempts - use:

fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd-root.conf

to test that it identifies the correct log entries.

Then you need to edit your jail.local to make use of the new filter - add something like:

[ssh]

enabled  = true
port     = 1:65535
filter   = sshd-root
logpath  = /var/log/auth.log
bantime  = 604800
maxretry = 3

Obviously you should adjust these values according to your needs. The settings above will drop all incoming packets from the offending IP address after three attempts to log on as root, and will release the IP again after one week.

Solution 3:

Since the default /etc/fail2ban/filter.d/sshd.conf already has a regex for AllowUsers and DenyUsers...

...
^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers\s*$
^%(__prefix_line)sUser .+ from <HOST> not allowed because listed in DenyUsers\s*$
...

The following will:

  • Allow connections from exampleusername from external IPs
  • And root or any connections on local network (192.168.0.*)

The line `/etc/ssh/sshd_config':

AllowUsers exampleusername *@192.168.0.* *@localhost *@127.0.0.1

And in /etc/fail2ban/jail.conf :

ignoreip = 127.0.0.1/8 192.168.0.2/255
...
...
[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 1
findtime = 99999999 
bantime  = 99999999