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