Home How ToInstall Fail2Ban to Protect SSH on Ubuntu

Install Fail2Ban to Protect SSH on Ubuntu

by Knowledge Base Linux
Install Fail2Ban to protect SSH on Ubuntu

What Is Fail2Ban and Why Do You Need It? – Install Fail2Ban to Protect SSH on

Every server with SSH exposed to the internet is probed by bots within minutes of coming online — thousands of login attempts per day is normal. Fail2Ban is an intrusion-prevention tool that scans log files for repeated failures and automatically bans offending IPs via firewall rules. Learning how to install Fail2Ban on Ubuntu (and AlmaLinux) is one of the highest-value hardening steps for any public server. This article covers Install Fail2Ban to Protect SSH on in detail.

Fail2Ban complements the firewall: while CSF or UFW controls who may connect, Fail2Ban reacts to how they behave — banning IPs that fail authentication too many times. It is lightweight, log-driven, and works with virtually any service that writes failed logins to a file.

Prerequisites – Install Fail2Ban to Protect SSH on

  • Ubuntu 22.04/24.04 or AlmaLinux 8/9 server with SSH exposed
  • Root or sudo access
  • A working firewall (UFW, firewalld, or iptables) — Fail2Ban inserts ban rules into it
Fail2Ban banning brute force SSH attacks

Step 1 – Install Fail2Ban

On Ubuntu/Debian:

sudo apt update
sudo apt install fail2ban -y

On AlmaLinux/Rocky/CentOS:

sudo dnf install epel-release -y
sudo dnf install fail2ban fail2ban-systemd -y

Enable and start the service:

sudo systemctl enable --now fail2ban
sudo systemctl status fail2ban --no-pager

Step 2 – Create a Local Jail Configuration

Never edit jail.conf directly — package updates overwrite it. Create jail.local instead, which overrides defaults:

sudo nano /etc/fail2ban/jail.local
[DEFAULT]
# Ban an IP for 1 hour after 5 failures within 10 minutes
bantime  = 1h
findtime = 10m
maxretry = 5
# Where to send notifications (optional)
destemail = [email protected]
action = %(action_mw)s

[sshd]
enabled = true
port    = ssh
# If you use a custom SSH port, set it here instead:
# port  = 2222
maxretry = 3
bantime  = 24h

Restart to apply:

sudo systemctl restart fail2ban

Step 3 – Verify SSH Protection Is Active

sudo fail2ban-client status
sudo fail2ban-client status sshd

Expected output shows the jail with zero bans initially:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
`- Actions
   |- Currently banned: 0
   |- Total banned:     0

Check that the firewall chain exists:

# UFW-based systems:
sudo iptables -L f2b-sshd -n --line-numbers 2>/dev/null || sudo ufw status | grep -i f2b
# firewalld-based systems (AlmaLinux):
sudo firewall-cmd --direct --get-all-chains | grep f2b

Step 4 – Test the Ban (Safely)

From a different machine (never your main admin IP), intentionally fail SSH logins 4+ times with a wrong password, then check from the server:

sudo fail2ban-client status sshd
# The test IP should appear under "Currently banned"

Unban it afterward:

sudo fail2ban-client set sshd unbanip 203.0.113.50

Always whitelist your own static IPs and monitoring hosts to avoid locking yourself out:

# in [DEFAULT] of jail.local:
ignoreip = 127.0.0.1/8 ::1 203.0.113.25

Step 5 – Protect Additional Services (Optional)

Fail2Ban ships with filters for many services. Enable a few common ones in jail.local:

[nginx-http-auth]
enabled = true

[nginx-botsearch]
enabled = true

# For WordPress login protection (requires the wordpress filter):
[wordpress]
enabled = true
logpath = /var/log/auth.log

List all available filters with ls /etc/fail2ban/filter.d/. Each jail needs its logpath to match where the service actually logs — check before enabling.

Troubleshooting

Fail2Ban is running but never bans

The usual cause is a wrong logpath or a backend mismatch. Check sudo fail2ban-client -d | grep logpath and confirm the file exists and contains failure lines. On systemd-only systems, ensure backend = systemd in the jail. Inspect /var/log/fail2ban.log for filter errors.

Bans don’t actually block traffic

Fail2Ban inserts rules into the active firewall. If you use Docker, its iptables rules can bypass Fail2Ban chains — same caveat as with UFW. Verify with iptables -L -n -v | grep <banned-ip> that packets hit the DROP/REJECT rule.

Legitimate users get banned

Raise maxretry/findtime, add their IPs to ignoreip, and consider longer bantime only for repeat offenders via recidive jail (ships disabled by default — enable it in jail.local).

Understanding Filters, Actions, and Jails

Three concepts drive Fail2Ban. A filter is a set of regular expressions that match failure lines in a log file (see /etc/fail2ban/filter.d/sshd.conf for the SSH patterns). A jail ties a filter to a log path plus ban parameters (maxretry, bantime, findtime). An action defines what happens on ban — typically inserting a firewall rule, optionally sending email.

You can preview which log lines a filter would catch without banning anyone:

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

The output shows match counts per regex. Use this whenever you write a custom filter — for example, to protect a Node.js app with its own log format, copy an existing filter, adjust the failregex lines, and validate with fail2ban-regex before enabling the jail.

Enabling the Recidive Jail for Repeat Offenders

Some bots rotate through thousands of IPs; others hammer from one IP for weeks. The recidive jail watches Fail2Ban’s own log and bans IPs that get banned repeatedly — with much longer durations:

# append to /etc/fail2ban/jail.local
[recidive]
enabled  = true
logpath  = /var/log/fail2ban.log
bantime  = 1w
findtime = 1d
maxretry = 5
sudo systemctl restart fail2ban
sudo fail2ban-client status recidive

A one-week ban for chronic offenders dramatically cuts log noise without affecting legitimate users, who never trigger even the first-level jails.

Fail2Ban on cPanel and Behind Cloudflare

Two common environments need special attention. On cPanel servers, use the cpanel jail family and point logpaths at /usr/local/cpanel/logs/; cPHulk already handles some brute-force protection, so coordinate maxretry values to avoid double-banning confusion. On servers behind Cloudflare, Fail2Ban sees Cloudflare’s edge IPs instead of real attackers — restore real IPs first (via mod_remoteip for Apache or set_real_ip_from for Nginx) or bans will hit Cloudflare ranges and break your site for everyone.

For Cloudflare specifically, consider the cloudflare action, which bans at the edge via API instead of locally:

# requires the cloudflare action config with your API token
action = cloudflare

Edge bans stop attackers before they reach your origin, saving bandwidth as well as log space.

Conclusion

You now know how to install Fail2Ban on Ubuntu and AlmaLinux, configure the SSH jail, test bans safely, and extend protection to web services. Combined with key-based SSH logins and SSH keys instead of passwords, Fail2Ban reduces brute-force noise to near zero. Review fail2ban-client status sshd weekly — a sudden spike in bans often means a new botnet is scanning your IP range. Upstream docs: fail2ban.org.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.