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