Select Page
This entry has been published on 2016-11-01 and may be out of date.

Last Updated on 2016-11-01.

[:en]There are many tutorials (e.g. the official one) how to make Magento secure, but none of them worked perfectly (for me).

So this is my approach:

Secure /downloader

Add to downloader/.htaccess:

Order deny,allow
Deny from all
Allow from 77.12.34.56
Allow from 10.1.0.0/16
Allow from 192.168.0.0/24
Allow from 91.12.34.56
#adjust to your needs

Secure /admin via .htaccess

Because the admin URL does not point to a real directory called “admin” (but points to /index.php), this is a bit more complicated.

Add to your Magento root .htaccess:

#Some IP Blacklisting (fake orderers etc.)
Deny from 91.123.45.
Deny from 80.12.34.56

# Restrict admin access
RewriteCond %{REQUEST_URI} ^/(index.php/)?admin/ [NC]
RewriteCond expr "! -R '10.1.0.0/16'"
RewriteCond expr "! -R '192.168.1.0/24'"
RewriteCond %{REMOTE_ADDR} !^77.12.34.56
RewriteCond %{REMOTE_ADDR} !^91.12.34.56
#add more if needed
RewriteRule ^(.*)$ / [F,L]

Note the different syntax (expr) when using wildcards/subnet ranges instead of full IPs.

Secure /admin via index.php

The code above works for many cases, but under some circumstances it might happen that the user can access the login form anyway. For me, it worked e.g. with example.com/index.php/admin/admin…, but not for example.com/admin (so an attacker would be able to test passwords).

So I recommend to use the following PHP script in addition.

<?php

//ds, 11.2016
//Addition to .htaccess to restrict /admin access.   
                  
function isAllowedAsAdmin()
{
    $whitelist = array(
        '10.1.*',
        '192.168.1.*',
        '77.12.34.56',
        '91.12.34.566'
    );
    
    if(in_array($_SERVER['REMOTE_ADDR'], $whitelist))
        return true;
    else{
        foreach($whitelist as $i){
            $wildcardPos = strpos($i, "*");

            if($wildcardPos !== false && substr($_SERVER['REMOTE_ADDR'], 0, $wildcardPos) . "*" == $i)
                return true;
        }
    }

    return false;
}

if (strpos($_SERVER['REQUEST_URI'], "/admin") !== false)
{
    if (!isAllowedAsAdmin())
    {
        echo $_SERVER['REMOTE_ADDR'] . " not allowed.";
        exit;
    }
}

                
?>

Save it as /ipcheck.inc.php, then edit index.php and add this line at the beginning:

<?php
include('ipcheck.inc.php');
?>

 [:]