How to Protect SSH With Fail2Ban on Debian 12

Fail2Ban is a log-parsing application that protects Linux systems from various types of attacks, particularly those targeting services that interact with the internet, like SSH (Secure Shell). The primary goal of Fail2Ban is to monitor log files for suspicious activity and dynamically modify firewall rules to block the IP addresses of hosts exhibiting malicious behavior.

Update the System

First, update the system,

apt update -y

apt upgrade -y

Install Fail2ban

Install fail2ban using the below command,

apt install fail2ban

Install and Configure Firewall

Install UFW using the below command,

apt install ufw

Enable the UFW using the below command,

ufw enable

Allow SSH using the below command,

ufw allow 22

Reload the UFW using the below command,

ufw reload

Configure Fail2ban for SSH

Create a copy of the default configuration file:

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

Open the jail.local file in a text editor,

nano /etc/fail2ban/jail.local

Find the [sshd] section in the jail.local file and make sure the following configurations are set,

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
  • Configuration Settings
  • enabled: Set to true to enable the rule.
  • port: The port where your SSH service is running (default is ssh which is equivalent to port 22).
  • filter: The filter to be used (in this case, the sshd filter).
  • logpath: The path to the SSH log file.
  • maxretry: The number of failures before an IP is banned.

Save and close the file.

Restart the Fail2ban

Restart the fail2ban service to apply the changes,

systemctl restart fail2ban

Verify fail2ban Status using below command,

systemctl status fail2ban

Output:

root@vps:~# systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: active (running) since Fri 2023-11-10 22:05:03 UTC; 40min ago
       Docs: man:fail2ban(1)
   Main PID: 15873 (fail2ban-server)
      Tasks: 5 (limit: 4644)
     Memory: 14.0M
        CPU: 503ms
     CGroup: /system.slice/fail2ban.service
             └─15873 /usr/bin/python3 /usr/bin/fail2ban-server -xf start

Check the jail status.

fail2ban-client status sshd

To unban an IP.

fail2ban-client set sshd unbanip "IP address here"

To Ban an IP.

fail2ban-client set sshd banip "IP address here"

Once banned the IP Address you can try to log in using ban IP and you'll get below result,

root@vps:~# ssh root@<Your_IP_Address>
ssh: connect to host <Your_IP_Address> port 22: Connection refused

Done.


CrownCloud - Get a SSD powered KVM VPS at $4.5/month!
Use the code WELCOME for 10% off!

1 GB RAM / 25 GB SSD / 1 CPU Core / 1 TB Bandwidth per month

Available Locations: LAX | MIA | ATL | FRA | AMS