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