What is Fail2ban?

Fail2ban is an intrusion prevention tool that monitors log files for suspicious activity (like repeated failed login attempts) and automatically bans offending IP addresses by updating firewall rules.

It is one of the most effective defenses against brute-force attacks on SSH, web servers, mail servers, and other services.

💡
How it works

Fail2ban watches log files → detects patterns of failure → adds a temporary firewall rule to block the attacker's IP → automatically unbans after a set time.

Installation

On Ubuntu/Debian:

sudo apt update
sudo apt install fail2ban

Start and enable the service:

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

Verify it is running:

sudo systemctl status fail2ban

Configuration: jail.local

Never edit /etc/fail2ban/jail.conf directly as it gets overwritten on updates. Instead, create a local override file:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

Key Parameters

bantime How long an IP stays banned (default: 10m). Use bantime = 1h for one hour.
findtime The time window to count failures (default: 10m). If maxretry failures happen within findtime, the IP is banned.
maxretry Number of failures before banning (default: 5).

Enabling the SSH Jail

Find the [sshd] section in jail.local and ensure it is enabled:

[sshd]
enabled = true
port    = ssh
logpath = %(sshd_log)s
maxretry = 5
bantime  = 1h
findtime = 10m

After changes, restart Fail2ban:

sudo systemctl restart fail2ban

Monitoring Fail2ban

Check overall status:

sudo fail2ban-client status

Check a specific jail:

sudo fail2ban-client status sshd

Example output:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 2
|  |- Total failed:     47
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 1
   |- Total banned:     8
   `- Banned IP list:   203.0.113.50

Unbanning an IP

If you accidentally ban a legitimate IP (like your own):

sudo fail2ban-client set sshd unbanip 203.0.113.50
⚠️
Do not lock yourself out

Before enabling Fail2ban on SSH, make sure you have console access or an alternative way to reach the server in case you accidentally trigger a ban on your own IP.

Testing Fail2ban

To verify Fail2ban is working, you can intentionally trigger failed logins from a test IP:

# From another machine, attempt SSH with wrong credentials
ssh baduser@your-server-ip
# Repeat until maxretry is exceeded

Then check if the IP was banned:

sudo fail2ban-client status sshd

Summary

In this tutorial, you learned:

  • What Fail2ban does and how it protects your server
  • How to install and enable Fail2ban
  • Configuring jail.local with bantime, findtime, and maxretry
  • Monitoring banned IPs and jail status
  • How to unban IPs and test your configuration
🎉
Your server is now protected!

Fail2ban will automatically block brute-force attackers. Check the logs periodically to see how many attacks it is stopping.