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