Merge pull request #3995 from dokuwiki-translate/lang_update_664_1687019870
[dokuwiki.git] / inc / auth.php
blob6e7510555d623a94934311fe51e9ba87bba9b4f8
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>
12 use dokuwiki\Extension\AuthPlugin;
13 use dokuwiki\Extension\Event;
14 use dokuwiki\Extension\PluginController;
15 use dokuwiki\PassHash;
16 use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
18 /**
19 * Initialize the auth system.
21 * This function is automatically called at the end of init.php
23 * This used to be the main() of the auth.php
25 * @todo backend loading maybe should be handled by the class autoloader
26 * @todo maybe split into multiple functions at the XXX marked positions
27 * @triggers AUTH_LOGIN_CHECK
28 * @return bool
30 function auth_setup() {
31 global $conf;
32 /* @var AuthPlugin $auth */
33 global $auth;
34 /* @var Input $INPUT */
35 global $INPUT;
36 global $AUTH_ACL;
37 global $lang;
38 /* @var PluginController $plugin_controller */
39 global $plugin_controller;
40 $AUTH_ACL = array();
42 if(!$conf['useacl']) return false;
44 // try to load auth backend from plugins
45 foreach ($plugin_controller->getList('auth') as $plugin) {
46 if ($conf['authtype'] === $plugin) {
47 $auth = $plugin_controller->load('auth', $plugin);
48 break;
52 if(!isset($auth) || !$auth){
53 msg($lang['authtempfail'], -1);
54 return false;
57 if ($auth->success == false) {
58 // degrade to unauthenticated user
59 $auth = null;
60 auth_logoff();
61 msg($lang['authtempfail'], -1);
62 return false;
65 // do the login either by cookie or provided credentials XXX
66 $INPUT->set('http_credentials', false);
67 if(!$conf['rememberme']) $INPUT->set('r', false);
69 // Populate Basic Auth user/password from Authorization header
70 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
71 $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
72 if(preg_match( '~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches )) {
73 $userpass = explode(':', base64_decode($matches[1]));
74 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $userpass;
77 // if no credentials were given try to use HTTP auth (for SSO)
78 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
79 $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
80 $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
81 $INPUT->set('http_credentials', true);
84 // apply cleaning (auth specific user names, remove control chars)
85 if (true === $auth->success) {
86 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
87 $INPUT->set('p', stripctl($INPUT->str('p')));
90 $ok = null;
91 if (!is_null($auth) && $auth->canDo('external')) {
92 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
95 if ($ok === null) {
96 // external trust mechanism not in place, or returns no result,
97 // then attempt auth_login
98 $evdata = array(
99 'user' => $INPUT->str('u'),
100 'password' => $INPUT->str('p'),
101 'sticky' => $INPUT->bool('r'),
102 'silent' => $INPUT->bool('http_credentials')
104 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
107 //load ACL into a global array XXX
108 $AUTH_ACL = auth_loadACL();
110 return true;
114 * Loads the ACL setup and handle user wildcards
116 * @author Andreas Gohr <andi@splitbrain.org>
118 * @return array
120 function auth_loadACL() {
121 global $config_cascade;
122 global $USERINFO;
123 /* @var Input $INPUT */
124 global $INPUT;
126 if(!is_readable($config_cascade['acl']['default'])) return array();
128 $acl = file($config_cascade['acl']['default']);
130 $out = array();
131 foreach($acl as $line) {
132 $line = trim($line);
133 if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
134 list($id,$rest) = preg_split('/[ \t]+/',$line,2);
136 // substitute user wildcard first (its 1:1)
137 if(strstr($line, '%USER%')){
138 // if user is not logged in, this ACL line is meaningless - skip it
139 if (!$INPUT->server->has('REMOTE_USER')) continue;
141 $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
142 $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
145 // substitute group wildcard (its 1:m)
146 if(strstr($line, '%GROUP%')){
147 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
148 if(isset($USERINFO['grps'])){
149 foreach((array) $USERINFO['grps'] as $grp){
150 $nid = str_replace('%GROUP%',cleanID($grp),$id);
151 $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
152 $out[] = "$nid\t$nrest";
155 } else {
156 $out[] = "$id\t$rest";
160 return $out;
164 * Event hook callback for AUTH_LOGIN_CHECK
166 * @param array $evdata
167 * @return bool
169 function auth_login_wrapper($evdata) {
170 return auth_login(
171 $evdata['user'],
172 $evdata['password'],
173 $evdata['sticky'],
174 $evdata['silent']
179 * This tries to login the user based on the sent auth credentials
181 * The authentication works like this: if a username was given
182 * a new login is assumed and user/password are checked. If they
183 * are correct the password is encrypted with blowfish and stored
184 * together with the username in a cookie - the same info is stored
185 * in the session, too. Additonally a browserID is stored in the
186 * session.
188 * If no username was given the cookie is checked: if the username,
189 * crypted password and browserID match between session and cookie
190 * no further testing is done and the user is accepted
192 * If a cookie was found but no session info was availabe the
193 * blowfish encrypted password from the cookie is decrypted and
194 * together with username rechecked by calling this function again.
196 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
197 * are set.
199 * @author Andreas Gohr <andi@splitbrain.org>
201 * @param string $user Username
202 * @param string $pass Cleartext Password
203 * @param bool $sticky Cookie should not expire
204 * @param bool $silent Don't show error on bad auth
205 * @return bool true on successful auth
207 function auth_login($user, $pass, $sticky = false, $silent = false) {
208 global $USERINFO;
209 global $conf;
210 global $lang;
211 /* @var AuthPlugin $auth */
212 global $auth;
213 /* @var Input $INPUT */
214 global $INPUT;
216 $sticky ? $sticky = true : $sticky = false; //sanity check
218 if(!$auth) return false;
220 if(!empty($user)) {
221 //usual login
222 if(!empty($pass) && $auth->checkPass($user, $pass)) {
223 // make logininfo globally available
224 $INPUT->server->set('REMOTE_USER', $user);
225 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
226 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
227 return true;
228 } else {
229 //invalid credentials - log off
230 if(!$silent) {
231 http_status(403, 'Login failed');
232 msg($lang['badlogin'], -1);
234 auth_logoff();
235 return false;
237 } else {
238 // read cookie information
239 list($user, $sticky, $pass) = auth_getCookie();
240 if($user && $pass) {
241 // we got a cookie - see if we can trust it
243 // get session info
244 if (isset($_SESSION[DOKU_COOKIE])) {
245 $session = $_SESSION[DOKU_COOKIE]['auth'];
246 if (isset($session) &&
247 $auth->useSessionCache($user) &&
248 ($session['time'] >= time() - $conf['auth_security_timeout']) &&
249 ($session['user'] == $user) &&
250 ($session['pass'] == sha1($pass)) && //still crypted
251 ($session['buid'] == auth_browseruid())
254 // he has session, cookie and browser right - let him in
255 $INPUT->server->set('REMOTE_USER', $user);
256 $USERINFO = $session['info']; //FIXME move all references to session
257 return true;
260 // no we don't trust it yet - recheck pass but silent
261 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
262 $pass = auth_decrypt($pass, $secret);
263 return auth_login($user, $pass, $sticky, true);
266 //just to be sure
267 auth_logoff(true);
268 return false;
272 * Builds a pseudo UID from browser and IP data
274 * This is neither unique nor unfakable - still it adds some
275 * security. Using the first part of the IP makes sure
276 * proxy farms like AOLs are still okay.
278 * @author Andreas Gohr <andi@splitbrain.org>
280 * @return string a SHA256 sum of various browser headers
282 function auth_browseruid() {
283 /* @var Input $INPUT */
284 global $INPUT;
286 $ip = clientIP(true);
287 // convert IP string to packed binary representation
288 $pip = inet_pton($ip);
290 $uid = implode("\n", [
291 $INPUT->server->str('HTTP_USER_AGENT'),
292 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
293 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
295 return hash('sha256', $uid);
299 * Creates a random key to encrypt the password in cookies
301 * This function tries to read the password for encrypting
302 * cookies from $conf['metadir'].'/_htcookiesalt'
303 * if no such file is found a random key is created and
304 * and stored in this file.
306 * @author Andreas Gohr <andi@splitbrain.org>
308 * @param bool $addsession if true, the sessionid is added to the salt
309 * @param bool $secure if security is more important than keeping the old value
310 * @return string
312 function auth_cookiesalt($addsession = false, $secure = false) {
313 if (defined('SIMPLE_TEST')) {
314 return 'test';
316 global $conf;
317 $file = $conf['metadir'].'/_htcookiesalt';
318 if ($secure || !file_exists($file)) {
319 $file = $conf['metadir'].'/_htcookiesalt2';
321 $salt = io_readFile($file);
322 if(empty($salt)) {
323 $salt = bin2hex(auth_randombytes(64));
324 io_saveFile($file, $salt);
326 if($addsession) {
327 $salt .= session_id();
329 return $salt;
333 * Return cryptographically secure random bytes.
335 * @author Niklas Keller <me@kelunik.com>
337 * @param int $length number of bytes
338 * @return string cryptographically secure random bytes
340 function auth_randombytes($length) {
341 return random_bytes($length);
345 * Cryptographically secure random number generator.
347 * @author Niklas Keller <me@kelunik.com>
349 * @param int $min
350 * @param int $max
351 * @return int
353 function auth_random($min, $max) {
354 return random_int($min, $max);
358 * Encrypt data using the given secret using AES
360 * The mode is CBC with a random initialization vector, the key is derived
361 * using pbkdf2.
363 * @param string $data The data that shall be encrypted
364 * @param string $secret The secret/password that shall be used
365 * @return string The ciphertext
367 function auth_encrypt($data, $secret) {
368 $iv = auth_randombytes(16);
369 $cipher = new \phpseclib\Crypt\AES();
370 $cipher->setPassword($secret);
373 this uses the encrypted IV as IV as suggested in
374 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
375 for unique but necessarily random IVs. The resulting ciphertext is
376 compatible to ciphertext that was created using a "normal" IV.
378 return $cipher->encrypt($iv.$data);
382 * Decrypt the given AES ciphertext
384 * The mode is CBC, the key is derived using pbkdf2
386 * @param string $ciphertext The encrypted data
387 * @param string $secret The secret/password that shall be used
388 * @return string The decrypted data
390 function auth_decrypt($ciphertext, $secret) {
391 $iv = substr($ciphertext, 0, 16);
392 $cipher = new \phpseclib\Crypt\AES();
393 $cipher->setPassword($secret);
394 $cipher->setIV($iv);
396 return $cipher->decrypt(substr($ciphertext, 16));
400 * Log out the current user
402 * This clears all authentication data and thus log the user
403 * off. It also clears session data.
405 * @author Andreas Gohr <andi@splitbrain.org>
407 * @param bool $keepbc - when true, the breadcrumb data is not cleared
409 function auth_logoff($keepbc = false) {
410 global $conf;
411 global $USERINFO;
412 /* @var AuthPlugin $auth */
413 global $auth;
414 /* @var Input $INPUT */
415 global $INPUT;
417 // make sure the session is writable (it usually is)
418 @session_start();
420 if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
421 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
422 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
423 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
424 if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
425 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
426 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
427 unset($_SESSION[DOKU_COOKIE]['bc']);
428 $INPUT->server->remove('REMOTE_USER');
429 $USERINFO = null; //FIXME
431 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
432 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
434 if($auth) $auth->logOff();
438 * Check if a user is a manager
440 * Should usually be called without any parameters to check the current
441 * user.
443 * The info is available through $INFO['ismanager'], too
445 * @param string $user Username
446 * @param array $groups List of groups the user is in
447 * @param bool $adminonly when true checks if user is admin
448 * @param bool $recache set to true to refresh the cache
449 * @return bool
450 * @see auth_isadmin
452 * @author Andreas Gohr <andi@splitbrain.org>
454 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
455 global $conf;
456 global $USERINFO;
457 /* @var AuthPlugin $auth */
458 global $auth;
459 /* @var Input $INPUT */
460 global $INPUT;
463 if(!$auth) return false;
464 if(is_null($user)) {
465 if(!$INPUT->server->has('REMOTE_USER')) {
466 return false;
467 } else {
468 $user = $INPUT->server->str('REMOTE_USER');
471 if (is_null($groups)) {
472 // checking the logged in user, or another one?
473 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
474 $groups = (array) $USERINFO['grps'];
475 } else {
476 $groups = $auth->getUserData($user);
477 $groups = $groups ? $groups['grps'] : [];
481 // prefer cached result
482 static $cache = [];
483 $cachekey = serialize([$user, $adminonly, $groups]);
484 if (!isset($cache[$cachekey]) || $recache) {
485 // check superuser match
486 $ok = auth_isMember($conf['superuser'], $user, $groups);
488 // check managers
489 if (!$ok && !$adminonly) {
490 $ok = auth_isMember($conf['manager'], $user, $groups);
493 $cache[$cachekey] = $ok;
496 return $cache[$cachekey];
500 * Check if a user is admin
502 * Alias to auth_ismanager with adminonly=true
504 * The info is available through $INFO['isadmin'], too
506 * @param string $user Username
507 * @param array $groups List of groups the user is in
508 * @param bool $recache set to true to refresh the cache
509 * @return bool
510 * @author Andreas Gohr <andi@splitbrain.org>
511 * @see auth_ismanager()
514 function auth_isadmin($user = null, $groups = null, $recache=false) {
515 return auth_ismanager($user, $groups, true, $recache);
519 * Match a user and his groups against a comma separated list of
520 * users and groups to determine membership status
522 * Note: all input should NOT be nameencoded.
524 * @param string $memberlist commaseparated list of allowed users and groups
525 * @param string $user user to match against
526 * @param array $groups groups the user is member of
527 * @return bool true for membership acknowledged
529 function auth_isMember($memberlist, $user, array $groups) {
530 /* @var AuthPlugin $auth */
531 global $auth;
532 if(!$auth) return false;
534 // clean user and groups
535 if(!$auth->isCaseSensitive()) {
536 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
537 $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
539 $user = $auth->cleanUser($user);
540 $groups = array_map(array($auth, 'cleanGroup'), $groups);
542 // extract the memberlist
543 $members = explode(',', $memberlist);
544 $members = array_map('trim', $members);
545 $members = array_unique($members);
546 $members = array_filter($members);
548 // compare cleaned values
549 foreach($members as $member) {
550 if($member == '@ALL' ) return true;
551 if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
552 if($member[0] == '@') {
553 $member = $auth->cleanGroup(substr($member, 1));
554 if(in_array($member, $groups)) return true;
555 } else {
556 $member = $auth->cleanUser($member);
557 if($member == $user) return true;
561 // still here? not a member!
562 return false;
566 * Convinience function for auth_aclcheck()
568 * This checks the permissions for the current user
570 * @author Andreas Gohr <andi@splitbrain.org>
572 * @param string $id page ID (needs to be resolved and cleaned)
573 * @return int permission level
575 function auth_quickaclcheck($id) {
576 global $conf;
577 global $USERINFO;
578 /* @var Input $INPUT */
579 global $INPUT;
580 # if no ACL is used always return upload rights
581 if(!$conf['useacl']) return AUTH_UPLOAD;
582 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
586 * Returns the maximum rights a user has for the given ID or its namespace
588 * @author Andreas Gohr <andi@splitbrain.org>
590 * @triggers AUTH_ACL_CHECK
591 * @param string $id page ID (needs to be resolved and cleaned)
592 * @param string $user Username
593 * @param array|null $groups Array of groups the user is in
594 * @return int permission level
596 function auth_aclcheck($id, $user, $groups) {
597 $data = array(
598 'id' => $id ?? '',
599 'user' => $user,
600 'groups' => $groups
603 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
607 * default ACL check method
609 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
611 * @author Andreas Gohr <andi@splitbrain.org>
613 * @param array $data event data
614 * @return int permission level
616 function auth_aclcheck_cb($data) {
617 $id =& $data['id'];
618 $user =& $data['user'];
619 $groups =& $data['groups'];
621 global $conf;
622 global $AUTH_ACL;
623 /* @var AuthPlugin $auth */
624 global $auth;
626 // if no ACL is used always return upload rights
627 if(!$conf['useacl']) return AUTH_UPLOAD;
628 if(!$auth) return AUTH_NONE;
629 if(!is_array($AUTH_ACL)) return AUTH_NONE;
631 //make sure groups is an array
632 if(!is_array($groups)) $groups = array();
634 //if user is superuser or in superusergroup return 255 (acl_admin)
635 if(auth_isadmin($user, $groups)) {
636 return AUTH_ADMIN;
639 if(!$auth->isCaseSensitive()) {
640 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
641 $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
643 $user = auth_nameencode($auth->cleanUser($user));
644 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
646 //prepend groups with @ and nameencode
647 foreach($groups as &$group) {
648 $group = '@'.auth_nameencode($group);
651 $ns = getNS($id);
652 $perm = -1;
654 //add ALL group
655 $groups[] = '@ALL';
657 //add User
658 if($user) $groups[] = $user;
660 //check exact match first
661 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
662 if(count($matches)) {
663 foreach($matches as $match) {
664 $match = preg_replace('/#.*$/', '', $match); //ignore comments
665 $acl = preg_split('/[ \t]+/', $match);
666 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
667 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
669 if(!in_array($acl[1], $groups)) {
670 continue;
672 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
673 if($acl[2] > $perm) {
674 $perm = $acl[2];
677 if($perm > -1) {
678 //we had a match - return it
679 return (int) $perm;
683 //still here? do the namespace checks
684 if($ns) {
685 $path = $ns.':*';
686 } else {
687 $path = '*'; //root document
690 do {
691 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
692 if(count($matches)) {
693 foreach($matches as $match) {
694 $match = preg_replace('/#.*$/', '', $match); //ignore comments
695 $acl = preg_split('/[ \t]+/', $match);
696 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
697 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
699 if(!in_array($acl[1], $groups)) {
700 continue;
702 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
703 if($acl[2] > $perm) {
704 $perm = $acl[2];
707 //we had a match - return it
708 if($perm != -1) {
709 return (int) $perm;
712 //get next higher namespace
713 $ns = getNS($ns);
715 if($path != '*') {
716 $path = $ns.':*';
717 if($path == ':*') $path = '*';
718 } else {
719 //we did this already
720 //looks like there is something wrong with the ACL
721 //break here
722 msg('No ACL setup yet! Denying access to everyone.');
723 return AUTH_NONE;
725 } while(1); //this should never loop endless
726 return AUTH_NONE;
730 * Encode ASCII special chars
732 * Some auth backends allow special chars in their user and groupnames
733 * The special chars are encoded with this function. Only ASCII chars
734 * are encoded UTF-8 multibyte are left as is (different from usual
735 * urlencoding!).
737 * Decoding can be done with rawurldecode
739 * @author Andreas Gohr <gohr@cosmocode.de>
740 * @see rawurldecode()
742 * @param string $name
743 * @param bool $skip_group
744 * @return string
746 function auth_nameencode($name, $skip_group = false) {
747 global $cache_authname;
748 $cache =& $cache_authname;
749 $name = (string) $name;
751 // never encode wildcard FS#1955
752 if($name == '%USER%') return $name;
753 if($name == '%GROUP%') return $name;
755 if(!isset($cache[$name][$skip_group])) {
756 if($skip_group && $name[0] == '@') {
757 $cache[$name][$skip_group] = '@'.preg_replace_callback(
758 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
759 'auth_nameencode_callback', substr($name, 1)
761 } else {
762 $cache[$name][$skip_group] = preg_replace_callback(
763 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
764 'auth_nameencode_callback', $name
769 return $cache[$name][$skip_group];
773 * callback encodes the matches
775 * @param array $matches first complete match, next matching subpatterms
776 * @return string
778 function auth_nameencode_callback($matches) {
779 return '%'.dechex(ord(substr($matches[1],-1)));
783 * Create a pronouncable password
785 * The $foruser variable might be used by plugins to run additional password
786 * policy checks, but is not used by the default implementation
788 * @author Andreas Gohr <andi@splitbrain.org>
789 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
790 * @triggers AUTH_PASSWORD_GENERATE
792 * @param string $foruser username for which the password is generated
793 * @return string pronouncable password
795 function auth_pwgen($foruser = '') {
796 $data = array(
797 'password' => '',
798 'foruser' => $foruser
801 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
802 if($evt->advise_before(true)) {
803 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
804 $v = 'aeiou'; //vowels
805 $a = $c.$v; //both
806 $s = '!$%&?+*~#-_:.;,'; // specials
808 //use thre syllables...
809 for($i = 0; $i < 3; $i++) {
810 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
811 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
812 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
814 //... and add a nice number and special
815 $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
817 $evt->advise_after();
819 return $data['password'];
823 * Sends a password to the given user
825 * @author Andreas Gohr <andi@splitbrain.org>
827 * @param string $user Login name of the user
828 * @param string $password The new password in clear text
829 * @return bool true on success
831 function auth_sendPassword($user, $password) {
832 global $lang;
833 /* @var AuthPlugin $auth */
834 global $auth;
835 if(!$auth) return false;
837 $user = $auth->cleanUser($user);
838 $userinfo = $auth->getUserData($user, $requireGroups = false);
840 if(!$userinfo['mail']) return false;
842 $text = rawLocale('password');
843 $trep = array(
844 'FULLNAME' => $userinfo['name'],
845 'LOGIN' => $user,
846 'PASSWORD' => $password
849 $mail = new Mailer();
850 $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
851 $mail->subject($lang['regpwmail']);
852 $mail->setBody($text, $trep);
853 return $mail->send();
857 * Register a new user
859 * This registers a new user - Data is read directly from $_POST
861 * @author Andreas Gohr <andi@splitbrain.org>
863 * @return bool true on success, false on any error
865 function register() {
866 global $lang;
867 global $conf;
868 /* @var \dokuwiki\Extension\AuthPlugin $auth */
869 global $auth;
870 global $INPUT;
872 if(!$INPUT->post->bool('save')) return false;
873 if(!actionOK('register')) return false;
875 // gather input
876 $login = trim($auth->cleanUser($INPUT->post->str('login')));
877 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
878 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
879 $pass = $INPUT->post->str('pass');
880 $passchk = $INPUT->post->str('passchk');
882 if(empty($login) || empty($fullname) || empty($email)) {
883 msg($lang['regmissing'], -1);
884 return false;
887 if($conf['autopasswd']) {
888 $pass = auth_pwgen($login); // automatically generate password
889 } elseif(empty($pass) || empty($passchk)) {
890 msg($lang['regmissing'], -1); // complain about missing passwords
891 return false;
892 } elseif($pass != $passchk) {
893 msg($lang['regbadpass'], -1); // complain about misspelled passwords
894 return false;
897 //check mail
898 if(!mail_isvalid($email)) {
899 msg($lang['regbadmail'], -1);
900 return false;
903 //okay try to create the user
904 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
905 msg($lang['regfail'], -1);
906 return false;
909 // send notification about the new user
910 $subscription = new RegistrationSubscriptionSender();
911 $subscription->sendRegister($login, $fullname, $email);
913 // are we done?
914 if(!$conf['autopasswd']) {
915 msg($lang['regsuccess2'], 1);
916 return true;
919 // autogenerated password? then send password to user
920 if(auth_sendPassword($login, $pass)) {
921 msg($lang['regsuccess'], 1);
922 return true;
923 } else {
924 msg($lang['regmailfail'], -1);
925 return false;
930 * Update user profile
932 * @author Christopher Smith <chris@jalakai.co.uk>
934 function updateprofile() {
935 global $conf;
936 global $lang;
937 /* @var AuthPlugin $auth */
938 global $auth;
939 /* @var Input $INPUT */
940 global $INPUT;
942 if(!$INPUT->post->bool('save')) return false;
943 if(!checkSecurityToken()) return false;
945 if(!actionOK('profile')) {
946 msg($lang['profna'], -1);
947 return false;
950 $changes = array();
951 $changes['pass'] = $INPUT->post->str('newpass');
952 $changes['name'] = $INPUT->post->str('fullname');
953 $changes['mail'] = $INPUT->post->str('email');
955 // check misspelled passwords
956 if($changes['pass'] != $INPUT->post->str('passchk')) {
957 msg($lang['regbadpass'], -1);
958 return false;
961 // clean fullname and email
962 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
963 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
965 // no empty name and email (except the backend doesn't support them)
966 if((empty($changes['name']) && $auth->canDo('modName')) ||
967 (empty($changes['mail']) && $auth->canDo('modMail'))
969 msg($lang['profnoempty'], -1);
970 return false;
972 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
973 msg($lang['regbadmail'], -1);
974 return false;
977 $changes = array_filter($changes);
979 // check for unavailable capabilities
980 if(!$auth->canDo('modName')) unset($changes['name']);
981 if(!$auth->canDo('modMail')) unset($changes['mail']);
982 if(!$auth->canDo('modPass')) unset($changes['pass']);
984 // anything to do?
985 if(!count($changes)) {
986 msg($lang['profnochange'], -1);
987 return false;
990 if($conf['profileconfirm']) {
991 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
992 msg($lang['badpassconfirm'], -1);
993 return false;
997 if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
998 msg($lang['proffail'], -1);
999 return false;
1002 if($changes['pass']) {
1003 // update cookie and session with the changed data
1004 list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
1005 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1006 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1007 } else {
1008 // make sure the session is writable
1009 @session_start();
1010 // invalidate session cache
1011 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1012 session_write_close();
1015 return true;
1019 * Delete the current logged-in user
1021 * @return bool true on success, false on any error
1023 function auth_deleteprofile(){
1024 global $conf;
1025 global $lang;
1026 /* @var \dokuwiki\Extension\AuthPlugin $auth */
1027 global $auth;
1028 /* @var Input $INPUT */
1029 global $INPUT;
1031 if(!$INPUT->post->bool('delete')) return false;
1032 if(!checkSecurityToken()) return false;
1034 // action prevented or auth module disallows
1035 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1036 msg($lang['profnodelete'], -1);
1037 return false;
1040 if(!$INPUT->post->bool('confirm_delete')){
1041 msg($lang['profconfdeletemissing'], -1);
1042 return false;
1045 if($conf['profileconfirm']) {
1046 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1047 msg($lang['badpassconfirm'], -1);
1048 return false;
1052 $deleted = array();
1053 $deleted[] = $INPUT->server->str('REMOTE_USER');
1054 if($auth->triggerUserMod('delete', array($deleted))) {
1055 // force and immediate logout including removing the sticky cookie
1056 auth_logoff();
1057 return true;
1060 return false;
1064 * Send a new password
1066 * This function handles both phases of the password reset:
1068 * - handling the first request of password reset
1069 * - validating the password reset auth token
1071 * @author Benoit Chesneau <benoit@bchesneau.info>
1072 * @author Chris Smith <chris@jalakai.co.uk>
1073 * @author Andreas Gohr <andi@splitbrain.org>
1075 * @return bool true on success, false on any error
1077 function act_resendpwd() {
1078 global $lang;
1079 global $conf;
1080 /* @var AuthPlugin $auth */
1081 global $auth;
1082 /* @var Input $INPUT */
1083 global $INPUT;
1085 if(!actionOK('resendpwd')) {
1086 msg($lang['resendna'], -1);
1087 return false;
1090 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1092 if($token) {
1093 // we're in token phase - get user info from token
1095 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1096 if(!file_exists($tfile)) {
1097 msg($lang['resendpwdbadauth'], -1);
1098 $INPUT->remove('pwauth');
1099 return false;
1101 // token is only valid for 3 days
1102 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1103 msg($lang['resendpwdbadauth'], -1);
1104 $INPUT->remove('pwauth');
1105 @unlink($tfile);
1106 return false;
1109 $user = io_readfile($tfile);
1110 $userinfo = $auth->getUserData($user, $requireGroups = false);
1111 if(!$userinfo['mail']) {
1112 msg($lang['resendpwdnouser'], -1);
1113 return false;
1116 if(!$conf['autopasswd']) { // we let the user choose a password
1117 $pass = $INPUT->str('pass');
1119 // password given correctly?
1120 if(!$pass) return false;
1121 if($pass != $INPUT->str('passchk')) {
1122 msg($lang['regbadpass'], -1);
1123 return false;
1126 // change it
1127 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1128 msg($lang['proffail'], -1);
1129 return false;
1132 } else { // autogenerate the password and send by mail
1134 $pass = auth_pwgen($user);
1135 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1136 msg($lang['proffail'], -1);
1137 return false;
1140 if(auth_sendPassword($user, $pass)) {
1141 msg($lang['resendpwdsuccess'], 1);
1142 } else {
1143 msg($lang['regmailfail'], -1);
1147 @unlink($tfile);
1148 return true;
1150 } else {
1151 // we're in request phase
1153 if(!$INPUT->post->bool('save')) return false;
1155 if(!$INPUT->post->str('login')) {
1156 msg($lang['resendpwdmissing'], -1);
1157 return false;
1158 } else {
1159 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1162 $userinfo = $auth->getUserData($user, $requireGroups = false);
1163 if(!$userinfo['mail']) {
1164 msg($lang['resendpwdnouser'], -1);
1165 return false;
1168 // generate auth token
1169 $token = md5(auth_randombytes(16)); // random secret
1170 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1171 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1173 io_saveFile($tfile, $user);
1175 $text = rawLocale('pwconfirm');
1176 $trep = array(
1177 'FULLNAME' => $userinfo['name'],
1178 'LOGIN' => $user,
1179 'CONFIRM' => $url
1182 $mail = new Mailer();
1183 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1184 $mail->subject($lang['regpwmail']);
1185 $mail->setBody($text, $trep);
1186 if($mail->send()) {
1187 msg($lang['resendpwdconfirm'], 1);
1188 } else {
1189 msg($lang['regmailfail'], -1);
1191 return true;
1193 // never reached
1197 * Encrypts a password using the given method and salt
1199 * If the selected method needs a salt and none was given, a random one
1200 * is chosen.
1202 * @author Andreas Gohr <andi@splitbrain.org>
1204 * @param string $clear The clear text password
1205 * @param string $method The hashing method
1206 * @param string $salt A salt, null for random
1207 * @return string The crypted password
1209 function auth_cryptPassword($clear, $method = '', $salt = null) {
1210 global $conf;
1211 if(empty($method)) $method = $conf['passcrypt'];
1213 $pass = new PassHash();
1214 $call = 'hash_'.$method;
1216 if(!method_exists($pass, $call)) {
1217 msg("Unsupported crypt method $method", -1);
1218 return false;
1221 return $pass->$call($clear, $salt);
1225 * Verifies a cleartext password against a crypted hash
1227 * @author Andreas Gohr <andi@splitbrain.org>
1229 * @param string $clear The clear text password
1230 * @param string $crypt The hash to compare with
1231 * @return bool true if both match
1233 function auth_verifyPassword($clear, $crypt) {
1234 $pass = new PassHash();
1235 return $pass->verify_hash($clear, $crypt);
1239 * Set the authentication cookie and add user identification data to the session
1241 * @param string $user username
1242 * @param string $pass encrypted password
1243 * @param bool $sticky whether or not the cookie will last beyond the session
1244 * @return bool
1246 function auth_setCookie($user, $pass, $sticky) {
1247 global $conf;
1248 /* @var AuthPlugin $auth */
1249 global $auth;
1250 global $USERINFO;
1252 if(!$auth) return false;
1253 $USERINFO = $auth->getUserData($user);
1255 // set cookie
1256 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1257 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1258 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1259 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1261 // set session
1262 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1263 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1264 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1265 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1266 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1268 return true;
1272 * Returns the user, (encrypted) password and sticky bit from cookie
1274 * @returns array
1276 function auth_getCookie() {
1277 if(!isset($_COOKIE[DOKU_COOKIE])) {
1278 return array(null, null, null);
1280 list($user, $sticky, $pass) = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1281 $sticky = (bool) $sticky;
1282 $pass = base64_decode($pass);
1283 $user = base64_decode($user);
1284 return array($user, $sticky, $pass);
1287 //Setup VIM: ex: et ts=2 :