xref: /dokuwiki/inc/auth.php (revision 220c87090a31e0013775f1d7841f92f48c978882)
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        die($lang['authmodfailed']);
37      }
38    } else {
39      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  //if user is superuser return 255 (acl_admin)
268  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
269
270  //make sure groups is an array
271  if(!is_array($groups)) $groups = array();
272
273  //prepend groups with @
274  $cnt = count($groups);
275  for($i=0; $i<$cnt; $i++){
276    $groups[$i] = '@'.$groups[$i];
277  }
278  //if user is in superuser group return 255 (acl_admin)
279  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
280
281  $ns    = getNS($id);
282  $perm  = -1;
283
284  if($user){
285    //add ALL group
286    $groups[] = '@ALL';
287    //add User
288    $groups[] = $user;
289    //build regexp
290    $regexp   = join('|',$groups);
291  }else{
292    $regexp = '@ALL';
293  }
294
295  //check exact match first
296  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
297  if(count($matches)){
298    foreach($matches as $match){
299      $match = preg_replace('/#.*$/','',$match); //ignore comments
300      $acl   = preg_split('/\s+/',$match);
301      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
302      if($acl[2] > $perm){
303        $perm = $acl[2];
304      }
305    }
306    if($perm > -1){
307      //we had a match - return it
308      return $perm;
309    }
310  }
311
312  //still here? do the namespace checks
313  if($ns){
314    $path = $ns.':\*';
315  }else{
316    $path = '\*'; //root document
317  }
318
319  do{
320    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
321    if(count($matches)){
322      foreach($matches as $match){
323        $match = preg_replace('/#.*$/','',$match); //ignore comments
324        $acl   = preg_split('/\s+/',$match);
325        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
326        if($acl[2] > $perm){
327          $perm = $acl[2];
328        }
329      }
330      //we had a match - return it
331      return $perm;
332    }
333
334    //get next higher namespace
335    $ns   = getNS($ns);
336
337    if($path != '\*'){
338      $path = $ns.':\*';
339      if($path == ':\*') $path = '\*';
340    }else{
341      //we did this already
342      //looks like there is something wrong with the ACL
343      //break here
344      msg('No ACL setup yet! Denying access to everyone.');
345      return AUTH_NONE;
346    }
347  }while(1); //this should never loop endless
348
349  //still here? return no permissions
350  return AUTH_NONE;
351}
352
353/**
354 * Create a pronouncable password
355 *
356 * @author  Andreas Gohr <andi@splitbrain.org>
357 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
358 *
359 * @return string  pronouncable password
360 */
361function auth_pwgen(){
362  $pw = '';
363  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
364  $v  = 'aeiou';              //vowels
365  $a  = $c.$v;                //both
366
367  //use two syllables...
368  for($i=0;$i < 2; $i++){
369    $pw .= $c[rand(0, strlen($c)-1)];
370    $pw .= $v[rand(0, strlen($v)-1)];
371    $pw .= $a[rand(0, strlen($a)-1)];
372  }
373  //... and add a nice number
374  $pw .= rand(10,99);
375
376  return $pw;
377}
378
379/**
380 * Sends a password to the given user
381 *
382 * @author  Andreas Gohr <andi@splitbrain.org>
383 *
384 * @return bool  true on success
385 */
386function auth_sendPassword($user,$password){
387  global $conf;
388  global $lang;
389  global $auth;
390
391  $hdrs  = '';
392  $userinfo = $auth->getUserData($user);
393
394  if(!$userinfo['mail']) return false;
395
396  $text = rawLocale('password');
397  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
398  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
399  $text = str_replace('@LOGIN@',$user,$text);
400  $text = str_replace('@PASSWORD@',$password,$text);
401  $text = str_replace('@TITLE@',$conf['title'],$text);
402
403  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
404                   $lang['regpwmail'],
405                   $text,
406                   $conf['mailfrom']);
407}
408
409/**
410 * Register a new user
411 *
412 * This registers a new user - Data is read directly from $_POST
413 *
414 * @author  Andreas Gohr <andi@splitbrain.org>
415 *
416 * @return bool  true on success, false on any error
417 */
418function register(){
419  global $lang;
420  global $conf;
421  global $auth;
422
423  if(!$_POST['save']) return false;
424  if(!$auth->canDo('addUser')) return false;
425
426  //clean username
427  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
428  $_POST['login'] = cleanID($_POST['login']);
429  //clean fullname and email
430  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
431  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
432
433  if( empty($_POST['login']) ||
434      empty($_POST['fullname']) ||
435      empty($_POST['email']) ){
436    msg($lang['regmissing'],-1);
437    return false;
438  }
439
440  if ($conf['autopasswd']) {
441    $pass = auth_pwgen();                // automatically generate password
442  } elseif (empty($_POST['pass']) ||
443            empty($_POST['passchk'])) {
444    msg($lang['regmissing'], -1);        // complain about missing passwords
445    return false;
446  } elseif ($_POST['pass'] != $_POST['passchk']) {
447    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
448    return false;
449  } else {
450    $pass = $_POST['pass'];              // accept checked and valid password
451  }
452
453  //check mail
454  if(!mail_isvalid($_POST['email'])){
455    msg($lang['regbadmail'],-1);
456    return false;
457  }
458
459  //okay try to create the user
460  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
461    msg($lang['reguexists'],-1);
462    return false;
463  }
464
465  if (!$conf['autopasswd']) {
466    msg($lang['regsuccess2'],1);
467    return true;
468  }
469
470  // autogenerated password? then send him the password
471  if (auth_sendPassword($_POST['login'],$pass)){
472    msg($lang['regsuccess'],1);
473    return true;
474  }else{
475    msg($lang['regmailfail'],-1);
476    return false;
477  }
478}
479
480/**
481 * Update user profile
482 *
483 * @author    Christopher Smith <chris@jalakai.co.uk>
484 */
485function updateprofile() {
486  global $conf;
487  global $INFO;
488  global $lang;
489  global $auth;
490
491  if(!$_POST['save']) return false;
492
493  // should not be able to get here without Profile being possible...
494  if(!$auth->canDo('Profile')) {
495    msg($lang['profna'],-1);
496    return false;
497  }
498
499  if ($_POST['newpass'] != $_POST['passchk']) {
500    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
501    return false;
502  }
503
504  //clean fullname and email
505  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
506  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
507
508  if (empty($_POST['fullname']) || empty($_POST['email'])) {
509    msg($lang['profnoempty'],-1);
510    return false;
511  }
512
513  if (!mail_isvalid($_POST['email'])){
514    msg($lang['regbadmail'],-1);
515    return false;
516  }
517
518  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
519  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
520  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
521
522  if (!count($changes)) {
523    msg($lang['profnochange'], -1);
524    return false;
525  }
526
527  if ($conf['profileconfirm']) {
528      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
529      msg($lang['badlogin'],-1);
530      return false;
531    }
532  }
533
534  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
535}
536
537/**
538 * Send a  new password
539 *
540 * @author Benoit Chesneau <benoit@bchesneau.info>
541 * @author Chris Smith <chris@jalakai.co.uk>
542 *
543 * @return bool true on success, false on any error
544*/
545function act_resendpwd(){
546    global $lang;
547    global $conf;
548    global $auth;
549
550    if(!$_POST['save']) return false;
551    if(!$conf['resendpasswd']) return false;
552
553    // should not be able to get here without modPass being possible...
554    if(!$auth->canDo('modPass')) {
555      msg($lang['resendna'],-1);
556      return false;
557    }
558
559    if (empty($_POST['login'])) {
560      msg($lang['resendpwdmissing'], -1);
561      return false;
562    } else {
563      $user = $_POST['login'];
564    }
565
566    $userinfo = $auth->getUserData($user);
567    if(!$userinfo['mail']) {
568      msg($lang['resendpwdnouser'], -1);
569      return false;
570    }
571
572    $pass = auth_pwgen();
573    if (!$auth->modifyUser($user,array('pass' => $pass))) {
574      msg('error modifying user data',-1);
575      return false;
576    }
577
578    if (auth_sendPassword($user,$pass)) {
579      msg($lang['resendpwdsuccess'],1);
580    } else {
581      msg($lang['regmailfail'],-1);
582    }
583    return true;
584}
585
586/**
587 * Uses a regular expresion to check if a given mail address is valid
588 *
589 * May not be completly RFC conform!
590 *
591 * @link    http://www.webmasterworld.com/forum88/135.htm
592 *
593 * @param   string $email the address to check
594 * @return  bool          true if address is valid
595 */
596function isvalidemail($email){
597  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
598}
599
600/**
601 * Encrypts a password using the given method and salt
602 *
603 * If the selected method needs a salt and none was given, a random one
604 * is chosen.
605 *
606 * The following methods are understood:
607 *
608 *   smd5  - Salted MD5 hashing
609 *   md5   - Simple MD5 hashing
610 *   sha1  - SHA1 hashing
611 *   ssha  - Salted SHA1 hashing
612 *   crypt - Unix crypt
613 *   mysql - MySQL password (old method)
614 *   my411 - MySQL 4.1.1 password
615 *
616 * @author  Andreas Gohr <andi@splitbrain.org>
617 * @return  string  The crypted password
618 */
619function auth_cryptPassword($clear,$method='',$salt=''){
620  global $conf;
621  if(empty($method)) $method = $conf['passcrypt'];
622
623  //prepare a salt
624  if(empty($salt)) $salt = md5(uniqid(rand(), true));
625
626  switch(strtolower($method)){
627    case 'smd5':
628        return crypt($clear,'$1$'.substr($salt,0,8).'$');
629    case 'md5':
630      return md5($clear);
631    case 'sha1':
632      return sha1($clear);
633    case 'ssha':
634      $salt=substr($salt,0,4);
635      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
636    case 'crypt':
637      return crypt($clear,substr($salt,0,2));
638    case 'mysql':
639      //from http://www.php.net/mysql comment by <soren at byu dot edu>
640      $nr=0x50305735;
641      $nr2=0x12345671;
642      $add=7;
643      $charArr = preg_split("//", $clear);
644      foreach ($charArr as $char) {
645        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
646        $charVal = ord($char);
647        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
648        $nr2 += ($nr2 << 8) ^ $nr;
649        $add += $charVal;
650      }
651      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
652    case 'my411':
653      return '*'.sha1(pack("H*", sha1($clear)));
654    default:
655      msg("Unsupported crypt method $method",-1);
656  }
657}
658
659/**
660 * Verifies a cleartext password against a crypted hash
661 *
662 * The method and salt used for the crypted hash is determined automatically
663 * then the clear text password is crypted using the same method. If both hashs
664 * match true is is returned else false
665 *
666 * @author  Andreas Gohr <andi@splitbrain.org>
667 * @return  bool
668 */
669function auth_verifyPassword($clear,$crypt){
670  $method='';
671  $salt='';
672
673  //determine the used method and salt
674  $len = strlen($crypt);
675  if(substr($crypt,0,3) == '$1$'){
676    $method = 'smd5';
677    $salt   = substr($crypt,3,8);
678  }elseif(substr($crypt,0,6) == '{SSHA}'){
679    $method = 'ssha';
680    $salt   = substr(base64_decode(substr($crypt, 6)),20);
681  }elseif($len == 32){
682    $method = 'md5';
683  }elseif($len == 40){
684    $method = 'sha1';
685  }elseif($len == 16){
686    $method = 'mysql';
687  }elseif($len == 41 && $crypt[0] == '*'){
688    $method = 'my411';
689  }else{
690    $method = 'crypt';
691    $salt   = substr($crypt,0,2);
692  }
693
694  //crypt and compare
695  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
696    return true;
697  }
698  return false;
699}
700
701//Setup VIM: ex: et ts=2 enc=utf-8 :
702