Add detection for PHP running in CGI mode and add HTTP_AUTHORIZATION rewrite rule

Detect and parse HTTP_AUTHORIZATION for basic authentication running PHP in CGI mode
Add comments about using CGI mode with Apache and Basic Auth in /docs/en/topics/environment-management.md
Added notes  to docs/en/changelogs/3.1.9.md
This commit is contained in:
Corey Sewell 2014-11-28 08:34:55 +13:00 committed by Corey Sewell
parent 3b3478136d
commit fbebf96d66
4 changed files with 51 additions and 26 deletions

View File

@ -1494,6 +1494,8 @@ HTML;
if($base != '.') $baseClause = "RewriteBase '$base'\n"; if($base != '.') $baseClause = "RewriteBase '$base'\n";
else $baseClause = ""; else $baseClause = "";
if(strpos(strtolower(php_sapi_name()), "cgi") !== false) $cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]\n";
else $cgiClause = "";
$modulePath = FRAMEWORK_NAME; $modulePath = FRAMEWORK_NAME;
$rewrite = <<<TEXT $rewrite = <<<TEXT
# Deny access to templates (but allow from localhost) # Deny access to templates (but allow from localhost)
@ -1523,6 +1525,7 @@ ErrorDocument 500 /assets/error-500.html
SetEnv HTTP_MOD_REWRITE On SetEnv HTTP_MOD_REWRITE On
RewriteEngine On RewriteEngine On
$baseClause $baseClause
$cgiClause
# Deny access to potentially sensitive files and folders # Deny access to potentially sensitive files and folders
RewriteRule ^vendor(/|$) - [F,L,NC] RewriteRule ^vendor(/|$) - [F,L,NC]

View File

@ -0,0 +1,14 @@
# 3.1.9
# Overview
This release replaces the 3.1.8 release, and resolves an issue where basic authentication would not work when PHP is running under CGI mode with Apache.
## Upgrading
* Add the rule ``` RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]``` to the .htacces file in your sites root directory after the line ```RewriteEngine On```.
### Bugfixes
## Changelog

View File

@ -119,7 +119,7 @@ This is my `_ss_environment.php` file. I have it placed in `/var`, as each of th
| `SS_ENVIRONMENT_TYPE`| The environment type: dev, test or live.| | `SS_ENVIRONMENT_TYPE`| The environment type: dev, test or live.|
| `SS_DEFAULT_ADMIN_USERNAME`| The username of the default admin. This is a user with administrative privileges.| | `SS_DEFAULT_ADMIN_USERNAME`| The username of the default admin. This is a user with administrative privileges.|
| `SS_DEFAULT_ADMIN_PASSWORD`| The password of the default admin. This will not be stored in the database.| | `SS_DEFAULT_ADMIN_PASSWORD`| The password of the default admin. This will not be stored in the database.|
| `SS_USE_BASIC_AUTH`| Protect the site with basic auth (good for test sites)| | `SS_USE_BASIC_AUTH`| Protect the site with basic auth (good for test sites).<br/>When using CGI/FastCGI with Apache, you will have to add the `RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]` rewrite rule to your `.htaccess` file|
| `SS_SEND_ALL_EMAILS_TO`| If you set this define, all emails will be redirected to this address.| | `SS_SEND_ALL_EMAILS_TO`| If you set this define, all emails will be redirected to this address.|
| `SS_SEND_ALL_EMAILS_FROM`| If you set this define, all emails will be send from this address.| | `SS_SEND_ALL_EMAILS_FROM`| If you set this define, all emails will be send from this address.|
| `SS_ERROR_LOG` | | | `SS_ERROR_LOG` | |

View File

