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