xref: /dokuwiki/inc/auth.php (revision 1d096a1019c5e9af62c7fd5678fb258a1ea7ed17)
1<?php
2/**
3 * Authentication library
4 *
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
7 *
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author     Andreas Gohr <andi@splitbrain.org>
10 */
11
12  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
13  require_once(DOKU_INC.'inc/common.php');
14  require_once(DOKU_INC.'inc/io.php');
15  require_once(DOKU_INC.'inc/blowfish.php');
16  require_once(DOKU_INC.'inc/mail.php');
17
18  // load the the backend auth functions and instantiate the auth object
19  if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
20    require_once(DOKU_INC.'inc/auth/basic.class.php');
21    require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
22
23    $auth_class = "auth_".$conf['authtype'];
24    if (class_exists($auth_class)) {
25      $auth = new $auth_class();
26      if ($auth->success == false) {
27			  unset($auth);
28				msg($lang['authtempfail'], -1);
29
30        // turn acl config setting off for the rest of this page
31				$conf['useacl'] = 0;
32			}
33		} else {
34			die($lang['authmodfailed']);
35		}
36	} else {
37	  die($lang['authmodfailed']);
38	}
39
40  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
41
42  // some ACL level defines
43  define('AUTH_NONE',0);
44  define('AUTH_READ',1);
45  define('AUTH_EDIT',2);
46  define('AUTH_CREATE',4);
47  define('AUTH_UPLOAD',8);
48  define('AUTH_DELETE',16);
49  define('AUTH_ADMIN',255);
50
51  // do the login either by cookie or provided credentials
52  if($conf['useacl']){
53    // external trust mechanism in place?
54    if(!is_null($auth) && $auth->canDo('external')){
55      $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
56    }else{
57      auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
58    }
59
60    //load ACL into a global array
61    if(is_readable(DOKU_CONF.'acl.auth.php')){
62      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
63    }else{
64      $AUTH_ACL = array();
65    }
66  }
67
68/**
69 * This tries to login the user based on the sent auth credentials
70 *
71 * The authentication works like this: if a username was given
72 * a new login is assumed and user/password are checked. If they
73 * are correct the password is encrypted with blowfish and stored
74 * together with the username in a cookie - the same info is stored
75 * in the session, too. Additonally a browserID is stored in the
76 * session.
77 *
78 * If no username was given the cookie is checked: if the username,
79 * crypted password and browserID match between session and cookie
80 * no further testing is done and the user is accepted
81 *
82 * If a cookie was found but no session info was availabe the
83 * blowfish encrypted password from the cookie is decrypted and
84 * together with username rechecked by calling this function again.
85 *
86 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
87 * are set.
88 *
89 * @author  Andreas Gohr <andi@splitbrain.org>
90 *
91 * @param   string  $user    Username
92 * @param   string  $pass    Cleartext Password
93 * @param   bool    $sticky  Cookie should not expire
94 * @return  bool             true on successful auth
95*/
96function auth_login($user,$pass,$sticky=false){
97  global $USERINFO;
98  global $conf;
99  global $lang;
100	global $auth;
101  $sticky ? $sticky = true : $sticky = false; //sanity check
102
103  if(isset($user)){
104    //usual login
105    if ($auth->checkPass($user,$pass)){
106      // make logininfo globally available
107      $_SERVER['REMOTE_USER'] = $user;
108      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
109
110      // set cookie
111      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
112      $cookie = base64_encode("$user|$sticky|$pass");
113      if($sticky) $time = time()+60*60*24*365; //one year
114      setcookie(DOKU_COOKIE,$cookie,$time,'/');
115
116      // set session
117      $_SESSION[$conf['title']]['auth']['user'] = $user;
118      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
119      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
120      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
121      return true;
122    }else{
123      //invalid credentials - log off
124      msg($lang['badlogin'],-1);
125      auth_logoff();
126      return false;
127    }
128  }else{
129    // read cookie information
130    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
131    list($user,$sticky,$pass) = split('\|',$cookie,3);
132    // get session info
133    $session = $_SESSION[$conf['title']]['auth'];
134
135    if($user && $pass){
136      // we got a cookie - see if we can trust it
137      if(isset($session) &&
138        ($session['user'] == $user) &&
139        ($session['pass'] == $pass) &&  //still crypted
140        ($session['buid'] == auth_browseruid()) ){
141        // he has session, cookie and browser right - let him in
142        $_SERVER['REMOTE_USER'] = $user;
143        $USERINFO = $session['info']; //FIXME move all references to session
144        return true;
145      }
146      // no we don't trust it yet - recheck pass
147      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
148      return auth_login($user,$pass,$sticky);
149    }
150  }
151  //just to be sure
152  auth_logoff();
153  return false;
154}
155
156/**
157 * Builds a pseudo UID from browser and IP data
158 *
159 * This is neither unique nor unfakable - still it adds some
160 * security. Using the first part of the IP makes sure
161 * proxy farms like AOLs are stil okay.
162 *
163 * @author  Andreas Gohr <andi@splitbrain.org>
164 *
165 * @return  string  a MD5 sum of various browser headers
166 */
167function auth_browseruid(){
168  $uid  = '';
169  $uid .= $_SERVER['HTTP_USER_AGENT'];
170  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
171  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
172  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
173  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
174  return md5($uid);
175}
176
177/**
178 * Creates a random key to encrypt the password in cookies
179 *
180 * This function tries to read the password for encrypting
181 * cookies from $conf['metadir'].'/_htcookiesalt'
182 * if no such file is found a random key is created and
183 * and stored in this file.
184 *
185 * @author  Andreas Gohr <andi@splitbrain.org>
186 *
187 * @return  string
188 */
189function auth_cookiesalt(){
190  global $conf;
191  $file = $conf['metadir'].'/_htcookiesalt';
192  $salt = io_readFile($file);
193  if(empty($salt)){
194    $salt = uniqid(rand(),true);
195    io_saveFile($file,$salt);
196  }
197  return $salt;
198}
199
200/**
201 * This clears all authenticationdata and thus log the user
202 * off
203 *
204 * @author  Andreas Gohr <andi@splitbrain.org>
205 */
206function auth_logoff(){
207  global $conf;
208  global $USERINFO;
209  global $INFO, $ID;
210  global $auth;
211
212  if(isset($_SESSION[$conf['title']]['auth']['user']))
213    unset($_SESSION[$conf['title']]['auth']['user']);
214  if(isset($_SESSION[$conf['title']]['auth']['pass']))
215    unset($_SESSION[$conf['title']]['auth']['pass']);
216  if(isset($_SESSION[$conf['title']]['auth']['info']))
217    unset($_SESSION[$conf['title']]['auth']['info']);
218  if(isset($_SERVER['REMOTE_USER']))
219    unset($_SERVER['REMOTE_USER']);
220  $USERINFO=null; //FIXME
221  setcookie(DOKU_COOKIE,'',time()-600000,'/');
222
223  if($auth && $auth->canDo('logoff')){
224    $auth->logOff();
225  }
226}
227
228/**
229 * Convinience function for auth_aclcheck()
230 *
231 * This checks the permissions for the current user
232 *
233 * @author  Andreas Gohr <andi@splitbrain.org>
234 *
235 * @param  string  $id  page ID
236 * @return int          permission level
237 */
238function auth_quickaclcheck($id){
239  global $conf;
240  global $USERINFO;
241  # if no ACL is used always return upload rights
242  if(!$conf['useacl']) return AUTH_UPLOAD;
243  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
244}
245
246/**
247 * Returns the maximum rights a user has for
248 * the given ID or its namespace
249 *
250 * @author  Andreas Gohr <andi@splitbrain.org>
251 *
252 * @param  string  $id     page ID
253 * @param  string  $user   Username
254 * @param  array   $groups Array of groups the user is in
255 * @return int             permission level
256 */
257function auth_aclcheck($id,$user,$groups){
258  global $conf;
259  global $AUTH_ACL;
260
261  # if no ACL is used always return upload rights
262  if(!$conf['useacl']) return AUTH_UPLOAD;
263
264  //if user is superuser return 255 (acl_admin)
265  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
266
267  //make sure groups is an array
268  if(!is_array($groups)) $groups = array();
269
270  //prepend groups with @
271  $cnt = count($groups);
272  for($i=0; $i<$cnt; $i++){
273    $groups[$i] = '@'.$groups[$i];
274  }
275  //if user is in superuser group return 255 (acl_admin)
276  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
277
278  $ns    = getNS($id);
279  $perm  = -1;
280
281  if($user){
282    //add ALL group
283    $groups[] = '@ALL';
284    //add User
285    $groups[] = $user;
286    //build regexp
287    $regexp   = join('|',$groups);
288  }else{
289    $regexp = '@ALL';
290  }
291
292  //check exact match first
293  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
294  if(count($matches)){
295    foreach($matches as $match){
296      $match = preg_replace('/#.*$/','',$match); //ignore comments
297      $acl   = preg_split('/\s+/',$match);
298      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
299      if($acl[2] > $perm){
300        $perm = $acl[2];
301      }
302    }
303    if($perm > -1){
304      //we had a match - return it
305      return $perm;
306    }
307  }
308
309  //still here? do the namespace checks
310  if($ns){
311    $path = $ns.':\*';
312  }else{
313    $path = '\*'; //root document
314  }
315
316  do{
317    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
318    if(count($matches)){
319      foreach($matches as $match){
320        $match = preg_replace('/#.*$/','',$match); //ignore comments
321        $acl   = preg_split('/\s+/',$match);
322        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
323        if($acl[2] > $perm){
324          $perm = $acl[2];
325        }
326      }
327      //we had a match - return it
328      return $perm;
329    }
330
331    //get next higher namespace
332    $ns   = getNS($ns);
333
334    if($path != '\*'){
335      $path = $ns.':\*';
336      if($path == ':\*') $path = '\*';
337    }else{
338      //we did this already
339      //looks like there is something wrong with the ACL
340      //break here
341      msg('No ACL setup yet! Denying access to everyone.');
342      return AUTH_NONE;
343    }
344  }while(1); //this should never loop endless
345
346  //still here? return no permissions
347  return AUTH_NONE;
348}
349
350/**
351 * Create a pronouncable password
352 *
353 * @author  Andreas Gohr <andi@splitbrain.org>
354 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
355 *
356 * @return string  pronouncable password
357 */
358function auth_pwgen(){
359  $pw = '';
360  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
361  $v  = 'aeiou';              //vowels
362  $a  = $c.$v;                //both
363
364  //use two syllables...
365  for($i=0;$i < 2; $i++){
366    $pw .= $c[rand(0, strlen($c)-1)];
367    $pw .= $v[rand(0, strlen($v)-1)];
368    $pw .= $a[rand(0, strlen($a)-1)];
369  }
370  //... and add a nice number
371  $pw .= rand(10,99);
372
373  return $pw;
374}
375
376/**
377 * Sends a password to the given user
378 *
379 * @author  Andreas Gohr <andi@splitbrain.org>
380 *
381 * @return bool  true on success
382 */
383function auth_sendPassword($user,$password){
384  global $conf;
385  global $lang;
386	global $auth;
387
388  $hdrs  = '';
389  $userinfo = $auth->getUserData($user);
390
391  if(!$userinfo['mail']) return false;
392
393  $text = rawLocale('password');
394  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
395  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
396  $text = str_replace('@LOGIN@',$user,$text);
397  $text = str_replace('@PASSWORD@',$password,$text);
398  $text = str_replace('@TITLE@',$conf['title'],$text);
399
400  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
401                   $lang['regpwmail'],
402                   $text,
403                   $conf['mailfrom']);
404}
405
406/**
407 * Register a new user
408 *
409 * This registers a new user - Data is read directly from $_POST
410 *
411 * @author  Andreas Gohr <andi@splitbrain.org>
412 *
413 * @return bool  true on success, false on any error
414 */
415function register(){
416  global $lang;
417  global $conf;
418	global $auth;
419
420  if(!$_POST['save']) return false;
421	if(!$auth->canDo('addUser')) return false;
422
423  //clean username
424  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
425  $_POST['login'] = cleanID($_POST['login']);
426  //clean fullname and email
427  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
428  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
429
430  if( empty($_POST['login']) ||
431      empty($_POST['fullname']) ||
432      empty($_POST['email']) ){
433    msg($lang['regmissing'],-1);
434    return false;
435  }
436
437  if ($conf['autopasswd']) {
438    $pass = auth_pwgen();                // automatically generate password
439  } elseif (empty($_POST['pass']) ||
440            empty($_POST['passchk'])) {
441    msg($lang['regmissing'], -1);        // complain about missing passwords
442    return false;
443  } elseif ($_POST['pass'] != $_POST['passchk']) {
444    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
445    return false;
446  } else {
447    $pass = $_POST['pass'];              // accept checked and valid password
448  }
449
450  //check mail
451  if(!mail_isvalid($_POST['email'])){
452    msg($lang['regbadmail'],-1);
453    return false;
454  }
455
456  //okay try to create the user
457  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
458    msg($lang['reguexists'],-1);
459    return false;
460  }
461
462  if (!$conf['autopasswd']) {
463    msg($lang['regsuccess2'],1);
464    return true;
465  }
466
467  // autogenerated password? then send him the password
468  if (auth_sendPassword($_POST['login'],$pass)){
469    msg($lang['regsuccess'],1);
470    return true;
471  }else{
472    msg($lang['regmailfail'],-1);
473    return false;
474  }
475}
476
477/**
478 * Update user profile
479 *
480 * @author    Christopher Smith <chris@jalakai.co.uk>
481 */
482function updateprofile() {
483  global $conf;
484  global $INFO;
485  global $lang;
486	global $auth;
487
488  if(!$_POST['save']) return false;
489
490  // should not be able to get here without Profile being possible...
491  if(!$auth->canDo('Profile')) {
492    msg($lang['profna'],-1);
493    return false;
494  }
495
496  if ($_POST['newpass'] != $_POST['passchk']) {
497    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
498    return false;
499  }
500
501  //clean fullname and email
502  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
503  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
504
505  if (empty($_POST['fullname']) || empty($_POST['email'])) {
506    msg($lang['profnoempty'],-1);
507    return false;
508  }
509
510  if (!mail_isvalid($_POST['email'])){
511    msg($lang['regbadmail'],-1);
512    return false;
513  }
514
515  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
516  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
517  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
518
519  if (!count($changes)) {
520    msg($lang['profnochange'], -1);
521    return false;
522  }
523
524  if ($conf['profileconfirm']) {
525      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
526      msg($lang['badlogin'],-1);
527      return false;
528    }
529  }
530
531  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
532}
533
534/**
535 * Send a  new password
536 *
537 * @author Benoit Chesneau <benoit@bchesneau.info>
538 * @author Chris Smith <chris@jalakai.co.uk>
539 *
540 * @return bool true on success, false on any error
541*/
542function act_resendpwd(){
543    global $lang;
544    global $conf;
545		global $auth;
546
547    if(!$_POST['save']) return false;
548    if(!$conf['resendpasswd']) return false;
549
550    // should not be able to get here without modPass being possible...
551    if(!$auth->canDo('modPass')) {
552      msg($lang['resendna'],-1);
553      return false;
554    }
555
556    if (empty($_POST['login'])) {
557      msg($lang['resendpwdmissing'], -1);
558      return false;
559    } else {
560      $user = $_POST['login'];
561    }
562
563    $userinfo = $auth->getUserData($user);
564    if(!$userinfo['mail']) {
565      msg($lang['resendpwdnouser'], -1);
566      return false;
567    }
568
569    $pass = auth_pwgen();
570    if (!$auth->modifyUser($user,array('pass' => $pass))) {
571      msg('error modifying user data',-1);
572      return false;
573    }
574
575    if (auth_sendPassword($user,$pass)) {
576      msg($lang['resendpwdsuccess'],1);
577    } else {
578      msg($lang['regmailfail'],-1);
579    }
580    return true;
581}
582
583/**
584 * Uses a regular expresion to check if a given mail address is valid
585 *
586 * May not be completly RFC conform!
587 *
588 * @link    http://www.webmasterworld.com/forum88/135.htm
589 *
590 * @param   string $email the address to check
591 * @return  bool          true if address is valid
592 */
593function isvalidemail($email){
594  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
595}
596
597/**
598 * Encrypts a password using the given method and salt
599 *
600 * If the selected method needs a salt and none was given, a random one
601 * is chosen.
602 *
603 * The following methods are understood:
604 *
605 *   smd5  - Salted MD5 hashing
606 *   md5   - Simple MD5 hashing
607 *   sha1  - SHA1 hashing
608 *   ssha  - Salted SHA1 hashing
609 *   crypt - Unix crypt
610 *   mysql - MySQL password (old method)
611 *   my411 - MySQL 4.1.1 password
612 *
613 * @author  Andreas Gohr <andi@splitbrain.org>
614 * @return  string  The crypted password
615 */
616function auth_cryptPassword($clear,$method='',$salt=''){
617  global $conf;
618  if(empty($method)) $method = $conf['passcrypt'];
619
620  //prepare a salt
621  if(empty($salt)) $salt = md5(uniqid(rand(), true));
622
623  switch(strtolower($method)){
624    case 'smd5':
625        return crypt($clear,'$1$'.substr($salt,0,8).'$');
626    case 'md5':
627      return md5($clear);
628    case 'sha1':
629      return sha1($clear);
630    case 'ssha':
631      $salt=substr($salt,0,4);
632      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
633    case 'crypt':
634      return crypt($clear,substr($salt,0,2));
635    case 'mysql':
636      //from http://www.php.net/mysql comment by <soren at byu dot edu>
637      $nr=0x50305735;
638      $nr2=0x12345671;
639      $add=7;
640      $charArr = preg_split("//", $clear);
641      foreach ($charArr as $char) {
642        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
643        $charVal = ord($char);
644        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
645        $nr2 += ($nr2 << 8) ^ $nr;
646        $add += $charVal;
647      }
648      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
649    case 'my411':
650      return '*'.sha1(pack("H*", sha1($clear)));
651    default:
652      msg("Unsupported crypt method $method",-1);
653  }
654}
655
656/**
657 * Verifies a cleartext password against a crypted hash
658 *
659 * The method and salt used for the crypted hash is determined automatically
660 * then the clear text password is crypted using the same method. If both hashs
661 * match true is is returned else false
662 *
663 * @author  Andreas Gohr <andi@splitbrain.org>
664 * @return  bool
665 */
666function auth_verifyPassword($clear,$crypt){
667  $method='';
668  $salt='';
669
670  //determine the used method and salt
671  $len = strlen($crypt);
672  if(substr($crypt,0,3) == '$1$'){
673    $method = 'smd5';
674    $salt   = substr($crypt,3,8);
675  }elseif(substr($crypt,0,6) == '{SSHA}'){
676    $method = 'ssha';
677    $salt   = substr(base64_decode(substr($crypt, 6)),20);
678  }elseif($len == 32){
679    $method = 'md5';
680  }elseif($len == 40){
681    $method = 'sha1';
682  }elseif($len == 16){
683    $method = 'mysql';
684  }elseif($len == 41 && $crypt[0] == '*'){
685    $method = 'my411';
686  }else{
687    $method = 'crypt';
688    $salt   = substr($crypt,0,2);
689  }
690
691  //crypt and compare
692  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
693    return true;
694  }
695  return false;
696}
697
698//Setup VIM: ex: et ts=2 enc=utf-8 :
699