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(isset($_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)) { 340 if (!isset($_SERVER['REMOTE_USER'])) { 341 return false; 342 } else { 343 $user = $_SERVER['REMOTE_USER']; 344 } 345 } 346 if(is_null($groups)) $groups = (array) $USERINFO['grps']; 347 $user = auth_nameencode($user); 348 349 // check username against superuser and manager 350 $superusers = explode(',', $conf['superuser']); 351 $superusers = array_unique($superusers); 352 $superusers = array_map('trim', $superusers); 353 // prepare an array containing only true values for array_map call 354 $alltrue = array_fill(0, count($superusers), true); 355 $superusers = array_map('auth_nameencode', $superusers, $alltrue); 356 if(in_array($user, $superusers)) return true; 357 358 if(!$adminonly){ 359 $managers = explode(',', $conf['manager']); 360 $managers = array_unique($managers); 361 $managers = array_map('trim', $managers); 362 // prepare an array containing only true values for array_map call 363 $alltrue = array_fill(0, count($managers), true); 364 $managers = array_map('auth_nameencode', $managers, $alltrue); 365 if(in_array($user, $managers)) return true; 366 } 367 368 // check user's groups against superuser and manager 369 if (!empty($groups)) { 370 371 //prepend groups with @ and nameencode 372 $cnt = count($groups); 373 for($i=0; $i<$cnt; $i++){ 374 $groups[$i] = '@'.auth_nameencode($groups[$i]); 375 } 376 377 // check groups against superuser and manager 378 foreach($superusers as $supu) 379 if(in_array($supu, $groups)) return true; 380 if(!$adminonly){ 381 foreach($managers as $mana) 382 if(in_array($mana, $groups)) return true; 383 } 384 } 385 386 return false; 387} 388 389/** 390 * Check if a user is admin 391 * 392 * Alias to auth_ismanager with adminonly=true 393 * 394 * The info is available through $INFO['isadmin'], too 395 * 396 * @author Andreas Gohr <andi@splitbrain.org> 397 * @see auth_ismanager 398 */ 399function auth_isadmin($user=null,$groups=null){ 400 return auth_ismanager($user,$groups,true); 401} 402 403/** 404 * Convinience function for auth_aclcheck() 405 * 406 * This checks the permissions for the current user 407 * 408 * @author Andreas Gohr <andi@splitbrain.org> 409 * 410 * @param string $id page ID (needs to be resolved and cleaned) 411 * @return int permission level 412 */ 413function auth_quickaclcheck($id){ 414 global $conf; 415 global $USERINFO; 416 # if no ACL is used always return upload rights 417 if(!$conf['useacl']) return AUTH_UPLOAD; 418 return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']); 419} 420 421/** 422 * Returns the maximum rights a user has for 423 * the given ID or its namespace 424 * 425 * @author Andreas Gohr <andi@splitbrain.org> 426 * 427 * @param string $id page ID (needs to be resolved and cleaned) 428 * @param string $user Username 429 * @param array $groups Array of groups the user is in 430 * @return int permission level 431 */ 432function auth_aclcheck($id,$user,$groups){ 433 global $conf; 434 global $AUTH_ACL; 435 436 // if no ACL is used always return upload rights 437 if(!$conf['useacl']) return AUTH_UPLOAD; 438 439 //make sure groups is an array 440 if(!is_array($groups)) $groups = array(); 441 442 //if user is superuser or in superusergroup return 255 (acl_admin) 443 if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; } 444 445 $user = auth_nameencode($user); 446 447 //prepend groups with @ and nameencode 448 $cnt = count($groups); 449 for($i=0; $i<$cnt; $i++){ 450 $groups[$i] = '@'.auth_nameencode($groups[$i]); 451 } 452 453 $ns = getNS($id); 454 $perm = -1; 455 456 if($user || count($groups)){ 457 //add ALL group 458 $groups[] = '@ALL'; 459 //add User 460 if($user) $groups[] = $user; 461 //build regexp 462 $regexp = join('|',$groups); 463 }else{ 464 $regexp = '@ALL'; 465 } 466 467 //check exact match first 468 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL); 469 if(count($matches)){ 470 foreach($matches as $match){ 471 $match = preg_replace('/#.*$/','',$match); //ignore comments 472 $acl = preg_split('/\s+/',$match); 473 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 474 if($acl[2] > $perm){ 475 $perm = $acl[2]; 476 } 477 } 478 if($perm > -1){ 479 //we had a match - return it 480 return $perm; 481 } 482 } 483 484 //still here? do the namespace checks 485 if($ns){ 486 $path = $ns.':\*'; 487 }else{ 488 $path = '\*'; //root document 489 } 490 491 do{ 492 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL); 493 if(count($matches)){ 494 foreach($matches as $match){ 495 $match = preg_replace('/#.*$/','',$match); //ignore comments 496 $acl = preg_split('/\s+/',$match); 497 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 498 if($acl[2] > $perm){ 499 $perm = $acl[2]; 500 } 501 } 502 //we had a match - return it 503 return $perm; 504 } 505 506 //get next higher namespace 507 $ns = getNS($ns); 508 509 if($path != '\*'){ 510 $path = $ns.':\*'; 511 if($path == ':\*') $path = '\*'; 512 }else{ 513 //we did this already 514 //looks like there is something wrong with the ACL 515 //break here 516 msg('No ACL setup yet! Denying access to everyone.'); 517 return AUTH_NONE; 518 } 519 }while(1); //this should never loop endless 520 521 //still here? return no permissions 522 return AUTH_NONE; 523} 524 525/** 526 * Encode ASCII special chars 527 * 528 * Some auth backends allow special chars in their user and groupnames 529 * The special chars are encoded with this function. Only ASCII chars 530 * are encoded UTF-8 multibyte are left as is (different from usual 531 * urlencoding!). 532 * 533 * Decoding can be done with rawurldecode 534 * 535 * @author Andreas Gohr <gohr@cosmocode.de> 536 * @see rawurldecode() 537 */ 538function auth_nameencode($name,$skip_group=false){ 539 global $cache_authname; 540 $cache =& $cache_authname; 541 $name = (string) $name; 542 543 if (!isset($cache[$name][$skip_group])) { 544 if($skip_group && $name{0} =='@'){ 545 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 546 "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1)); 547 }else{ 548 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 549 "'%'.dechex(ord(substr('\\1',-1)))",$name); 550 } 551 } 552 553 return $cache[$name][$skip_group]; 554} 555 556/** 557 * Create a pronouncable password 558 * 559 * @author Andreas Gohr <andi@splitbrain.org> 560 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 561 * 562 * @return string pronouncable password 563 */ 564function auth_pwgen(){ 565 $pw = ''; 566 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 567 $v = 'aeiou'; //vowels 568 $a = $c.$v; //both 569 570 //use two syllables... 571 for($i=0;$i < 2; $i++){ 572 $pw .= $c[rand(0, strlen($c)-1)]; 573 $pw .= $v[rand(0, strlen($v)-1)]; 574 $pw .= $a[rand(0, strlen($a)-1)]; 575 } 576 //... and add a nice number 577 $pw .= rand(10,99); 578 579 return $pw; 580} 581 582/** 583 * Sends a password to the given user 584 * 585 * @author Andreas Gohr <andi@splitbrain.org> 586 * 587 * @return bool true on success 588 */ 589function auth_sendPassword($user,$password){ 590 global $conf; 591 global $lang; 592 global $auth; 593 594 $hdrs = ''; 595 $userinfo = $auth->getUserData($user); 596 597 if(!$userinfo['mail']) return false; 598 599 $text = rawLocale('password'); 600 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 601 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 602 $text = str_replace('@LOGIN@',$user,$text); 603 $text = str_replace('@PASSWORD@',$password,$text); 604 $text = str_replace('@TITLE@',$conf['title'],$text); 605 606 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 607 $lang['regpwmail'], 608 $text, 609 $conf['mailfrom']); 610} 611 612/** 613 * Register a new user 614 * 615 * This registers a new user - Data is read directly from $_POST 616 * 617 * @author Andreas Gohr <andi@splitbrain.org> 618 * 619 * @return bool true on success, false on any error 620 */ 621function register(){ 622 global $lang; 623 global $conf; 624 global $auth; 625 626 if(!$_POST['save']) return false; 627 if(!$auth->canDo('addUser')) return false; 628 629 //clean username 630 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 631 $_POST['login'] = cleanID($_POST['login']); 632 //clean fullname and email 633 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 634 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 635 636 if( empty($_POST['login']) || 637 empty($_POST['fullname']) || 638 empty($_POST['email']) ){ 639 msg($lang['regmissing'],-1); 640 return false; 641 } 642 643 if ($conf['autopasswd']) { 644 $pass = auth_pwgen(); // automatically generate password 645 } elseif (empty($_POST['pass']) || 646 empty($_POST['passchk'])) { 647 msg($lang['regmissing'], -1); // complain about missing passwords 648 return false; 649 } elseif ($_POST['pass'] != $_POST['passchk']) { 650 msg($lang['regbadpass'], -1); // complain about misspelled passwords 651 return false; 652 } else { 653 $pass = $_POST['pass']; // accept checked and valid password 654 } 655 656 //check mail 657 if(!mail_isvalid($_POST['email'])){ 658 msg($lang['regbadmail'],-1); 659 return false; 660 } 661 662 //okay try to create the user 663 if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){ 664 msg($lang['reguexists'],-1); 665 return false; 666 } 667 668 // create substitutions for use in notification email 669 $substitutions = array( 670 'NEWUSER' => $_POST['login'], 671 'NEWNAME' => $_POST['fullname'], 672 'NEWEMAIL' => $_POST['email'], 673 ); 674 675 if (!$conf['autopasswd']) { 676 msg($lang['regsuccess2'],1); 677 notify('', 'register', '', $_POST['login'], false, $substitutions); 678 return true; 679 } 680 681 // autogenerated password? then send him the password 682 if (auth_sendPassword($_POST['login'],$pass)){ 683 msg($lang['regsuccess'],1); 684 notify('', 'register', '', $_POST['login'], false, $substitutions); 685 return true; 686 }else{ 687 msg($lang['regmailfail'],-1); 688 return false; 689 } 690} 691 692/** 693 * Update user profile 694 * 695 * @author Christopher Smith <chris@jalakai.co.uk> 696 */ 697function updateprofile() { 698 global $conf; 699 global $INFO; 700 global $lang; 701 global $auth; 702 703 if(empty($_POST['save'])) return false; 704 if(!checkSecurityToken()) return false; 705 706 // should not be able to get here without Profile being possible... 707 if(!$auth->canDo('Profile')) { 708 msg($lang['profna'],-1); 709 return false; 710 } 711 712 if ($_POST['newpass'] != $_POST['passchk']) { 713 msg($lang['regbadpass'], -1); // complain about misspelled passwords 714 return false; 715 } 716 717 //clean fullname and email 718 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 719 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 720 721 if (empty($_POST['fullname']) || empty($_POST['email'])) { 722 msg($lang['profnoempty'],-1); 723 return false; 724 } 725 726 if (!mail_isvalid($_POST['email'])){ 727 msg($lang['regbadmail'],-1); 728 return false; 729 } 730 731 if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname']; 732 if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email']; 733 if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass']; 734 735 if (!count($changes)) { 736 msg($lang['profnochange'], -1); 737 return false; 738 } 739 740 if ($conf['profileconfirm']) { 741 if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) { 742 msg($lang['badlogin'],-1); 743 return false; 744 } 745 } 746 747 if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) { 748 // update cookie and session with the changed data 749 $cookie = base64_decode($_COOKIE[DOKU_COOKIE]); 750 list($user,$sticky,$pass) = explode('|',$cookie,3); 751 if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt()); 752 753 auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky); 754 return true; 755 } 756} 757 758/** 759 * Send a new password 760 * 761 * This function handles both phases of the password reset: 762 * 763 * - handling the first request of password reset 764 * - validating the password reset auth token 765 * 766 * @author Benoit Chesneau <benoit@bchesneau.info> 767 * @author Chris Smith <chris@jalakai.co.uk> 768 * @author Andreas Gohr <andi@splitbrain.org> 769 * 770 * @return bool true on success, false on any error 771 */ 772function act_resendpwd(){ 773 global $lang; 774 global $conf; 775 global $auth; 776 777 if(!actionOK('resendpwd')) return false; 778 779 // should not be able to get here without modPass being possible... 780 if(!$auth->canDo('modPass')) { 781 msg($lang['resendna'],-1); 782 return false; 783 } 784 785 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']); 786 787 if($token){ 788 // we're in token phase 789 790 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 791 if(!@file_exists($tfile)){ 792 msg($lang['resendpwdbadauth'],-1); 793 return false; 794 } 795 $user = io_readfile($tfile); 796 @unlink($tfile); 797 $userinfo = $auth->getUserData($user); 798 if(!$userinfo['mail']) { 799 msg($lang['resendpwdnouser'], -1); 800 return false; 801 } 802 803 $pass = auth_pwgen(); 804 if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) { 805 msg('error modifying user data',-1); 806 return false; 807 } 808 809 if (auth_sendPassword($user,$pass)) { 810 msg($lang['resendpwdsuccess'],1); 811 } else { 812 msg($lang['regmailfail'],-1); 813 } 814 return true; 815 816 } else { 817 // we're in request phase 818 819 if(!$_POST['save']) return false; 820 821 if (empty($_POST['login'])) { 822 msg($lang['resendpwdmissing'], -1); 823 return false; 824 } else { 825 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 826 $user = cleanID($_POST['login']); 827 } 828 829 $userinfo = $auth->getUserData($user); 830 if(!$userinfo['mail']) { 831 msg($lang['resendpwdnouser'], -1); 832 return false; 833 } 834 835 // generate auth token 836 $token = md5(auth_cookiesalt().$user); //secret but user based 837 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 838 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&'); 839 840 io_saveFile($tfile,$user); 841 842 $text = rawLocale('pwconfirm'); 843 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 844 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 845 $text = str_replace('@LOGIN@',$user,$text); 846 $text = str_replace('@TITLE@',$conf['title'],$text); 847 $text = str_replace('@CONFIRM@',$url,$text); 848 849 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 850 $lang['regpwmail'], 851 $text, 852 $conf['mailfrom'])){ 853 msg($lang['resendpwdconfirm'],1); 854 }else{ 855 msg($lang['regmailfail'],-1); 856 } 857 return true; 858 } 859 860 return false; // never reached 861} 862 863/** 864 * Encrypts a password using the given method and salt 865 * 866 * If the selected method needs a salt and none was given, a random one 867 * is chosen. 868 * 869 * The following methods are understood: 870 * 871 * smd5 - Salted MD5 hashing 872 * apr1 - Apache salted MD5 hashing 873 * md5 - Simple MD5 hashing 874 * sha1 - SHA1 hashing 875 * ssha - Salted SHA1 hashing 876 * crypt - Unix crypt 877 * mysql - MySQL password (old method) 878 * my411 - MySQL 4.1.1 password 879 * kmd5 - Salted MD5 hashing as used by UNB 880 * 881 * @author Andreas Gohr <andi@splitbrain.org> 882 * @return string The crypted password 883 */ 884function auth_cryptPassword($clear,$method='',$salt=null){ 885 global $conf; 886 if(empty($method)) $method = $conf['passcrypt']; 887 888 //prepare a salt 889 if(is_null($salt)) $salt = md5(uniqid(rand(), true)); 890 891 switch(strtolower($method)){ 892 case 'smd5': 893 if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$'); 894 // when crypt can't handle SMD5, falls through to pure PHP implementation 895 $magic = '1'; 896 case 'apr1': 897 //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com> 898 if(!$magic) $magic = 'apr1'; 899 $salt = substr($salt,0,8); 900 $len = strlen($clear); 901 $text = $clear.'$'.$magic.'$'.$salt; 902 $bin = pack("H32", md5($clear.$salt.$clear)); 903 for($i = $len; $i > 0; $i -= 16) { 904 $text .= substr($bin, 0, min(16, $i)); 905 } 906 for($i = $len; $i > 0; $i >>= 1) { 907 $text .= ($i & 1) ? chr(0) : $clear{0}; 908 } 909 $bin = pack("H32", md5($text)); 910 for($i = 0; $i < 1000; $i++) { 911 $new = ($i & 1) ? $clear : $bin; 912 if ($i % 3) $new .= $salt; 913 if ($i % 7) $new .= $clear; 914 $new .= ($i & 1) ? $bin : $clear; 915 $bin = pack("H32", md5($new)); 916 } 917 $tmp = ''; 918 for ($i = 0; $i < 5; $i++) { 919 $k = $i + 6; 920 $j = $i + 12; 921 if ($j == 16) $j = 5; 922 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp; 923 } 924 $tmp = chr(0).chr(0).$bin[11].$tmp; 925 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)), 926 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 927 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); 928 return '$'.$magic.'$'.$salt.'$'.$tmp; 929 case 'md5': 930 return md5($clear); 931 case 'sha1': 932 return sha1($clear); 933 case 'ssha': 934 $salt=substr($salt,0,4); 935 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt); 936 case 'crypt': 937 return crypt($clear,substr($salt,0,2)); 938 case 'mysql': 939 //from http://www.php.net/mysql comment by <soren at byu dot edu> 940 $nr=0x50305735; 941 $nr2=0x12345671; 942 $add=7; 943 $charArr = preg_split("//", $clear); 944 foreach ($charArr as $char) { 945 if (($char == '') || ($char == ' ') || ($char == '\t')) continue; 946 $charVal = ord($char); 947 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 948 $nr2 += ($nr2 << 8) ^ $nr; 949 $add += $charVal; 950 } 951 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 952 case 'my411': 953 return '*'.sha1(pack("H*", sha1($clear))); 954 case 'kmd5': 955 $key = substr($salt, 16, 2); 956 $hash1 = strtolower(md5($key . md5($clear))); 957 $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16); 958 return $hash2; 959 default: 960 msg("Unsupported crypt method $method",-1); 961 } 962} 963 964/** 965 * Verifies a cleartext password against a crypted hash 966 * 967 * The method and salt used for the crypted hash is determined automatically 968 * then the clear text password is crypted using the same method. If both hashs 969 * match true is is returned else false 970 * 971 * @author Andreas Gohr <andi@splitbrain.org> 972 * @return bool 973 */ 974function auth_verifyPassword($clear,$crypt){ 975 $method=''; 976 $salt=''; 977 978 //determine the used method and salt 979 $len = strlen($crypt); 980 if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){ 981 $method = 'smd5'; 982 $salt = $m[1]; 983 }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){ 984 $method = 'apr1'; 985 $salt = $m[1]; 986 }elseif(substr($crypt,0,6) == '{SSHA}'){ 987 $method = 'ssha'; 988 $salt = substr(base64_decode(substr($crypt, 6)),20); 989 }elseif($len == 32){ 990 $method = 'md5'; 991 }elseif($len == 40){ 992 $method = 'sha1'; 993 }elseif($len == 16){ 994 $method = 'mysql'; 995 }elseif($len == 41 && $crypt[0] == '*'){ 996 $method = 'my411'; 997 }elseif($len == 34){ 998 $method = 'kmd5'; 999 $salt = $crypt; 1000 }else{ 1001 $method = 'crypt'; 1002 $salt = substr($crypt,0,2); 1003 } 1004 1005 //crypt and compare 1006 if(auth_cryptPassword($clear,$method,$salt) === $crypt){ 1007 return true; 1008 } 1009 return false; 1010} 1011 1012/** 1013 * Set the authentication cookie and add user identification data to the session 1014 * 1015 * @param string $user username 1016 * @param string $pass encrypted password 1017 * @param bool $sticky whether or not the cookie will last beyond the session 1018 */ 1019function auth_setCookie($user,$pass,$sticky) { 1020 global $conf; 1021 global $auth; 1022 global $USERINFO; 1023 1024 $USERINFO = $auth->getUserData($user); 1025 1026 // set cookie 1027 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass); 1028 $time = $sticky ? (time()+60*60*24*365) : 0; //one year 1029 if (version_compare(PHP_VERSION, '5.2.0', '>')) { 1030 setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true); 1031 }else{ 1032 setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl())); 1033 } 1034 // set session 1035 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1036 $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass; 1037 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1038 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1039 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1040} 1041 1042/** 1043 * Returns the user, (encrypted) password and sticky bit from cookie 1044 * 1045 * @returns array 1046 */ 1047function auth_getCookie(){ 1048 if (!isset($_COOKIE[DOKU_COOKIE])) { 1049 return array(null, null, null); 1050 } 1051 list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3); 1052 $sticky = (bool) $sticky; 1053 $pass = base64_decode($pass); 1054 $user = base64_decode($user); 1055 return array($user,$sticky,$pass); 1056} 1057 1058//Setup VIM: ex: et ts=2 enc=utf-8 : 1059