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