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