Introduction

If you want to secure your webpage with a simple authentication you may want to use an external authentication backend. For example, you already have some authentication in PHP in an existing system, then here's how to extend Apache's HTTP Basic Auth with it.

Getting started

Install the authnz-external Apache module. In Debian/Ubuntu:

apt-get install libapache2-mod-authnz-external

Enable the module.

In Debian/Ubuntu:

a2enmod authnz_external

then reload Apache's config

apache2ctl graceful

An example script to test the credentials in PHP. (myauth.php):

#!/usr/bin/php5
<?php
// Read from stdin. First line is the username, second line is the password.
$handle = fopen ("php://stdin","r");
$username = trim(fgets($handle));
$password = trim(fgets($handle));

// Check the username/password. Below is a very simple example, write your own!
// Probably you want to create a query to some database, add salts, etc.
if($username != 'gert' || $password != 'mypassword'){
    # Output to stdout/stderr will be included in the Apache log for debugging purposes
    echo "wrong username or password for user $username\n";
    # In case of a failure, sleep a few seconds to slowdown bruteforce attacks.
    sleep (3);
    exit (1);
} else {
    echo "username/password allowed for user $username\n";
    exit (0);
}
?>

Note

This is an example of a PHP5 CLI script (for which you need the php5-cli package).

While this is a PHP5 script, it could actually be any kind of script or executable which integrates with your current authentication system, as long as it complies with the exit status codes; 0 means OK, anything else means NOT OK.

Important note: In order to slow bruteforce attacks down be sure to set up some sleep time for a failed attempt. Also, I recommend to configure fail2ban for Apache to actually stop these attacks.

Don't forget to set the script as executable:

chmod +x myauth.php

Define an ExternalAuth directive in for example /etc/apache2/conf.d/authnz_external.conf:

# define phptest for authentication
DefineExternalAuth phptest pipe /path/to/script/myauth.php

In some site config you need to provide the AuthBasicProvider and AuthExternal directive. For example, to protect the location /secure on your website:

<Location /secure>
        AuthType Basic
        AuthName "Gert test"
        AuthBasicProvider external
        AuthExternal phptest
        Require valid-user
</Location>

Finally, reload Apache again and test your configuration!

Tip

You can reuse the configured AuthExternal in any other site configuration on the server.

Share on: TwitterHacker NewsFacebookLinkedInRedditEmail


Related Posts


Published

Last Updated

Category

Security

Tags

Connect with me on...