How To Protect SSH with Fail2Ban: A Beginner’s Guide

Dive into our beginner's guide on securing SSH with Fail2Ban to safeguard your server from unauthorized access and brute-force attacks.

We will start with a metaphor. Imagine a fortress; while its tall walls and strong gates are built to keep out unwanted visitors, there will always be those who attempt to scale the walls or force the gates.

Similarly, our digital fortress, especially servers, faces persistent threats. One such gate to it is the Secure Shell (SSH), a protocol allowing secure remote access. So, just as gates require guards and monitoring systems, SSH requires protective measures against potential intruders.

Enter Fail2Ban โ€“ a vigilant sentry for your servers. It is one of the most effective shields against unauthorized access attempts, especially brute force.

What is Fail2Ban?

Fail2Ban is an open-source software tool that protects against automated malicious activities like brute-force server attacks.

One of its most valuable things is it acts proactive. In other words, instead of waiting for an attack, Fail2Ban offers an approach by identifying and blocking potential threats in real time.

The beauty of Fail2Ban lies in its simplicity and adaptability. While it is frequently used to secure SSH, its functionality isn’t limited to this protocol. Fail2Ban can be configured to monitor any service’s log files, providing a versatile solution for services like FTP, SMTP, web servers, and more.

Moreover, it is light on resources, so it doesnโ€™t burden your serverโ€™s performance – a critical consideration for servers handling high volumes of transactions or interactions.

How Fail2Ban Works

First, let us briefly explain what exactly is brute-forcing. It is a type of cyberattack in which an attacker attempts to gain unauthorized access to a system or service by systematically trying all possible combinations of passwords or encryption keys until the correct one is found.

In this regard, Fail2Ban monitors server logs for specific patterns indicative of such attacks โ€“ for example, repeated failed login attempts within a short time frame.

Based on predefined or custom rules, called โ€œfilters,โ€ Fail2Ban identifies patterns that suggest an attack and automatically triggers some predefined action. The most common one is to temporarily ban the IP address of the attacker, enforce firewall rules, and prevent further malicious attempts.

How Fail2Ban Works
How Fail2Ban Works

A key feature of Fail2Ban is the concept of โ€œjailsโ€ โ€“ specific monitoring policies for server services that combine a filter with actions. You can have different jails for different services (e.g., one for SSH, another for FTP, etc).

Each jail specifies which log file to monitor, what patterns to look for, and what actions to take when those patterns are detected.

After being banned for a set period, the IP address is automatically unbanned, allowing legitimate users who might have been temporarily blocked due to, for instance, forgetting their password to try again.

Installing Fail2Ban

Let’s now install Fail2Ban, which is quite simple, as you can see. Please use the command appropriate for the Linux distribution you are using.

Debian / Ubuntu

sudo apt install fail2ban

No further action is needed here since the service is automatically activated after installation.

RHEL / Rocky Linux / Alma Linux / Fedora

Since Fail2Ban resides in the EPEL repository, you must first add it to your system if you have not already done so:

sudo dnf install epel-release

Then install Fail2Ban and enable the service to start on boot:

sudo dnf install fail2ban
sudo systemctl enable fail2ban

openSUSE

sudo zypper in fail2ban

Configuring Fail2Ban for SSH

Once installed, the main configuration file is โ€œ/etc/fail2ban/jail.conf.โ€ However, best practices do not recommend modifying this directly. Instead, we will copy it by creating a new one with the extension โ€œ.local.โ€ Why? It is simple โ€“ this avoids merging problems when upgrading. So, letโ€™s do it.

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

When the Fail2Ban service is restarted, the โ€œjail.confโ€ file is read first, then โ€œjail.local,โ€ with later settings overriding earlier ones.

Now, let’s get to the fun part – configuring Fail2Ban. Open the “jail.local” file with your preferred terminal text editor.

sudo nano /etc/fail2ban/jail.local

Scroll down until you find the โ€œ[sshd]โ€ part, which looks similar to the one below.

Edit the 'jail.local' file.
Edit the ‘jail.local’ file.

Replace the existing contents of the “[sshd]” part with this:

[sshd]

enabled = true
port    = ssh
backend = systemd
maxretry = 3
findtime = 300
bantime = 3600
ignoreip = 127.0.0.1Code language: JavaScript (javascript)

