Protect WordPress Login Using Fail2Ban and Cloudflare

I’ve discovered a way to protect my WordPress site from brute force attacks thanks to these two guides I found:

DDOS PROTECTION WITH CLOUDFLARE AND FAIL2BAN
WordPress Login Security with Fail2Ban

The best part is these guides do not require installing yet another plugin to WordPress. If your WordPress site does not sit behind Cloudflare, you can just follow the second guide; if you are using Cloudflare however, that guide won’t do anything for you because iptables will only ever see IP addresses from Cloudflare, not your attacker. To make it work with Cloudflare, we need the action filter created in the first guide.

The following steps are a combination of the two guides above and are what I used to configure fail2ban to ban IPs at Cloudflare after failed logins on WordPress; if you haven’t done so already you need to install mod_cloudflare for Apache so it can see the IPs of visitors instead of Cloudflare’s. It’s also a good idea to configure iptables to only allow HTTP/HTTPS traffic from Cloudflare so they can’t bypass it and browse your site directly; the list of Cloudflare IPs is available here as a text file.

First we need to make WordPress log failed authentication attempts; edit the functions.php of your site’s theme and add the following:

Next we need edit /etc/rsyslog.conf and add the following lines under the “Rules” section:

Since we’ve added a new log, we should configure logrotate; add the following to the bottom of /etc/logrotate.conf:

Restart rsyslog with:

Next we create the filter for fail2ban to use; create a new file /etc/fail2ban/filter.d/wordpress.conf with the following contents:

Now we define the action for fail2ban to use; create a new file /etc/fail2ban/action.d/cloudflare.conf with the contents below. Remember to insert your Cloudflare email address and API Key at the bottom.

Now that we have the filter and action created for fail2ban we can add the jail to /etc/fail2ban/jail.local:

Restart fail2ban and it will watch /var/log/wp_f2b.log for failed WordPress authentication and use the Cloudflare API to ban/unban IPs.