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