xref: /dokuwiki/inc/auth.php (revision 4befca0c401cd5d13a1de3ac5e17477757a8c284)
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($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($conf['superuser'], $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){
369  return preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',"'%'.dechex(ord('\\1'))",$name);
370}
371
372/**
373 * Create a pronouncable password
374 *
375 * @author  Andreas Gohr <andi@splitbrain.org>
376 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
377 *
378 * @return string  pronouncable password
379 */
380function auth_pwgen(){
381  $pw = '';
382  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
383  $v  = 'aeiou';              //vowels
384  $a  = $c.$v;                //both
385
386  //use two syllables...
387  for($i=0;$i < 2; $i++){
388    $pw .= $c[rand(0, strlen($c)-1)];
389    $pw .= $v[rand(0, strlen($v)-1)];
390    $pw .= $a[rand(0, strlen($a)-1)];
391  }
392  //... and add a nice number
393  $pw .= rand(10,99);
394
395  return $pw;
396}
397
398/**
399 * Sends a password to the given user
400 *
401 * @author  Andreas Gohr <andi@splitbrain.org>
402 *
403 * @return bool  true on success
404 */
405function auth_sendPassword($user,$password){
406  global $conf;
407  global $lang;
408  global $auth;
409
410  $hdrs  = '';
411  $userinfo = $auth->getUserData($user);
412
413  if(!$userinfo['mail']) return false;
414
415  $text = rawLocale('password');
416  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
417  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
418  $text = str_replace('@LOGIN@',$user,$text);
419  $text = str_replace('@PASSWORD@',$password,$text);
420  $text = str_replace('@TITLE@',$conf['title'],$text);
421
422  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
423                   $lang['regpwmail'],
424                   $text,
425                   $conf['mailfrom']);
426}
427
428/**
429 * Register a new user
430 *
431 * This registers a new user - Data is read directly from $_POST
432 *
433 * @author  Andreas Gohr <andi@splitbrain.org>
434 *
435 * @return bool  true on success, false on any error
436 */
437function register(){
438  global $lang;
439  global $conf;
440  global $auth;
441
442  if(!$_POST['save']) return false;
443  if(!$auth->canDo('addUser')) return false;
444
445  //clean username
446  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
447  $_POST['login'] = cleanID($_POST['login']);
448  //clean fullname and email
449  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
450  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
451
452  if( empty($_POST['login']) ||
453      empty($_POST['fullname']) ||
454      empty($_POST['email']) ){
455    msg($lang['regmissing'],-1);
456    return false;
457  }
458
459  if ($conf['autopasswd']) {
460    $pass = auth_pwgen();                // automatically generate password
461  } elseif (empty($_POST['pass']) ||
462            empty($_POST['passchk'])) {
463    msg($lang['regmissing'], -1);        // complain about missing passwords
464    return false;
465  } elseif ($_POST['pass'] != $_POST['passchk']) {
466    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
467    return false;
468  } else {
469    $pass = $_POST['pass'];              // accept checked and valid password
470  }
471
472  //check mail
473  if(!mail_isvalid($_POST['email'])){
474    msg($lang['regbadmail'],-1);
475    return false;
476  }
477
478  //okay try to create the user
479  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
480    msg($lang['reguexists'],-1);
481    return false;
482  }
483
484  if (!$conf['autopasswd']) {
485    msg($lang['regsuccess2'],1);
486    return true;
487  }
488
489  // autogenerated password? then send him the password
490  if (auth_sendPassword($_POST['login'],$pass)){
491    msg($lang['regsuccess'],1);
492    return true;
493  }else{
494    msg($lang['regmailfail'],-1);
495    return false;
496  }
497}
498
499/**
500 * Update user profile
501 *
502 * @author    Christopher Smith <chris@jalakai.co.uk>
503 */
504function updateprofile() {
505  global $conf;
506  global $INFO;
507  global $lang;
508  global $auth;
509
510  if(!$_POST['save']) return false;
511
512  // should not be able to get here without Profile being possible...
513  if(!$auth->canDo('Profile')) {
514    msg($lang['profna'],-1);
515    return false;
516  }
517
518  if ($_POST['newpass'] != $_POST['passchk']) {
519    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
520    return false;
521  }
522
523  //clean fullname and email
524  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
525  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
526
527  if (empty($_POST['fullname']) || empty($_POST['email'])) {
528    msg($lang['profnoempty'],-1);
529    return false;
530  }
531
532  if (!mail_isvalid($_POST['email'])){
533    msg($lang['regbadmail'],-1);
534    return false;
535  }
536
537  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
538  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
539  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
540
541  if (!count($changes)) {
542    msg($lang['profnochange'], -1);
543    return false;
544  }
545
546  if ($conf['profileconfirm']) {
547      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
548      msg($lang['badlogin'],-1);
549      return false;
550    }
551  }
552
553  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
554}
555
556/**
557 * Send a  new password
558 *
559 * @author Benoit Chesneau <benoit@bchesneau.info>
560 * @author Chris Smith <chris@jalakai.co.uk>
561 *
562 * @return bool true on success, false on any error
563*/
564function act_resendpwd(){
565    global $lang;
566    global $conf;
567    global $auth;
568
569    if(!$_POST['save']) return false;
570    if(!$conf['resendpasswd']) return false;
571
572    // should not be able to get here without modPass being possible...
573    if(!$auth->canDo('modPass')) {
574      msg($lang['resendna'],-1);
575      return false;
576    }
577
578    if (empty($_POST['login'])) {
579      msg($lang['resendpwdmissing'], -1);
580      return false;
581    } else {
582      $user = $_POST['login'];
583    }
584
585    $userinfo = $auth->getUserData($user);
586    if(!$userinfo['mail']) {
587      msg($lang['resendpwdnouser'], -1);
588      return false;
589    }
590
591    $pass = auth_pwgen();
592    if (!$auth->modifyUser($user,array('pass' => $pass))) {
593      msg('error modifying user data',-1);
594      return false;
595    }
596
597    if (auth_sendPassword($user,$pass)) {
598      msg($lang['resendpwdsuccess'],1);
599    } else {
600      msg($lang['regmailfail'],-1);
601    }
602    return true;
603}
604
605/**
606 * Uses a regular expresion to check if a given mail address is valid
607 *
608 * May not be completly RFC conform!
609 *
610 * @link    http://www.webmasterworld.com/forum88/135.htm
611 *
612 * @param   string $email the address to check
613 * @return  bool          true if address is valid
614 */
615function isvalidemail($email){
616  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
617}
618
619/**
620 * Encrypts a password using the given method and salt
621 *
622 * If the selected method needs a salt and none was given, a random one
623 * is chosen.
624 *
625 * The following methods are understood:
626 *
627 *   smd5  - Salted MD5 hashing
628 *   md5   - Simple MD5 hashing
629 *   sha1  - SHA1 hashing
630 *   ssha  - Salted SHA1 hashing
631 *   crypt - Unix crypt
632 *   mysql - MySQL password (old method)
633 *   my411 - MySQL 4.1.1 password
634 *
635 * @author  Andreas Gohr <andi@splitbrain.org>
636 * @return  string  The crypted password
637 */
638function auth_cryptPassword($clear,$method='',$salt=''){
639  global $conf;
640  if(empty($method)) $method = $conf['passcrypt'];
641
642  //prepare a salt
643  if(empty($salt)) $salt = md5(uniqid(rand(), true));
644
645  switch(strtolower($method)){
646    case 'smd5':
647        return crypt($clear,'$1$'.substr($salt,0,8).'$');
648    case 'md5':
649      return md5($clear);
650    case 'sha1':
651      return sha1($clear);
652    case 'ssha':
653      $salt=substr($salt,0,4);
654      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
655    case 'crypt':
656      return crypt($clear,substr($salt,0,2));
657    case 'mysql':
658      //from http://www.php.net/mysql comment by <soren at byu dot edu>
659      $nr=0x50305735;
660      $nr2=0x12345671;
661      $add=7;
662      $charArr = preg_split("//", $clear);
663      foreach ($charArr as $char) {
664        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
665        $charVal = ord($char);
666        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
667        $nr2 += ($nr2 << 8) ^ $nr;
668        $add += $charVal;
669      }
670      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
671    case 'my411':
672      return '*'.sha1(pack("H*", sha1($clear)));
673    default:
674      msg("Unsupported crypt method $method",-1);
675  }
676}
677
678/**
679 * Verifies a cleartext password against a crypted hash
680 *
681 * The method and salt used for the crypted hash is determined automatically
682 * then the clear text password is crypted using the same method. If both hashs
683 * match true is is returned else false
684 *
685 * @author  Andreas Gohr <andi@splitbrain.org>
686 * @return  bool
687 */
688function auth_verifyPassword($clear,$crypt){
689  $method='';
690  $salt='';
691
692  //determine the used method and salt
693  $len = strlen($crypt);
694  if(substr($crypt,0,3) == '$1$'){
695    $method = 'smd5';
696    $salt   = substr($crypt,3,8);
697  }elseif(substr($crypt,0,6) == '{SSHA}'){
698    $method = 'ssha';
699    $salt   = substr(base64_decode(substr($crypt, 6)),20);
700  }elseif($len == 32){
701    $method = 'md5';
702  }elseif($len == 40){
703    $method = 'sha1';
704  }elseif($len == 16){
705    $method = 'mysql';
706  }elseif($len == 41 && $crypt[0] == '*'){
707    $method = 'my411';
708  }else{
709    $method = 'crypt';
710    $salt   = substr($crypt,0,2);
711  }
712
713  //crypt and compare
714  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
715    return true;
716  }
717  return false;
718}
719
720//Setup VIM: ex: et ts=2 enc=utf-8 :
721