Prevent WordPress wp-login.php brute force attack

Dima

I’m maintaining a lot of WordPress based sites. And almost daily there is some brute force attack on one of them. The target of these attacks is wp-login.php file. There is a lot of solutions to protect this file by limiting access to it using a separate password or manually adding allowed IP address. And changing them all the time is not an option for me.

So how I solved this? By automagisation! 😉
Main point is to modify .htaccess file to have access rules like:

<Files wp-login.php>
   Order deny,allow
   Deny from all
   Allow from 123.123.123.123
</Files>

This rule denies access from all and allows from ip 123.123.123.123.

But we need to change IP automatically wherever we are. My solution is to use a PHP script that checks my current IP and changes it to .htaccess file. And by adding a little bit of magic I can access wp-login.php with only one click! How?

Like this:

  1. I’m opening my-wordpress-site.com/magical-login.php url
  2. magical-login.php checks my current IP and changes it to the access rule
  3. magical-login.php redirects me to wp-login.php, which now accessible for me

And of course nobody knows that magical-login.php file exists. I can change the filename to whatever I want.

You probably want to know what does this magical-login.php contain? Here:

<?php 

// reading current content from .htaccess
$ht = fopen(".htaccess", "r");
$content = fread($ht, filesize(".htaccess"));
fclose($ht);

// removing old access rule for wp-login.php file 
$content = preg_replace("/\<Files wp-login\.php\>.*\<\/Files\>\s+/s","",$content);

// checking current ip address
if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else $ip = $_SERVER['REMOTE_ADDR'];

// creating new access rule with new ip address
$rule = <<< rule
<Files wp-login.php>
        Order deny,allow
        Deny from all
        Allow from $ip
</Files>

rule;

// writing new .htaccess content
$ht = fopen(".htaccess", "w");
fwrite($ht, $rule.$content);
fclose($ht);

// redirecting to wp-login.php
header('Location: wp-login.php');

?>

Make sure your webserver has write permission to .htaccess file.

Just drop your PHP file to the same folder with wp-login.php and open it with your browser. It will add access rule to the top of .htaccess file and you are done. Next time just forget about wp-login.php and use the file you have created.

One thought on “Prevent WordPress wp-login.php brute force attack

  1. Kiitos Dima. Tämä lähtee kokeiluun. Aikas näppärä!

Leave a Reply

Your email address will not be published. Required fields are marked *