This guide will tell you how to setup a custom fail2ban filter and jail to watch the Apache access log and ban malicious attackers who brute for wp-login.php. I am sure we have all seen it in our access logs. I would say it the most common thing I see in wordpress and non wordpress sites access logs that stands out as a blind brute force. Im tired of it. So I found out how to ban them.
# apt install fail2ban
This will watch apache logs. For my testing I did this on Debian Buster (10.1) which at the time of writing this was using apache2.4.38. First create a file at:
/etc/fail2ban/filter.d/wordpress.conf
I created this basic filter. I may update this later after further testing. Right now I am awaiting my ban expiration from the intial test so I decided to write up a guide while I wait (even though I could unban myself with fail2ban-client set wordpress unbanip <IPADDR>
). Here is the filter definition. Save this to wordpress.conf
[Definition]
failregex = ^<HOST> .* "POST /wp-login.php .* 200 \d* "https?://.*"$
A very simple filter that checks for login attempts on wp-login.php. A successful login will not return a 200. It actually returns a 302 redirect so the regex does not match.
Fail2ban has the concept of "Jails" which is a fancy name for a config file to enable your filter. It seems you can really go crazy with these jails and I can't wait to explore more in the future but for now this is the filter we will use. Put this at:
/etc/fail2ban/jail.d/wordpress.conf
with these contents:
[wordpress]
enabled = true
filter = wordpress
# Feel free to customize the apache2 log file location
# nginx/fpm will need diff filter
logpath = /var/log/apache2/access.log
# How many 'strikes' or 'chances' the ip gets before ban
maxretry = 10
# Time IP banned for. Can also use seconds. Shorthand info in jail.conf(5)
bantime = 1 day
And feel free to modify the bantime or maxretry to your hearts content :)
Now you can enable this "jail" with the fail2ban client (CLI). The command is:
# fail2ban-client add wordpress && fail2ban start wordpress
The first part enables the wordpress "jail" the second starts the jail.
If you want or need to customize the filter you might google for a resource on filters. The website linked me to https://docs.python.org/2/library/re.html as a resource for the regex format used. To test the regex you can use the command:
# fail2ban-regex /var/log/apache2/access.log wordpress
which should tell you the number of matches found for the regex. Change the log location or filter as needed.
Update it: