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