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