Setting Up Fail2ban: Protecting Your SSH Server
1. What is Fail2ban?
Fail2ban is a tool that protects servers against brute-force attacks. It scans log files and automatically blocks IP addresses that show suspicious behavior.
2. Installing Fail2ban
Debian/Ubuntu:
sudo apt update && sudo apt install fail2ban -y
CentOS/RHEL:
sudo yum install epel-release
sudo yum install fail2ban
Arch Linux:
sudo pacman -S fail2ban
3. Starting and Checking the Service Status
After installation, enable and start the Fail2ban service:
sudo systemctl enable --now fail2ban
Check the status:
sudo systemctl status fail2ban
Expected output:
● fail2ban.service - Fail2Ban Service
Loaded: loaded (/etc/systemd/system/fail2ban.service; enabled; vendor preset: enabled)
Active: active (running)
4. Configuring Fail2ban for SSH
Creating the Configuration File
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Open the file for editing:
sudo vim /etc/fail2ban/jail.local
Add or modify the following settings:
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 3
ignoreip = 127.0.0.1/8 192.168.1.0/24 10.10.0.0/24
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log # For Debian/Ubuntu
# logpath = /var/log/secure # For CentOS/RHEL
maxretry = 3
bantime = 1h
findtime = 10m
maxretry— number of failed login attempts before banning.bantime— how long an IP will be banned (e.g.,1h= 1 hour).findtime— the time window in which failed attempts are counted.
Save and exit the file.
5. Restarting and Verifying Fail2ban
Apply the changes:
sudo systemctl restart fail2ban
Check active jails:
sudo fail2ban-client status
Expected result:
Status
|- Number of jail: 1
`- Jail list: sshd
Testing the Setup
- View banned IPs:
sudo fail2ban-client status sshd
- Unban an IP manually:
sudo fail2ban-client set sshd unbanip 192.168.1.1
6. Unbanning Your Own IP
If you accidentally ban your own IP:
sudo fail2ban-client set sshd unbanip <IP-ADDRESS>
7. Additional Tweaks
- Increase ban time for frequent attacks:
bantime = 24h
8. Viewing Fail2ban Logs
From journalctl:
sudo journalctl -u fail2ban --no-pager | tail -n 50
Or directly from the log file:
sudo cat /var/log/fail2ban.log
Conclusion
Fail2ban is a simple yet powerful tool for protecting your server from brute-force attacks.
By enabling SSH protection, you can significantly reduce the risk of unauthorized access.
You can also extend Fail2ban protection to services like Nginx, Apache, and Postfix by adding the relevant configuration blocks to /etc/fail2ban/jail.local.
🚀 Explore more guides on our blog 👉 blog.1it.pro
📧 Contact us: admin@1it.pro for expert IT guidance.
🌐 Explore more: Visit 1it.pro for top-tier IT solutions.