Merge pull request #4165 from dokuwiki/bot/autofix
[dokuwiki.git] / inc / auth.php
blob0821e59cbd572dc1fb3995722ddeaf149386ce75
1 <?php
3 /**
4 * Authentication library
6 * Including this file will automatically try to login
7 * a user by calling auth_login()
9 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
10 * @author Andreas Gohr <andi@splitbrain.org>
13 use dokuwiki\JWT;
14 use dokuwiki\Utf8\PhpString;
15 use dokuwiki\Extension\AuthPlugin;
16 use dokuwiki\Extension\Event;
17 use dokuwiki\Extension\PluginController;
18 use dokuwiki\PassHash;
19 use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
20 use phpseclib3\Crypt\AES;
21 use phpseclib3\Crypt\Common\SymmetricKey;
23 /**
24 * Initialize the auth system.
26 * This function is automatically called at the end of init.php
28 * This used to be the main() of the auth.php
30 * @todo backend loading maybe should be handled by the class autoloader
31 * @todo maybe split into multiple functions at the XXX marked positions
32 * @triggers AUTH_LOGIN_CHECK
33 * @return bool
35 function auth_setup()
37 global $conf;
38 /* @var AuthPlugin $auth */
39 global $auth;
40 /* @var Input $INPUT */
41 global $INPUT;
42 global $AUTH_ACL;
43 global $lang;
44 /* @var PluginController $plugin_controller */
45 global $plugin_controller;
46 $AUTH_ACL = [];
48 if (!$conf['useacl']) return false;
50 // try to load auth backend from plugins
51 foreach ($plugin_controller->getList('auth') as $plugin) {
52 if ($conf['authtype'] === $plugin) {
53 $auth = $plugin_controller->load('auth', $plugin);
54 break;
58 if (!$auth instanceof AuthPlugin) {
59 msg($lang['authtempfail'], -1);
60 return false;
63 if ($auth->success == false) {
64 // degrade to unauthenticated user
65 $auth = null;
66 auth_logoff();
67 msg($lang['authtempfail'], -1);
68 return false;
71 // do the login either by cookie or provided credentials XXX
72 $INPUT->set('http_credentials', false);
73 if (!$conf['rememberme']) $INPUT->set('r', false);
75 // Populate Basic Auth user/password from Authorization header
76 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
77 $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
78 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
79 $userpass = explode(':', base64_decode($matches[1]));
80 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
83 // if no credentials were given try to use HTTP auth (for SSO)
84 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
85 $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
86 $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
87 $INPUT->set('http_credentials', true);
90 // apply cleaning (auth specific user names, remove control chars)
91 if (true === $auth->success) {
92 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
93 $INPUT->set('p', stripctl($INPUT->str('p')));
96 if (!auth_tokenlogin()) {
97 $ok = null;
99 if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
100 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
103 if ($ok === null) {
104 // external trust mechanism not in place, or returns no result,
105 // then attempt auth_login
106 $evdata = [
107 'user' => $INPUT->str('u'),
108 'password' => $INPUT->str('p'),
109 'sticky' => $INPUT->bool('r'),
110 'silent' => $INPUT->bool('http_credentials')
112 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
116 //load ACL into a global array XXX
117 $AUTH_ACL = auth_loadACL();
119 return true;
123 * Loads the ACL setup and handle user wildcards
125 * @author Andreas Gohr <andi@splitbrain.org>
127 * @return array
129 function auth_loadACL()
131 global $config_cascade;
132 global $USERINFO;
133 /* @var Input $INPUT */
134 global $INPUT;
136 if (!is_readable($config_cascade['acl']['default'])) return [];
138 $acl = file($config_cascade['acl']['default']);
140 $out = [];
141 foreach ($acl as $line) {
142 $line = trim($line);
143 if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
144 [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
146 // substitute user wildcard first (its 1:1)
147 if (strstr($line, '%USER%')) {
148 // if user is not logged in, this ACL line is meaningless - skip it
149 if (!$INPUT->server->has('REMOTE_USER')) continue;
151 $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
152 $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
155 // substitute group wildcard (its 1:m)
156 if (strstr($line, '%GROUP%')) {
157 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
158 if (isset($USERINFO['grps'])) {
159 foreach ((array) $USERINFO['grps'] as $grp) {
160 $nid = str_replace('%GROUP%', cleanID($grp), $id);
161 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
162 $out[] = "$nid\t$nrest";
165 } else {
166 $out[] = "$id\t$rest";
170 return $out;
174 * Try a token login
176 * @return bool true if token login succeeded
178 function auth_tokenlogin()
180 global $USERINFO;
181 global $INPUT;
182 /** @var DokuWiki_Auth_Plugin $auth */
183 global $auth;
184 if (!$auth) return false;
186 // see if header has token
187 $header = '';
188 if (function_exists('getallheaders')) {
189 // Authorization headers are not in $_SERVER for mod_php
190 $headers = array_change_key_case(getallheaders());
191 if (isset($headers['authorization'])) $header = $headers['authorization'];
192 } else {
193 $header = $INPUT->server->str('HTTP_AUTHORIZATION');
195 if (!$header) return false;
196 [$type, $token] = sexplode(' ', $header, 2);
197 if ($type !== 'Bearer') return false;
199 // check token
200 try {
201 $authtoken = JWT::validate($token);
202 } catch (Exception $e) {
203 msg(hsc($e->getMessage()), -1);
204 return false;
207 // fetch user info from backend
208 $user = $authtoken->getUser();
209 $USERINFO = $auth->getUserData($user);
210 if (!$USERINFO) return false;
212 // the code is correct, set up user
213 $INPUT->server->set('REMOTE_USER', $user);
214 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
215 $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
216 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
218 return true;
222 * Event hook callback for AUTH_LOGIN_CHECK
224 * @param array $evdata
225 * @return bool
226 * @throws Exception
228 function auth_login_wrapper($evdata)
230 return auth_login(
231 $evdata['user'],
232 $evdata['password'],
233 $evdata['sticky'],
234 $evdata['silent']
239 * This tries to login the user based on the sent auth credentials
241 * The authentication works like this: if a username was given
242 * a new login is assumed and user/password are checked. If they
243 * are correct the password is encrypted with blowfish and stored
244 * together with the username in a cookie - the same info is stored
245 * in the session, too. Additonally a browserID is stored in the
246 * session.
248 * If no username was given the cookie is checked: if the username,
249 * crypted password and browserID match between session and cookie
250 * no further testing is done and the user is accepted
252 * If a cookie was found but no session info was availabe the
253 * blowfish encrypted password from the cookie is decrypted and
254 * together with username rechecked by calling this function again.
256 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
257 * are set.
259 * @param string $user Username
260 * @param string $pass Cleartext Password
261 * @param bool $sticky Cookie should not expire
262 * @param bool $silent Don't show error on bad auth
263 * @return bool true on successful auth
264 * @throws Exception
266 * @author Andreas Gohr <andi@splitbrain.org>
268 function auth_login($user, $pass, $sticky = false, $silent = false)
270 global $USERINFO;
271 global $conf;
272 global $lang;
273 /* @var AuthPlugin $auth */
274 global $auth;
275 /* @var Input $INPUT */
276 global $INPUT;
278 if (!$auth instanceof AuthPlugin) return false;
280 if (!empty($user)) {
281 //usual login
282 if (!empty($pass) && $auth->checkPass($user, $pass)) {
283 // make logininfo globally available
284 $INPUT->server->set('REMOTE_USER', $user);
285 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
286 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
287 return true;
288 } else {
289 //invalid credentials - log off
290 if (!$silent) {
291 http_status(403, 'Login failed');
292 msg($lang['badlogin'], -1);
294 auth_logoff();
295 return false;
297 } else {
298 // read cookie information
299 [$user, $sticky, $pass] = auth_getCookie();
300 if ($user && $pass) {
301 // we got a cookie - see if we can trust it
303 // get session info
304 if (isset($_SESSION[DOKU_COOKIE])) {
305 $session = $_SESSION[DOKU_COOKIE]['auth'];
306 if (
307 isset($session) &&
308 $auth->useSessionCache($user) &&
309 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
310 ($session['user'] == $user) &&
311 ($session['pass'] == sha1($pass)) && //still crypted
312 ($session['buid'] == auth_browseruid())
314 // he has session, cookie and browser right - let him in
315 $INPUT->server->set('REMOTE_USER', $user);
316 $USERINFO = $session['info']; //FIXME move all references to session
317 return true;
320 // no we don't trust it yet - recheck pass but silent
321 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
322 $pass = auth_decrypt($pass, $secret);
323 return auth_login($user, $pass, $sticky, true);
326 //just to be sure
327 auth_logoff(true);
328 return false;
332 * Builds a pseudo UID from browser and IP data
334 * This is neither unique nor unfakable - still it adds some
335 * security. Using the first part of the IP makes sure
336 * proxy farms like AOLs are still okay.
338 * @author Andreas Gohr <andi@splitbrain.org>
340 * @return string a SHA256 sum of various browser headers
342 function auth_browseruid()
344 /* @var Input $INPUT */
345 global $INPUT;
347 $ip = clientIP(true);
348 // convert IP string to packed binary representation
349 $pip = inet_pton($ip);
351 $uid = implode("\n", [
352 $INPUT->server->str('HTTP_USER_AGENT'),
353 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
354 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
356 return hash('sha256', $uid);
360 * Creates a random key to encrypt the password in cookies
362 * This function tries to read the password for encrypting
363 * cookies from $conf['metadir'].'/_htcookiesalt'
364 * if no such file is found a random key is created and
365 * and stored in this file.
367 * @param bool $addsession if true, the sessionid is added to the salt
368 * @param bool $secure if security is more important than keeping the old value
369 * @return string
370 * @throws Exception
372 * @author Andreas Gohr <andi@splitbrain.org>
374 function auth_cookiesalt($addsession = false, $secure = false)
376 if (defined('SIMPLE_TEST')) {
377 return 'test';
379 global $conf;
380 $file = $conf['metadir'] . '/_htcookiesalt';
381 if ($secure || !file_exists($file)) {
382 $file = $conf['metadir'] . '/_htcookiesalt2';
384 $salt = io_readFile($file);
385 if (empty($salt)) {
386 $salt = bin2hex(auth_randombytes(64));
387 io_saveFile($file, $salt);
389 if ($addsession) {
390 $salt .= session_id();
392 return $salt;
396 * Return cryptographically secure random bytes.
398 * @param int $length number of bytes
399 * @return string cryptographically secure random bytes
400 * @throws Exception
402 * @author Niklas Keller <me@kelunik.com>
404 function auth_randombytes($length)
406 return random_bytes($length);
410 * Cryptographically secure random number generator.
412 * @param int $min
413 * @param int $max
414 * @return int
415 * @throws Exception
417 * @author Niklas Keller <me@kelunik.com>
419 function auth_random($min, $max)
421 return random_int($min, $max);
425 * Encrypt data using the given secret using AES
427 * The mode is CBC with a random initialization vector, the key is derived
428 * using pbkdf2.
430 * @param string $data The data that shall be encrypted
431 * @param string $secret The secret/password that shall be used
432 * @return string The ciphertext
433 * @throws Exception
435 function auth_encrypt($data, $secret)
437 $iv = auth_randombytes(16);
438 $cipher = new AES('cbc');
439 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
440 $cipher->setIV($iv);
443 this uses the encrypted IV as IV as suggested in
444 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
445 for unique but necessarily random IVs. The resulting ciphertext is
446 compatible to ciphertext that was created using a "normal" IV.
448 return $cipher->encrypt($iv . $data);
452 * Decrypt the given AES ciphertext
454 * The mode is CBC, the key is derived using pbkdf2
456 * @param string $ciphertext The encrypted data
457 * @param string $secret The secret/password that shall be used
458 * @return string The decrypted data
460 function auth_decrypt($ciphertext, $secret)
462 $iv = substr($ciphertext, 0, 16);
463 $cipher = new AES('cbc');
464 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
465 $cipher->setIV($iv);
467 return $cipher->decrypt(substr($ciphertext, 16));
471 * Log out the current user
473 * This clears all authentication data and thus log the user
474 * off. It also clears session data.
476 * @author Andreas Gohr <andi@splitbrain.org>
478 * @param bool $keepbc - when true, the breadcrumb data is not cleared
480 function auth_logoff($keepbc = false)
482 global $conf;
483 global $USERINFO;
484 /* @var AuthPlugin $auth */
485 global $auth;
486 /* @var Input $INPUT */
487 global $INPUT;
489 // make sure the session is writable (it usually is)
490 @session_start();
492 if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
493 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
494 if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
495 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
496 if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
497 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
498 if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
499 unset($_SESSION[DOKU_COOKIE]['bc']);
500 $INPUT->server->remove('REMOTE_USER');
501 $USERINFO = null; //FIXME
503 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
504 setcookie(DOKU_COOKIE, '', [
505 'expires' => time() - 600000,
506 'path' => $cookieDir,
507 'secure' => ($conf['securecookie'] && is_ssl()),
508 'httponly' => true,
509 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
512 if ($auth instanceof AuthPlugin) {
513 $auth->logOff();
518 * Check if a user is a manager
520 * Should usually be called without any parameters to check the current
521 * user.
523 * The info is available through $INFO['ismanager'], too
525 * @param string $user Username
526 * @param array $groups List of groups the user is in
527 * @param bool $adminonly when true checks if user is admin
528 * @param bool $recache set to true to refresh the cache
529 * @return bool
530 * @see auth_isadmin
532 * @author Andreas Gohr <andi@splitbrain.org>
534 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
536 global $conf;
537 global $USERINFO;
538 /* @var AuthPlugin $auth */
539 global $auth;
540 /* @var Input $INPUT */
541 global $INPUT;
544 if (!$auth instanceof AuthPlugin) return false;
545 if (is_null($user)) {
546 if (!$INPUT->server->has('REMOTE_USER')) {
547 return false;
548 } else {
549 $user = $INPUT->server->str('REMOTE_USER');
552 if (is_null($groups)) {
553 // checking the logged in user, or another one?
554 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
555 $groups = (array) $USERINFO['grps'];
556 } else {
557 $groups = $auth->getUserData($user);
558 $groups = $groups ? $groups['grps'] : [];
562 // prefer cached result
563 static $cache = [];
564 $cachekey = serialize([$user, $adminonly, $groups]);
565 if (!isset($cache[$cachekey]) || $recache) {
566 // check superuser match
567 $ok = auth_isMember($conf['superuser'], $user, $groups);
569 // check managers
570 if (!$ok && !$adminonly) {
571 $ok = auth_isMember($conf['manager'], $user, $groups);
574 $cache[$cachekey] = $ok;
577 return $cache[$cachekey];
581 * Check if a user is admin
583 * Alias to auth_ismanager with adminonly=true
585 * The info is available through $INFO['isadmin'], too
587 * @param string $user Username
588 * @param array $groups List of groups the user is in
589 * @param bool $recache set to true to refresh the cache
590 * @return bool
591 * @author Andreas Gohr <andi@splitbrain.org>
592 * @see auth_ismanager()
595 function auth_isadmin($user = null, $groups = null, $recache = false)
597 return auth_ismanager($user, $groups, true, $recache);
601 * Match a user and his groups against a comma separated list of
602 * users and groups to determine membership status
604 * Note: all input should NOT be nameencoded.
606 * @param string $memberlist commaseparated list of allowed users and groups
607 * @param string $user user to match against
608 * @param array $groups groups the user is member of
609 * @return bool true for membership acknowledged
611 function auth_isMember($memberlist, $user, array $groups)
613 /* @var AuthPlugin $auth */
614 global $auth;
615 if (!$auth instanceof AuthPlugin) return false;
617 // clean user and groups
618 if (!$auth->isCaseSensitive()) {
619 $user = PhpString::strtolower($user);
620 $groups = array_map([PhpString::class, 'strtolower'], $groups);
622 $user = $auth->cleanUser($user);
623 $groups = array_map([$auth, 'cleanGroup'], $groups);
625 // extract the memberlist
626 $members = explode(',', $memberlist);
627 $members = array_map('trim', $members);
628 $members = array_unique($members);
629 $members = array_filter($members);
631 // compare cleaned values
632 foreach ($members as $member) {
633 if ($member == '@ALL') return true;
634 if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
635 if ($member[0] == '@') {
636 $member = $auth->cleanGroup(substr($member, 1));
637 if (in_array($member, $groups)) return true;
638 } else {
639 $member = $auth->cleanUser($member);
640 if ($member == $user) return true;
644 // still here? not a member!
645 return false;
649 * Convinience function for auth_aclcheck()
651 * This checks the permissions for the current user
653 * @author Andreas Gohr <andi@splitbrain.org>
655 * @param string $id page ID (needs to be resolved and cleaned)
656 * @return int permission level
658 function auth_quickaclcheck($id)
660 global $conf;
661 global $USERINFO;
662 /* @var Input $INPUT */
663 global $INPUT;
664 # if no ACL is used always return upload rights
665 if (!$conf['useacl']) return AUTH_UPLOAD;
666 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
670 * Returns the maximum rights a user has for the given ID or its namespace
672 * @author Andreas Gohr <andi@splitbrain.org>
674 * @triggers AUTH_ACL_CHECK
675 * @param string $id page ID (needs to be resolved and cleaned)
676 * @param string $user Username
677 * @param array|null $groups Array of groups the user is in
678 * @return int permission level
680 function auth_aclcheck($id, $user, $groups)
682 $data = [
683 'id' => $id ?? '',
684 'user' => $user,
685 'groups' => $groups
688 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
692 * default ACL check method
694 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
696 * @author Andreas Gohr <andi@splitbrain.org>
698 * @param array $data event data
699 * @return int permission level
701 function auth_aclcheck_cb($data)
703 $id =& $data['id'];
704 $user =& $data['user'];
705 $groups =& $data['groups'];
707 global $conf;
708 global $AUTH_ACL;
709 /* @var AuthPlugin $auth */
710 global $auth;
712 // if no ACL is used always return upload rights
713 if (!$conf['useacl']) return AUTH_UPLOAD;
714 if (!$auth instanceof AuthPlugin) return AUTH_NONE;
715 if (!is_array($AUTH_ACL)) return AUTH_NONE;
717 //make sure groups is an array
718 if (!is_array($groups)) $groups = [];
720 //if user is superuser or in superusergroup return 255 (acl_admin)
721 if (auth_isadmin($user, $groups)) {
722 return AUTH_ADMIN;
725 if (!$auth->isCaseSensitive()) {
726 $user = PhpString::strtolower($user);
727 $groups = array_map([PhpString::class, 'strtolower'], $groups);
729 $user = auth_nameencode($auth->cleanUser($user));
730 $groups = array_map([$auth, 'cleanGroup'], $groups);
732 //prepend groups with @ and nameencode
733 foreach ($groups as &$group) {
734 $group = '@' . auth_nameencode($group);
737 $ns = getNS($id);
738 $perm = -1;
740 //add ALL group
741 $groups[] = '@ALL';
743 //add User
744 if ($user) $groups[] = $user;
746 //check exact match first
747 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
748 if (count($matches)) {
749 foreach ($matches as $match) {
750 $match = preg_replace('/#.*$/', '', $match); //ignore comments
751 $acl = preg_split('/[ \t]+/', $match);
752 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
753 $acl[1] = PhpString::strtolower($acl[1]);
755 if (!in_array($acl[1], $groups)) {
756 continue;
758 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
759 if ($acl[2] > $perm) {
760 $perm = $acl[2];
763 if ($perm > -1) {
764 //we had a match - return it
765 return (int) $perm;
769 //still here? do the namespace checks
770 if ($ns) {
771 $path = $ns . ':*';
772 } else {
773 $path = '*'; //root document
776 do {
777 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
778 if (count($matches)) {
779 foreach ($matches as $match) {
780 $match = preg_replace('/#.*$/', '', $match); //ignore comments
781 $acl = preg_split('/[ \t]+/', $match);
782 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
783 $acl[1] = PhpString::strtolower($acl[1]);
785 if (!in_array($acl[1], $groups)) {
786 continue;
788 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
789 if ($acl[2] > $perm) {
790 $perm = $acl[2];
793 //we had a match - return it
794 if ($perm != -1) {
795 return (int) $perm;
798 //get next higher namespace
799 $ns = getNS($ns);
801 if ($path != '*') {
802 $path = $ns . ':*';
803 if ($path == ':*') $path = '*';
804 } else {
805 //we did this already
806 //looks like there is something wrong with the ACL
807 //break here
808 msg('No ACL setup yet! Denying access to everyone.');
809 return AUTH_NONE;
811 } while (1); //this should never loop endless
812 return AUTH_NONE;
816 * Encode ASCII special chars
818 * Some auth backends allow special chars in their user and groupnames
819 * The special chars are encoded with this function. Only ASCII chars
820 * are encoded UTF-8 multibyte are left as is (different from usual
821 * urlencoding!).
823 * Decoding can be done with rawurldecode
825 * @author Andreas Gohr <gohr@cosmocode.de>
826 * @see rawurldecode()
828 * @param string $name
829 * @param bool $skip_group
830 * @return string
832 function auth_nameencode($name, $skip_group = false)
834 global $cache_authname;
835 $cache =& $cache_authname;
836 $name = (string) $name;
838 // never encode wildcard FS#1955
839 if ($name == '%USER%') return $name;
840 if ($name == '%GROUP%') return $name;
842 if (!isset($cache[$name][$skip_group])) {
843 if ($skip_group && $name[0] == '@') {
844 $cache[$name][$skip_group] = '@' . preg_replace_callback(
845 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
846 'auth_nameencode_callback',
847 substr($name, 1)
849 } else {
850 $cache[$name][$skip_group] = preg_replace_callback(
851 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
852 'auth_nameencode_callback',
853 $name
858 return $cache[$name][$skip_group];
862 * callback encodes the matches
864 * @param array $matches first complete match, next matching subpatterms
865 * @return string
867 function auth_nameencode_callback($matches)
869 return '%' . dechex(ord(substr($matches[1], -1)));
873 * Create a pronouncable password
875 * The $foruser variable might be used by plugins to run additional password
876 * policy checks, but is not used by the default implementation
878 * @param string $foruser username for which the password is generated
879 * @return string pronouncable password
880 * @throws Exception
882 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
883 * @triggers AUTH_PASSWORD_GENERATE
885 * @author Andreas Gohr <andi@splitbrain.org>
887 function auth_pwgen($foruser = '')
889 $data = [
890 'password' => '',
891 'foruser' => $foruser
894 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
895 if ($evt->advise_before(true)) {
896 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
897 $v = 'aeiou'; //vowels
898 $a = $c . $v; //both
899 $s = '!$%&?+*~#-_:.;,'; // specials
901 //use thre syllables...
902 for ($i = 0; $i < 3; $i++) {
903 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
904 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
905 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
907 //... and add a nice number and special
908 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
910 $evt->advise_after();
912 return $data['password'];
916 * Sends a password to the given user
918 * @author Andreas Gohr <andi@splitbrain.org>
920 * @param string $user Login name of the user
921 * @param string $password The new password in clear text
922 * @return bool true on success
924 function auth_sendPassword($user, $password)
926 global $lang;
927 /* @var AuthPlugin $auth */
928 global $auth;
929 if (!$auth instanceof AuthPlugin) return false;
931 $user = $auth->cleanUser($user);
932 $userinfo = $auth->getUserData($user, false);
934 if (!$userinfo['mail']) return false;
936 $text = rawLocale('password');
937 $trep = [
938 'FULLNAME' => $userinfo['name'],
939 'LOGIN' => $user,
940 'PASSWORD' => $password
943 $mail = new Mailer();
944 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
945 $mail->subject($lang['regpwmail']);
946 $mail->setBody($text, $trep);
947 return $mail->send();
951 * Register a new user
953 * This registers a new user - Data is read directly from $_POST
955 * @return bool true on success, false on any error
956 * @throws Exception
958 * @author Andreas Gohr <andi@splitbrain.org>
960 function register()
962 global $lang;
963 global $conf;
964 /* @var AuthPlugin $auth */
965 global $auth;
966 global $INPUT;
968 if (!$INPUT->post->bool('save')) return false;
969 if (!actionOK('register')) return false;
971 // gather input
972 $login = trim($auth->cleanUser($INPUT->post->str('login')));
973 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
974 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
975 $pass = $INPUT->post->str('pass');
976 $passchk = $INPUT->post->str('passchk');
978 if (empty($login) || empty($fullname) || empty($email)) {
979 msg($lang['regmissing'], -1);
980 return false;
983 if ($conf['autopasswd']) {
984 $pass = auth_pwgen($login); // automatically generate password
985 } elseif (empty($pass) || empty($passchk)) {
986 msg($lang['regmissing'], -1); // complain about missing passwords
987 return false;
988 } elseif ($pass != $passchk) {
989 msg($lang['regbadpass'], -1); // complain about misspelled passwords
990 return false;
993 //check mail
994 if (!mail_isvalid($email)) {
995 msg($lang['regbadmail'], -1);
996 return false;
999 //okay try to create the user
1000 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1001 msg($lang['regfail'], -1);
1002 return false;
1005 // send notification about the new user
1006 $subscription = new RegistrationSubscriptionSender();
1007 $subscription->sendRegister($login, $fullname, $email);
1009 // are we done?
1010 if (!$conf['autopasswd']) {
1011 msg($lang['regsuccess2'], 1);
1012 return true;
1015 // autogenerated password? then send password to user
1016 if (auth_sendPassword($login, $pass)) {
1017 msg($lang['regsuccess'], 1);
1018 return true;
1019 } else {
1020 msg($lang['regmailfail'], -1);
1021 return false;
1026 * Update user profile
1028 * @throws Exception
1030 * @author Christopher Smith <chris@jalakai.co.uk>
1032 function updateprofile()
1034 global $conf;
1035 global $lang;
1036 /* @var AuthPlugin $auth */
1037 global $auth;
1038 /* @var Input $INPUT */
1039 global $INPUT;
1041 if (!$INPUT->post->bool('save')) return false;
1042 if (!checkSecurityToken()) return false;
1044 if (!actionOK('profile')) {
1045 msg($lang['profna'], -1);
1046 return false;
1049 $changes = [];
1050 $changes['pass'] = $INPUT->post->str('newpass');
1051 $changes['name'] = $INPUT->post->str('fullname');
1052 $changes['mail'] = $INPUT->post->str('email');
1054 // check misspelled passwords
1055 if ($changes['pass'] != $INPUT->post->str('passchk')) {
1056 msg($lang['regbadpass'], -1);
1057 return false;
1060 // clean fullname and email
1061 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1062 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1064 // no empty name and email (except the backend doesn't support them)
1065 if (
1066 (empty($changes['name']) && $auth->canDo('modName')) ||
1067 (empty($changes['mail']) && $auth->canDo('modMail'))
1069 msg($lang['profnoempty'], -1);
1070 return false;
1072 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1073 msg($lang['regbadmail'], -1);
1074 return false;
1077 $changes = array_filter($changes);
1079 // check for unavailable capabilities
1080 if (!$auth->canDo('modName')) unset($changes['name']);
1081 if (!$auth->canDo('modMail')) unset($changes['mail']);
1082 if (!$auth->canDo('modPass')) unset($changes['pass']);
1084 // anything to do?
1085 if ($changes === []) {
1086 msg($lang['profnochange'], -1);
1087 return false;
1090 if ($conf['profileconfirm']) {
1091 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1092 msg($lang['badpassconfirm'], -1);
1093 return false;
1097 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1098 msg($lang['proffail'], -1);
1099 return false;
1102 if (array_key_exists('pass', $changes) && $changes['pass']) {
1103 // update cookie and session with the changed data
1104 [/* user */, $sticky, /* pass */] = auth_getCookie();
1105 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1106 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1107 } else {
1108 // make sure the session is writable
1109 @session_start();
1110 // invalidate session cache
1111 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1112 session_write_close();
1115 return true;
1119 * Delete the current logged-in user
1121 * @return bool true on success, false on any error
1123 function auth_deleteprofile()
1125 global $conf;
1126 global $lang;
1127 /* @var AuthPlugin $auth */
1128 global $auth;
1129 /* @var Input $INPUT */
1130 global $INPUT;
1132 if (!$INPUT->post->bool('delete')) return false;
1133 if (!checkSecurityToken()) return false;
1135 // action prevented or auth module disallows
1136 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1137 msg($lang['profnodelete'], -1);
1138 return false;
1141 if (!$INPUT->post->bool('confirm_delete')) {
1142 msg($lang['profconfdeletemissing'], -1);
1143 return false;
1146 if ($conf['profileconfirm']) {
1147 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1148 msg($lang['badpassconfirm'], -1);
1149 return false;
1153 $deleted = [];
1154 $deleted[] = $INPUT->server->str('REMOTE_USER');
1155 if ($auth->triggerUserMod('delete', [$deleted])) {
1156 // force and immediate logout including removing the sticky cookie
1157 auth_logoff();
1158 return true;
1161 return false;
1165 * Send a new password
1167 * This function handles both phases of the password reset:
1169 * - handling the first request of password reset
1170 * - validating the password reset auth token
1172 * @return bool true on success, false on any error
1173 * @throws Exception
1175 * @author Andreas Gohr <andi@splitbrain.org>
1176 * @author Benoit Chesneau <benoit@bchesneau.info>
1177 * @author Chris Smith <chris@jalakai.co.uk>
1179 function act_resendpwd()
1181 global $lang;
1182 global $conf;
1183 /* @var AuthPlugin $auth */
1184 global $auth;
1185 /* @var Input $INPUT */
1186 global $INPUT;
1188 if (!actionOK('resendpwd')) {
1189 msg($lang['resendna'], -1);
1190 return false;
1193 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1195 if ($token) {
1196 // we're in token phase - get user info from token
1198 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1199 if (!file_exists($tfile)) {
1200 msg($lang['resendpwdbadauth'], -1);
1201 $INPUT->remove('pwauth');
1202 return false;
1204 // token is only valid for 3 days
1205 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1206 msg($lang['resendpwdbadauth'], -1);
1207 $INPUT->remove('pwauth');
1208 @unlink($tfile);
1209 return false;
1212 $user = io_readfile($tfile);
1213 $userinfo = $auth->getUserData($user, false);
1214 if (!$userinfo['mail']) {
1215 msg($lang['resendpwdnouser'], -1);
1216 return false;
1219 if (!$conf['autopasswd']) { // we let the user choose a password
1220 $pass = $INPUT->str('pass');
1222 // password given correctly?
1223 if (!$pass) return false;
1224 if ($pass != $INPUT->str('passchk')) {
1225 msg($lang['regbadpass'], -1);
1226 return false;
1229 // change it
1230 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1231 msg($lang['proffail'], -1);
1232 return false;
1234 } else { // autogenerate the password and send by mail
1235 $pass = auth_pwgen($user);
1236 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1237 msg($lang['proffail'], -1);
1238 return false;
1241 if (auth_sendPassword($user, $pass)) {
1242 msg($lang['resendpwdsuccess'], 1);
1243 } else {
1244 msg($lang['regmailfail'], -1);
1248 @unlink($tfile);
1249 return true;
1250 } else {
1251 // we're in request phase
1253 if (!$INPUT->post->bool('save')) return false;
1255 if (!$INPUT->post->str('login')) {
1256 msg($lang['resendpwdmissing'], -1);
1257 return false;
1258 } else {
1259 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1262 $userinfo = $auth->getUserData($user, false);
1263 if (!$userinfo['mail']) {
1264 msg($lang['resendpwdnouser'], -1);
1265 return false;
1268 // generate auth token
1269 $token = md5(auth_randombytes(16)); // random secret
1270 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1271 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1273 io_saveFile($tfile, $user);
1275 $text = rawLocale('pwconfirm');
1276 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
1278 $mail = new Mailer();
1279 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1280 $mail->subject($lang['regpwmail']);
1281 $mail->setBody($text, $trep);
1282 if ($mail->send()) {
1283 msg($lang['resendpwdconfirm'], 1);
1284 } else {
1285 msg($lang['regmailfail'], -1);
1287 return true;
1289 // never reached
1293 * Encrypts a password using the given method and salt
1295 * If the selected method needs a salt and none was given, a random one
1296 * is chosen.
1298 * @author Andreas Gohr <andi@splitbrain.org>
1300 * @param string $clear The clear text password
1301 * @param string $method The hashing method
1302 * @param string $salt A salt, null for random
1303 * @return string The crypted password
1305 function auth_cryptPassword($clear, $method = '', $salt = null)
1307 global $conf;
1308 if (empty($method)) $method = $conf['passcrypt'];
1310 $pass = new PassHash();
1311 $call = 'hash_' . $method;
1313 if (!method_exists($pass, $call)) {
1314 msg("Unsupported crypt method $method", -1);
1315 return false;
1318 return $pass->$call($clear, $salt);
1322 * Verifies a cleartext password against a crypted hash
1324 * @param string $clear The clear text password
1325 * @param string $crypt The hash to compare with
1326 * @return bool true if both match
1327 * @throws Exception
1329 * @author Andreas Gohr <andi@splitbrain.org>
1331 function auth_verifyPassword($clear, $crypt)
1333 $pass = new PassHash();
1334 return $pass->verify_hash($clear, $crypt);
1338 * Set the authentication cookie and add user identification data to the session
1340 * @param string $user username
1341 * @param string $pass encrypted password
1342 * @param bool $sticky whether or not the cookie will last beyond the session
1343 * @return bool
1345 function auth_setCookie($user, $pass, $sticky)
1347 global $conf;
1348 /* @var AuthPlugin $auth */
1349 global $auth;
1350 global $USERINFO;
1352 if (!$auth instanceof AuthPlugin) return false;
1353 $USERINFO = $auth->getUserData($user);
1355 // set cookie
1356 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1357 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1358 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1359 setcookie(DOKU_COOKIE, $cookie, [
1360 'expires' => $time,
1361 'path' => $cookieDir,
1362 'secure' => ($conf['securecookie'] && is_ssl()),
1363 'httponly' => true,
1364 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1367 // set session
1368 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1369 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1370 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1371 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1372 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1374 return true;
1378 * Returns the user, (encrypted) password and sticky bit from cookie
1380 * @returns array
1382 function auth_getCookie()
1384 if (!isset($_COOKIE[DOKU_COOKIE])) {
1385 return [null, null, null];
1387 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1388 $sticky = (bool) $sticky;
1389 $pass = base64_decode($pass);
1390 $user = base64_decode($user);
1391 return [$user, $sticky, $pass];
1394 //Setup VIM: ex: et ts=2 :