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