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(empty($line) || ($line{0} == '#')) continue; // skip blank lines & comments 143 list($id,$rest) = preg_split('/[ \t]+/',$line,2); 144 145 // substitute 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 // If no strong randoms available, try OS the specific ways 395 if(!$strong) { 396 // Unix/Linux platform 397 $fp = @fopen('/dev/urandom', 'rb'); 398 if($fp !== false) { 399 $rbytes = fread($fp, $length); 400 fclose($fp); 401 } 402 403 // MS-Windows platform 404 if(class_exists('COM')) { 405 // http://msdn.microsoft.com/en-us/library/aa388176(VS.85).aspx 406 try { 407 $CAPI_Util = new COM('CAPICOM.Utilities.1'); 408 $rbytes = $CAPI_Util->GetRandom($length, 0); 409 410 // if we ask for binary data PHP munges it, so we 411 // request base64 return value. 412 if($rbytes) $rbytes = base64_decode($rbytes); 413 } catch(Exception $ex) { 414 // fail 415 } 416 } 417 } 418 if(strlen($rbytes) < $length) $rbytes = false; 419 420 // still no random bytes available - fall back to mt_rand() 421 if($rbytes === false) { 422 $rbytes = ''; 423 for ($i = 0; $i < $length; ++$i) { 424 $rbytes .= chr(mt_rand(0, 255)); 425 } 426 } 427 428 return $rbytes; 429} 430 431/** 432 * Random number generator using the best available source 433 * 434 * @author Michael Samuel 435 * @author Michael Hamann <michael@content-space.de> 436 * @param int $min 437 * @param int $max 438 * @return int 439 */ 440function auth_random($min, $max) { 441 $abs_max = $max - $min; 442 443 $nbits = 0; 444 for ($n = $abs_max; $n > 0; $n >>= 1) { 445 ++$nbits; 446 } 447 448 $mask = (1 << $nbits) - 1; 449 do { 450 $bytes = auth_randombytes(PHP_INT_SIZE); 451 $integers = unpack('Inum', $bytes); 452 $integer = $integers["num"] & $mask; 453 } while ($integer > $abs_max); 454 455 return $min + $integer; 456} 457 458/** 459 * Encrypt data using the given secret using AES 460 * 461 * The mode is CBC with a random initialization vector, the key is derived 462 * using pbkdf2. 463 * 464 * @param string $data The data that shall be encrypted 465 * @param string $secret The secret/password that shall be used 466 * @return string The ciphertext 467 */ 468function auth_encrypt($data, $secret) { 469 $iv = auth_randombytes(16); 470 $cipher = new Crypt_AES(); 471 $cipher->setPassword($secret); 472 473 /* 474 this uses the encrypted IV as IV as suggested in 475 http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C 476 for unique but necessarily random IVs. The resulting ciphertext is 477 compatible to ciphertext that was created using a "normal" IV. 478 */ 479 return $cipher->encrypt($iv.$data); 480} 481 482/** 483 * Decrypt the given AES ciphertext 484 * 485 * The mode is CBC, the key is derived using pbkdf2 486 * 487 * @param string $ciphertext The encrypted data 488 * @param string $secret The secret/password that shall be used 489 * @return string The decrypted data 490 */ 491function auth_decrypt($ciphertext, $secret) { 492 $iv = substr($ciphertext, 0, 16); 493 $cipher = new Crypt_AES(); 494 $cipher->setPassword($secret); 495 $cipher->setIV($iv); 496 497 return $cipher->decrypt(substr($ciphertext, 16)); 498} 499 500/** 501 * Log out the current user 502 * 503 * This clears all authentication data and thus log the user 504 * off. It also clears session data. 505 * 506 * @author Andreas Gohr <andi@splitbrain.org> 507 * @param bool $keepbc - when true, the breadcrumb data is not cleared 508 */ 509function auth_logoff($keepbc = false) { 510 global $conf; 511 global $USERINFO; 512 /* @var DokuWiki_Auth_Plugin $auth */ 513 global $auth; 514 515 // make sure the session is writable (it usually is) 516 @session_start(); 517 518 if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 519 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 520 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 521 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 522 if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 523 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 524 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 525 unset($_SESSION[DOKU_COOKIE]['bc']); 526 if(isset($_SERVER['REMOTE_USER'])) 527 unset($_SERVER['REMOTE_USER']); 528 $USERINFO = null; //FIXME 529 530 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 531 if(version_compare(PHP_VERSION, '5.2.0', '>')) { 532 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 533 } else { 534 setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl())); 535 } 536 537 if($auth) $auth->logOff(); 538} 539 540/** 541 * Check if a user is a manager 542 * 543 * Should usually be called without any parameters to check the current 544 * user. 545 * 546 * The info is available through $INFO['ismanager'], too 547 * 548 * @author Andreas Gohr <andi@splitbrain.org> 549 * @see auth_isadmin 550 * @param string $user Username 551 * @param array $groups List of groups the user is in 552 * @param bool $adminonly when true checks if user is admin 553 * @return bool 554 */ 555function auth_ismanager($user = null, $groups = null, $adminonly = false) { 556 global $conf; 557 global $USERINFO; 558 /* @var DokuWiki_Auth_Plugin $auth */ 559 global $auth; 560 561 if(!$auth) return false; 562 if(is_null($user)) { 563 if(!isset($_SERVER['REMOTE_USER'])) { 564 return false; 565 } else { 566 $user = $_SERVER['REMOTE_USER']; 567 } 568 } 569 if(is_null($groups)) { 570 $groups = (array) $USERINFO['grps']; 571 } 572 573 // check superuser match 574 if(auth_isMember($conf['superuser'], $user, $groups)) return true; 575 if($adminonly) return false; 576 // check managers 577 if(auth_isMember($conf['manager'], $user, $groups)) return true; 578 579 return false; 580} 581 582/** 583 * Check if a user is admin 584 * 585 * Alias to auth_ismanager with adminonly=true 586 * 587 * The info is available through $INFO['isadmin'], too 588 * 589 * @author Andreas Gohr <andi@splitbrain.org> 590 * @see auth_ismanager() 591 * @param string $user Username 592 * @param array $groups List of groups the user is in 593 * @return bool 594 */ 595function auth_isadmin($user = null, $groups = null) { 596 return auth_ismanager($user, $groups, true); 597} 598 599/** 600 * Match a user and his groups against a comma separated list of 601 * users and groups to determine membership status 602 * 603 * Note: all input should NOT be nameencoded. 604 * 605 * @param $memberlist string commaseparated list of allowed users and groups 606 * @param $user string user to match against 607 * @param $groups array groups the user is member of 608 * @return bool true for membership acknowledged 609 */ 610function auth_isMember($memberlist, $user, array $groups) { 611 /* @var DokuWiki_Auth_Plugin $auth */ 612 global $auth; 613 if(!$auth) return false; 614 615 // clean user and groups 616 if(!$auth->isCaseSensitive()) { 617 $user = utf8_strtolower($user); 618 $groups = array_map('utf8_strtolower', $groups); 619 } 620 $user = $auth->cleanUser($user); 621 $groups = array_map(array($auth, 'cleanGroup'), $groups); 622 623 // extract the memberlist 624 $members = explode(',', $memberlist); 625 $members = array_map('trim', $members); 626 $members = array_unique($members); 627 $members = array_filter($members); 628 629 // compare cleaned values 630 foreach($members as $member) { 631 if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member); 632 if($member[0] == '@') { 633 $member = $auth->cleanGroup(substr($member, 1)); 634 if(in_array($member, $groups)) return true; 635 } else { 636 $member = $auth->cleanUser($member); 637 if($member == $user) return true; 638 } 639 } 640 641 // still here? not a member! 642 return false; 643} 644 645/** 646 * Convinience function for auth_aclcheck() 647 * 648 * This checks the permissions for the current user 649 * 650 * @author Andreas Gohr <andi@splitbrain.org> 651 * 652 * @param string $id page ID (needs to be resolved and cleaned) 653 * @return int permission level 654 */ 655function auth_quickaclcheck($id) { 656 global $conf; 657 global $USERINFO; 658 # if no ACL is used always return upload rights 659 if(!$conf['useacl']) return AUTH_UPLOAD; 660 return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']); 661} 662 663/** 664 * Returns the maximum rights a user has for the given ID or its namespace 665 * 666 * @author Andreas Gohr <andi@splitbrain.org> 667 * @triggers AUTH_ACL_CHECK 668 * @param string $id page ID (needs to be resolved and cleaned) 669 * @param string $user Username 670 * @param array|null $groups Array of groups the user is in 671 * @return int permission level 672 */ 673function auth_aclcheck($id, $user, $groups) { 674 $data = array( 675 'id' => $id, 676 'user' => $user, 677 'groups' => $groups 678 ); 679 680 return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 681} 682 683/** 684 * default ACL check method 685 * 686 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 687 * 688 * @author Andreas Gohr <andi@splitbrain.org> 689 * @param array $data event data 690 * @return int permission level 691 */ 692function auth_aclcheck_cb($data) { 693 $id =& $data['id']; 694 $user =& $data['user']; 695 $groups =& $data['groups']; 696 697 global $conf; 698 global $AUTH_ACL; 699 /* @var DokuWiki_Auth_Plugin $auth */ 700 global $auth; 701 702 // if no ACL is used always return upload rights 703 if(!$conf['useacl']) return AUTH_UPLOAD; 704 if(!$auth) return AUTH_NONE; 705 706 //make sure groups is an array 707 if(!is_array($groups)) $groups = array(); 708 709 //if user is superuser or in superusergroup return 255 (acl_admin) 710 if(auth_isadmin($user, $groups)) { 711 return AUTH_ADMIN; 712 } 713 714 if(!$auth->isCaseSensitive()) { 715 $user = utf8_strtolower($user); 716 $groups = array_map('utf8_strtolower', $groups); 717 } 718 $user = $auth->cleanUser($user); 719 $groups = array_map(array($auth, 'cleanGroup'), (array) $groups); 720 $user = auth_nameencode($user); 721 722 //prepend groups with @ and nameencode 723 $cnt = count($groups); 724 for($i = 0; $i < $cnt; $i++) { 725 $groups[$i] = '@'.auth_nameencode($groups[$i]); 726 } 727 728 $ns = getNS($id); 729 $perm = -1; 730 731 if($user || count($groups)) { 732 //add ALL group 733 $groups[] = '@ALL'; 734 //add User 735 if($user) $groups[] = $user; 736 } else { 737 $groups[] = '@ALL'; 738 } 739 740 //check exact match first 741 $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 742 if(count($matches)) { 743 foreach($matches as $match) { 744 $match = preg_replace('/#.*$/', '', $match); //ignore comments 745 $acl = preg_split('/[ \t]+/', $match); 746 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 747 $acl[1] = utf8_strtolower($acl[1]); 748 } 749 if(!in_array($acl[1], $groups)) { 750 continue; 751 } 752 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 753 if($acl[2] > $perm) { 754 $perm = $acl[2]; 755 } 756 } 757 if($perm > -1) { 758 //we had a match - return it 759 return (int) $perm; 760 } 761 } 762 763 //still here? do the namespace checks 764 if($ns) { 765 $path = $ns.':*'; 766 } else { 767 $path = '*'; //root document 768 } 769 770 do { 771 $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 772 if(count($matches)) { 773 foreach($matches as $match) { 774 $match = preg_replace('/#.*$/', '', $match); //ignore comments 775 $acl = preg_split('/[ \t]+/', $match); 776 if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 777 $acl[1] = utf8_strtolower($acl[1]); 778 } 779 if(!in_array($acl[1], $groups)) { 780 continue; 781 } 782 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 783 if($acl[2] > $perm) { 784 $perm = $acl[2]; 785 } 786 } 787 //we had a match - return it 788 if($perm != -1) { 789 return (int) $perm; 790 } 791 } 792 //get next higher namespace 793 $ns = getNS($ns); 794 795 if($path != '*') { 796 $path = $ns.':*'; 797 if($path == ':*') $path = '*'; 798 } else { 799 //we did this already 800 //looks like there is something wrong with the ACL 801 //break here 802 msg('No ACL setup yet! Denying access to everyone.'); 803 return AUTH_NONE; 804 } 805 } while(1); //this should never loop endless 806 return AUTH_NONE; 807} 808 809/** 810 * Encode ASCII special chars 811 * 812 * Some auth backends allow special chars in their user and groupnames 813 * The special chars are encoded with this function. Only ASCII chars 814 * are encoded UTF-8 multibyte are left as is (different from usual 815 * urlencoding!). 816 * 817 * Decoding can be done with rawurldecode 818 * 819 * @author Andreas Gohr <gohr@cosmocode.de> 820 * @see rawurldecode() 821 */ 822function auth_nameencode($name, $skip_group = false) { 823 global $cache_authname; 824 $cache =& $cache_authname; 825 $name = (string) $name; 826 827 // never encode wildcard FS#1955 828 if($name == '%USER%') return $name; 829 if($name == '%GROUP%') return $name; 830 831 if(!isset($cache[$name][$skip_group])) { 832 if($skip_group && $name{0} == '@') { 833 $cache[$name][$skip_group] = '@'.preg_replace_callback( 834 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 835 'auth_nameencode_callback', substr($name, 1) 836 ); 837 } else { 838 $cache[$name][$skip_group] = preg_replace_callback( 839 '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 840 'auth_nameencode_callback', $name 841 ); 842 } 843 } 844 845 return $cache[$name][$skip_group]; 846} 847 848/** 849 * callback encodes the matches 850 * 851 * @param array $matches first complete match, next matching subpatterms 852 * @return string 853 */ 854function auth_nameencode_callback($matches) { 855 return '%'.dechex(ord(substr($matches[1],-1))); 856} 857 858/** 859 * Create a pronouncable password 860 * 861 * The $foruser variable might be used by plugins to run additional password 862 * policy checks, but is not used by the default implementation 863 * 864 * @author Andreas Gohr <andi@splitbrain.org> 865 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 866 * @triggers AUTH_PASSWORD_GENERATE 867 * 868 * @param string $foruser username for which the password is generated 869 * @return string pronouncable password 870 */ 871function auth_pwgen($foruser = '') { 872 $data = array( 873 'password' => '', 874 'foruser' => $foruser 875 ); 876 877 $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data); 878 if($evt->advise_before(true)) { 879 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 880 $v = 'aeiou'; //vowels 881 $a = $c.$v; //both 882 $s = '!$%&?+*~#-_:.;,'; // specials 883 884 //use thre syllables... 885 for($i = 0; $i < 3; $i++) { 886 $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 887 $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 888 $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 889 } 890 //... and add a nice number and special 891 $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)]; 892 } 893 $evt->advise_after(); 894 895 return $data['password']; 896} 897 898/** 899 * Sends a password to the given user 900 * 901 * @author Andreas Gohr <andi@splitbrain.org> 902 * @param string $user Login name of the user 903 * @param string $password The new password in clear text 904 * @return bool true on success 905 */ 906function auth_sendPassword($user, $password) { 907 global $lang; 908 /* @var DokuWiki_Auth_Plugin $auth */ 909 global $auth; 910 if(!$auth) return false; 911 912 $user = $auth->cleanUser($user); 913 $userinfo = $auth->getUserData($user); 914 915 if(!$userinfo['mail']) return false; 916 917 $text = rawLocale('password'); 918 $trep = array( 919 'FULLNAME' => $userinfo['name'], 920 'LOGIN' => $user, 921 'PASSWORD' => $password 922 ); 923 924 $mail = new Mailer(); 925 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 926 $mail->subject($lang['regpwmail']); 927 $mail->setBody($text, $trep); 928 return $mail->send(); 929} 930 931/** 932 * Register a new user 933 * 934 * This registers a new user - Data is read directly from $_POST 935 * 936 * @author Andreas Gohr <andi@splitbrain.org> 937 * @return bool true on success, false on any error 938 */ 939function register() { 940 global $lang; 941 global $conf; 942 /* @var DokuWiki_Auth_Plugin $auth */ 943 global $auth; 944 global $INPUT; 945 946 if(!$INPUT->post->bool('save')) return false; 947 if(!actionOK('register')) return false; 948 949 // gather input 950 $login = trim($auth->cleanUser($INPUT->post->str('login'))); 951 $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 952 $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 953 $pass = $INPUT->post->str('pass'); 954 $passchk = $INPUT->post->str('passchk'); 955 956 if(empty($login) || empty($fullname) || empty($email)) { 957 msg($lang['regmissing'], -1); 958 return false; 959 } 960 961 if($conf['autopasswd']) { 962 $pass = auth_pwgen($login); // automatically generate password 963 } elseif(empty($pass) || empty($passchk)) { 964 msg($lang['regmissing'], -1); // complain about missing passwords 965 return false; 966 } elseif($pass != $passchk) { 967 msg($lang['regbadpass'], -1); // complain about misspelled passwords 968 return false; 969 } 970 971 //check mail 972 if(!mail_isvalid($email)) { 973 msg($lang['regbadmail'], -1); 974 return false; 975 } 976 977 //okay try to create the user 978 if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) { 979 msg($lang['reguexists'], -1); 980 return false; 981 } 982 983 // send notification about the new user 984 $subscription = new Subscription(); 985 $subscription->send_register($login, $fullname, $email); 986 987 // are we done? 988 if(!$conf['autopasswd']) { 989 msg($lang['regsuccess2'], 1); 990 return true; 991 } 992 993 // autogenerated password? then send password to user 994 if(auth_sendPassword($login, $pass)) { 995 msg($lang['regsuccess'], 1); 996 return true; 997 } else { 998 msg($lang['regmailfail'], -1); 999 return false; 1000 } 1001} 1002 1003/** 1004 * Update user profile 1005 * 1006 * @author Christopher Smith <chris@jalakai.co.uk> 1007 */ 1008function updateprofile() { 1009 global $conf; 1010 global $lang; 1011 /* @var DokuWiki_Auth_Plugin $auth */ 1012 global $auth; 1013 /* @var Input $INPUT */ 1014 global $INPUT; 1015 1016 if(!$INPUT->post->bool('save')) return false; 1017 if(!checkSecurityToken()) return false; 1018 1019 if(!actionOK('profile')) { 1020 msg($lang['profna'], -1); 1021 return false; 1022 } 1023 1024 $changes = array(); 1025 $changes['pass'] = $INPUT->post->str('newpass'); 1026 $changes['name'] = $INPUT->post->str('fullname'); 1027 $changes['mail'] = $INPUT->post->str('email'); 1028 1029 // check misspelled passwords 1030 if($changes['pass'] != $INPUT->post->str('passchk')) { 1031 msg($lang['regbadpass'], -1); 1032 return false; 1033 } 1034 1035 // clean fullname and email 1036 $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1037 $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 1038 1039 // no empty name and email (except the backend doesn't support them) 1040 if((empty($changes['name']) && $auth->canDo('modName')) || 1041 (empty($changes['mail']) && $auth->canDo('modMail')) 1042 ) { 1043 msg($lang['profnoempty'], -1); 1044 return false; 1045 } 1046 if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 1047 msg($lang['regbadmail'], -1); 1048 return false; 1049 } 1050 1051 $changes = array_filter($changes); 1052 1053 // check for unavailable capabilities 1054 if(!$auth->canDo('modName')) unset($changes['name']); 1055 if(!$auth->canDo('modMail')) unset($changes['mail']); 1056 if(!$auth->canDo('modPass')) unset($changes['pass']); 1057 1058 // anything to do? 1059 if(!count($changes)) { 1060 msg($lang['profnochange'], -1); 1061 return false; 1062 } 1063 1064 if($conf['profileconfirm']) { 1065 if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) { 1066 msg($lang['badpassconfirm'], -1); 1067 return false; 1068 } 1069 } 1070 1071 if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) { 1072 // update cookie and session with the changed data 1073 if($changes['pass']) { 1074 list( /*user*/, $sticky, /*pass*/) = auth_getCookie(); 1075 $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1076 auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky); 1077 } 1078 return true; 1079 } 1080 1081 return false; 1082} 1083 1084/** 1085 * Delete the current logged-in user 1086 * 1087 * @return bool true on success, false on any error 1088 */ 1089function auth_deleteprofile(){ 1090 global $conf; 1091 global $lang; 1092 /* @var DokuWiki_Auth_Plugin $auth */ 1093 global $auth; 1094 /* @var Input $INPUT */ 1095 global $INPUT; 1096 1097 if(!$INPUT->post->bool('delete')) return false; 1098 if(!checkSecurityToken()) return false; 1099 1100 // action prevented or auth module disallows 1101 if(!actionOK('profile_delete') || !$auth->canDo('delUser')) { 1102 msg($lang['profnodelete'], -1); 1103 return false; 1104 } 1105 1106 if(!$INPUT->post->bool('confirm_delete')){ 1107 msg($lang['profconfdeletemissing'], -1); 1108 return false; 1109 } 1110 1111 if($conf['profileconfirm']) { 1112 if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) { 1113 msg($lang['badpassconfirm'], -1); 1114 return false; 1115 } 1116 } 1117 1118 $deleted[] = $_SERVER['REMOTE_USER']; 1119 if($auth->triggerUserMod('delete', array($deleted))) { 1120 // force and immediate logout including removing the sticky cookie 1121 auth_logoff(); 1122 return true; 1123 } 1124 1125 return false; 1126} 1127 1128/** 1129 * Send a new password 1130 * 1131 * This function handles both phases of the password reset: 1132 * 1133 * - handling the first request of password reset 1134 * - validating the password reset auth token 1135 * 1136 * @author Benoit Chesneau <benoit@bchesneau.info> 1137 * @author Chris Smith <chris@jalakai.co.uk> 1138 * @author Andreas Gohr <andi@splitbrain.org> 1139 * 1140 * @return bool true on success, false on any error 1141 */ 1142function act_resendpwd() { 1143 global $lang; 1144 global $conf; 1145 /* @var DokuWiki_Auth_Plugin $auth */ 1146 global $auth; 1147 /* @var Input $INPUT */ 1148 global $INPUT; 1149 1150 if(!actionOK('resendpwd')) { 1151 msg($lang['resendna'], -1); 1152 return false; 1153 } 1154 1155 $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 1156 1157 if($token) { 1158 // we're in token phase - get user info from token 1159 1160 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1161 if(!@file_exists($tfile)) { 1162 msg($lang['resendpwdbadauth'], -1); 1163 $INPUT->remove('pwauth'); 1164 return false; 1165 } 1166 // token is only valid for 3 days 1167 if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 1168 msg($lang['resendpwdbadauth'], -1); 1169 $INPUT->remove('pwauth'); 1170 @unlink($tfile); 1171 return false; 1172 } 1173 1174 $user = io_readfile($tfile); 1175 $userinfo = $auth->getUserData($user); 1176 if(!$userinfo['mail']) { 1177 msg($lang['resendpwdnouser'], -1); 1178 return false; 1179 } 1180 1181 if(!$conf['autopasswd']) { // we let the user choose a password 1182 $pass = $INPUT->str('pass'); 1183 1184 // password given correctly? 1185 if(!$pass) return false; 1186 if($pass != $INPUT->str('passchk')) { 1187 msg($lang['regbadpass'], -1); 1188 return false; 1189 } 1190 1191 // change it 1192 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1193 msg('error modifying user data', -1); 1194 return false; 1195 } 1196 1197 } else { // autogenerate the password and send by mail 1198 1199 $pass = auth_pwgen($user); 1200 if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) { 1201 msg('error modifying user data', -1); 1202 return false; 1203 } 1204 1205 if(auth_sendPassword($user, $pass)) { 1206 msg($lang['resendpwdsuccess'], 1); 1207 } else { 1208 msg($lang['regmailfail'], -1); 1209 } 1210 } 1211 1212 @unlink($tfile); 1213 return true; 1214 1215 } else { 1216 // we're in request phase 1217 1218 if(!$INPUT->post->bool('save')) return false; 1219 1220 if(!$INPUT->post->str('login')) { 1221 msg($lang['resendpwdmissing'], -1); 1222 return false; 1223 } else { 1224 $user = trim($auth->cleanUser($INPUT->post->str('login'))); 1225 } 1226 1227 $userinfo = $auth->getUserData($user); 1228 if(!$userinfo['mail']) { 1229 msg($lang['resendpwdnouser'], -1); 1230 return false; 1231 } 1232 1233 // generate auth token 1234 $token = md5(auth_randombytes(16)); // random secret 1235 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 1236 $url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&'); 1237 1238 io_saveFile($tfile, $user); 1239 1240 $text = rawLocale('pwconfirm'); 1241 $trep = array( 1242 'FULLNAME' => $userinfo['name'], 1243 'LOGIN' => $user, 1244 'CONFIRM' => $url 1245 ); 1246 1247 $mail = new Mailer(); 1248 $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>'); 1249 $mail->subject($lang['regpwmail']); 1250 $mail->setBody($text, $trep); 1251 if($mail->send()) { 1252 msg($lang['resendpwdconfirm'], 1); 1253 } else { 1254 msg($lang['regmailfail'], -1); 1255 } 1256 return true; 1257 } 1258 // never reached 1259} 1260 1261/** 1262 * Encrypts a password using the given method and salt 1263 * 1264 * If the selected method needs a salt and none was given, a random one 1265 * is chosen. 1266 * 1267 * @author Andreas Gohr <andi@splitbrain.org> 1268 * @param string $clear The clear text password 1269 * @param string $method The hashing method 1270 * @param string $salt A salt, null for random 1271 * @return string The crypted password 1272 */ 1273function auth_cryptPassword($clear, $method = '', $salt = null) { 1274 global $conf; 1275 if(empty($method)) $method = $conf['passcrypt']; 1276 1277 $pass = new PassHash(); 1278 $call = 'hash_'.$method; 1279 1280 if(!method_exists($pass, $call)) { 1281 msg("Unsupported crypt method $method", -1); 1282 return false; 1283 } 1284 1285 return $pass->$call($clear, $salt); 1286} 1287 1288/** 1289 * Verifies a cleartext password against a crypted hash 1290 * 1291 * @author Andreas Gohr <andi@splitbrain.org> 1292 * @param string $clear The clear text password 1293 * @param string $crypt The hash to compare with 1294 * @return bool true if both match 1295 */ 1296function auth_verifyPassword($clear, $crypt) { 1297 $pass = new PassHash(); 1298 return $pass->verify_hash($clear, $crypt); 1299} 1300 1301/** 1302 * Set the authentication cookie and add user identification data to the session 1303 * 1304 * @param string $user username 1305 * @param string $pass encrypted password 1306 * @param bool $sticky whether or not the cookie will last beyond the session 1307 * @return bool 1308 */ 1309function auth_setCookie($user, $pass, $sticky) { 1310 global $conf; 1311 /* @var DokuWiki_Auth_Plugin $auth */ 1312 global $auth; 1313 global $USERINFO; 1314 1315 if(!$auth) return false; 1316 $USERINFO = $auth->getUserData($user); 1317 1318 // set cookie 1319 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); 1320 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1321 $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1322 if(version_compare(PHP_VERSION, '5.2.0', '>')) { 1323 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true); 1324 } else { 1325 setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl())); 1326 } 1327 // set session 1328 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1329 $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1330 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1331 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1332 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1333 1334 return true; 1335} 1336 1337/** 1338 * Returns the user, (encrypted) password and sticky bit from cookie 1339 * 1340 * @returns array 1341 */ 1342function auth_getCookie() { 1343 if(!isset($_COOKIE[DOKU_COOKIE])) { 1344 return array(null, null, null); 1345 } 1346 list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3); 1347 $sticky = (bool) $sticky; 1348 $pass = base64_decode($pass); 1349 $user = base64_decode($user); 1350 return array($user, $sticky, $pass); 1351} 1352 1353//Setup VIM: ex: et ts=2 : 1354