code style: static visibility
[dokuwiki.git] / inc / auth.php
blob08a0467d879af23f7191e502a8fd6d0c32a04d8d
1 <?php
2 /**
3 * Authentication library
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author Andreas Gohr <andi@splitbrain.org>
11 use phpseclib\Crypt\AES;
12 use dokuwiki\Utf8\PhpString;
13 use dokuwiki\Extension\AuthPlugin;
14 use dokuwiki\Extension\Event;
15 use dokuwiki\Extension\PluginController;
16 use dokuwiki\PassHash;
17 use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
19 /**
20 * Initialize the auth system.
22 * This function is automatically called at the end of init.php
24 * This used to be the main() of the auth.php
26 * @todo backend loading maybe should be handled by the class autoloader
27 * @todo maybe split into multiple functions at the XXX marked positions
28 * @triggers AUTH_LOGIN_CHECK
29 * @return bool
31 function auth_setup()
33 global $conf;
34 /* @var AuthPlugin $auth */
35 global $auth;
36 /* @var Input $INPUT */
37 global $INPUT;
38 global $AUTH_ACL;
39 global $lang;
40 /* @var PluginController $plugin_controller */
41 global $plugin_controller;
42 $AUTH_ACL = [];
44 if (!$conf['useacl']) return false;
46 // try to load auth backend from plugins
47 foreach ($plugin_controller->getList('auth') as $plugin) {
48 if ($conf['authtype'] === $plugin) {
49 $auth = $plugin_controller->load('auth', $plugin);
50 break;
54 if (!isset($auth) || !$auth) {
55 msg($lang['authtempfail'], -1);
56 return false;
59 if ($auth->success == false) {
60 // degrade to unauthenticated user
61 $auth = null;
62 auth_logoff();
63 msg($lang['authtempfail'], -1);
64 return false;
67 // do the login either by cookie or provided credentials XXX
68 $INPUT->set('http_credentials', false);
69 if (!$conf['rememberme']) $INPUT->set('r', false);
71 // Populate Basic Auth user/password from Authorization header
72 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
73 $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
74 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
75 $userpass = explode(':', base64_decode($matches[1]));
76 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
79 // if no credentials were given try to use HTTP auth (for SSO)
80 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
81 $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
82 $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
83 $INPUT->set('http_credentials', true);
86 // apply cleaning (auth specific user names, remove control chars)
87 if (true === $auth->success) {
88 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
89 $INPUT->set('p', stripctl($INPUT->str('p')));
92 $ok = null;
93 if (!is_null($auth) && $auth->canDo('external')) {
94 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
97 if ($ok === null) {
98 // external trust mechanism not in place, or returns no result,
99 // then attempt auth_login
100 $evdata = [
101 'user' => $INPUT->str('u'),
102 'password' => $INPUT->str('p'),
103 'sticky' => $INPUT->bool('r'),
104 'silent' => $INPUT->bool('http_credentials')
106 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
109 //load ACL into a global array XXX
110 $AUTH_ACL = auth_loadACL();
112 return true;
116 * Loads the ACL setup and handle user wildcards
118 * @author Andreas Gohr <andi@splitbrain.org>
120 * @return array
122 function auth_loadACL()
124 global $config_cascade;
125 global $USERINFO;
126 /* @var Input $INPUT */
127 global $INPUT;
129 if (!is_readable($config_cascade['acl']['default'])) return [];
131 $acl = file($config_cascade['acl']['default']);
133 $out = [];
134 foreach ($acl as $line) {
135 $line = trim($line);
136 if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
137 [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
139 // substitute user wildcard first (its 1:1)
140 if (strstr($line, '%USER%')) {
141 // if user is not logged in, this ACL line is meaningless - skip it
142 if (!$INPUT->server->has('REMOTE_USER')) continue;
144 $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
145 $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
148 // substitute group wildcard (its 1:m)
149 if (strstr($line, '%GROUP%')) {
150 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
151 if (isset($USERINFO['grps'])) {
152 foreach ((array) $USERINFO['grps'] as $grp) {
153 $nid = str_replace('%GROUP%', cleanID($grp), $id);
154 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
155 $out[] = "$nid\t$nrest";
158 } else {
159 $out[] = "$id\t$rest";
163 return $out;
167 * Event hook callback for AUTH_LOGIN_CHECK
169 * @param array $evdata
170 * @return bool
172 function auth_login_wrapper($evdata)
174 return auth_login(
175 $evdata['user'],
176 $evdata['password'],
177 $evdata['sticky'],
178 $evdata['silent']
183 * This tries to login the user based on the sent auth credentials
185 * The authentication works like this: if a username was given
186 * a new login is assumed and user/password are checked. If they
187 * are correct the password is encrypted with blowfish and stored
188 * together with the username in a cookie - the same info is stored
189 * in the session, too. Additonally a browserID is stored in the
190 * session.
192 * If no username was given the cookie is checked: if the username,
193 * crypted password and browserID match between session and cookie
194 * no further testing is done and the user is accepted
196 * If a cookie was found but no session info was availabe the
197 * blowfish encrypted password from the cookie is decrypted and
198 * together with username rechecked by calling this function again.
200 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
201 * are set.
203 * @author Andreas Gohr <andi@splitbrain.org>
205 * @param string $user Username
206 * @param string $pass Cleartext Password
207 * @param bool $sticky Cookie should not expire
208 * @param bool $silent Don't show error on bad auth
209 * @return bool true on successful auth
211 function auth_login($user, $pass, $sticky = false, $silent = false)
213 global $USERINFO;
214 global $conf;
215 global $lang;
216 /* @var AuthPlugin $auth */
217 global $auth;
218 /* @var Input $INPUT */
219 global $INPUT;
221 if (!$auth) return false;
223 if (!empty($user)) {
224 //usual login
225 if (!empty($pass) && $auth->checkPass($user, $pass)) {
226 // make logininfo globally available
227 $INPUT->server->set('REMOTE_USER', $user);
228 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
229 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
230 return true;
231 } else {
232 //invalid credentials - log off
233 if (!$silent) {
234 http_status(403, 'Login failed');
235 msg($lang['badlogin'], -1);
237 auth_logoff();
238 return false;
240 } else {
241 // read cookie information
242 [$user, $sticky, $pass] = auth_getCookie();
243 if ($user && $pass) {
244 // we got a cookie - see if we can trust it
246 // get session info
247 if (isset($_SESSION[DOKU_COOKIE])) {
248 $session = $_SESSION[DOKU_COOKIE]['auth'];
249 if (
250 isset($session) &&
251 $auth->useSessionCache($user) &&
252 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
253 ($session['user'] == $user) &&
254 ($session['pass'] == sha1($pass)) && //still crypted
255 ($session['buid'] == auth_browseruid())
257 // he has session, cookie and browser right - let him in
258 $INPUT->server->set('REMOTE_USER', $user);
259 $USERINFO = $session['info']; //FIXME move all references to session
260 return true;
263 // no we don't trust it yet - recheck pass but silent
264 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
265 $pass = auth_decrypt($pass, $secret);
266 return auth_login($user, $pass, $sticky, true);
269 //just to be sure
270 auth_logoff(true);
271 return false;
275 * Builds a pseudo UID from browser and IP data
277 * This is neither unique nor unfakable - still it adds some
278 * security. Using the first part of the IP makes sure
279 * proxy farms like AOLs are still okay.
281 * @author Andreas Gohr <andi@splitbrain.org>
283 * @return string a SHA256 sum of various browser headers
285 function auth_browseruid()
287 /* @var Input $INPUT */
288 global $INPUT;
290 $ip = clientIP(true);
291 // convert IP string to packed binary representation
292 $pip = inet_pton($ip);
294 $uid = implode("\n", [
295 $INPUT->server->str('HTTP_USER_AGENT'),
296 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
297 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
299 return hash('sha256', $uid);
303 * Creates a random key to encrypt the password in cookies
305 * This function tries to read the password for encrypting
306 * cookies from $conf['metadir'].'/_htcookiesalt'
307 * if no such file is found a random key is created and
308 * and stored in this file.
310 * @author Andreas Gohr <andi@splitbrain.org>
312 * @param bool $addsession if true, the sessionid is added to the salt
313 * @param bool $secure if security is more important than keeping the old value
314 * @return string
316 function auth_cookiesalt($addsession = false, $secure = false)
318 if (defined('SIMPLE_TEST')) {
319 return 'test';
321 global $conf;
322 $file = $conf['metadir'] . '/_htcookiesalt';
323 if ($secure || !file_exists($file)) {
324 $file = $conf['metadir'] . '/_htcookiesalt2';
326 $salt = io_readFile($file);
327 if (empty($salt)) {
328 $salt = bin2hex(auth_randombytes(64));
329 io_saveFile($file, $salt);
331 if ($addsession) {
332 $salt .= session_id();
334 return $salt;
338 * Return cryptographically secure random bytes.
340 * @author Niklas Keller <me@kelunik.com>
342 * @param int $length number of bytes
343 * @return string cryptographically secure random bytes
345 function auth_randombytes($length)
347 return random_bytes($length);
351 * Cryptographically secure random number generator.
353 * @author Niklas Keller <me@kelunik.com>
355 * @param int $min
356 * @param int $max
357 * @return int
359 function auth_random($min, $max)
361 return random_int($min, $max);
365 * Encrypt data using the given secret using AES
367 * The mode is CBC with a random initialization vector, the key is derived
368 * using pbkdf2.
370 * @param string $data The data that shall be encrypted
371 * @param string $secret The secret/password that shall be used
372 * @return string The ciphertext
374 function auth_encrypt($data, $secret)
376 $iv = auth_randombytes(16);
377 $cipher = new AES();
378 $cipher->setPassword($secret);
381 this uses the encrypted IV as IV as suggested in
382 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
383 for unique but necessarily random IVs. The resulting ciphertext is
384 compatible to ciphertext that was created using a "normal" IV.
386 return $cipher->encrypt($iv . $data);
390 * Decrypt the given AES ciphertext
392 * The mode is CBC, the key is derived using pbkdf2
394 * @param string $ciphertext The encrypted data
395 * @param string $secret The secret/password that shall be used
396 * @return string The decrypted data
398 function auth_decrypt($ciphertext, $secret)
400 $iv = substr($ciphertext, 0, 16);
401 $cipher = new AES();
402 $cipher->setPassword($secret);
403 $cipher->setIV($iv);
405 return $cipher->decrypt(substr($ciphertext, 16));
409 * Log out the current user
411 * This clears all authentication data and thus log the user
412 * off. It also clears session data.
414 * @author Andreas Gohr <andi@splitbrain.org>
416 * @param bool $keepbc - when true, the breadcrumb data is not cleared
418 function auth_logoff($keepbc = false)
420 global $conf;
421 global $USERINFO;
422 /* @var AuthPlugin $auth */
423 global $auth;
424 /* @var Input $INPUT */
425 global $INPUT;
427 // make sure the session is writable (it usually is)
428 @session_start();
430 if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
431 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
432 if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
433 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
434 if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
435 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
436 if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
437 unset($_SESSION[DOKU_COOKIE]['bc']);
438 $INPUT->server->remove('REMOTE_USER');
439 $USERINFO = null; //FIXME
441 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
442 setcookie(DOKU_COOKIE, '', [
443 'expires' => time() - 600000,
444 'path' => $cookieDir,
445 'secure' => ($conf['securecookie'] && is_ssl()),
446 'httponly' => true,
447 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
450 if ($auth) $auth->logOff();
454 * Check if a user is a manager
456 * Should usually be called without any parameters to check the current
457 * user.
459 * The info is available through $INFO['ismanager'], too
461 * @param string $user Username
462 * @param array $groups List of groups the user is in
463 * @param bool $adminonly when true checks if user is admin
464 * @param bool $recache set to true to refresh the cache
465 * @return bool
466 * @see auth_isadmin
468 * @author Andreas Gohr <andi@splitbrain.org>
470 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
472 global $conf;
473 global $USERINFO;
474 /* @var AuthPlugin $auth */
475 global $auth;
476 /* @var Input $INPUT */
477 global $INPUT;
480 if (!$auth) return false;
481 if (is_null($user)) {
482 if (!$INPUT->server->has('REMOTE_USER')) {
483 return false;
484 } else {
485 $user = $INPUT->server->str('REMOTE_USER');
488 if (is_null($groups)) {
489 // checking the logged in user, or another one?
490 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
491 $groups = (array) $USERINFO['grps'];
492 } else {
493 $groups = $auth->getUserData($user);
494 $groups = $groups ? $groups['grps'] : [];
498 // prefer cached result
499 static $cache = [];
500 $cachekey = serialize([$user, $adminonly, $groups]);
501 if (!isset($cache[$cachekey]) || $recache) {
502 // check superuser match
503 $ok = auth_isMember($conf['superuser'], $user, $groups);
505 // check managers
506 if (!$ok && !$adminonly) {
507 $ok = auth_isMember($conf['manager'], $user, $groups);
510 $cache[$cachekey] = $ok;
513 return $cache[$cachekey];
517 * Check if a user is admin
519 * Alias to auth_ismanager with adminonly=true
521 * The info is available through $INFO['isadmin'], too
523 * @param string $user Username
524 * @param array $groups List of groups the user is in
525 * @param bool $recache set to true to refresh the cache
526 * @return bool
527 * @author Andreas Gohr <andi@splitbrain.org>
528 * @see auth_ismanager()
531 function auth_isadmin($user = null, $groups = null, $recache = false)
533 return auth_ismanager($user, $groups, true, $recache);
537 * Match a user and his groups against a comma separated list of
538 * users and groups to determine membership status
540 * Note: all input should NOT be nameencoded.
542 * @param string $memberlist commaseparated list of allowed users and groups
543 * @param string $user user to match against
544 * @param array $groups groups the user is member of
545 * @return bool true for membership acknowledged
547 function auth_isMember($memberlist, $user, array $groups)
549 /* @var AuthPlugin $auth */
550 global $auth;
551 if (!$auth) return false;
553 // clean user and groups
554 if (!$auth->isCaseSensitive()) {
555 $user = PhpString::strtolower($user);
556 $groups = array_map([PhpString::class, 'strtolower'], $groups);
558 $user = $auth->cleanUser($user);
559 $groups = array_map([$auth, 'cleanGroup'], $groups);
561 // extract the memberlist
562 $members = explode(',', $memberlist);
563 $members = array_map('trim', $members);
564 $members = array_unique($members);
565 $members = array_filter($members);
567 // compare cleaned values
568 foreach ($members as $member) {
569 if ($member == '@ALL') return true;
570 if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
571 if ($member[0] == '@') {
572 $member = $auth->cleanGroup(substr($member, 1));
573 if (in_array($member, $groups)) return true;
574 } else {
575 $member = $auth->cleanUser($member);
576 if ($member == $user) return true;
580 // still here? not a member!
581 return false;
585 * Convinience function for auth_aclcheck()
587 * This checks the permissions for the current user
589 * @author Andreas Gohr <andi@splitbrain.org>
591 * @param string $id page ID (needs to be resolved and cleaned)
592 * @return int permission level
594 function auth_quickaclcheck($id)
596 global $conf;
597 global $USERINFO;
598 /* @var Input $INPUT */
599 global $INPUT;
600 # if no ACL is used always return upload rights
601 if (!$conf['useacl']) return AUTH_UPLOAD;
602 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
606 * Returns the maximum rights a user has for the given ID or its namespace
608 * @author Andreas Gohr <andi@splitbrain.org>
610 * @triggers AUTH_ACL_CHECK
611 * @param string $id page ID (needs to be resolved and cleaned)
612 * @param string $user Username
613 * @param array|null $groups Array of groups the user is in
614 * @return int permission level
616 function auth_aclcheck($id, $user, $groups)
618 $data = [
619 'id' => $id ?? '',
620 'user' => $user,
621 'groups' => $groups
624 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
628 * default ACL check method
630 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
632 * @author Andreas Gohr <andi@splitbrain.org>
634 * @param array $data event data
635 * @return int permission level
637 function auth_aclcheck_cb($data)
639 $id =& $data['id'];
640 $user =& $data['user'];
641 $groups =& $data['groups'];
643 global $conf;
644 global $AUTH_ACL;
645 /* @var AuthPlugin $auth */
646 global $auth;
648 // if no ACL is used always return upload rights
649 if (!$conf['useacl']) return AUTH_UPLOAD;
650 if (!$auth) return AUTH_NONE;
651 if (!is_array($AUTH_ACL)) return AUTH_NONE;
653 //make sure groups is an array
654 if (!is_array($groups)) $groups = [];
656 //if user is superuser or in superusergroup return 255 (acl_admin)
657 if (auth_isadmin($user, $groups)) {
658 return AUTH_ADMIN;
661 if (!$auth->isCaseSensitive()) {
662 $user = PhpString::strtolower($user);
663 $groups = array_map([PhpString::class, 'strtolower'], $groups);
665 $user = auth_nameencode($auth->cleanUser($user));
666 $groups = array_map([$auth, 'cleanGroup'], $groups);
668 //prepend groups with @ and nameencode
669 foreach ($groups as &$group) {
670 $group = '@' . auth_nameencode($group);
673 $ns = getNS($id);
674 $perm = -1;
676 //add ALL group
677 $groups[] = '@ALL';
679 //add User
680 if ($user) $groups[] = $user;
682 //check exact match first
683 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
684 if (count($matches)) {
685 foreach ($matches as $match) {
686 $match = preg_replace('/#.*$/', '', $match); //ignore comments
687 $acl = preg_split('/[ \t]+/', $match);
688 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
689 $acl[1] = PhpString::strtolower($acl[1]);
691 if (!in_array($acl[1], $groups)) {
692 continue;
694 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
695 if ($acl[2] > $perm) {
696 $perm = $acl[2];
699 if ($perm > -1) {
700 //we had a match - return it
701 return (int) $perm;
705 //still here? do the namespace checks
706 if ($ns) {
707 $path = $ns . ':*';
708 } else {
709 $path = '*'; //root document
712 do {
713 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
714 if (count($matches)) {
715 foreach ($matches as $match) {
716 $match = preg_replace('/#.*$/', '', $match); //ignore comments
717 $acl = preg_split('/[ \t]+/', $match);
718 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
719 $acl[1] = PhpString::strtolower($acl[1]);
721 if (!in_array($acl[1], $groups)) {
722 continue;
724 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
725 if ($acl[2] > $perm) {
726 $perm = $acl[2];
729 //we had a match - return it
730 if ($perm != -1) {
731 return (int) $perm;
734 //get next higher namespace
735 $ns = getNS($ns);
737 if ($path != '*') {
738 $path = $ns . ':*';
739 if ($path == ':*') $path = '*';
740 } else {
741 //we did this already
742 //looks like there is something wrong with the ACL
743 //break here
744 msg('No ACL setup yet! Denying access to everyone.');
745 return AUTH_NONE;
747 } while (1); //this should never loop endless
748 return AUTH_NONE;
752 * Encode ASCII special chars
754 * Some auth backends allow special chars in their user and groupnames
755 * The special chars are encoded with this function. Only ASCII chars
756 * are encoded UTF-8 multibyte are left as is (different from usual
757 * urlencoding!).
759 * Decoding can be done with rawurldecode
761 * @author Andreas Gohr <gohr@cosmocode.de>
762 * @see rawurldecode()
764 * @param string $name
765 * @param bool $skip_group
766 * @return string
768 function auth_nameencode($name, $skip_group = false)
770 global $cache_authname;
771 $cache =& $cache_authname;
772 $name = (string) $name;
774 // never encode wildcard FS#1955
775 if ($name == '%USER%') return $name;
776 if ($name == '%GROUP%') return $name;
778 if (!isset($cache[$name][$skip_group])) {
779 if ($skip_group && $name[0] == '@') {
780 $cache[$name][$skip_group] = '@' . preg_replace_callback(
781 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
782 'auth_nameencode_callback',
783 substr($name, 1)
785 } else {
786 $cache[$name][$skip_group] = preg_replace_callback(
787 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
788 'auth_nameencode_callback',
789 $name
794 return $cache[$name][$skip_group];
798 * callback encodes the matches
800 * @param array $matches first complete match, next matching subpatterms
801 * @return string
803 function auth_nameencode_callback($matches)
805 return '%' . dechex(ord(substr($matches[1], -1)));
809 * Create a pronouncable password
811 * The $foruser variable might be used by plugins to run additional password
812 * policy checks, but is not used by the default implementation
814 * @author Andreas Gohr <andi@splitbrain.org>
815 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
816 * @triggers AUTH_PASSWORD_GENERATE
818 * @param string $foruser username for which the password is generated
819 * @return string pronouncable password
821 function auth_pwgen($foruser = '')
823 $data = [
824 'password' => '',
825 'foruser' => $foruser
828 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
829 if ($evt->advise_before(true)) {
830 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
831 $v = 'aeiou'; //vowels
832 $a = $c . $v; //both
833 $s = '!$%&?+*~#-_:.;,'; // specials
835 //use thre syllables...
836 for ($i = 0; $i < 3; $i++) {
837 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
838 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
839 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
841 //... and add a nice number and special
842 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
844 $evt->advise_after();
846 return $data['password'];
850 * Sends a password to the given user
852 * @author Andreas Gohr <andi@splitbrain.org>
854 * @param string $user Login name of the user
855 * @param string $password The new password in clear text
856 * @return bool true on success
858 function auth_sendPassword($user, $password)
860 global $lang;
861 /* @var AuthPlugin $auth */
862 global $auth;
863 if (!$auth) return false;
865 $user = $auth->cleanUser($user);
866 $userinfo = $auth->getUserData($user, $requireGroups = false);
868 if (!$userinfo['mail']) return false;
870 $text = rawLocale('password');
871 $trep = [
872 'FULLNAME' => $userinfo['name'],
873 'LOGIN' => $user,
874 'PASSWORD' => $password
877 $mail = new Mailer();
878 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
879 $mail->subject($lang['regpwmail']);
880 $mail->setBody($text, $trep);
881 return $mail->send();
885 * Register a new user
887 * This registers a new user - Data is read directly from $_POST
889 * @author Andreas Gohr <andi@splitbrain.org>
891 * @return bool true on success, false on any error
893 function register()
895 global $lang;
896 global $conf;
897 /* @var \dokuwiki\Extension\AuthPlugin $auth */
898 global $auth;
899 global $INPUT;
901 if (!$INPUT->post->bool('save')) return false;
902 if (!actionOK('register')) return false;
904 // gather input
905 $login = trim($auth->cleanUser($INPUT->post->str('login')));
906 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
907 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
908 $pass = $INPUT->post->str('pass');
909 $passchk = $INPUT->post->str('passchk');
911 if (empty($login) || empty($fullname) || empty($email)) {
912 msg($lang['regmissing'], -1);
913 return false;
916 if ($conf['autopasswd']) {
917 $pass = auth_pwgen($login); // automatically generate password
918 } elseif (empty($pass) || empty($passchk)) {
919 msg($lang['regmissing'], -1); // complain about missing passwords
920 return false;
921 } elseif ($pass != $passchk) {
922 msg($lang['regbadpass'], -1); // complain about misspelled passwords
923 return false;
926 //check mail
927 if (!mail_isvalid($email)) {
928 msg($lang['regbadmail'], -1);
929 return false;
932 //okay try to create the user
933 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
934 msg($lang['regfail'], -1);
935 return false;
938 // send notification about the new user
939 $subscription = new RegistrationSubscriptionSender();
940 $subscription->sendRegister($login, $fullname, $email);
942 // are we done?
943 if (!$conf['autopasswd']) {
944 msg($lang['regsuccess2'], 1);
945 return true;
948 // autogenerated password? then send password to user
949 if (auth_sendPassword($login, $pass)) {
950 msg($lang['regsuccess'], 1);
951 return true;
952 } else {
953 msg($lang['regmailfail'], -1);
954 return false;
959 * Update user profile
961 * @author Christopher Smith <chris@jalakai.co.uk>
963 function updateprofile()
965 global $conf;
966 global $lang;
967 /* @var AuthPlugin $auth */
968 global $auth;
969 /* @var Input $INPUT */
970 global $INPUT;
972 if (!$INPUT->post->bool('save')) return false;
973 if (!checkSecurityToken()) return false;
975 if (!actionOK('profile')) {
976 msg($lang['profna'], -1);
977 return false;
980 $changes = [];
981 $changes['pass'] = $INPUT->post->str('newpass');
982 $changes['name'] = $INPUT->post->str('fullname');
983 $changes['mail'] = $INPUT->post->str('email');
985 // check misspelled passwords
986 if ($changes['pass'] != $INPUT->post->str('passchk')) {
987 msg($lang['regbadpass'], -1);
988 return false;
991 // clean fullname and email
992 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
993 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
995 // no empty name and email (except the backend doesn't support them)
996 if (
997 (empty($changes['name']) && $auth->canDo('modName')) ||
998 (empty($changes['mail']) && $auth->canDo('modMail'))
1000 msg($lang['profnoempty'], -1);
1001 return false;
1003 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1004 msg($lang['regbadmail'], -1);
1005 return false;
1008 $changes = array_filter($changes);
1010 // check for unavailable capabilities
1011 if (!$auth->canDo('modName')) unset($changes['name']);
1012 if (!$auth->canDo('modMail')) unset($changes['mail']);
1013 if (!$auth->canDo('modPass')) unset($changes['pass']);
1015 // anything to do?
1016 if ($changes === []) {
1017 msg($lang['profnochange'], -1);
1018 return false;
1021 if ($conf['profileconfirm']) {
1022 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1023 msg($lang['badpassconfirm'], -1);
1024 return false;
1028 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1029 msg($lang['proffail'], -1);
1030 return false;
1033 if ($changes['pass']) {
1034 // update cookie and session with the changed data
1035 [/* user */, $sticky, /* pass */] = auth_getCookie();
1036 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1037 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1038 } else {
1039 // make sure the session is writable
1040 @session_start();
1041 // invalidate session cache
1042 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1043 session_write_close();
1046 return true;
1050 * Delete the current logged-in user
1052 * @return bool true on success, false on any error
1054 function auth_deleteprofile()
1056 global $conf;
1057 global $lang;
1058 /* @var \dokuwiki\Extension\AuthPlugin $auth */
1059 global $auth;
1060 /* @var Input $INPUT */
1061 global $INPUT;
1063 if (!$INPUT->post->bool('delete')) return false;
1064 if (!checkSecurityToken()) return false;
1066 // action prevented or auth module disallows
1067 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1068 msg($lang['profnodelete'], -1);
1069 return false;
1072 if (!$INPUT->post->bool('confirm_delete')) {
1073 msg($lang['profconfdeletemissing'], -1);
1074 return false;
1077 if ($conf['profileconfirm']) {
1078 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1079 msg($lang['badpassconfirm'], -1);
1080 return false;
1084 $deleted = [];
1085 $deleted[] = $INPUT->server->str('REMOTE_USER');
1086 if ($auth->triggerUserMod('delete', [$deleted])) {
1087 // force and immediate logout including removing the sticky cookie
1088 auth_logoff();
1089 return true;
1092 return false;
1096 * Send a new password
1098 * This function handles both phases of the password reset:
1100 * - handling the first request of password reset
1101 * - validating the password reset auth token
1103 * @author Benoit Chesneau <benoit@bchesneau.info>
1104 * @author Chris Smith <chris@jalakai.co.uk>
1105 * @author Andreas Gohr <andi@splitbrain.org>
1107 * @return bool true on success, false on any error
1109 function act_resendpwd()
1111 global $lang;
1112 global $conf;
1113 /* @var AuthPlugin $auth */
1114 global $auth;
1115 /* @var Input $INPUT */
1116 global $INPUT;
1118 if (!actionOK('resendpwd')) {
1119 msg($lang['resendna'], -1);
1120 return false;
1123 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1125 if ($token) {
1126 // we're in token phase - get user info from token
1128 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1129 if (!file_exists($tfile)) {
1130 msg($lang['resendpwdbadauth'], -1);
1131 $INPUT->remove('pwauth');
1132 return false;
1134 // token is only valid for 3 days
1135 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1136 msg($lang['resendpwdbadauth'], -1);
1137 $INPUT->remove('pwauth');
1138 @unlink($tfile);
1139 return false;
1142 $user = io_readfile($tfile);
1143 $userinfo = $auth->getUserData($user, $requireGroups = false);
1144 if (!$userinfo['mail']) {
1145 msg($lang['resendpwdnouser'], -1);
1146 return false;
1149 if (!$conf['autopasswd']) { // we let the user choose a password
1150 $pass = $INPUT->str('pass');
1152 // password given correctly?
1153 if (!$pass) return false;
1154 if ($pass != $INPUT->str('passchk')) {
1155 msg($lang['regbadpass'], -1);
1156 return false;
1159 // change it
1160 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1161 msg($lang['proffail'], -1);
1162 return false;
1164 } else { // autogenerate the password and send by mail
1165 $pass = auth_pwgen($user);
1166 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1167 msg($lang['proffail'], -1);
1168 return false;
1171 if (auth_sendPassword($user, $pass)) {
1172 msg($lang['resendpwdsuccess'], 1);
1173 } else {
1174 msg($lang['regmailfail'], -1);
1178 @unlink($tfile);
1179 return true;
1180 } else {
1181 // we're in request phase
1183 if (!$INPUT->post->bool('save')) return false;
1185 if (!$INPUT->post->str('login')) {
1186 msg($lang['resendpwdmissing'], -1);
1187 return false;
1188 } else {
1189 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1192 $userinfo = $auth->getUserData($user, $requireGroups = false);
1193 if (!$userinfo['mail']) {
1194 msg($lang['resendpwdnouser'], -1);
1195 return false;
1198 // generate auth token
1199 $token = md5(auth_randombytes(16)); // random secret
1200 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
1201 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
1203 io_saveFile($tfile, $user);
1205 $text = rawLocale('pwconfirm');
1206 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url];
1208 $mail = new Mailer();
1209 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1210 $mail->subject($lang['regpwmail']);
1211 $mail->setBody($text, $trep);
1212 if ($mail->send()) {
1213 msg($lang['resendpwdconfirm'], 1);
1214 } else {
1215 msg($lang['regmailfail'], -1);
1217 return true;
1219 // never reached
1223 * Encrypts a password using the given method and salt
1225 * If the selected method needs a salt and none was given, a random one
1226 * is chosen.
1228 * @author Andreas Gohr <andi@splitbrain.org>
1230 * @param string $clear The clear text password
1231 * @param string $method The hashing method
1232 * @param string $salt A salt, null for random
1233 * @return string The crypted password
1235 function auth_cryptPassword($clear, $method = '', $salt = null)
1237 global $conf;
1238 if (empty($method)) $method = $conf['passcrypt'];
1240 $pass = new PassHash();
1241 $call = 'hash_' . $method;
1243 if (!method_exists($pass, $call)) {
1244 msg("Unsupported crypt method $method", -1);
1245 return false;
1248 return $pass->$call($clear, $salt);
1252 * Verifies a cleartext password against a crypted hash
1254 * @author Andreas Gohr <andi@splitbrain.org>
1256 * @param string $clear The clear text password
1257 * @param string $crypt The hash to compare with
1258 * @return bool true if both match
1260 function auth_verifyPassword($clear, $crypt)
1262 $pass = new PassHash();
1263 return $pass->verify_hash($clear, $crypt);
1267 * Set the authentication cookie and add user identification data to the session
1269 * @param string $user username
1270 * @param string $pass encrypted password
1271 * @param bool $sticky whether or not the cookie will last beyond the session
1272 * @return bool
1274 function auth_setCookie($user, $pass, $sticky)
1276 global $conf;
1277 /* @var AuthPlugin $auth */
1278 global $auth;
1279 global $USERINFO;
1281 if (!$auth) return false;
1282 $USERINFO = $auth->getUserData($user);
1284 // set cookie
1285 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
1286 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1287 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1288 setcookie(DOKU_COOKIE, $cookie, [
1289 'expires' => $time,
1290 'path' => $cookieDir,
1291 'secure' => ($conf['securecookie'] && is_ssl()),
1292 'httponly' => true,
1293 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1296 // set session
1297 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1298 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1299 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1300 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1301 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1303 return true;
1307 * Returns the user, (encrypted) password and sticky bit from cookie
1309 * @returns array
1311 function auth_getCookie()
1313 if (!isset($_COOKIE[DOKU_COOKIE])) {
1314 return [null, null, null];
1316 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1317 $sticky = (bool) $sticky;
1318 $pass = base64_decode($pass);
1319 $user = base64_decode($user);
1320 return [$user, $sticky, $pass];
1323 //Setup VIM: ex: et ts=2 :