Security

Protect SSH from brute-force attacks with Fail2ban

Install Fail2ban, create a safe jail.local for SSH, check which addresses are banned and unban yourself if you mistype a password too often.

IntermediateLinux server2 min read

Fail2ban watches your logs for repeated failed logins and blocks the offending IP address in the firewall for a while. It cuts noise in your logs and makes password guessing far slower.

Note: Fail2ban is a useful extra layer, not a replacement for SSH keys. Keys plus disabled password logins stop guessing completely. See Disable root login and password authentication.

1. Install

Ubuntu and Debian:

Bash
sudo apt install -y fail2ban

AlmaLinux and Rocky Linux get it from EPEL:

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

2. Create jail.local

Never edit jail.conf; updates overwrite it. Put your settings in jail.local:

Bash
sudo nano /etc/fail2ban/jail.local
INI
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 ::1

[sshd]
enabled = true

If you have a fixed home or office IP, add it to ignoreip (space separated) so you can never ban yourself. If SSH runs on another port, add port = 2222 under [sshd].

Debian 12 only: Debian 12 logs to the systemd journal and has no /var/log/auth.log by default, so tell the jail to read the journal. Add this line under [sshd]:

INI
backend = systemd

3. Start it

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

4. Check bans

Bash
sudo fail2ban-client status
sudo fail2ban-client status sshd

The second command shows how many failures were seen and which IPs are banned right now.

Unban an address

Bash
sudo fail2ban-client set sshd unbanip 198.51.100.7

Tip: Banned yourself and cannot connect? Use the browser console from Open Control Panel on your service page, or wait for bantime to run out.

Troubleshooting

  • Fail2ban will not start: run sudo fail2ban-client -t to test the configuration. On Debian 12, a missing log file error means backend = systemd is not set.
  • No bans ever appear: check the jail reads the right port and log. sudo fail2ban-client get sshd logpath and sudo fail2ban-client get sshd journalmatch show what it watches.
  • Rules not visible in UFW or firewalld: Fail2ban adds its own chains or ipsets. Check sudo fail2ban-client status sshd rather than the firewall rule list.

Next steps

Was this guide helpful?

Still stuck?

Ask MdmHost AI for a quick answer, or open a ticket and our team will take a look. We are here 24/7.