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