Skip to content

5. Add fail2ban

Fail2ban is an intrusion prevention software that protects your server from brute-force attacks. It works by monitoring log files for suspicious activity and temporarily banning IP addresses that show malicious signs like multiple failed login attempts.

Install fail2ban using apt:

sudo apt install fail2ban
sudo systemctl status fail2ban

Goto /etc/fail2ban/

cd /etc/fail2ban/
sudo cp jail.conf jail.local
# /etc/fail2ban/jail.local
bantime = 7d
findtime = 3h
maxretry = 4

Search for [sshd]

# /etc/fail2ban/jail.local
[sshd]
mode = aggressive
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
enabled = true
sudo systemctl restart fail2ban
cat /var/log/fail2ban.log

Check if ok, you should see some lines looking like that :

Creating new jail 'sshd'
2025-03-02 01:52:12,536 fail2ban.jail [2023]: INFO Jail 'sshd' uses pyinotify {}
2025-03-02 01:52:12,538 fail2ban.jail [2023]: INFO Initiated 'pyinotify' backend
2025-03-02 01:52:12,539 fail2ban.filter [2023]: INFO maxLines: 1
2025-03-02 01:52:12,552 fail2ban.filter [2023]: INFO maxRetry: 4
2025-03-02 01:52:12,553 fail2ban.filter [2023]: INFO findtime: 10800
2025-03-02 01:52:12,553 fail2ban.actions [2023]: INFO banTime: 604800
sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 12
| |- Total failed: 327
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 10
|- Total banned: 10
`- Banned IP list: 193.168.198.61 92.118.39.72 193.32.162.130 218.92.0.154 2.57.122.188 92.255.85.188 37.44.238.88 94.204.155.90 92.255.85.189 92.255.57.132

5.3. Steps to Unban an IP Address with Fail2Ban

Section titled “5.3. Steps to Unban an IP Address with Fail2Ban”
  1. Check the current status of a jail (e.g., sshd): Use the following command to check which IPs are banned:
sudo fail2ban-client status sshd

Look for the Banned IP list section to find the IP you want to unban.

  1. Unban the IP: To unban a specific IP address, use the unban command:
sudo fail2ban-client unban <IP_ADDRESS>

Replace <IP_ADDRESS> with the actual IP you want to unban. Example:

sudo fail2ban-client unban 193.168.198.61
  1. Verify the IP is unbanned: Check the jail status again to ensure the IP is no longer listed:
sudo fail2ban-client status sshd
  1. Restart Fail2Ban if necessary: If the IP remains banned after unbanning, restart Fail2Ban:
sudo systemctl restart fail2ban
  1. Check the status of the jail to see the banned IPs:
sudo fail2ban-client status <JAIL_NAME>

Replace <JAIL_NAME> with the actual jail name (e.g., sshd). 2. Use the unban command with --all to unban all IPs for that specific jail:

sudo fail2ban-client unban --all