We’ve all been there and have had pesky bots filling up the SSH logs on our servers with irrelevant login attempts that often make it hard to actually do meaningful things with the logs.
Often this issue can be mitigated a bit by changing the port for the SSH daemon, which will definitely decrease the attack vector by a fair bit as most common bots only target the default ports.
All of the servers I am operating have their username changed to something more secure as this further reduces the attack vector. This made me think and recently I had the idea to implement Fail2Ban banning based on a blacklist of the root username. To implement this sort of rule, I took the following steps to configure it on a server running Fedora 36:
The first thing that you need to do is to install the Fail2Ban service on your system by running the below commands:
yum install fail2ban -y systemctl enable fail2ban systemctl start fail2ban
Create a file named “ssh-ban-root.conf” in your “/etc/fail2ban/filter.d/” folder with the following content:
[INCLUDES] before = common.conf [Definition] _daemon = sshd failregex = ^%(__prefix_line)spam_unix\(sshd:auth\):\s+authentication failure;\s*logname=\S*\s*uid=\d*\s*euid=\d*\s*tty=\S*\s*ruser=\S*\s*rhost=\S*\s*user=(root|admin)\s.*$ ignoreregex = [Init] maxlines = 10 journalmatch = _SYSTEMD_UNIT=sshd.service + _COMM=sshd
Create a basic jail configuration within the /etc/fail2ban-folder that uses the newly created filter:
[DEFAULT] bantime = 3600 findtime = 1800 maxretry = 5 backend = systemd ignoreip = 127.0.0.0/8 [ssh-ban-root] enabled = true filter = ssh-ban-root maxretry = 0 bantime = 15770000
Lastly, restart the fail2ban daemon to apply the changes we made to the configuration:
systemctl restart fail2ban