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