Debian and Ubuntu Install Fail2Ban to Automatically Block IPs for SSH Brute Force Protection Tutorial (Step-by-Step Guide)

Introduction

This tutorial details how to install and configure Fail2Ban on Debian and Ubuntu systems. It automatically identifies SSH brute force attacks by monitoring /var/log/auth.log and blocks malicious IPs, thereby protecting your server. Supports custom SSH ports, ban duration settings, and is suitable for beginners and system administrators.

1. Check if rsyslog is running normally

Fail2Ban's default configuration might not read logs correctly, so check if rsyslog is running.

ps -aux | grep [r]syslog

If the output is empty, rsyslog is not installed.

If not installed, install it first.

sudo apt update
sudo apt install rsyslog -y
sudo systemctl start rsyslog
sudo systemctl enable rsyslog

Restart the ssh service

sudo systemctl restart sshd

Check the rsyslog service status

sudo systemctl status rsyslog

If it shows Active: active (running), the installation was successful. If it's not running, start it with sudo systemctl start rsyslog.

2. Check for the log file

# Debian / Ubuntu:
ls /var/log/auth.log
# CentOS / Rocky / AlmaLinux:
ls /var/log/secure

If there is no output, confirm that rsyslog is correctly installed, as it handles and forwards system logs.

3. Install and start Fail2Ban

sudo apt install fail2ban -y
sudo systemctl enable --now fail2ban

4. Edit the configuration file to configure fail2ban

Edit the configuration file:

sudo nano /etc/fail2ban/jail.local

Enter the following content:

[sshd]
enabled = true
port    = 22         # <- Your SSH port
filter  = sshd
logpath = /var/log/auth.log   # debain
maxretry = 5            # <- Number of failures allowed
findtime = 600         # <- Within 10 minutes (600 seconds)
bantime  = 3600        # Ban for 1 hour

Press Ctrl+o, Enter, then Ctrl+x to save.

5. Restart related services

systemctl restart fail2ban

6. Verify successful configuration

sudo fail2ban-client status sshd

Through the above steps, Fail2Ban can effectively protect your server from SSH brute force attacks. Combined with measures like changing the default SSH port, disabling password login, and enabling a firewall, you can significantly enhance overall server security.