Skip to content
STAGE33R

Guides · Hardening · 5 steps · reviewed

How to stop SSH brute-force attacks with fail2ban on Ubuntu and Debian

Any server with SSH open to the internet is attacked every few minutes. Keys-only login stops the attack from succeeding, and fail2ban stops it from filling your logs by banning the addresses that keep failing.

  1. Install it

    It starts and enables itself.

    sudo apt-get install -y fail2ban
    systemctl is-active fail2ban
  2. Create your own configuration

    Never edit jail.conf, it is replaced on updates. Put your settings in jail.local. Add your own address to ignoreip first so you cannot ban yourself.

    printf '[DEFAULT]\nignoreip = 127.0.0.1/8 ::1 YOUR_IP\nbantime = 1h\nfindtime = 10m\nmaxretry = 5\n\n[sshd]\nenabled = true\n' | sudo tee /etc/fail2ban/jail.local
  3. Reload and check

    The sshd jail should be listed, with the number of failures and bans.

    sudo systemctl restart fail2ban
    sudo fail2ban-client status
    sudo fail2ban-client status sshd
  4. Unban an address

    If you or a customer got banned.

    sudo fail2ban-client set sshd unbanip 203.0.113.9
  5. Make repeat offenders wait longer

    Optional: ban addresses that return for a week.

    printf '[recidive]\nenabled = true\nbantime = 1w\nfindtime = 1d\nmaxretry = 3\n' | sudo tee -a /etc/fail2ban/jail.local && sudo systemctl restart fail2ban

Common mistakes

  • Not setting ignoreip and banning your own office or CI address.
  • Thinking fail2ban replaces keys-only login or a firewall: it reduces noise, it does not make a weak password safe.
  • Using a non-default SSH port without telling fail2ban (set port in the jail).

How to undo it

Remove /etc/fail2ban/jail.local and restart fail2ban, or sudo apt-get purge fail2ban.

Sources

Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.