Merge branch 'master' into revisionHandle3
[dokuwiki.git] / inc / auth.php
blob532574c7e58b2551149d79ba012d1b0b05321ddf
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 // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
70 // the one presented at
71 // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
72 // for enabling HTTP authentication with CGI/SuExec)
73 if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
74 $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
75 // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
76 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
77 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
78 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
81 // if no credentials were given try to use HTTP auth (for SSO)
82 if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
83 $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
84 $INPUT->set('p', $_SERVER['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 $ok = null;
95 if (!is_null($auth) && $auth->canDo('external')) {
96 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
99 if ($ok === null) {
100 // external trust mechanism not in place, or returns no result,
101 // then attempt auth_login
102 $evdata = array(
103 'user' => $INPUT->str('u'),
104 'password' => $INPUT->str('p'),
105 'sticky' => $INPUT->bool('r'),
106 'silent' => $INPUT->bool('http_credentials')
108 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
111 //load ACL into a global array XXX
112 $AUTH_ACL = auth_loadACL();
114 return true;
118 * Loads the ACL setup and handle user wildcards
120 * @author Andreas Gohr <andi@splitbrain.org>
122 * @return array
124 function auth_loadACL() {
125 global $config_cascade;
126 global $USERINFO;
127 /* @var Input $INPUT */
128 global $INPUT;
130 if(!is_readable($config_cascade['acl']['default'])) return array();
132 $acl = file($config_cascade['acl']['default']);
134 $out = array();
135 foreach($acl as $line) {
136 $line = trim($line);
137 if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
138 list($id,$rest) = preg_split('/[ \t]+/',$line,2);
140 // substitute user wildcard first (its 1:1)
141 if(strstr($line, '%USER%')){
142 // if user is not logged in, this ACL line is meaningless - skip it
143 if (!$INPUT->server->has('REMOTE_USER')) continue;
145 $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
146 $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
149 // substitute group wildcard (its 1:m)
150 if(strstr($line, '%GROUP%')){
151 // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
152 if(isset($USERINFO['grps'])){
153 foreach((array) $USERINFO['grps'] as $grp){
154 $nid = str_replace('%GROUP%',cleanID($grp),$id);
155 $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
156 $out[] = "$nid\t$nrest";
159 } else {
160 $out[] = "$id\t$rest";
164 return $out;
168 * Event hook callback for AUTH_LOGIN_CHECK
170 * @param array $evdata
171 * @return bool
173 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) {
212 global $USERINFO;
213 global $conf;
214 global $lang;
215 /* @var AuthPlugin $auth */
216 global $auth;
217 /* @var Input $INPUT */
218 global $INPUT;
220 $sticky ? $sticky = true : $sticky = false; //sanity check
222 if(!$auth) return false;
224 if(!empty($user)) {
225 //usual login
226 if(!empty($pass) && $auth->checkPass($user, $pass)) {
227 // make logininfo globally available
228 $INPUT->server->set('REMOTE_USER', $user);
229 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
230 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
231 return true;
232 } else {
233 //invalid credentials - log off
234 if(!$silent) {
235 http_status(403, 'Login failed');
236 msg($lang['badlogin'], -1);
238 auth_logoff();
239 return false;
241 } else {
242 // read cookie information
243 list($user, $sticky, $pass) = auth_getCookie();
244 if($user && $pass) {
245 // we got a cookie - see if we can trust it
247 // get session info
248 if (isset($_SESSION[DOKU_COOKIE])) {
249 $session = $_SESSION[DOKU_COOKIE]['auth'];
250 if (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())
258 // he has session, cookie and browser right - let him in
259 $INPUT->server->set('REMOTE_USER', $user);
260 $USERINFO = $session['info']; //FIXME move all references to session
261 return true;
264 // no we don't trust it yet - recheck pass but silent
265 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
266 $pass = auth_decrypt($pass, $secret);
267 return auth_login($user, $pass, $sticky, true);
270 //just to be sure
271 auth_logoff(true);
272 return false;
276 * Builds a pseudo UID from browser and IP data
278 * This is neither unique nor unfakable - still it adds some
279 * security. Using the first part of the IP makes sure
280 * proxy farms like AOLs are still okay.
282 * @author Andreas Gohr <andi@splitbrain.org>
284 * @return string a SHA256 sum of various browser headers
286 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 $INPUT->server->str('HTTP_ACCEPT_ENCODING'),
298 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
300 return hash('sha256', $uid);
304 * Creates a random key to encrypt the password in cookies
306 * This function tries to read the password for encrypting
307 * cookies from $conf['metadir'].'/_htcookiesalt'
308 * if no such file is found a random key is created and
309 * and stored in this file.
311 * @author Andreas Gohr <andi@splitbrain.org>
313 * @param bool $addsession if true, the sessionid is added to the salt
314 * @param bool $secure if security is more important than keeping the old value
315 * @return string
317 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) {
346 return random_bytes($length);
350 * Cryptographically secure random number generator.
352 * @author Niklas Keller <me@kelunik.com>
354 * @param int $min
355 * @param int $max
356 * @return int
358 function auth_random($min, $max) {
359 return random_int($min, $max);
363 * Encrypt data using the given secret using AES
365 * The mode is CBC with a random initialization vector, the key is derived
366 * using pbkdf2.
368 * @param string $data The data that shall be encrypted
369 * @param string $secret The secret/password that shall be used
370 * @return string The ciphertext
372 function auth_encrypt($data, $secret) {
373 $iv = auth_randombytes(16);
374 $cipher = new \phpseclib\Crypt\AES();
375 $cipher->setPassword($secret);
378 this uses the encrypted IV as IV as suggested in
379 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
380 for unique but necessarily random IVs. The resulting ciphertext is
381 compatible to ciphertext that was created using a "normal" IV.
383 return $cipher->encrypt($iv.$data);
387 * Decrypt the given AES ciphertext
389 * The mode is CBC, the key is derived using pbkdf2
391 * @param string $ciphertext The encrypted data
392 * @param string $secret The secret/password that shall be used
393 * @return string The decrypted data
395 function auth_decrypt($ciphertext, $secret) {
396 $iv = substr($ciphertext, 0, 16);
397 $cipher = new \phpseclib\Crypt\AES();
398 $cipher->setPassword($secret);
399 $cipher->setIV($iv);
401 return $cipher->decrypt(substr($ciphertext, 16));
405 * Log out the current user
407 * This clears all authentication data and thus log the user
408 * off. It also clears session data.
410 * @author Andreas Gohr <andi@splitbrain.org>
412 * @param bool $keepbc - when true, the breadcrumb data is not cleared
414 function auth_logoff($keepbc = false) {
415 global $conf;
416 global $USERINFO;
417 /* @var AuthPlugin $auth */
418 global $auth;
419 /* @var Input $INPUT */
420 global $INPUT;
422 // make sure the session is writable (it usually is)
423 @session_start();
425 if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
426 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
427 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
428 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
429 if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
430 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
431 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
432 unset($_SESSION[DOKU_COOKIE]['bc']);
433 $INPUT->server->remove('REMOTE_USER');
434 $USERINFO = null; //FIXME
436 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
437 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
439 if($auth) $auth->logOff();
443 * Check if a user is a manager
445 * Should usually be called without any parameters to check the current
446 * user.
448 * The info is available through $INFO['ismanager'], too
450 * @param string $user Username
451 * @param array $groups List of groups the user is in
452 * @param bool $adminonly when true checks if user is admin
453 * @param bool $recache set to true to refresh the cache
454 * @return bool
455 * @see auth_isadmin
457 * @author Andreas Gohr <andi@splitbrain.org>
459 function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
460 global $conf;
461 global $USERINFO;
462 /* @var AuthPlugin $auth */
463 global $auth;
464 /* @var Input $INPUT */
465 global $INPUT;
468 if(!$auth) return false;
469 if(is_null($user)) {
470 if(!$INPUT->server->has('REMOTE_USER')) {
471 return false;
472 } else {
473 $user = $INPUT->server->str('REMOTE_USER');
476 if (is_null($groups)) {
477 // checking the logged in user, or another one?
478 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
479 $groups = (array) $USERINFO['grps'];
480 } else {
481 $groups = $auth->getUserData($user);
482 $groups = $groups ? $groups['grps'] : [];
486 // prefer cached result
487 static $cache = [];
488 $cachekey = serialize([$user, $adminonly, $groups]);
489 if (!isset($cache[$cachekey]) || $recache) {
490 // check superuser match
491 $ok = auth_isMember($conf['superuser'], $user, $groups);
493 // check managers
494 if (!$ok && !$adminonly) {
495 $ok = auth_isMember($conf['manager'], $user, $groups);
498 $cache[$cachekey] = $ok;
501 return $cache[$cachekey];
505 * Check if a user is admin
507 * Alias to auth_ismanager with adminonly=true
509 * The info is available through $INFO['isadmin'], too
511 * @param string $user Username
512 * @param array $groups List of groups the user is in
513 * @param bool $recache set to true to refresh the cache
514 * @return bool
515 * @author Andreas Gohr <andi@splitbrain.org>
516 * @see auth_ismanager()
519 function auth_isadmin($user = null, $groups = null, $recache=false) {
520 return auth_ismanager($user, $groups, true, $recache);
524 * Match a user and his groups against a comma separated list of
525 * users and groups to determine membership status
527 * Note: all input should NOT be nameencoded.
529 * @param string $memberlist commaseparated list of allowed users and groups
530 * @param string $user user to match against
531 * @param array $groups groups the user is member of
532 * @return bool true for membership acknowledged
534 function auth_isMember($memberlist, $user, array $groups) {
535 /* @var AuthPlugin $auth */
536 global $auth;
537 if(!$auth) return false;
539 // clean user and groups
540 if(!$auth->isCaseSensitive()) {
541 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
542 $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups);
544 $user = $auth->cleanUser($user);
545 $groups = array_map(array($auth, 'cleanGroup'), $groups);
547 // extract the memberlist
548 $members = explode(',', $memberlist);
549 $members = array_map('trim', $members);
550 $members = array_unique($members);
551 $members = array_filter($members);
553 // compare cleaned values
554 foreach($members as $member) {
555 if($member == '@ALL' ) return true;
556 if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
557 if($member[0] == '@') {
558 $member = $auth->cleanGroup(substr($member, 1));
559 if(in_array($member, $groups)) return true;
560 } else {
561 $member = $auth->cleanUser($member);
562 if($member == $user) return true;
566 // still here? not a member!
567 return false;
571 * Convinience function for auth_aclcheck()
573 * This checks the permissions for the current user
575 * @author Andreas Gohr <andi@splitbrain.org>
577 * @param string $id page ID (needs to be resolved and cleaned)
578 * @return int permission level
580 function auth_quickaclcheck($id) {
581 global $conf;
582 global $USERINFO;
583 /* @var Input $INPUT */
584 global $INPUT;
585 # if no ACL is used always return upload rights
586 if(!$conf['useacl']) return AUTH_UPLOAD;
587 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
591 * Returns the maximum rights a user has for the given ID or its namespace
593 * @author Andreas Gohr <andi@splitbrain.org>
595 * @triggers AUTH_ACL_CHECK
596 * @param string $id page ID (needs to be resolved and cleaned)
597 * @param string $user Username
598 * @param array|null $groups Array of groups the user is in
599 * @return int permission level
601 function auth_aclcheck($id, $user, $groups) {
602 $data = array(
603 'id' => $id,
604 'user' => $user,
605 'groups' => $groups
608 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
612 * default ACL check method
614 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
616 * @author Andreas Gohr <andi@splitbrain.org>
618 * @param array $data event data
619 * @return int permission level
621 function auth_aclcheck_cb($data) {
622 $id =& $data['id'];
623 $user =& $data['user'];
624 $groups =& $data['groups'];
626 global $conf;
627 global $AUTH_ACL;
628 /* @var AuthPlugin $auth */
629 global $auth;
631 // if no ACL is used always return upload rights
632 if(!$conf['useacl']) return AUTH_UPLOAD;
633 if(!$auth) return AUTH_NONE;
635 //make sure groups is an array
636 if(!is_array($groups)) $groups = array();
638 //if user is superuser or in superusergroup return 255 (acl_admin)
639 if(auth_isadmin($user, $groups)) {
640 return AUTH_ADMIN;
643 if(!$auth->isCaseSensitive()) {
644 $user = \dokuwiki\Utf8\PhpString::strtolower($user);
645 $groups = array_map('utf8_strtolower', $groups);
647 $user = auth_nameencode($auth->cleanUser($user));
648 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
650 //prepend groups with @ and nameencode
651 foreach($groups as &$group) {
652 $group = '@'.auth_nameencode($group);
655 $ns = getNS($id);
656 $perm = -1;
658 //add ALL group
659 $groups[] = '@ALL';
661 //add User
662 if($user) $groups[] = $user;
664 //check exact match first
665 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
666 if(count($matches)) {
667 foreach($matches as $match) {
668 $match = preg_replace('/#.*$/', '', $match); //ignore comments
669 $acl = preg_split('/[ \t]+/', $match);
670 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
671 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
673 if(!in_array($acl[1], $groups)) {
674 continue;
676 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
677 if($acl[2] > $perm) {
678 $perm = $acl[2];
681 if($perm > -1) {
682 //we had a match - return it
683 return (int) $perm;
687 //still here? do the namespace checks
688 if($ns) {
689 $path = $ns.':*';
690 } else {
691 $path = '*'; //root document
694 do {
695 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
696 if(count($matches)) {
697 foreach($matches as $match) {
698 $match = preg_replace('/#.*$/', '', $match); //ignore comments
699 $acl = preg_split('/[ \t]+/', $match);
700 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
701 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
703 if(!in_array($acl[1], $groups)) {
704 continue;
706 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
707 if($acl[2] > $perm) {
708 $perm = $acl[2];
711 //we had a match - return it
712 if($perm != -1) {
713 return (int) $perm;
716 //get next higher namespace
717 $ns = getNS($ns);
719 if($path != '*') {
720 $path = $ns.':*';
721 if($path == ':*') $path = '*';
722 } else {
723 //we did this already
724 //looks like there is something wrong with the ACL
725 //break here
726 msg('No ACL setup yet! Denying access to everyone.');
727 return AUTH_NONE;
729 } while(1); //this should never loop endless
730 return AUTH_NONE;
734 * Encode ASCII special chars
736 * Some auth backends allow special chars in their user and groupnames
737 * The special chars are encoded with this function. Only ASCII chars
738 * are encoded UTF-8 multibyte are left as is (different from usual
739 * urlencoding!).
741 * Decoding can be done with rawurldecode
743 * @author Andreas Gohr <gohr@cosmocode.de>
744 * @see rawurldecode()
746 * @param string $name
747 * @param bool $skip_group
748 * @return string
750 function auth_nameencode($name, $skip_group = false) {
751 global $cache_authname;
752 $cache =& $cache_authname;
753 $name = (string) $name;
755 // never encode wildcard FS#1955
756 if($name == '%USER%') return $name;
757 if($name == '%GROUP%') return $name;
759 if(!isset($cache[$name][$skip_group])) {
760 if($skip_group && $name[0] == '@') {
761 $cache[$name][$skip_group] = '@'.preg_replace_callback(
762 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
763 'auth_nameencode_callback', substr($name, 1)
765 } else {
766 $cache[$name][$skip_group] = preg_replace_callback(
767 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
768 'auth_nameencode_callback', $name
773 return $cache[$name][$skip_group];
777 * callback encodes the matches
779 * @param array $matches first complete match, next matching subpatterms
780 * @return string
782 function auth_nameencode_callback($matches) {
783 return '%'.dechex(ord(substr($matches[1],-1)));
787 * Create a pronouncable password
789 * The $foruser variable might be used by plugins to run additional password
790 * policy checks, but is not used by the default implementation
792 * @author Andreas Gohr <andi@splitbrain.org>
793 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
794 * @triggers AUTH_PASSWORD_GENERATE
796 * @param string $foruser username for which the password is generated
797 * @return string pronouncable password
799 function auth_pwgen($foruser = '') {
800 $data = array(
801 'password' => '',
802 'foruser' => $foruser
805 $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
806 if($evt->advise_before(true)) {
807 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
808 $v = 'aeiou'; //vowels
809 $a = $c.$v; //both
810 $s = '!$%&?+*~#-_:.;,'; // specials
812 //use thre syllables...
813 for($i = 0; $i < 3; $i++) {
814 $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
815 $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
816 $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
818 //... and add a nice number and special
819 $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
821 $evt->advise_after();
823 return $data['password'];
827 * Sends a password to the given user
829 * @author Andreas Gohr <andi@splitbrain.org>
831 * @param string $user Login name of the user
832 * @param string $password The new password in clear text
833 * @return bool true on success
835 function auth_sendPassword($user, $password) {
836 global $lang;
837 /* @var AuthPlugin $auth */
838 global $auth;
839 if(!$auth) return false;
841 $user = $auth->cleanUser($user);
842 $userinfo = $auth->getUserData($user, $requireGroups = false);
844 if(!$userinfo['mail']) return false;
846 $text = rawLocale('password');
847 $trep = array(
848 'FULLNAME' => $userinfo['name'],
849 'LOGIN' => $user,
850 'PASSWORD' => $password
853 $mail = new Mailer();
854 $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
855 $mail->subject($lang['regpwmail']);
856 $mail->setBody($text, $trep);
857 return $mail->send();
861 * Register a new user
863 * This registers a new user - Data is read directly from $_POST
865 * @author Andreas Gohr <andi@splitbrain.org>
867 * @return bool true on success, false on any error
869 function register() {
870 global $lang;
871 global $conf;
872 /* @var \dokuwiki\Extension\AuthPlugin $auth */
873 global $auth;
874 global $INPUT;
876 if(!$INPUT->post->bool('save')) return false;
877 if(!actionOK('register')) return false;
879 // gather input
880 $login = trim($auth->cleanUser($INPUT->post->str('login')));
881 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
882 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
883 $pass = $INPUT->post->str('pass');
884 $passchk = $INPUT->post->str('passchk');
886 if(empty($login) || empty($fullname) || empty($email)) {
887 msg($lang['regmissing'], -1);
888 return false;
891 if($conf['autopasswd']) {
892 $pass = auth_pwgen($login); // automatically generate password
893 } elseif(empty($pass) || empty($passchk)) {
894 msg($lang['regmissing'], -1); // complain about missing passwords
895 return false;
896 } elseif($pass != $passchk) {
897 msg($lang['regbadpass'], -1); // complain about misspelled passwords
898 return false;
901 //check mail
902 if(!mail_isvalid($email)) {
903 msg($lang['regbadmail'], -1);
904 return false;
907 //okay try to create the user
908 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
909 msg($lang['regfail'], -1);
910 return false;
913 // send notification about the new user
914 $subscription = new RegistrationSubscriptionSender();
915 $subscription->sendRegister($login, $fullname, $email);
917 // are we done?
918 if(!$conf['autopasswd']) {
919 msg($lang['regsuccess2'], 1);
920 return true;
923 // autogenerated password? then send password to user
924 if(auth_sendPassword($login, $pass)) {
925 msg($lang['regsuccess'], 1);
926 return true;
927 } else {
928 msg($lang['regmailfail'], -1);
929 return false;
934 * Update user profile
936 * @author Christopher Smith <chris@jalakai.co.uk>
938 function updateprofile() {
939 global $conf;
940 global $lang;
941 /* @var AuthPlugin $auth */
942 global $auth;
943 /* @var Input $INPUT */
944 global $INPUT;
946 if(!$INPUT->post->bool('save')) return false;
947 if(!checkSecurityToken()) return false;
949 if(!actionOK('profile')) {
950 msg($lang['profna'], -1);
951 return false;
954 $changes = array();
955 $changes['pass'] = $INPUT->post->str('newpass');
956 $changes['name'] = $INPUT->post->str('fullname');
957 $changes['mail'] = $INPUT->post->str('email');
959 // check misspelled passwords
960 if($changes['pass'] != $INPUT->post->str('passchk')) {
961 msg($lang['regbadpass'], -1);
962 return false;
965 // clean fullname and email
966 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
967 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
969 // no empty name and email (except the backend doesn't support them)
970 if((empty($changes['name']) && $auth->canDo('modName')) ||
971 (empty($changes['mail']) && $auth->canDo('modMail'))
973 msg($lang['profnoempty'], -1);
974 return false;
976 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
977 msg($lang['regbadmail'], -1);
978 return false;
981 $changes = array_filter($changes);
983 // check for unavailable capabilities
984 if(!$auth->canDo('modName')) unset($changes['name']);
985 if(!$auth->canDo('modMail')) unset($changes['mail']);
986 if(!$auth->canDo('modPass')) unset($changes['pass']);
988 // anything to do?
989 if(!count($changes)) {
990 msg($lang['profnochange'], -1);
991 return false;
994 if($conf['profileconfirm']) {
995 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
996 msg($lang['badpassconfirm'], -1);
997 return false;
1001 if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
1002 msg($lang['proffail'], -1);
1003 return false;
1006 if($changes['pass']) {
1007 // update cookie and session with the changed data
1008 list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
1009 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1010 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1011 } else {
1012 // make sure the session is writable
1013 @session_start();
1014 // invalidate session cache
1015 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1016 session_write_close();
1019 return true;
1023 * Delete the current logged-in user
1025 * @return bool true on success, false on any error
1027 function auth_deleteprofile(){
1028 global $conf;
1029 global $lang;
1030 /* @var \dokuwiki\Extension\AuthPlugin $auth */
1031 global $auth;
1032 /* @var Input $INPUT */
1033 global $INPUT;
1035 if(!$INPUT->post->bool('delete')) return false;
1036 if(!checkSecurityToken()) return false;
1038 // action prevented or auth module disallows
1039 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1040 msg($lang['profnodelete'], -1);
1041 return false;
1044 if(!$INPUT->post->bool('confirm_delete')){
1045 msg($lang['profconfdeletemissing'], -1);
1046 return false;
1049 if($conf['profileconfirm']) {
1050 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1051 msg($lang['badpassconfirm'], -1);
1052 return false;
1056 $deleted = array();
1057 $deleted[] = $INPUT->server->str('REMOTE_USER');
1058 if($auth->triggerUserMod('delete', array($deleted))) {
1059 // force and immediate logout including removing the sticky cookie
1060 auth_logoff();
1061 return true;
1064 return false;
1068 * Send a new password
1070 * This function handles both phases of the password reset:
1072 * - handling the first request of password reset
1073 * - validating the password reset auth token
1075 * @author Benoit Chesneau <benoit@bchesneau.info>
1076 * @author Chris Smith <chris@jalakai.co.uk>
1077 * @author Andreas Gohr <andi@splitbrain.org>
1079 * @return bool true on success, false on any error
1081 function act_resendpwd() {
1082 global $lang;
1083 global $conf;
1084 /* @var AuthPlugin $auth */
1085 global $auth;
1086 /* @var Input $INPUT */
1087 global $INPUT;
1089 if(!actionOK('resendpwd')) {
1090 msg($lang['resendna'], -1);
1091 return false;
1094 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1096 if($token) {
1097 // we're in token phase - get user info from token
1099 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1100 if(!file_exists($tfile)) {
1101 msg($lang['resendpwdbadauth'], -1);
1102 $INPUT->remove('pwauth');
1103 return false;
1105 // token is only valid for 3 days
1106 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1107 msg($lang['resendpwdbadauth'], -1);
1108 $INPUT->remove('pwauth');
1109 @unlink($tfile);
1110 return false;
1113 $user = io_readfile($tfile);
1114 $userinfo = $auth->getUserData($user, $requireGroups = false);
1115 if(!$userinfo['mail']) {
1116 msg($lang['resendpwdnouser'], -1);
1117 return false;
1120 if(!$conf['autopasswd']) { // we let the user choose a password
1121 $pass = $INPUT->str('pass');
1123 // password given correctly?
1124 if(!$pass) return false;
1125 if($pass != $INPUT->str('passchk')) {
1126 msg($lang['regbadpass'], -1);
1127 return false;
1130 // change it
1131 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1132 msg($lang['proffail'], -1);
1133 return false;
1136 } else { // autogenerate the password and send by mail
1138 $pass = auth_pwgen($user);
1139 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1140 msg($lang['proffail'], -1);
1141 return false;
1144 if(auth_sendPassword($user, $pass)) {
1145 msg($lang['resendpwdsuccess'], 1);
1146 } else {
1147 msg($lang['regmailfail'], -1);
1151 @unlink($tfile);
1152 return true;
1154 } else {
1155 // we're in request phase
1157 if(!$INPUT->post->bool('save')) return false;
1159 if(!$INPUT->post->str('login')) {
1160 msg($lang['resendpwdmissing'], -1);
1161 return false;
1162 } else {
1163 $user = trim($auth->cleanUser($INPUT->post->str('login')));
1166 $userinfo = $auth->getUserData($user, $requireGroups = false);
1167 if(!$userinfo['mail']) {
1168 msg($lang['resendpwdnouser'], -1);
1169 return false;
1172 // generate auth token
1173 $token = md5(auth_randombytes(16)); // random secret
1174 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1175 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1177 io_saveFile($tfile, $user);
1179 $text = rawLocale('pwconfirm');
1180 $trep = array(
1181 'FULLNAME' => $userinfo['name'],
1182 'LOGIN' => $user,
1183 'CONFIRM' => $url
1186 $mail = new Mailer();
1187 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1188 $mail->subject($lang['regpwmail']);
1189 $mail->setBody($text, $trep);
1190 if($mail->send()) {
1191 msg($lang['resendpwdconfirm'], 1);
1192 } else {
1193 msg($lang['regmailfail'], -1);
1195 return true;
1197 // never reached
1201 * Encrypts a password using the given method and salt
1203 * If the selected method needs a salt and none was given, a random one
1204 * is chosen.
1206 * @author Andreas Gohr <andi@splitbrain.org>
1208 * @param string $clear The clear text password
1209 * @param string $method The hashing method
1210 * @param string $salt A salt, null for random
1211 * @return string The crypted password
1213 function auth_cryptPassword($clear, $method = '', $salt = null) {
1214 global $conf;
1215 if(empty($method)) $method = $conf['passcrypt'];
1217 $pass = new PassHash();
1218 $call = 'hash_'.$method;
1220 if(!method_exists($pass, $call)) {
1221 msg("Unsupported crypt method $method", -1);
1222 return false;
1225 return $pass->$call($clear, $salt);
1229 * Verifies a cleartext password against a crypted hash
1231 * @author Andreas Gohr <andi@splitbrain.org>
1233 * @param string $clear The clear text password
1234 * @param string $crypt The hash to compare with
1235 * @return bool true if both match
1237 function auth_verifyPassword($clear, $crypt) {
1238 $pass = new PassHash();
1239 return $pass->verify_hash($clear, $crypt);
1243 * Set the authentication cookie and add user identification data to the session
1245 * @param string $user username
1246 * @param string $pass encrypted password
1247 * @param bool $sticky whether or not the cookie will last beyond the session
1248 * @return bool
1250 function auth_setCookie($user, $pass, $sticky) {
1251 global $conf;
1252 /* @var AuthPlugin $auth */
1253 global $auth;
1254 global $USERINFO;
1256 if(!$auth) return false;
1257 $USERINFO = $auth->getUserData($user);
1259 // set cookie
1260 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1261 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1262 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1263 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1265 // set session
1266 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1267 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1268 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1269 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1270 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1272 return true;
1276 * Returns the user, (encrypted) password and sticky bit from cookie
1278 * @returns array
1280 function auth_getCookie() {
1281 if(!isset($_COOKIE[DOKU_COOKIE])) {
1282 return array(null, null, null);
1284 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1285 $sticky = (bool) $sticky;
1286 $pass = base64_decode($pass);
1287 $user = base64_decode($user);
1288 return array($user, $sticky, $pass);
1291 //Setup VIM: ex: et ts=2 :