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, true); //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, true); //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 * @param bool $secure if security is more important than keeping the old value 337 * @return string 338 */ 339function auth_cookiesalt($addsession = false, $secure = false) { 340 global $conf; 341 $file = $conf['metadir'].'/_htcookiesalt'; 342 if ($secure || !file_exists($file)) { 343 $file = $conf['metadir'].'/_htcookiesalt2'; 344 } 345 $salt = io_readFile($file); 346 if(empty($salt)) { 347 $salt = bin2hex(auth_randombytes(64)); 348 io_saveFile($file, $salt); 349 } 350 if($addsession) { 351 $salt .= session_id(); 352 } 353 return $salt; 354} 355 356/** 357 * Return truly (pseudo) random bytes if available, otherwise fall back to mt_rand 358 * 359 * @author Mark Seecof 360 * @author Michael Hamann <michael@content-space.de> 361 * @link http://www.php.net/manual/de/function.mt-rand.php#83655 362 * @param int $length number of bytes to get 363 * @throws Exception when no usable random generator is found 364 * @return string binary random strings 365 */ 366function auth_randombytes($length) { 367 $strong = false; 368 $rbytes = false; 369 370 if (function_exists('openssl_random_pseudo_bytes') 371 && (version_compare(PHP_VERSION, '5.3.4') >= 0 372 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') 373 ) { 374 $rbytes = openssl_random_pseudo_bytes($length, $strong); 375 } 376 377 if (!$strong && function_exists('mcrypt_create_iv') 378 && (version_compare(PHP_VERSION, '5.3.7') >= 0 379 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') 380 ) { 381 $rbytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); 382 if ($rbytes !== false && strlen($rbytes) === $length) { 383 $strong = true; 384 } 385 } 386 387 388 // If no strong randoms available, try OS the specific ways 389 if(!$strong) { 390 // Unix/Linux platform 391 $fp = @fopen('/dev/urandom', 'rb'); 392 if($fp !== false) { 393 $rbytes = fread($fp, $length); 394 fclose($fp); 395 } 396 397 // MS-Windows platform 398 if(class_exists('COM')) { 399 // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx 400 try { 401 $CAPI_Util = new COM('CAPICOM.Utilities.1'); 402 $rbytes = $CAPI_Util->GetRandom($length, 0); 403 404 // if we ask for binary data PHP munges it, so we 405 // request base64 return value. 406 if($rbytes) $rbytes = base64_decode($rbytes); 407 } catch(Exception $ex) { 408 // fail 409 } 410 } 411 } 412 if(strlen($rbytes) < $length) $rbytes = false; 413 414 // still no random bytes available - fall back to mt_rand() 415 if($rbytes === false) { 416 $rbytes = ''; 417 for ($i = 0; $i < $length; ++$i) { 418 $rbytes .= chr(mt_rand(0, 255)); 419 } 420 } 421 422 return $rbytes; 423} 424 425/** 426 * Random number generator using the best available source 427 * 428 * @author Michael Samuel 429 * @author Michael Hamann <michael@content-space.de> 430 * @param int $min 431 * @param int $max 432 * @return int 433 */ 434function auth_random($min, $max) { 435 $abs_max = $max - $min; 436 437 $nbits = 0; 438 for ($n = $abs_max; $n > 0; $n >>= 1) { 439 ++$nbits; 440 } 441 442 $mask = (1 << $nbits) - 1; 443 do { 444 $bytes = auth_randombytes(PHP_INT_SIZE); 445 $integers = unpack('Inum', $bytes); 446 $integer = $integers["num"] & $mask; 447 } while ($integer > $abs_max); 448 449 return $min + $integer; 450} 451 452/** 453 * Log out the current user 454 * 455 * This clears all authentication data and thus log the user 456 * off. It also clears session data. 457 * 458 * @author Andreas Gohr <andi@splitbrain.org> 459 * @param bool $keepbc - when true, the breadcrumb data is not cleared 460 */ 461function auth_logoff($keepbc = false) { 462 global $conf; 463 global $USERINFO; 464 /* @var DokuWiki_Auth_Plugin $auth */ 465 global $auth; 466 467 // make sure the session is writable (it usually is) 468 @session_start(); 469 470 if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 471 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 472 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 473 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 474 if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 475 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 476 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 477 unset($_SESSION[DOKU_COOKIE]['bc']); 478 if(isset($_SERVER['REMOTE_USER'])) 479 unset($_SERVER['REMOTE_USER']); 480 $USERINFO = null; //FIXME 481 482 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 483 if(version_compare(PHP_VERSION, '5.2.0', '>')) { 484 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 485 } else { 486 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl())); 487 } 488 489 if($auth) $auth->logOff(); 490} 491 492/** 493 * Check if a user is a manager 494 * 495 * Should usually be called without any parameters to check the current 496 * user. 497 * 498 * The info is available through $INFO['ismanager'], too 499 * 500 * @author Andreas Gohr <andi@splitbrain.org> 501 * @see auth_isadmin 502 * @param string $user Username 503 * @param array $groups List of groups the user is in 504 * @param bool $adminonly when true checks if user is admin 505 * @return bool 506 */ 507function auth_ismanager($user = null, $groups = null, $adminonly = false) { 508 global $conf; 509 global $USERINFO; 510 /* @var DokuWiki_Auth_Plugin $auth */ 511 global $auth; 512 513 if(!$auth) return false; 514 if(is_null($user)) { 515 if(!isset($_SERVER['REMOTE_USER'])) { 516 return false; 517 } else { 518 $user = $_SERVER['REMOTE_USER']; 519 } 520 } 521 if(is_null($groups)) { 522 $groups = (array) $USERINFO['grps']; 523 } 524 525 // check superuser match 526 if(auth_isMember($conf['superuser'], $user, $groups)) return true; 527 if($adminonly) return false; 528 // check managers 529 if(auth_isMember($conf['manager'], $user, $groups)) return true; 530 531 return false; 532} 533 534/** 535 * Check if a user is admin 536 * 537 * Alias to auth_ismanager with adminonly=true 538 * 539 * The info is available through $INFO['isadmin'], too 540 * 541 * @author Andreas Gohr <andi@splitbrain.org> 542 * @see auth_ismanager() 543 * @param string $user Username 544 * @param array $groups List of groups the user is in 545 * @return bool 546 */ 547function auth_isadmin($user = null, $groups = null) { 548 return auth_ismanager($user, $groups, true); 549} 550 551/** 552 * Match a user and his groups against a comma separated list of 553 * users and groups to determine membership status 554 * 555 * Note: all input should NOT be nameencoded. 556 * 557 * @param $memberlist string commaseparated list of allowed users and groups 558 * @param $user string user to match against 559 * @param $groups array groups the user is member of 560 * @return bool true for membership acknowledged 561 */ 562function auth_isMember($memberlist, $user, array $groups) { 563 /* @var DokuWiki_Auth_Plugin $auth */ 564 global $auth; 565 if(!$auth) return false; 566 567 // clean user and groups 568 if(!$auth->isCaseSensitive()) { 569 $user = utf8_strtolower($user); 570 $groups = array_map('utf8_strtolower', $groups); 571 } 572 $user = $auth->cleanUser($user); 573 $groups = array_map(array($auth, 'cleanGroup'), $groups); 574 575 // extract the memberlist 576 $members = explode(',', $memberlist); 577 $members = array_map('trim', $members); 578 $members = array_unique($members); 579 $members = array_filter($members); 580 581 // compare cleaned values 582 foreach($members as $member) { 583 if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); 584 if($member[0] == '@') { 585 $member = $auth->cleanGroup(substr($member, 1)); 586 if(in_array($member, $groups)) return true; 587 } else { 588 $member = $auth->cleanUser($member); 589 if($member == $user) return true; 590 } 591 } 592 593 // still here? not a member! 594 return false; 595} 596 597/** 598 * Convinience function for auth_aclcheck() 599 * 600 * This checks the permissions for the current user 601 * 602 * @author Andreas Gohr <andi@splitbrain.org> 603 * 604 * @param string $id page ID (needs to be resolved and cleaned) 605 * @return int permission level 606 */ 607function auth_quickaclcheck($id) { 608 global $conf; 609 global $USERINFO; 610 # if no ACL is used always return upload rights 611 if(!$conf['useacl']) return AUTH_UPLOAD; 612 return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']); 613} 614 615/** 616 * Returns the maximum rights a user has for 617 * the given ID or its namespace 618 * 619 * @author Andreas Gohr <andi@splitbrain.org> 620 * 621 * @param string $id page ID (needs to be resolved and cleaned) 622 * @param string $user Username 623 * @param array|null $groups Array of groups the user is in 624 * @return int permission level 625 */ 626function auth_aclcheck($id, $user, $groups) { 627 global $conf; 628 global $AUTH_ACL; 629 /* @var DokuWiki_Auth_Plugin $auth */ 630 global $auth; 631 632 // if no ACL is used always return upload rights 633 if(!$conf['useacl']) return AUTH_UPLOAD; 634 if(!$auth) return AUTH_NONE; 635 636 //make sure groups is an array 637 if(!is_array($groups)) $groups = array(); 638 639 //if user is superuser or in superusergroup return 255 (acl_admin) 640 if(auth_isadmin($user, $groups)) { 641 return AUTH_ADMIN; 642 } 643 644 if(!$auth->isCaseSensitive()) { 645 $user = utf8_strtolower($user); 646 $groups = array_map('utf8_strtolower', $groups); 647 } 648 $user = $auth->cleanUser($user); 649 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); 650 $user = auth_nameencode($user); 651 652 //prepend groups with @ and nameencode 653 $cnt = count($groups); 654 for($i = 0; $i < $cnt; $i++) { 655 $groups[$i] = '@'.auth_nameencode($groups[$i]); 656 } 657 658 $ns = getNS($id); 659 $perm = -1; 660 661 if($user || count($groups)) { 662 //add ALL group 663 $groups[] = '@ALL'; 664 //add User 665 if($user) $groups[] = $user; 666 } else { 667 $groups[] = '@ALL'; 668 } 669 670 //check exact match first 671 $matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/u', $AUTH_ACL); 672 if(count($matches)) { 673 foreach($matches as $match) { 674 $match = preg_replace('/#.*$/', '', $match); //ignore comments 675 $acl = preg_split('/\s+/', $match); 676 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 677 $acl[1] = utf8_strtolower($acl[1]); 678 } 679 if(!in_array($acl[1], $groups)) { 680 continue; 681 } 682 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 683 if($acl[2] > $perm) { 684 $perm = $acl[2]; 685 } 686 } 687 if($perm > -1) { 688 //we had a match - return it 689 return (int) $perm; 690 } 691 } 692 693 //still here? do the namespace checks 694 if($ns) { 695 $path = $ns.':*'; 696 } else { 697 $path = '*'; //root document 698 } 699 700 do { 701 $matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/u', $AUTH_ACL); 702 if(count($matches)) { 703 foreach($matches as $match) { 704 $match = preg_replace('/#.*$/', '', $match); //ignore comments 705 $acl = preg_split('/\s+/', $match); 706 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 707 $acl[1] = utf8_strtolower($acl[1]); 708 } 709 if(!in_array($acl[1], $groups)) { 710 continue; 711 } 712 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 713 if($acl[2] > $perm) { 714 $perm = $acl[2]; 715 } 716 } 717 //we had a match - return it 718 if($perm != -1) { 719 return (int) $perm; 720 } 721 } 722 //get next higher namespace 723 $ns = getNS($ns); 724 725 if($path != '*') { 726 $path = $ns.':*'; 727 if($path == ':*') $path = '*'; 728 } else { 729 //we did this already 730 //looks like there is something wrong with the ACL 731 //break here 732 msg('No ACL setup yet! Denying access to everyone.'); 733 return AUTH_NONE; 734 } 735 } while(1); //this should never loop endless 736 return AUTH_NONE; 737} 738 739/** 740 * Encode ASCII special chars 741 * 742 * Some auth backends allow special chars in their user and groupnames 743 * The special chars are encoded with this function. Only ASCII chars 744 * are encoded UTF-8 multibyte are left as is (different from usual 745 * urlencoding!). 746 * 747 * Decoding can be done with rawurldecode 748 * 749 * @author Andreas Gohr <gohr@cosmocode.de> 750 * @see rawurldecode() 751 */ 752function auth_nameencode($name, $skip_group = false) { 753 global $cache_authname; 754 $cache =& $cache_authname; 755 $name = (string) $name; 756 757 // never encode wildcard FS#1955 758 if($name == '%USER%') return $name; 759 if($name == '%GROUP%') return $name; 760 761 if(!isset($cache[$name][$skip_group])) { 762 if($skip_group && $name{0} == '@') { 763 $cache[$name][$skip_group] = '@'.preg_replace( 764 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 765 "'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1) 766 ); 767 } else { 768 $cache[$name][$skip_group] = preg_replace( 769 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 770 "'%'.dechex(ord(substr('\\1',-1)))", $name 771 ); 772 } 773 } 774 775 return $cache[$name][$skip_group]; 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 Doku_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'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; 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 * @param string $user Login name of the user 823 * @param string $password The new password in clear text 824 * @return bool true on success 825 */ 826function auth_sendPassword($user, $password) { 827 global $lang; 828 /* @var DokuWiki_Auth_Plugin $auth */ 829 global $auth; 830 if(!$auth) return false; 831 832 $user = $auth->cleanUser($user); 833 $userinfo = $auth->getUserData($user); 834 835 if(!$userinfo['mail']) return false; 836 837 $text = rawLocale('password'); 838 $trep = array( 839 'FULLNAME' => $userinfo['name'], 840 'LOGIN' => $user, 841 'PASSWORD' => $password 842 ); 843 844 $mail = new Mailer(); 845 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 846 $mail->subject($lang['regpwmail']); 847 $mail->setBody($text, $trep); 848 return $mail->send(); 849} 850 851/** 852 * Register a new user 853 * 854 * This registers a new user - Data is read directly from $_POST 855 * 856 * @author Andreas Gohr <andi@splitbrain.org> 857 * @return bool true on success, false on any error 858 */ 859function register() { 860 global $lang; 861 global $conf; 862 /* @var DokuWiki_Auth_Plugin $auth */ 863 global $auth; 864 global $INPUT; 865 866 if(!$INPUT->post->bool('save')) return false; 867 if(!actionOK('register')) return false; 868 869 // gather input 870 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 871 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 872 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 873 $pass = $INPUT->post->str('pass'); 874 $passchk = $INPUT->post->str('passchk'); 875 876 if(empty($login) || empty($fullname) || empty($email)) { 877 msg($lang['regmissing'], -1); 878 return false; 879 } 880 881 if($conf['autopasswd']) { 882 $pass = auth_pwgen($login); // automatically generate password 883 } elseif(empty($pass) || empty($passchk)) { 884 msg($lang['regmissing'], -1); // complain about missing passwords 885 return false; 886 } elseif($pass != $passchk) { 887 msg($lang['regbadpass'], -1); // complain about misspelled passwords 888 return false; 889 } 890 891 //check mail 892 if(!mail_isvalid($email)) { 893 msg($lang['regbadmail'], -1); 894 return false; 895 } 896 897 //okay try to create the user 898 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { 899 msg($lang['reguexists'], -1); 900 return false; 901 } 902 903 // send notification about the new user 904 $subscription = new Subscription(); 905 $subscription->send_register($login, $fullname, $email); 906 907 // are we done? 908 if(!$conf['autopasswd']) { 909 msg($lang['regsuccess2'], 1); 910 return true; 911 } 912 913 // autogenerated password? then send password to user 914 if(auth_sendPassword($login, $pass)) { 915 msg($lang['regsuccess'], 1); 916 return true; 917 } else { 918 msg($lang['regmailfail'], -1); 919 return false; 920 } 921} 922 923/** 924 * Update user profile 925 * 926 * @author Christopher Smith <chris@jalakai.co.uk> 927 */ 928function updateprofile() { 929 global $conf; 930 global $lang; 931 /* @var DokuWiki_Auth_Plugin $auth */ 932 global $auth; 933 /* @var Input $INPUT */ 934 global $INPUT; 935 936 if(!$INPUT->post->bool('save')) return false; 937 if(!checkSecurityToken()) return false; 938 939 if(!actionOK('profile')) { 940 msg($lang['profna'], -1); 941 return false; 942 } 943 944 $changes = array(); 945 $changes['pass'] = $INPUT->post->str('newpass'); 946 $changes['name'] = $INPUT->post->str('fullname'); 947 $changes['mail'] = $INPUT->post->str('email'); 948 949 // check misspelled passwords 950 if($changes['pass'] != $INPUT->post->str('passchk')) { 951 msg($lang['regbadpass'], -1); 952 return false; 953 } 954 955 // clean fullname and email 956 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 957 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 958 959 // no empty name and email (except the backend doesn't support them) 960 if((empty($changes['name']) && $auth->canDo('modName')) || 961 (empty($changes['mail']) && $auth->canDo('modMail')) 962 ) { 963 msg($lang['profnoempty'], -1); 964 return false; 965 } 966 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 967 msg($lang['regbadmail'], -1); 968 return false; 969 } 970 971 $changes = array_filter($changes); 972 973 // check for unavailable capabilities 974 if(!$auth->canDo('modName')) unset($changes['name']); 975 if(!$auth->canDo('modMail')) unset($changes['mail']); 976 if(!$auth->canDo('modPass')) unset($changes['pass']); 977 978 // anything to do? 979 if(!count($changes)) { 980 msg($lang['profnochange'], -1); 981 return false; 982 } 983 984 if($conf['profileconfirm']) { 985 if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) { 986 msg($lang['badlogin'], -1); 987 return false; 988 } 989 } 990 991 if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) { 992 // update cookie and session with the changed data 993 if($changes['pass']) { 994 list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); 995 $pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 996 auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky); 997 } 998 return true; 999 } 1000 1001 return false; 1002} 1003 1004/** 1005 * Send a new password 1006 * 1007 * This function handles both phases of the password reset: 1008 * 1009 * - handling the first request of password reset 1010 * - validating the password reset auth token 1011 * 1012 * @author Benoit Chesneau <benoit@bchesneau.info> 1013 * @author Chris Smith <chris@jalakai.co.uk> 1014 * @author Andreas Gohr <andi@splitbrain.org> 1015 * 1016 * @return bool true on success, false on any error 1017 */ 1018function act_resendpwd() { 1019 global $lang; 1020 global $conf; 1021 /* @var DokuWiki_Auth_Plugin $auth */ 1022 global $auth; 1023 /* @var Input $INPUT */ 1024 global $INPUT; 1025 1026 if(!actionOK('resendpwd')) { 1027 msg($lang['resendna'], -1); 1028 return false; 1029 } 1030 1031 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1032 1033 if($token) { 1034 // we're in token phase - get user info from token 1035 1036 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1037 if(!@file_exists($tfile)) { 1038 msg($lang['resendpwdbadauth'], -1); 1039 $INPUT->remove('pwauth'); 1040 return false; 1041 } 1042 // token is only valid for 3 days 1043 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1044 msg($lang['resendpwdbadauth'], -1); 1045 $INPUT->remove('pwauth'); 1046 @unlink($tfile); 1047 return false; 1048 } 1049 1050 $user = io_readfile($tfile); 1051 $userinfo = $auth->getUserData($user); 1052 if(!$userinfo['mail']) { 1053 msg($lang['resendpwdnouser'], -1); 1054 return false; 1055 } 1056 1057 if(!$conf['autopasswd']) { // we let the user choose a password 1058 $pass = $INPUT->str('pass'); 1059 1060 // password given correctly? 1061 if(!$pass) return false; 1062 if($pass != $INPUT->str('passchk')) { 1063 msg($lang['regbadpass'], -1); 1064 return false; 1065 } 1066 1067 // change it 1068 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1069 msg('error modifying user data', -1); 1070 return false; 1071 } 1072 1073 } else { // autogenerate the password and send by mail 1074 1075 $pass = auth_pwgen($user); 1076 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1077 msg('error modifying user data', -1); 1078 return false; 1079 } 1080 1081 if(auth_sendPassword($user, $pass)) { 1082 msg($lang['resendpwdsuccess'], 1); 1083 } else { 1084 msg($lang['regmailfail'], -1); 1085 } 1086 } 1087 1088 @unlink($tfile); 1089 return true; 1090 1091 } else { 1092 // we're in request phase 1093 1094 if(!$INPUT->post->bool('save')) return false; 1095 1096 if(!$INPUT->post->str('login')) { 1097 msg($lang['resendpwdmissing'], -1); 1098 return false; 1099 } else { 1100 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1101 } 1102 1103 $userinfo = $auth->getUserData($user); 1104 if(!$userinfo['mail']) { 1105 msg($lang['resendpwdnouser'], -1); 1106 return false; 1107 } 1108 1109 // generate auth token 1110 $token = md5(auth_randombytes(16)); // random secret 1111 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1112 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); 1113 1114 io_saveFile($tfile, $user); 1115 1116 $text = rawLocale('pwconfirm'); 1117 $trep = array( 1118 'FULLNAME' => $userinfo['name'], 1119 'LOGIN' => $user, 1120 'CONFIRM' => $url 1121 ); 1122 1123 $mail = new Mailer(); 1124 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 1125 $mail->subject($lang['regpwmail']); 1126 $mail->setBody($text, $trep); 1127 if($mail->send()) { 1128 msg($lang['resendpwdconfirm'], 1); 1129 } else { 1130 msg($lang['regmailfail'], -1); 1131 } 1132 return true; 1133 } 1134 // never reached 1135} 1136 1137/** 1138 * Encrypts a password using the given method and salt 1139 * 1140 * If the selected method needs a salt and none was given, a random one 1141 * is chosen. 1142 * 1143 * @author Andreas Gohr <andi@splitbrain.org> 1144 * @param string $clear The clear text password 1145 * @param string $method The hashing method 1146 * @param string $salt A salt, null for random 1147 * @return string The crypted password 1148 */ 1149function auth_cryptPassword($clear, $method = '', $salt = null) { 1150 global $conf; 1151 if(empty($method)) $method = $conf['passcrypt']; 1152 1153 $pass = new PassHash(); 1154 $call = 'hash_'.$method; 1155 1156 if(!method_exists($pass, $call)) { 1157 msg("Unsupported crypt method $method", -1); 1158 return false; 1159 } 1160 1161 return $pass->$call($clear, $salt); 1162} 1163 1164/** 1165 * Verifies a cleartext password against a crypted hash 1166 * 1167 * @author Andreas Gohr <andi@splitbrain.org> 1168 * @param string $clear The clear text password 1169 * @param string $crypt The hash to compare with 1170 * @return bool true if both match 1171 */ 1172function auth_verifyPassword($clear, $crypt) { 1173 $pass = new PassHash(); 1174 return $pass->verify_hash($clear, $crypt); 1175} 1176 1177/** 1178 * Set the authentication cookie and add user identification data to the session 1179 * 1180 * @param string $user username 1181 * @param string $pass encrypted password 1182 * @param bool $sticky whether or not the cookie will last beyond the session 1183 * @return bool 1184 */ 1185function auth_setCookie($user, $pass, $sticky) { 1186 global $conf; 1187 /* @var DokuWiki_Auth_Plugin $auth */ 1188 global $auth; 1189 global $USERINFO; 1190 1191 if(!$auth) return false; 1192 $USERINFO = $auth->getUserData($user); 1193 1194 // set cookie 1195 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); 1196 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1197 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1198 if(version_compare(PHP_VERSION, '5.2.0', '>')) { 1199 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 1200 } else { 1201 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl())); 1202 } 1203 // set session 1204 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1205 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1206 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1207 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1208 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1209 1210 return true; 1211} 1212 1213/** 1214 * Returns the user, (encrypted) password and sticky bit from cookie 1215 * 1216 * @returns array 1217 */ 1218function auth_getCookie() { 1219 if(!isset($_COOKIE[DOKU_COOKIE])) { 1220 return array(null, null, null); 1221 } 1222 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); 1223 $sticky = (bool) $sticky; 1224 $pass = base64_decode($pass); 1225 $user = base64_decode($user); 1226 return array($user, $sticky, $pass); 1227} 1228 1229//Setup VIM: ex: et ts=2 : 1230