xref: /dokuwiki/inc/auth.php (revision cb147489e8f609bd5206afe4feab702c2eccf106)
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 * @triggers AUTH_LOGIN_CHECK
33 * @return bool
34 */
35function auth_setup() {
36    global $conf;
37    /* @var DokuWiki_Auth_Plugin $auth */
38    global $auth;
39    /* @var Input $INPUT */
40    global $INPUT;
41    global $AUTH_ACL;
42    global $lang;
43    /* @var Doku_Plugin_Controller $plugin_controller */
44    global $plugin_controller;
45    $AUTH_ACL = array();
46
47    if(!$conf['useacl']) return false;
48
49    // try to load auth backend from plugins
50    foreach ($plugin_controller->getList('auth') as $plugin) {
51        if ($conf['authtype'] === $plugin) {
52            $auth = $plugin_controller->load('auth', $plugin);
53            break;
54        }
55    }
56
57    if(!isset($auth) || !$auth){
58        msg($lang['authtempfail'], -1);
59        return false;
60    }
61
62    if ($auth->success == false) {
63        // degrade to unauthenticated user
64        unset($auth);
65        auth_logoff();
66        msg($lang['authtempfail'], -1);
67        return false;
68    }
69
70    // do the login either by cookie or provided credentials XXX
71    $INPUT->set('http_credentials', false);
72    if(!$conf['rememberme']) $INPUT->set('r', false);
73
74    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
75    // the one presented at
76    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
77    // for enabling HTTP authentication with CGI/SuExec)
78    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
79        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
80    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
81    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
82        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
83            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
84    }
85
86    // if no credentials were given try to use HTTP auth (for SSO)
87    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
88        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
89        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
90        $INPUT->set('http_credentials', true);
91    }
92
93    // apply cleaning (auth specific user names, remove control chars)
94    if (true === $auth->success) {
95        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
96        $INPUT->set('p', stripctl($INPUT->str('p')));
97    }
98
99    if(!is_null($auth) && $auth->canDo('external')) {
100        // external trust mechanism in place
101        $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
102    } else {
103        $evdata = array(
104            'user'     => $INPUT->str('u'),
105            'password' => $INPUT->str('p'),
106            'sticky'   => $INPUT->bool('r'),
107            'silent'   => $INPUT->bool('http_credentials')
108        );
109        trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
110    }
111
112    //load ACL into a global array XXX
113    $AUTH_ACL = auth_loadACL();
114
115    return true;
116}
117
118/**
119 * Loads the ACL setup and handle user wildcards
120 *
121 * @author Andreas Gohr <andi@splitbrain.org>
122 *
123 * @return array
124 */
125function auth_loadACL() {
126    global $config_cascade;
127    global $USERINFO;
128    /* @var Input $INPUT */
129    global $INPUT;
130
131    if(!is_readable($config_cascade['acl']['default'])) return array();
132
133    $acl = file($config_cascade['acl']['default']);
134
135    $out = array();
136    foreach($acl as $line) {
137        $line = trim($line);
138        if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments
139        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
140
141        // substitute user wildcard first (its 1:1)
142        if(strstr($line, '%USER%')){
143            // if user is not logged in, this ACL line is meaningless - skip it
144            if (!$INPUT->server->has('REMOTE_USER')) continue;
145
146            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
147            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
148        }
149
150        // substitute group wildcard (its 1:m)
151        if(strstr($line, '%GROUP%')){
152            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
153            foreach((array) $USERINFO['grps'] as $grp){
154                $nid   = str_replace('%GROUP%',cleanID($grp),$id);
155                $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
156                $out[] = "$nid\t$nrest";
157            }
158        } else {
159            $out[] = "$id\t$rest";
160        }
161    }
162
163    return $out;
164}
165
166/**
167 * Event hook callback for AUTH_LOGIN_CHECK
168 *
169 * @param array $evdata
170 * @return bool
171 */
172function auth_login_wrapper($evdata) {
173    return auth_login(
174        $evdata['user'],
175        $evdata['password'],
176        $evdata['sticky'],
177        $evdata['silent']
178    );
179}
180
181/**
182 * This tries to login the user based on the sent auth credentials
183 *
184 * The authentication works like this: if a username was given
185 * a new login is assumed and user/password are checked. If they
186 * are correct the password is encrypted with blowfish and stored
187 * together with the username in a cookie - the same info is stored
188 * in the session, too. Additonally a browserID is stored in the
189 * session.
190 *
191 * If no username was given the cookie is checked: if the username,
192 * crypted password and browserID match between session and cookie
193 * no further testing is done and the user is accepted
194 *
195 * If a cookie was found but no session info was availabe the
196 * blowfish encrypted password from the cookie is decrypted and
197 * together with username rechecked by calling this function again.
198 *
199 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
200 * are set.
201 *
202 * @author  Andreas Gohr <andi@splitbrain.org>
203 *
204 * @param   string  $user    Username
205 * @param   string  $pass    Cleartext Password
206 * @param   bool    $sticky  Cookie should not expire
207 * @param   bool    $silent  Don't show error on bad auth
208 * @return  bool             true on successful auth
209 */
210function auth_login($user, $pass, $sticky = false, $silent = false) {
211    global $USERINFO;
212    global $conf;
213    global $lang;
214    /* @var DokuWiki_Auth_Plugin $auth */
215    global $auth;
216    /* @var Input $INPUT */
217    global $INPUT;
218
219    $sticky ? $sticky = true : $sticky = false; //sanity check
220
221    if(!$auth) return false;
222
223    if(!empty($user)) {
224        //usual login
225        if(!empty($pass) && $auth->checkPass($user, $pass)) {
226            // make logininfo globally available
227            $INPUT->server->set('REMOTE_USER', $user);
228            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
229            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
230            return true;
231        } else {
232            //invalid credentials - log off
233            if(!$silent) msg($lang['badlogin'], -1);
234            auth_logoff();
235            return false;
236        }
237    } else {
238        // read cookie information
239        list($user, $sticky, $pass) = auth_getCookie();
240        if($user && $pass) {
241            // we got a cookie - see if we can trust it
242
243            // get session info
244            $session = $_SESSION[DOKU_COOKIE]['auth'];
245            if(isset($session) &&
246                $auth->useSessionCache($user) &&
247                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
248                ($session['user'] == $user) &&
249                ($session['pass'] == sha1($pass)) && //still crypted
250                ($session['buid'] == auth_browseruid())
251            ) {
252
253                // he has session, cookie and browser right - let him in
254                $INPUT->server->set('REMOTE_USER', $user);
255                $USERINFO               = $session['info']; //FIXME move all references to session
256                return true;
257            }
258            // no we don't trust it yet - recheck pass but silent
259            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
260            $pass   = auth_decrypt($pass, $secret);
261            return auth_login($user, $pass, $sticky, true);
262        }
263    }
264    //just to be sure
265    auth_logoff(true);
266    return false;
267}
268
269/**
270 * Builds a pseudo UID from browser and IP data
271 *
272 * This is neither unique nor unfakable - still it adds some
273 * security. Using the first part of the IP makes sure
274 * proxy farms like AOLs are still okay.
275 *
276 * @author  Andreas Gohr <andi@splitbrain.org>
277 *
278 * @return  string  a MD5 sum of various browser headers
279 */
280function auth_browseruid() {
281    /* @var Input $INPUT */
282    global $INPUT;
283
284    $ip  = clientIP(true);
285    $uid = '';
286    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
287    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
288    $uid .= substr($ip, 0, strpos($ip, '.'));
289    $uid = strtolower($uid);
290    return md5($uid);
291}
292
293/**
294 * Creates a random key to encrypt the password in cookies
295 *
296 * This function tries to read the password for encrypting
297 * cookies from $conf['metadir'].'/_htcookiesalt'
298 * if no such file is found a random key is created and
299 * and stored in this file.
300 *
301 * @author  Andreas Gohr <andi@splitbrain.org>
302 *
303 * @param   bool $addsession if true, the sessionid is added to the salt
304 * @param   bool $secure     if security is more important than keeping the old value
305 * @return  string
306 */
307function auth_cookiesalt($addsession = false, $secure = false) {
308    global $conf;
309    $file = $conf['metadir'].'/_htcookiesalt';
310    if ($secure || !file_exists($file)) {
311        $file = $conf['metadir'].'/_htcookiesalt2';
312    }
313    $salt = io_readFile($file);
314    if(empty($salt)) {
315        $salt = bin2hex(auth_randombytes(64));
316        io_saveFile($file, $salt);
317    }
318    if($addsession) {
319        $salt .= session_id();
320    }
321    return $salt;
322}
323
324/**
325 * Return cryptographically secure random bytes.
326 *
327 * @author Niklas Keller <me@kelunik.com>
328 *
329 * @param int $length number of bytes
330 * @return string cryptographically secure random bytes
331 */
332function auth_randombytes($length) {
333    return random_bytes($length);
334}
335
336/**
337 * Cryptographically secure random number generator.
338 *
339 * @author Niklas Keller <me@kelunik.com>
340 *
341 * @param int $min
342 * @param int $max
343 * @return int
344 */
345function auth_random($min, $max) {
346    return random_int($min, $max);
347}
348
349/**
350 * Encrypt data using the given secret using AES
351 *
352 * The mode is CBC with a random initialization vector, the key is derived
353 * using pbkdf2.
354 *
355 * @param string $data   The data that shall be encrypted
356 * @param string $secret The secret/password that shall be used
357 * @return string The ciphertext
358 */
359function auth_encrypt($data, $secret) {
360    $iv     = auth_randombytes(16);
361    $cipher = new \phpseclib\Crypt\AES();
362    $cipher->setPassword($secret);
363
364    /*
365    this uses the encrypted IV as IV as suggested in
366    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
367    for unique but necessarily random IVs. The resulting ciphertext is
368    compatible to ciphertext that was created using a "normal" IV.
369    */
370    return $cipher->encrypt($iv.$data);
371}
372
373/**
374 * Decrypt the given AES ciphertext
375 *
376 * The mode is CBC, the key is derived using pbkdf2
377 *
378 * @param string $ciphertext The encrypted data
379 * @param string $secret     The secret/password that shall be used
380 * @return string The decrypted data
381 */
382function auth_decrypt($ciphertext, $secret) {
383    $iv     = substr($ciphertext, 0, 16);
384    $cipher = new \phpseclib\Crypt\AES();
385    $cipher->setPassword($secret);
386    $cipher->setIV($iv);
387
388    return $cipher->decrypt(substr($ciphertext, 16));
389}
390
391/**
392 * Log out the current user
393 *
394 * This clears all authentication data and thus log the user
395 * off. It also clears session data.
396 *
397 * @author  Andreas Gohr <andi@splitbrain.org>
398 *
399 * @param bool $keepbc - when true, the breadcrumb data is not cleared
400 */
401function auth_logoff($keepbc = false) {
402    global $conf;
403    global $USERINFO;
404    /* @var DokuWiki_Auth_Plugin $auth */
405    global $auth;
406    /* @var Input $INPUT */
407    global $INPUT;
408
409    // make sure the session is writable (it usually is)
410    @session_start();
411
412    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
413        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
414    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
415        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
416    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
417        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
418    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
419        unset($_SESSION[DOKU_COOKIE]['bc']);
420    $INPUT->server->remove('REMOTE_USER');
421    $USERINFO = null; //FIXME
422
423    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
424    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
425
426    if($auth) $auth->logOff();
427}
428
429/**
430 * Check if a user is a manager
431 *
432 * Should usually be called without any parameters to check the current
433 * user.
434 *
435 * The info is available through $INFO['ismanager'], too
436 *
437 * @author Andreas Gohr <andi@splitbrain.org>
438 * @see    auth_isadmin
439 *
440 * @param  string $user       Username
441 * @param  array  $groups     List of groups the user is in
442 * @param  bool   $adminonly  when true checks if user is admin
443 * @return bool
444 */
445function auth_ismanager($user = null, $groups = null, $adminonly = false) {
446    global $conf;
447    global $USERINFO;
448    /* @var DokuWiki_Auth_Plugin $auth */
449    global $auth;
450    /* @var Input $INPUT */
451    global $INPUT;
452
453
454    if(!$auth) return false;
455    if(is_null($user)) {
456        if(!$INPUT->server->has('REMOTE_USER')) {
457            return false;
458        } else {
459            $user = $INPUT->server->str('REMOTE_USER');
460        }
461    }
462    if(is_null($groups)) {
463        $groups = (array) $USERINFO['grps'];
464    }
465
466    // check superuser match
467    if(auth_isMember($conf['superuser'], $user, $groups)) return true;
468    if($adminonly) return false;
469    // check managers
470    if(auth_isMember($conf['manager'], $user, $groups)) return true;
471
472    return false;
473}
474
475/**
476 * Check if a user is admin
477 *
478 * Alias to auth_ismanager with adminonly=true
479 *
480 * The info is available through $INFO['isadmin'], too
481 *
482 * @author Andreas Gohr <andi@splitbrain.org>
483 * @see auth_ismanager()
484 *
485 * @param  string $user       Username
486 * @param  array  $groups     List of groups the user is in
487 * @return bool
488 */
489function auth_isadmin($user = null, $groups = null) {
490    return auth_ismanager($user, $groups, true);
491}
492
493/**
494 * Match a user and his groups against a comma separated list of
495 * users and groups to determine membership status
496 *
497 * Note: all input should NOT be nameencoded.
498 *
499 * @param string $memberlist commaseparated list of allowed users and groups
500 * @param string $user       user to match against
501 * @param array  $groups     groups the user is member of
502 * @return bool       true for membership acknowledged
503 */
504function auth_isMember($memberlist, $user, array $groups) {
505    /* @var DokuWiki_Auth_Plugin $auth */
506    global $auth;
507    if(!$auth) return false;
508
509    // clean user and groups
510    if(!$auth->isCaseSensitive()) {
511        $user   = utf8_strtolower($user);
512        $groups = array_map('utf8_strtolower', $groups);
513    }
514    $user   = $auth->cleanUser($user);
515    $groups = array_map(array($auth, 'cleanGroup'), $groups);
516
517    // extract the memberlist
518    $members = explode(',', $memberlist);
519    $members = array_map('trim', $members);
520    $members = array_unique($members);
521    $members = array_filter($members);
522
523    // compare cleaned values
524    foreach($members as $member) {
525        if($member == '@ALL' ) return true;
526        if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
527        if($member[0] == '@') {
528            $member = $auth->cleanGroup(substr($member, 1));
529            if(in_array($member, $groups)) return true;
530        } else {
531            $member = $auth->cleanUser($member);
532            if($member == $user) return true;
533        }
534    }
535
536    // still here? not a member!
537    return false;
538}
539
540/**
541 * Convinience function for auth_aclcheck()
542 *
543 * This checks the permissions for the current user
544 *
545 * @author  Andreas Gohr <andi@splitbrain.org>
546 *
547 * @param  string  $id  page ID (needs to be resolved and cleaned)
548 * @return int          permission level
549 */
550function auth_quickaclcheck($id) {
551    global $conf;
552    global $USERINFO;
553    /* @var Input $INPUT */
554    global $INPUT;
555    # if no ACL is used always return upload rights
556    if(!$conf['useacl']) return AUTH_UPLOAD;
557    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
558}
559
560/**
561 * Returns the maximum rights a user has for the given ID or its namespace
562 *
563 * @author  Andreas Gohr <andi@splitbrain.org>
564 *
565 * @triggers AUTH_ACL_CHECK
566 * @param  string       $id     page ID (needs to be resolved and cleaned)
567 * @param  string       $user   Username
568 * @param  array|null   $groups Array of groups the user is in
569 * @return int             permission level
570 */
571function auth_aclcheck($id, $user, $groups) {
572    $data = array(
573        'id'     => $id,
574        'user'   => $user,
575        'groups' => $groups
576    );
577
578    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
579}
580
581/**
582 * default ACL check method
583 *
584 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
585 *
586 * @author  Andreas Gohr <andi@splitbrain.org>
587 *
588 * @param  array $data event data
589 * @return int   permission level
590 */
591function auth_aclcheck_cb($data) {
592    $id     =& $data['id'];
593    $user   =& $data['user'];
594    $groups =& $data['groups'];
595
596    global $conf;
597    global $AUTH_ACL;
598    /* @var DokuWiki_Auth_Plugin $auth */
599    global $auth;
600
601    // if no ACL is used always return upload rights
602    if(!$conf['useacl']) return AUTH_UPLOAD;
603    if(!$auth) return AUTH_NONE;
604
605    //make sure groups is an array
606    if(!is_array($groups)) $groups = array();
607
608    //if user is superuser or in superusergroup return 255 (acl_admin)
609    if(auth_isadmin($user, $groups)) {
610        return AUTH_ADMIN;
611    }
612
613    if(!$auth->isCaseSensitive()) {
614        $user   = utf8_strtolower($user);
615        $groups = array_map('utf8_strtolower', $groups);
616    }
617    $user   = auth_nameencode($auth->cleanUser($user));
618    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
619
620    //prepend groups with @ and nameencode
621    foreach($groups as &$group) {
622        $group = '@'.auth_nameencode($group);
623    }
624
625    $ns   = getNS($id);
626    $perm = -1;
627
628    //add ALL group
629    $groups[] = '@ALL';
630
631    //add User
632    if($user) $groups[] = $user;
633
634    //check exact match first
635    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
636    if(count($matches)) {
637        foreach($matches as $match) {
638            $match = preg_replace('/#.*$/', '', $match); //ignore comments
639            $acl   = preg_split('/[ \t]+/', $match);
640            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
641                $acl[1] = utf8_strtolower($acl[1]);
642            }
643            if(!in_array($acl[1], $groups)) {
644                continue;
645            }
646            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
647            if($acl[2] > $perm) {
648                $perm = $acl[2];
649            }
650        }
651        if($perm > -1) {
652            //we had a match - return it
653            return (int) $perm;
654        }
655    }
656
657    //still here? do the namespace checks
658    if($ns) {
659        $path = $ns.':*';
660    } else {
661        $path = '*'; //root document
662    }
663
664    do {
665        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
666        if(count($matches)) {
667            foreach($matches as $match) {
668                $match = preg_replace('/#.*$/', '', $match); //ignore comments
669                $acl   = preg_split('/[ \t]+/', $match);
670                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
671                    $acl[1] = utf8_strtolower($acl[1]);
672                }
673                if(!in_array($acl[1], $groups)) {
674                    continue;
675                }
676                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
677                if($acl[2] > $perm) {
678                    $perm = $acl[2];
679                }
680            }
681            //we had a match - return it
682            if($perm != -1) {
683                return (int) $perm;
684            }
685        }
686        //get next higher namespace
687        $ns = getNS($ns);
688
689        if($path != '*') {
690            $path = $ns.':*';
691            if($path == ':*') $path = '*';
692        } else {
693            //we did this already
694            //looks like there is something wrong with the ACL
695            //break here
696            msg('No ACL setup yet! Denying access to everyone.');
697            return AUTH_NONE;
698        }
699    } while(1); //this should never loop endless
700    return AUTH_NONE;
701}
702
703/**
704 * Encode ASCII special chars
705 *
706 * Some auth backends allow special chars in their user and groupnames
707 * The special chars are encoded with this function. Only ASCII chars
708 * are encoded UTF-8 multibyte are left as is (different from usual
709 * urlencoding!).
710 *
711 * Decoding can be done with rawurldecode
712 *
713 * @author Andreas Gohr <gohr@cosmocode.de>
714 * @see rawurldecode()
715 *
716 * @param string $name
717 * @param bool $skip_group
718 * @return string
719 */
720function auth_nameencode($name, $skip_group = false) {
721    global $cache_authname;
722    $cache =& $cache_authname;
723    $name  = (string) $name;
724
725    // never encode wildcard FS#1955
726    if($name == '%USER%') return $name;
727    if($name == '%GROUP%') return $name;
728
729    if(!isset($cache[$name][$skip_group])) {
730        if($skip_group && $name{0} == '@') {
731            $cache[$name][$skip_group] = '@'.preg_replace_callback(
732                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
733                'auth_nameencode_callback', substr($name, 1)
734            );
735        } else {
736            $cache[$name][$skip_group] = preg_replace_callback(
737                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
738                'auth_nameencode_callback', $name
739            );
740        }
741    }
742
743    return $cache[$name][$skip_group];
744}
745
746/**
747 * callback encodes the matches
748 *
749 * @param array $matches first complete match, next matching subpatterms
750 * @return string
751 */
752function auth_nameencode_callback($matches) {
753    return '%'.dechex(ord(substr($matches[1],-1)));
754}
755
756/**
757 * Create a pronouncable password
758 *
759 * The $foruser variable might be used by plugins to run additional password
760 * policy checks, but is not used by the default implementation
761 *
762 * @author   Andreas Gohr <andi@splitbrain.org>
763 * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
764 * @triggers AUTH_PASSWORD_GENERATE
765 *
766 * @param  string $foruser username for which the password is generated
767 * @return string  pronouncable password
768 */
769function auth_pwgen($foruser = '') {
770    $data = array(
771        'password' => '',
772        'foruser'  => $foruser
773    );
774
775    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
776    if($evt->advise_before(true)) {
777        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
778        $v = 'aeiou'; //vowels
779        $a = $c.$v; //both
780        $s = '!$%&?+*~#-_:.;,'; // specials
781
782        //use thre syllables...
783        for($i = 0; $i < 3; $i++) {
784            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
785            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
786            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
787        }
788        //... and add a nice number and special
789        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
790    }
791    $evt->advise_after();
792
793    return $data['password'];
794}
795
796/**
797 * Sends a password to the given user
798 *
799 * @author  Andreas Gohr <andi@splitbrain.org>
800 *
801 * @param string $user Login name of the user
802 * @param string $password The new password in clear text
803 * @return bool  true on success
804 */
805function auth_sendPassword($user, $password) {
806    global $lang;
807    /* @var DokuWiki_Auth_Plugin $auth */
808    global $auth;
809    if(!$auth) return false;
810
811    $user     = $auth->cleanUser($user);
812    $userinfo = $auth->getUserData($user, $requireGroups = false);
813
814    if(!$userinfo['mail']) return false;
815
816    $text = rawLocale('password');
817    $trep = array(
818        'FULLNAME' => $userinfo['name'],
819        'LOGIN'    => $user,
820        'PASSWORD' => $password
821    );
822
823    $mail = new Mailer();
824    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
825    $mail->subject($lang['regpwmail']);
826    $mail->setBody($text, $trep);
827    return $mail->send();
828}
829
830/**
831 * Register a new user
832 *
833 * This registers a new user - Data is read directly from $_POST
834 *
835 * @author  Andreas Gohr <andi@splitbrain.org>
836 *
837 * @return bool  true on success, false on any error
838 */
839function register() {
840    global $lang;
841    global $conf;
842    /* @var DokuWiki_Auth_Plugin $auth */
843    global $auth;
844    global $INPUT;
845
846    if(!$INPUT->post->bool('save')) return false;
847    if(!actionOK('register')) return false;
848
849    // gather input
850    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
851    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
852    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
853    $pass     = $INPUT->post->str('pass');
854    $passchk  = $INPUT->post->str('passchk');
855
856    if(empty($login) || empty($fullname) || empty($email)) {
857        msg($lang['regmissing'], -1);
858        return false;
859    }
860
861    if($conf['autopasswd']) {
862        $pass = auth_pwgen($login); // automatically generate password
863    } elseif(empty($pass) || empty($passchk)) {
864        msg($lang['regmissing'], -1); // complain about missing passwords
865        return false;
866    } elseif($pass != $passchk) {
867        msg($lang['regbadpass'], -1); // complain about misspelled passwords
868        return false;
869    }
870
871    //check mail
872    if(!mail_isvalid($email)) {
873        msg($lang['regbadmail'], -1);
874        return false;
875    }
876
877    //okay try to create the user
878    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
879        msg($lang['regfail'], -1);
880        return false;
881    }
882
883    // send notification about the new user
884    $subscription = new Subscription();
885    $subscription->send_register($login, $fullname, $email);
886
887    // are we done?
888    if(!$conf['autopasswd']) {
889        msg($lang['regsuccess2'], 1);
890        return true;
891    }
892
893    // autogenerated password? then send password to user
894    if(auth_sendPassword($login, $pass)) {
895        msg($lang['regsuccess'], 1);
896        return true;
897    } else {
898        msg($lang['regmailfail'], -1);
899        return false;
900    }
901}
902
903/**
904 * Update user profile
905 *
906 * @author    Christopher Smith <chris@jalakai.co.uk>
907 */
908function updateprofile() {
909    global $conf;
910    global $lang;
911    /* @var DokuWiki_Auth_Plugin $auth */
912    global $auth;
913    /* @var Input $INPUT */
914    global $INPUT;
915
916    if(!$INPUT->post->bool('save')) return false;
917    if(!checkSecurityToken()) return false;
918
919    if(!actionOK('profile')) {
920        msg($lang['profna'], -1);
921        return false;
922    }
923
924    $changes         = array();
925    $changes['pass'] = $INPUT->post->str('newpass');
926    $changes['name'] = $INPUT->post->str('fullname');
927    $changes['mail'] = $INPUT->post->str('email');
928
929    // check misspelled passwords
930    if($changes['pass'] != $INPUT->post->str('passchk')) {
931        msg($lang['regbadpass'], -1);
932        return false;
933    }
934
935    // clean fullname and email
936    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
937    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
938
939    // no empty name and email (except the backend doesn't support them)
940    if((empty($changes['name']) && $auth->canDo('modName')) ||
941        (empty($changes['mail']) && $auth->canDo('modMail'))
942    ) {
943        msg($lang['profnoempty'], -1);
944        return false;
945    }
946    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
947        msg($lang['regbadmail'], -1);
948        return false;
949    }
950
951    $changes = array_filter($changes);
952
953    // check for unavailable capabilities
954    if(!$auth->canDo('modName')) unset($changes['name']);
955    if(!$auth->canDo('modMail')) unset($changes['mail']);
956    if(!$auth->canDo('modPass')) unset($changes['pass']);
957
958    // anything to do?
959    if(!count($changes)) {
960        msg($lang['profnochange'], -1);
961        return false;
962    }
963
964    if($conf['profileconfirm']) {
965        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
966            msg($lang['badpassconfirm'], -1);
967            return false;
968        }
969    }
970
971    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
972        msg($lang['proffail'], -1);
973        return false;
974    }
975
976    if($changes['pass']) {
977        // update cookie and session with the changed data
978        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
979        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
980        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
981    } else {
982        // make sure the session is writable
983        @session_start();
984        // invalidate session cache
985        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
986        session_write_close();
987    }
988
989    return true;
990}
991
992/**
993 * Delete the current logged-in user
994 *
995 * @return bool true on success, false on any error
996 */
997function auth_deleteprofile(){
998    global $conf;
999    global $lang;
1000    /* @var DokuWiki_Auth_Plugin $auth */
1001    global $auth;
1002    /* @var Input $INPUT */
1003    global $INPUT;
1004
1005    if(!$INPUT->post->bool('delete')) return false;
1006    if(!checkSecurityToken()) return false;
1007
1008    // action prevented or auth module disallows
1009    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1010        msg($lang['profnodelete'], -1);
1011        return false;
1012    }
1013
1014    if(!$INPUT->post->bool('confirm_delete')){
1015        msg($lang['profconfdeletemissing'], -1);
1016        return false;
1017    }
1018
1019    if($conf['profileconfirm']) {
1020        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1021            msg($lang['badpassconfirm'], -1);
1022            return false;
1023        }
1024    }
1025
1026    $deleted = array();
1027    $deleted[] = $INPUT->server->str('REMOTE_USER');
1028    if($auth->triggerUserMod('delete', array($deleted))) {
1029        // force and immediate logout including removing the sticky cookie
1030        auth_logoff();
1031        return true;
1032    }
1033
1034    return false;
1035}
1036
1037/**
1038 * Send a  new password
1039 *
1040 * This function handles both phases of the password reset:
1041 *
1042 *   - handling the first request of password reset
1043 *   - validating the password reset auth token
1044 *
1045 * @author Benoit Chesneau <benoit@bchesneau.info>
1046 * @author Chris Smith <chris@jalakai.co.uk>
1047 * @author Andreas Gohr <andi@splitbrain.org>
1048 *
1049 * @return bool true on success, false on any error
1050 */
1051function act_resendpwd() {
1052    global $lang;
1053    global $conf;
1054    /* @var DokuWiki_Auth_Plugin $auth */
1055    global $auth;
1056    /* @var Input $INPUT */
1057    global $INPUT;
1058
1059    if(!actionOK('resendpwd')) {
1060        msg($lang['resendna'], -1);
1061        return false;
1062    }
1063
1064    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1065
1066    if($token) {
1067        // we're in token phase - get user info from token
1068
1069        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
1070        if(!file_exists($tfile)) {
1071            msg($lang['resendpwdbadauth'], -1);
1072            $INPUT->remove('pwauth');
1073            return false;
1074        }
1075        // token is only valid for 3 days
1076        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1077            msg($lang['resendpwdbadauth'], -1);
1078            $INPUT->remove('pwauth');
1079            @unlink($tfile);
1080            return false;
1081        }
1082
1083        $user     = io_readfile($tfile);
1084        $userinfo = $auth->getUserData($user, $requireGroups = false);
1085        if(!$userinfo['mail']) {
1086            msg($lang['resendpwdnouser'], -1);
1087            return false;
1088        }
1089
1090        if(!$conf['autopasswd']) { // we let the user choose a password
1091            $pass = $INPUT->str('pass');
1092
1093            // password given correctly?
1094            if(!$pass) return false;
1095            if($pass != $INPUT->str('passchk')) {
1096                msg($lang['regbadpass'], -1);
1097                return false;
1098            }
1099
1100            // change it
1101            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1102                msg($lang['proffail'], -1);
1103                return false;
1104            }
1105
1106        } else { // autogenerate the password and send by mail
1107
1108            $pass = auth_pwgen($user);
1109            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1110                msg($lang['proffail'], -1);
1111                return false;
1112            }
1113
1114            if(auth_sendPassword($user, $pass)) {
1115                msg($lang['resendpwdsuccess'], 1);
1116            } else {
1117                msg($lang['regmailfail'], -1);
1118            }
1119        }
1120
1121        @unlink($tfile);
1122        return true;
1123
1124    } else {
1125        // we're in request phase
1126
1127        if(!$INPUT->post->bool('save')) return false;
1128
1129        if(!$INPUT->post->str('login')) {
1130            msg($lang['resendpwdmissing'], -1);
1131            return false;
1132        } else {
1133            $user = trim($auth->cleanUser($INPUT->post->str('login')));
1134        }
1135
1136        $userinfo = $auth->getUserData($user, $requireGroups = false);
1137        if(!$userinfo['mail']) {
1138            msg($lang['resendpwdnouser'], -1);
1139            return false;
1140        }
1141
1142        // generate auth token
1143        $token = md5(auth_randombytes(16)); // random secret
1144        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
1145        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1146
1147        io_saveFile($tfile, $user);
1148
1149        $text = rawLocale('pwconfirm');
1150        $trep = array(
1151            'FULLNAME' => $userinfo['name'],
1152            'LOGIN'    => $user,
1153            'CONFIRM'  => $url
1154        );
1155
1156        $mail = new Mailer();
1157        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1158        $mail->subject($lang['regpwmail']);
1159        $mail->setBody($text, $trep);
1160        if($mail->send()) {
1161            msg($lang['resendpwdconfirm'], 1);
1162        } else {
1163            msg($lang['regmailfail'], -1);
1164        }
1165        return true;
1166    }
1167    // never reached
1168}
1169
1170/**
1171 * Encrypts a password using the given method and salt
1172 *
1173 * If the selected method needs a salt and none was given, a random one
1174 * is chosen.
1175 *
1176 * @author  Andreas Gohr <andi@splitbrain.org>
1177 *
1178 * @param string $clear The clear text password
1179 * @param string $method The hashing method
1180 * @param string $salt A salt, null for random
1181 * @return  string  The crypted password
1182 */
1183function auth_cryptPassword($clear, $method = '', $salt = null) {
1184    global $conf;
1185    if(empty($method)) $method = $conf['passcrypt'];
1186
1187    $pass = new PassHash();
1188    $call = 'hash_'.$method;
1189
1190    if(!method_exists($pass, $call)) {
1191        msg("Unsupported crypt method $method", -1);
1192        return false;
1193    }
1194
1195    return $pass->$call($clear, $salt);
1196}
1197
1198/**
1199 * Verifies a cleartext password against a crypted hash
1200 *
1201 * @author Andreas Gohr <andi@splitbrain.org>
1202 *
1203 * @param  string $clear The clear text password
1204 * @param  string $crypt The hash to compare with
1205 * @return bool true if both match
1206 */
1207function auth_verifyPassword($clear, $crypt) {
1208    $pass = new PassHash();
1209    return $pass->verify_hash($clear, $crypt);
1210}
1211
1212/**
1213 * Set the authentication cookie and add user identification data to the session
1214 *
1215 * @param string  $user       username
1216 * @param string  $pass       encrypted password
1217 * @param bool    $sticky     whether or not the cookie will last beyond the session
1218 * @return bool
1219 */
1220function auth_setCookie($user, $pass, $sticky) {
1221    global $conf;
1222    /* @var DokuWiki_Auth_Plugin $auth */
1223    global $auth;
1224    global $USERINFO;
1225
1226    if(!$auth) return false;
1227    $USERINFO = $auth->getUserData($user);
1228
1229    // set cookie
1230    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1231    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1232    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1233    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1234
1235    // set session
1236    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1237    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1238    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1239    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1240    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1241
1242    return true;
1243}
1244
1245/**
1246 * Returns the user, (encrypted) password and sticky bit from cookie
1247 *
1248 * @returns array
1249 */
1250function auth_getCookie() {
1251    if(!isset($_COOKIE[DOKU_COOKIE])) {
1252        return array(null, null, null);
1253    }
1254    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1255    $sticky = (bool) $sticky;
1256    $pass   = base64_decode($pass);
1257    $user   = base64_decode($user);
1258    return array($user, $sticky, $pass);
1259}
1260
1261//Setup VIM: ex: et ts=2 :
1262