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