Protect SSH With Fail2ban
Protect SSH With Fail2ban
Public SSH servers are constantly scanned and brute-forced. Changing
the SSH port is not real security by itself, but it reduces background
noise. fail2ban adds an actual defensive layer by watching
failed login attempts and temporarily banning abusive IP addresses.
This note records a minimal setup for SSH protection with
fail2ban and systemd logs.
Install Fail2ban
Arch Linux:
1 | sudo pacman -S fail2ban |
Debian/Ubuntu:
1 | sudo apt install fail2ban |
Enable the service:
1 | sudo systemctl enable --now fail2ban |
Optional: Change SSH Port
Edit the SSH daemon config:
1 | sudo vim /etc/ssh/sshd_config |
Set a non-default port. This article uses 22222 as an
example; replace it with your own value.
1 | Port 22222 |
Before restarting SSH, keep your current SSH session open. A bad config or firewall mistake can lock you out.
Validate the config:
1 | sudo sshd -t |
Restart SSH:
1 | sudo systemctl restart sshd |
Some distributions use ssh instead of sshd
as the service name:
1 | sudo systemctl restart ssh |
Test login from another terminal before closing the old session:
1 | ssh -p 22222 user@example.com |
Configure Fail2ban For SSH
Create a local jail config instead of editing the packaged defaults:
1 | sudo vim /etc/fail2ban/jail.d/sshd.local |
Minimal config:
1 | [sshd] |
If you keep SSH on the default port, use:
1 | port = ssh |
Restart fail2ban:
1 | sudo systemctl restart fail2ban |
Check Status
List enabled jails:
1 | sudo fail2ban-client status |
Check the SSH jail:
1 | sudo fail2ban-client status sshd |
View logs:
1 | sudo journalctl -u fail2ban -e |
On systems where fail2ban logs to a file:
1 | sudo less /var/log/fail2ban.log |
Unban An IP
If you accidentally ban yourself, unban the IP from another trusted session:
1 | sudo fail2ban-client set sshd unbanip 203.0.113.10 |
203.0.113.10 is a documentation example address. Replace
it with the real IP you need to unban.
Safer SSH Baseline
Fail2ban is only one layer. These SSH settings are usually worth enabling too:
1 | PermitRootLogin no |
After changing SSH config, always validate and restart:
1 | sudo sshd -t |
Notes
- Do not rely on port changes as the only protection.
- Prefer SSH keys over passwords.
- Keep an existing SSH session open while changing SSH and firewall settings.
- If a firewall is enabled, allow the SSH port before restarting SSH.
- Use
/etc/fail2ban/jail.d/*.localfiles for local overrides so package updates do not overwrite your changes.