Fail2Ban on Ubuntu Server

Fail2Ban falls under the category of security tools. It is primarily used to protect against various types of automated attacks, especially brute-force attacks on login systems. It works by monitoring log files of applications (such as SSH, FTP, web servers, and many others) and looks for patterns that match repeated login attempts or other suspicious activities. Once Fail2Ban detects certain behavior that meets the blocking rules (such as a certain number of unsuccessful login attempts within a short time frame), it can automatically update firewall rules to block the attacker's IP address for a certain period.

Install, configurate & manage Fail2Ban

  • Install the package
    sudo apt install fail2ban
  • Open fail2ban configuration file
    sudo nano /etc/fail2ban/jail.d/ssh.local

    Set configuration for the tool. See the sample configuration below:

    [sshd]
    enabled = true
    banaction = ufw
    # ufw ssh port
    port = 22
    filter = sshd
    logpath = %(sshd_log)s
    # maximum number of failed login attempts from the given IP
    maxretry = 5
    # Time window within which invalid attempts are added.
    findtime = 3600
    # ban time in seconds (86400 = day)
    bantime = 86400
  • Start fail2ban
    sudo fail2ban-client start
    sudo fail2ban-client reload
    sudo fail2ban-client add sshd # This may fail on some systems if the sshd jail was added by default
  • Set fail2ban to automatically start on server startup
    sudo systemctl restart fail2ban
    sudo systemctl enable fail2ban

Check fail2ban state

sudo fail2ban-client status
sudo fail2ban-client status sshd

Unban IP

#sample
# sudo fail2ban-client set [jail] unbanip [IP]

#unban IP 192.168.1.100
sudo fail2ban-client set sshd unbanip 192.168.1.100