Security

Protect SSH with Fail2ban: installation, testing and recovery

Limit repeated failed SSH logins, validate the jail and learn how to recover from an accidental ban.

6 min read
Server access gate blocking invalid keys

Fail2ban reads failure events and temporarily blocks matching IP addresses. It does not replace strong authentication or stop bandwidth-saturating attacks. This example covers SSH on Ubuntu 24.04 LTS.

1. Keep a recovery path

Leave your current SSH session open and verify provider-console access. Test key-based login in another terminal:

bashsudo sshd -T | grep '^port '
sudo journalctl -u ssh --since "10 minutes ago"

Use the real SSH port below. If a hosting panel already manages login protection, inspect its configuration before adding another policy.

2. Install packages

bashsudo apt update
sudo apt install -y fail2ban python3-systemd

Keep local settings separate from the package's jail.conf.

3. Create the jail

Create /etc/fail2ban/jail.d/sshd.local:

ini[sshd]
enabled = true
backend = systemd
port = 22
maxretry = 5
findtime = 10m
bantime = 1h
ignoreip = 127.0.0.1/8 ::1

This example chooses five matching failures within ten minutes and a one-hour ban. Consider shared office IPs before adopting the values. Add only a trusted static administrative IP to exclusions if appropriate.

The systemd backend reads the journal; do not add logpath here. See the configuration manual and upstream example.

4. Validate and activate

bashsudo fail2ban-client -t

Only continue if validation succeeds:

bashsudo systemctl enable --now fail2ban
sudo systemctl restart fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd

An active service does not prove events match. Generate a controlled failed login from a separate test connection you own and inspect the counter. Do not repeatedly fail through your only administrative connection.

5. Troubleshoot the layer

bashsudo journalctl -u fail2ban -n 50 --no-pager

A missing jail calls for checking configuration loading. A static counter calls for checking journal events and filters. A recorded ban that does not block traffic calls for checking the actual SSH port and firewall action.

6. Remove an accidental ban

From the console or another working session, replace the example IP:

bashsudo fail2ban-client set sshd unbanip 203.0.113.10

Remove the specific ban instead of flushing the firewall. Find the cause before restoring normal operation. The client manual documents these commands.

Back up your local configuration. Continue with server hardening and the separate DDoS guide.