1. Blog
  2. Manuals

Fail2Ban: Installation, Configuration and Essential Commands

Fail2Ban: Installation, Configuration and Essential Commands

Fail2Ban reads service logs and temporarily blocks IP addresses that produce suspicious login attempts. For a server with SSH exposed it is the baseline protection against password guessing.

Installation

Ubuntu and Debian:

sudo apt update
sudo apt install fail2ban

AlmaLinux, Rocky Linux, RHEL (the package is in the EPEL repository):

sudo dnf install epel-release
sudo dnf install fail2ban

Enable the service:

sudo systemctl enable --now fail2ban

Where the settings live

Everything is in /etc/fail2ban/. The jail.conf file holds the defaults and is overwritten on package updates, so do not edit it. Put your own settings in jail.local or in separate files under /etc/fail2ban/jail.d/.

Global settings

Create a file with settings shared by all jails:

sudo nano /etc/fail2ban/jail.d/defaults.conf
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 198.51.100.7
bantime = 1h
findtime = 10m
maxretry = 5
bantime.increment = true
bantime.maxtime = 1w
  • ignoreip — addresses that are never banned. Add your own static IP here.
  • maxretry — failed attempts before a ban.
  • findtime — the window in which attempts are counted.
  • bantime — how long the ban lasts.
  • bantime.increment — each repeated ban of the same address lasts longer, up to bantime.maxtime.

Protecting SSH

sudo nano /etc/fail2ban/jail.d/sshd.conf
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 3

If SSH runs on a non-standard port, put its number in port.

Apply the settings:

sudo systemctl restart fail2ban

Banning through nftables

Modern distributions use nftables instead of iptables. To have Fail2Ban create rules in nftables directly, add to the [DEFAULT] section:

banaction = nftables-multiport
banaction_allports = nftables-allports

On systems with firewalld use banaction = firewallcmd-rich-rules. All available actions are in /etc/fail2ban/action.d/, filters in /etc/fail2ban/filter.d/.

Essential commands

List active jails:

sudo fail2ban-client status

Show a jail’s status and banned addresses:

sudo fail2ban-client status sshd

Ban an address manually:

sudo fail2ban-client set sshd banip 203.0.113.50

Unban an address:

sudo fail2ban-client set sshd unbanip 203.0.113.50

Remove all bans:

sudo fail2ban-client unban --all

Test whether a filter matches log entries:

sudo fail2ban-regex systemd-journal /etc/fail2ban/filter.d/sshd.conf

If you locked yourself out

Connect through the server console in your hosting control panel (VNC) and run fail2ban-client set sshd unbanip <your IP>. To prevent a repeat, add your address to ignoreip.

What Fail2Ban does not replace

Fail2Ban cuts log noise and stops simple brute force, but it does not protect a weak password that is guessed in the first few attempts. Use it together with SSH key login and a non-default SSH port.