🤖 Rector and PHPCS fixes
[dokuwiki.git] / inc / auth.php
blobd10ae1a41510ddfeeec01a36cad2717ed5b2cb77
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 phpseclib\Crypt\AES;
15 use dokuwiki\Utf8\PhpString;
16 use dokuwiki\Extension\AuthPlugin;
17 use dokuwiki\Extension\Event;
18 use dokuwiki\Extension\PluginController;
19 use dokuwiki\PassHash;
20 use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
22 /**
23 * Initialize the auth system.
25 * This function is automatically called at the end of init.php
27 * This used to be the main() of the auth.php
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
34 function auth_setup()
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 = [];
47 if (!$conf['useacl']) return false;
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;
57 if (!$auth instanceof AuthPlugin) {
58 msg($lang['authtempfail'], -1);
59 return false;
62 if ($auth->success == false) {
63 // degrade to unauthenticated user
64 $auth = null;
65 auth_logoff();
66 msg($lang['authtempfail'], -1);
67 return false;
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);
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;
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);
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')));
95 if (!auth_tokenlogin()) {
96 $ok = null;
98 if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
99 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
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')
111 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
115 //load ACL into a global array XXX
116 $AUTH_ACL = auth_loadACL();
118 return true;
122 * Loads the ACL setup and handle user wildcards
124 * @author Andreas Gohr <andi@splitbrain.org>
126 * @return array
128 function auth_loadACL()
130 global $config_cascade;
131 global $USERINFO;
132 /* @var Input $INPUT */
133 global $INPUT;
135 if (!is_readable($config_cascade['acl']['default'])) return [];
137 $acl = file($config_cascade['acl']['default']);
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);
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;
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);
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";
164 } else {
165 $out[] = "$id\t$rest";
169 return $out;
173 * Try a token login
175 * @return bool true if token login succeeded
177 function auth_tokenlogin()
179 global $USERINFO;
180 global $INPUT;
181 /** @var DokuWiki_Auth_Plugin $auth */
182 global $auth;
183 if (!$auth) return false;
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');
194 if (!$header) return false;
195 [$type, $token] = sexplode(' ', $header, 2);
196 if ($type !== 'Bearer') return false;
198 // check token
199 try {
200 $authtoken = JWT::validate($token);
201 } catch (Exception $e) {
202 msg(hsc($e->getMessage()), -1);
203 return false;
206 // fetch user info from backend
207 $user = $authtoken->getUser();
208 $USERINFO = $auth->getUserData($user);
209 if (!$USERINFO) return false;
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;
217 return true;
221 * Event hook callback for AUTH_LOGIN_CHECK
223 * @param array $evdata
224 * @return bool
225 * @throws Exception
227 function auth_login_wrapper($evdata)
229 return auth_login(
230 $evdata['user'],
231 $evdata['password'],
232 $evdata['sticky'],
233 $evdata['silent']
238 * This tries to login the user based on the sent auth credentials
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.
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
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.
255 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
256 * are set.
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
265 * @author Andreas Gohr <andi@splitbrain.org>
267 function auth_login($user, $pass, $sticky = false, $silent = false)
269 global $USERINFO;
270 global $conf;
271 global $lang;
272 /* @var AuthPlugin $auth */
273 global $auth;
274 /* @var Input $INPUT */
275 global $INPUT;
277 if (!$auth instanceof AuthPlugin) return false;
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);
293 auth_logoff();
294 return false;
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
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())
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;
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);
325 //just to be sure
326 auth_logoff(true);
327 return false;
331 * Builds a pseudo UID from browser and IP data
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.
337 * @author Andreas Gohr <andi@splitbrain.org>
339 * @return string a SHA256 sum of various browser headers
341 function auth_browseruid()
343 /* @var Input $INPUT */
344 global $INPUT;
346 $ip = clientIP(true);
347 // convert IP string to packed binary representation
348 $pip = inet_pton($ip);
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)
355 return hash('sha256', $uid);
359 * Creates a random key to encrypt the password in cookies
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.
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
371 * @author Andreas Gohr <andi@splitbrain.org>
373 function auth_cookiesalt($addsession = false, $secure = false)
375 if (defined('SIMPLE_TEST')) {
376 return 'test';
378 global $conf;
379 $file = $conf['metadir'] . '/_htcookiesalt';
380 if ($secure || !file_exists($file)) {
381 $file = $conf['metadir'] . '/_htcookiesalt2';
383 $salt = io_readFile($file);
384 if (empty($salt)) {
385 $salt = bin2hex(auth_randombytes(64));
386 io_saveFile($file, $salt);
388 if ($addsession) {
389 $salt .= session_id();
391 return $salt;
395 * Return cryptographically secure random bytes.
397 * @param int $length number of bytes
398 * @return string cryptographically secure random bytes
399 * @throws Exception
401 * @author Niklas Keller <me@kelunik.com>
403 function auth_randombytes($length)
405 return random_bytes($length);
409 * Cryptographically secure random number generator.
411 * @param int $min
412 * @param int $max
413 * @return int
414 * @throws Exception
416 * @author Niklas Keller <me@kelunik.com>
418 function auth_random($min, $max)
420 return random_int($min, $max);
424 * Encrypt data using the given secret using AES
426 * The mode is CBC with a random initialization vector, the key is derived
427 * using pbkdf2.
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
434 function auth_encrypt($data, $secret)
436 $iv = auth_randombytes(16);
437 $cipher = new AES();
438 $cipher->setPassword($secret);
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.
446 return $cipher->encrypt($iv . $data);
450 * Decrypt the given AES ciphertext
452 * The mode is CBC, the key is derived using pbkdf2
454 * @param string $ciphertext The encrypted data
455 * @param string $secret The secret/password that shall be used
456 * @return string The decrypted data
458 function auth_decrypt($ciphertext, $secret)
460 $iv = substr($ciphertext, 0, 16);
461 $cipher = new AES();
462 $cipher->setPassword($secret);
463 $cipher->setIV($iv);
465 return $cipher->decrypt(substr($ciphertext, 16));
469 * Log out the current user
471 * This clears all authentication data and thus log the user
472 * off. It also clears session data.
474 * @author Andreas Gohr <andi@splitbrain.org>
476 * @param bool $keepbc - when true, the breadcrumb data is not cleared
478 function auth_logoff($keepbc = false)
480 global $conf;
481 global $USERINFO;
482 /* @var AuthPlugin $auth */
483 global $auth;
484 /* @var Input $INPUT */
485 global $INPUT;
487 // make sure the session is writable (it usually is)
488 @session_start();
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
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
510 if ($auth instanceof AuthPlugin) {
511 $auth->logOff();
516 * Check if a user is a manager
518 * Should usually be called without any parameters to check the current
519 * user.
521 * The info is available through $INFO['ismanager'], too
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
530 * @author Andreas Gohr <andi@splitbrain.org>
532 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
534 global $conf;
535 global $USERINFO;
536 /* @var AuthPlugin $auth */
537 global $auth;
538 /* @var Input $INPUT */
539 global $INPUT;
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');
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'] : [];
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);
567 // check managers
568 if (!$ok && !$adminonly) {
569 $ok = auth_isMember($conf['manager'], $user, $groups);
572 $cache[$cachekey] = $ok;
575 return $cache[$cachekey];
579 * Check if a user is admin
581 * Alias to auth_ismanager with adminonly=true
583 * The info is available through $INFO['isadmin'], too
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()
593 function auth_isadmin($user = null, $groups = null, $recache = false)
595 return auth_ismanager($user, $groups, true, $recache);
599 * Match a user and his groups against a comma separated list of
600 * users and groups to determine membership status
602 * Note: all input should NOT be nameencoded.
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
609 function auth_isMember($memberlist, $user, array $groups)
611 /* @var AuthPlugin $auth */
612 global $auth;
613 if (!$auth instanceof AuthPlugin) return false;
615 // clean user and groups
616 if (!$auth->isCaseSensitive()) {
617 $user = PhpString::strtolower($user);
618 $groups = array_map([PhpString::class, 'strtolower'], $groups);
620 $user = $auth->cleanUser($user);
621 $groups = array_map([$auth, 'cleanGroup'], $groups);
623 // extract the memberlist
624 $members = explode(',', $memberlist);
625 $members = array_map('trim', $members);
626 $members = array_unique($members);
627 $members = array_filter($members);
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;
642 // still here? not a member!
643 return false;
647 * Convinience function for auth_aclcheck()
649 * This checks the permissions for the current user
651 * @author Andreas Gohr <andi@splitbrain.org>
653 * @param string $id page ID (needs to be resolved and cleaned)
654 * @return int permission level
656 function auth_quickaclcheck($id)
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'] : []);
668 * Returns the maximum rights a user has for the given ID or its namespace
670 * @author Andreas Gohr <andi@splitbrain.org>
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
678 function auth_aclcheck($id, $user, $groups)
680 $data = [
681 'id' => $id ?? '',
682 'user' => $user,
683 'groups' => $groups
686 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
690 * default ACL check method
692 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
694 * @author Andreas Gohr <andi@splitbrain.org>
696 * @param array $data event data
697 * @return int permission level
699 function auth_aclcheck_cb($data)
701 $id =& $data['id'];
702 $user =& $data['user'];
703 $groups =& $data['groups'];
705 global $conf;
706 global $AUTH_ACL;
707 /* @var AuthPlugin $auth */
708 global $auth;
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;
715 //make sure groups is an array
716 if (!is_array($groups)) $groups = [];
718 //if user is superuser or in superusergroup return 255 (acl_admin)
719 if (auth_isadmin($user, $groups)) {
720 return AUTH_ADMIN;
723 if (!$auth->isCaseSensitive()) {
724 $user = PhpString::strtolower($user);
725 $groups = array_map([PhpString::class, 'strtolower'], $groups);
727 $user = auth_nameencode($auth->cleanUser($user));
728 $groups = array_map([$auth, 'cleanGroup'], $groups);
730 //prepend groups with @ and nameencode
731 foreach ($groups as &$group) {
732 $group = '@' . auth_nameencode($group);
735 $ns = getNS($id);
736 $perm = -1;
738 //add ALL group
739 $groups[] = '@ALL';
741 //add User
742 if ($user) $groups[] = $user;
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]);
753 if (!in_array($acl[1], $groups)) {
754 continue;
756 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
757 if ($acl[2] > $perm) {
758 $perm = $acl[2];
761 if ($perm > -1) {
762 //we had a match - return it
763 return (int) $perm;
767 //still here? do the namespace checks
768 if ($ns) {
769 $path = $ns . ':*';
770 } else {
771 $path = '*'; //root document
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]);
783 if (!in_array($acl[1], $groups)) {
784 continue;
786 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
787 if ($acl[2] > $perm) {
788 $perm = $acl[2];
791 //we had a match - return it
792 if ($perm != -1) {
793 return (int) $perm;
796 //get next higher namespace
797 $ns = getNS($ns);
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;
809 } while (1); //this should never loop endless
810 return AUTH_NONE;
814 * Encode ASCII special chars
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!).
821 * Decoding can be done with rawurldecode
823 * @author Andreas Gohr <gohr@cosmocode.de>
824 * @see rawurldecode()
826 * @param string $name
827 * @param bool $skip_group
828 * @return string
830 function auth_nameencode($name, $skip_group = false)
832 global $cache_authname;
833 $cache =& $cache_authname;
834 $name = (string) $name;
836 // never encode wildcard FS#1955
837 if ($name == '%USER%') return $name;
838 if ($name == '%GROUP%') return $name;
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)
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
856 return $cache[$name][$skip_group];
860 * callback encodes the matches
862 * @param array $matches first complete match, next matching subpatterms
863 * @return string
865 function auth_nameencode_callback($matches)
867 return '%' . dechex(ord(substr($matches[1], -1)));
871 * Create a pronouncable password
873 * The $foruser variable might be used by plugins to run additional password
874 * policy checks, but is not used by the default implementation
876 * @param string $foruser username for which the password is generated
877 * @return string pronouncable password
878 * @throws Exception
880 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
881 * @triggers AUTH_PASSWORD_GENERATE
883 * @author Andreas Gohr <andi@splitbrain.org>
885 function auth_pwgen($foruser = '')
887 $data = [
888 'password' => '',
889 'foruser' => $foruser
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
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)];
905 //... and add a nice number and special
906 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
908 $evt->advise_after();
910 return $data['password'];
914 * Sends a password to the given user
916 * @author Andreas Gohr <andi@splitbrain.org>
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
922 function auth_sendPassword($user, $password)
924 global $lang;
925 /* @var AuthPlugin $auth */
926 global $auth;
927 if (!$auth instanceof AuthPlugin) return false;
929 $user = $auth->cleanUser($user);
930 $userinfo = $auth->getUserData($user, false);
932 if (!$userinfo['mail']) return false;
934 $text = rawLocale('password');
935 $trep = [
936 'FULLNAME' => $userinfo['name'],
937 'LOGIN' => $user,
938 'PASSWORD' => $password
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();
949 * Register a new user
951 * This registers a new user - Data is read directly from $_POST
953 * @return bool true on success, false on any error
954 * @throws Exception
956 * @author Andreas Gohr <andi@splitbrain.org>
958 function register()
960 global $lang;
961 global $conf;
962 /* @var AuthPlugin $auth */
963 global $auth;
964 global $INPUT;
966 if (!$INPUT->post->bool('save')) return false;
967 if (!actionOK('register')) return false;
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');
976 if (empty($login) || empty($fullname) || empty($email)) {
977 msg($lang['regmissing'], -1);
978 return false;
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;
991 //check mail
992 if (!mail_isvalid($email)) {
993 msg($lang['regbadmail'], -1);
994 return false;
997 //okay try to create the user
998 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
999 msg($lang['regfail'], -1);
1000 return false;
1003 // send notification about the new user
1004 $subscription = new RegistrationSubscriptionSender();
1005 $subscription->sendRegister($login, $fullname, $email);
1007 // are we done?
1008 if (!$conf['autopasswd']) {
1009 msg($lang['regsuccess2'], 1);
1010 return true;
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;
1024 * Update user profile
1026 * @throws Exception
1028 * @author Christopher Smith <chris@jalakai.co.uk>
1030 function updateprofile()
1032 global $conf;
1033 global $lang;
1034 /* @var AuthPlugin $auth */
1035 global $auth;
1036 /* @var Input $INPUT */
1037 global $INPUT;
1039 if (!$INPUT->post->bool('save')) return false;
1040 if (!checkSecurityToken()) return false;
1042 if (!actionOK('profile')) {
1043 msg($lang['profna'], -1);
1044 return false;
1047 $changes = [];
1048 $changes['pass'] = $INPUT->post->str('newpass');
1049 $changes['name'] = $INPUT->post->str('fullname');
1050 $changes['mail'] = $INPUT->post->str('email');
1052 // check misspelled passwords
1053 if ($changes['pass'] != $INPUT->post->str('passchk')) {
1054 msg($lang['regbadpass'], -1);
1055 return false;
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']));
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'))
1067 msg($lang['profnoempty'], -1);
1068 return false;
1070 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1071 msg($lang['regbadmail'], -1);
1072 return false;
1075 $changes = array_filter($changes);
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']);
1082 // anything to do?
1083 if ($changes === []) {
1084 msg($lang['profnochange'], -1);
1085 return false;
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;
1095 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1096 msg($lang['proffail'], -1);
1097 return false;
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();
1113 return true;
1117 * Delete the current logged-in user
1119 * @return bool true on success, false on any error
1121 function auth_deleteprofile()
1123 global $conf;
1124 global $lang;
1125 /* @var AuthPlugin $auth */
1126 global $auth;
1127 /* @var Input $INPUT */
1128 global $INPUT;
1130 if (!$INPUT->post->bool('delete')) return false;
1131 if (!checkSecurityToken()) return false;
1133 // action prevented or auth module disallows
1134 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1135 msg($lang['profnodelete'], -1);
1136 return false;
1139 if (!$INPUT->post->bool('confirm_delete')) {
1140 msg($lang['profconfdeletemissing'], -1);
1141 return false;
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;
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;
1159 return false;
1163 * Send a new password
1165 * This function handles both phases of the password reset:
1167 * - handling the first request of password reset
1168 * - validating the password reset auth token
1170 * @return bool true on success, false on any error
1171 * @throws Exception
1173 * @author Andreas Gohr <andi@splitbrain.org>
1174 * @author Benoit Chesneau <benoit@bchesneau.info>
1175 * @author Chris Smith <chris@jalakai.co.uk>
1177 function act_resendpwd()
1179 global $lang;
1180 global $conf;
1181 /* @var AuthPlugin $auth */
1182 global $auth;
1183 /* @var Input $INPUT */
1184 global $INPUT;
1186 if (!actionOK('resendpwd')) {
1187 msg($lang['resendna'], -1);
1188 return false;
1191 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1193 if ($token) {
1194 // we're in token phase - get user info from token
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;
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;
1210 $user = io_readfile($tfile);
1211 $userinfo = $auth->getUserData($user, false);
1212 if (!$userinfo['mail']) {
1213 msg($lang['resendpwdnouser'], -1);
1214 return false;
1217 if (!$conf['autopasswd']) { // we let the user choose a password
1218 $pass = $INPUT->str('pass');
1220 // password given correctly?
1221 if (!$pass) return false;
1222 if ($pass != $INPUT->str('passchk')) {
1223 msg($lang['regbadpass'], -1);
1224 return false;
1227 // change it
1228 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1229 msg($lang['proffail'], -1);
1230 return false;
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;
1239 if (auth_sendPassword($user, $pass)) {
1240 msg($lang['resendpwdsuccess'], 1);
1241 } else {
1242 msg($lang['regmailfail'], -1);
1246 @unlink($tfile);
1247 return true;
1248 } else {
1249 // we're in request phase
1251 if (!$INPUT->post->bool('save')) return false;
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')));
1260 $userinfo = $auth->getUserData($user, false);
1261 if (!$userinfo['mail']) {
1262 msg($lang['resendpwdnouser'], -1);
1263 return false;
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, '&');
1271 io_saveFile($tfile, $user);
1273 $text = rawLocale('pwconfirm');
1274 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
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);
1285 return true;
1287 // never reached
1291 * Encrypts a password using the given method and salt
1293 * If the selected method needs a salt and none was given, a random one
1294 * is chosen.
1296 * @author Andreas Gohr <andi@splitbrain.org>
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
1303 function auth_cryptPassword($clear, $method = '', $salt = null)
1305 global $conf;
1306 if (empty($method)) $method = $conf['passcrypt'];
1308 $pass = new PassHash();
1309 $call = 'hash_' . $method;
1311 if (!method_exists($pass, $call)) {
1312 msg("Unsupported crypt method $method", -1);
1313 return false;
1316 return $pass->$call($clear, $salt);
1320 * Verifies a cleartext password against a crypted hash
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
1327 * @author Andreas Gohr <andi@splitbrain.org>
1329 function auth_verifyPassword($clear, $crypt)
1331 $pass = new PassHash();
1332 return $pass->verify_hash($clear, $crypt);
1336 * Set the authentication cookie and add user identification data to the session
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
1343 function auth_setCookie($user, $pass, $sticky)
1345 global $conf;
1346 /* @var AuthPlugin $auth */
1347 global $auth;
1348 global $USERINFO;
1350 if (!$auth instanceof AuthPlugin) return false;
1351 $USERINFO = $auth->getUserData($user);
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
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();
1372 return true;
1376 * Returns the user, (encrypted) password and sticky bit from cookie
1378 * @returns array
1380 function auth_getCookie()
1382 if (!isset($_COOKIE[DOKU_COOKIE])) {
1383 return [null, null, null];
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];
1392 //Setup VIM: ex: et ts=2 :