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