How to Set Up Fail2Ban on Your VPS to Prevent Unauthorized Access
Fail2Ban is a security tool that helps protect your VPS from unauthorized access attempts by monitoring log files and banning suspicious IP addresses. This guide will walk you through setting up Fail2Ban on your VPS.
Step 1: Update Your System
Before installing Fail2Ban, ensure your VPS is up to date.
- Run the following command:
sudo apt update && sudo apt upgrade -y
Step 2: Install Fail2Ban
Fail2Ban is included in most Linux distributions. Install it using your package manager.
- On Ubuntu or Debian-based systems:
sudo apt install fail2ban -y
- On CentOS or RHEL-based systems:
sudo yum install epel-release -y sudo yum install fail2ban -y
Step 3: Enable and Start Fail2Ban
Ensure the Fail2Ban service is enabled and running.
- Enable and start the service:
sudo systemctl enable fail2ban sudo systemctl start fail2ban
- Check the status:
sudo systemctl status fail2ban
Step 4: Configure Fail2Ban
The default configuration files are located in /etc/fail2ban/
. You’ll need to create a local configuration file to customize Fail2Ban settings.
- Copy the default configuration file:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
- Edit the local file:
sudo nano /etc/fail2ban/jail.local
Step 5: Adjust Basic Settings
Modify the following parameters in the [DEFAULT]
section of jail.local
as needed:
- Ban time: Duration of the ban (default is 10 minutes).
bantime = 3600
- Find time: The time window to count failed attempts.
findtime = 600
- Max retry attempts: Number of failed login attempts allowed before banning.
maxretry = 5
Step 6: Configure Jail Rules
Fail2Ban uses "jails" to monitor specific services. Enable jails for services like SSH.
- Locate the
[sshd]
section injail.local
. - Ensure it is enabled:
[sshd] enabled = true port = ssh logpath = /var/log/auth.log maxretry = 5
Step 7: Restart Fail2Ban
After making changes, restart the Fail2Ban service to apply the configuration.
- Restart Fail2Ban:
sudo systemctl restart fail2ban
Step 8: Monitor Fail2Ban
You can monitor Fail2Ban activity and view banned IP addresses.
- Check Fail2Ban logs:
sudo tail -f /var/log/fail2ban.log
- List banned IPs for a specific jail:
sudo fail2ban-client status sshd
Step 9: Unban an IP Address (Optional)
If an IP is mistakenly banned, you can unban it manually.
- Unban a specific IP:
Replacesudo fail2ban-client set sshd unbanip <IP-address>
<IP-address>
with the actual IP to unban.
Step 10: Test Fail2Ban
Verify that Fail2Ban is working by intentionally attempting failed logins from a test IP. Check if the IP gets banned as expected.
Conclusion
By following these steps, you have successfully set up Fail2Ban to enhance the security of your VPS. Fail2Ban provides robust protection against unauthorized access attempts, ensuring your server remains secure. Regularly monitor your logs and update the configuration to adapt to new security needs.