xref: /dokuwiki/inc/auth.php (revision 5d87b2ccd4d2bf7733dcc50e4bf2c4cc8bc95f51)
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')) die('meh.');
13  require_once(DOKU_INC.'inc/common.php');
14  require_once(DOKU_INC.'inc/io.php');
15
16  // some ACL level defines
17  define('AUTH_NONE',0);
18  define('AUTH_READ',1);
19  define('AUTH_EDIT',2);
20  define('AUTH_CREATE',4);
21  define('AUTH_UPLOAD',8);
22  define('AUTH_DELETE',16);
23  define('AUTH_ADMIN',255);
24
25  global $conf;
26
27  if($conf['useacl']){
28    require_once(DOKU_INC.'inc/blowfish.php');
29    require_once(DOKU_INC.'inc/mail.php');
30
31    global $auth;
32
33    // load the the backend auth functions and instantiate the auth object
34    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
35      require_once(DOKU_INC.'inc/auth/basic.class.php');
36      require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
37
38      $auth_class = "auth_".$conf['authtype'];
39      if (class_exists($auth_class)) {
40        $auth = new $auth_class();
41        if ($auth->success == false) {
42          // degrade to unauthenticated user
43          unset($auth);
44          auth_logoff();
45          msg($lang['authtempfail'], -1);
46        }
47      } else {
48        nice_die($lang['authmodfailed']);
49      }
50    } else {
51      nice_die($lang['authmodfailed']);
52    }
53  }
54
55  // do the login either by cookie or provided credentials
56  if($conf['useacl']){
57    if($auth){
58      if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59      if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60      if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61      $_REQUEST['http_credentials'] = false;
62      if (!$conf['rememberme']) $_REQUEST['r'] = false;
63
64      // if no credentials were given try to use HTTP auth (for SSO)
65      if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
66        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
67        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
68        $_REQUEST['http_credentials'] = true;
69      }
70
71      if($_REQUEST['authtok']){
72        // when an authentication token is given, trust the session
73        auth_validateToken($_REQUEST['authtok']);
74      }elseif(!is_null($auth) && $auth->canDo('external')){
75        // external trust mechanism in place
76        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
77      }else{
78        auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r'],$_REQUEST['http_credentials']);
79      }
80    }
81
82    //load ACL into a global array
83    global $AUTH_ACL;
84    if(is_readable(DOKU_CONF.'acl.auth.php')){
85      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
86      if(isset($_SERVER['REMOTE_USER'])){
87        $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
88        $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
89      }
90    }else{
91      $AUTH_ACL = array();
92    }
93  }
94
95/**
96 * This tries to login the user based on the sent auth credentials
97 *
98 * The authentication works like this: if a username was given
99 * a new login is assumed and user/password are checked. If they
100 * are correct the password is encrypted with blowfish and stored
101 * together with the username in a cookie - the same info is stored
102 * in the session, too. Additonally a browserID is stored in the
103 * session.
104 *
105 * If no username was given the cookie is checked: if the username,
106 * crypted password and browserID match between session and cookie
107 * no further testing is done and the user is accepted
108 *
109 * If a cookie was found but no session info was availabe the
110 * blowfish encrypted password from the cookie is decrypted and
111 * together with username rechecked by calling this function again.
112 *
113 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
114 * are set.
115 *
116 * @author  Andreas Gohr <andi@splitbrain.org>
117 *
118 * @param   string  $user    Username
119 * @param   string  $pass    Cleartext Password
120 * @param   bool    $sticky  Cookie should not expire
121 * @param   bool    $silent  Don't show error on bad auth
122 * @return  bool             true on successful auth
123*/
124function auth_login($user,$pass,$sticky=false,$silent=false){
125  global $USERINFO;
126  global $conf;
127  global $lang;
128  global $auth;
129  $sticky ? $sticky = true : $sticky = false; //sanity check
130
131  if(!empty($user)){
132    //usual login
133    if ($auth->checkPass($user,$pass)){
134      // make logininfo globally available
135      $_SERVER['REMOTE_USER'] = $user;
136      auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
137      return true;
138    }else{
139      //invalid credentials - log off
140      if(!$silent) msg($lang['badlogin'],-1);
141      auth_logoff();
142      return false;
143    }
144  }else{
145    // read cookie information
146    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
147    list($user,$sticky,$pass) = split('\|',$cookie,3);
148    // get session info
149    $session = $_SESSION[DOKU_COOKIE]['auth'];
150    if($user && $pass){
151      // we got a cookie - see if we can trust it
152      if(isset($session) &&
153        $auth->useSessionCache($user) &&
154        ($session['time'] >= time()-$conf['auth_security_timeout']) &&
155        ($session['user'] == $user) &&
156        ($session['pass'] == $pass) &&  //still crypted
157        ($session['buid'] == auth_browseruid()) ){
158        // he has session, cookie and browser right - let him in
159        $_SERVER['REMOTE_USER'] = $user;
160        $USERINFO = $session['info']; //FIXME move all references to session
161        return true;
162      }
163      // no we don't trust it yet - recheck pass but silent
164      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
165      return auth_login($user,$pass,$sticky,true);
166    }
167  }
168  //just to be sure
169  auth_logoff();
170  return false;
171}
172
173/**
174 * Checks if a given authentication token was stored in the session
175 *
176 * Will setup authentication data using data from the session if the
177 * token is correct. Will exit with a 401 Status if not.
178 *
179 * @author Andreas Gohr <andi@splitbrain.org>
180 * @param  string $token The authentication token
181 * @return boolean true (or will exit on failure)
182 */
183function auth_validateToken($token){
184    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
185        // bad token
186        header("HTTP/1.0 401 Unauthorized");
187        print 'Invalid auth token - maybe the session timed out';
188        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
189        exit;
190    }
191    // still here? trust the session data
192    global $USERINFO;
193    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
194    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
195    return true;
196}
197
198/**
199 * Create an auth token and store it in the session
200 *
201 * NOTE: this is completely unrelated to the getSecurityToken() function
202 *
203 * @author Andreas Gohr <andi@splitbrain.org>
204 * @return string The auth token
205 */
206function auth_createToken(){
207    $token = md5(mt_rand());
208    @session_start(); // reopen the session if needed
209    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
210    session_write_close();
211    return $token;
212}
213
214/**
215 * Builds a pseudo UID from browser and IP data
216 *
217 * This is neither unique nor unfakable - still it adds some
218 * security. Using the first part of the IP makes sure
219 * proxy farms like AOLs are stil okay.
220 *
221 * @author  Andreas Gohr <andi@splitbrain.org>
222 *
223 * @return  string  a MD5 sum of various browser headers
224 */
225function auth_browseruid(){
226  $uid  = '';
227  $uid .= $_SERVER['HTTP_USER_AGENT'];
228  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
229  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
230  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
231  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
232  return md5($uid);
233}
234
235/**
236 * Creates a random key to encrypt the password in cookies
237 *
238 * This function tries to read the password for encrypting
239 * cookies from $conf['metadir'].'/_htcookiesalt'
240 * if no such file is found a random key is created and
241 * and stored in this file.
242 *
243 * @author  Andreas Gohr <andi@splitbrain.org>
244 *
245 * @return  string
246 */
247function auth_cookiesalt(){
248  global $conf;
249  $file = $conf['metadir'].'/_htcookiesalt';
250  $salt = io_readFile($file);
251  if(empty($salt)){
252    $salt = uniqid(rand(),true);
253    io_saveFile($file,$salt);
254  }
255  return $salt;
256}
257
258/**
259 * This clears all authenticationdata and thus log the user
260 * off
261 *
262 * @author  Andreas Gohr <andi@splitbrain.org>
263 */
264function auth_logoff(){
265  global $conf;
266  global $USERINFO;
267  global $INFO, $ID;
268  global $auth;
269
270  // reopen session
271  @session_start();
272
273  if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
274    unset($_SESSION[DOKU_COOKIE]['auth']['user']);
275  if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
276    unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
277  if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
278    unset($_SESSION[DOKU_COOKIE]['auth']['info']);
279  if(isset($_SESSION[DOKU_COOKIE]['bc']))
280    unset($_SESSION[DOKU_COOKIE]['bc']);
281  if(isset($_SERVER['REMOTE_USER']))
282    unset($_SERVER['REMOTE_USER']);
283  $USERINFO=null; //FIXME
284
285  if (version_compare(PHP_VERSION, '5.2.0', '>')) {
286    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,($conf['securecookie'] && is_ssl()),true);
287  }else{
288    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,($conf['securecookie'] && is_ssl()));
289  }
290
291  if($auth && $auth->canDo('logoff')){
292    $auth->logOff();
293  }
294
295  // close session again
296  session_write_close();
297}
298
299/**
300 * Check if a user is a manager
301 *
302 * Should usually be called without any parameters to check the current
303 * user.
304 *
305 * The info is available through $INFO['ismanager'], too
306 *
307 * @author Andreas Gohr <andi@splitbrain.org>
308 * @see    auth_isadmin
309 * @param  string user      - Username
310 * @param  array  groups    - List of groups the user is in
311 * @param  bool   adminonly - when true checks if user is admin
312 */
313function auth_ismanager($user=null,$groups=null,$adminonly=false){
314  global $conf;
315  global $USERINFO;
316
317  if(!$conf['useacl']) return false;
318  if(is_null($user))   $user   = $_SERVER['REMOTE_USER'];
319  if(is_null($groups)) $groups = (array) $USERINFO['grps'];
320  $user   = auth_nameencode($user);
321
322  // check username against superuser and manager
323  $superusers = explode(',', $conf['superuser']);
324  $superusers = array_unique($superusers);
325  $superusers = array_map('trim', $superusers);
326  // prepare an array containing only true values for array_map call
327  $alltrue = array_fill(0, count($superusers), true);
328  $superusers = array_map('auth_nameencode', $superusers, $alltrue);
329  if(in_array($user, $superusers)) return true;
330
331  if(!$adminonly){
332    $managers = explode(',', $conf['manager']);
333    $managers = array_unique($managers);
334    $managers = array_map('trim', $managers);
335    // prepare an array containing only true values for array_map call
336    $alltrue = array_fill(0, count($managers), true);
337    $managers = array_map('auth_nameencode', $managers, $alltrue);
338    if(in_array($user, $managers)) return true;
339  }
340
341  // check user's groups against superuser and manager
342  if (!empty($groups)) {
343
344    //prepend groups with @ and nameencode
345    $cnt = count($groups);
346    for($i=0; $i<$cnt; $i++){
347      $groups[$i] = '@'.auth_nameencode($groups[$i]);
348    }
349
350    // check groups against superuser and manager
351    foreach($superusers as $supu)
352      if(in_array($supu, $groups)) return true;
353    if(!$adminonly){
354      foreach($managers as $mana)
355        if(in_array($mana, $groups)) return true;
356    }
357  }
358
359  return false;
360}
361
362/**
363 * Check if a user is admin
364 *
365 * Alias to auth_ismanager with adminonly=true
366 *
367 * The info is available through $INFO['isadmin'], too
368 *
369 * @author Andreas Gohr <andi@splitbrain.org>
370 * @see auth_ismanager
371 */
372function auth_isadmin($user=null,$groups=null){
373  return auth_ismanager($user,$groups,true);
374}
375
376/**
377 * Convinience function for auth_aclcheck()
378 *
379 * This checks the permissions for the current user
380 *
381 * @author  Andreas Gohr <andi@splitbrain.org>
382 *
383 * @param  string  $id  page ID
384 * @return int          permission level
385 */
386function auth_quickaclcheck($id){
387  global $conf;
388  global $USERINFO;
389  # if no ACL is used always return upload rights
390  if(!$conf['useacl']) return AUTH_UPLOAD;
391  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
392}
393
394/**
395 * Returns the maximum rights a user has for
396 * the given ID or its namespace
397 *
398 * @author  Andreas Gohr <andi@splitbrain.org>
399 *
400 * @param  string  $id     page ID
401 * @param  string  $user   Username
402 * @param  array   $groups Array of groups the user is in
403 * @return int             permission level
404 */
405function auth_aclcheck($id,$user,$groups){
406  global $conf;
407  global $AUTH_ACL;
408
409  // if no ACL is used always return upload rights
410  if(!$conf['useacl']) return AUTH_UPLOAD;
411
412  //make sure groups is an array
413  if(!is_array($groups)) $groups = array();
414
415  //if user is superuser or in superusergroup return 255 (acl_admin)
416  if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
417
418  $user = auth_nameencode($user);
419
420  //prepend groups with @ and nameencode
421  $cnt = count($groups);
422  for($i=0; $i<$cnt; $i++){
423    $groups[$i] = '@'.auth_nameencode($groups[$i]);
424  }
425
426  $ns    = getNS($id);
427  $perm  = -1;
428
429  if($user || count($groups)){
430    //add ALL group
431    $groups[] = '@ALL';
432    //add User
433    if($user) $groups[] = $user;
434    //build regexp
435    $regexp   = join('|',$groups);
436  }else{
437    $regexp = '@ALL';
438  }
439
440  //check exact match first
441  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
442  if(count($matches)){
443    foreach($matches as $match){
444      $match = preg_replace('/#.*$/','',$match); //ignore comments
445      $acl   = preg_split('/\s+/',$match);
446      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
447      if($acl[2] > $perm){
448        $perm = $acl[2];
449      }
450    }
451    if($perm > -1){
452      //we had a match - return it
453      return $perm;
454    }
455  }
456
457  //still here? do the namespace checks
458  if($ns){
459    $path = $ns.':\*';
460  }else{
461    $path = '\*'; //root document
462  }
463
464  do{
465    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
466    if(count($matches)){
467      foreach($matches as $match){
468        $match = preg_replace('/#.*$/','',$match); //ignore comments
469        $acl   = preg_split('/\s+/',$match);
470        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
471        if($acl[2] > $perm){
472          $perm = $acl[2];
473        }
474      }
475      //we had a match - return it
476      return $perm;
477    }
478
479    //get next higher namespace
480    $ns   = getNS($ns);
481
482    if($path != '\*'){
483      $path = $ns.':\*';
484      if($path == ':\*') $path = '\*';
485    }else{
486      //we did this already
487      //looks like there is something wrong with the ACL
488      //break here
489      msg('No ACL setup yet! Denying access to everyone.');
490      return AUTH_NONE;
491    }
492  }while(1); //this should never loop endless
493
494  //still here? return no permissions
495  return AUTH_NONE;
496}
497
498/**
499 * Encode ASCII special chars
500 *
501 * Some auth backends allow special chars in their user and groupnames
502 * The special chars are encoded with this function. Only ASCII chars
503 * are encoded UTF-8 multibyte are left as is (different from usual
504 * urlencoding!).
505 *
506 * Decoding can be done with rawurldecode
507 *
508 * @author Andreas Gohr <gohr@cosmocode.de>
509 * @see rawurldecode()
510 */
511function auth_nameencode($name,$skip_group=false){
512  global $cache_authname;
513  $cache =& $cache_authname;
514  $name  = (string) $name;
515
516  if (!isset($cache[$name][$skip_group])) {
517    if($skip_group && $name{0} =='@'){
518      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
519                                                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
520    }else{
521      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
522                                                "'%'.dechex(ord(substr('\\1',-1)))",$name);
523    }
524  }
525
526  return $cache[$name][$skip_group];
527}
528
529/**
530 * Create a pronouncable password
531 *
532 * @author  Andreas Gohr <andi@splitbrain.org>
533 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
534 *
535 * @return string  pronouncable password
536 */
537function auth_pwgen(){
538  $pw = '';
539  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
540  $v  = 'aeiou';              //vowels
541  $a  = $c.$v;                //both
542
543  //use two syllables...
544  for($i=0;$i < 2; $i++){
545    $pw .= $c[rand(0, strlen($c)-1)];
546    $pw .= $v[rand(0, strlen($v)-1)];
547    $pw .= $a[rand(0, strlen($a)-1)];
548  }
549  //... and add a nice number
550  $pw .= rand(10,99);
551
552  return $pw;
553}
554
555/**
556 * Sends a password to the given user
557 *
558 * @author  Andreas Gohr <andi@splitbrain.org>
559 *
560 * @return bool  true on success
561 */
562function auth_sendPassword($user,$password){
563  global $conf;
564  global $lang;
565  global $auth;
566
567  $hdrs  = '';
568  $userinfo = $auth->getUserData($user);
569
570  if(!$userinfo['mail']) return false;
571
572  $text = rawLocale('password');
573  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
574  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
575  $text = str_replace('@LOGIN@',$user,$text);
576  $text = str_replace('@PASSWORD@',$password,$text);
577  $text = str_replace('@TITLE@',$conf['title'],$text);
578
579  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
580                   $lang['regpwmail'],
581                   $text,
582                   $conf['mailfrom']);
583}
584
585/**
586 * Register a new user
587 *
588 * This registers a new user - Data is read directly from $_POST
589 *
590 * @author  Andreas Gohr <andi@splitbrain.org>
591 *
592 * @return bool  true on success, false on any error
593 */
594function register(){
595  global $lang;
596  global $conf;
597  global $auth;
598
599  if(!$_POST['save']) return false;
600  if(!$auth->canDo('addUser')) return false;
601
602  //clean username
603  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
604  $_POST['login'] = cleanID($_POST['login']);
605  //clean fullname and email
606  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
607  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
608
609  if( empty($_POST['login']) ||
610      empty($_POST['fullname']) ||
611      empty($_POST['email']) ){
612    msg($lang['regmissing'],-1);
613    return false;
614  }
615
616  if ($conf['autopasswd']) {
617    $pass = auth_pwgen();                // automatically generate password
618  } elseif (empty($_POST['pass']) ||
619            empty($_POST['passchk'])) {
620    msg($lang['regmissing'], -1);        // complain about missing passwords
621    return false;
622  } elseif ($_POST['pass'] != $_POST['passchk']) {
623    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
624    return false;
625  } else {
626    $pass = $_POST['pass'];              // accept checked and valid password
627  }
628
629  //check mail
630  if(!mail_isvalid($_POST['email'])){
631    msg($lang['regbadmail'],-1);
632    return false;
633  }
634
635  //okay try to create the user
636  if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
637    msg($lang['reguexists'],-1);
638    return false;
639  }
640
641  // create substitutions for use in notification email
642  $substitutions = array(
643    'NEWUSER' => $_POST['login'],
644    'NEWNAME' => $_POST['fullname'],
645    'NEWEMAIL' => $_POST['email'],
646  );
647
648  if (!$conf['autopasswd']) {
649    msg($lang['regsuccess2'],1);
650    notify('', 'register', '', $_POST['login'], false, $substitutions);
651    return true;
652  }
653
654  // autogenerated password? then send him the password
655  if (auth_sendPassword($_POST['login'],$pass)){
656    msg($lang['regsuccess'],1);
657    notify('', 'register', '', $_POST['login'], false, $substitutions);
658    return true;
659  }else{
660    msg($lang['regmailfail'],-1);
661    return false;
662  }
663}
664
665/**
666 * Update user profile
667 *
668 * @author    Christopher Smith <chris@jalakai.co.uk>
669 */
670function updateprofile() {
671  global $conf;
672  global $INFO;
673  global $lang;
674  global $auth;
675
676  if(empty($_POST['save'])) return false;
677  if(!checkSecurityToken()) return false;
678
679  // should not be able to get here without Profile being possible...
680  if(!$auth->canDo('Profile')) {
681    msg($lang['profna'],-1);
682    return false;
683  }
684
685  if ($_POST['newpass'] != $_POST['passchk']) {
686    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
687    return false;
688  }
689
690  //clean fullname and email
691  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
692  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
693
694  if (empty($_POST['fullname']) || empty($_POST['email'])) {
695    msg($lang['profnoempty'],-1);
696    return false;
697  }
698
699  if (!mail_isvalid($_POST['email'])){
700    msg($lang['regbadmail'],-1);
701    return false;
702  }
703
704  if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
705  if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
706  if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
707
708
709  if (!count($changes)) {
710    msg($lang['profnochange'], -1);
711    return false;
712  }
713
714  if ($conf['profileconfirm']) {
715    if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
716      msg($lang['badlogin'],-1);
717      return false;
718    }
719  }
720
721  if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
722    // update cookie and session with the changed data
723    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
724    list($user,$sticky,$pass) = split('\|',$cookie,3);
725    if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
726
727    auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
728    return true;
729  }
730}
731
732/**
733 * Send a  new password
734 *
735 * This function handles both phases of the password reset:
736 *
737 *   - handling the first request of password reset
738 *   - validating the password reset auth token
739 *
740 * @author Benoit Chesneau <benoit@bchesneau.info>
741 * @author Chris Smith <chris@jalakai.co.uk>
742 * @author Andreas Gohr <andi@splitbrain.org>
743 *
744 * @return bool true on success, false on any error
745*/
746function act_resendpwd(){
747    global $lang;
748    global $conf;
749    global $auth;
750
751    if(!actionOK('resendpwd')) return false;
752
753    // should not be able to get here without modPass being possible...
754    if(!$auth->canDo('modPass')) {
755        msg($lang['resendna'],-1);
756        return false;
757    }
758
759    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
760
761    if($token){
762        // we're in token phase
763
764        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
765        if(!@file_exists($tfile)){
766            msg($lang['resendpwdbadauth'],-1);
767            return false;
768        }
769        $user = io_readfile($tfile);
770        @unlink($tfile);
771        $userinfo = $auth->getUserData($user);
772        if(!$userinfo['mail']) {
773            msg($lang['resendpwdnouser'], -1);
774            return false;
775        }
776
777        $pass = auth_pwgen();
778        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
779            msg('error modifying user data',-1);
780            return false;
781        }
782
783        if (auth_sendPassword($user,$pass)) {
784            msg($lang['resendpwdsuccess'],1);
785        } else {
786            msg($lang['regmailfail'],-1);
787        }
788        return true;
789
790    } else {
791        // we're in request phase
792
793        if(!$_POST['save']) return false;
794
795        if (empty($_POST['login'])) {
796            msg($lang['resendpwdmissing'], -1);
797            return false;
798        } else {
799            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
800            $user = cleanID($_POST['login']);
801        }
802
803        $userinfo = $auth->getUserData($user);
804        if(!$userinfo['mail']) {
805            msg($lang['resendpwdnouser'], -1);
806            return false;
807        }
808
809        // generate auth token
810        $token = md5(auth_cookiesalt().$user); //secret but user based
811        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
812        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
813
814        io_saveFile($tfile,$user);
815
816        $text = rawLocale('pwconfirm');
817        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
818        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
819        $text = str_replace('@LOGIN@',$user,$text);
820        $text = str_replace('@TITLE@',$conf['title'],$text);
821        $text = str_replace('@CONFIRM@',$url,$text);
822
823        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
824                     $lang['regpwmail'],
825                     $text,
826                     $conf['mailfrom'])){
827            msg($lang['resendpwdconfirm'],1);
828        }else{
829            msg($lang['regmailfail'],-1);
830        }
831        return true;
832    }
833
834    return false; // never reached
835}
836
837/**
838 * Encrypts a password using the given method and salt
839 *
840 * If the selected method needs a salt and none was given, a random one
841 * is chosen.
842 *
843 * The following methods are understood:
844 *
845 *   smd5  - Salted MD5 hashing
846 *   apr1  - Apache salted MD5 hashing
847 *   md5   - Simple MD5 hashing
848 *   sha1  - SHA1 hashing
849 *   ssha  - Salted SHA1 hashing
850 *   crypt - Unix crypt
851 *   mysql - MySQL password (old method)
852 *   my411 - MySQL 4.1.1 password
853 *
854 * @author  Andreas Gohr <andi@splitbrain.org>
855 * @return  string  The crypted password
856 */
857function auth_cryptPassword($clear,$method='',$salt=null){
858    global $conf;
859    if(empty($method)) $method = $conf['passcrypt'];
860
861    //prepare a salt
862    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
863
864    switch(strtolower($method)){
865        case 'smd5':
866            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
867            // when crypt can't handle SMD5, falls through to pure PHP implementation
868            $magic = '1';
869        case 'apr1':
870            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
871            if(!$magic) $magic = 'apr1';
872            $salt = substr($salt,0,8);
873            $len = strlen($clear);
874            $text = $clear.'$'.$magic.'$'.$salt;
875            $bin = pack("H32", md5($clear.$salt.$clear));
876            for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
877            for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $clear{0}; }
878            $bin = pack("H32", md5($text));
879            for($i = 0; $i < 1000; $i++) {
880                $new = ($i & 1) ? $clear : $bin;
881                if ($i % 3) $new .= $salt;
882                if ($i % 7) $new .= $clear;
883                $new .= ($i & 1) ? $bin : $clear;
884                $bin = pack("H32", md5($new));
885            }
886            $tmp = '';
887            for ($i = 0; $i < 5; $i++) {
888                $k = $i + 6;
889                $j = $i + 12;
890                if ($j == 16) $j = 5;
891                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
892            }
893            $tmp = chr(0).chr(0).$bin[11].$tmp;
894            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
895                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
896                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
897            return '$'.$magic.'$'.$salt.'$'.$tmp;
898        case 'md5':
899            return md5($clear);
900        case 'sha1':
901            return sha1($clear);
902        case 'ssha':
903            $salt=substr($salt,0,4);
904            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
905        case 'crypt':
906            return crypt($clear,substr($salt,0,2));
907        case 'mysql':
908            //from http://www.php.net/mysql comment by <soren at byu dot edu>
909            $nr=0x50305735;
910            $nr2=0x12345671;
911            $add=7;
912            $charArr = preg_split("//", $clear);
913            foreach ($charArr as $char) {
914                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
915                $charVal = ord($char);
916                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
917                $nr2 += ($nr2 << 8) ^ $nr;
918                $add += $charVal;
919            }
920            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
921        case 'my411':
922            return '*'.sha1(pack("H*", sha1($clear)));
923        default:
924            msg("Unsupported crypt method $method",-1);
925    }
926}
927
928/**
929 * Verifies a cleartext password against a crypted hash
930 *
931 * The method and salt used for the crypted hash is determined automatically
932 * then the clear text password is crypted using the same method. If both hashs
933 * match true is is returned else false
934 *
935 * @author  Andreas Gohr <andi@splitbrain.org>
936 * @return  bool
937 */
938function auth_verifyPassword($clear,$crypt){
939    $method='';
940    $salt='';
941
942    //determine the used method and salt
943    $len = strlen($crypt);
944    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
945        $method = 'smd5';
946        $salt   = $m[1];
947    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
948        $method = 'apr1';
949        $salt   = $m[1];
950    }elseif(substr($crypt,0,6) == '{SSHA}'){
951        $method = 'ssha';
952        $salt   = substr(base64_decode(substr($crypt, 6)),20);
953    }elseif($len == 32){
954        $method = 'md5';
955    }elseif($len == 40){
956        $method = 'sha1';
957    }elseif($len == 16){
958        $method = 'mysql';
959    }elseif($len == 41 && $crypt[0] == '*'){
960        $method = 'my411';
961    }else{
962        $method = 'crypt';
963        $salt   = substr($crypt,0,2);
964    }
965
966    //crypt and compare
967    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
968        return true;
969    }
970    return false;
971}
972
973/**
974 * Set the authentication cookie and add user identification data to the session
975 *
976 * @param string  $user       username
977 * @param string  $pass       encrypted password
978 * @param bool    $sticky     whether or not the cookie will last beyond the session
979 */
980function auth_setCookie($user,$pass,$sticky) {
981    global $conf;
982    global $auth;
983    global $USERINFO;
984
985      $USERINFO = $auth->getUserData($user);
986
987      // set cookie
988      $cookie = base64_encode("$user|$sticky|$pass");
989      if($sticky) $time = time()+60*60*24*365; //one year
990      if (version_compare(PHP_VERSION, '5.2.0', '>')) {
991          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
992      }else{
993          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
994      }
995
996      // set session
997      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
998      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
999      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1000      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1001      $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1002}
1003
1004//Setup VIM: ex: et ts=2 enc=utf-8 :
1005