5. Add fail2ban
5.1. What is fail2ban?
Section titled “5.1. What is 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.
5.2. Installation
Section titled “5.2. Installation”Install fail2ban using apt:
sudo apt install fail2bansudo systemctl status fail2banGoto /etc/fail2ban/
cd /etc/fail2ban/sudo cp jail.conf jail.local# /etc/fail2ban/jail.localbantime = 7dfindtime = 3hmaxretry = 4Search for [sshd]
# /etc/fail2ban/jail.local[sshd]
mode = aggressiveport = sshlogpath = %(sshd_log)sbackend = %(sshd_backend)senabled = truesudo systemctl restart fail2bancat /var/log/fail2ban.logCheck 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' backend2025-03-02 01:52:12,539 fail2ban.filter [2023]: INFO maxLines: 12025-03-02 01:52:12,552 fail2ban.filter [2023]: INFO maxRetry: 42025-03-02 01:52:12,553 fail2ban.filter [2023]: INFO findtime: 108002025-03-02 01:52:12,553 fail2ban.actions [2023]: INFO banTime: 604800sudo fail2ban-client status sshdStatus 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.1325.3. Steps to Unban an IP Address with Fail2Ban
Section titled “5.3. Steps to Unban an IP Address with Fail2Ban”- Check the current status of a jail (e.g.,
sshd): Use the following command to check which IPs are banned:
sudo fail2ban-client status sshdLook for the Banned IP list section to find the IP you want to unban.
- Unban the IP: To unban a specific IP address, use the
unbancommand:
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- Verify the IP is unbanned: Check the jail status again to ensure the IP is no longer listed:
sudo fail2ban-client status sshd- Restart Fail2Ban if necessary: If the IP remains banned after unbanning, restart Fail2Ban:
sudo systemctl restart fail2ban5.4. Unban All IPs in a Specific Jail
Section titled “5.4. Unban All IPs in a Specific Jail”- 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