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 /* @var Input $INPUT */ 135 global $INPUT; 136 137 if(!is_readable($config_cascade['acl']['default'])) return array(); 138 139 $acl = file($config_cascade['acl']['default']); 140 141 $out = array(); 142 foreach($acl as $line) { 143 $line = trim($line); 144 if(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments 145 list($id,$rest) = preg_split('/[ \t]+/',$line,2); 146 147 // substitute user wildcard first (its 1:1) 148 if(strstr($line, '%USER%')){ 149 // if user is not logged in, this ACL line is meaningless - skip it 150 if (!$INPUT->server->has('REMOTE_USER')) continue; 151 152 $id = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id); 153 $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest); 154 } 155 156 // substitute group wildcard (its 1:m) 157 if(strstr($line, '%GROUP%')){ 158 // if user is not logged in, grps is empty, no output will be added (i.e. skipped) 159 foreach((array) $USERINFO['grps'] as $grp){ 160 $nid = str_replace('%GROUP%',cleanID($grp),$id); 161 $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest); 162 $out[] = "$nid\t$nrest"; 163 } 164 } else { 165 $out[] = "$id\t$rest"; 166 } 167 } 168 169 return $out; 170} 171 172/** 173 * Event hook callback for AUTH_LOGIN_CHECK 174 * 175 * @param $evdata 176 * @return bool 177 */ 178function auth_login_wrapper($evdata) { 179 return auth_login( 180 $evdata['user'], 181 $evdata['password'], 182 $evdata['sticky'], 183 $evdata['silent'] 184 ); 185} 186 187/** 188 * This tries to login the user based on the sent auth credentials 189 * 190 * The authentication works like this: if a username was given 191 * a new login is assumed and user/password are checked. If they 192 * are correct the password is encrypted with blowfish and stored 193 * together with the username in a cookie - the same info is stored 194 * in the session, too. Additonally a browserID is stored in the 195 * session. 196 * 197 * If no username was given the cookie is checked: if the username, 198 * crypted password and browserID match between session and cookie 199 * no further testing is done and the user is accepted 200 * 201 * If a cookie was found but no session info was availabe the 202 * blowfish encrypted password from the cookie is decrypted and 203 * together with username rechecked by calling this function again. 204 * 205 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 206 * are set. 207 * 208 * @author Andreas Gohr <andi@splitbrain.org> 209 * 210 * @param string $user Username 211 * @param string $pass Cleartext Password 212 * @param bool $sticky Cookie should not expire 213 * @param bool $silent Don't show error on bad auth 214 * @return bool true on successful auth 215 */ 216function auth_login($user, $pass, $sticky = false, $silent = false) { 217 global $USERINFO; 218 global $conf; 219 global $lang; 220 /* @var DokuWiki_Auth_Plugin $auth */ 221 global $auth; 222 /* @var Input $INPUT */ 223 global $INPUT; 224 225 $sticky ? $sticky = true : $sticky = false; //sanity check 226 227 if(!$auth) return false; 228 229 if(!empty($user)) { 230 //usual login 231 if($auth->checkPass($user, $pass)) { 232 // make logininfo globally available 233 $INPUT->server->set('REMOTE_USER', $user); 234 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 235 auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); 236 return true; 237 } else { 238 //invalid credentials - log off 239 if(!$silent) msg($lang['badlogin'], -1); 240 auth_logoff(); 241 return false; 242 } 243 } else { 244 // read cookie information 245 list($user, $sticky, $pass) = auth_getCookie(); 246 if($user && $pass) { 247 // we got a cookie - see if we can trust it 248 249 // get session info 250 $session = $_SESSION[DOKU_COOKIE]['auth']; 251 if(isset($session) && 252 $auth->useSessionCache($user) && 253 ($session['time'] >= time() - $conf['auth_security_timeout']) && 254 ($session['user'] == $user) && 255 ($session['pass'] == sha1($pass)) && //still crypted 256 ($session['buid'] == auth_browseruid()) 257 ) { 258 259 // he has session, cookie and browser right - let him in 260 $INPUT->server->set('REMOTE_USER', $user); 261 $USERINFO = $session['info']; //FIXME move all references to session 262 return true; 263 } 264 // no we don't trust it yet - recheck pass but silent 265 $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 266 $pass = auth_decrypt($pass, $secret); 267 return auth_login($user, $pass, $sticky, true); 268 } 269 } 270 //just to be sure 271 auth_logoff(true); 272 return false; 273} 274 275/** 276 * Checks if a given authentication token was stored in the session 277 * 278 * Will setup authentication data using data from the session if the 279 * token is correct. Will exit with a 401 Status if not. 280 * 281 * @author Andreas Gohr <andi@splitbrain.org> 282 * @param string $token The authentication token 283 * @return boolean true (or will exit on failure) 284 */ 285function auth_validateToken($token) { 286 if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) { 287 // bad token 288 http_status(401); 289 print 'Invalid auth token - maybe the session timed out'; 290 unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance 291 exit; 292 } 293 // still here? trust the session data 294 global $USERINFO; 295 /* @var Input $INPUT */ 296 global $INPUT; 297 298 $INPUT->server->set('REMOTE_USER',$_SESSION[DOKU_COOKIE]['auth']['user']); 299 $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info']; 300 return true; 301} 302 303/** 304 * Create an auth token and store it in the session 305 * 306 * NOTE: this is completely unrelated to the getSecurityToken() function 307 * 308 * @author Andreas Gohr <andi@splitbrain.org> 309 * @return string The auth token 310 */ 311function auth_createToken() { 312 $token = md5(auth_randombytes(16)); 313 @session_start(); // reopen the session if needed 314 $_SESSION[DOKU_COOKIE]['auth']['token'] = $token; 315 session_write_close(); 316 return $token; 317} 318 319/** 320 * Builds a pseudo UID from browser and IP data 321 * 322 * This is neither unique nor unfakable - still it adds some 323 * security. Using the first part of the IP makes sure 324 * proxy farms like AOLs are still okay. 325 * 326 * @author Andreas Gohr <andi@splitbrain.org> 327 * 328 * @return string a MD5 sum of various browser headers 329 */ 330function auth_browseruid() { 331 /* @var Input $INPUT */ 332 global $INPUT; 333 334 $ip = clientIP(true); 335 $uid = ''; 336 $uid .= $INPUT->server->str('HTTP_USER_AGENT'); 337 $uid .= $INPUT->server->str('HTTP_ACCEPT_ENCODING'); 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(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); 642 if($member[0] == '@') { 643 $member = $auth->cleanGroup(substr($member, 1)); 644 if(in_array($member, $groups)) return true; 645 } else { 646 $member = $auth->cleanUser($member); 647 if($member == $user) return true; 648 } 649 } 650 651 // still here? not a member! 652 return false; 653} 654 655/** 656 * Convinience function for auth_aclcheck() 657 * 658 * This checks the permissions for the current user 659 * 660 * @author Andreas Gohr <andi@splitbrain.org> 661 * 662 * @param string $id page ID (needs to be resolved and cleaned) 663 * @return int permission level 664 */ 665function auth_quickaclcheck($id) { 666 global $conf; 667 global $USERINFO; 668 /* @var Input $INPUT */ 669 global $INPUT; 670 # if no ACL is used always return upload rights 671 if(!$conf['useacl']) return AUTH_UPLOAD; 672 return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); 673} 674 675/** 676 * Returns the maximum rights a user has for the given ID or its namespace 677 * 678 * @author Andreas Gohr <andi@splitbrain.org> 679 * @triggers AUTH_ACL_CHECK 680 * @param string $id page ID (needs to be resolved and cleaned) 681 * @param string $user Username 682 * @param array|null $groups Array of groups the user is in 683 * @return int permission level 684 */ 685function auth_aclcheck($id, $user, $groups) { 686 $data = array( 687 'id' => $id, 688 'user' => $user, 689 'groups' => $groups 690 ); 691 692 return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 693} 694 695/** 696 * default ACL check method 697 * 698 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 699 * 700 * @author Andreas Gohr <andi@splitbrain.org> 701 * @param array $data event data 702 * @return int permission level 703 */ 704function auth_aclcheck_cb($data) { 705 $id =& $data['id']; 706 $user =& $data['user']; 707 $groups =& $data['groups']; 708 709 global $conf; 710 global $AUTH_ACL; 711 /* @var DokuWiki_Auth_Plugin $auth */ 712 global $auth; 713 714 // if no ACL is used always return upload rights 715 if(!$conf['useacl']) return AUTH_UPLOAD; 716 if(!$auth) return AUTH_NONE; 717 718 //make sure groups is an array 719 if(!is_array($groups)) $groups = array(); 720 721 //if user is superuser or in superusergroup return 255 (acl_admin) 722 if(auth_isadmin($user, $groups)) { 723 return AUTH_ADMIN; 724 } 725 726 if(!$auth->isCaseSensitive()) { 727 $user = utf8_strtolower($user); 728 $groups = array_map('utf8_strtolower', $groups); 729 } 730 $user = $auth->cleanUser($user); 731 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); 732 $user = auth_nameencode($user); 733 734 //prepend groups with @ and nameencode 735 $cnt = count($groups); 736 for($i = 0; $i < $cnt; $i++) { 737 $groups[$i] = '@'.auth_nameencode($groups[$i]); 738 } 739 740 $ns = getNS($id); 741 $perm = -1; 742 743 if($user || count($groups)) { 744 //add ALL group 745 $groups[] = '@ALL'; 746 //add User 747 if($user) $groups[] = $user; 748 } else { 749 $groups[] = '@ALL'; 750 } 751 752 //check exact match first 753 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 754 if(count($matches)) { 755 foreach($matches as $match) { 756 $match = preg_replace('/#.*$/', '', $match); //ignore comments 757 $acl = preg_split('/[ \t]+/', $match); 758 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 759 $acl[1] = utf8_strtolower($acl[1]); 760 } 761 if(!in_array($acl[1], $groups)) { 762 continue; 763 } 764 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 765 if($acl[2] > $perm) { 766 $perm = $acl[2]; 767 } 768 } 769 if($perm > -1) { 770 //we had a match - return it 771 return (int) $perm; 772 } 773 } 774 775 //still here? do the namespace checks 776 if($ns) { 777 $path = $ns.':*'; 778 } else { 779 $path = '*'; //root document 780 } 781 782 do { 783 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 784 if(count($matches)) { 785 foreach($matches as $match) { 786 $match = preg_replace('/#.*$/', '', $match); //ignore comments 787 $acl = preg_split('/[ \t]+/', $match); 788 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 789 $acl[1] = utf8_strtolower($acl[1]); 790 } 791 if(!in_array($acl[1], $groups)) { 792 continue; 793 } 794 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 795 if($acl[2] > $perm) { 796 $perm = $acl[2]; 797 } 798 } 799 //we had a match - return it 800 if($perm != -1) { 801 return (int) $perm; 802 } 803 } 804 //get next higher namespace 805 $ns = getNS($ns); 806 807 if($path != '*') { 808 $path = $ns.':*'; 809 if($path == ':*') $path = '*'; 810 } else { 811 //we did this already 812 //looks like there is something wrong with the ACL 813 //break here 814 msg('No ACL setup yet! Denying access to everyone.'); 815 return AUTH_NONE; 816 } 817 } while(1); //this should never loop endless 818 return AUTH_NONE; 819} 820 821/** 822 * Encode ASCII special chars 823 * 824 * Some auth backends allow special chars in their user and groupnames 825 * The special chars are encoded with this function. Only ASCII chars 826 * are encoded UTF-8 multibyte are left as is (different from usual 827 * urlencoding!). 828 * 829 * Decoding can be done with rawurldecode 830 * 831 * @author Andreas Gohr <gohr@cosmocode.de> 832 * @see rawurldecode() 833 */ 834function auth_nameencode($name, $skip_group = false) { 835 global $cache_authname; 836 $cache =& $cache_authname; 837 $name = (string) $name; 838 839 // never encode wildcard FS#1955 840 if($name == '%USER%') return $name; 841 if($name == '%GROUP%') return $name; 842 843 if(!isset($cache[$name][$skip_group])) { 844 if($skip_group && $name{0} == '@') { 845 $cache[$name][$skip_group] = '@'.preg_replace_callback( 846 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 847 'auth_nameencode_callback', substr($name, 1) 848 ); 849 } else { 850 $cache[$name][$skip_group] = preg_replace_callback( 851 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 852 'auth_nameencode_callback', $name 853 ); 854 } 855 } 856 857 return $cache[$name][$skip_group]; 858} 859 860/** 861 * callback encodes the matches 862 * 863 * @param array $matches first complete match, next matching subpatterms 864 * @return string 865 */ 866function auth_nameencode_callback($matches) { 867 return '%'.dechex(ord(substr($matches[1],-1))); 868} 869 870/** 871 * Create a pronouncable password 872 * 873 * The $foruser variable might be used by plugins to run additional password 874 * policy checks, but is not used by the default implementation 875 * 876 * @author Andreas Gohr <andi@splitbrain.org> 877 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 878 * @triggers AUTH_PASSWORD_GENERATE 879 * 880 * @param string $foruser username for which the password is generated 881 * @return string pronouncable password 882 */ 883function auth_pwgen($foruser = '') { 884 $data = array( 885 'password' => '', 886 'foruser' => $foruser 887 ); 888 889 $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data); 890 if($evt->advise_before(true)) { 891 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 892 $v = 'aeiou'; //vowels 893 $a = $c.$v; //both 894 $s = '!$%&?+*~#-_:.;,'; // specials 895 896 //use thre syllables... 897 for($i = 0; $i < 3; $i++) { 898 $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 899 $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 900 $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 901 } 902 //... and add a nice number and special 903 $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; 904 } 905 $evt->advise_after(); 906 907 return $data['password']; 908} 909 910/** 911 * Sends a password to the given user 912 * 913 * @author Andreas Gohr <andi@splitbrain.org> 914 * @param string $user Login name of the user 915 * @param string $password The new password in clear text 916 * @return bool true on success 917 */ 918function auth_sendPassword($user, $password) { 919 global $lang; 920 /* @var DokuWiki_Auth_Plugin $auth */ 921 global $auth; 922 if(!$auth) return false; 923 924 $user = $auth->cleanUser($user); 925 $userinfo = $auth->getUserData($user); 926 927 if(!$userinfo['mail']) return false; 928 929 $text = rawLocale('password'); 930 $trep = array( 931 'FULLNAME' => $userinfo['name'], 932 'LOGIN' => $user, 933 'PASSWORD' => $password 934 ); 935 936 $mail = new Mailer(); 937 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 938 $mail->subject($lang['regpwmail']); 939 $mail->setBody($text, $trep); 940 return $mail->send(); 941} 942 943/** 944 * Register a new user 945 * 946 * This registers a new user - Data is read directly from $_POST 947 * 948 * @author Andreas Gohr <andi@splitbrain.org> 949 * @return bool true on success, false on any error 950 */ 951function register() { 952 global $lang; 953 global $conf; 954 /* @var DokuWiki_Auth_Plugin $auth */ 955 global $auth; 956 global $INPUT; 957 958 if(!$INPUT->post->bool('save')) return false; 959 if(!actionOK('register')) return false; 960 961 // gather input 962 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 963 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 964 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 965 $pass = $INPUT->post->str('pass'); 966 $passchk = $INPUT->post->str('passchk'); 967 968 if(empty($login) || empty($fullname) || empty($email)) { 969 msg($lang['regmissing'], -1); 970 return false; 971 } 972 973 if($conf['autopasswd']) { 974 $pass = auth_pwgen($login); // automatically generate password 975 } elseif(empty($pass) || empty($passchk)) { 976 msg($lang['regmissing'], -1); // complain about missing passwords 977 return false; 978 } elseif($pass != $passchk) { 979 msg($lang['regbadpass'], -1); // complain about misspelled passwords 980 return false; 981 } 982 983 //check mail 984 if(!mail_isvalid($email)) { 985 msg($lang['regbadmail'], -1); 986 return false; 987 } 988 989 //okay try to create the user 990 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { 991 msg($lang['reguexists'], -1); 992 return false; 993 } 994 995 // send notification about the new user 996 $subscription = new Subscription(); 997 $subscription->send_register($login, $fullname, $email); 998 999 // are we done? 1000 if(!$conf['autopasswd']) { 1001 msg($lang['regsuccess2'], 1); 1002 return true; 1003 } 1004 1005 // autogenerated password? then send password to user 1006 if(auth_sendPassword($login, $pass)) { 1007 msg($lang['regsuccess'], 1); 1008 return true; 1009 } else { 1010 msg($lang['regmailfail'], -1); 1011 return false; 1012 } 1013} 1014 1015/** 1016 * Update user profile 1017 * 1018 * @author Christopher Smith <chris@jalakai.co.uk> 1019 */ 1020function updateprofile() { 1021 global $conf; 1022 global $lang; 1023 /* @var DokuWiki_Auth_Plugin $auth */ 1024 global $auth; 1025 /* @var Input $INPUT */ 1026 global $INPUT; 1027 1028 if(!$INPUT->post->bool('save')) return false; 1029 if(!checkSecurityToken()) return false; 1030 1031 if(!actionOK('profile')) { 1032 msg($lang['profna'], -1); 1033 return false; 1034 } 1035 1036 $changes = array(); 1037 $changes['pass'] = $INPUT->post->str('newpass'); 1038 $changes['name'] = $INPUT->post->str('fullname'); 1039 $changes['mail'] = $INPUT->post->str('email'); 1040 1041 // check misspelled passwords 1042 if($changes['pass'] != $INPUT->post->str('passchk')) { 1043 msg($lang['regbadpass'], -1); 1044 return false; 1045 } 1046 1047 // clean fullname and email 1048 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1049 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 1050 1051 // no empty name and email (except the backend doesn't support them) 1052 if((empty($changes['name']) && $auth->canDo('modName')) || 1053 (empty($changes['mail']) && $auth->canDo('modMail')) 1054 ) { 1055 msg($lang['profnoempty'], -1); 1056 return false; 1057 } 1058 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 1059 msg($lang['regbadmail'], -1); 1060 return false; 1061 } 1062 1063 $changes = array_filter($changes); 1064 1065 // check for unavailable capabilities 1066 if(!$auth->canDo('modName')) unset($changes['name']); 1067 if(!$auth->canDo('modMail')) unset($changes['mail']); 1068 if(!$auth->canDo('modPass')) unset($changes['pass']); 1069 1070 // anything to do? 1071 if(!count($changes)) { 1072 msg($lang['profnochange'], -1); 1073 return false; 1074 } 1075 1076 if($conf['profileconfirm']) { 1077 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1078 msg($lang['badpassconfirm'], -1); 1079 return false; 1080 } 1081 } 1082 1083 if($result = $auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), $changes))) { 1084 // update cookie and session with the changed data 1085 if($changes['pass']) { 1086 list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); 1087 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1088 auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1089 } 1090 return true; 1091 } 1092 1093 return false; 1094} 1095 1096/** 1097 * Delete the current logged-in user 1098 * 1099 * @return bool true on success, false on any error 1100 */ 1101function auth_deleteprofile(){ 1102 global $conf; 1103 global $lang; 1104 /* @var DokuWiki_Auth_Plugin $auth */ 1105 global $auth; 1106 /* @var Input $INPUT */ 1107 global $INPUT; 1108 1109 if(!$INPUT->post->bool('delete')) return false; 1110 if(!checkSecurityToken()) return false; 1111 1112 // action prevented or auth module disallows 1113 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { 1114 msg($lang['profnodelete'], -1); 1115 return false; 1116 } 1117 1118 if(!$INPUT->post->bool('confirm_delete')){ 1119 msg($lang['profconfdeletemissing'], -1); 1120 return false; 1121 } 1122 1123 if($conf['profileconfirm']) { 1124 if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 1125 msg($lang['badpassconfirm'], -1); 1126 return false; 1127 } 1128 } 1129 1130 $deleted[] = $INPUT->server->str('REMOTE_USER'); 1131 if($auth->triggerUserMod('delete', array($deleted))) { 1132 // force and immediate logout including removing the sticky cookie 1133 auth_logoff(); 1134 return true; 1135 } 1136 1137 return false; 1138} 1139 1140/** 1141 * Send a new password 1142 * 1143 * This function handles both phases of the password reset: 1144 * 1145 * - handling the first request of password reset 1146 * - validating the password reset auth token 1147 * 1148 * @author Benoit Chesneau <benoit@bchesneau.info> 1149 * @author Chris Smith <chris@jalakai.co.uk> 1150 * @author Andreas Gohr <andi@splitbrain.org> 1151 * 1152 * @return bool true on success, false on any error 1153 */ 1154function act_resendpwd() { 1155 global $lang; 1156 global $conf; 1157 /* @var DokuWiki_Auth_Plugin $auth */ 1158 global $auth; 1159 /* @var Input $INPUT */ 1160 global $INPUT; 1161 1162 if(!actionOK('resendpwd')) { 1163 msg($lang['resendna'], -1); 1164 return false; 1165 } 1166 1167 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1168 1169 if($token) { 1170 // we're in token phase - get user info from token 1171 1172 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1173 if(!@file_exists($tfile)) { 1174 msg($lang['resendpwdbadauth'], -1); 1175 $INPUT->remove('pwauth'); 1176 return false; 1177 } 1178 // token is only valid for 3 days 1179 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1180 msg($lang['resendpwdbadauth'], -1); 1181 $INPUT->remove('pwauth'); 1182 @unlink($tfile); 1183 return false; 1184 } 1185 1186 $user = io_readfile($tfile); 1187 $userinfo = $auth->getUserData($user); 1188 if(!$userinfo['mail']) { 1189 msg($lang['resendpwdnouser'], -1); 1190 return false; 1191 } 1192 1193 if(!$conf['autopasswd']) { // we let the user choose a password 1194 $pass = $INPUT->str('pass'); 1195 1196 // password given correctly? 1197 if(!$pass) return false; 1198 if($pass != $INPUT->str('passchk')) { 1199 msg($lang['regbadpass'], -1); 1200 return false; 1201 } 1202 1203 // change it 1204 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1205 msg('error modifying user data', -1); 1206 return false; 1207 } 1208 1209 } else { // autogenerate the password and send by mail 1210 1211 $pass = auth_pwgen($user); 1212 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1213 msg('error modifying user data', -1); 1214 return false; 1215 } 1216 1217 if(auth_sendPassword($user, $pass)) { 1218 msg($lang['resendpwdsuccess'], 1); 1219 } else { 1220 msg($lang['regmailfail'], -1); 1221 } 1222 } 1223 1224 @unlink($tfile); 1225 return true; 1226 1227 } else { 1228 // we're in request phase 1229 1230 if(!$INPUT->post->bool('save')) return false; 1231 1232 if(!$INPUT->post->str('login')) { 1233 msg($lang['resendpwdmissing'], -1); 1234 return false; 1235 } else { 1236 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1237 } 1238 1239 $userinfo = $auth->getUserData($user); 1240 if(!$userinfo['mail']) { 1241 msg($lang['resendpwdnouser'], -1); 1242 return false; 1243 } 1244 1245 // generate auth token 1246 $token = md5(auth_randombytes(16)); // random secret 1247 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1248 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); 1249 1250 io_saveFile($tfile, $user); 1251 1252 $text = rawLocale('pwconfirm'); 1253 $trep = array( 1254 'FULLNAME' => $userinfo['name'], 1255 'LOGIN' => $user, 1256 'CONFIRM' => $url 1257 ); 1258 1259 $mail = new Mailer(); 1260 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 1261 $mail->subject($lang['regpwmail']); 1262 $mail->setBody($text, $trep); 1263 if($mail->send()) { 1264 msg($lang['resendpwdconfirm'], 1); 1265 } else { 1266 msg($lang['regmailfail'], -1); 1267 } 1268 return true; 1269 } 1270 // never reached 1271} 1272 1273/** 1274 * Encrypts a password using the given method and salt 1275 * 1276 * If the selected method needs a salt and none was given, a random one 1277 * is chosen. 1278 * 1279 * @author Andreas Gohr <andi@splitbrain.org> 1280 * @param string $clear The clear text password 1281 * @param string $method The hashing method 1282 * @param string $salt A salt, null for random 1283 * @return string The crypted password 1284 */ 1285function auth_cryptPassword($clear, $method = '', $salt = null) { 1286 global $conf; 1287 if(empty($method)) $method = $conf['passcrypt']; 1288 1289 $pass = new PassHash(); 1290 $call = 'hash_'.$method; 1291 1292 if(!method_exists($pass, $call)) { 1293 msg("Unsupported crypt method $method", -1); 1294 return false; 1295 } 1296 1297 return $pass->$call($clear, $salt); 1298} 1299 1300/** 1301 * Verifies a cleartext password against a crypted hash 1302 * 1303 * @author Andreas Gohr <andi@splitbrain.org> 1304 * @param string $clear The clear text password 1305 * @param string $crypt The hash to compare with 1306 * @return bool true if both match 1307 */ 1308function auth_verifyPassword($clear, $crypt) { 1309 $pass = new PassHash(); 1310 return $pass->verify_hash($clear, $crypt); 1311} 1312 1313/** 1314 * Set the authentication cookie and add user identification data to the session 1315 * 1316 * @param string $user username 1317 * @param string $pass encrypted password 1318 * @param bool $sticky whether or not the cookie will last beyond the session 1319 * @return bool 1320 */ 1321function auth_setCookie($user, $pass, $sticky) { 1322 global $conf; 1323 /* @var DokuWiki_Auth_Plugin $auth */ 1324 global $auth; 1325 global $USERINFO; 1326 1327 if(!$auth) return false; 1328 $USERINFO = $auth->getUserData($user); 1329 1330 // set cookie 1331 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); 1332 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1333 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1334 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 1335 1336 // set session 1337 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1338 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1339 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1340 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1341 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1342 1343 return true; 1344} 1345 1346/** 1347 * Returns the user, (encrypted) password and sticky bit from cookie 1348 * 1349 * @returns array 1350 */ 1351function auth_getCookie() { 1352 if(!isset($_COOKIE[DOKU_COOKIE])) { 1353 return array(null, null, null); 1354 } 1355 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); 1356 $sticky = (bool) $sticky; 1357 $pass = base64_decode($pass); 1358 $user = base64_decode($user); 1359 return array($user, $sticky, $pass); 1360} 1361 1362//Setup VIM: ex: et ts=2 : 1363