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