How to Configure Fail2ban for VPS Security

How to Configure Fail2ban for VPS Security

Fail2ban is an intrusion prevention tool that monitors log files for brute-force login attempts and automatically bans offending IP addresses using firewall rules. For any VPS exposed to the internet — whether running SSH, a web server, or mail services — fail2ban is a critical first line of defense. This guide covers installation, configuration of common jails, custom rule creation, and monitoring best practices.

Installing Fail2ban

On Ubuntu or Debian-based systems, installation is a single command:

apt update && apt install fail2ban -y

After installation, copy the default configuration file — never edit jail.conf directly, as package updates will overwrite it:

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Configuring the SSH Jail

SSH brute-force attacks are the most common threat to any VPS. Edit /etc/fail2ban/jail.local and ensure the SSH jail is enabled:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
findtime = 600

This configuration bans an IP for 1 hour after 5 failed login attempts within 10 minutes. For higher-security setups, reduce maxretry to 3 and increase bantime to 86400 (24 hours).

Web Server Protection (Nginx/Apache)

Fail2ban ships with jails for common web attacks. Enable the Nginx jail to block bots probing for vulnerable paths:

[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3
bantime = 3600

[nginx-botsearch]
enabled = true
port = http,https
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 10
bantime = 3600

Creating Custom Filters

If you run a custom application, you can create your own fail2ban filter. For example, to block IPs that hit a non-existent WordPress XML-RPC endpoint repeatedly:

# /etc/fail2ban/filter.d/wp-xmlrpc.conf
[Definition]
failregex = ^<HOST>.*POST .*/xmlrpc\.php.* 404
ignoreregex =

Then add a corresponding jail in jail.local and restart fail2ban.

Monitoring and Maintenance

Check the current ban status with:

fail2ban-client status
fail2ban-client status sshd

View banned IPs in the firewall:

iptables -L -n | grep f2b

Set up email alerts for bans by adding destemail = [email protected] and action = %(action_mw)s to your jails. Restart fail2ban after any config change: systemctl restart fail2ban.

Conclusion

Fail2ban is a lightweight, highly effective security tool that every VPS should run. Combined with SSH key-only authentication, regular patching, and a well-configured firewall, it dramatically reduces your attack surface. For more VPS security guidance, see our full security benchmarks and recommended configurations.

Leave a Reply