All Snippets

Protect SSH with Fail2Ban

Install and configure Fail2Ban to automatically block brute-force SSH attacks on your Linux server.

Brute-force SSH attacks are constant on any public-facing server. Fail2Ban monitors log files and automatically bans IPs that show malicious patterns — repeated failed login attempts, for example.

Why Fail2Ban

  • Automatically blocks IPs after repeated failed SSH logins
  • Configurable ban duration, retry limits, and detection windows
  • Works with iptables, nftables, or firewalld
  • Supports more than just SSH — also Nginx, Apache, Postfix, and others

Install

Ubuntu / Debianbash
1
sudo apt update && sudo apt install -y fail2ban
RHEL / CentOSbash
1
sudo yum install -y epel-release
2
sudo yum install -y fail2ban
Start and enablebash
1
sudo systemctl enable --now fail2ban

Configure SSH Jail

Never edit /etc/fail2ban/jail.conf directly — it gets overwritten on upgrades. Use a local override instead:

/etc/fail2ban/jail.localini
1
[DEFAULT]
2
bantime  = 1h
3
findtime = 10m
4
maxretry = 5
5
banaction = iptables-multiport
6
 
7
[sshd]
8
enabled  = true
9
port     = ssh
10
logpath  = %(sshd_log)s
11
maxretry = 3
12
bantime  = 24h

What Each Setting Does

SettingMeaning
bantimeHow long an IP stays banned (1h, 24h, 1d, or -1 for permanent)
findtimeTime window to count failures — 5 failures in this window triggers a ban
maxretryNumber of failures before banning
banactionFirewall backend to use (iptables-multiport, nftables, firewalld)
logpathLog file to monitor — %(sshd_log)s resolves to the correct path per distro
Restart after config changesbash
1
sudo systemctl restart fail2ban

Managing Bans

Check banned IPs and statusbash
1
# Status of the SSH jail
2
sudo fail2ban-client status sshd
3
 
4
# Unban a specific IP
5
sudo fail2ban-client set sshd unbanip 203.0.113.42
6
 
7
# Ban an IP manually
8
sudo fail2ban-client set sshd banip 203.0.113.42

Add your own IP to the ignoreip list in jail.local so you don't lock yourself out: ignoreip = 127.0.0.1/8 ::1 YOUR.IP.HERE

Hardening Checklist

Beyond Fail2Ban, stack these SSH protections:

  1. Disable password auth entirely — use key-based auth only
  2. Disable root login via SSH (PermitRootLogin no)
  3. Move SSH to a non-standard port (reduces log noise)
  4. Use AllowUsers or AllowGroups to restrict who can SSH in
/etc/ssh/sshd_config tweaksbash
1
PermitRootLogin no
2
PasswordAuthentication no
3
MaxAuthTries 3
4
AllowUsers deployer admin
Restart SSH after changesbash
1
sudo systemctl restart sshd

Before disabling password auth, verify your SSH key works by opening a second terminal and connecting with your key. If you disable passwords and your key doesn't work, you're locked out.

For more granular rate-limiting, combine Fail2Ban with UFW or cloud-level firewalls (AWS Security Groups, GCP Firewall Rules). Defense in depth.