One case study involved an Ubuntu 20.04 (Focal Fossa) system that was protected with Fail2fan. However the server was also protected with Cloudflare, so there was some work needed to get the remote IP of the attacker (this topic was covered in another post). If you try to ban the offender’s real IP (not the Cloudflare IP) with that configuration, you may receive messages in the fail2ban.log that look similar to the below:
fail2ban.observer INFO [jail] Found x.x.x.x, bad
fail2ban.actions NOTICE [jail] x.x.x.x already banned
You should also see the ban in iptables:
sudo iptables -L
However with the bans in place, the offending IP can still access the resource. The root cause is because the attack is originating from Cloudflare.
The solution is to ban and unban attacker’s remote IPs using Cloudflare’s API for their firewall. Fail2ban has a built in actions.d/cloudflare.conf to help with that. However with the Fail2ban version (0.11.1) available in Ubuntu 20.04 , the action file included was not completely functional, especially on the unban side. The trick is replace it (or use an action local file) using the latest action file on GitHub:
Duplicate the latest action file, then:
- Populate cftoken with your Global API key from Cloudflare
- Populate cfuser with the email address of your Cloudflare account.
Save the new action file (e.g., cloudflare.conf or cloudflare.local). Before proceeding further, flush out any old bans that may be present in Fail2ban from previous attempts at banning, doing one or more of the following:
sudo fail2ban-client set JAILNAME unbanip x.x.x.x
Once complete, the next step is to update your jail to have the following line (NOTE – if your action file is not called cloudflare.conf or cloudflare.local, change it below accordingly):
action = cloudflare
Save the jail and then reload Fail2ban:
sudo service fail2ban reload
Test to see if the banning works. You can monitor fail2ban in real time using the command:
sudo tail -f /var/log/fail2ban.log
As of today, you can view and manage bans in your Cloudflare account at Websites -> “Your-Site” -> Security -> WAF -> Tools. Any bans that come in through the API will have a note “Fail2Ban JAILNAME” under the IP address.