How to Set Up Fail2ban for SSH on Linux
Protect your Linux server against repeated SSH authentication failures with Fail2ban. Learn how to install it, enable the SSH jail, configure ban thresholds, verify blocked IP addresses, and troubleshoot common problems on Ubuntu, Debian, and RHEL-based systems.
sshd jail, configure reasonable retry and ban thresholds, and start the service. Verify the jail with sudo fail2ban-client status sshd. Fail2ban monitors authentication failures and invokes a firewall action to block offending IP addresses according to your policy.Add an Automatic Defense Against SSH Brute-Force Attempts
Public-facing SSH servers can receive repeated login attempts from automated scanners and bots. Fail2ban watches relevant authentication logs and temporarily blocks IP addresses that exceed your configured failure threshold. Combined with SSH keys, restricted users, updates, and firewall rules, it adds another useful layer of defense.
FOR SSHMONITOR • DETECT • BAN
Monitor SSH Failures
Use the SSH jail to detect repeated authentication failures in supported logs or the systemd journal.
Apply Temporary Bans
Define how many failures trigger a ban, the observation window, and the ban duration.
Verify and Maintain
Check jail status, inspect logs, test your firewall action, and recover legitimate access safely.
What Is Fail2ban?
Fail2ban is an open-source intrusion-prevention tool that monitors log events for patterns associated with repeated authentication failures. When a configured jail detects enough matching failures from a source IP address within a specified period, Fail2ban runs an action to block that address for a configured duration.
For SSH protection, the commonly used jail is named sshd. A jail combines a filter that recognizes relevant log entries with an action that applies the ban. The exact behavior depends on your Fail2ban version, distribution configuration, logging backend, and firewall action.
| Term | Meaning | Example |
|---|---|---|
| Jail | Configuration for a service, filter, and action. | [sshd] |
| Filter | Identifies log entries that match the configured failure patterns. | SSH authentication failures |
| maxretry | Number of matching failures that trigger a ban within the window. | 5 |
| findtime | Window during which failures are counted. | 10m |
| bantime | Initial duration for which an offending address is banned. | 1h |
| Action | Mechanism that applies and removes the ban. | Compatible firewall action |
Requirements and Safety Checks
- A Linux server with administrative privileges.
- An SSH server such as OpenSSH, with authentication events logged.
- Package-manager access to install Fail2ban.
- A supported firewall and compatible Fail2ban ban action.
- A second trusted session or console/recovery access in case a legitimate client is blocked.
- Knowledge of your actual SSH port and server logging configuration.
The commands below cover Ubuntu/Debian and Rocky Linux/AlmaLinux-style systems. Package names, service behavior, firewall tools, and logging defaults can differ by distribution and version.
Step 1: Install Fail2ban
Install on Ubuntu or Debian
sudo apt update
sudo apt install fail2banThe distribution package normally provides the Fail2ban service, client utility, default configuration, filters, and actions. Review the package version and local distribution documentation if your server uses a customized image.
Install on Rocky Linux or AlmaLinux
sudo dnf install epel-release
sudo dnf install fail2banOn RHEL-compatible systems, the availability of Fail2ban and its repository can depend on the operating-system release and enabled repositories. If the package is not found, check the supported repositories for your exact distribution and version rather than installing an untrusted package.
Check that the client is available
fail2ban-client versionThe output should show the installed Fail2ban version. If the command is not found, confirm the package installation and the executable’s location.
Step 2: Configure the SSH Jail
Fail2ban recommends keeping distribution-provided .conf files intact and placing local customizations in a .local file. This helps preserve your settings during package upgrades.
Create a local SSH jail configuration
On common Linux package installations, you can create a dedicated local file under /etc/fail2ban/jail.d/:
sudo nano /etc/fail2ban/jail.d/sshd.localAdd the following baseline configuration:
[sshd]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1hSave the file. This configuration enables the SSH jail, counts five matching failures within ten minutes, and sets an initial one-hour ban. These are example starting values; adjust them to your operational requirements.
Alternative: use jail.local
If you prefer a single local configuration file, you can instead edit:
sudo nano /etc/fail2ban/jail.localAdd the same [sshd] section. Use either this method or the dedicated sshd.local file, and avoid maintaining conflicting duplicate settings in multiple files.
.local files or appropriate local snippets rather than editing the packaged jail.conf directly. Later-loaded local configuration can override packaged defaults. Always inspect your actual configuration when a value does not behave as expected.Step 3: Understand Ban Thresholds
Before enabling a ban policy on a production server, understand the three most important settings.
maxretry = 5
Sets the number of matching failures needed to trigger a ban within the configured observation window. Lower values react faster but can increase accidental bans.
findtime = 10m
Sets the window in which matching failures are counted. Use a duration that matches your expected authentication behavior and risk tolerance.
bantime = 1h
Sets the initial ban duration. A longer ban can reduce repeated attempts but may disrupt legitimate users behind shared or changing IP addresses.
ignoreip
Defines trusted addresses or networks that should not be banned. Add only carefully verified management addresses and avoid broad exceptions.
Example starting policy
| Setting | Example | Operational effect |
|---|---|---|
maxretry | 5 | Ban after five matching failures during the observation window. |
findtime | 10 minutes | Count failures within a ten-minute period. |
bantime | 1 hour | Block the offending address for the initial one-hour ban period. |
These values are examples, not universal security recommendations. Consider your support processes, VPN or NAT architecture, authentication policy, and the consequences of blocking a shared IP address.
Step 4: Check Log and Backend Compatibility
Fail2ban must be able to read the SSH authentication events generated by your system. Some distributions write these events to files such as /var/log/auth.log or /var/log/secure; others may use the systemd journal without maintaining the expected log file.
Check the SSH service logs
On Ubuntu or Debian, you can inspect the journal with:
sudo journalctl -u ssh --since "1 hour ago"On systems using the sshd unit, try:
sudo journalctl -u sshd --since "1 hour ago"Some systems also record authentication events in a general authentication log or system log. Confirm where your SSH service actually records failed logins.
Use the systemd backend when appropriate
If your system logs SSH authentication events to the systemd journal and Fail2ban reports that it cannot find the expected log file, edit your local SSH jail file:
sudo nano /etc/fail2ban/jail.d/sshd.localUse this configuration for a systemd-journal setup, keeping your existing thresholds:
[sshd]
enabled = true
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1hOnly choose this backend if the required systemd journal integration is available and appropriate for your system. Depending on the distribution and Python packaging, the systemd bindings may also be required.
Step 5: Enable and Start Fail2ban
Enable the service at boot
sudo systemctl enable --now fail2banThis command enables Fail2ban to start automatically and starts the service immediately.
Check the service status
sudo systemctl status fail2ban --no-pagerConfirm that the service is active. If it fails to start, inspect the logs before changing the configuration again:
sudo journalctl -u fail2ban -n 100 --no-pagerStep 6: Verify the SSH Jail
Display the active jails
sudo fail2ban-client statusLook for sshd in the list of active jails. If it is absent, inspect the configuration files and Fail2ban startup logs.
Inspect the SSH jail in detail
sudo fail2ban-client status sshdThe output normally includes the filter status, total failed attempts, currently failed attempts, and currently banned IP addresses. The exact output varies by Fail2ban version and action.
Inspect effective jail configuration
sudo fail2ban-client get sshd maxretry
sudo fail2ban-client get sshd findtime
sudo fail2ban-client get sshd bantimeThese commands help confirm the active threshold values. If a command is not supported by your installed version, consult the local fail2ban-client help and configuration.
Step 7: Inspect and Manage Banned IPs
View currently banned IP addresses
sudo fail2ban-client status sshdReview the banned-IP list and confirm that it matches the events you expect to see in your SSH authentication logs.
Check Fail2ban logs
Depending on the installation, Fail2ban may log to a file or to the systemd journal. For a systemd-managed installation, inspect:
sudo journalctl -u fail2ban --since "1 hour ago"If your configuration writes to a file, use the actual log path defined by your installation. Check for ban and unban messages, filter errors, missing logs, and action failures.
Inspect the firewall action
Fail2ban relies on an action to apply the ban. The exact firewall mechanism can differ by distribution, Fail2ban version, and configuration. Depending on your setup, it may use nftables, iptables, or another supported action.
Step 8: Unban a Legitimate IP Address
A trusted administrator may be temporarily blocked after repeated failed authentication attempts. Verify the source address and the reason for the ban before removing it.
Remove an IP from the SSH jail ban list
sudo fail2ban-client set sshd unbanip 203.0.113.25203.0.113.25 is a documentation-only example address. Replace it with the exact legitimate IP address you have verified. Do not copy the example literally.
Verify the unban
sudo fail2ban-client status sshdConfirm that the address is no longer listed as banned. If access is still unavailable, investigate firewall rules, routing, SSH authentication settings, and the source IP actually observed by the server.
ignoreip or the system firewall simply to resolve one administrator’s login issue.Troubleshooting Common Fail2ban Problems
Fail2ban service will not start
Check sudo journalctl -u fail2ban -n 100 --no-pager. Inspect syntax, duplicate settings, unsupported options, missing modules, and jail startup errors.
SSH jail is missing
Confirm that enabled = true is in the correct local configuration file and that the service has loaded the changes. Inspect the active jail list and service logs.
No SSH log file found
Determine whether SSH writes to a file or systemd journal. Configure a compatible backend and install any required integration package for your distribution.
Failed attempts are not counted
Check the SSH logs, filter configuration, source addresses, and backend. Confirm that the relevant failures match the active SSH filter.
IP appears banned but can still connect
Check the active jail action, firewall backend, rule application, IPv4/IPv6 behavior, and whether traffic is reaching a different host or port.
A legitimate administrator is blocked
Verify the source IP, unban that address with the Fail2ban client, and review why authentication failures occurred before reconnecting.
Useful diagnostic commands
sudo systemctl status fail2ban --no-pager
sudo journalctl -u fail2ban -n 100 --no-pager
sudo fail2ban-client status
sudo fail2ban-client status sshdFor an additional filter-level diagnostic, the fail2ban-regex utility can test whether a supported log source matches the configured SSH filter. The exact command depends on whether the source is a file or systemd journal and on your installed version.
SSH Security Best Practices
Fail2ban works best as part of a layered server security strategy. Combine it with strong authentication, access restrictions, network controls, and regular monitoring.
Disable direct root login
Use a named administrator account and sudo rather than logging in remotely as root.
Prefer public-key authentication
Test key-based access and disable SSH password authentication when compatible with your access policy.
Restrict permitted users
Use OpenSSH’s AllowUsers or an appropriate access policy to limit which accounts can connect.
Restrict network access
Use a VPN, management network, or firewall allowlist when possible. Confirm the rules before applying remote changes.
Keep the system patched
Apply supported operating-system, OpenSSH, and Fail2ban updates through a controlled patching process.
Monitor security events
Review authentication logs and bans, and forward important events to a central logging system when appropriate.
AllowUsers, configuration validation, and safe testing.Frequently Asked Questions
What is Fail2ban used for on Linux?
Fail2ban monitors configured logs for repeated patterns such as failed SSH authentication attempts. When a jail reaches its configured threshold, an action can block the source IP address for a specified period.
Does Fail2ban automatically protect SSH after installation?
Not necessarily. You must confirm that the service is running, the SSH jail is enabled, the logging backend is compatible, and the ban action is working. Verify with fail2ban-client status and fail2ban-client status sshd.
What are reasonable Fail2ban settings for SSH?
Five failures within ten minutes with an initial one-hour ban is a possible starting configuration. These are example values rather than universal recommendations. Adjust them for your access patterns, shared IP addresses, operational needs, and security policy.
Does Fail2ban stop all SSH brute-force attacks?
No. It can reduce repeated attempts from sources detected by its filters, but it does not eliminate all attack paths. Strong SSH authentication, limited access, software updates, and network controls remain important.
Can Fail2ban work without /var/log/auth.log?
Yes, depending on the distribution and configuration. If SSH events are recorded in the systemd journal, a compatible systemd backend and its required dependencies may be appropriate. Confirm the logging source before changing the backend.
How do I check whether an IP address is banned?
Run sudo fail2ban-client status sshd and inspect the banned-IP list and jail counters. Check the Fail2ban logs as well if you need to understand why the address was blocked.
How do I unban an IP address?
After verifying the address is legitimate, run sudo fail2ban-client set sshd unbanip YOUR_IP, replacing the placeholder with the exact address. Then check the jail status again.
Should I change SSH from port 22?
Changing the port may reduce some routine automated scan noise, but it is not a substitute for strong authentication or firewall controls. If you change it, update the firewall, client configuration, and Fail2ban jail port setting where needed.
Can Fail2ban block users behind the same public IP?
Yes. If several people or systems share a public IP address, repeated failures from one of them can cause the shared address to be banned. Consider this risk when choosing thresholds and durations.
Conclusion: Protect SSH with Fail2ban
Fail2ban provides a practical way to respond automatically to repeated SSH authentication failures. Install the package, enable the sshd jail, choose sensible ban thresholds, ensure the correct log source is monitored, and verify the active jail and firewall action.
For a stronger security posture, combine Fail2ban with public-key authentication, restricted SSH users, disabled direct root login, firewall controls, and regular security updates. These controls work together; no single setting or tool guarantees that a server is secure.
- Install Fail2ban from a trusted distribution repository.
- Create a local SSH jail configuration without modifying packaged defaults.
- Enable the
sshdjail and set suitable retry, window, and ban values. - Verify the logging backend and SSH event source.
- Enable and start the Fail2ban service.
- Confirm the jail appears in
fail2ban-client status. - Inspect the SSH jail, logs, and configured ban action.
- Test changes without risking your only management connection.
- Document the safe procedure for checking and removing legitimate bans.
- Harden SSH authentication using the companion SSH hardening guide.
Build a Stronger Linux Security Baseline
Explore more practical guides covering Linux administration, cloud infrastructure, virtualization, networking, and cybersecurity.
Official Sources and Further Reading
- Fail2ban official GitHub repository — project information, installation guidance, and documentation.
- Fail2ban README — how Fail2ban detects repeated authentication errors and uses actions to block hosts.
- Fail2ban jail.conf manual — jail configuration, local overrides, thresholds, and backends.
- OpenSSH sshd_config manual — SSH server authentication and access-control settings.
- Ubuntu Server OpenSSH documentation — SSH server administration and configuration.
Technical disclaimer: Fail2ban behavior depends on the installed version, distribution defaults, log source, jail configuration, and firewall action. Test changes in a controlled environment when possible. Apply these instructions only to systems you are authorized to administer.

