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