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