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