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