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