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