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