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