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 (substr($key, 0, 5) === '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 ($session !== []) && 337 $auth->useSessionCache($user) && 338 ($session['time'] >= time() - $conf['auth_security_timeout']) && 339 ($session['user'] == $user) && 340 ($session['pass'] == sha1($pass)) && //still crypted 341 ($session['buid'] == auth_browseruid()) 342 ) { 343 // he has session, cookie and browser right - let him in 344 $INPUT->server->set('REMOTE_USER', $user); 345 $USERINFO = $session['info']; //FIXME move all references to session 346 return true; 347 } 348 } 349 // no we don't trust it yet - recheck pass but silent 350 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 351 $pass = auth_decrypt($pass, $secret); 352 return auth_login($user, $pass, $sticky, true); 353 } 354 } 355 //just to be sure 356 auth_logoff(true); 357 return false; 358} 359 360/** 361 * Builds a pseudo UID from browser and IP data 362 * 363 * This is neither unique nor unfakable - still it adds some 364 * security. Using the first part of the IP makes sure 365 * proxy farms like AOLs are still okay. 366 * 367 * @author Andreas Gohr <andi@splitbrain.org> 368 * 369 * @return string a SHA256 sum of various browser headers 370 */ 371function auth_browseruid() 372{ 373 /* @var Input $INPUT */ 374 global $INPUT; 375 376 $ip = clientIP(true); 377 // convert IP string to packed binary representation 378 $pip = inet_pton($ip); 379 380 $uid = implode("\n", [ 381 $INPUT->server->str('HTTP_USER_AGENT'), 382 $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'), 383 substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6) 384 ]); 385 return hash('sha256', $uid); 386} 387 388/** 389 * Creates a random key to encrypt the password in cookies 390 * 391 * This function tries to read the password for encrypting 392 * cookies from $conf['metadir'].'/_htcookiesalt' 393 * if no such file is found a random key is created and 394 * and stored in this file. 395 * 396 * @param bool $addsession if true, the sessionid is added to the salt 397 * @param bool $secure if security is more important than keeping the old value 398 * @return string 399 * @throws Exception 400 * 401 * @author Andreas Gohr <andi@splitbrain.org> 402 */ 403function auth_cookiesalt($addsession = false, $secure = false) 404{ 405 if (defined('SIMPLE_TEST')) { 406 return 'test'; 407 } 408 global $conf; 409 $file = $conf['metadir'] . '/_htcookiesalt'; 410 if ($secure || !file_exists($file)) { 411 $file = $conf['metadir'] . '/_htcookiesalt2'; 412 } 413 $salt = io_readFile($file); 414 if (empty($salt)) { 415 $salt = bin2hex(auth_randombytes(64)); 416 io_saveFile($file, $salt); 417 } 418 if ($addsession) { 419 $salt .= session_id(); 420 } 421 return $salt; 422} 423 424/** 425 * Return cryptographically secure random bytes. 426 * 427 * @param int $length number of bytes 428 * @return string cryptographically secure random bytes 429 * @throws Exception 430 * 431 * @author Niklas Keller <me@kelunik.com> 432 */ 433function auth_randombytes($length) 434{ 435 return random_bytes($length); 436} 437 438/** 439 * Cryptographically secure random number generator. 440 * 441 * @param int $min 442 * @param int $max 443 * @return int 444 * @throws Exception 445 * 446 * @author Niklas Keller <me@kelunik.com> 447 */ 448function auth_random($min, $max) 449{ 450 return random_int($min, $max); 451} 452 453/** 454 * Encrypt data using the given secret using AES 455 * 456 * The mode is CBC with a random initialization vector, the key is derived 457 * using pbkdf2. 458 * 459 * @param string $data The data that shall be encrypted 460 * @param string $secret The secret/password that shall be used 461 * @return string The ciphertext 462 * @throws Exception 463 */ 464function auth_encrypt($data, $secret) 465{ 466 $iv = auth_randombytes(16); 467 $cipher = new AES('cbc'); 468 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 469 $cipher->setIV($iv); 470 471 /* 472 this uses the encrypted IV as IV as suggested in 473 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C 474 for unique but necessarily random IVs. The resulting ciphertext is 475 compatible to ciphertext that was created using a "normal" IV. 476 */ 477 return $cipher->encrypt($iv . $data); 478} 479 480/** 481 * Decrypt the given AES ciphertext 482 * 483 * The mode is CBC, the key is derived using pbkdf2 484 * 485 * @param string $ciphertext The encrypted data 486 * @param string $secret The secret/password that shall be used 487 * @return string|null The decrypted data 488 */ 489function auth_decrypt($ciphertext, $secret) 490{ 491 $iv = substr($ciphertext, 0, 16); 492 $cipher = new AES('cbc'); 493 $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 494 $cipher->setIV($iv); 495 496 try { 497 return $cipher->decrypt(substr($ciphertext, 16)); 498 } catch (BadDecryptionException $e) { 499 ErrorHandler::logException($e); 500 return null; 501 } 502} 503 504/** 505 * Log out the current user 506 * 507 * This clears all authentication data and thus log the user 508 * off. It also clears session data. 509 * 510 * @author Andreas Gohr <andi@splitbrain.org> 511 * 512 * @param bool $keepbc - when true, the breadcrumb data is not cleared 513 */ 514function auth_logoff($keepbc = false) 515{ 516 global $conf; 517 global $USERINFO; 518 /* @var AuthPlugin $auth */ 519 global $auth; 520 /* @var Input $INPUT */ 521 global $INPUT; 522 523 // make sure the session is writable (it usually is) 524 @session_start(); 525 526 if (isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 527 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 528 if (isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 529 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 530 if (isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 531 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 532 if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 533 unset($_SESSION[DOKU_COOKIE]['bc']); 534 $INPUT->server->remove('REMOTE_USER'); 535 $USERINFO = null; //FIXME 536 537 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 538 setcookie(DOKU_COOKIE, '', [ 539 'expires' => time() - 600000, 540 'path' => $cookieDir, 541 'secure' => ($conf['securecookie'] && Ip::isSsl()), 542 'httponly' => true, 543 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 544 ]); 545 546 if ($auth instanceof AuthPlugin) { 547 $auth->logOff(); 548 } 549} 550 551/** 552 * Check if a user is a manager 553 * 554 * Should usually be called without any parameters to check the current 555 * user. 556 * 557 * The info is available through $INFO['ismanager'], too 558 * 559 * @param string $user Username 560 * @param array $groups List of groups the user is in 561 * @param bool $adminonly when true checks if user is admin 562 * @param bool $recache set to true to refresh the cache 563 * @return bool 564 * @see auth_isadmin 565 * 566 * @author Andreas Gohr <andi@splitbrain.org> 567 */ 568function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false) 569{ 570 global $conf; 571 global $USERINFO; 572 /* @var AuthPlugin $auth */ 573 global $auth; 574 /* @var Input $INPUT */ 575 global $INPUT; 576 577 578 if (!$auth instanceof AuthPlugin) return false; 579 if (is_null($user)) { 580 if (!$INPUT->server->has('REMOTE_USER')) { 581 return false; 582 } else { 583 $user = $INPUT->server->str('REMOTE_USER'); 584 } 585 } 586 if (is_null($groups)) { 587 // checking the logged in user, or another one? 588 if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) { 589 $groups = (array) $USERINFO['grps']; 590 } else { 591 $groups = $auth->getUserData($user); 592 $groups = $groups ? $groups['grps'] : []; 593 } 594 } 595 596 // prefer cached result 597 static $cache = []; 598 $cachekey = serialize([$user, $adminonly, $groups]); 599 if (!isset($cache[$cachekey]) || $recache) { 600 // check superuser match 601 $ok = auth_isMember($conf['superuser'], $user, $groups); 602 603 // check managers 604 if (!$ok && !$adminonly) { 605 $ok = auth_isMember($conf['manager'], $user, $groups); 606 } 607 608 $cache[$cachekey] = $ok; 609 } 610 611 return $cache[$cachekey]; 612} 613 614/** 615 * Check if a user is admin 616 * 617 * Alias to auth_ismanager with adminonly=true 618 * 619 * The info is available through $INFO['isadmin'], too 620 * 621 * @param string $user Username 622 * @param array $groups List of groups the user is in 623 * @param bool $recache set to true to refresh the cache 624 * @return bool 625 * @author Andreas Gohr <andi@splitbrain.org> 626 * @see auth_ismanager() 627 * 628 */ 629function auth_isadmin($user = null, $groups = null, $recache = false) 630{ 631 return auth_ismanager($user, $groups, true, $recache); 632} 633 634/** 635 * Match a user and his groups against a comma separated list of 636 * users and groups to determine membership status 637 * 638 * Note: all input should NOT be nameencoded. 639 * 640 * @param string $memberlist commaseparated list of allowed users and groups 641 * @param string $user user to match against 642 * @param array $groups groups the user is member of 643 * @return bool true for membership acknowledged 644 */ 645function auth_isMember($memberlist, $user, array $groups) 646{ 647 /* @var AuthPlugin $auth */ 648 global $auth; 649 if (!$auth instanceof AuthPlugin) return false; 650 651 // clean user and groups 652 if (!$auth->isCaseSensitive()) { 653 $user = PhpString::strtolower($user); 654 $groups = array_map([PhpString::class, 'strtolower'], $groups); 655 } 656 $user = $auth->cleanUser($user); 657 $groups = array_map([$auth, 'cleanGroup'], $groups); 658 659 // extract the memberlist 660 $members = explode(',', $memberlist); 661 $members = array_map('trim', $members); 662 $members = array_unique($members); 663 $members = array_filter($members); 664 665 // compare cleaned values 666 foreach ($members as $member) { 667 if ($member == '@ALL') return true; 668 if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member); 669 if ($member[0] == '@') { 670 $member = $auth->cleanGroup(substr($member, 1)); 671 if (in_array($member, $groups)) return true; 672 } else { 673 $member = $auth->cleanUser($member); 674 if ($member == $user) return true; 675 } 676 } 677 678 // still here? not a member! 679 return false; 680} 681 682/** 683 * Convinience function for auth_aclcheck() 684 * 685 * This checks the permissions for the current user 686 * 687 * @author Andreas Gohr <andi@splitbrain.org> 688 * 689 * @param string $id page ID (needs to be resolved and cleaned) 690 * @return int permission level 691 */ 692function auth_quickaclcheck($id) 693{ 694 global $conf; 695 global $USERINFO; 696 /* @var Input $INPUT */ 697 global $INPUT; 698 # if no ACL is used always return upload rights 699 if (!$conf['useacl']) return AUTH_UPLOAD; 700 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []); 701} 702 703/** 704 * Returns the maximum rights a user has for the given ID or its namespace 705 * 706 * @author Andreas Gohr <andi@splitbrain.org> 707 * 708 * @triggers AUTH_ACL_CHECK 709 * @param string $id page ID (needs to be resolved and cleaned) 710 * @param string $user Username 711 * @param array|null $groups Array of groups the user is in 712 * @return int permission level 713 */ 714function auth_aclcheck($id, $user, $groups) 715{ 716 $data = [ 717 'id' => $id ?? '', 718 'user' => $user, 719 'groups' => $groups 720 ]; 721 722 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 723} 724 725/** 726 * default ACL check method 727 * 728 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 729 * 730 * @author Andreas Gohr <andi@splitbrain.org> 731 * 732 * @param array $data event data 733 * @return int permission level 734 */ 735function auth_aclcheck_cb($data) 736{ 737 $id =& $data['id']; 738 $user =& $data['user']; 739 $groups =& $data['groups']; 740 741 global $conf; 742 global $AUTH_ACL; 743 /* @var AuthPlugin $auth */ 744 global $auth; 745 746 // if no ACL is used always return upload rights 747 if (!$conf['useacl']) return AUTH_UPLOAD; 748 if (!$auth instanceof AuthPlugin) return AUTH_NONE; 749 if (!is_array($AUTH_ACL)) return AUTH_NONE; 750 751 //make sure groups is an array 752 if (!is_array($groups)) $groups = []; 753 754 //if user is superuser or in superusergroup return 255 (acl_admin) 755 if (auth_isadmin($user, $groups)) { 756 return AUTH_ADMIN; 757 } 758 759 if (!$auth->isCaseSensitive()) { 760 $user = PhpString::strtolower($user); 761 $groups = array_map([PhpString::class, 'strtolower'], $groups); 762 } 763 $user = auth_nameencode($auth->cleanUser($user)); 764 $groups = array_map([$auth, 'cleanGroup'], $groups); 765 766 //prepend groups with @ and nameencode 767 foreach ($groups as &$group) { 768 $group = '@' . auth_nameencode($group); 769 } 770 771 $ns = getNS($id); 772 $perm = -1; 773 774 //add ALL group 775 $groups[] = '@ALL'; 776 777 //add User 778 if ($user) $groups[] = $user; 779 780 //check exact match first 781 $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 782 if (count($matches)) { 783 foreach ($matches as $match) { 784 $match = preg_replace('/#.*$/', '', $match); //ignore comments 785 $acl = preg_split('/[ \t]+/', $match); 786 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 787 $acl[1] = PhpString::strtolower($acl[1]); 788 } 789 if (!in_array($acl[1], $groups)) { 790 continue; 791 } 792 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 793 if ($acl[2] > $perm) { 794 $perm = $acl[2]; 795 } 796 } 797 if ($perm > -1) { 798 //we had a match - return it 799 return (int) $perm; 800 } 801 } 802 803 //still here? do the namespace checks 804 if ($ns) { 805 $path = $ns . ':*'; 806 } else { 807 $path = '*'; //root document 808 } 809 810 do { 811 $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 812 if (count($matches)) { 813 foreach ($matches as $match) { 814 $match = preg_replace('/#.*$/', '', $match); //ignore comments 815 $acl = preg_split('/[ \t]+/', $match); 816 if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 817 $acl[1] = PhpString::strtolower($acl[1]); 818 } 819 if (!in_array($acl[1], $groups)) { 820 continue; 821 } 822 if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 823 if ($acl[2] > $perm) { 824 $perm = $acl[2]; 825 } 826 } 827 //we had a match - return it 828 if ($perm != -1) { 829 return (int) $perm; 830 } 831 } 832 //get next higher namespace 833 $ns = getNS($ns); 834 835 if ($path != '*') { 836 $path = $ns . ':*'; 837 if ($path == ':*') $path = '*'; 838 } else { 839 //we did this already 840 //looks like there is something wrong with the ACL 841 //break here 842 msg('No ACL setup yet! Denying access to everyone.'); 843 return AUTH_NONE; 844 } 845 } while (1); //this should never loop endless 846 return AUTH_NONE; 847} 848 849/** 850 * Encode ASCII special chars 851 * 852 * Some auth backends allow special chars in their user and groupnames 853 * The special chars are encoded with this function. Only ASCII chars 854 * are encoded UTF-8 multibyte are left as is (different from usual 855 * urlencoding!). 856 * 857 * Decoding can be done with rawurldecode 858 * 859 * @author Andreas Gohr <gohr@cosmocode.de> 860 * @see rawurldecode() 861 * 862 * @param string $name 863 * @param bool $skip_group 864 * @return string 865 */ 866function auth_nameencode($name, $skip_group = false) 867{ 868 global $cache_authname; 869 $cache =& $cache_authname; 870 $name = (string) $name; 871 872 // never encode wildcard FS#1955 873 if ($name == '%USER%') return $name; 874 if ($name == '%GROUP%') return $name; 875 876 if (!isset($cache[$name][$skip_group])) { 877 if ($skip_group && $name[0] == '@') { 878 $cache[$name][$skip_group] = '@' . preg_replace_callback( 879 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 880 'auth_nameencode_callback', 881 substr($name, 1) 882 ); 883 } else { 884 $cache[$name][$skip_group] = preg_replace_callback( 885 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 886 'auth_nameencode_callback', 887 $name 888 ); 889 } 890 } 891 892 return $cache[$name][$skip_group]; 893} 894 895/** 896 * callback encodes the matches 897 * 898 * @param array $matches first complete match, next matching subpatterms 899 * @return string 900 */ 901function auth_nameencode_callback($matches) 902{ 903 return '%' . dechex(ord(substr($matches[1], -1))); 904} 905 906/** 907 * Create a pronouncable password 908 * 909 * The $foruser variable might be used by plugins to run additional password 910 * policy checks, but is not used by the default implementation 911 * 912 * @param string $foruser username for which the password is generated 913 * @return string pronouncable password 914 * @throws Exception 915 * 916 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 917 * @triggers AUTH_PASSWORD_GENERATE 918 * 919 * @author Andreas Gohr <andi@splitbrain.org> 920 */ 921function auth_pwgen($foruser = '') 922{ 923 $data = [ 924 'password' => '', 925 'foruser' => $foruser 926 ]; 927 928 $evt = new Event('AUTH_PASSWORD_GENERATE', $data); 929 if ($evt->advise_before(true)) { 930 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 931 $v = 'aeiou'; //vowels 932 $a = $c . $v; //both 933 $s = '!$%&?+*~#-_:.;,'; // specials 934 935 //use thre syllables... 936 for ($i = 0; $i < 3; $i++) { 937 $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 938 $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 939 $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 940 } 941 //... and add a nice number and special 942 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99); 943 } 944 $evt->advise_after(); 945 946 return $data['password']; 947} 948 949/** 950 * Sends a password to the given user 951 * 952 * @author Andreas Gohr <andi@splitbrain.org> 953 * 954 * @param string $user Login name of the user 955 * @param string $password The new password in clear text 956 * @return bool true on success 957 */ 958function auth_sendPassword($user, $password) 959{ 960 global $lang; 961 /* @var AuthPlugin $auth */ 962 global $auth; 963 if (!$auth instanceof AuthPlugin) return false; 964 965 $user = $auth->cleanUser($user); 966 $userinfo = $auth->getUserData($user, false); 967 968 if (!$userinfo['mail']) return false; 969 970 $text = rawLocale('password'); 971 $trep = [ 972 'FULLNAME' => $userinfo['name'], 973 'LOGIN' => $user, 974 'PASSWORD' => $password 975 ]; 976 977 $mail = new Mailer(); 978 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>'); 979 $mail->subject($lang['regpwmail']); 980 $mail->setBody($text, $trep); 981 return $mail->send(); 982} 983 984/** 985 * Register a new user 986 * 987 * This registers a new user - Data is read directly from $_POST 988 * 989 * @return bool true on success, false on any error 990 * @throws Exception 991 * 992 * @author Andreas Gohr <andi@splitbrain.org> 993 */ 994function register() 995{ 996 global $lang; 997 global $conf; 998 /* @var AuthPlugin $auth */ 999 global $auth; 1000 global $INPUT; 1001 1002 if (!$INPUT->post->bool('save')) return false; 1003 if (!actionOK('register')) return false; 1004 1005 // gather input 1006 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 1007 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 1008 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 1009 $pass = $INPUT->post->str('pass'); 1010 $passchk = $INPUT->post->str('passchk'); 1011 1012 if (empty($login) || empty($fullname) || empty($email)) { 1013 msg($lang['regmissing'], -1); 1014 return false; 1015 } 1016 1017 if ($conf['autopasswd']) { 1018 $pass = auth_pwgen($login); // automatically generate password 1019 } elseif (empty($pass) || empty($passchk)) { 1020 msg($lang['regmissing'], -1); // complain about missing passwords 1021 return false; 1022 } elseif ($pass != $passchk) { 1023 msg($lang['regbadpass'], -1); // complain about misspelled passwords 1024 return false; 1025 } 1026 1027 //check mail 1028 if (!mail_isvalid($email)) { 1029 msg($lang['regbadmail'], -1); 1030 return false; 1031 } 1032 1033 //okay try to create the user 1034 if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) { 1035 msg($lang['regfail'], -1); 1036 return false; 1037 } 1038 1039 // send notification about the new user 1040 $subscription = new RegistrationSubscriptionSender(); 1041 $subscription->sendRegister($login, $fullname, $email); 1042 1043 // are we done? 1044 if (!$conf['autopasswd']) { 1045 msg($lang['regsuccess2'], 1); 1046 return true; 1047 } 1048 1049 // autogenerated password? then send password to user 1050 if (auth_sendPassword($login, $pass)) { 1051 msg($lang['regsuccess'], 1); 1052 return true; 1053 } else { 1054 msg($lang['regmailfail'], -1); 1055 return false; 1056 } 1057} 1058 1059/** 1060 * Update user profile 1061 * 1062 * @throws Exception 1063 * 1064 * @author Christopher Smith <chris@jalakai.co.uk> 1065 */ 1066function updateprofile() 1067{ 1068 global $conf; 1069 global $lang; 1070 /* @var AuthPlugin $auth */ 1071 global $auth; 1072 /* @var Input $INPUT */ 1073 global $INPUT; 1074 1075 if (!$INPUT->post->bool('save')) return false; 1076 if (!checkSecurityToken()) return false; 1077 1078 if (!actionOK('profile')) { 1079 msg($lang['profna'], -1); 1080 return false; 1081 } 1082 1083 $changes = []; 1084 $changes['pass'] = $INPUT->post->str('newpass'); 1085 $changes['name'] = $INPUT->post->str('fullname'); 1086 $changes['mail'] = $INPUT->post->str('email'); 1087 1088 // check misspelled passwords 1089 if ($changes['pass'] != $INPUT->post->str('passchk')) { 1090 msg($lang['regbadpass'], -1); 1091 return false; 1092 } 1093 1094 // clean fullname and email 1095 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1096 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 1097 1098 // no empty name and email (except the backend doesn't support them) 1099 if ( 1100 (empty($changes['name']) && $auth->canDo('modName')) || 1101 (empty($changes['mail']) && $auth->canDo('modMail')) 1102 ) { 1103 msg($lang['profnoempty'], -1); 1104 return false; 1105 } 1106 if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 1107 msg($lang['regbadmail'], -1); 1108 return false; 1109 } 1110 1111 $changes = array_filter($changes); 1112 1113 // check for unavailable capabilities 1114 if (!$auth->canDo('modName')) unset($changes['name']); 1115 if (!$auth->canDo('modMail')) unset($changes['mail']); 1116 if (!$auth->canDo('modPass')) unset($changes['pass']); 1117 1118 // anything to do? 1119 if ($changes === []) { 1120 msg($lang['profnochange'], -1); 1121 return false; 1122 } 1123 1124 if ($conf['profileconfirm']) { 1125 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1126 msg($lang['badpassconfirm'], -1); 1127 return false; 1128 } 1129 } 1130 1131 if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) { 1132 msg($lang['proffail'], -1); 1133 return false; 1134 } 1135 1136 if (array_key_exists('pass', $changes) && $changes['pass']) { 1137 // update cookie and session with the changed data 1138 [/* user */, $sticky, /* pass */] = auth_getCookie(); 1139 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1140 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1141 } else { 1142 // make sure the session is writable 1143 @session_start(); 1144 // invalidate session cache 1145 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0; 1146 session_write_close(); 1147 } 1148 1149 return true; 1150} 1151 1152/** 1153 * Delete the current logged-in user 1154 * 1155 * @return bool true on success, false on any error 1156 */ 1157function auth_deleteprofile() 1158{ 1159 global $conf; 1160 global $lang; 1161 /* @var AuthPlugin $auth */ 1162 global $auth; 1163 /* @var Input $INPUT */ 1164 global $INPUT; 1165 1166 if (!$INPUT->post->bool('delete')) return false; 1167 if (!checkSecurityToken()) return false; 1168 1169 // action prevented or auth module disallows 1170 if (!actionOK('profile_delete') || !$auth->canDo('delUser')) { 1171 msg($lang['profnodelete'], -1); 1172 return false; 1173 } 1174 1175 if (!$INPUT->post->bool('confirm_delete')) { 1176 msg($lang['profconfdeletemissing'], -1); 1177 return false; 1178 } 1179 1180 if ($conf['profileconfirm']) { 1181 if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1182 msg($lang['badpassconfirm'], -1); 1183 return false; 1184 } 1185 } 1186 1187 $deleted = []; 1188 $deleted[] = $INPUT->server->str('REMOTE_USER'); 1189 if ($auth->triggerUserMod('delete', [$deleted])) { 1190 // force and immediate logout including removing the sticky cookie 1191 auth_logoff(); 1192 return true; 1193 } 1194 1195 return false; 1196} 1197 1198/** 1199 * Send a new password 1200 * 1201 * This function handles both phases of the password reset: 1202 * 1203 * - handling the first request of password reset 1204 * - validating the password reset auth token 1205 * 1206 * @return bool true on success, false on any error 1207 * @throws Exception 1208 * 1209 * @author Andreas Gohr <andi@splitbrain.org> 1210 * @author Benoit Chesneau <benoit@bchesneau.info> 1211 * @author Chris Smith <chris@jalakai.co.uk> 1212 */ 1213function act_resendpwd() 1214{ 1215 global $lang; 1216 global $conf; 1217 /* @var AuthPlugin $auth */ 1218 global $auth; 1219 /* @var Input $INPUT */ 1220 global $INPUT; 1221 1222 if (!actionOK('resendpwd')) { 1223 msg($lang['resendna'], -1); 1224 return false; 1225 } 1226 1227 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1228 1229 if ($token) { 1230 // we're in token phase - get user info from token 1231 1232 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 1233 if (!file_exists($tfile)) { 1234 msg($lang['resendpwdbadauth'], -1); 1235 $INPUT->remove('pwauth'); 1236 return false; 1237 } 1238 // token is only valid for 3 days 1239 if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1240 msg($lang['resendpwdbadauth'], -1); 1241 $INPUT->remove('pwauth'); 1242 @unlink($tfile); 1243 return false; 1244 } 1245 1246 $user = io_readfile($tfile); 1247 $userinfo = $auth->getUserData($user, false); 1248 if (!$userinfo['mail']) { 1249 msg($lang['resendpwdnouser'], -1); 1250 return false; 1251 } 1252 1253 if (!$conf['autopasswd']) { // we let the user choose a password 1254 $pass = $INPUT->str('pass'); 1255 1256 // password given correctly? 1257 if (!$pass) return false; 1258 if ($pass != $INPUT->str('passchk')) { 1259 msg($lang['regbadpass'], -1); 1260 return false; 1261 } 1262 1263 // change it 1264 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1265 msg($lang['proffail'], -1); 1266 return false; 1267 } 1268 } else { // autogenerate the password and send by mail 1269 $pass = auth_pwgen($user); 1270 if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1271 msg($lang['proffail'], -1); 1272 return false; 1273 } 1274 1275 if (auth_sendPassword($user, $pass)) { 1276 msg($lang['resendpwdsuccess'], 1); 1277 } else { 1278 msg($lang['regmailfail'], -1); 1279 } 1280 } 1281 1282 @unlink($tfile); 1283 return true; 1284 } else { 1285 // we're in request phase 1286 1287 if (!$INPUT->post->bool('save')) return false; 1288 1289 if (!$INPUT->post->str('login')) { 1290 msg($lang['resendpwdmissing'], -1); 1291 return false; 1292 } else { 1293 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1294 } 1295 1296 $userinfo = $auth->getUserData($user, false); 1297 if (!$userinfo['mail']) { 1298 msg($lang['resendpwdnouser'], -1); 1299 return false; 1300 } 1301 1302 // generate auth token 1303 $token = md5(auth_randombytes(16)); // random secret 1304 $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 1305 $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&'); 1306 1307 io_saveFile($tfile, $user); 1308 1309 $text = rawLocale('pwconfirm'); 1310 $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url]; 1311 1312 $mail = new Mailer(); 1313 $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>'); 1314 $mail->subject($lang['regpwmail']); 1315 $mail->setBody($text, $trep); 1316 if ($mail->send()) { 1317 msg($lang['resendpwdconfirm'], 1); 1318 } else { 1319 msg($lang['regmailfail'], -1); 1320 } 1321 return true; 1322 } 1323 // never reached 1324} 1325 1326/** 1327 * Encrypts a password using the given method and salt 1328 * 1329 * If the selected method needs a salt and none was given, a random one 1330 * is chosen. 1331 * 1332 * You can pass null as the password to create an unusable hash. 1333 * 1334 * @author Andreas Gohr <andi@splitbrain.org> 1335 * 1336 * @param string $clear The clear text password 1337 * @param string $method The hashing method 1338 * @param string $salt A salt, null for random 1339 * @return string The crypted password 1340 */ 1341function auth_cryptPassword($clear, $method = '', $salt = null) 1342{ 1343 global $conf; 1344 1345 if ($clear === null) { 1346 return DOKU_UNUSABLE_PASSWORD; 1347 } 1348 1349 if (empty($method)) $method = $conf['passcrypt']; 1350 1351 $pass = new PassHash(); 1352 $call = 'hash_' . $method; 1353 1354 if (!method_exists($pass, $call)) { 1355 msg("Unsupported crypt method $method", -1); 1356 return false; 1357 } 1358 1359 return $pass->$call($clear, $salt); 1360} 1361 1362/** 1363 * Verifies a cleartext password against a crypted hash 1364 * 1365 * @param string $clear The clear text password 1366 * @param string $crypt The hash to compare with 1367 * @return bool true if both match 1368 * @throws Exception 1369 * 1370 * @author Andreas Gohr <andi@splitbrain.org> 1371 */ 1372function auth_verifyPassword($clear, $crypt) 1373{ 1374 if ($crypt === DOKU_UNUSABLE_PASSWORD) { 1375 return false; 1376 } 1377 1378 $pass = new PassHash(); 1379 return $pass->verify_hash($clear, $crypt); 1380} 1381 1382/** 1383 * Set the authentication cookie and add user identification data to the session 1384 * 1385 * @param string $user username 1386 * @param string $pass encrypted password 1387 * @param bool $sticky whether or not the cookie will last beyond the session 1388 * @return bool 1389 */ 1390function auth_setCookie($user, $pass, $sticky) 1391{ 1392 global $conf; 1393 /* @var AuthPlugin $auth */ 1394 global $auth; 1395 global $USERINFO; 1396 1397 if (!$auth instanceof AuthPlugin) return false; 1398 $USERINFO = $auth->getUserData($user); 1399 1400 // set cookie 1401 $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass); 1402 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1403 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1404 setcookie(DOKU_COOKIE, $cookie, [ 1405 'expires' => $time, 1406 'path' => $cookieDir, 1407 'secure' => ($conf['securecookie'] && Ip::isSsl()), 1408 'httponly' => true, 1409 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 1410 ]); 1411 1412 // set session 1413 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1414 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1415 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1416 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1417 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1418 1419 return true; 1420} 1421 1422/** 1423 * Returns the user, (encrypted) password and sticky bit from cookie 1424 * 1425 * @returns array 1426 */ 1427function auth_getCookie() 1428{ 1429 if (!isset($_COOKIE[DOKU_COOKIE])) { 1430 return [null, null, null]; 1431 } 1432 [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, ''); 1433 $sticky = (bool) $sticky; 1434 $pass = base64_decode($pass); 1435 $user = base64_decode($user); 1436 return [$user, $sticky, $pass]; 1437} 1438 1439//Setup VIM: ex: et ts=2 : 1440