Mitigating Brute Force Attacks with Fail2Ban and IPTables
Introduction
Brute force attacks are a common method used by attackers to gain unauthorized access to servers. Fail2Ban and IPTables provide an effective defense mechanism by detecting multiple failed login attempts and blocking the offending IPs. This guide will help you set up Fail2Ban and IPTables to secure your server.
Step 1: Install Fail2Ban
-
Update your package list and install Fail2Ban:
sudo apt update && sudo apt install fail2ban -y
-
Enable and start the Fail2Ban service:
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
-
Verify that Fail2Ban is running:
sudo systemctl status fail2ban
Step 2: Configure Fail2Ban
-
Copy the default configuration file to create a local override:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
-
Edit the Fail2Ban configuration:
sudo nano /etc/fail2ban/jail.local
-
Modify the settings under DEFAULT to configure ban times and retry limits:
ignoreip = 127.0.0.1/8 ::1
bantime = 600
findtime = 600
maxretry = 5
-
Save and close the file.
Step 3: Enable SSH Protection
-
Open the jail configuration file:
sudo nano /etc/fail2ban/jail.local
-
Find the section for SSH and enable it:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
-
Restart Fail2Ban to apply changes:
sudo systemctl restart fail2ban
-
Check the status of Fail2Ban’s SSH protection:
sudo fail2ban-client status sshd
Step 4: Configure IPTables for Additional Security
-
Block repeated failed login attempts manually using IPTables:
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH --rsource
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 --rttl --name SSH --rsource -j DROP
-
Save the IPTables rules:
sudo iptables-save | sudo tee /etc/iptables/rules.v4
-
To reload IPTables rules on boot, install the persistent package:
sudo apt install iptables-persistent
Step 5: Monitor and Maintain Security
-
Check Fail2Ban logs to monitor blocked IPs:
sudo fail2ban-client status sshd
-
To unban an IP manually:
sudo fail2ban-client set sshd unbanip
IP_ADDRESS
-
Regularly update your server and security configurations:
sudo apt update && sudo apt upgrade -y
Conclusion
By setting up Fail2Ban and IPTables, you add an essential layer of security against brute force attacks. Regular monitoring and updates will help keep your server protected from potential threats.