Using Fail2Ban with Cloudflare for Enhanced DDoS Protection
Introduction
Fail2Ban is a powerful tool that helps protect Linux servers from brute-force attacks by banning suspicious IPs. When combined with Cloudflare, you can further mitigate DDoS attacks by blocking abusive IPs at the network edge before they even reach your server. This guide will walk you through configuring Fail2Ban to update Cloudflare’s firewall rules automatically.
Step 1: Install Fail2Ban
- Update your system and install Fail2Ban:
sudo apt update && sudo apt install -y fail2ban
- Enable and start the Fail2Ban service:
sudo systemctl enable --now fail2ban
Step 2: Get Your Cloudflare API Token
-
Log in to your Cloudflare dashboard.
-
Navigate to My Profile > API Tokens.
-
Click Create Token and choose the Edit Firewall Rules template.
-
Copy the generated API token and store it securely.
Step 3: Configure Fail2Ban to Work with Cloudflare
- Create a new action script for Cloudflare:
sudo nano /etc/fail2ban/action.d/cloudflare.conf
- Add the following content:
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = curl -s -X POST "https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules" -H "Authorization: Bearer <YOUR_CLOUDFLARE_API_TOKEN>" -H "Content-Type: application/json" --data '{"mode":"block","configuration":{"target":"ip","value":""},"notes":"Banned by Fail2Ban"}'
actionunban = curl -s -X DELETE "https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/" -H "Authorization: Bearer <YOUR_CLOUDFLARE_API_TOKEN>" -H "Content-Type: application/json"
- Save and exit the file.
Step 4: Create a Jail for Cloudflare
- Edit the Fail2Ban jail configuration:
sudo nano /etc/fail2ban/jail.local
- Add a new jail for SSH brute-force protection:
[sshd-cloudflare]
enabled = true
filter = sshd
action = cloudflare
logpath = /var/log/auth.log
maxretry = 5
findtime = 600
bantime = 86400
- Save and restart Fail2Ban:
sudo systemctl restart fail2ban
Step 5: Verify That It Works
- Test Fail2Ban status:
sudo fail2ban-client status sshd-cloudflare
- Simulate failed login attempts and check if the IP gets banned:
sudo fail2ban-client status
- Verify blocked IPs in the Cloudflare dashboard under Security > WAF > Tools.
Conclusion
By integrating Fail2Ban with Cloudflare, you add an extra layer of security that blocks malicious IPs before they reach your server. This significantly enhances your ability to mitigate brute-force and DDoS attacks. Regularly monitoring Fail2Ban logs and Cloudflare firewall rules ensures ongoing protection.