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