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 $groups = $USERINFO ? (array) $USERINFO['grps'] : array(); 474 } 475 476 // prefer cached result 477 static $cache = []; 478 $cachekey = serialize([$user, $adminonly, $groups]); 479 if (!isset($cache[$cachekey]) || $recache) { 480 // check superuser match 481 $ok = auth_isMember($conf['superuser'], $user, $groups); 482 483 // check managers 484 if (!$ok && !$adminonly) { 485 $ok = auth_isMember($conf['manager'], $user, $groups); 486 } 487 488 $cache[$cachekey] = $ok; 489 } 490 491 return $cache[$cachekey]; 492} 493 494/** 495 * Check if a user is admin 496 * 497 * Alias to auth_ismanager with adminonly=true 498 * 499 * The info is available through $INFO['isadmin'], too 500 * 501 * @param string $user Username 502 * @param array $groups List of groups the user is in 503 * @param bool $recache set to true to refresh the cache 504 * @return bool 505 * @author Andreas Gohr <andi@splitbrain.org> 506 * @see auth_ismanager() 507 * 508 */ 509function auth_isadmin($user = null, $groups = null, $recache=false) { 510 return auth_ismanager($user, $groups, true, $recache); 511} 512 513/** 514 * Match a user and his groups against a comma separated list of 515 * users and groups to determine membership status 516 * 517 * Note: all input should NOT be nameencoded. 518 * 519 * @param string $memberlist commaseparated list of allowed users and groups 520 * @param string $user user to match against 521 * @param array $groups groups the user is member of 522 * @return bool true for membership acknowledged 523 */ 524function auth_isMember($memberlist, $user, array $groups) { 525 /* @var AuthPlugin $auth */ 526 global $auth; 527 if(!$auth) return false; 528 529 // clean user and groups 530 if(!$auth->isCaseSensitive()) { 531 $user = \dokuwiki\Utf8\PhpString::strtolower($user); 532 $groups = array_map([\dokuwiki\Utf8\PhpString::class, 'strtolower'], $groups); 533 } 534 $user = $auth->cleanUser($user); 535 $groups = array_map(array($auth, 'cleanGroup'), $groups); 536 537 // extract the memberlist 538 $members = explode(',', $memberlist); 539 $members = array_map('trim', $members); 540 $members = array_unique($members); 541 $members = array_filter($members); 542 543 // compare cleaned values 544 foreach($members as $member) { 545 if($member == '@ALL' ) return true; 546 if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member); 547 if($member[0] == '@') { 548 $member = $auth->cleanGroup(substr($member, 1)); 549 if(in_array($member, $groups)) return true; 550 } else { 551 $member = $auth->cleanUser($member); 552 if($member == $user) return true; 553 } 554 } 555 556 // still here? not a member! 557 return false; 558} 559 560/** 561 * Convinience function for auth_aclcheck() 562 * 563 * This checks the permissions for the current user 564 * 565 * @author Andreas Gohr <andi@splitbrain.org> 566 * 567 * @param string $id page ID (needs to be resolved and cleaned) 568 * @return int permission level 569 */ 570function auth_quickaclcheck($id) { 571 global $conf; 572 global $USERINFO; 573 /* @var Input $INPUT */ 574 global $INPUT; 575 # if no ACL is used always return upload rights 576 if(!$conf['useacl']) return AUTH_UPLOAD; 577 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array()); 578} 579 580/** 581 * Returns the maximum rights a user has for the given ID or its namespace 582 * 583 * @author Andreas Gohr <andi@splitbrain.org> 584 * 585 * @triggers AUTH_ACL_CHECK 586 * @param string $id page ID (needs to be resolved and cleaned) 587 * @param string $user Username 588 * @param array|null $groups Array of groups the user is in 589 * @return int permission level 590 */ 591function auth_aclcheck($id, $user, $groups) { 592 $data = array( 593 'id' => $id, 594 'user' => $user, 595 'groups' => $groups 596 ); 597 598 return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 599} 600 601/** 602 * default ACL check method 603 * 604 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 605 * 606 * @author Andreas Gohr <andi@splitbrain.org> 607 * 608 * @param array $data event data 609 * @return int permission level 610 */ 611function auth_aclcheck_cb($data) { 612 $id =& $data['id']; 613 $user =& $data['user']; 614 $groups =& $data['groups']; 615 616 global $conf; 617 global $AUTH_ACL; 618 /* @var AuthPlugin $auth */ 619 global $auth; 620 621 // if no ACL is used always return upload rights 622 if(!$conf['useacl']) return AUTH_UPLOAD; 623 if(!$auth) return AUTH_NONE; 624 625 //make sure groups is an array 626 if(!is_array($groups)) $groups = array(); 627 628 //if user is superuser or in superusergroup return 255 (acl_admin) 629 if(auth_isadmin($user, $groups)) { 630 return AUTH_ADMIN; 631 } 632 633 if(!$auth->isCaseSensitive()) { 634 $user = \dokuwiki\Utf8\PhpString::strtolower($user); 635 $groups = array_map('utf8_strtolower', $groups); 636 } 637 $user = auth_nameencode($auth->cleanUser($user)); 638 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); 639 640 //prepend groups with @ and nameencode 641 foreach($groups as &$group) { 642 $group = '@'.auth_nameencode($group); 643 } 644 645 $ns = getNS($id); 646 $perm = -1; 647 648 //add ALL group 649 $groups[] = '@ALL'; 650 651 //add User 652 if($user) $groups[] = $user; 653 654 //check exact match first 655 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 656 if(count($matches)) { 657 foreach($matches as $match) { 658 $match = preg_replace('/#.*$/', '', $match); //ignore comments 659 $acl = preg_split('/[ \t]+/', $match); 660 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 661 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]); 662 } 663 if(!in_array($acl[1], $groups)) { 664 continue; 665 } 666 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 667 if($acl[2] > $perm) { 668 $perm = $acl[2]; 669 } 670 } 671 if($perm > -1) { 672 //we had a match - return it 673 return (int) $perm; 674 } 675 } 676 677 //still here? do the namespace checks 678 if($ns) { 679 $path = $ns.':*'; 680 } else { 681 $path = '*'; //root document 682 } 683 684 do { 685 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 686 if(count($matches)) { 687 foreach($matches as $match) { 688 $match = preg_replace('/#.*$/', '', $match); //ignore comments 689 $acl = preg_split('/[ \t]+/', $match); 690 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 691 $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]); 692 } 693 if(!in_array($acl[1], $groups)) { 694 continue; 695 } 696 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 697 if($acl[2] > $perm) { 698 $perm = $acl[2]; 699 } 700 } 701 //we had a match - return it 702 if($perm != -1) { 703 return (int) $perm; 704 } 705 } 706 //get next higher namespace 707 $ns = getNS($ns); 708 709 if($path != '*') { 710 $path = $ns.':*'; 711 if($path == ':*') $path = '*'; 712 } else { 713 //we did this already 714 //looks like there is something wrong with the ACL 715 //break here 716 msg('No ACL setup yet! Denying access to everyone.'); 717 return AUTH_NONE; 718 } 719 } while(1); //this should never loop endless 720 return AUTH_NONE; 721} 722 723/** 724 * Encode ASCII special chars 725 * 726 * Some auth backends allow special chars in their user and groupnames 727 * The special chars are encoded with this function. Only ASCII chars 728 * are encoded UTF-8 multibyte are left as is (different from usual 729 * urlencoding!). 730 * 731 * Decoding can be done with rawurldecode 732 * 733 * @author Andreas Gohr <gohr@cosmocode.de> 734 * @see rawurldecode() 735 * 736 * @param string $name 737 * @param bool $skip_group 738 * @return string 739 */ 740function auth_nameencode($name, $skip_group = false) { 741 global $cache_authname; 742 $cache =& $cache_authname; 743 $name = (string) $name; 744 745 // never encode wildcard FS#1955 746 if($name == '%USER%') return $name; 747 if($name == '%GROUP%') return $name; 748 749 if(!isset($cache[$name][$skip_group])) { 750 if($skip_group && $name[0] == '@') { 751 $cache[$name][$skip_group] = '@'.preg_replace_callback( 752 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 753 'auth_nameencode_callback', substr($name, 1) 754 ); 755 } else { 756 $cache[$name][$skip_group] = preg_replace_callback( 757 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 758 'auth_nameencode_callback', $name 759 ); 760 } 761 } 762 763 return $cache[$name][$skip_group]; 764} 765 766/** 767 * callback encodes the matches 768 * 769 * @param array $matches first complete match, next matching subpatterms 770 * @return string 771 */ 772function auth_nameencode_callback($matches) { 773 return '%'.dechex(ord(substr($matches[1],-1))); 774} 775 776/** 777 * Create a pronouncable password 778 * 779 * The $foruser variable might be used by plugins to run additional password 780 * policy checks, but is not used by the default implementation 781 * 782 * @author Andreas Gohr <andi@splitbrain.org> 783 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 784 * @triggers AUTH_PASSWORD_GENERATE 785 * 786 * @param string $foruser username for which the password is generated 787 * @return string pronouncable password 788 */ 789function auth_pwgen($foruser = '') { 790 $data = array( 791 'password' => '', 792 'foruser' => $foruser 793 ); 794 795 $evt = new Event('AUTH_PASSWORD_GENERATE', $data); 796 if($evt->advise_before(true)) { 797 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 798 $v = 'aeiou'; //vowels 799 $a = $c.$v; //both 800 $s = '!$%&?+*~#-_:.;,'; // specials 801 802 //use thre syllables... 803 for($i = 0; $i < 3; $i++) { 804 $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 805 $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 806 $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 807 } 808 //... and add a nice number and special 809 $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99); 810 } 811 $evt->advise_after(); 812 813 return $data['password']; 814} 815 816/** 817 * Sends a password to the given user 818 * 819 * @author Andreas Gohr <andi@splitbrain.org> 820 * 821 * @param string $user Login name of the user 822 * @param string $password The new password in clear text 823 * @return bool true on success 824 */ 825function auth_sendPassword($user, $password) { 826 global $lang; 827 /* @var AuthPlugin $auth */ 828 global $auth; 829 if(!$auth) return false; 830 831 $user = $auth->cleanUser($user); 832 $userinfo = $auth->getUserData($user, $requireGroups = false); 833 834 if(!$userinfo['mail']) return false; 835 836 $text = rawLocale('password'); 837 $trep = array( 838 'FULLNAME' => $userinfo['name'], 839 'LOGIN' => $user, 840 'PASSWORD' => $password 841 ); 842 843 $mail = new Mailer(); 844 $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>'); 845 $mail->subject($lang['regpwmail']); 846 $mail->setBody($text, $trep); 847 return $mail->send(); 848} 849 850/** 851 * Register a new user 852 * 853 * This registers a new user - Data is read directly from $_POST 854 * 855 * @author Andreas Gohr <andi@splitbrain.org> 856 * 857 * @return bool true on success, false on any error 858 */ 859function register() { 860 global $lang; 861 global $conf; 862 /* @var \dokuwiki\Extension\AuthPlugin $auth */ 863 global $auth; 864 global $INPUT; 865 866 if(!$INPUT->post->bool('save')) return false; 867 if(!actionOK('register')) return false; 868 869 // gather input 870 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 871 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 872 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 873 $pass = $INPUT->post->str('pass'); 874 $passchk = $INPUT->post->str('passchk'); 875 876 if(empty($login) || empty($fullname) || empty($email)) { 877 msg($lang['regmissing'], -1); 878 return false; 879 } 880 881 if($conf['autopasswd']) { 882 $pass = auth_pwgen($login); // automatically generate password 883 } elseif(empty($pass) || empty($passchk)) { 884 msg($lang['regmissing'], -1); // complain about missing passwords 885 return false; 886 } elseif($pass != $passchk) { 887 msg($lang['regbadpass'], -1); // complain about misspelled passwords 888 return false; 889 } 890 891 //check mail 892 if(!mail_isvalid($email)) { 893 msg($lang['regbadmail'], -1); 894 return false; 895 } 896 897 //okay try to create the user 898 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { 899 msg($lang['regfail'], -1); 900 return false; 901 } 902 903 // send notification about the new user 904 $subscription = new RegistrationSubscriptionSender(); 905 $subscription->sendRegister($login, $fullname, $email); 906 907 // are we done? 908 if(!$conf['autopasswd']) { 909 msg($lang['regsuccess2'], 1); 910 return true; 911 } 912 913 // autogenerated password? then send password to user 914 if(auth_sendPassword($login, $pass)) { 915 msg($lang['regsuccess'], 1); 916 return true; 917 } else { 918 msg($lang['regmailfail'], -1); 919 return false; 920 } 921} 922 923/** 924 * Update user profile 925 * 926 * @author Christopher Smith <chris@jalakai.co.uk> 927 */ 928function updateprofile() { 929 global $conf; 930 global $lang; 931 /* @var AuthPlugin $auth */ 932 global $auth; 933 /* @var Input $INPUT */ 934 global $INPUT; 935 936 if(!$INPUT->post->bool('save')) return false; 937 if(!checkSecurityToken()) return false; 938 939 if(!actionOK('profile')) { 940 msg($lang['profna'], -1); 941 return false; 942 } 943 944 $changes = array(); 945 $changes['pass'] = $INPUT->post->str('newpass'); 946 $changes['name'] = $INPUT->post->str('fullname'); 947 $changes['mail'] = $INPUT->post->str('email'); 948 949 // check misspelled passwords 950 if($changes['pass'] != $INPUT->post->str('passchk')) { 951 msg($lang['regbadpass'], -1); 952 return false; 953 } 954 955 // clean fullname and email 956 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 957 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 958 959 // no empty name and email (except the backend doesn't support them) 960 if((empty($changes['name']) && $auth->canDo('modName')) || 961 (empty($changes['mail']) && $auth->canDo('modMail')) 962 ) { 963 msg($lang['profnoempty'], -1); 964 return false; 965 } 966 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 967 msg($lang['regbadmail'], -1); 968 return false; 969 } 970 971 $changes = array_filter($changes); 972 973 // check for unavailable capabilities 974 if(!$auth->canDo('modName')) unset($changes['name']); 975 if(!$auth->canDo('modMail')) unset($changes['mail']); 976 if(!$auth->canDo('modPass')) unset($changes['pass']); 977 978 // anything to do? 979 if(!count($changes)) { 980 msg($lang['profnochange'], -1); 981 return false; 982 } 983 984 if($conf['profileconfirm']) { 985 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 986 msg($lang['badpassconfirm'], -1); 987 return false; 988 } 989 } 990 991 if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) { 992 msg($lang['proffail'], -1); 993 return false; 994 } 995 996 if($changes['pass']) { 997 // update cookie and session with the changed data 998 list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); 999 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1000 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1001 } else { 1002 // make sure the session is writable 1003 @session_start(); 1004 // invalidate session cache 1005 $_SESSION[DOKU_COOKIE]['auth']['time'] = 0; 1006 session_write_close(); 1007 } 1008 1009 return true; 1010} 1011 1012/** 1013 * Delete the current logged-in user 1014 * 1015 * @return bool true on success, false on any error 1016 */ 1017function auth_deleteprofile(){ 1018 global $conf; 1019 global $lang; 1020 /* @var \dokuwiki\Extension\AuthPlugin $auth */ 1021 global $auth; 1022 /* @var Input $INPUT */ 1023 global $INPUT; 1024 1025 if(!$INPUT->post->bool('delete')) return false; 1026 if(!checkSecurityToken()) return false; 1027 1028 // action prevented or auth module disallows 1029 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { 1030 msg($lang['profnodelete'], -1); 1031 return false; 1032 } 1033 1034 if(!$INPUT->post->bool('confirm_delete')){ 1035 msg($lang['profconfdeletemissing'], -1); 1036 return false; 1037 } 1038 1039 if($conf['profileconfirm']) { 1040 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1041 msg($lang['badpassconfirm'], -1); 1042 return false; 1043 } 1044 } 1045 1046 $deleted = array(); 1047 $deleted[] = $INPUT->server->str('REMOTE_USER'); 1048 if($auth->triggerUserMod('delete', array($deleted))) { 1049 // force and immediate logout including removing the sticky cookie 1050 auth_logoff(); 1051 return true; 1052 } 1053 1054 return false; 1055} 1056 1057/** 1058 * Send a new password 1059 * 1060 * This function handles both phases of the password reset: 1061 * 1062 * - handling the first request of password reset 1063 * - validating the password reset auth token 1064 * 1065 * @author Benoit Chesneau <benoit@bchesneau.info> 1066 * @author Chris Smith <chris@jalakai.co.uk> 1067 * @author Andreas Gohr <andi@splitbrain.org> 1068 * 1069 * @return bool true on success, false on any error 1070 */ 1071function act_resendpwd() { 1072 global $lang; 1073 global $conf; 1074 /* @var AuthPlugin $auth */ 1075 global $auth; 1076 /* @var Input $INPUT */ 1077 global $INPUT; 1078 1079 if(!actionOK('resendpwd')) { 1080 msg($lang['resendna'], -1); 1081 return false; 1082 } 1083 1084 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1085 1086 if($token) { 1087 // we're in token phase - get user info from token 1088 1089 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth'; 1090 if(!file_exists($tfile)) { 1091 msg($lang['resendpwdbadauth'], -1); 1092 $INPUT->remove('pwauth'); 1093 return false; 1094 } 1095 // token is only valid for 3 days 1096 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1097 msg($lang['resendpwdbadauth'], -1); 1098 $INPUT->remove('pwauth'); 1099 @unlink($tfile); 1100 return false; 1101 } 1102 1103 $user = io_readfile($tfile); 1104 $userinfo = $auth->getUserData($user, $requireGroups = false); 1105 if(!$userinfo['mail']) { 1106 msg($lang['resendpwdnouser'], -1); 1107 return false; 1108 } 1109 1110 if(!$conf['autopasswd']) { // we let the user choose a password 1111 $pass = $INPUT->str('pass'); 1112 1113 // password given correctly? 1114 if(!$pass) return false; 1115 if($pass != $INPUT->str('passchk')) { 1116 msg($lang['regbadpass'], -1); 1117 return false; 1118 } 1119 1120 // change it 1121 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1122 msg($lang['proffail'], -1); 1123 return false; 1124 } 1125 1126 } else { // autogenerate the password and send by mail 1127 1128 $pass = auth_pwgen($user); 1129 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1130 msg($lang['proffail'], -1); 1131 return false; 1132 } 1133 1134 if(auth_sendPassword($user, $pass)) { 1135 msg($lang['resendpwdsuccess'], 1); 1136 } else { 1137 msg($lang['regmailfail'], -1); 1138 } 1139 } 1140 1141 @unlink($tfile); 1142 return true; 1143 1144 } else { 1145 // we're in request phase 1146 1147 if(!$INPUT->post->bool('save')) return false; 1148 1149 if(!$INPUT->post->str('login')) { 1150 msg($lang['resendpwdmissing'], -1); 1151 return false; 1152 } else { 1153 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1154 } 1155 1156 $userinfo = $auth->getUserData($user, $requireGroups = false); 1157 if(!$userinfo['mail']) { 1158 msg($lang['resendpwdnouser'], -1); 1159 return false; 1160 } 1161 1162 // generate auth token 1163 $token = md5(auth_randombytes(16)); // random secret 1164 $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth'; 1165 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); 1166 1167 io_saveFile($tfile, $user); 1168 1169 $text = rawLocale('pwconfirm'); 1170 $trep = array( 1171 'FULLNAME' => $userinfo['name'], 1172 'LOGIN' => $user, 1173 'CONFIRM' => $url 1174 ); 1175 1176 $mail = new Mailer(); 1177 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 1178 $mail->subject($lang['regpwmail']); 1179 $mail->setBody($text, $trep); 1180 if($mail->send()) { 1181 msg($lang['resendpwdconfirm'], 1); 1182 } else { 1183 msg($lang['regmailfail'], -1); 1184 } 1185 return true; 1186 } 1187 // never reached 1188} 1189 1190/** 1191 * Encrypts a password using the given method and salt 1192 * 1193 * If the selected method needs a salt and none was given, a random one 1194 * is chosen. 1195 * 1196 * @author Andreas Gohr <andi@splitbrain.org> 1197 * 1198 * @param string $clear The clear text password 1199 * @param string $method The hashing method 1200 * @param string $salt A salt, null for random 1201 * @return string The crypted password 1202 */ 1203function auth_cryptPassword($clear, $method = '', $salt = null) { 1204 global $conf; 1205 if(empty($method)) $method = $conf['passcrypt']; 1206 1207 $pass = new PassHash(); 1208 $call = 'hash_'.$method; 1209 1210 if(!method_exists($pass, $call)) { 1211 msg("Unsupported crypt method $method", -1); 1212 return false; 1213 } 1214 1215 return $pass->$call($clear, $salt); 1216} 1217 1218/** 1219 * Verifies a cleartext password against a crypted hash 1220 * 1221 * @author Andreas Gohr <andi@splitbrain.org> 1222 * 1223 * @param string $clear The clear text password 1224 * @param string $crypt The hash to compare with 1225 * @return bool true if both match 1226 */ 1227function auth_verifyPassword($clear, $crypt) { 1228 $pass = new PassHash(); 1229 return $pass->verify_hash($clear, $crypt); 1230} 1231 1232/** 1233 * Set the authentication cookie and add user identification data to the session 1234 * 1235 * @param string $user username 1236 * @param string $pass encrypted password 1237 * @param bool $sticky whether or not the cookie will last beyond the session 1238 * @return bool 1239 */ 1240function auth_setCookie($user, $pass, $sticky) { 1241 global $conf; 1242 /* @var AuthPlugin $auth */ 1243 global $auth; 1244 global $USERINFO; 1245 1246 if(!$auth) return false; 1247 $USERINFO = $auth->getUserData($user); 1248 1249 // set cookie 1250 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); 1251 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1252 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1253 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 1254 1255 // set session 1256 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1257 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1258 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1259 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1260 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1261 1262 return true; 1263} 1264 1265/** 1266 * Returns the user, (encrypted) password and sticky bit from cookie 1267 * 1268 * @returns array 1269 */ 1270function auth_getCookie() { 1271 if(!isset($_COOKIE[DOKU_COOKIE])) { 1272 return array(null, null, null); 1273 } 1274 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); 1275 $sticky = (bool) $sticky; 1276 $pass = base64_decode($pass); 1277 $user = base64_decode($user); 1278 return array($user, $sticky, $pass); 1279} 1280 1281//Setup VIM: ex: et ts=2 : 1282