What is Fail2ban?
Fail2ban is an intrusion prevention software framework that protects computer servers from brute-force attacks. It works by scanning log files (e.g., /var/log/auth.log) and banning IP addresses that show malicious signs, such as too many password failures, seeking for exploits, etc.
Installing Fail2ban
Choose the installation method according to your Linux distribution.
1. Using Package Manager
Debian / Ubuntu
| |
CentOS / RHEL (Using yum or dnf)
On CentOS/RHEL, you typically need to install the EPEL repository first:
| |
2. From Source (tar.gz)
If you need a specific version or your distribution doesn’t provide a package, you can install from source:
| |
Note: Source installation typically requires manual configuration of systemd service files and log paths.
After installation, it is recommended to set Fail2ban to start on boot:
| |
Configuring Fail2ban
The default configuration file for Fail2ban is /etc/fail2ban/jail.conf. However, it’s not recommended to modify this file directly, as it may be overwritten during package upgrades. Instead, you should create a local configuration file, /etc/fail2ban/jail.local, or new .conf files in the /etc/fail2ban/jail.d/ directory to override the defaults.
Create a Local Configuration File
First, copy jail.conf to jail.local:
| |
Now you can safely edit the jail.local file.
Configure SSH Protection
Open the /etc/fail2ban/jail.local file and find the [sshd] section. You can customize the following parameters as needed:
| |
enabled:trueenables this jail.port: The port for the SSH service.logpath: The path to the SSH authentication log file.maxretry: The number of failures before a ban is imposed.findtime: The time window during which the failures must occur.bantime: The duration for which the IP address is banned.1dmeans one day.
More Practical Scenarios
In addition to SSH, Fail2ban can protect many other services. Add the following to jail.local:
Nginx Prevention of Malicious Scans (Too many 404 errors)
| |
Note: This requires you to define an nginx-404.conf filter under /etc/fail2ban/filter.d/.
MySQL/MariaDB Protection
| |
Common Fail2ban Management Commands
fail2ban-client is the primary tool for managing Fail2ban.
1. Check Status
| |
2. Manage Banned IPs
| |
3. Reload Configuration
When you modify .local files or filters, you can apply changes without restarting the entire service:
| |
FAQ & Tips
- Whitelist: Set
ignoreip = 127.0.0.1/8 ::1 <Your Fixed IP>in the[DEFAULT]section to prevent locking yourself out. - Persistence: By default, bans expire after a service restart. For persistence, you can configure database storage.
- Email Notifications: Fail2ban supports sending email alerts to administrators when an IP is banned.
Summary
Fail2ban is a simple yet effective tool that adds a significant layer of security to your server. With proper configuration, you can greatly reduce the risk of brute-force attacks.