>

Blocking SSH after failed logins: fail2ban step by step

Every server with a public IP address gets SSH login attempts. Usually these are bots guessing passwords for the root account or common usernames. fail2ban reads the logs and, once an address goes over the attempt limit, blocks it for a set time.

The settings below block an address after four failed attempts within ten minutes, for one hour. You can change the numbers; a sensible range is 3 to 5 attempts.

1. Installation

sudo apt install -y fail2ban

2. Configuration in jail.local

Do not edit jail.conf, because package updates will overwrite it. Put your own settings in jail.local:

sudo nano /etc/fail2ban/jail.local
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 4
backend  = systemd
ignoreip = 127.0.0.1/8 ::1 YOUR_IP

[sshd]
enabled = true
port    = ssh

What the values mean:

If SSH runs on another port, enter that number in the [sshd] section instead of ssh.

3. Start and check

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

The output shows the number of failed attempts (Currently failed) and the list of blocked addresses (Banned IP list). On a fresh server the list may be empty, but after a few hours the first addresses usually appear.

4. Unblocking an address

If you block yourself, for example after a few wrong passwords, unblock the address:

sudo fail2ban-client set sshd unbanip IP_ADDRESS

Before you experiment with the limits, add your fixed IP to ignoreip. If SSH stops working, the console in the VPS panel is still available.

5. Logs and monitoring

sudo tail -n 20 /var/log/fail2ban.log
sudo grep "Ban " /var/log/fail2ban.log | tail -n 20

The first command shows recent events, the second shows only bans. Check them once a week, especially after changing the settings.

6. Better protection: keys instead of passwords

fail2ban limits the effects of an attack but does not remove its cause. When you log in with an SSH key and password login is turned off, guessing a password is pointless. We describe how to do it in the SSH keys section of the guide on securing a VPS server.

Summary

fail2ban with sensible limits (3 to 5 attempts, a one-hour block) takes little effort and cuts down password guessing. Keep your IP in ignoreip, use SSH keys, and keep the console in the panel as your fallback.

The Chmura.tech team