xref: /dokuwiki/inc/auth.php (revision 7917b6f2f2768c559c2b891f5c0077afe3eeef69)
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
12if(!defined('DOKU_INC')) die('meh.');
13require_once(DOKU_INC.'inc/common.php');
14require_once(DOKU_INC.'inc/io.php');
15
16// some ACL level defines
17define('AUTH_NONE',0);
18define('AUTH_READ',1);
19define('AUTH_EDIT',2);
20define('AUTH_CREATE',4);
21define('AUTH_UPLOAD',8);
22define('AUTH_DELETE',16);
23define('AUTH_ADMIN',255);
24
25global $conf;
26
27if($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
56if($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        // apply cleaning
78        $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
79
80        if(isset($_REQUEST['authtok'])){
81            // when an authentication token is given, trust the session
82            auth_validateToken($_REQUEST['authtok']);
83        }elseif(!is_null($auth) && $auth->canDo('external')){
84            // external trust mechanism in place
85            $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
86        }else{
87            $evdata = array(
88                    'user'     => $_REQUEST['u'],
89                    'password' => $_REQUEST['p'],
90                    'sticky'   => $_REQUEST['r'],
91                    'silent'   => $_REQUEST['http_credentials'],
92                    );
93            $evt = new Doku_Event('AUTH_LOGIN_CHECK',$evdata);
94            if($evt->advise_before()){
95                auth_login($evdata['user'],
96                           $evdata['password'],
97                           $evdata['sticky'],
98                           $evdata['silent']);
99            }
100        }
101    }
102
103    //load ACL into a global array
104    global $AUTH_ACL;
105    if(is_readable(DOKU_CONF.'acl.auth.php')){
106        $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
107        //support user wildcard
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    global $auth;
339
340    if(!$conf['useacl']) return false;
341    if(is_null($user)) {
342        if (!isset($_SERVER['REMOTE_USER'])) {
343            return false;
344        } else {
345            $user = $_SERVER['REMOTE_USER'];
346        }
347    }
348    $user = $auth->cleanUser($user);
349    if(is_null($groups)) $groups = (array) $USERINFO['grps'];
350    $groups = array_map(array($auth,'cleanGroup'),$groups);
351    $user   = auth_nameencode($user);
352
353    // check username against superuser and manager
354    $superusers = explode(',', $conf['superuser']);
355    $superusers = array_unique($superusers);
356    $superusers = array_map('trim', $superusers);
357    // prepare an array containing only true values for array_map call
358    $alltrue = array_fill(0, count($superusers), true);
359    $superusers = array_map('auth_nameencode', $superusers, $alltrue);
360    if(in_array($user, $superusers)) return true;
361
362    if(!$adminonly){
363        $managers = explode(',', $conf['manager']);
364        $managers = array_unique($managers);
365        $managers = array_map('trim', $managers);
366        // prepare an array containing only true values for array_map call
367        $alltrue = array_fill(0, count($managers), true);
368        $managers = array_map('auth_nameencode', $managers, $alltrue);
369        if(in_array($user, $managers)) return true;
370    }
371
372    // check user's groups against superuser and manager
373    if (!empty($groups)) {
374
375        //prepend groups with @ and nameencode
376        $cnt = count($groups);
377        for($i=0; $i<$cnt; $i++){
378            $groups[$i] = '@'.auth_nameencode($groups[$i]);
379        }
380
381        // check groups against superuser and manager
382        foreach($superusers as $supu)
383            if(in_array($supu, $groups)) return true;
384        if(!$adminonly){
385            foreach($managers as $mana)
386                if(in_array($mana, $groups)) return true;
387        }
388    }
389
390    return false;
391}
392
393/**
394 * Check if a user is admin
395 *
396 * Alias to auth_ismanager with adminonly=true
397 *
398 * The info is available through $INFO['isadmin'], too
399 *
400 * @author Andreas Gohr <andi@splitbrain.org>
401 * @see auth_ismanager
402 */
403function auth_isadmin($user=null,$groups=null){
404    return auth_ismanager($user,$groups,true);
405}
406
407/**
408 * Convinience function for auth_aclcheck()
409 *
410 * This checks the permissions for the current user
411 *
412 * @author  Andreas Gohr <andi@splitbrain.org>
413 *
414 * @param  string  $id  page ID (needs to be resolved and cleaned)
415 * @return int          permission level
416 */
417function auth_quickaclcheck($id){
418    global $conf;
419    global $USERINFO;
420    # if no ACL is used always return upload rights
421    if(!$conf['useacl']) return AUTH_UPLOAD;
422    return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
423}
424
425/**
426 * Returns the maximum rights a user has for
427 * the given ID or its namespace
428 *
429 * @author  Andreas Gohr <andi@splitbrain.org>
430 *
431 * @param  string  $id     page ID (needs to be resolved and cleaned)
432 * @param  string  $user   Username
433 * @param  array   $groups Array of groups the user is in
434 * @return int             permission level
435 */
436function auth_aclcheck($id,$user,$groups){
437    global $conf;
438    global $AUTH_ACL;
439    global $auth;
440
441    // if no ACL is used always return upload rights
442    if(!$conf['useacl']) return AUTH_UPLOAD;
443
444    //make sure groups is an array
445    if(!is_array($groups)) $groups = array();
446
447    //if user is superuser or in superusergroup return 255 (acl_admin)
448    if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
449
450
451    $user = $auth->cleanUser($user);
452    $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
453    $user = auth_nameencode($user);
454
455    //prepend groups with @ and nameencode
456    $cnt = count($groups);
457    for($i=0; $i<$cnt; $i++){
458        $groups[$i] = '@'.auth_nameencode($groups[$i]);
459    }
460
461    $ns    = getNS($id);
462    $perm  = -1;
463
464    if($user || count($groups)){
465        //add ALL group
466        $groups[] = '@ALL';
467        //add User
468        if($user) $groups[] = $user;
469        //build regexp
470        $regexp   = join('|',$groups);
471    }else{
472        $regexp = '@ALL';
473    }
474
475    //check exact match first
476    $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
477    if(count($matches)){
478        foreach($matches as $match){
479            $match = preg_replace('/#.*$/','',$match); //ignore comments
480            $acl   = preg_split('/\s+/',$match);
481            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
482            if($acl[2] > $perm){
483                $perm = $acl[2];
484            }
485        }
486        if($perm > -1){
487            //we had a match - return it
488            return $perm;
489        }
490    }
491
492    //still here? do the namespace checks
493    if($ns){
494        $path = $ns.':\*';
495    }else{
496        $path = '\*'; //root document
497    }
498
499    do{
500        $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
501        if(count($matches)){
502            foreach($matches as $match){
503                $match = preg_replace('/#.*$/','',$match); //ignore comments
504                $acl   = preg_split('/\s+/',$match);
505                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
506                if($acl[2] > $perm){
507                    $perm = $acl[2];
508                }
509            }
510            //we had a match - return it
511            return $perm;
512        }
513
514        //get next higher namespace
515        $ns   = getNS($ns);
516
517        if($path != '\*'){
518            $path = $ns.':\*';
519            if($path == ':\*') $path = '\*';
520        }else{
521            //we did this already
522            //looks like there is something wrong with the ACL
523            //break here
524            msg('No ACL setup yet! Denying access to everyone.');
525            return AUTH_NONE;
526        }
527    }while(1); //this should never loop endless
528
529    //still here? return no permissions
530    return AUTH_NONE;
531}
532
533/**
534 * Encode ASCII special chars
535 *
536 * Some auth backends allow special chars in their user and groupnames
537 * The special chars are encoded with this function. Only ASCII chars
538 * are encoded UTF-8 multibyte are left as is (different from usual
539 * urlencoding!).
540 *
541 * Decoding can be done with rawurldecode
542 *
543 * @author Andreas Gohr <gohr@cosmocode.de>
544 * @see rawurldecode()
545 */
546function auth_nameencode($name,$skip_group=false){
547    global $cache_authname;
548    $cache =& $cache_authname;
549    $name  = (string) $name;
550
551    if (!isset($cache[$name][$skip_group])) {
552        if($skip_group && $name{0} =='@'){
553            $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
554                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
555        }else{
556            $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
557                    "'%'.dechex(ord(substr('\\1',-1)))",$name);
558        }
559    }
560
561    return $cache[$name][$skip_group];
562}
563
564/**
565 * Create a pronouncable password
566 *
567 * @author  Andreas Gohr <andi@splitbrain.org>
568 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
569 *
570 * @return string  pronouncable password
571 */
572function auth_pwgen(){
573    $pw = '';
574    $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
575    $v  = 'aeiou';              //vowels
576    $a  = $c.$v;                //both
577
578    //use two syllables...
579    for($i=0;$i < 2; $i++){
580        $pw .= $c[rand(0, strlen($c)-1)];
581        $pw .= $v[rand(0, strlen($v)-1)];
582        $pw .= $a[rand(0, strlen($a)-1)];
583    }
584    //... and add a nice number
585    $pw .= rand(10,99);
586
587    return $pw;
588}
589
590/**
591 * Sends a password to the given user
592 *
593 * @author  Andreas Gohr <andi@splitbrain.org>
594 *
595 * @return bool  true on success
596 */
597function auth_sendPassword($user,$password){
598    global $conf;
599    global $lang;
600    global $auth;
601
602    $hdrs  = '';
603    $user     = $auth->cleanUser($user);
604    $userinfo = $auth->getUserData($user);
605
606    if(!$userinfo['mail']) return false;
607
608    $text = rawLocale('password');
609    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
610    $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
611    $text = str_replace('@LOGIN@',$user,$text);
612    $text = str_replace('@PASSWORD@',$password,$text);
613    $text = str_replace('@TITLE@',$conf['title'],$text);
614
615    return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
616            $lang['regpwmail'],
617            $text,
618            $conf['mailfrom']);
619}
620
621/**
622 * Register a new user
623 *
624 * This registers a new user - Data is read directly from $_POST
625 *
626 * @author  Andreas Gohr <andi@splitbrain.org>
627 *
628 * @return bool  true on success, false on any error
629 */
630function register(){
631    global $lang;
632    global $conf;
633    global $auth;
634
635    if(!$_POST['save']) return false;
636    if(!$auth->canDo('addUser')) return false;
637
638    //clean username
639    $_POST['login'] = trim($auth->cleanUser($_POST['login']));
640
641    //clean fullname and email
642    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
643    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
644
645    if( empty($_POST['login']) ||
646        empty($_POST['fullname']) ||
647        empty($_POST['email']) ){
648        msg($lang['regmissing'],-1);
649        return false;
650    }
651
652    if ($conf['autopasswd']) {
653        $pass = auth_pwgen();                // automatically generate password
654    } elseif (empty($_POST['pass']) ||
655            empty($_POST['passchk'])) {
656        msg($lang['regmissing'], -1);        // complain about missing passwords
657        return false;
658    } elseif ($_POST['pass'] != $_POST['passchk']) {
659        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
660        return false;
661    } else {
662        $pass = $_POST['pass'];              // accept checked and valid password
663    }
664
665    //check mail
666    if(!mail_isvalid($_POST['email'])){
667        msg($lang['regbadmail'],-1);
668        return false;
669    }
670
671    //okay try to create the user
672    if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
673        msg($lang['reguexists'],-1);
674        return false;
675    }
676
677    // create substitutions for use in notification email
678    $substitutions = array(
679            'NEWUSER' => $_POST['login'],
680            'NEWNAME' => $_POST['fullname'],
681            'NEWEMAIL' => $_POST['email'],
682            );
683
684    if (!$conf['autopasswd']) {
685        msg($lang['regsuccess2'],1);
686        notify('', 'register', '', $_POST['login'], false, $substitutions);
687        return true;
688    }
689
690    // autogenerated password? then send him the password
691    if (auth_sendPassword($_POST['login'],$pass)){
692        msg($lang['regsuccess'],1);
693        notify('', 'register', '', $_POST['login'], false, $substitutions);
694        return true;
695    }else{
696        msg($lang['regmailfail'],-1);
697        return false;
698    }
699}
700
701/**
702 * Update user profile
703 *
704 * @author    Christopher Smith <chris@jalakai.co.uk>
705 */
706function updateprofile() {
707    global $conf;
708    global $INFO;
709    global $lang;
710    global $auth;
711
712    if(empty($_POST['save'])) return false;
713    if(!checkSecurityToken()) return false;
714
715    // should not be able to get here without Profile being possible...
716    if(!$auth->canDo('Profile')) {
717        msg($lang['profna'],-1);
718        return false;
719    }
720
721    if ($_POST['newpass'] != $_POST['passchk']) {
722        msg($lang['regbadpass'], -1);      // complain about misspelled passwords
723        return false;
724    }
725
726    //clean fullname and email
727    $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
728    $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
729
730    if (empty($_POST['fullname']) || empty($_POST['email'])) {
731        msg($lang['profnoempty'],-1);
732        return false;
733    }
734
735    if (!mail_isvalid($_POST['email'])){
736        msg($lang['regbadmail'],-1);
737        return false;
738    }
739
740    if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
741    if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
742    if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
743
744    if (!count($changes)) {
745        msg($lang['profnochange'], -1);
746        return false;
747    }
748
749    if ($conf['profileconfirm']) {
750        if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
751            msg($lang['badlogin'],-1);
752            return false;
753        }
754    }
755
756    if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
757        // update cookie and session with the changed data
758        $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
759        list($user,$sticky,$pass) = explode('|',$cookie,3);
760        if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
761
762        auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
763        return true;
764    }
765}
766
767/**
768 * Send a  new password
769 *
770 * This function handles both phases of the password reset:
771 *
772 *   - handling the first request of password reset
773 *   - validating the password reset auth token
774 *
775 * @author Benoit Chesneau <benoit@bchesneau.info>
776 * @author Chris Smith <chris@jalakai.co.uk>
777 * @author Andreas Gohr <andi@splitbrain.org>
778 *
779 * @return bool true on success, false on any error
780 */
781function act_resendpwd(){
782    global $lang;
783    global $conf;
784    global $auth;
785
786    if(!actionOK('resendpwd')) return false;
787
788    // should not be able to get here without modPass being possible...
789    if(!$auth->canDo('modPass')) {
790        msg($lang['resendna'],-1);
791        return false;
792    }
793
794    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
795
796    if($token){
797        // we're in token phase
798
799        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
800        if(!@file_exists($tfile)){
801            msg($lang['resendpwdbadauth'],-1);
802            return false;
803        }
804        $user = io_readfile($tfile);
805        @unlink($tfile);
806        $userinfo = $auth->getUserData($user);
807        if(!$userinfo['mail']) {
808            msg($lang['resendpwdnouser'], -1);
809            return false;
810        }
811
812        $pass = auth_pwgen();
813        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
814            msg('error modifying user data',-1);
815            return false;
816        }
817
818        if (auth_sendPassword($user,$pass)) {
819            msg($lang['resendpwdsuccess'],1);
820        } else {
821            msg($lang['regmailfail'],-1);
822        }
823        return true;
824
825    } else {
826        // we're in request phase
827
828        if(!$_POST['save']) return false;
829
830        if (empty($_POST['login'])) {
831            msg($lang['resendpwdmissing'], -1);
832            return false;
833        } else {
834            $user = trim($auth->cleanUser($_POST['login']));
835        }
836
837        $userinfo = $auth->getUserData($user);
838        if(!$userinfo['mail']) {
839            msg($lang['resendpwdnouser'], -1);
840            return false;
841        }
842
843        // generate auth token
844        $token = md5(auth_cookiesalt().$user); //secret but user based
845        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
846        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
847
848        io_saveFile($tfile,$user);
849
850        $text = rawLocale('pwconfirm');
851        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
852        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
853        $text = str_replace('@LOGIN@',$user,$text);
854        $text = str_replace('@TITLE@',$conf['title'],$text);
855        $text = str_replace('@CONFIRM@',$url,$text);
856
857        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
858                     $lang['regpwmail'],
859                     $text,
860                     $conf['mailfrom'])){
861            msg($lang['resendpwdconfirm'],1);
862        }else{
863            msg($lang['regmailfail'],-1);
864        }
865        return true;
866    }
867
868    return false; // never reached
869}
870
871/**
872 * Encrypts a password using the given method and salt
873 *
874 * If the selected method needs a salt and none was given, a random one
875 * is chosen.
876 *
877 * The following methods are understood:
878 *
879 *   smd5  - Salted MD5 hashing
880 *   apr1  - Apache salted MD5 hashing
881 *   md5   - Simple MD5 hashing
882 *   sha1  - SHA1 hashing
883 *   ssha  - Salted SHA1 hashing
884 *   crypt - Unix crypt
885 *   mysql - MySQL password (old method)
886 *   my411 - MySQL 4.1.1 password
887 *   kmd5  - Salted MD5 hashing as used by UNB
888 *
889 * @author  Andreas Gohr <andi@splitbrain.org>
890 * @return  string  The crypted password
891 */
892function auth_cryptPassword($clear,$method='',$salt=null){
893    global $conf;
894    if(empty($method)) $method = $conf['passcrypt'];
895
896    //prepare a salt
897    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
898
899    switch(strtolower($method)){
900        case 'smd5':
901            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
902            // when crypt can't handle SMD5, falls through to pure PHP implementation
903            $magic = '1';
904        case 'apr1':
905            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
906            if(!$magic) $magic = 'apr1';
907            $salt = substr($salt,0,8);
908            $len = strlen($clear);
909            $text = $clear.'$'.$magic.'$'.$salt;
910            $bin = pack("H32", md5($clear.$salt.$clear));
911            for($i = $len; $i > 0; $i -= 16) {
912                $text .= substr($bin, 0, min(16, $i));
913            }
914            for($i = $len; $i > 0; $i >>= 1) {
915                $text .= ($i & 1) ? chr(0) : $clear{0};
916            }
917            $bin = pack("H32", md5($text));
918            for($i = 0; $i < 1000; $i++) {
919                $new = ($i & 1) ? $clear : $bin;
920                if ($i % 3) $new .= $salt;
921                if ($i % 7) $new .= $clear;
922                $new .= ($i & 1) ? $bin : $clear;
923                $bin = pack("H32", md5($new));
924            }
925            $tmp = '';
926            for ($i = 0; $i < 5; $i++) {
927                $k = $i + 6;
928                $j = $i + 12;
929                if ($j == 16) $j = 5;
930                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
931            }
932            $tmp = chr(0).chr(0).$bin[11].$tmp;
933            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
934                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
935                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
936            return '$'.$magic.'$'.$salt.'$'.$tmp;
937        case 'md5':
938            return md5($clear);
939        case 'sha1':
940            return sha1($clear);
941        case 'ssha':
942            $salt=substr($salt,0,4);
943            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
944        case 'crypt':
945            return crypt($clear,substr($salt,0,2));
946        case 'mysql':
947            //from http://www.php.net/mysql comment by <soren at byu dot edu>
948            $nr=0x50305735;
949            $nr2=0x12345671;
950            $add=7;
951            $charArr = preg_split("//", $clear);
952            foreach ($charArr as $char) {
953                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
954                $charVal = ord($char);
955                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
956                $nr2 += ($nr2 << 8) ^ $nr;
957                $add += $charVal;
958            }
959            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
960        case 'my411':
961            return '*'.sha1(pack("H*", sha1($clear)));
962        case 'kmd5':
963            $key = substr($salt, 16, 2);
964            $hash1 = strtolower(md5($key . md5($clear)));
965            $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
966            return $hash2;
967        default:
968            msg("Unsupported crypt method $method",-1);
969    }
970}
971
972/**
973 * Verifies a cleartext password against a crypted hash
974 *
975 * The method and salt used for the crypted hash is determined automatically
976 * then the clear text password is crypted using the same method. If both hashs
977 * match true is is returned else false
978 *
979 * @author  Andreas Gohr <andi@splitbrain.org>
980 * @return  bool
981 */
982function auth_verifyPassword($clear,$crypt){
983    $method='';
984    $salt='';
985
986    //determine the used method and salt
987    $len = strlen($crypt);
988    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
989        $method = 'smd5';
990        $salt   = $m[1];
991    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
992        $method = 'apr1';
993        $salt   = $m[1];
994    }elseif(substr($crypt,0,6) == '{SSHA}'){
995        $method = 'ssha';
996        $salt   = substr(base64_decode(substr($crypt, 6)),20);
997    }elseif($len == 32){
998        $method = 'md5';
999    }elseif($len == 40){
1000        $method = 'sha1';
1001    }elseif($len == 16){
1002        $method = 'mysql';
1003    }elseif($len == 41 && $crypt[0] == '*'){
1004        $method = 'my411';
1005    }elseif($len == 34){
1006        $method = 'kmd5';
1007        $salt   = $crypt;
1008    }else{
1009        $method = 'crypt';
1010        $salt   = substr($crypt,0,2);
1011    }
1012
1013    //crypt and compare
1014    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1015        return true;
1016    }
1017    return false;
1018}
1019
1020/**
1021 * Set the authentication cookie and add user identification data to the session
1022 *
1023 * @param string  $user       username
1024 * @param string  $pass       encrypted password
1025 * @param bool    $sticky     whether or not the cookie will last beyond the session
1026 */
1027function auth_setCookie($user,$pass,$sticky) {
1028    global $conf;
1029    global $auth;
1030    global $USERINFO;
1031
1032    $USERINFO = $auth->getUserData($user);
1033
1034    // set cookie
1035    $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1036    $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1037    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
1038        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
1039    }else{
1040        setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1041    }
1042    // set session
1043    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1044    $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1045    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1046    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1047    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1048}
1049
1050/**
1051 * Returns the user, (encrypted) password and sticky bit from cookie
1052 *
1053 * @returns array
1054 */
1055function auth_getCookie(){
1056    if (!isset($_COOKIE[DOKU_COOKIE])) {
1057        return array(null, null, null);
1058    }
1059    list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1060    $sticky = (bool) $sticky;
1061    $pass   = base64_decode($pass);
1062    $user   = base64_decode($user);
1063    return array($user,$sticky,$pass);
1064}
1065
1066//Setup VIM: ex: et ts=2 enc=utf-8 :
1067