Security hardening with fail2ban

Security hardening with fail2ban

After deploying a VPS on the cloud, I realized how important hardening SSH is. Taking a look at the auth.log file revealed lots of connection attempts from different IPs that I don't own. This led me to explore one of the easiest and smartest ways to harden servers: the Fail2ban package. It blocks login attempts after a number of failed tries for a certain amount of time, all configurable to your needs.


Installation

The installation is fairly easy. Simply install the fail2ban package using your favorite package manager (apt for debian based distros):

sudo apt install fail2ban

Configuring fail2ban

The next step is to configure /etc/fail2ban/jail.conf with your favorite text editor:

sudo vi /etc/fail2ban/jail.conf

Then uncomment and add the following lines to the sshd section:

[sshd]
enabled = true
bantime = 4w
maxretry = 3

This blocks login attempts for 4 weeks after 3 failed attempts. A bit risky, but worth it.

It is also a good idea to backup this file to have a copy for future updates.
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

SSH Keys

The second best thing to do about SSH is to disable Password Authentication and use keys instead. If not possible, you can always consider adding a Multi-Factor Authentication (MFA) module like pam_google_authenticator to receive a One Time Password (OTP) on your phone to use it as a second password that changes every 30 seconds.

For me, I'll just disable Password Authentication for now:

sudo vi /etc/ssh/sshd_conf
PasswordAuthentication no

Enjoy the rest of your day!

Subscribe for new projects, tips and tricks!