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