@ -1,13 +1,13 @@
<?php <?php
/** /**
* Provides an interface to HTTP basic authentication. * Provides an interface to HTTP basic authentication.
* *
* This utility class can be used to secure any request with basic authentication. To do so, * This utility class can be used to secure any request with basic authentication. To do so,
* {@link BasicAuth::requireLogin()} from your Controller's init() method or action handler method. * {@link BasicAuth::requireLogin()} from your Controller's init() method or action handler method.
* *
* It also has a function to protect your entire site. See {@link BasicAuth::protect_entire_site()} * It also has a function to protect your entire site. See {@link BasicAuth::protect_entire_site()}
* for more information. You can control this setting on controller-level by using {@link Controller->basicAuthEnabled}. * for more information. You can control this setting on controller-level by using {@link Controller->basicAuthEnabled}.
* *
* @package framework * @package framework
* @subpackage security * @subpackage security
*/ */
@ -17,15 +17,15 @@ class BasicAuth {
* @var Boolean Flag set by {@link self::protect_entire_site()} * @var Boolean Flag set by {@link self::protect_entire_site()}
*/ */
private static $entire_site_protected = false; private static $entire_site_protected = false;
/** /**
* @config * @config
* @var String|array Holds a {@link Permission} code that is required * @var String|array Holds a {@link Permission} code that is required
* when calling {@link protect_site_if_necessary()}. Set this value through * when calling {@link protect_site_if_necessary()}. Set this value through
* {@link protect_entire_site()}. * {@link protect_entire_site()}.
*/ */
private static $entire_site_protected_code = 'ADMIN'; private static $entire_site_protected_code = 'ADMIN';
/** /**
* @config * @config
* @var String Message that shows in the authentication box. * @var String Message that shows in the authentication box.
@ -35,31 +35,39 @@ class BasicAuth {
/** /**
* Require basic authentication. Will request a username and password if none is given. * Require basic authentication. Will request a username and password if none is given.
* *
* Used by {@link Controller::init()}. * Used by {@link Controller::init()}.
* *
* @throws SS_HTTPResponse_Exception * @throws SS_HTTPResponse_Exception
* *
* @param string $realm * @param string $realm
* @param string|array $permissionCode Optional * @param string|array $permissionCode Optional
* @param boolean $tryUsingSessionLogin If true, then the method with authenticate against the * @param boolean $tryUsingSessionLogin If true, then the method with authenticate against the
* session log-in if those credentials are disabled. * session log-in if those credentials are disabled.
* @return Member $member * @return Member $member
*/ */
public static function requireLogin($realm, $permissionCode = null, $tryUsingSessionLogin = true) { public static function requireLogin($realm, $permissionCode = null, $tryUsingSessionLogin = true) {
$isRunningTests = (class_exists('SapphireTest', false) && SapphireTest::is_running_test()); $isRunningTests = (class_exists('SapphireTest', false) && SapphireTest::is_running_test());
if(!Security::database_is_ready() || (Director::is_cli() && !$isRunningTests)) return true; if(!Security::database_is_ready() || (Director::is_cli() && !$isRunningTests)) return true;
$matches = array();
if (isset($_SERVER['HTTP_AUTHORIZATION']) &&
preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
list($name, $password) = explode(':', base64_decode($matches[1]));
$_SERVER['PHP_AUTH_USER'] = strip_tags($name);
$_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
$member = null; $member = null;
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$member = MemberAuthenticator::authenticate(array( $member = MemberAuthenticator::authenticate(array(
'Email' => $_SERVER['PHP_AUTH_USER'], 'Email' => $_SERVER['PHP_AUTH_USER'],
'Password' => $_SERVER['PHP_AUTH_PW'], 'Password' => $_SERVER['PHP_AUTH_PW'],
), null); ), null);
} }
if(!$member && $tryUsingSessionLogin) $member = Member::currentUser(); if(!$member && $tryUsingSessionLogin) $member = Member::currentUser();
// If we've failed the authentication mechanism, then show the login form // If we've failed the authentication mechanism, then show the login form
if(!$member) { if(!$member) {
$response = new SS_HTTPResponse(null, 401); $response = new SS_HTTPResponse(null, 401);
@ -70,13 +78,13 @@ class BasicAuth {
} else { } else {
$response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password.")); $response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password."));
} }
// Exception is caught by RequestHandler->handleRequest() and will halt further execution // Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401); $e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response); $e->setResponse($response);
throw $e; throw $e;
} }
if($permissionCode && !Permission::checkMember($member->ID, $permissionCode)) { if($permissionCode && !Permission::checkMember($member->ID, $permissionCode)) {
$response = new SS_HTTPResponse(null, 401); $response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\""); $response->addHeader('WWW-Authenticate', "Basic realm=\"$realm\"");
@ -84,28 +92,28 @@ class BasicAuth {
if(isset($_SERVER['PHP_AUTH_USER'])) { if(isset($_SERVER['PHP_AUTH_USER'])) {
$response->setBody(_t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator.")); $response->setBody(_t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator."));
} }
// Exception is caught by RequestHandler->handleRequest() and will halt further execution // Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401); $e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response); $e->setResponse($response);
throw $e; throw $e;
} }
return $member; return $member;
} }
/** /**
* Enable protection of the entire site with basic authentication. * Enable protection of the entire site with basic authentication.
* *
* This log-in uses the Member database for authentication, but doesn't interfere with the * This log-in uses the Member database for authentication, but doesn't interfere with the
* regular log-in form. This can be useful for test sites, where you want to hide the site * regular log-in form. This can be useful for test sites, where you want to hide the site
* away from prying eyes, but still be able to test the regular log-in features of the site. * away from prying eyes, but still be able to test the regular log-in features of the site.
* *
* If you are including conf/ConfigureFromEnv.php in your _config.php file, you can also enable * If you are including conf/ConfigureFromEnv.php in your _config.php file, you can also enable
* this feature by adding this line to your _ss_environment.php: * this feature by adding this line to your _ss_environment.php:
* *
* define('SS_USE_BASIC_AUTH', true); * define('SS_USE_BASIC_AUTH', true);
* *
* @param boolean $protect Set this to false to disable protection. * @param boolean $protect Set this to false to disable protection.
* @param String $code {@link Permission} code that is required from the user. * @param String $code {@link Permission} code that is required from the user.
* Defaults to "ADMIN". Set to NULL to just require a valid login, regardless * Defaults to "ADMIN". Set to NULL to just require a valid login, regardless
@ -116,11 +124,11 @@ class BasicAuth {
Config::inst()->update('BasicAuth', 'entire_site_protected_code', $code); Config::inst()->update('BasicAuth', 'entire_site_protected_code', $code);
Config::inst()->update('BasicAuth', 'entire_site_protected_message', $message); Config::inst()->update('BasicAuth', 'entire_site_protected_message', $message);
} }
/** /**
* Call {@link BasicAuth::requireLogin()} if {@link BasicAuth::protect_entire_site()} has been called. * Call {@link BasicAuth::requireLogin()} if {@link BasicAuth::protect_entire_site()} has been called.
* This is a helper function used by {@link Controller::init()}. * This is a helper function used by {@link Controller::init()}.
* *
* If you want to enabled protection (rather than enforcing it), * If you want to enabled protection (rather than enforcing it),
* please use {@link protect_entire_site()}. * please use {@link protect_entire_site()}.
*/ */