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