DAViCal
Loading...
Searching...
No Matches
HTTPAuthSession.php
1<?php
11
21
26 public $username;
27
32 public $user_no;
33
38 public $principal_id;
39
44 public $email;
45
50 public $fullname;
51
57 public $groups;
58
59 /* These fields were being added dynmically. Set to private mostly, I had to
60 * set these as public for tests to pass: principal
61 */
62 private $dav_name;
63 private $logged_in;
64 public $principal;
65 private $roles;
67
71 function __construct() {
72 global $c;
73
74 if ( ! empty($_SERVER['PHP_AUTH_DIGEST'])) {
75 $this->DigestAuthSession();
76 }
77 else if ( isset($_SERVER['PHP_AUTH_USER']) || isset($_SERVER["AUTHORIZATION"]) ) {
78 $this->BasicAuthSession();
79 }
80 else if ( isset($c->http_auth_mode) && $c->http_auth_mode == "Digest" ) {
81 $this->DigestAuthSession();
82 }
83 else {
84 $this->BasicAuthSession();
85 }
86 }
87
93 function AuthFailedResponse( $auth_header = "" ) {
94 global $c;
95 if ( $auth_header == "" ) {
96 $auth_realm = $c->system_name;
97 if ( isset($c->per_principal_realm) && $c->per_principal_realm && !empty($_SERVER['PATH_INFO']) ) {
98 $principal_name = preg_replace( '{^/(.*?)/.*$}', '$1', $_SERVER['PATH_INFO']);
99 if ( $principal_name != $_SERVER['PATH_INFO'] ) {
100 $auth_realm .= ' - ' . $principal_name;
101 }
102 }
103 dbg_error_log( "HTTPAuth", ":AuthFailedResponse Requesting authentication in the '%s' realm", $auth_realm );
104 $auth_header = sprintf( 'WWW-Authenticate: Basic realm="%s"', $auth_realm );
105 }
106
107 header('HTTP/1.1 401 Unauthorized', true, 401 );
108 header('Content-type: text/plain; ; charset="utf-8"' );
109 if ( $c->test_mode ) header( "Request-ID: " . request_id() );
110
111 header( $auth_header );
112 echo 'Please log in for access to this system.';
113 if ( isset($_SERVER['PHP_AUTH_USER']) ) {
114 dbg_error_log( "ERROR", "authentication failure for user '%s' from host [%s]", $_SERVER['PHP_AUTH_USER'], $_SERVER['REMOTE_ADDR'] );
115 } else {
116 dbg_error_log( "HTTPAuth", ":Session: User is not authorised: %s ", $_SERVER['REMOTE_ADDR'] );
117 }
118 @ob_flush(); exit(0);
119 }
120
121
125 function BasicAuthSession() {
126 global $c;
127
131 if ( !isset($_SERVER['AUTHORIZATION']) && isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
132 $_SERVER['AUTHORIZATION'] = $_SERVER['HTTP_AUTHORIZATION'];
133 if (isset($_SERVER['AUTHORIZATION']) && !empty($_SERVER['AUTHORIZATION'])) {
134 list ($type, $cred) = explode(" ", $_SERVER['AUTHORIZATION']);
135 if ($type == 'Basic') {
136 list ($user, $pass) = explode(":", base64_decode($cred), 2);
137 $_SERVER['PHP_AUTH_USER'] = $user;
138 $_SERVER['PHP_AUTH_PW'] = $pass;
139 }
140 }
141 else if ( isset($c->authenticate_hook['server_auth_type'])
142 && ( ( isset($_SERVER["REMOTE_USER"]) && !empty($_SERVER["REMOTE_USER"]) ) ||
143 ( isset($_SERVER["REDIRECT_REMOTE_USER"]) && !empty($_SERVER["REDIRECT_REMOTE_USER"]) ) ) ) {
144 if ( ( is_array($c->authenticate_hook['server_auth_type'])
145 && in_array( strtolower($_SERVER['AUTH_TYPE']), array_map('strtolower', $c->authenticate_hook['server_auth_type'])) )
146 ||
147 ( !is_array($c->authenticate_hook['server_auth_type'])
148 && strtolower($c->authenticate_hook['server_auth_type']) == strtolower($_SERVER['AUTH_TYPE']) )
149 ) {
153 if (isset($_SERVER["REMOTE_USER"]))
154 $_SERVER['PHP_AUTH_USER'] = $_SERVER['REMOTE_USER'];
155 else
156 $_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
157 $_SERVER['PHP_AUTH_PW'] = 'Externally Authenticated';
158 if ( ! isset($c->authenticate_hook['call']) ) {
164 $c->authenticate_hook['call'] = 'auth_external';
165 }
166 }
167 }
168
169
173 if ( isset($_SERVER['PHP_AUTH_USER']) ) {
174 if ( $p = $this->CheckPassword( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
175 if ( isset($p->active) && !isset($p->user_active) ) {
176 trace_bug('Some authentication failed to return a dav_principal record and needs fixing.');
177 $p->user_active = $p->active;
178 }
179
184 if ( $p->user_active ) {
185 $this->AssignSessionDetails($p);
186 return;
187 }
188 }
189 }
190
191 if ( isset($c->allow_unauthenticated) && $c->allow_unauthenticated ) {
192 $this->AssignSessionDetails('unauthenticated');
193 $this->logged_in = false;
194 return;
195 }
196
197 $this->AuthFailedResponse();
198 // Does not return
199 }
200
201
216 function DigestAuthSession() {
217 global $c;
218
219 $realm = $c->system_name;
220 $opaque = $realm;
221 if ( isset($_SERVER['HTTP_USER_AGENT']) ) $opaque .= $_SERVER['HTTP_USER_AGENT'];
222 if ( isset($_SERVER['REMOTE_ADDR']) ) $opaque .= $_SERVER['REMOTE_ADDR'];
223 $opaque = sha1($opaque);
224
225 if ( ! empty($_SERVER['PHP_AUTH_DIGEST'])) {
226 // analyze the PHP_AUTH_DIGEST variable
227 if ( $data = $this->ParseDigestHeader($_SERVER['PHP_AUTH_DIGEST']) ) {
228
229 if ( $data['uri'] != $_SERVER['REQUEST_URI'] ) {
230 dbg_error_log( "ERROR", " DigestAuth: WTF! URI is '%s' and request URI is '%s'!?!" );
231 $this->AuthFailedResponse();
232 // Does not return
233 }
234
235 // generate the valid response
236 $test_user = new Principal('username', $data['username']);
237
238 if ( preg_match( '{\*(Digest)?\*(.*)}', $test_user->password, $matches ) ) {
239 if ( $matches[1] == 'Digest' )
240 $A1 = $matches[2];
241 else {
242// dbg_error_log( "HTTPAuth", "Constructing A1 from md5(%s:%s:%s)", $data['username'], $realm, $matches[2] );
243 $A1 = md5($data['username'] . ':' . $realm . ':' . $matches[2]);
244 }
245 $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
246 $auth_string = $A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2;
247// dbg_error_log( "HTTPAuth", "DigestAuthString: %s", $auth_string);
248 $valid_response = md5($auth_string);
249// dbg_error_log( "HTTPAuth", "DigestResponse: %s", $valid_response);
250
251 if ( $data['response'] == $valid_response ) {
252 $this->AssignSessionDetails($test_user);
253// dbg_error_log( "HTTPAuth", "Success!!!" );
254 return;
255 }
256 }
257 else {
258 // Their account is not configured for Digest auth so we need to use Basic.
259 $this->AuthFailedResponse();
260 // Does not return
261 }
262 }
263 }
264
265 $nonce = sha1(uniqid('',true));
266 $authheader = sprintf('WWW-Authenticate: Digest realm="%s", qop="auth", nonce="%s", opaque="%s", algorithm="MD5"',
267 $realm, $nonce, $opaque );
268 dbg_error_log( "HTTPAuth", $authheader );
269 $this->AuthFailedResponse( $authheader );
270 // Does not return
271 }
272
273
278 function ParseDigestHeader($auth_header) {
279 // protect against missing data
280 $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
281 $data = array();
282
283 preg_match_all('{(\w+)="([^"]+)"}', $auth_header, $matches, PREG_SET_ORDER);
284 foreach ($matches as $m) {
285// dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
286 $data[$m[1]] = $m[2];
287 unset($needed_parts[$m[1]]);
288 dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
289 }
290
291 preg_match_all('{(\w+)=([^" ,]+)}', $auth_header, $matches, PREG_SET_ORDER);
292 foreach ($matches as $m) {
293// dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
294 $data[$m[1]] = $m[2];
295 unset($needed_parts[$m[1]]);
296 dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
297 }
298
299
300 @dbg_error_log( "HTTPAuth", 'Received: nonce: %s, nc: %s, cnonce: %s, qop: %s, username: %s, uri: %s, response: %s',
301 $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], $data['username'], $data['uri'], $data['response']
302 );
303 return $needed_parts ? false : $data;
304 }
305
306
311 function CheckPassword( $username, $password ) {
312 global $c;
313
314 if(isset($c->login_append_domain_if_missing) && $c->login_append_domain_if_missing && !preg_match('/@/',$username))
315 $username.='@'.$c->domain_name;
316
317 $cache_result = $this->_CheckCache($username, $password);
318
319 if ($cache_result == 0) {
320 # noop as _CheckCache has nothing for this username/password combo
321 # and we need to perform full authentication check.
322
323 } else if ($cache_result == 1) {
324 # cached credentials match and are valid
325
326 if ( $principal = new Principal('username', $username) ) {
327 if ( isset($c->dbg['password']) ) dbg_error_log( "password", ":CheckPassword (cached): Name:%s, Pass:%s, File:%s, Active:%s", $username, $password, $principal->password, ($principal->user_active?'Yes':'No') );
328 if ( $principal->user_active ) {
329 return $principal;
330 } else {
331 return false;
332 }
333 } else {
334
335 # If we fail to find the Principal, then fall through to full authentication below.
336 dbg_error_log('password', 'Cache check: Failed to find principal after valid cache result, falling through to full authentication check.');
337 }
338
339 } else if ($cache_result == 2) {
340 # cached credentials match and are invalid
341
342 return false;
343 }
344
345 if ( !isset($c->authenticate_hook) || !isset($c->authenticate_hook['call'])
346 || !function_exists($c->authenticate_hook['call'])
347 || (isset($c->authenticate_hook['optional']) && $c->authenticate_hook['optional']) )
348 {
349 if ( $principal = new Principal('username', $username) ) {
350 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') );
351 if ( $principal->user_active && session_validate_password( $password, $principal->password ) ) {
352 $this->_SetCache($username, $password, 'pass');
353 return $principal;
354 }
355 }
356 }
357
358 if ( isset($c->authenticate_hook) && isset($c->authenticate_hook['call']) && function_exists($c->authenticate_hook['call']) ) {
370 $principal = call_user_func( $c->authenticate_hook['call'], $username, $password );
371 if ( $principal !== false && !($principal instanceof Principal) ) {
372 $principal = new Principal('username', $username);
373 }
374
375 if ( $principal === false ) {
376 $this->_SetCache($username, $password, 'fail');
377 } else {
378 $this->_SetCache($username, $password, 'pass');
379 }
380
381 return $principal;
382 }
383
384 $this->_SetCache($username, $password, 'fail');
385 return false;
386 }
387
388
397 function AllowedTo ( $whatever ) {
398 return ( isset($this->logged_in) && $this->logged_in && isset($this->roles[$whatever]) && $this->roles[$whatever] );
399 }
400
401
405 function GetRoles () {
406 $this->roles = array();
407 $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 ',
408 array( ':user_no' => $this->user_no) );
409 if ( $qry->Exec('BasicAuth') && $qry->rows() > 0 ) {
410 while( $role = $qry->Fetch() ) {
411 $this->roles[$role->role_name] = true;
412 }
413 }
414 }
415
416
421 function AssignSessionDetails( $principal ) {
422 if ( is_string($principal) ) $principal = new Principal('username',$principal);
423 if ( get_class($principal) != 'Principal' ) {
424 $principal = new Principal('username',$principal->username);
425 }
426
427 if ( !get_class($principal) == 'Principal' ) {
428 throw new Exception('HTTPAuthSession::AssignSessionDetails could not find a Principal object');
429 }
430 $this->username = $principal->username();
431 $this->user_no = $principal->user_no();
432 $this->principal_id = $principal->principal_id();
433 $this->email = $principal->email();
434 $this->fullname = $principal->fullname;
435 $this->dav_name = $principal->dav_name();
436 $this->principal = $principal;
437
438 $this->GetRoles();
439 $this->logged_in = true;
440 if ( function_exists("awl_set_locale") && isset($this->locale) && $this->locale != "" ) {
441 awl_set_locale($this->locale);
442 }
443 }
444
449 function _CheckCache( $username, $password ) {
450 global $c;
451
452 if (! $c->auth_cache) return 0;
453 if (! isset($c->auth_cache_secret) || $c->auth_cache_secret == '') {
454 dbg_error_log('LOG', "HTTPAuth:CheckCache: caching of credentials is enabled, but \$c->auth_cache_secret isn't set, using auth source");
455 return 0;
456 }
457
458 $cache = getCacheInstance();
459 if ($cache->isActive() === false) return 0;
460
461 $cache_ns = 'auth-' . $username;
462
463 $salt = $cache->get($cache_ns, 'salt');
464
465 if (!isset($salt) || (is_bool($salt) && $salt == false) || $salt == '') {
466 dbg_error_log('HTTPAuth', 'CheckCache: No stored salt for %s, need to use auth source', $username);
467 return 0;
468 }
469
470 # The hashed password to fetch
471 $hash = $this->_MakeHash($password, $salt);
472 if (! isset($hash)) {
473 dbg_error_log('LOG', 'HTTPAuth:CheckCache: failed to generate hash of credential, using auth source');
474 return 0;
475 }
476
477 $cached_credentials = $cache->get($cache_ns, $hash);
478
479 if (isset($cached_credentials)) {
480 if ($cached_credentials === 'pass') {
481 dbg_error_log('HTTPAuth', 'CheckCache: Cached credentials for %s are good and valid', $username);
482 return 1;
483
484 } else if ($cached_credentials === 'fail') {
485 dbg_error_log('HTTPAuth', 'CheckCache: Cached credentials for %s are good and invalid', $username);
486 return 2;
487 }
488
489 dbg_error_log('HTTPAuth', 'CheckCache: No stored salted password for %s, need to use auth source', $username);
490 }
491
492 # All hope is lost, we must have failed to find anything decent.
493 return 0;
494 }
495
500 function _SetCache( $username, $password, $state ) {
501 global $c;
502
503 if (! $c->auth_cache) return 0;
504 if (! isset($c->auth_cache_secret) || $c->auth_cache_secret === '') {
505 dbg_error_log('LOG', "HTTPAuth:CheckCache: caching of credentials is enabled, \$c->auth_cache_secret isn't set, not caching credential");
506 return 0;
507 }
508
509 # Work out the expiry to use, some sites might prefer different TTLs for
510 # pass/fail results.
511 if ($state === 'pass') {
512 $expiry = $c->auth_cache_pass;
513 } else if ($state === 'fail') {
514 $expiry = $c->auth_cache_fail;
515 } else {
516 dbg_error_log('ERROR', 'HTTPAuth:CheckCache: SetCache: Unexpected state %s, bailing out from caching credential.', $state);
517 return 0;
518 }
519
520 # Only cache if the expiry is set to non-zero. This allows disabling
521 # caching on a pass or fail basis.
522 if ($expiry == 0) {
523 dbg_error_log('ERROR', 'HTTPAuth:CheckCache: SetCache: Expiry set to 0, not caching credential.', $state);
524 return 0;
525 }
526
527
528 $cache = getCacheInstance();
529 if ($cache->isActive() === false) return 0;
530
531 $cache_ns = 'auth-' . $username;
532
533 $salt = $cache->get($cache_ns, 'salt');
534
535 if (!isset($salt) || (is_bool($salt) && $salt == false) || $salt == '') {
536 # bcrypt requires the salt is 22 bytes.
537 $salt = $this->_GenerateSalt(22);
538
539 # We use the default expiry setting for the salt, because the worst
540 # case scenario is that we won't access the cached credentials and
541 # need to fail back to the full authentication source.
542 if (! $cache->set($cache_ns, 'salt', $salt) ) {
543 dbg_error_log('ERROR', 'HTTPAuth:CheckCache: SetCache: Failed to store salt, bailing out from caching credential.');
544 return 0;
545 }
546 }
547
548 # The hashed password to store
549 $hash = $this->_MakeHash($password, $salt);
550 if (! isset($hash)) {
551 dbg_error_log('ERROR', 'HTTPAuth:CheckCache: SetCache: Failed to generate hash, bailing out from caching credential.');
552 return 0;
553 }
554
555 if (! $cache->set($cache_ns, $hash, $state, $expiry) ) {
556 dbg_error_log('ERROR', 'HTTPAuth:CheckCache: SetCache: Failed to store credential.');
557 return 0;
558 }
559
560 return 1;
561 }
562
566 function _MakeHash( $password, $salt ) {
567 global $c;
568
569 $password_salt = '$2y$07$' . $salt . '$';
570 $password_peppered = hash_hmac('sha256', $password, $c->auth_cache_secret);
571 $password_hashed = crypt($password_peppered, $password_salt);
572
573 if ($password_hashed == $password_salt || $password_hashed == '*0') {
574 return NULL;
575 } else {
576 return $password_hashed;
577 }
578 }
579
580 /*
581 * Internal function to generate a salt.
582 *
583 * Uses random_bytes if available, falls back to mcrypt_create_iv if it
584 * isn't.
585 */
586 function _GenerateSalt( $length ) {
587 # We fetch a bit more incase we need to strip out unacceptable characters.
588 if (function_exists('random_bytes')) {
589 $salt = random_bytes($length + 20);
590 } else {
591 $salt = mcrypt_create_iv($length + 20, MCRYPT_DEV_URANDOM);
592 }
593
594 # We use this salt with CRYPT_BLOWFISH which only accepts the characters
595 #./0-9a-zA-Z as per https://www.php.net/manual/en/function.crypt.php
596 $salt = base64_encode($salt);
597 $salt = preg_replace('/[^0-9\.\/a-zA-Z]/', '', $salt);
598
599 $salt = substr($salt, 1, $length);
600 return $salt;
601 }
602}
AuthFailedResponse( $auth_header="")
ParseDigestHeader($auth_header)
AllowedTo( $whatever)
_CheckCache( $username, $password)
AssignSessionDetails( $principal)
_MakeHash( $password, $salt)
CheckPassword( $username, $password)
_SetCache( $username, $password, $state)