The short answer
Fail2Ban monitors SSH login failures and automatically bans offending IPs using firewall rules. By installing Fail2Ban and enabling its sshd jail, you can stop most brute‑force attacks on your server.
Why SSH brute‑force attacks matter
Repeated SSH login attempts are a common way for attackers to discover valid usernames and passwords. Each failed attempt may seem harmless, but when thousands of attempts are made from many IP addresses, the chances of a successful guess increase dramatically. Brute‑force attacks also generate noise in log files, making it harder to spot genuine issues, and they can consume CPU and network resources on a small VPS or dedicated server.
Because SSH is often the only remote entry point, an attacker who gains access can control the entire system, install malware, or pivot to other services. Manual monitoring of logs is impractical for busy teams, so an automated solution that detects repeated failures and temporarily bans the offending IPs is essential. This reduces the attack surface without requiring constant human oversight.
- Fail2ban watches /var/log/secure or /var/log/auth.log for repeated failures.
- It adds temporary iptables or nftables rules to block the source address.
- Bans can be configured to expire after a set period, allowing legitimate users to reconnect.
apt-get update && apt-get install -y fail2ban
# Enable the default sshd jail
echo '[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nmaxretry = 5' > /etc/fail2ban/jail.d/sshd.conf
systemctl restart fail2banAfter restarting fail2ban, check its status with systemctl status fail2ban and verify that the sshd jail is active. The log /var/log/fail2ban.log will show when IPs are banned.
Verify current SSH exposure
Begin by reviewing the SSH authentication logs. On most Linux distributions the relevant file is /var/log/auth.log (or /var/log/secure on RHEL‑based systems). Use grep to filter for SSH entries and look for repeated failures, e.g., grep "Failed password" /var/log/auth.log. If you see many attempts from the same IP or a pattern of rapid failures, it indicates a brute‑force scan. Keep the log view read‑only; the command shown is an example to run after confirming the file path on your server.
Next, inspect the active firewall rules for the SSH port (default 22). On systems using iptables you can list rules with iptables -L -n -v | grep :22. For firewalld use firewall-cmd --list-all. On Ubuntu with ufw run ufw status numbered. Look for rules that allow unrestricted access (e.g., 0.0.0.0/0 or ::/0). If the SSH port is open to the world, consider limiting it to known IP ranges or moving it to a non‑standard port before enabling fail2ban.
These checks give you a baseline of current exposure. If you notice a high volume of failed logins or an open SSH port, fail2ban can help mitigate the risk by automatically blocking offending IPs.
- Use
grep "sshd" /var/log/auth.logto isolate SSH events. - Count failures per IP:
awk '{print $11}' /var/log/auth.log | sort | uniq -c | sort -nr. - List firewall rules for port 22 with
iptables -L -n -v | grep :22.
grep "Failed password" /var/log/auth.log
iptables -L -n -v | grep :22The log command should show timestamps, usernames, and source IPs for each failed attempt. A large number of entries from a single IP or many different IPs in a short period signals a brute‑force attack. The firewall command will list any rule that permits traffic to port 22; if it shows 0.0.0.0/0 or ::/0, the SSH service is publicly reachable.
Install and configure Fail2Ban
Begin by updating the package index and installing Fail2Ban from the distribution's repository. Use the package manager that matches your Linux distribution; this ensures you receive updates and security patches automatically. After installation, the service will be present but not yet configured for any specific service. It is safe to start the service and enable it to launch at boot, but always review the default configuration files before making changes. The default jail configuration is conservative and will not interfere with legitimate SSH connections.
To protect SSH, enable the built‑in sshd jail. Copy the example local configuration file and adjust the settings to suit your environment, such as the ban time, the number of failed attempts, and the log path. The defaults provided by Fail2Ban are a good starting point: a 10‑minute ban after five failed attempts. After editing, reload the Fail2Ban service so the new jail becomes active. Monitor the log file to confirm that bans are being applied as expected.
- Update package index before installing.
- Install the
fail2banpackage from the official repo. - Copy
jail.conftojail.localbefore editing. - Enable the
sshdjail and set sensiblemaxretryandbantime. - Reload the service to apply changes.
sudo apt-get update && sudo apt-get install -y fail2ban
sudo systemctl enable fail2ban && sudo systemctl start fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo sed -i 's/^#\?\s*enabled\s*=.*/enabled = true/' /etc/fail2ban/jail.local
sudo systemctl reload fail2banCheck /var/log/fail2ban.log for entries showing the sshd jail started and any bans applied. Successful configuration will show messages like "Ban <IP>" when repeated failed logins occur.
Fine‑tune jail settings
The three core timers in a fail2ban jail – bantime, findtime and maxretry – work together to define how aggressively the service reacts to repeated login failures. bantime is the length of time an offending IP stays blocked; findtime is the window in which fail2ban counts failed attempts; maxretry is the number of failures that must occur within findtime to trigger a ban. Adjust these values to reflect the risk tolerance of your environment: a short bantime (e.g., 10m) limits disruption for legitimate users who mistype passwords, while a longer bantime (e.g., 24h) deters persistent attackers.
For a small business with a few administrators, a common starting point is findtime 600 seconds (10 minutes) and maxretry 5, which blocks an IP after five failures in ten minutes. If you notice frequent legitimate lockouts, increase maxretry or reduce bantime. Conversely, on a public-facing VPS that hosts many accounts, you might set findtime 300 seconds and maxretry 3, with a bantime of several hours, to stop rapid credential‑guessing. Always test changes on a non‑production system before applying them to live servers.
- Start with default values: bantime=10m, findtime=10m, maxretry=5.
- Increase bantime for high‑risk services or public servers.
- Lower maxretry if you see rapid brute‑force attempts.
- Adjust findtime to match your typical login patterns.
- Reload fail2ban after each change:
fail2ban-client reload.
fail2ban-client set sshd bantime 3600
fail2ban-client set sshd findtime 600
fail2ban-client set sshd maxretry 3
fail2ban-client reloadAfter reloading, monitor the fail2ban log (/var/log/fail2ban.log) for ban and unban events. Verify that legitimate users are not blocked excessively and that repeated failed attempts are being blocked as expected.
What to avoid when using Fail2Ban
When configuring Fail2Ban, avoid setting ban times that are too long or applying them to all IP ranges indiscriminately. An excessively permissive ban can lock out legitimate users, especially if the filter matches common scanning tools or internal monitoring IPs. Always scope the jail to the specific service and define a reasonable bantime, such as a few minutes to an hour, and use the ignoreip option for trusted networks. This prevents accidental denial of service for your own staff or monitoring systems.
Do not disable essential services or default system accounts while creating custom jails. Removing the default SSH jail or altering the sshd filter without testing can leave the server exposed to brute‑force attempts. Likewise, avoid using generic regular expressions that match unrelated traffic, as they may generate false positives. Test each jail in a staging environment, verify the log paths, and ensure that the action directives only affect the intended service.
- Set a reasonable
bantimeinstead of an indefinite block. - Use
ignoreipto whitelist internal and trusted addresses. - Limit the
maxretrycount to a realistic number for your environment. - Verify log file paths and patterns match the actual service logs.
- Keep the default SSH jail enabled and only modify it after testing.
fail2ban-client status sshd # shows current SSH jail stats
fail2ban-client set sshd banip 203.0.113.45 # manually add a test ban (example only)After applying changes, check the Fail2Ban status output to confirm the jail is active and the ban count reflects expected behavior. Look for the correct number of currently banned IPs and ensure no legitimate IPs appear in the list.
Test the protection
To confirm fail2ban is protecting SSH, generate a few intentional login failures from a test machine. Use a non‑existent user name or an incorrect password and attempt to connect repeatedly, for example three times in quick succession. Each failed attempt will be logged in /var/log/auth.log (or /var/log/secure on RHEL‑based systems). After the configured threshold is reached, fail2ban should create a temporary jail and add the source IP to the sshd jail's ban list.
After the simulated attacks, check the fail2ban status for the SSH jail. The command fail2ban-client status sshd will display the number of currently banned IPs and list them. You can also verify that the IP is blocked by trying to open a new SSH session from the same source; the connection should be refused or time out. Remember to run these commands on a test system or after taking a snapshot, as they affect network access.
- Use a separate test IP or VM to avoid locking yourself out.
- Ensure the fail2ban service is running:
systemctl status fail2ban. - Check the jail log:
journalctl -u fail2banfor any errors.
fail2ban-client status sshdIf fail2ban is working, the status output will show at least one banned IP and the SSH connection from that IP will be rejected. No further login attempts should succeed until the ban expires or is manually removed.
Maintain and monitor Fail2Ban
Regularly reviewing the Fail2Ban logs helps you understand which IP addresses are being blocked and why. Check the main log file at /var/log/fail2ban.log for entries about bans, unbans, and any errors. Look for repeated patterns that may indicate a new attack vector or a mis‑configured jail. Keeping an eye on the log also lets you verify that legitimate users are not being blocked inadvertently, allowing you to adjust ignore rules before they cause service disruption.
Keep Fail2Ban up to date with the latest security patches and bug fixes. Use your distribution's package manager to apply updates on a routine schedule, such as weekly or monthly. Before making any changes to the configuration files in /etc/fail2ban/, create a backup copy or snapshot of the directory. This ensures you can quickly restore a working setup if a new rule causes unexpected behavior or if a rollback is needed after an upgrade.
- Review
/var/log/fail2ban.logdaily for new ban entries. - Run
fail2ban-client statusto see active jails and banned IPs. - Schedule regular package updates (
apt update && apt upgradeoryum update). - Backup
/etc/fail2ban/before editing or after upgrades. - Test configuration changes with
fail2ban-client reload.
cp -a /etc/fail2ban /etc/fail2ban.backup && fail2ban-client status && tail -n 20 /var/log/fail2ban.logThe command shows a copy of the current configuration, the status of active jails, and the most recent log entries. Verify that the status lists the expected jails and that the log tail does not contain error messages. If everything looks normal, your Fail2Ban setup is operating correctly.
If you would rather have engineers do this for you, see Linux server management, Windows server management or emergency malware cleanup.
Questions people ask
How does Fail2Ban detect SSH brute‑force attempts?
Fail2Ban watches the SSH log file (e.g., /var/log/auth.log or /var/log/secure) for repeated failed login messages. It uses a regular expression defined in the sshd jail to count failures from the same source address within a configurable time window, then triggers a ban when the threshold is reached.
Can Fail2Ban block IPs on both iptables and firewalld?
Yes. Fail2Ban can add rules to both iptables (or nftables) and firewalld. The jail configuration includes a "action" line; you can use the built‑in actions like "iptables-multiport" for iptables or "firewalld‑rich‑rule" for firewalld, or combine them as needed.
What should I do if a legitimate IP gets banned?
First, verify the IP is indeed legitimate. Then unban it with the fail2ban-client command (e.g., `fail2ban-client set sshd unbanip <IP>`). After that, add the address to the jail’s ignoreip list so future bans skip it, and consider adjusting the jail’s maxretry or bantime to reduce false positives.
How often should I update Fail2Ban and its jail definitions?
Check the distribution’s package repository at least monthly and apply security updates promptly. Also review the fail2ban GitHub releases for new jail definitions or bug fixes. After updating, restart fail2ban and test that the sshd jail loads without errors.