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