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