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