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