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