Loading...
Searching...
No Matches
HTTPAuthSession.php
<?php
class HTTPAuthSession {
public $username;
public $user_no;
public $principal_id;
public $email;
public $fullname;
public $groups;
/* These fields were being added dynmically. Set to private mostly, I had to
* set these as public for tests to pass: principal
*/
private $dav_name;
private $logged_in;
public $principal;
private $roles;
function __construct() {
global $c;
if ( ! empty($_SERVER['PHP_AUTH_DIGEST'])) {
$this->DigestAuthSession();
}
else if ( isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER["AUTHORIZATION"]) ) {
$this->BasicAuthSession();
}
else if ( isset($c->http_auth_mode) && $c->http_auth_mode == "Digest" ) {
$this->DigestAuthSession();
}
else {
$this->BasicAuthSession();
}
}
function AuthFailedResponse( $auth_header = "" ) {
global $c;
if ( $auth_header == "" ) {
$auth_realm = $c->system_name;
if ( isset($c->per_principal_realm) && $c->per_principal_realm && !empty($_SERVER['PATH_INFO']) ) {
$principal_name = preg_replace( '{^/(.*?)/.*$}', '$1', $_SERVER['PATH_INFO']);
if ( $principal_name != $_SERVER['PATH_INFO'] ) {
$auth_realm .= ' - ' . $principal_name;
}
}
dbg_error_log( "HTTPAuth", ":AuthFailedResponse Requesting authentication in the '%s' realm", $auth_realm );
$auth_header = sprintf( 'WWW-Authenticate: Basic realm="%s"', $auth_realm );
}
header('HTTP/1.1 401 Unauthorized', true, 401 );
header('Content-type: text/plain; ; charset="utf-8"' );
header( $auth_header );
echo 'Please log in for access to this system.';
if ( isset($_SERVER['PHP_AUTH_USER']) ) {
dbg_error_log( "ERROR", "authentication failure for user '%s' from host [%s]", $_SERVER['PHP_AUTH_USER'], $_SERVER['REMOTE_ADDR'] );
} else {
dbg_error_log( "HTTPAuth", ":Session: User is not authorised: %s ", $_SERVER['REMOTE_ADDR'] );
}
@ob_flush(); exit(0);
}
function BasicAuthSession() {
global $c;
if ( !isset($_SERVER['AUTHORIZATION']) && isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
$_SERVER['AUTHORIZATION'] = $_SERVER['HTTP_AUTHORIZATION'];
if (isset($_SERVER['AUTHORIZATION']) && !empty($_SERVER['AUTHORIZATION'])) {
list ($type, $cred) = explode(" ", $_SERVER['AUTHORIZATION']);
if ($type == 'Basic') {
list ($user, $pass) = explode(":", base64_decode($cred), 2);
$_SERVER['PHP_AUTH_USER'] = $user;
$_SERVER['PHP_AUTH_PW'] = $pass;
}
}
else if ( isset($c->authenticate_hook['server_auth_type'])
&& ( ( isset($_SERVER["REMOTE_USER"]) && !empty($_SERVER["REMOTE_USER"]) ) ||
( isset($_SERVER["REDIRECT_REMOTE_USER"]) && !empty($_SERVER["REDIRECT_REMOTE_USER"]) ) ) ) {
if ( ( is_array($c->authenticate_hook['server_auth_type'])
&& in_array( strtolower($_SERVER['AUTH_TYPE']), array_map('strtolower', $c->authenticate_hook['server_auth_type'])) )
||
( !is_array($c->authenticate_hook['server_auth_type'])
&& strtolower($c->authenticate_hook['server_auth_type']) == strtolower($_SERVER['AUTH_TYPE']) )
) {
if (isset($_SERVER["REMOTE_USER"]))
$_SERVER['PHP_AUTH_USER'] = $_SERVER['REMOTE_USER'];
else
$_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
$_SERVER['PHP_AUTH_PW'] = 'Externally Authenticated';
if ( ! isset($c->authenticate_hook['call']) ) {
$c->authenticate_hook['call'] = 'auth_external';
}
}
}
if ( isset($_SERVER['PHP_AUTH_USER']) ) {
if ( $p = $this->CheckPassword( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
if ( isset($p->active) && !isset($p->user_active) ) {
trace_bug('Some authentication failed to return a dav_principal record and needs fixing.');
$p->user_active = $p->active;
}
if ( $p->user_active ) {
$this->AssignSessionDetails($p);
return;
}
}
}
if ( isset($c->allow_unauthenticated) && $c->allow_unauthenticated ) {
$this->AssignSessionDetails('unauthenticated');
$this->logged_in = false;
return;
}
$this->AuthFailedResponse();
// Does not return
}
function DigestAuthSession() {
global $c;
$realm = $c->system_name;
$opaque = $realm;
if ( isset($_SERVER['HTTP_USER_AGENT']) ) $opaque .= $_SERVER['HTTP_USER_AGENT'];
if ( isset($_SERVER['REMOTE_ADDR']) ) $opaque .= $_SERVER['REMOTE_ADDR'];
$opaque = sha1($opaque);
if ( ! empty($_SERVER['PHP_AUTH_DIGEST'])) {
// analyze the PHP_AUTH_DIGEST variable
if ( $data = $this->ParseDigestHeader($_SERVER['PHP_AUTH_DIGEST']) ) {
if ( $data['uri'] != $_SERVER['REQUEST_URI'] ) {
dbg_error_log( "ERROR", " DigestAuth: WTF! URI is '%s' and request URI is '%s'!?!" );
$this->AuthFailedResponse();
// Does not return
}
// generate the valid response
$test_user = new Principal('username', $data['username']);
if ( preg_match( '{\*(Digest)?\*(.*)}', $test_user->password, $matches ) ) {
if ( $matches[1] == 'Digest' )
$A1 = $matches[2];
else {
// dbg_error_log( "HTTPAuth", "Constructing A1 from md5(%s:%s:%s)", $data['username'], $realm, $matches[2] );
$A1 = md5($data['username'] . ':' . $realm . ':' . $matches[2]);
}
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$auth_string = $A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2;
// dbg_error_log( "HTTPAuth", "DigestAuthString: %s", $auth_string);
$valid_response = md5($auth_string);
// dbg_error_log( "HTTPAuth", "DigestResponse: %s", $valid_response);
if ( $data['response'] == $valid_response ) {
$this->AssignSessionDetails($test_user);
// dbg_error_log( "HTTPAuth", "Success!!!" );
return;
}
}
else {
// Their account is not configured for Digest auth so we need to use Basic.
$this->AuthFailedResponse();
// Does not return
}
}
}
$nonce = sha1(uniqid('',true));
$authheader = sprintf('WWW-Authenticate: Digest realm="%s", qop="auth", nonce="%s", opaque="%s", algorithm="MD5"',
$realm, $nonce, $opaque );
dbg_error_log( "HTTPAuth", $authheader );
$this->AuthFailedResponse( $authheader );
// Does not return
}
function ParseDigestHeader($auth_header) {
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
preg_match_all('{(\w+)="([^"]+)"}', $auth_header, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
// dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
$data[$m[1]] = $m[2];
unset($needed_parts[$m[1]]);
dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
}
preg_match_all('{(\w+)=([^" ,]+)}', $auth_header, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
// dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
$data[$m[1]] = $m[2];
unset($needed_parts[$m[1]]);
dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
}
@dbg_error_log( "HTTPAuth", 'Received: nonce: %s, nc: %s, cnonce: %s, qop: %s, username: %s, uri: %s, response: %s',
$data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], $data['username'], $data['uri'], $data['response']
);
return $needed_parts ? false : $data;
}
function CheckPassword( $username, $password ) {
global $c;
if(isset($c->login_append_domain_if_missing) && $c->login_append_domain_if_missing && !preg_match('/@/',$username))
$username.='@'.$c->domain_name;
if ( !isset($c->authenticate_hook) || !isset($c->authenticate_hook['call'])
|| !function_exists($c->authenticate_hook['call'])
|| (isset($c->authenticate_hook['optional']) && $c->authenticate_hook['optional']) )
{
if ( $principal = new Principal('username', $username) ) {
if ( isset($c->dbg['password']) ) dbg_error_log( "password", ":CheckPassword: Name:%s, Pass:%s, File:%s, Active:%s", $username, $password, $principal->password, ($principal->user_active?'Yes':'No') );
if ( $principal->user_active && session_validate_password( $password, $principal->password ) ) {
return $principal;
}
}
}
if ( isset($c->authenticate_hook) && isset($c->authenticate_hook['call']) && function_exists($c->authenticate_hook['call']) ) {
$principal = call_user_func( $c->authenticate_hook['call'], $username, $password );
if ( $principal !== false && !($principal instanceof Principal) ) {
$principal = new Principal('username', $username);
}
return $principal;
}
return false;
}
function AllowedTo ( $whatever ) {
return ( isset($this->logged_in) && $this->logged_in && isset($this->roles[$whatever]) && $this->roles[$whatever] );
}
function GetRoles () {
$this->roles = array();
$qry = new AwlQuery( 'SELECT role_name FROM role_member m join roles r ON r.role_no = m.role_no WHERE user_no = :user_no ',
array( ':user_no' => $this->user_no) );
if ( $qry->Exec('BasicAuth') && $qry->rows() > 0 ) {
while( $role = $qry->Fetch() ) {
$this->roles[$role->role_name] = true;
}
}
}
function AssignSessionDetails( $principal ) {
if ( is_string($principal) ) $principal = new Principal('username',$principal);
if ( get_class($principal) != 'Principal' ) {
$principal = new Principal('username',$principal->username);
}
if ( !get_class($principal) == 'Principal' ) {
throw new Exception('HTTPAuthSession::AssignSessionDetails could not find a Principal object');
}
$this->username = $principal->username();
$this->user_no = $principal->user_no();
$this->principal_id = $principal->principal_id();
$this->email = $principal->email();
$this->fullname = $principal->fullname;
$this->dav_name = $principal->dav_name();
$this->principal = $principal;
$this->GetRoles();
$this->logged_in = true;
if ( function_exists("awl_set_locale") && isset($this->locale) && $this->locale != "" ) {
awl_set_locale($this->locale);
}
}
}
HTTPAuthSession
Definition HTTPAuthSession.php:17
HTTPAuthSession\BasicAuthSession
BasicAuthSession()
Definition HTTPAuthSession.php:123
HTTPAuthSession\AuthFailedResponse
AuthFailedResponse( $auth_header="")
Definition HTTPAuthSession.php:93
HTTPAuthSession\ParseDigestHeader
ParseDigestHeader($auth_header)
Definition HTTPAuthSession.php:276
HTTPAuthSession\AllowedTo
AllowedTo( $whatever)
Definition HTTPAuthSession.php:358
HTTPAuthSession\GetRoles
GetRoles()
Definition HTTPAuthSession.php:366
HTTPAuthSession\AssignSessionDetails
AssignSessionDetails( $principal)
Definition HTTPAuthSession.php:382
HTTPAuthSession\DigestAuthSession
DigestAuthSession()
Definition HTTPAuthSession.php:214
HTTPAuthSession\__construct
__construct()
Definition HTTPAuthSession.php:71
HTTPAuthSession\CheckPassword
CheckPassword( $username, $password)
Definition HTTPAuthSession.php:309
Principal
Definition Principal.php:19