1<?php 2 3/** 4 * Authentication library 5 * 6 * Including this file will automatically try to login 7 * a user by calling auth_login() 8 * 9 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 10 * @author Andreas Gohr <andi@splitbrain.org> 11 */ 12 13use dokuwiki\Ip; 14use dokuwiki\ErrorHandler; 15use dokuwiki\JWT; 16use dokuwiki\Utf8\PhpString; 17use dokuwiki\Extension\AuthPlugin; 18use dokuwiki\Extension\Event; 19use dokuwiki\Extension\PluginController; 20use dokuwiki\PassHash; 21use dokuwiki\Subscriptions\RegistrationSubscriptionSender; 22use phpseclib3\Crypt\AES; 23use phpseclib3\Crypt\Common\SymmetricKey; 24use phpseclib3\Exception\BadDecryptionException; 25 26/** 27 * Initialize the auth system. 28 * 29 * This function is automatically called at the end of init.php 30 * 31 * This used to be the main() of the auth.php 32 * 33 * @todo backend loading maybe should be handled by the class autoloader 34 * @todo maybe split into multiple functions at the XXX marked positions 35 * @triggers AUTH_LOGIN_CHECK 36 * @return bool 37 */ 38function auth_setup() 39{ 40 global $conf; 41 /* @var AuthPlugin $auth */ 42 global $auth; 43 /* @var Input $INPUT */ 44 global $INPUT; 45 global $AUTH_ACL; 46 global $lang; 47 /* @var PluginController $plugin_controller */ 48 global $plugin_controller; 49 $AUTH_ACL = []; 50 51 // unset REMOTE_USER if empty 52 if ($INPUT->server->str('REMOTE_USER') === '') { 53 $INPUT->server->remove('REMOTE_USER'); 54 } 55 56 if (!$conf['useacl']) return false; 57 58 // try to load auth backend from plugins 59 foreach ($plugin_controller->getList('auth') as $plugin) { 60 if ($conf['authtype'] === $plugin) { 61 $auth = $plugin_controller->load('auth', $plugin); 62 break; 63 } 64 } 65 66 if (!$auth instanceof AuthPlugin) { 67 msg($lang['authtempfail'], -1); 68 return false; 69 } 70 71 if ($auth->success == false) { 72 // degrade to unauthenticated user 73 $auth = null; 74 auth_logoff(); 75 msg($lang['authtempfail'], -1); 76 return false; 77 } 78 79 // do the login either by cookie or provided credentials XXX 80 $INPUT->set('http_credentials', false); 81 if (!$conf['rememberme']) $INPUT->set('r', false); 82 83 // Populate Basic Auth user/password from Authorization header 84 // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION 85 $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION'); 86 if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) { 87 $userpass = explode(':', base64_decode($matches[1])); 88 [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass; 89 } 90 91 // if no credentials were given try to use HTTP auth (for SSO) 92 if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) { 93 $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER')); 94 $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW')); 95 $INPUT->set('http_credentials', true); 96 } 97 98 // apply cleaning (auth specific user names, remove control chars) 99 if (true === $auth->success) { 100 $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); 101 $INPUT->set('p', stripctl($INPUT->str('p'))); 102 } 103 104 if (!auth_tokenlogin()) { 105 $ok = null; 106 107 if ($auth->canDo('external')) { 108 $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); 109 } 110 111 if ($ok === null) { 112 // external trust mechanism not in place, or returns no result, 113 // then attempt auth_login 114 $evdata = [ 115 'user' => $INPUT->str('u'), 116 'password' => $INPUT->str('p'), 117 'sticky' => $INPUT->bool('r'), 118 'silent' => $INPUT->bool('http_credentials') 119 ]; 120 Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); 121 } 122 } 123 124 //load ACL into a global array XXX 125 $AUTH_ACL = auth_loadACL(); 126 127 return true; 128} 129 130/** 131 * Loads the ACL setup and handle user wildcards 132 * 133 * @author Andreas Gohr <andi@splitbrain.org> 134 * 135 * @return array 136 */ 137function auth_loadACL() 138{ 139 global $config_cascade; 140 global $USERINFO; 141 /* @var Input $INPUT */ 142 global $INPUT; 143 144 if (!is_readable($config_cascade['acl']['default'])) return []; 145 146 $acl = file($config_cascade['acl']['default']); 147 148 $out = []; 149 foreach ($acl as $line) { 150 $line = trim($line); 151 if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments 152 [$id, $rest] = preg_split('/[ \t]+/', $line, 2); 153 154 // substitute user wildcard first (its 1:1) 155 if (strstr($line, '%USER%')) { 156 // if user is not logged in, this ACL line is meaningless - skip it 157 if (!$INPUT->server->has('REMOTE_USER')) continue; 158 159 $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id); 160 $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest); 161 } 162 163 // substitute group wildcard (its 1:m) 164 if (strstr($line, '%GROUP%')) { 165 // if user is not logged in, grps is empty, no output will be added (i.e. skipped) 166 if (isset($USERINFO['grps'])) { 167 foreach ((array) $USERINFO['grps'] as $grp) { 168 $nid = str_replace('%GROUP%', cleanID($grp), $id); 169 $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest); 170 $out[] = "$nid\t$nrest"; 171 } 172 } 173 } else { 174 $out[] = "$id\t$rest"; 175 } 176 } 177 178 return $out; 179} 180 181/** 182 * Try a token login 183 * 184 * @return bool true if token login succeeded 185 */ 186function auth_tokenlogin() 187{ 188 global $USERINFO; 189 global $INPUT; 190 /** @var DokuWiki_Auth_Plugin $auth */ 191 global $auth; 192 if (!$auth) return false; 193 194 $headers = []; 195 196 // try to get the headers from Apache 197 if (function_exists('getallheaders')) { 198 $headers = getallheaders(); 199 if (is_array($headers)) { 200 $headers = array_change_key_case($headers); 201 } 202 } 203 204 // get the headers from $_SERVER 205 if (!$headers) { 206 foreach ($_SERVER as $key => $value) { 207 if (str_starts_with($key, 'HTTP_')) { 208 $headers[strtolower(substr($key, 5))] = $value; 209 } 210 } 211 } 212 213 // check authorization header 214 if (isset($headers['authorization'])) { 215 [$type, $token] = sexplode(' ', $headers['authorization'], 2); 216 if ($type !== 'Bearer') $token = ''; // not the token we want 217 } 218 219 // check x-dokuwiki-token header 220 if (isset($headers['x-dokuwiki-token'])) { 221 $token = $headers['x-dokuwiki-token']; 222 } 223 224 if (empty($token)) return false; 225 226 // check token 227 try { 228 $authtoken = JWT::validate($token); 229 } catch (Exception $e) { 230 msg(hsc($e->getMessage()), -1); 231 return false; 232 } 233 234 // fetch user info from backend 235 $user = $authtoken->getUser(); 236 $USERINFO = $auth->getUserData($user); 237 if (!$USERINFO) return false; 238 239 // the code is correct, set up user 240 $INPUT->server->set('REMOTE_USER', $user); 241 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 242 $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope'; 243 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 244 $_SESSION[DOKU_COOKIE]['auth']['token'] = $token; 245 246 return true; 247} 248 249/** 250 * Event hook callback for AUTH_LOGIN_CHECK 251 * 252 * @param array $evdata 253 * @return bool 254 * @throws Exception 255 */ 256function auth_login_wrapper($evdata) 257{ 258 return auth_login( 259 $evdata['user'], 260 $evdata['password'], 261 $evdata['sticky'], 262 $evdata['silent'] 263 ); 264} 265 266/** 267 * This tries to login the user based on the sent auth credentials 268 * 269 * The authentication works like this: if a username was given 270 * a new login is assumed and user/password are checked. If they 271 * are correct the password is encrypted with blowfish and stored 272 * together with the username in a cookie - the same info is stored 273 * in the session, too. Additonally a browserID is stored in the 274 * session. 275 * 276 * If no username was given the cookie is checked: if the username, 277 * crypted password and browserID match between session and cookie 278 * no further testing is done and the user is accepted 279 * 280 * If a cookie was found but no session info was availabe the 281 * blowfish encrypted password from the cookie is decrypted and 282 * together with username rechecked by calling this function again. 283 * 284 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 285 * are set. 286 * 287 * @param string $user Username 288 * @param string $pass Cleartext Password 289 * @param bool $sticky Cookie should not expire 290 * @param bool $silent Don't show error on bad auth 291 * @return bool true on successful auth 292 * @throws Exception 293 * 294 * @author Andreas Gohr <andi@splitbrain.org> 295 */ 296function auth_login($user, $pass, $sticky = false, $silent = false) 297{ 298 global $USERINFO; 299 global $conf; 300 global $lang; 301 /* @var AuthPlugin $auth */ 302 global $auth; 303 /* @var Input $INPUT */ 304 global $INPUT; 305 306 if (!$auth instanceof AuthPlugin) return false; 307 308 if (!empty($user)) { 309 //usual login 310 if (!empty($pass)) usleep(random_int(0, 250)); // add a random delay to prevent timing attacks #4491 311 if (!empty($pass) && $auth->checkPass($user, $pass)) { 312 // make logininfo globally available 313 $INPUT->server->set('REMOTE_USER', $user); 314 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 315 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); 316 return true; 317 } else { 318 //invalid credentials - log off 319 if (!$silent) { 320 http_status(403, 'Login failed'); 321 msg($lang['badlogin'], -1); 322 } 323 auth_logoff(); 324 return false; 325 } 326 } else { 327 // read cookie information 328 [$user, $sticky, $pass] = auth_getCookie(); 329 if ($user && $pass) { 330 // we got a cookie - see if we can trust it 331 332 // get session info 333 if (isset($_SESSION[DOKU_COOKIE])) { 334 $session = $_SESSION[DOKU_COOKIE]['auth'] ?? []; 335 if ( 336 isset($session['user']) && 337 isset($session['pass']) && 338 $auth->useSessionCache($user) && 339 ($session['time'] >= time() - $conf['auth_security_timeout']) && 340 ($session['user'] === $user) && 341 ($session['pass'] === sha1($pass)) && //still crypted 342 ($session['buid'] === auth_browseruid()) 343 ) { 344 // he has session, cookie and browser right - let him in 345 $INPUT->server->set('REMOTE_USER', $user); 346 $USERINFO = $session['info']; //FIXME move all references to session 347 return true; 348 } 349 } 350 // no we don't trust it yet - recheck pass but silent 351 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 352 $pass = auth_decrypt($pass, $secret); 353 return auth_login($user, $pass, $sticky, true); 354 } 355 } 356 //just to be sure 357 auth_logoff(true); 358 return false; 359} 360 361/** 362 * Builds a pseudo UID from browser and IP data 363 * 364 * This is neither unique nor unfakable - still it adds some 365 * security. Using the first part of the IP makes sure 366 * proxy farms like AOLs are still okay. 367 * 368 * @author Andreas Gohr <andi@splitbrain.org> 369 * 370 * @return string a SHA256 sum of various browser headers 371 */ 372function auth_browseruid() 373{ 374 /* @var Input $INPUT */ 375 global $INPUT; 376 377 $ip = clientIP(true); 378 // convert IP string to packed binary representation 379 $pip = inet_pton($ip); 380 381 $uid = implode("\n", [ 382 $INPUT->server->str('HTTP_USER_AGENT'), 383 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'), 384 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6) 385 ]); 386 return hash('sha256', $uid); 387} 388 389/** 390 * Creates a random key to encrypt the password in cookies 391 * 392 * This function tries to read the password for encrypting 393 * cookies from $conf['metadir'].'/_htcookiesalt' 394 * if no such file is found a random key is created and 395 * and stored in this file. 396 * 397 * @param bool $addsession if true, the sessionid is added to the salt 398 * @param bool $secure if security is more important than keeping the old value 399 * @return string 400 * @throws Exception 401 * 402 * @author Andreas Gohr <andi@splitbrain.org> 403 */ 404function auth_cookiesalt($addsession = false, $secure = false) 405{ 406 if (defined('SIMPLE_TEST')) { 407 return 'test'; 408 } 409 global $conf; 410 $file = $conf['metadir'] . '/_htcookiesalt'; 411 if ($secure || !file_exists($file)) { 412 $file = $conf['metadir'] . '/_htcookiesalt2'; 413 } 414 $salt = io_readFile($file); 415 if (empty($salt)) { 416 $salt = bin2hex(auth_randombytes(64)); 417 io_saveFile($file, $salt); 418 } 419 if ($addsession) { 420 $salt .= session_id(); 421 } 422 return $salt; 423} 424 425/** 426 * Return cryptographically secure random bytes. 427 * 428 * @param int $length number of bytes 429 * @return string cryptographically secure random bytes 430 * @throws Exception 431 * 432 * @author Niklas Keller <me@kelunik.com> 433 */ 434function auth_randombytes($length) 435{ 436 return random_bytes($length); 437} 438 439/** 440 * Cryptographically secure random number generator. 441 * 442 * @param int $min 443 * @param int $max 444 * @return int 445 * @throws Exception 446 * 447 * @author Niklas Keller <me@kelunik.com> 448 */ 449function auth_random($min, $max) 450{ 451 return random_int($min, $max); 452} 453 454/** 455 * Encrypt data using the given secret using AES 456 * 457 * The mode is CBC with a random initialization vector, the key is derived 458 * using pbkdf2. 459 * 460 * @param string $data The data that shall be encrypted 461 * @param string $secret The secret/password that shall be used 462 * @return string The ciphertext 463 * @throws Exception 464 */ 465function auth_encrypt($data, $secret) 466{ 467 $iv = auth_randombytes(16); 468 $cipher = new AES('cbc'); 469 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 470 $cipher->setIV($iv); 471 472 /* 473 this uses the encrypted IV as IV as suggested in 474 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C 475 for unique but necessarily random IVs. The resulting ciphertext is 476 compatible to ciphertext that was created using a "normal" IV. 477 */ 478 return $cipher->encrypt($iv . $data); 479} 480 481/** 482 * Decrypt the given AES ciphertext 483 * 484 * The mode is CBC, the key is derived using pbkdf2 485 * 486 * @param string $ciphertext The encrypted data 487 * @param string $secret The secret/password that shall be used 488 * @return string|null The decrypted data 489 */ 490function auth_decrypt($ciphertext, $secret) 491{ 492 $iv = substr($ciphertext, 0, 16); 493 $cipher = new AES('cbc'); 494 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 495 $cipher->setIV($iv); 496 497 try { 498 return $cipher->decrypt(substr($ciphertext, 16)); 499 } catch (BadDecryptionException $e) { 500 ErrorHandler::logException($e); 501 return null; 502 } 503} 504 505/** 506 * Log out the current user 507 * 508 * This clears all authentication data and thus log the user 509 * off. It also clears session data. 510 * 511 * @author Andreas Gohr <andi@splitbrain.org> 512 * 513 * @param bool $keepbc - when true, the breadcrumb data is not cleared 514 */ 515function auth_logoff($keepbc = false) 516{ 517 global $conf; 518 global $USERINFO; 519 /* @var AuthPlugin $auth */ 520 global $auth; 521 /* @var Input $INPUT */ 522 global $INPUT; 523 524 // make sure the session is writable (it usually is) 525 @session_start(); 526 527 if (isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 528 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 529 if (isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 530 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 531 if (isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 532 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 533 if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 534 unset($_SESSION[DOKU_COOKIE]['bc']); 535 $INPUT->server->remove('REMOTE_USER'); 536 $USERINFO = null; //FIXME 537 538 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 539 setcookie(DOKU_COOKIE, '', [ 540 'expires' => time() - 600000, 541 'path' => $cookieDir, 542 'secure' => ($conf['securecookie'] && Ip::isSsl()), 543 'httponly' => true, 544 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 545 ]); 546 547 if ($auth instanceof AuthPlugin) { 548 $auth->logOff(); 549 } 550} 551 552/** 553 * Check if a user is a manager 554 * 555 * Should usually be called without any parameters to check the current 556 * user. 557 * 558 * The info is available through $INFO['ismanager'], too 559 * 560 * @param string $user Username 561 * @param array $groups List of groups the user is in 562 * @param bool $adminonly when true checks if user is admin 563 * @param bool $recache set to true to refresh the cache 564 * @return bool 565 * @see auth_isadmin 566 * 567 * @author Andreas Gohr <andi@splitbrain.org> 568 */ 569function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false) 570{ 571 global $conf; 572 global $USERINFO; 573 /* @var AuthPlugin $auth */ 574 global $auth; 575 /* @var Input $INPUT */ 576 global $INPUT; 577 578 579 if (!$auth instanceof AuthPlugin) return false; 580 if (is_null($user)) { 581 if (!$INPUT->server->has('REMOTE_USER')) { 582 return false; 583 } else { 584 $user = $INPUT->server->str('REMOTE_USER'); 585 } 586 } 587 if (is_null($groups)) { 588 // checking the logged in user, or another one? 589 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) { 590 $groups = (array) $USERINFO['grps']; 591 } else { 592 $groups = $auth->getUserData($user); 593 $groups = $groups ? $groups['grps'] : []; 594 } 595 } 596 597 // prefer cached result 598 static $cache = []; 599 $cachekey = serialize([$user, $adminonly, $groups]); 600 if (!isset($cache[$cachekey]) || $recache) { 601 // check superuser match 602 $ok = auth_isMember($conf['superuser'], $user, $groups); 603 604 // check managers 605 if (!$ok && !$adminonly) { 606 $ok = auth_isMember($conf['manager'], $user, $groups); 607 } 608 609 $cache[$cachekey] = $ok; 610 } 611 612 return $cache[$cachekey]; 613} 614 615/** 616 * Check if a user is admin 617 * 618 * Alias to auth_ismanager with adminonly=true 619 * 620 * The info is available through $INFO['isadmin'], too 621 * 622 * @param string $user Username 623 * @param array $groups List of groups the user is in 624 * @param bool $recache set to true to refresh the cache 625 * @return bool 626 * @author Andreas Gohr <andi@splitbrain.org> 627 * @see auth_ismanager() 628 * 629 */ 630function auth_isadmin($user = null, $groups = null, $recache = false) 631{ 632 return auth_ismanager($user, $groups, true, $recache); 633} 634 635/** 636 * Match a user and his groups against a comma separated list of 637 * users and groups to determine membership status 638 * 639 * Note: all input should NOT be nameencoded. 640 * 641 * @param string $memberlist commaseparated list of allowed users and groups 642 * @param string $user user to match against 643 * @param array $groups groups the user is member of 644 * @return bool true for membership acknowledged 645 */ 646function auth_isMember($memberlist, $user, array $groups) 647{ 648 /* @var AuthPlugin $auth */ 649 global $auth; 650 if (!$auth instanceof AuthPlugin) return false; 651 652 // clean user and groups 653 if (!$auth->isCaseSensitive()) { 654 $user = PhpString::strtolower($user); 655 $groups = array_map(PhpString::strtolower(...), $groups); 656 } 657 $user = $auth->cleanUser($user); 658 $groups = array_map($auth->cleanGroup(...), $groups); 659 660 // extract the memberlist 661 $members = explode(',', $memberlist); 662 $members = array_map(trim(...), $members); 663 $members = array_unique($members); 664 $members = array_filter($members); 665 666 // compare cleaned values 667 foreach ($members as $member) { 668 if ($member == '@ALL') return true; 669 if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member); 670 if ($member[0] == '@') { 671 $member = $auth->cleanGroup(substr($member, 1)); 672 if (in_array($member, $groups)) return true; 673 } else { 674 $member = $auth->cleanUser($member); 675 if ($member == $user) return true; 676 } 677 } 678 679 // still here? not a member! 680 return false; 681} 682 683/** 684 * Convinience function for auth_aclcheck() 685 * 686 * This checks the permissions for the current user 687 * 688 * @author Andreas Gohr <andi@splitbrain.org> 689 * 690 * @param string $id page ID (needs to be resolved and cleaned) 691 * @return int permission level 692 */ 693function auth_quickaclcheck($id) 694{ 695 global $conf; 696 global $USERINFO; 697 /* @var Input $INPUT */ 698 global $INPUT; 699 # if no ACL is used always return upload rights 700 if (!$conf['useacl']) return AUTH_UPLOAD; 701 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []); 702} 703 704/** 705 * Build the ACL path for a media file. 706 * 707 * Media files do not have per-file ACLs; permissions are always evaluated against the namespace 708 * they live in. This returns the namespace wildcard path (e.g. "wiki:*" or "*" for root-namespace 709 * media) suitable for passing to auth_quickaclcheck() or auth_aclcheck(). 710 * 711 * @param string $id media ID (needs to be resolved and cleaned) 712 * @return string the ACL path to check 713 */ 714function mediaAclPath($id) 715{ 716 return ltrim(getNS($id) . ':*', ':'); 717} 718 719/** 720 * Returns the maximum rights a user has for the given ID or its namespace 721 * 722 * @author Andreas Gohr <andi@splitbrain.org> 723 * 724 * @triggers AUTH_ACL_CHECK 725 * @param string $id page ID (needs to be resolved and cleaned) 726 * @param string $user Username 727 * @param array|null $groups Array of groups the user is in 728 * @return int permission level 729 */ 730function auth_aclcheck($id, $user, $groups) 731{ 732 $data = [ 733 'id' => $id ?? '', 734 'user' => $user, 735 'groups' => $groups 736 ]; 737 738 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 739} 740 741/** 742 * default ACL check method 743 * 744 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 745 * 746 * @author Andreas Gohr <andi@splitbrain.org> 747 * 748 * @param array $data event data 749 * @return int permission level 750 */ 751function auth_aclcheck_cb($data) 752{ 753 $id =& $data['id']; 754 $user =& $data['user']; 755 $groups =& $data['groups']; 756 757 global $conf; 758 global $AUTH_ACL; 759 /* @var AuthPlugin $auth */ 760 global $auth; 761 762 // if no ACL is used always return upload rights 763 if (!$conf['useacl']) return AUTH_UPLOAD; 764 if (!$auth instanceof AuthPlugin) return AUTH_NONE; 765 if (!is_array($AUTH_ACL)) return AUTH_NONE; 766 767 //make sure groups is an array 768 if (!is_array($groups)) $groups = []; 769 770 //if user is superuser or in superusergroup return 255 (acl_admin) 771 if (auth_isadmin($user, $groups)) { 772 return AUTH_ADMIN; 773 } 774 775 if (!$auth->isCaseSensitive()) { 776 $user = PhpString::strtolower($user); 777 $groups = array_map(PhpString::strtolower(...), $groups); 778 } 779 $user = auth_nameencode($auth->cleanUser($user)); 780 $groups = array_map($auth->cleanGroup(...), $groups); 781 782 //prepend groups with @ and nameencode 783 foreach ($groups as &$group) { 784 $group = '@' . auth_nameencode($group); 785 } 786 787 $ns = getNS($id); 788 $perm = -1; 789 790 //add ALL group 791 $groups[] = '@ALL'; 792 793 //add User 794 if ($user) $groups[] = $user; 795 796 //check exact match first 797 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 798 if (count($matches)) { 799 foreach ($matches as $match) { 800 $match = preg_replace('/#.*$/', '', $match); //ignore comments 801 $acl = preg_split('/[ \t]+/', $match); 802 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 803 $acl[1] = PhpString::strtolower($acl[1]); 804 } 805 if (!in_array($acl[1], $groups)) { 806 continue; 807 } 808 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 809 if ($acl[2] > $perm) { 810 $perm = $acl[2]; 811 } 812 } 813 if ($perm > -1) { 814 //we had a match - return it 815 return (int) $perm; 816 } 817 } 818 819 //still here? do the namespace checks 820 if ($ns) { 821 $path = $ns . ':*'; 822 } else { 823 $path = '*'; //root document 824 } 825 826 do { 827 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 828 if (count($matches)) { 829 foreach ($matches as $match) { 830 $match = preg_replace('/#.*$/', '', $match); //ignore comments 831 $acl = preg_split('/[ \t]+/', $match); 832 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 833 $acl[1] = PhpString::strtolower($acl[1]); 834 } 835 if (!in_array($acl[1], $groups)) { 836 continue; 837 } 838 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 839 if ($acl[2] > $perm) { 840 $perm = $acl[2]; 841 } 842 } 843 //we had a match - return it 844 if ($perm != -1) { 845 return (int) $perm; 846 } 847 } 848 //get next higher namespace 849 $ns = getNS($ns); 850 851 if ($path != '*') { 852 $path = $ns . ':*'; 853 if ($path == ':*') $path = '*'; 854 } else { 855 //we did this already 856 //looks like there is something wrong with the ACL 857 //break here 858 msg('No ACL setup yet! Denying access to everyone.'); 859 return AUTH_NONE; 860 } 861 } while (1); //this should never loop endless 862 return AUTH_NONE; 863} 864 865/** 866 * Encode ASCII special chars 867 * 868 * Some auth backends allow special chars in their user and groupnames 869 * The special chars are encoded with this function. Only ASCII chars 870 * are encoded UTF-8 multibyte are left as is (different from usual 871 * urlencoding!). 872 * 873 * Decoding can be done with rawurldecode 874 * 875 * @author Andreas Gohr <gohr@cosmocode.de> 876 * @see rawurldecode() 877 * 878 * @param string $name 879 * @param bool $skip_group 880 * @return string 881 */ 882function auth_nameencode($name, $skip_group = false) 883{ 884 global $cache_authname; 885 $cache =& $cache_authname; 886 $name = (string) $name; 887 888 // never encode wildcard FS#1955 889 if ($name == '%USER%') return $name; 890 if ($name == '%GROUP%') return $name; 891 892 if (!isset($cache[$name][$skip_group])) { 893 if ($skip_group && $name[0] == '@') { 894 $cache[$name][$skip_group] = '@' . preg_replace_callback( 895 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 896 auth_nameencode_callback(...), 897 substr($name, 1) 898 ); 899 } else { 900 $cache[$name][$skip_group] = preg_replace_callback( 901 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 902 auth_nameencode_callback(...), 903 $name 904 ); 905 } 906 } 907 908 return $cache[$name][$skip_group]; 909} 910 911/** 912 * callback encodes the matches 913 * 914 * @param array $matches first complete match, next matching subpatterms 915 * @return string 916 */ 917function auth_nameencode_callback($matches) 918{ 919 return '%' . dechex(ord(substr($matches[1], -1))); 920} 921 922/** 923 * Create a pronouncable password 924 * 925 * The $foruser variable might be used by plugins to run additional password 926 * policy checks, but is not used by the default implementation 927 * 928 * @param string $foruser username for which the password is generated 929 * @return string pronouncable password 930 * @throws Exception 931 * 932 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 933 * @triggers AUTH_PASSWORD_GENERATE 934 * 935 * @author Andreas Gohr <andi@splitbrain.org> 936 */ 937function auth_pwgen($foruser = '') 938{ 939 $data = [ 940 'password' => '', 941 'foruser' => $foruser 942 ]; 943 944 $evt = new Event('AUTH_PASSWORD_GENERATE', $data); 945 if ($evt->advise_before(true)) { 946 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 947 $v = 'aeiou'; //vowels 948 $a = $c . $v; //both 949 $s = '!$%&?+*~#-_:.;,'; // specials 950 951 //use thre syllables... 952 for ($i = 0; $i < 3; $i++) { 953 $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 954 $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 955 $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 956 } 957 //... and add a nice number and special 958 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99); 959 } 960 $evt->advise_after(); 961 962 return $data['password']; 963} 964 965/** 966 * Sends a password to the given user 967 * 968 * @author Andreas Gohr <andi@splitbrain.org> 969 * 970 * @param string $user Login name of the user 971 * @param string $password The new password in clear text 972 * @return bool true on success 973 */ 974function auth_sendPassword($user, $password) 975{ 976 global $lang; 977 /* @var AuthPlugin $auth */ 978 global $auth; 979 if (!$auth instanceof AuthPlugin) return false; 980 981 $user = $auth->cleanUser($user); 982 $userinfo = $auth->getUserData($user, false); 983 984 if (!$userinfo['mail']) return false; 985 986 $text = rawLocale('password'); 987 $trep = [ 988 'FULLNAME' => $userinfo['name'], 989 'LOGIN' => $user, 990 'PASSWORD' => $password 991 ]; 992 993 $mail = new Mailer(); 994 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>'); 995 $mail->subject($lang['regpwmail']); 996 $mail->setBody($text, $trep); 997 return $mail->send(); 998} 999 1000/** 1001 * Register a new user 1002 * 1003 * This registers a new user - Data is read directly from $_POST 1004 * 1005 * @return bool true on success, false on any error 1006 * @throws Exception 1007 * 1008 * @author Andreas Gohr <andi@splitbrain.org> 1009 */ 1010function register() 1011{ 1012 global $lang; 1013 global $conf; 1014 /* @var AuthPlugin $auth */ 1015 global $auth; 1016 global $INPUT; 1017 1018 if (!$INPUT->post->bool('save')) return false; 1019 if (!actionOK('register')) return false; 1020 1021 // gather input 1022 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 1023 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 1024 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 1025 $pass = $INPUT->post->str('pass'); 1026 $passchk = $INPUT->post->str('passchk'); 1027 1028 if (empty($login) || empty($fullname) || empty($email)) { 1029 msg($lang['regmissing'], -1); 1030 return false; 1031 } 1032 1033 if ($conf['autopasswd']) { 1034 $pass = auth_pwgen($login); // automatically generate password 1035 } elseif (empty($pass) || empty($passchk)) { 1036 msg($lang['regmissing'], -1); // complain about missing passwords 1037 return false; 1038 } elseif ($pass != $passchk) { 1039 msg($lang['regbadpass'], -1); // complain about misspelled passwords 1040 return false; 1041 } 1042 1043 //check mail 1044 if (!mail_isvalid($email)) { 1045 msg($lang['regbadmail'], -1); 1046 return false; 1047 } 1048 1049 //okay try to create the user 1050 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) { 1051 msg($lang['regfail'], -1); 1052 return false; 1053 } 1054 1055 // send notification about the new user 1056 $subscription = new RegistrationSubscriptionSender(); 1057 $subscription->sendRegister($login, $fullname, $email); 1058 1059 // are we done? 1060 if (!$conf['autopasswd']) { 1061 msg($lang['regsuccess2'], 1); 1062 return true; 1063 } 1064 1065 // autogenerated password? then send password to user 1066 if (auth_sendPassword($login, $pass)) { 1067 msg($lang['regsuccess'], 1); 1068 return true; 1069 } else { 1070 msg($lang['regmailfail'], -1); 1071 return false; 1072 } 1073} 1074 1075/** 1076 * Update user profile 1077 * 1078 * @throws Exception 1079 * 1080 * @author Christopher Smith <chris@jalakai.co.uk> 1081 */ 1082function updateprofile() 1083{ 1084 global $conf; 1085 global $lang; 1086 /* @var AuthPlugin $auth */ 1087 global $auth; 1088 /* @var Input $INPUT */ 1089 global $INPUT; 1090 1091 if (!$INPUT->post->bool('save')) return false; 1092 if (!checkSecurityToken()) return false; 1093 1094 if (!actionOK('profile')) { 1095 msg($lang['profna'], -1); 1096 return false; 1097 } 1098 1099 $changes = []; 1100 $changes['pass'] = $INPUT->post->str('newpass'); 1101 $changes['name'] = $INPUT->post->str('fullname'); 1102 $changes['mail'] = $INPUT->post->str('email'); 1103 1104 // check misspelled passwords 1105 if ($changes['pass'] != $INPUT->post->str('passchk')) { 1106 msg($lang['regbadpass'], -1); 1107 return false; 1108 } 1109 1110 // clean fullname and email 1111 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1112 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 1113 1114 // no empty name and email (except the backend doesn't support them) 1115 if ( 1116 (empty($changes['name']) && $auth->canDo('modName')) || 1117 (empty($changes['mail']) && $auth->canDo('modMail')) 1118 ) { 1119 msg($lang['profnoempty'], -1); 1120 return false; 1121 } 1122 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 1123 msg($lang['regbadmail'], -1); 1124 return false; 1125 } 1126 1127 $changes = array_filter($changes); 1128 1129 // check for unavailable capabilities 1130 if (!$auth->canDo('modName')) unset($changes['name']); 1131 if (!$auth->canDo('modMail')) unset($changes['mail']); 1132 if (!$auth->canDo('modPass')) unset($changes['pass']); 1133 1134 // anything to do? 1135 if ($changes === []) { 1136 msg($lang['profnochange'], -1); 1137 return false; 1138 } 1139 1140 if ($conf['profileconfirm']) { 1141 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1142 msg($lang['badpassconfirm'], -1); 1143 return false; 1144 } 1145 } 1146 1147 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) { 1148 msg($lang['proffail'], -1); 1149 return false; 1150 } 1151 1152 if (array_key_exists('pass', $changes) && $changes['pass']) { 1153 // update cookie and session with the changed data 1154 [/* user */, $sticky, /* pass */] = auth_getCookie(); 1155 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1156 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1157 } else { 1158 // make sure the session is writable 1159 @session_start(); 1160 // invalidate session cache 1161 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0; 1162 session_write_close(); 1163 } 1164 1165 return true; 1166} 1167 1168/** 1169 * Delete the current logged-in user 1170 * 1171 * @return bool true on success, false on any error 1172 */ 1173function auth_deleteprofile() 1174{ 1175 global $conf; 1176 global $lang; 1177 /* @var AuthPlugin $auth */ 1178 global $auth; 1179 /* @var Input $INPUT */ 1180 global $INPUT; 1181 1182 if (!$INPUT->post->bool('delete')) return false; 1183 if (!checkSecurityToken()) return false; 1184 1185 // action prevented or auth module disallows 1186 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) { 1187 msg($lang['profnodelete'], -1); 1188 return false; 1189 } 1190 1191 if (!$INPUT->post->bool('confirm_delete')) { 1192 msg($lang['profconfdeletemissing'], -1); 1193 return false; 1194 } 1195 1196 if ($conf['profileconfirm']) { 1197 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1198 msg($lang['badpassconfirm'], -1); 1199 return false; 1200 } 1201 } 1202 1203 $deleted = []; 1204 $deleted[] = $INPUT->server->str('REMOTE_USER'); 1205 if ($auth->triggerUserMod('delete', [$deleted])) { 1206 // force and immediate logout including removing the sticky cookie 1207 auth_logoff(); 1208 return true; 1209 } 1210 1211 return false; 1212} 1213 1214/** 1215 * Send a new password 1216 * 1217 * This function handles both phases of the password reset: 1218 * 1219 * - handling the first request of password reset 1220 * - validating the password reset auth token 1221 * 1222 * @return bool true on success, false on any error 1223 * @throws Exception 1224 * 1225 * @author Andreas Gohr <andi@splitbrain.org> 1226 * @author Benoit Chesneau <benoit@bchesneau.info> 1227 * @author Chris Smith <chris@jalakai.co.uk> 1228 */ 1229function act_resendpwd() 1230{ 1231 global $lang; 1232 global $conf; 1233 /* @var AuthPlugin $auth */ 1234 global $auth; 1235 /* @var Input $INPUT */ 1236 global $INPUT; 1237 1238 if (!actionOK('resendpwd')) { 1239 msg($lang['resendna'], -1); 1240 return false; 1241 } 1242 1243 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1244 1245 if ($token) { 1246 // we're in token phase - get user info from token 1247 1248 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 1249 if (!file_exists($tfile)) { 1250 msg($lang['resendpwdbadauth'], -1); 1251 $INPUT->remove('pwauth'); 1252 return false; 1253 } 1254 // token is only valid for 3 days 1255 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1256 msg($lang['resendpwdbadauth'], -1); 1257 $INPUT->remove('pwauth'); 1258 @unlink($tfile); 1259 return false; 1260 } 1261 1262 $user = io_readfile($tfile); 1263 $userinfo = $auth->getUserData($user, false); 1264 if (!$userinfo['mail']) { 1265 msg($lang['resendpwdnouser'], -1); 1266 return false; 1267 } 1268 1269 if (!$conf['autopasswd']) { // we let the user choose a password 1270 $pass = $INPUT->str('pass'); 1271 1272 // password given correctly? 1273 if (!$pass) return false; 1274 if ($pass != $INPUT->str('passchk')) { 1275 msg($lang['regbadpass'], -1); 1276 return false; 1277 } 1278 1279 // change it 1280 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1281 msg($lang['proffail'], -1); 1282 return false; 1283 } 1284 } else { // autogenerate the password and send by mail 1285 $pass = auth_pwgen($user); 1286 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1287 msg($lang['proffail'], -1); 1288 return false; 1289 } 1290 1291 if (auth_sendPassword($user, $pass)) { 1292 msg($lang['resendpwdsuccess'], 1); 1293 } else { 1294 msg($lang['regmailfail'], -1); 1295 } 1296 } 1297 1298 @unlink($tfile); 1299 return true; 1300 } else { 1301 // we're in request phase 1302 1303 if (!$INPUT->post->bool('save')) return false; 1304 1305 if (!$INPUT->post->str('login')) { 1306 msg($lang['resendpwdmissing'], -1); 1307 return false; 1308 } else { 1309 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1310 } 1311 1312 $userinfo = $auth->getUserData($user, false); 1313 if (!$userinfo['mail']) { 1314 msg($lang['resendpwdnouser'], -1); 1315 return false; 1316 } 1317 1318 // generate auth token 1319 $token = md5(auth_randombytes(16)); // random secret 1320 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 1321 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&'); 1322 1323 io_saveFile($tfile, $user); 1324 1325 $text = rawLocale('pwconfirm'); 1326 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url]; 1327 1328 $mail = new Mailer(); 1329 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>'); 1330 $mail->subject($lang['regpwmail']); 1331 $mail->setBody($text, $trep); 1332 if ($mail->send()) { 1333 msg($lang['resendpwdconfirm'], 1); 1334 } else { 1335 msg($lang['regmailfail'], -1); 1336 } 1337 return true; 1338 } 1339 // never reached 1340} 1341 1342/** 1343 * Encrypts a password using the given method and salt 1344 * 1345 * If the selected method needs a salt and none was given, a random one 1346 * is chosen. 1347 * 1348 * You can pass null as the password to create an unusable hash. 1349 * 1350 * @author Andreas Gohr <andi@splitbrain.org> 1351 * 1352 * @param string $clear The clear text password 1353 * @param string $method The hashing method 1354 * @param string $salt A salt, null for random 1355 * @return string The crypted password 1356 */ 1357function auth_cryptPassword($clear, $method = '', $salt = null) 1358{ 1359 global $conf; 1360 1361 if ($clear === null) { 1362 return DOKU_UNUSABLE_PASSWORD; 1363 } 1364 1365 if (empty($method)) $method = $conf['passcrypt']; 1366 1367 $pass = new PassHash(); 1368 $call = 'hash_' . $method; 1369 1370 if (!method_exists($pass, $call)) { 1371 msg("Unsupported crypt method $method", -1); 1372 return false; 1373 } 1374 1375 return $pass->$call($clear, $salt); 1376} 1377 1378/** 1379 * Verifies a cleartext password against a crypted hash 1380 * 1381 * @param string $clear The clear text password 1382 * @param string $crypt The hash to compare with 1383 * @return bool true if both match 1384 * @throws Exception 1385 * 1386 * @author Andreas Gohr <andi@splitbrain.org> 1387 */ 1388function auth_verifyPassword($clear, $crypt) 1389{ 1390 if ($crypt === DOKU_UNUSABLE_PASSWORD) { 1391 return false; 1392 } 1393 1394 $pass = new PassHash(); 1395 return $pass->verify_hash($clear, $crypt); 1396} 1397 1398/** 1399 * Set the authentication cookie and add user identification data to the session 1400 * 1401 * @param string $user username 1402 * @param string $pass encrypted password 1403 * @param bool $sticky whether or not the cookie will last beyond the session 1404 * @return bool 1405 */ 1406function auth_setCookie($user, $pass, $sticky) 1407{ 1408 global $conf; 1409 /* @var AuthPlugin $auth */ 1410 global $auth; 1411 global $USERINFO; 1412 1413 if (!$auth instanceof AuthPlugin) return false; 1414 $USERINFO = $auth->getUserData($user); 1415 1416 // set cookie 1417 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass); 1418 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1419 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1420 setcookie(DOKU_COOKIE, $cookie, [ 1421 'expires' => $time, 1422 'path' => $cookieDir, 1423 'secure' => ($conf['securecookie'] && Ip::isSsl()), 1424 'httponly' => true, 1425 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 1426 ]); 1427 1428 // set session 1429 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1430 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1431 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1432 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1433 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1434 1435 return true; 1436} 1437 1438/** 1439 * Returns the user, (encrypted) password and sticky bit from cookie 1440 * 1441 * @returns array 1442 */ 1443function auth_getCookie() 1444{ 1445 if (!isset($_COOKIE[DOKU_COOKIE])) { 1446 return [null, null, null]; 1447 } 1448 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, ''); 1449 $sticky = (bool) $sticky; 1450 $pass = base64_decode($pass); 1451 $user = base64_decode($user); 1452 return [$user, $sticky, $pass]; 1453} 1454 1455//Setup VIM: ex: et ts=2 : 1456