Protect SSH with Fail2ban on Ubuntu 24.04: step-by-step guide
How to install and configure Fail2ban on Ubuntu 24.04 to automatically block brute force attacks against SSH: dedicated jail, ban testing and unblocking an IP.
Anyone who manages a Linux server that can be accessed from the internet knows: as soon as the SSH port is exposed, automated bot access attempts begin to arrive that experience username combinations and repeat passwords. It's classicbrute force attack. A robust password or key authentication already reduces the risk, but does not prevent bots from continuing to knock, occupying resources and filling logs. The most common solution to curb the problem is calledFail2ban, and in this guide we see how to install it and configure it step by stepUbuntu 24.04 LTS (Noble Numbat).
What is Fail2ban and how it works
Fail2ban is a service (demon) that analyzes the system log files in real time — in our case those relating to SSH access — looking for patterns that indicate failed login attempts. When the same IP address exceeds a number of failed attempts at a given time interval, Fail2ban automatically intervenes by creating a firewall rule that blocks that IP for an established period. This monitoring and blocking mechanism is called jail(literally "prison"): each jail is dedicated to a specific service (SSH, a web server, a mail server, etc.) and has its own rules.
On Ubuntu 24.04, Fail2ban is available as an official package in the repositoryuniverse universe(version 1.0.2 at the time we write), so you do not need to add external repositories: as long as the universe repository is enabled, what happens by default in the standard installations of Ubuntu Server and Desktop.
Prerequisites
- A Ubuntu 24.04 serverwith SSH access and a user with privileges
sudo. - Access to the command line, locally or via SSH (be careful not to close the current session before verifying that the new rules do not block you too: later we will see how to avoid it).
- Optional but recommended: aActive firewall(UFW is the one included by default on Ubuntu), which Fail2ban will use as "armed arm" to apply the blocks.
1. Install Fail2ban
Update the package list and install Fail2ban with:
sudo apt update
sudo apt install fail2banAt the end of the installation, the service starts already active with the default configuration, but it is good to check the status immediately:
sudo systemctl status fail2banIf the system is not already enabled, activate it with:
sudo systemctl enable fail2ban2. Create custom configuration (jail.local)
Fail2ban reads its settings from different files. The main one,/etc/fail2ban/jail.conf, is overwritten to every update of the package: for this reasonmust never be changed directly. Customizations should be written in a separate file,jail.local, that Fail2ban reads after and that it always precedes the default settings. Create the file by copying the original file as a basis:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.localSection[DEFAULT], which applies to all jails unless otherwise indicated, find three key parameters that it is useful to understand before editing them:
- bans: how long an IP remains blocked once the attempt threshold is exceeded (e.g.
10mfor ten minutes,1hfor an hour). - find time: the time window within which failed attempts are counted (by default 10 minutes).
- Maxretry: the number of failed attempts allowed before the block (default 5).
For a more aggressive SSH jail towards bots, without risking too many false positives for a human user who mistakes password once, values likemaxretry = 4,findtime = 10mandbantime = 1hI'm a good starting point. If your fixed IP is known, you can also exclude it from controls by adding it to the lineignoreip(already present in section[DEFAULT]), separating it from others with a space: this avoids self-excluding it by mistake during testing.
3. Configure jail for SSH
Using the file you will find the section dedicated to SSH, which starts with[sshd]. Make sure this is set:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 4
findtime = 10m
bantime = 1hThe parameterenabled = trueis what actually activates protection for SSH: in the default configuration many jails are present but disabled, just to let the administrator choose which services to protect. If you have moved SSH on a different port from 22 (a common practice to reduce the background noise of the bots), remember to indicate it in the fieldport.
Save the file and restart the service because the changes have effect:
sudo systemctl restart fail2ban4. Make sure the jail is active
The main command to dialogue with Fail2ban It isfail2ban-client. To see the list of currently active jails:
sudo fail2ban-client statusFor details of SSH jail in particular — how many failed attempts it recorded and which IPs are currently blocked:
sudo fail2ban-client status sshdIt is also useful to keep an eye on the dedicated log, especially in the first days after activation, to understand how jail behaves in practice:
sudo tail -f /var/log/fail2ban.log5. Test the block
The most realistic way to test the jail is to try to connect to SSH from another machine (or from another terminal) by voluntarily entering a wrong password several times below, until you pass the thresholdmaxretryset. After the last failed attempt, the IP from which the links came should appear as bandit in the output offail2ban-client status sshd, and further attempts to connect from that same address will fall into the void until the end of thebantime.
Alternatively, if you prefer not to risk blocking your work session by mistake, you can manually force a test ban on a test IP (such as an address of your unused local network):
sudo fail2ban-client set sshd banip 192.0.2.106. Unlock an IP
It may happen that a legitimate IP is mistakenly banned, for example after some failed login attempts by you. To manually remove the block without having to wait for the expiry of thebantime, used:
sudo fail2ban-client set sshd unbanip 192.0.2.10By replacing of course the example address with the real one to unlock. The command has immediate effect: you do not need to restart the service.
A few more notices
- Never turn off the SSH session current currentbefore verifying that the new rules work: if possible, test by a second terminal while keeping an authenticated session open, so you can correct any configuration errors without losing access to the server.
- Integration with UFW: If you use UFW as a firewall, Fail2ban automatically detects it and leans on it to apply the blocks, without needing additional configurations in most cases.
- Authentication with SSH key: Fail2ban reduces the impact of automated attacks, but remains an additional defense level. Disable login with password for the only SSH keys, where possible, remains the most effective security measure ever.
- Growing bans: For those who want a more advanced level of protection, Fail2ban also supports abanswhich progressively increases for relapse IPs, through the option
bantime.increment: a useful insight once confidence with the basic configuration.
With these steps you have basic but effective protection against automated access attempts at SSH, without having to manually intervene whenever a bot knocks at your server door.
Official sources
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0