Introduce token authentication #2431
[dokuwiki.git] / inc / auth.php
blob372845359f4fba24fdb2953cf3102e43ce8b0d57
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 phpseclib\Crypt\AES;
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;
21 /**
22 * Initialize the auth system.
24 * This function is automatically called at the end of init.php
26 * This used to be the main() of the auth.php
28 * @todo backend loading maybe should be handled by the class autoloader
29 * @todo maybe split into multiple functions at the XXX marked positions
30 * @triggers AUTH_LOGIN_CHECK
31 * @return bool
33 function auth_setup()
35 global $conf;
36 /* @var AuthPlugin $auth */
37 global $auth;
38 /* @var Input $INPUT */
39 global $INPUT;
40 global $AUTH_ACL;
41 global $lang;
42 /* @var PluginController $plugin_controller */
43 global $plugin_controller;
44 $AUTH_ACL = [];
46 if (!$conf['useacl']) return false;
48 // try to load auth backend from plugins
49 foreach ($plugin_controller->getList('auth') as $plugin) {
50 if ($conf['authtype'] === $plugin) {
51 $auth = $plugin_controller->load('auth', $plugin);
52 break;
56 if (!$auth instanceof AuthPlugin) {
57 msg($lang['authtempfail'], -1);
58 return false;
61 if ($auth->success == false) {
62 // degrade to unauthenticated user
63 $auth = null;
64 auth_logoff();
65 msg($lang['authtempfail'], -1);
66 return false;
69 // do the login either by cookie or provided credentials XXX
70 $INPUT->set('http_credentials', false);
71 if (!$conf['rememberme']) $INPUT->set('r', false);
73 // Populate Basic Auth user/password from Authorization header
74 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
75 $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
76 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
77 $userpass = explode(':', base64_decode($matches[1]));
78 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
81 // if no credentials were given try to use HTTP auth (for SSO)
82 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
83 $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
84 $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
85 $INPUT->set('http_credentials', true);
88 // apply cleaning (auth specific user names, remove control chars)
89 if (true === $auth->success) {
90 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91 $INPUT->set('p', stripctl($INPUT->str('p')));
94 if(!auth_tokenlogin()) {
95 $ok = null;
97 if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
98 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
101 if ($ok === null) {
102 // external trust mechanism not in place, or returns no result,
103 // then attempt auth_login
104 $evdata = [
105 'user' => $INPUT->str('u'),
106 'password' => $INPUT->str('p'),
107 'sticky' => $INPUT->bool('r'),
108 'silent' => $INPUT->bool('http_credentials')
110 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
114 //load ACL into a global array XXX
115 $AUTH_ACL = auth_loadACL();
117 return true;
121 * Loads the ACL setup and handle user wildcards
123 * @author Andreas Gohr <andi@splitbrain.org>
125 * @return array
127 function auth_loadACL()
129 global $config_cascade;
130 global $USERINFO;
131 /* @var Input $INPUT */
132 global $INPUT;
134 if (!is_readable($config_cascade['acl']['default'])) return [];
136 $acl = file($config_cascade['acl']['default']);
138 $out = [];
139 foreach ($acl as $line) {
140 $line = trim($line);
141 if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
142 [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
144 // substitute user wildcard first (its 1:1)
145 if (strstr($line, '%USER%')) {
146 // if user is not logged in, this ACL line is meaningless - skip it
147 if (!$INPUT->server->has('REMOTE_USER')) continue;
149 $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
150 $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
153 // substitute group wildcard (its 1:m)
154 if (strstr($line, '%GROUP%')) {
155 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
156 if (isset($USERINFO['grps'])) {
157 foreach ((array) $USERINFO['grps'] as $grp) {
158 $nid = str_replace('%GROUP%', cleanID($grp), $id);
159 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
160 $out[] = "$nid\t$nrest";
163 } else {
164 $out[] = "$id\t$rest";
168 return $out;
172 * Try a token login
174 * @return bool true if token login succeeded
176 function auth_tokenlogin() {
177 global $USERINFO;
178 global $INPUT;
179 /** @var DokuWiki_Auth_Plugin $auth */
180 global $auth;
181 if(!$auth) return false;
183 // see if header has token
184 $header = '';
185 if(function_exists('apache_request_headers')) {
186 // Authorization headers are not in $_SERVER for mod_php
187 $headers = apache_request_headers();
188 if(isset($headers['Authorization'])) $header = $headers['Authorization'];
189 } else {
190 $header = $INPUT->server->str('HTTP_AUTHORIZATION');
192 if(!$header) return false;
193 list($type, $token) = sexplode(' ', $header, 2);
194 if($type !== 'Bearer') return false;
196 // check token
197 try {
198 $authtoken = \dokuwiki\JWT::validate($token);
199 } catch (Exception $e) {
200 msg(hsc($e->getMessage()), -1);
201 return false;
204 // fetch user info from backend
205 $user = $authtoken->getUser();
206 $USERINFO = $auth->getUserData($user);
207 if(!$USERINFO) return false;
209 // the code is correct, set up user
210 $INPUT->server->set('REMOTE_USER', $user);
211 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
212 $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
213 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
215 return true;
219 * Event hook callback for AUTH_LOGIN_CHECK
221 * @param array $evdata
222 * @return bool
223 * @throws Exception
225 function auth_login_wrapper($evdata)
227 return auth_login(
228 $evdata['user'],
229 $evdata['password'],
230 $evdata['sticky'],
231 $evdata['silent']
236 * This tries to login the user based on the sent auth credentials
238 * The authentication works like this: if a username was given
239 * a new login is assumed and user/password are checked. If they
240 * are correct the password is encrypted with blowfish and stored
241 * together with the username in a cookie - the same info is stored
242 * in the session, too. Additonally a browserID is stored in the
243 * session.
245 * If no username was given the cookie is checked: if the username,
246 * crypted password and browserID match between session and cookie
247 * no further testing is done and the user is accepted
249 * If a cookie was found but no session info was availabe the
250 * blowfish encrypted password from the cookie is decrypted and
251 * together with username rechecked by calling this function again.
253 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
254 * are set.
256 * @param string $user Username
257 * @param string $pass Cleartext Password
258 * @param bool $sticky Cookie should not expire
259 * @param bool $silent Don't show error on bad auth
260 * @return bool true on successful auth
261 * @throws Exception
263 * @author Andreas Gohr <andi@splitbrain.org>
265 function auth_login($user, $pass, $sticky = false, $silent = false)
267 global $USERINFO;
268 global $conf;
269 global $lang;
270 /* @var AuthPlugin $auth */
271 global $auth;
272 /* @var Input $INPUT */
273 global $INPUT;
275 if (!$auth instanceof AuthPlugin) return false;
277 if (!empty($user)) {
278 //usual login
279 if (!empty($pass) && $auth->checkPass($user, $pass)) {
280 // make logininfo globally available
281 $INPUT->server->set('REMOTE_USER', $user);
282 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
283 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
284 return true;
285 } else {
286 //invalid credentials - log off
287 if (!$silent) {
288 http_status(403, 'Login failed');
289 msg($lang['badlogin'], -1);
291 auth_logoff();
292 return false;
294 } else {
295 // read cookie information
296 [$user, $sticky, $pass] = auth_getCookie();
297 if ($user && $pass) {
298 // we got a cookie - see if we can trust it
300 // get session info
301 if (isset($_SESSION[DOKU_COOKIE])) {
302 $session = $_SESSION[DOKU_COOKIE]['auth'];
303 if (
304 isset($session) &&
305 $auth->useSessionCache($user) &&
306 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
307 ($session['user'] == $user) &&
308 ($session['pass'] == sha1($pass)) && //still crypted
309 ($session['buid'] == auth_browseruid())
311 // he has session, cookie and browser right - let him in
312 $INPUT->server->set('REMOTE_USER', $user);
313 $USERINFO = $session['info']; //FIXME move all references to session
314 return true;
317 // no we don't trust it yet - recheck pass but silent
318 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
319 $pass = auth_decrypt($pass, $secret);
320 return auth_login($user, $pass, $sticky, true);
323 //just to be sure
324 auth_logoff(true);
325 return false;
329 * Builds a pseudo UID from browser and IP data
331 * This is neither unique nor unfakable - still it adds some
332 * security. Using the first part of the IP makes sure
333 * proxy farms like AOLs are still okay.
335 * @author Andreas Gohr <andi@splitbrain.org>
337 * @return string a SHA256 sum of various browser headers
339 function auth_browseruid()
341 /* @var Input $INPUT */
342 global $INPUT;
344 $ip = clientIP(true);
345 // convert IP string to packed binary representation
346 $pip = inet_pton($ip);
348 $uid = implode("\n", [
349 $INPUT->server->str('HTTP_USER_AGENT'),
350 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
351 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
353 return hash('sha256', $uid);
357 * Creates a random key to encrypt the password in cookies
359 * This function tries to read the password for encrypting
360 * cookies from $conf['metadir'].'/_htcookiesalt'
361 * if no such file is found a random key is created and
362 * and stored in this file.
364 * @param bool $addsession if true, the sessionid is added to the salt
365 * @param bool $secure if security is more important than keeping the old value
366 * @return string
367 * @throws Exception
369 * @author Andreas Gohr <andi@splitbrain.org>
371 function auth_cookiesalt($addsession = false, $secure = false)
373 if (defined('SIMPLE_TEST')) {
374 return 'test';
376 global $conf;
377 $file = $conf['metadir'] . '/_htcookiesalt';
378 if ($secure || !file_exists($file)) {
379 $file = $conf['metadir'] . '/_htcookiesalt2';
381 $salt = io_readFile($file);
382 if (empty($salt)) {
383 $salt = bin2hex(auth_randombytes(64));
384 io_saveFile($file, $salt);
386 if ($addsession) {
387 $salt .= session_id();
389 return $salt;
393 * Return cryptographically secure random bytes.
395 * @param int $length number of bytes
396 * @return string cryptographically secure random bytes
397 * @throws Exception
399 * @author Niklas Keller <me@kelunik.com>
401 function auth_randombytes($length)
403 return random_bytes($length);
407 * Cryptographically secure random number generator.
409 * @param int $min
410 * @param int $max
411 * @return int
412 * @throws Exception
414 * @author Niklas Keller <me@kelunik.com>
416 function auth_random($min, $max)
418 return random_int($min, $max);
422 * Encrypt data using the given secret using AES
424 * The mode is CBC with a random initialization vector, the key is derived
425 * using pbkdf2.
427 * @param string $data The data that shall be encrypted
428 * @param string $secret The secret/password that shall be used
429 * @return string The ciphertext
430 * @throws Exception
432 function auth_encrypt($data, $secret)
434 $iv = auth_randombytes(16);
435 $cipher = new AES();
436 $cipher->setPassword($secret);
439 this uses the encrypted IV as IV as suggested in
440 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
441 for unique but necessarily random IVs. The resulting ciphertext is
442 compatible to ciphertext that was created using a "normal" IV.
444 return $cipher->encrypt($iv . $data);
448 * Decrypt the given AES ciphertext
450 * The mode is CBC, the key is derived using pbkdf2
452 * @param string $ciphertext The encrypted data
453 * @param string $secret The secret/password that shall be used
454 * @return string The decrypted data
456 function auth_decrypt($ciphertext, $secret)
458 $iv = substr($ciphertext, 0, 16);
459 $cipher = new AES();
460 $cipher->setPassword($secret);
461 $cipher->setIV($iv);
463 return $cipher->decrypt(substr($ciphertext, 16));
467 * Log out the current user
469 * This clears all authentication data and thus log the user
470 * off. It also clears session data.
472 * @author Andreas Gohr <andi@splitbrain.org>
474 * @param bool $keepbc - when true, the breadcrumb data is not cleared
476 function auth_logoff($keepbc = false)
478 global $conf;
479 global $USERINFO;
480 /* @var AuthPlugin $auth */
481 global $auth;
482 /* @var Input $INPUT */
483 global $INPUT;
485 // make sure the session is writable (it usually is)
486 @session_start();
488 if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
489 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
490 if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
491 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
492 if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
493 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
494 if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
495 unset($_SESSION[DOKU_COOKIE]['bc']);
496 $INPUT->server->remove('REMOTE_USER');
497 $USERINFO = null; //FIXME
499 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
500 setcookie(DOKU_COOKIE, '', [
501 'expires' => time() - 600000,
502 'path' => $cookieDir,
503 'secure' => ($conf['securecookie'] && is_ssl()),
504 'httponly' => true,
505 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
508 if ($auth instanceof AuthPlugin) {
509 $auth->logOff();
514 * Check if a user is a manager
516 * Should usually be called without any parameters to check the current
517 * user.
519 * The info is available through $INFO['ismanager'], too
521 * @param string $user Username
522 * @param array $groups List of groups the user is in
523 * @param bool $adminonly when true checks if user is admin
524 * @param bool $recache set to true to refresh the cache
525 * @return bool
526 * @see auth_isadmin
528 * @author Andreas Gohr <andi@splitbrain.org>
530 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
532 global $conf;
533 global $USERINFO;
534 /* @var AuthPlugin $auth */
535 global $auth;
536 /* @var Input $INPUT */
537 global $INPUT;
540 if (!$auth instanceof AuthPlugin) return false;
541 if (is_null($user)) {
542 if (!$INPUT->server->has('REMOTE_USER')) {
543 return false;
544 } else {
545 $user = $INPUT->server->str('REMOTE_USER');
548 if (is_null($groups)) {
549 // checking the logged in user, or another one?
550 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
551 $groups = (array) $USERINFO['grps'];
552 } else {
553 $groups = $auth->getUserData($user);
554 $groups = $groups ? $groups['grps'] : [];
558 // prefer cached result
559 static $cache = [];
560 $cachekey = serialize([$user, $adminonly, $groups]);
561 if (!isset($cache[$cachekey]) || $recache) {
562 // check superuser match
563 $ok = auth_isMember($conf['superuser'], $user, $groups);
565 // check managers
566 if (!$ok && !$adminonly) {
567 $ok = auth_isMember($conf['manager'], $user, $groups);
570 $cache[$cachekey] = $ok;
573 return $cache[$cachekey];
577 * Check if a user is admin
579 * Alias to auth_ismanager with adminonly=true
581 * The info is available through $INFO['isadmin'], too
583 * @param string $user Username
584 * @param array $groups List of groups the user is in
585 * @param bool $recache set to true to refresh the cache
586 * @return bool
587 * @author Andreas Gohr <andi@splitbrain.org>
588 * @see auth_ismanager()
591 function auth_isadmin($user = null, $groups = null, $recache = false)
593 return auth_ismanager($user, $groups, true, $recache);
597 * Match a user and his groups against a comma separated list of
598 * users and groups to determine membership status
600 * Note: all input should NOT be nameencoded.
602 * @param string $memberlist commaseparated list of allowed users and groups
603 * @param string $user user to match against
604 * @param array $groups groups the user is member of
605 * @return bool true for membership acknowledged
607 function auth_isMember($memberlist, $user, array $groups)
609 /* @var AuthPlugin $auth */
610 global $auth;
611 if (!$auth instanceof AuthPlugin) return false;
613 // clean user and groups
614 if (!$auth->isCaseSensitive()) {
615 $user = PhpString::strtolower($user);
616 $groups = array_map([PhpString::class, 'strtolower'], $groups);
618 $user = $auth->cleanUser($user);
619 $groups = array_map([$auth, 'cleanGroup'], $groups);
621 // extract the memberlist
622 $members = explode(',', $memberlist);
623 $members = array_map('trim', $members);
624 $members = array_unique($members);
625 $members = array_filter($members);
627 // compare cleaned values
628 foreach ($members as $member) {
629 if ($member == '@ALL') return true;
630 if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
631 if ($member[0] == '@') {
632 $member = $auth->cleanGroup(substr($member, 1));
633 if (in_array($member, $groups)) return true;
634 } else {
635 $member = $auth->cleanUser($member);
636 if ($member == $user) return true;
640 // still here? not a member!
641 return false;
645 * Convinience function for auth_aclcheck()
647 * This checks the permissions for the current user
649 * @author Andreas Gohr <andi@splitbrain.org>
651 * @param string $id page ID (needs to be resolved and cleaned)
652 * @return int permission level
654 function auth_quickaclcheck($id)
656 global $conf;
657 global $USERINFO;
658 /* @var Input $INPUT */
659 global $INPUT;
660 # if no ACL is used always return upload rights
661 if (!$conf['useacl']) return AUTH_UPLOAD;
662 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
666 * Returns the maximum rights a user has for the given ID or its namespace
668 * @author Andreas Gohr <andi@splitbrain.org>
670 * @triggers AUTH_ACL_CHECK
671 * @param string $id page ID (needs to be resolved and cleaned)
672 * @param string $user Username
673 * @param array|null $groups Array of groups the user is in
674 * @return int permission level
676 function auth_aclcheck($id, $user, $groups)
678 $data = [
679 'id' => $id ?? '',
680 'user' => $user,
681 'groups' => $groups
684 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
688 * default ACL check method
690 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
692 * @author Andreas Gohr <andi@splitbrain.org>
694 * @param array $data event data
695 * @return int permission level
697 function auth_aclcheck_cb($data)
699 $id =& $data['id'];
700 $user =& $data['user'];
701 $groups =& $data['groups'];
703 global $conf;
704 global $AUTH_ACL;
705 /* @var AuthPlugin $auth */
706 global $auth;
708 // if no ACL is used always return upload rights
709 if (!$conf['useacl']) return AUTH_UPLOAD;
710 if (!$auth instanceof AuthPlugin) return AUTH_NONE;
711 if (!is_array($AUTH_ACL)) return AUTH_NONE;
713 //make sure groups is an array
714 if (!is_array($groups)) $groups = [];
716 //if user is superuser or in superusergroup return 255 (acl_admin)
717 if (auth_isadmin($user, $groups)) {
718 return AUTH_ADMIN;
721 if (!$auth->isCaseSensitive()) {
722 $user = PhpString::strtolower($user);
723 $groups = array_map([PhpString::class, 'strtolower'], $groups);
725 $user = auth_nameencode($auth->cleanUser($user));
726 $groups = array_map([$auth, 'cleanGroup'], $groups);
728 //prepend groups with @ and nameencode
729 foreach ($groups as &$group) {
730 $group = '@' . auth_nameencode($group);
733 $ns = getNS($id);
734 $perm = -1;
736 //add ALL group
737 $groups[] = '@ALL';
739 //add User
740 if ($user) $groups[] = $user;
742 //check exact match first
743 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
744 if (count($matches)) {
745 foreach ($matches as $match) {
746 $match = preg_replace('/#.*$/', '', $match); //ignore comments
747 $acl = preg_split('/[ \t]+/', $match);
748 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
749 $acl[1] = PhpString::strtolower($acl[1]);
751 if (!in_array($acl[1], $groups)) {
752 continue;
754 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
755 if ($acl[2] > $perm) {
756 $perm = $acl[2];
759 if ($perm > -1) {
760 //we had a match - return it
761 return (int) $perm;
765 //still here? do the namespace checks
766 if ($ns) {
767 $path = $ns . ':*';
768 } else {
769 $path = '*'; //root document
772 do {
773 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
774 if (count($matches)) {
775 foreach ($matches as $match) {
776 $match = preg_replace('/#.*$/', '', $match); //ignore comments
777 $acl = preg_split('/[ \t]+/', $match);
778 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
779 $acl[1] = PhpString::strtolower($acl[1]);
781 if (!in_array($acl[1], $groups)) {
782 continue;
784 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
785 if ($acl[2] > $perm) {
786 $perm = $acl[2];
789 //we had a match - return it
790 if ($perm != -1) {
791 return (int) $perm;
794 //get next higher namespace
795 $ns = getNS($ns);
797 if ($path != '*') {
798 $path = $ns . ':*';
799 if ($path == ':*') $path = '*';
800 } else {
801 //we did this already
802 //looks like there is something wrong with the ACL
803 //break here
804 msg('No ACL setup yet! Denying access to everyone.');
805 return AUTH_NONE;
807 } while (1); //this should never loop endless
808 return AUTH_NONE;
812 * Encode ASCII special chars
814 * Some auth backends allow special chars in their user and groupnames
815 * The special chars are encoded with this function. Only ASCII chars
816 * are encoded UTF-8 multibyte are left as is (different from usual
817 * urlencoding!).
819 * Decoding can be done with rawurldecode
821 * @author Andreas Gohr <gohr@cosmocode.de>
822 * @see rawurldecode()
824 * @param string $name
825 * @param bool $skip_group
826 * @return string
828 function auth_nameencode($name, $skip_group = false)
830 global $cache_authname;
831 $cache =& $cache_authname;
832 $name = (string) $name;
834 // never encode wildcard FS#1955
835 if ($name == '%USER%') return $name;
836 if ($name == '%GROUP%') return $name;
838 if (!isset($cache[$name][$skip_group])) {
839 if ($skip_group && $name[0] == '@') {
840 $cache[$name][$skip_group] = '@' . preg_replace_callback(
841 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
842 'auth_nameencode_callback',
843 substr($name, 1)
845 } else {
846 $cache[$name][$skip_group] = preg_replace_callback(
847 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
848 'auth_nameencode_callback',
849 $name
854 return $cache[$name][$skip_group];
858 * callback encodes the matches
860 * @param array $matches first complete match, next matching subpatterms
861 * @return string
863 function auth_nameencode_callback($matches)
865 return '%' . dechex(ord(substr($matches[1], -1)));
869 * Create a pronouncable password
871 * The $foruser variable might be used by plugins to run additional password
872 * policy checks, but is not used by the default implementation
874 * @param string $foruser username for which the password is generated
875 * @return string pronouncable password
876 * @throws Exception
878 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
879 * @triggers AUTH_PASSWORD_GENERATE
881 * @author Andreas Gohr <andi@splitbrain.org>
883 function auth_pwgen($foruser = '')
885 $data = [
886 'password' => '',
887 'foruser' => $foruser
890 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
891 if ($evt->advise_before(true)) {
892 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
893 $v = 'aeiou'; //vowels
894 $a = $c . $v; //both
895 $s = '!$%&?+*~#-_:.;,'; // specials
897 //use thre syllables...
898 for ($i = 0; $i < 3; $i++) {
899 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
900 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
901 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
903 //... and add a nice number and special
904 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
906 $evt->advise_after();
908 return $data['password'];
912 * Sends a password to the given user
914 * @author Andreas Gohr <andi@splitbrain.org>
916 * @param string $user Login name of the user
917 * @param string $password The new password in clear text
918 * @return bool true on success
920 function auth_sendPassword($user, $password)
922 global $lang;
923 /* @var AuthPlugin $auth */
924 global $auth;
925 if (!$auth instanceof AuthPlugin) return false;
927 $user = $auth->cleanUser($user);
928 $userinfo = $auth->getUserData($user, false);
930 if (!$userinfo['mail']) return false;
932 $text = rawLocale('password');
933 $trep = [
934 'FULLNAME' => $userinfo['name'],
935 'LOGIN' => $user,
936 'PASSWORD' => $password
939 $mail = new Mailer();
940 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
941 $mail->subject($lang['regpwmail']);
942 $mail->setBody($text, $trep);
943 return $mail->send();
947 * Register a new user
949 * This registers a new user - Data is read directly from $_POST
951 * @return bool true on success, false on any error
952 * @throws Exception
954 * @author Andreas Gohr <andi@splitbrain.org>
956 function register()
958 global $lang;
959 global $conf;
960 /* @var AuthPlugin $auth */
961 global $auth;
962 global $INPUT;
964 if (!$INPUT->post->bool('save')) return false;
965 if (!actionOK('register')) return false;
967 // gather input
968 $login = trim($auth->cleanUser($INPUT->post->str('login')));
969 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
970 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
971 $pass = $INPUT->post->str('pass');
972 $passchk = $INPUT->post->str('passchk');
974 if (empty($login) || empty($fullname) || empty($email)) {
975 msg($lang['regmissing'], -1);
976 return false;
979 if ($conf['autopasswd']) {
980 $pass = auth_pwgen($login); // automatically generate password
981 } elseif (empty($pass) || empty($passchk)) {
982 msg($lang['regmissing'], -1); // complain about missing passwords
983 return false;
984 } elseif ($pass != $passchk) {
985 msg($lang['regbadpass'], -1); // complain about misspelled passwords
986 return false;
989 //check mail
990 if (!mail_isvalid($email)) {
991 msg($lang['regbadmail'], -1);
992 return false;
995 //okay try to create the user
996 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
997 msg($lang['regfail'], -1);
998 return false;
1001 // send notification about the new user
1002 $subscription = new RegistrationSubscriptionSender();
1003 $subscription->sendRegister($login, $fullname, $email);
1005 // are we done?
1006 if (!$conf['autopasswd']) {
1007 msg($lang['regsuccess2'], 1);
1008 return true;
1011 // autogenerated password? then send password to user
1012 if (auth_sendPassword($login, $pass)) {
1013 msg($lang['regsuccess'], 1);
1014 return true;
1015 } else {
1016 msg($lang['regmailfail'], -1);
1017 return false;
1022 * Update user profile
1024 * @throws Exception
1026 * @author Christopher Smith <chris@jalakai.co.uk>
1028 function updateprofile()
1030 global $conf;
1031 global $lang;
1032 /* @var AuthPlugin $auth */
1033 global $auth;
1034 /* @var Input $INPUT */
1035 global $INPUT;
1037 if (!$INPUT->post->bool('save')) return false;
1038 if (!checkSecurityToken()) return false;
1040 if (!actionOK('profile')) {
1041 msg($lang['profna'], -1);
1042 return false;
1045 $changes = [];
1046 $changes['pass'] = $INPUT->post->str('newpass');
1047 $changes['name'] = $INPUT->post->str('fullname');
1048 $changes['mail'] = $INPUT->post->str('email');
1050 // check misspelled passwords
1051 if ($changes['pass'] != $INPUT->post->str('passchk')) {
1052 msg($lang['regbadpass'], -1);
1053 return false;
1056 // clean fullname and email
1057 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1058 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1060 // no empty name and email (except the backend doesn't support them)
1061 if (
1062 (empty($changes['name']) && $auth->canDo('modName')) ||
1063 (empty($changes['mail']) && $auth->canDo('modMail'))
1065 msg($lang['profnoempty'], -1);
1066 return false;
1068 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1069 msg($lang['regbadmail'], -1);
1070 return false;
1073 $changes = array_filter($changes);
1075 // check for unavailable capabilities
1076 if (!$auth->canDo('modName')) unset($changes['name']);
1077 if (!$auth->canDo('modMail')) unset($changes['mail']);
1078 if (!$auth->canDo('modPass')) unset($changes['pass']);
1080 // anything to do?
1081 if ($changes === []) {
1082 msg($lang['profnochange'], -1);
1083 return false;
1086 if ($conf['profileconfirm']) {
1087 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1088 msg($lang['badpassconfirm'], -1);
1089 return false;
1093 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1094 msg($lang['proffail'], -1);
1095 return false;
1098 if ($changes['pass']) {
1099 // update cookie and session with the changed data
1100 [/* user */, $sticky, /* pass */] = auth_getCookie();
1101 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1102 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1103 } else {
1104 // make sure the session is writable
1105 @session_start();
1106 // invalidate session cache
1107 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1108 session_write_close();
1111 return true;
1115 * Delete the current logged-in user
1117 * @return bool true on success, false on any error
1119 function auth_deleteprofile()
1121 global $conf;
1122 global $lang;
1123 /* @var AuthPlugin $auth */
1124 global $auth;
1125 /* @var Input $INPUT */
1126 global $INPUT;
1128 if (!$INPUT->post->bool('delete')) return false;
1129 if (!checkSecurityToken()) return false;
1131 // action prevented or auth module disallows
1132 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1133 msg($lang['profnodelete'], -1);
1134 return false;
1137 if (!$INPUT->post->bool('confirm_delete')) {
1138 msg($lang['profconfdeletemissing'], -1);
1139 return false;
1142 if ($conf['profileconfirm']) {
1143 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1144 msg($lang['badpassconfirm'], -1);
1145 return false;
1149 $deleted = [];
1150 $deleted[] = $INPUT->server->str('REMOTE_USER');
1151 if ($auth->triggerUserMod('delete', [$deleted])) {
1152 // force and immediate logout including removing the sticky cookie
1153 auth_logoff();
1154 return true;
1157 return false;
1161 * Send a new password
1163 * This function handles both phases of the password reset:
1165 * - handling the first request of password reset
1166 * - validating the password reset auth token
1168 * @return bool true on success, false on any error
1169 * @throws Exception
1171 * @author Andreas Gohr <andi@splitbrain.org>
1172 * @author Benoit Chesneau <benoit@bchesneau.info>
1173 * @author Chris Smith <chris@jalakai.co.uk>
1175 function act_resendpwd()
1177 global $lang;
1178 global $conf;
1179 /* @var AuthPlugin $auth */
1180 global $auth;
1181 /* @var Input $INPUT */
1182 global $INPUT;
1184 if (!actionOK('resendpwd')) {
1185 msg($lang['resendna'], -1);
1186 return false;
1189 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1191 if ($token) {
1192 // we're in token phase - get user info from token
1194 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1195 if (!file_exists($tfile)) {
1196 msg($lang['resendpwdbadauth'], -1);
1197 $INPUT->remove('pwauth');
1198 return false;
1200 // token is only valid for 3 days
1201 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1202 msg($lang['resendpwdbadauth'], -1);
1203 $INPUT->remove('pwauth');
1204 @unlink($tfile);
1205 return false;
1208 $user = io_readfile($tfile);
1209 $userinfo = $auth->getUserData($user, false);
1210 if (!$userinfo['mail']) {
1211 msg($lang['resendpwdnouser'], -1);
1212 return false;
1215 if (!$conf['autopasswd']) { // we let the user choose a password
1216 $pass = $INPUT->str('pass');
1218 // password given correctly?
1219 if (!$pass) return false;
1220 if ($pass != $INPUT->str('passchk')) {
1221 msg($lang['regbadpass'], -1);
1222 return false;
1225 // change it
1226 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1227 msg($lang['proffail'], -1);
1228 return false;
1230 } else { // autogenerate the password and send by mail
1231 $pass = auth_pwgen($user);
1232 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1233 msg($lang['proffail'], -1);
1234 return false;
1237 if (auth_sendPassword($user, $pass)) {
1238 msg($lang['resendpwdsuccess'], 1);
1239 } else {
1240 msg($lang['regmailfail'], -1);
1244 @unlink($tfile);
1245 return true;
1246 } else {
1247 // we're in request phase
1249 if (!$INPUT->post->bool('save')) return false;
1251 if (!$INPUT->post->str('login')) {
1252 msg($lang['resendpwdmissing'], -1);
1253 return false;
1254 } else {
1255 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1258 $userinfo = $auth->getUserData($user, false);
1259 if (!$userinfo['mail']) {
1260 msg($lang['resendpwdnouser'], -1);
1261 return false;
1264 // generate auth token
1265 $token = md5(auth_randombytes(16)); // random secret
1266 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1267 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1269 io_saveFile($tfile, $user);
1271 $text = rawLocale('pwconfirm');
1272 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
1274 $mail = new Mailer();
1275 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1276 $mail->subject($lang['regpwmail']);
1277 $mail->setBody($text, $trep);
1278 if ($mail->send()) {
1279 msg($lang['resendpwdconfirm'], 1);
1280 } else {
1281 msg($lang['regmailfail'], -1);
1283 return true;
1285 // never reached
1289 * Encrypts a password using the given method and salt
1291 * If the selected method needs a salt and none was given, a random one
1292 * is chosen.
1294 * @author Andreas Gohr <andi@splitbrain.org>
1296 * @param string $clear The clear text password
1297 * @param string $method The hashing method
1298 * @param string $salt A salt, null for random
1299 * @return string The crypted password
1301 function auth_cryptPassword($clear, $method = '', $salt = null)
1303 global $conf;
1304 if (empty($method)) $method = $conf['passcrypt'];
1306 $pass = new PassHash();
1307 $call = 'hash_' . $method;
1309 if (!method_exists($pass, $call)) {
1310 msg("Unsupported crypt method $method", -1);
1311 return false;
1314 return $pass->$call($clear, $salt);
1318 * Verifies a cleartext password against a crypted hash
1320 * @param string $clear The clear text password
1321 * @param string $crypt The hash to compare with
1322 * @return bool true if both match
1323 * @throws Exception
1325 * @author Andreas Gohr <andi@splitbrain.org>
1327 function auth_verifyPassword($clear, $crypt)
1329 $pass = new PassHash();
1330 return $pass->verify_hash($clear, $crypt);
1334 * Set the authentication cookie and add user identification data to the session
1336 * @param string $user username
1337 * @param string $pass encrypted password
1338 * @param bool $sticky whether or not the cookie will last beyond the session
1339 * @return bool
1341 function auth_setCookie($user, $pass, $sticky)
1343 global $conf;
1344 /* @var AuthPlugin $auth */
1345 global $auth;
1346 global $USERINFO;
1348 if (!$auth instanceof AuthPlugin) return false;
1349 $USERINFO = $auth->getUserData($user);
1351 // set cookie
1352 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1353 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1354 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1355 setcookie(DOKU_COOKIE, $cookie, [
1356 'expires' => $time,
1357 'path' => $cookieDir,
1358 'secure' => ($conf['securecookie'] && is_ssl()),
1359 'httponly' => true,
1360 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1363 // set session
1364 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1365 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1366 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1367 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1368 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1370 return true;
1374 * Returns the user, (encrypted) password and sticky bit from cookie
1376 * @returns array
1378 function auth_getCookie()
1380 if (!isset($_COOKIE[DOKU_COOKIE])) {
1381 return [null, null, null];
1383 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1384 $sticky = (bool) $sticky;
1385 $pass = base64_decode($pass);
1386 $user = base64_decode($user);
1387 return [$user, $sticky, $pass];
1390 //Setup VIM: ex: et ts=2 :