Use fail2ban to defend against SSH brute force attack
Install fail2ban
sudo apt install fail2ban
Enable the fail2ban
service
sudo systemctl enable fail2ban
For the first time only, start manually
sudo systemctl start fail2ban
Set up the configuration file
cd
into the fail2ban
directory
cd /etc/fail2ban
Copy the default configuration file jail.conf
to jail.local
to take effect
sudo cp jail.conf jail.local
Start editing
sudo nano jail.local
The [DEFAULT]
section applies to all services supported by fail2ban
[DEFAULT]
. . .
# Double the ban time for the 2nd offence,
# double again for the 3rd, and so on
bantime.increment = true
bantime.maxtime = 1y
. . .
# If 10 failed attempt in 1 day, ban for 1 year
bantime = 10m
findtime = 10m
maxretry = 5
. . .
# If banned, ban from all ports
banaction = iptables-allports
. . .
# Ban only withought sending email notifications
action = %(action_)s
. . .
Specific config for SSH
[sshd]
# Add this line to enable this service
enabled = true
# Use the aggressive mode
mode = aggressive
. . .
Save and exit, then restart the fail2ban
service
sudo systemctl restart fail2ban
Check the status
sudo systemctl status fail2ban
Troubleshoot
For Debian
system, if getting ERROR Failed during configuration: Have not found any log file for sshd jail
, edit jail.local
as follows:
[sshd]
. . .
# Comment out the default backend
#backend = %(sshd_backend)s
# Use this instead
backend = systemd
# ref: https://github.com/fail2ban/fail2ban/issues/3292#issuecomment-1142503461
Then, restart the fail2ban
service
Check the status
Check the status of fail2ban
:
sudo fail2ban-client status
Check SSH:
sudo fail2ban-client status sshd
Check the last 100 lines of the log:
sudo tail -n 100 /var/log/fail2ban.log | less
Show the remaining time of a ban:
sudo fail2ban-client get sshd banip --with-time
Unban
sudo fail2ban-client set sshd unbanip <IP_ADDRESS>
Or, reset logs and database:
sudo fail2ban-client stop
sudo truncate -s 0 /var/log/fail2ban.log
sudo rm /var/lib/fail2ban/fail2ban.sqlite3
sudo fail2ban-client restart
Reference
https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-ubuntu-20-04
https://stackoverflow.com/questions/61715202/fail2ban-how-much-time-remaining-on-ban
https://denisrasulev.medium.com/server-protection-with-fail2ban-bfbe38a775b0#c0ec
Further reading for setting email notification
https://denisrasulev.medium.com/server-protection-with-fail2ban-bfbe38a775b0#c0ec