Automatically block IP addresses that repeatedly fail SSH authentication attempts
#Prerequisites
- Ubuntu/Debian Linux system with sudo access
- SSH service running and accessible
- Basic understanding of systemd services
- Access to system logs and configuration files
#Install Fail2ban
Install the Fail2ban package from the official Ubuntu/Debian repositories. This intrusion prevention system monitors log files and bans IPs that show malicious signs.
#Create the Jail Configuration
Create a local configuration file that overrides the default settings. Never edit the main jail.conf file directly as it gets overwritten during updates.
#Configuration Explanation:
enabled = trueโ Activates the SSH jail protectionport = sshโ Monitors your SSH port (default 22)logpath = %(sshd_log)sโ Uses systemd journal for SSH logsbackend = systemdโ Use systemd journal as log sourcemaxretry = 5โ Ban IP after 5 failed attemptsbantime = 3600โ Ban IP for 1 hour (3600 seconds)findtime = 600โ Count failures within 10 minutes (600 seconds)
#Start and Enable the Service
Enable Fail2ban to start automatically on boot and start the service immediately to begin protecting your system.
--now flag both enables the service for boot and starts it immediately. Fail2ban is now monitoring your SSH logs.
#Restart to Apply Configuration
Restart the Fail2ban service to apply your custom jail configuration. This ensures your SSH protection settings are active.
#Check Service Status
Verify that Fail2ban is running correctly and has loaded your configuration without errors.
Active: active (running) and no error messages in the status output.
#Verify Active Jails
Check that your SSH jail is active and monitoring for intrusion attempts. This confirms your protection is working.
For detailed information about the SSH jail status:
#Protection Active
Your server is now protected by Fail2ban. The system will automatically monitor SSH logs and ban IP addresses that exceed the failed login threshold.
#Useful Commands for Monitoring:
sudo fail2ban-client statusโ List all active jailssudo fail2ban-client status sshdโ Detailed SSH jail statussudo fail2ban-client unban <IP>โ Manually unban an IP addresssudo journalctl -u fail2ban -fโ Watch Fail2ban logs in real-timesudo fail2ban-client reloadโ Reload configuration without restart