The final version should look like the one shown below. Need to know what these options mean? Fear not โ€“ we’ve explained each one in detail further down.

Configuring Fail2Ban
Configuring Fail2Ban
  • enabled – Determines if the jail is active or not.
  • port – Specifies the port(s) you want to monitor. Accepts any port number or service name, e.g., “ssh,” “22,” “2200,” etc.
  • backend –  Specifies the backend used to get file modification. Since all modern Linux systems rely on systemdโ€™s logging service, we specify it as our backend.
  • maxretry – The number of failed attempts from an IP before it is banned.
  • findtime – The timeframe (in seconds) during which “maxretry” failed logins will lead to a ban. We have specified 300 seconds, i.e., 5 minutes.
  • bantime – The duration (in seconds) an IP should stay banned. In our case, we have set 3600 seconds, which means that in the next hour, any subsequent requests (not just to the SSH port) from this IP address will be blocked.
  • ignoreip – Allows you to whitelist IP addresses that should be ignored. This ensures that given IP addresses, even if they exceed the number of failed attempts specified in “maxretry,” will not be blocked.

That’s it. Save the file and exit, then restart the Fail2Ban service.

sudo systemctl restart fail2ban

Then, make sure everything is OK with the service.

sudo systemctl status fail2ban
Check if the service is up and running.
Check if the service is up and running.

Testing & Monitoring

Try logging in via SSH several times from another computer to the server on which you just installed and configured Fail2Ban. After the third failed attempt, your access should be blocked.

You’re already probably wondering how to monitor what’s happening inside. The good news is that Fail2Ban has excellent integrated tools for this purpose. To see IP addresses that are currently blocked, run the following command:

sudo fail2ban-client status sshd
Check the IP addresses blocked by Fail2Ban.
Check the IP addresses blocked by Fail2Ban.

If we go even further and review the iptables rules, we will find that Fail2Ban has created a chain (“f2b-sshd “) in which it has inserted the IP addresses in question. They will be automatically removed from there after the timeout period given in the “bantime” option.

sudo iptables -L -n
List iptables rules.
List iptables rules.

To manually unbans all IP addresses in all jails, execute the following:

sudo fail2ban-client unban --all

For a separate address only, your command should be:

sudo fail2ban-client unban <ip-address>Code language: HTML, XML (xml)

Of course, the fail2ban-client command has many other options, giving you great possibilities and flexibility. If you are curious to see them in detail, look here.

Important to Keep In Mind

Although Fail2Ban is excellent software, it is not as beneficial when your SSH server is configured to only public key authentication, as it is impossible to log in with a password. More about that here.

Additionally, remember that it does not replace the security a VPN would give you to access your server. Thus, unless absolutely required, avoid exposing your services to the internet.

Conclusion

Securing your server should always be a top priority. With SSH being a common entry point for many attackers, it requires particular attention.

Through this guide, we’ve walked through the straightforward steps of installing and configuring Fail2Ban to monitor and protect SSH from repeated malicious login attempts.

By setting up this tool, you’re adding an essential layer of security that can prevent potential intrusions. So, stay safe, stay updated, and always be proactive in your server’s defense strategy.

Thanks for your time! Finally, we recommend you check the Fail2Ban GitHub page for additional help or valuable information.

Bobby Borisov

Bobby Borisov

Bobby, an editor-in-chief at Linuxiac, is a Linux professional with over 20 years of experience. With a strong focus on Linux and open-source software, he has worked as a Senior Linux System Administrator, Software Developer, and DevOps Engineer for small and large multinational companies.

Think You're an Ubuntu Expert? Let's Find Out!

Put your knowledge to the test in our lightning-fast Ubuntu quiz!
Ten questions to challenge yourself to see if you're a Linux legend or just a penguin in the making.

1 / 10

Ubuntu is an ancient African word that means:

2 / 10

Who is the Ubuntu's founder?

3 / 10

What year was the first official Ubuntu release?

4 / 10

What does the Ubuntu logo symbolize?

5 / 10

What package format does Ubuntu use for installing software?

6 / 10

When are Ubuntu's LTS versions released?

7 / 10

What is Unity?

8 / 10

What are Ubuntu versions named after?

9 / 10

What's Ubuntu Core?

10 / 10

Which Ubuntu version is Snap introduced?

The average score is 68%