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