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