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