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