DAViCal
HTTPAuthSession.php
1 <?php
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;
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  header( $auth_header );
110  echo 'Please log in for access to this system.';
111  if ( isset($_SERVER['PHP_AUTH_USER']) ) {
112  dbg_error_log( "ERROR", "authentication failure for user '%s' from host [%s]", $_SERVER['PHP_AUTH_USER'], $_SERVER['REMOTE_ADDR'] );
113  } else {
114  dbg_error_log( "HTTPAuth", ":Session: User is not authorised: %s ", $_SERVER['REMOTE_ADDR'] );
115  }
116  @ob_flush(); exit(0);
117  }
118 
119 
123  function BasicAuthSession() {
124  global $c;
125 
129  if ( !isset($_SERVER['AUTHORIZATION']) && isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
130  $_SERVER['AUTHORIZATION'] = $_SERVER['HTTP_AUTHORIZATION'];
131  if (isset($_SERVER['AUTHORIZATION']) && !empty($_SERVER['AUTHORIZATION'])) {
132  list ($type, $cred) = explode(" ", $_SERVER['AUTHORIZATION']);
133  if ($type == 'Basic') {
134  list ($user, $pass) = explode(":", base64_decode($cred), 2);
135  $_SERVER['PHP_AUTH_USER'] = $user;
136  $_SERVER['PHP_AUTH_PW'] = $pass;
137  }
138  }
139  else if ( isset($c->authenticate_hook['server_auth_type'])
140  && ( ( isset($_SERVER["REMOTE_USER"]) && !empty($_SERVER["REMOTE_USER"]) ) ||
141  ( isset($_SERVER["REDIRECT_REMOTE_USER"]) && !empty($_SERVER["REDIRECT_REMOTE_USER"]) ) ) ) {
142  if ( ( is_array($c->authenticate_hook['server_auth_type'])
143  && in_array( strtolower($_SERVER['AUTH_TYPE']), array_map('strtolower', $c->authenticate_hook['server_auth_type'])) )
144  ||
145  ( !is_array($c->authenticate_hook['server_auth_type'])
146  && strtolower($c->authenticate_hook['server_auth_type']) == strtolower($_SERVER['AUTH_TYPE']) )
147  ) {
151  if (isset($_SERVER["REMOTE_USER"]))
152  $_SERVER['PHP_AUTH_USER'] = $_SERVER['REMOTE_USER'];
153  else
154  $_SERVER['PHP_AUTH_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
155  $_SERVER['PHP_AUTH_PW'] = 'Externally Authenticated';
156  if ( ! isset($c->authenticate_hook['call']) ) {
162  $c->authenticate_hook['call'] = 'auth_external';
163  }
164  }
165  }
166 
167 
171  if ( isset($_SERVER['PHP_AUTH_USER']) ) {
172  if ( $p = $this->CheckPassword( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
173  if ( isset($p->active) && !isset($p->user_active) ) {
174  trace_bug('Some authentication failed to return a dav_principal record and needs fixing.');
175  $p->user_active = $p->active;
176  }
177 
182  if ( $p->user_active ) {
183  $this->AssignSessionDetails($p);
184  return;
185  }
186  }
187  }
188 
189  if ( isset($c->allow_unauthenticated) && $c->allow_unauthenticated ) {
190  $this->AssignSessionDetails('unauthenticated');
191  $this->logged_in = false;
192  return;
193  }
194 
195  $this->AuthFailedResponse();
196  // Does not return
197  }
198 
199 
214  function DigestAuthSession() {
215  global $c;
216 
217  $realm = $c->system_name;
218  $opaque = $realm;
219  if ( isset($_SERVER['HTTP_USER_AGENT']) ) $opaque .= $_SERVER['HTTP_USER_AGENT'];
220  if ( isset($_SERVER['REMOTE_ADDR']) ) $opaque .= $_SERVER['REMOTE_ADDR'];
221  $opaque = sha1($opaque);
222 
223  if ( ! empty($_SERVER['PHP_AUTH_DIGEST'])) {
224  // analyze the PHP_AUTH_DIGEST variable
225  if ( $data = $this->ParseDigestHeader($_SERVER['PHP_AUTH_DIGEST']) ) {
226 
227  if ( $data['uri'] != $_SERVER['REQUEST_URI'] ) {
228  dbg_error_log( "ERROR", " DigestAuth: WTF! URI is '%s' and request URI is '%s'!?!" );
229  $this->AuthFailedResponse();
230  // Does not return
231  }
232 
233  // generate the valid response
234  $test_user = new Principal('username', $data['username']);
235 
236  if ( preg_match( '{\*(Digest)?\*(.*)}', $test_user->password, $matches ) ) {
237  if ( $matches[1] == 'Digest' )
238  $A1 = $matches[2];
239  else {
240 // dbg_error_log( "HTTPAuth", "Constructing A1 from md5(%s:%s:%s)", $data['username'], $realm, $matches[2] );
241  $A1 = md5($data['username'] . ':' . $realm . ':' . $matches[2]);
242  }
243  $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
244  $auth_string = $A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2;
245 // dbg_error_log( "HTTPAuth", "DigestAuthString: %s", $auth_string);
246  $valid_response = md5($auth_string);
247 // dbg_error_log( "HTTPAuth", "DigestResponse: %s", $valid_response);
248 
249  if ( $data['response'] == $valid_response ) {
250  $this->AssignSessionDetails($test_user);
251 // dbg_error_log( "HTTPAuth", "Success!!!" );
252  return;
253  }
254  }
255  else {
256  // Their account is not configured for Digest auth so we need to use Basic.
257  $this->AuthFailedResponse();
258  // Does not return
259  }
260  }
261  }
262 
263  $nonce = sha1(uniqid('',true));
264  $authheader = sprintf('WWW-Authenticate: Digest realm="%s", qop="auth", nonce="%s", opaque="%s", algorithm="MD5"',
265  $realm, $nonce, $opaque );
266  dbg_error_log( "HTTPAuth", $authheader );
267  $this->AuthFailedResponse( $authheader );
268  // Does not return
269  }
270 
271 
276  function ParseDigestHeader($auth_header) {
277  // protect against missing data
278  $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
279  $data = array();
280 
281  preg_match_all('{(\w+)="([^"]+)"}', $auth_header, $matches, PREG_SET_ORDER);
282  foreach ($matches as $m) {
283 // dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
284  $data[$m[1]] = $m[2];
285  unset($needed_parts[$m[1]]);
286  dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
287  }
288 
289  preg_match_all('{(\w+)=([^" ,]+)}', $auth_header, $matches, PREG_SET_ORDER);
290  foreach ($matches as $m) {
291 // dbg_error_log( "HTTPAuth", 'Match: "%s"', $m[0] );
292  $data[$m[1]] = $m[2];
293  unset($needed_parts[$m[1]]);
294  dbg_error_log( "HTTPAuth", 'Received: %s: %s', $m[1], $m[2] );
295  }
296 
297 
298  @dbg_error_log( "HTTPAuth", 'Received: nonce: %s, nc: %s, cnonce: %s, qop: %s, username: %s, uri: %s, response: %s',
299  $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], $data['username'], $data['uri'], $data['response']
300  );
301  return $needed_parts ? false : $data;
302  }
303 
304 
309  function CheckPassword( $username, $password ) {
310  global $c;
311 
312  if(isset($c->login_append_domain_if_missing) && $c->login_append_domain_if_missing && !preg_match('/@/',$username))
313  $username.='@'.$c->domain_name;
314 
315  if ( !isset($c->authenticate_hook) || !isset($c->authenticate_hook['call'])
316  || !function_exists($c->authenticate_hook['call'])
317  || (isset($c->authenticate_hook['optional']) && $c->authenticate_hook['optional']) )
318  {
319  if ( $principal = new Principal('username', $username) ) {
320  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') );
321  if ( $principal->user_active && session_validate_password( $password, $principal->password ) ) {
322  return $principal;
323  }
324  }
325  }
326 
327  if ( isset($c->authenticate_hook) && isset($c->authenticate_hook['call']) && function_exists($c->authenticate_hook['call']) ) {
339  $principal = call_user_func( $c->authenticate_hook['call'], $username, $password );
340  if ( $principal !== false && !($principal instanceof Principal) ) {
341  $principal = new Principal('username', $username);
342  }
343  return $principal;
344  }
345 
346  return false;
347  }
348 
349 
358  function AllowedTo ( $whatever ) {
359  return ( isset($this->logged_in) && $this->logged_in && isset($this->roles[$whatever]) && $this->roles[$whatever] );
360  }
361 
362 
366  function GetRoles () {
367  $this->roles = array();
368  $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 ',
369  array( ':user_no' => $this->user_no) );
370  if ( $qry->Exec('BasicAuth') && $qry->rows() > 0 ) {
371  while( $role = $qry->Fetch() ) {
372  $this->roles[$role->role_name] = true;
373  }
374  }
375  }
376 
377 
382  function AssignSessionDetails( $principal ) {
383  if ( is_string($principal) ) $principal = new Principal('username',$principal);
384  if ( get_class($principal) != 'Principal' ) {
385  $principal = new Principal('username',$principal->username);
386  }
387 
388  if ( !get_class($principal) == 'Principal' ) {
389  throw new Exception('HTTPAuthSession::AssignSessionDetails could not find a Principal object');
390  }
391  $this->username = $principal->username();
392  $this->user_no = $principal->user_no();
393  $this->principal_id = $principal->principal_id();
394  $this->email = $principal->email();
395  $this->fullname = $principal->fullname;
396  $this->dav_name = $principal->dav_name();
397  $this->principal = $principal;
398 
399  $this->GetRoles();
400  $this->logged_in = true;
401  if ( function_exists("awl_set_locale") && isset($this->locale) && $this->locale != "" ) {
402  awl_set_locale($this->locale);
403  }
404  }
405 
406 
407 }
408 
AuthFailedResponse( $auth_header="")
AssignSessionDetails( $principal)
ParseDigestHeader($auth_header)
AllowedTo( $whatever)
CheckPassword( $username, $password)