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