Fail2Ban
Fail2Ban is an intrusion prevention software framework that protects servers from brute-force attacks. It scans log files (e.g., /var/log/auth.log) and bans IP addresses that show malicious signs, such as too many password failures.
Status and Monitoring
Check Fail2Ban Service Status
sudo fail2ban-client statusChecks if the Fail2Ban service is running and lists all active "jails" (monitored services).
Check a Specific Jail
sudo fail2ban-client status sshdShows detailed status for a specific jail, including a list of currently banned IP addresses.
Managing Jails and Banned IPs
Manually Unban an IP
sudo fail2ban-client set sshd unbanip 123.45.67.89Removes a specific IP address from the sshd jail. Replace the IP and jail name as needed.
Manually Ban an IP
sudo fail2ban-client set sshd banip 123.45.67.89Manually bans a specific IP address in the sshd jail. Useful for proactively blocking known malicious actors.
Start a Jail
sudo fail2ban-client start sshdStarts a specific jail if it was previously stopped.
Stop a Jail
sudo fail2ban-client stop sshdStops a running jail. It will no longer monitor its log file or ban IPs.
Restart a Jail
sudo fail2ban-client restart sshdA quick way to stop and then start a jail again.
Debugging and Testing Filters
Get a Jail's Regex
sudo fail2ban-client get sshd failregexRetrieves the regular expression (failregex) that a specific jail is using to find malicious log entries.
Test a Regex Against a Log File
sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.confThis powerful command tests a filter configuration file against a real log file to see what lines would have matched and resulted in a ban.
Test a Custom Regex String
sudo fail2ban-regex /var/log/auth.log 'Failed password for .* from <HOST>'Allows you to test a custom regex string directly against a log file without needing a full filter configuration.
Configuration
The main configuration is in /etc/fail2ban/jail.conf, but you should never edit this file directly. Instead, create a local override file.
Create a Local Configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.localThis command creates your local configuration file. Settings in jail.local will override those in jail.conf and will be safe from package updates.
Example SSH Jail Configuration
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600 This is a typical configuration block inside jail.local. It enables the SSH jail, sets it to ban an IP after 5 failed attempts (maxretry) for 3600 seconds (bantime).
Service and Log Management
Reload Configuration
sudo systemctl reload fail2banReloads the configuration files after you've made changes to jail.local without fully restarting the service.
View Latest Logs
sudo journalctl -u fail2ban --no-pager -n 50Shows the last 50 log entries for the Fail2Ban service, which is essential for debugging issues.