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