1<?php 2/** 3 * Authentication library 4 * 5 * Including this file will automatically try to login 6 * a user by calling auth_login() 7 * 8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 9 * @author Andreas Gohr <andi@splitbrain.org> 10 */ 11 12 if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/'); 13 require_once(DOKU_INC.'inc/common.php'); 14 require_once(DOKU_INC.'inc/io.php'); 15 16 // some ACL level defines 17 define('AUTH_NONE',0); 18 define('AUTH_READ',1); 19 define('AUTH_EDIT',2); 20 define('AUTH_CREATE',4); 21 define('AUTH_UPLOAD',8); 22 define('AUTH_DELETE',16); 23 define('AUTH_ADMIN',255); 24 25 global $conf; 26 27 if($conf['useacl']){ 28 require_once(DOKU_INC.'inc/blowfish.php'); 29 require_once(DOKU_INC.'inc/mail.php'); 30 31 global $auth; 32 33 // load the the backend auth functions and instantiate the auth object 34 if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) { 35 require_once(DOKU_INC.'inc/auth/basic.class.php'); 36 require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php'); 37 38 $auth_class = "auth_".$conf['authtype']; 39 if (class_exists($auth_class)) { 40 $auth = new $auth_class(); 41 if ($auth->success == false) { 42 unset($auth); 43 msg($lang['authtempfail'], -1); 44 45 // turn acl config setting off for the rest of this page 46 $conf['useacl'] = 0; 47 } 48 } else { 49 nice_die($lang['authmodfailed']); 50 } 51 } else { 52 nice_die($lang['authmodfailed']); 53 } 54 } 55 56 // do the login either by cookie or provided credentials 57 if($conf['useacl']){ 58 if (!isset($_REQUEST['u'])) $_REQUEST['u'] = ''; 59 if (!isset($_REQUEST['p'])) $_REQUEST['p'] = ''; 60 if (!isset($_REQUEST['r'])) $_REQUEST['r'] = ''; 61 62 // if no credentials were given try to use HTTP auth (for SSO) 63 if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){ 64 $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER']; 65 $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW']; 66 } 67 68 // external trust mechanism in place? 69 if(!is_null($auth) && $auth->canDo('external')){ 70 $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']); 71 }else{ 72 auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']); 73 } 74 75 //load ACL into a global array 76 global $AUTH_ACL; 77 if(is_readable(DOKU_CONF.'acl.auth.php')){ 78 $AUTH_ACL = file(DOKU_CONF.'acl.auth.php'); 79 }else{ 80 $AUTH_ACL = array(); 81 } 82 } 83 84/** 85 * This tries to login the user based on the sent auth credentials 86 * 87 * The authentication works like this: if a username was given 88 * a new login is assumed and user/password are checked. If they 89 * are correct the password is encrypted with blowfish and stored 90 * together with the username in a cookie - the same info is stored 91 * in the session, too. Additonally a browserID is stored in the 92 * session. 93 * 94 * If no username was given the cookie is checked: if the username, 95 * crypted password and browserID match between session and cookie 96 * no further testing is done and the user is accepted 97 * 98 * If a cookie was found but no session info was availabe the 99 * blowfish encrypted password from the cookie is decrypted and 100 * together with username rechecked by calling this function again. 101 * 102 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 103 * are set. 104 * 105 * @author Andreas Gohr <andi@splitbrain.org> 106 * 107 * @param string $user Username 108 * @param string $pass Cleartext Password 109 * @param bool $sticky Cookie should not expire 110 * @return bool true on successful auth 111*/ 112function auth_login($user,$pass,$sticky=false){ 113 global $USERINFO; 114 global $conf; 115 global $lang; 116 global $auth; 117 $sticky ? $sticky = true : $sticky = false; //sanity check 118 119 if(!empty($user)){ 120 //usual login 121 if ($auth->checkPass($user,$pass)){ 122 // make logininfo globally available 123 $_SERVER['REMOTE_USER'] = $user; 124 $USERINFO = $auth->getUserData($user); //FIXME move all references to session 125 126 // set cookie 127 $pass = PMA_blowfish_encrypt($pass,auth_cookiesalt()); 128 $cookie = base64_encode("$user|$sticky|$pass"); 129 if($sticky) $time = time()+60*60*24*365; //one year 130 setcookie(DOKU_COOKIE,$cookie,$time,'/'); 131 132 // set session 133 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 134 $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass; 135 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 136 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 137 return true; 138 }else{ 139 //invalid credentials - log off 140 msg($lang['badlogin'],-1); 141 auth_logoff(); 142 return false; 143 } 144 }else{ 145 // read cookie information 146 $cookie = base64_decode($_COOKIE[DOKU_COOKIE]); 147 list($user,$sticky,$pass) = split('\|',$cookie,3); 148 // get session info 149 $session = $_SESSION[DOKU_COOKIE]['auth']; 150 151 if($user && $pass){ 152 // we got a cookie - see if we can trust it 153 if(isset($session) && 154 ($session['user'] == $user) && 155 ($session['pass'] == $pass) && //still crypted 156 ($session['buid'] == auth_browseruid()) ){ 157 // he has session, cookie and browser right - let him in 158 $_SERVER['REMOTE_USER'] = $user; 159 $USERINFO = $session['info']; //FIXME move all references to session 160 return true; 161 } 162 // no we don't trust it yet - recheck pass 163 $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt()); 164 return auth_login($user,$pass,$sticky); 165 } 166 } 167 //just to be sure 168 auth_logoff(); 169 return false; 170} 171 172/** 173 * Builds a pseudo UID from browser and IP data 174 * 175 * This is neither unique nor unfakable - still it adds some 176 * security. Using the first part of the IP makes sure 177 * proxy farms like AOLs are stil okay. 178 * 179 * @author Andreas Gohr <andi@splitbrain.org> 180 * 181 * @return string a MD5 sum of various browser headers 182 */ 183function auth_browseruid(){ 184 $uid = ''; 185 $uid .= $_SERVER['HTTP_USER_AGENT']; 186 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING']; 187 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE']; 188 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET']; 189 $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.')); 190 return md5($uid); 191} 192 193/** 194 * Creates a random key to encrypt the password in cookies 195 * 196 * This function tries to read the password for encrypting 197 * cookies from $conf['metadir'].'/_htcookiesalt' 198 * if no such file is found a random key is created and 199 * and stored in this file. 200 * 201 * @author Andreas Gohr <andi@splitbrain.org> 202 * 203 * @return string 204 */ 205function auth_cookiesalt(){ 206 global $conf; 207 $file = $conf['metadir'].'/_htcookiesalt'; 208 $salt = io_readFile($file); 209 if(empty($salt)){ 210 $salt = uniqid(rand(),true); 211 io_saveFile($file,$salt); 212 } 213 return $salt; 214} 215 216/** 217 * This clears all authenticationdata and thus log the user 218 * off 219 * 220 * @author Andreas Gohr <andi@splitbrain.org> 221 */ 222function auth_logoff(){ 223 global $conf; 224 global $USERINFO; 225 global $INFO, $ID; 226 global $auth; 227 228 if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 229 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 230 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 231 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 232 if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 233 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 234 if(isset($_SERVER['REMOTE_USER'])) 235 unset($_SERVER['REMOTE_USER']); 236 $USERINFO=null; //FIXME 237 setcookie(DOKU_COOKIE,'',time()-600000,'/'); 238 239 if($auth && $auth->canDo('logoff')){ 240 $auth->logOff(); 241 } 242} 243 244/** 245 * Convinience function for auth_aclcheck() 246 * 247 * This checks the permissions for the current user 248 * 249 * @author Andreas Gohr <andi@splitbrain.org> 250 * 251 * @param string $id page ID 252 * @return int permission level 253 */ 254function auth_quickaclcheck($id){ 255 global $conf; 256 global $USERINFO; 257 # if no ACL is used always return upload rights 258 if(!$conf['useacl']) return AUTH_UPLOAD; 259 return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']); 260} 261 262/** 263 * Returns the maximum rights a user has for 264 * the given ID or its namespace 265 * 266 * @author Andreas Gohr <andi@splitbrain.org> 267 * 268 * @param string $id page ID 269 * @param string $user Username 270 * @param array $groups Array of groups the user is in 271 * @return int permission level 272 */ 273function auth_aclcheck($id,$user,$groups){ 274 global $conf; 275 global $AUTH_ACL; 276 277 # if no ACL is used always return upload rights 278 if(!$conf['useacl']) return AUTH_UPLOAD; 279 280 $user = auth_nameencode($user); 281 282 //if user is superuser return 255 (acl_admin) 283 if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; } 284 285 //make sure groups is an array 286 if(!is_array($groups)) $groups = array(); 287 288 //prepend groups with @ and nameencode 289 $cnt = count($groups); 290 for($i=0; $i<$cnt; $i++){ 291 $groups[$i] = '@'.auth_nameencode($groups[$i]); 292 } 293 //if user is in superuser group return 255 (acl_admin) 294 if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; } 295 296 $ns = getNS($id); 297 $perm = -1; 298 299 if($user){ 300 //add ALL group 301 $groups[] = '@ALL'; 302 //add User 303 $groups[] = $user; 304 //build regexp 305 $regexp = join('|',$groups); 306 }else{ 307 $regexp = '@ALL'; 308 } 309 310 //check exact match first 311 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL); 312 if(count($matches)){ 313 foreach($matches as $match){ 314 $match = preg_replace('/#.*$/','',$match); //ignore comments 315 $acl = preg_split('/\s+/',$match); 316 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 317 if($acl[2] > $perm){ 318 $perm = $acl[2]; 319 } 320 } 321 if($perm > -1){ 322 //we had a match - return it 323 return $perm; 324 } 325 } 326 327 //still here? do the namespace checks 328 if($ns){ 329 $path = $ns.':\*'; 330 }else{ 331 $path = '\*'; //root document 332 } 333 334 do{ 335 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL); 336 if(count($matches)){ 337 foreach($matches as $match){ 338 $match = preg_replace('/#.*$/','',$match); //ignore comments 339 $acl = preg_split('/\s+/',$match); 340 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 341 if($acl[2] > $perm){ 342 $perm = $acl[2]; 343 } 344 } 345 //we had a match - return it 346 return $perm; 347 } 348 349 //get next higher namespace 350 $ns = getNS($ns); 351 352 if($path != '\*'){ 353 $path = $ns.':\*'; 354 if($path == ':\*') $path = '\*'; 355 }else{ 356 //we did this already 357 //looks like there is something wrong with the ACL 358 //break here 359 msg('No ACL setup yet! Denying access to everyone.'); 360 return AUTH_NONE; 361 } 362 }while(1); //this should never loop endless 363 364 //still here? return no permissions 365 return AUTH_NONE; 366} 367 368/** 369 * Encode ASCII special chars 370 * 371 * Some auth backends allow special chars in their user and groupnames 372 * The special chars are encoded with this function. Only ASCII chars 373 * are encoded UTF-8 multibyte are left as is (different from usual 374 * urlencoding!). 375 * 376 * Decoding can be done with rawurldecode 377 * 378 * @author Andreas Gohr <gohr@cosmocode.de> 379 * @see rawurldecode() 380 */ 381function auth_nameencode($name,$skip_group=false){ 382 global $cache_authname; 383 $cache =& $cache_authname; 384 385 if (!isset($cache[$name][$skip_group])) { 386 if($skip_group && $name{0} =='@'){ 387 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 388 "'%'.dechex(ord('\\1'))",substr($name,1)); 389 }else{ 390 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 391 "'%'.dechex(ord('\\1'))",$name); 392 } 393 } 394 395 return $cache[$name][$skip_group]; 396} 397 398/** 399 * Create a pronouncable password 400 * 401 * @author Andreas Gohr <andi@splitbrain.org> 402 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 403 * 404 * @return string pronouncable password 405 */ 406function auth_pwgen(){ 407 $pw = ''; 408 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 409 $v = 'aeiou'; //vowels 410 $a = $c.$v; //both 411 412 //use two syllables... 413 for($i=0;$i < 2; $i++){ 414 $pw .= $c[rand(0, strlen($c)-1)]; 415 $pw .= $v[rand(0, strlen($v)-1)]; 416 $pw .= $a[rand(0, strlen($a)-1)]; 417 } 418 //... and add a nice number 419 $pw .= rand(10,99); 420 421 return $pw; 422} 423 424/** 425 * Sends a password to the given user 426 * 427 * @author Andreas Gohr <andi@splitbrain.org> 428 * 429 * @return bool true on success 430 */ 431function auth_sendPassword($user,$password){ 432 global $conf; 433 global $lang; 434 global $auth; 435 436 $hdrs = ''; 437 $userinfo = $auth->getUserData($user); 438 439 if(!$userinfo['mail']) return false; 440 441 $text = rawLocale('password'); 442 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 443 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 444 $text = str_replace('@LOGIN@',$user,$text); 445 $text = str_replace('@PASSWORD@',$password,$text); 446 $text = str_replace('@TITLE@',$conf['title'],$text); 447 448 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 449 $lang['regpwmail'], 450 $text, 451 $conf['mailfrom']); 452} 453 454/** 455 * Register a new user 456 * 457 * This registers a new user - Data is read directly from $_POST 458 * 459 * @author Andreas Gohr <andi@splitbrain.org> 460 * 461 * @return bool true on success, false on any error 462 */ 463function register(){ 464 global $lang; 465 global $conf; 466 global $auth; 467 468 if(!$_POST['save']) return false; 469 if(!$auth->canDo('addUser')) return false; 470 471 //clean username 472 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 473 $_POST['login'] = cleanID($_POST['login']); 474 //clean fullname and email 475 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 476 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 477 478 if( empty($_POST['login']) || 479 empty($_POST['fullname']) || 480 empty($_POST['email']) ){ 481 msg($lang['regmissing'],-1); 482 return false; 483 } 484 485 if ($conf['autopasswd']) { 486 $pass = auth_pwgen(); // automatically generate password 487 } elseif (empty($_POST['pass']) || 488 empty($_POST['passchk'])) { 489 msg($lang['regmissing'], -1); // complain about missing passwords 490 return false; 491 } elseif ($_POST['pass'] != $_POST['passchk']) { 492 msg($lang['regbadpass'], -1); // complain about misspelled passwords 493 return false; 494 } else { 495 $pass = $_POST['pass']; // accept checked and valid password 496 } 497 498 //check mail 499 if(!mail_isvalid($_POST['email'])){ 500 msg($lang['regbadmail'],-1); 501 return false; 502 } 503 504 //okay try to create the user 505 if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){ 506 msg($lang['reguexists'],-1); 507 return false; 508 } 509 510 // create substitutions for use in notification email 511 $substitutions = array( 512 'NEWUSER' => $_POST['login'], 513 'NEWNAME' => $_POST['fullname'], 514 'NEWEMAIL' => $_POST['email'], 515 ); 516 517 if (!$conf['autopasswd']) { 518 msg($lang['regsuccess2'],1); 519 notify('', 'register', '', $_POST['login'], false, $substitutions); 520 return true; 521 } 522 523 // autogenerated password? then send him the password 524 if (auth_sendPassword($_POST['login'],$pass)){ 525 msg($lang['regsuccess'],1); 526 notify('', 'register', '', $_POST['login'], false, $substitutions); 527 return true; 528 }else{ 529 msg($lang['regmailfail'],-1); 530 return false; 531 } 532} 533 534/** 535 * Update user profile 536 * 537 * @author Christopher Smith <chris@jalakai.co.uk> 538 */ 539function updateprofile() { 540 global $conf; 541 global $INFO; 542 global $lang; 543 global $auth; 544 545 if(empty($_POST['save'])) return false; 546 547 // should not be able to get here without Profile being possible... 548 if(!$auth->canDo('Profile')) { 549 msg($lang['profna'],-1); 550 return false; 551 } 552 553 if ($_POST['newpass'] != $_POST['passchk']) { 554 msg($lang['regbadpass'], -1); // complain about misspelled passwords 555 return false; 556 } 557 558 //clean fullname and email 559 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 560 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 561 562 if (empty($_POST['fullname']) || empty($_POST['email'])) { 563 msg($lang['profnoempty'],-1); 564 return false; 565 } 566 567 if (!mail_isvalid($_POST['email'])){ 568 msg($lang['regbadmail'],-1); 569 return false; 570 } 571 572 if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname']; 573 if ($_POST['email'] != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email']; 574 if (!empty($_POST['newpass'])) $changes['pass'] = $_POST['newpass']; 575 576 if (!count($changes)) { 577 msg($lang['profnochange'], -1); 578 return false; 579 } 580 581 if ($conf['profileconfirm']) { 582 if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) { 583 msg($lang['badlogin'],-1); 584 return false; 585 } 586 } 587 588 return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes); 589} 590 591/** 592 * Send a new password 593 * 594 * This function handles both phases of the password reset: 595 * 596 * - handling the first request of password reset 597 * - validating the password reset auth token 598 * 599 * @author Benoit Chesneau <benoit@bchesneau.info> 600 * @author Chris Smith <chris@jalakai.co.uk> 601 * @author Andreas Gohr <andi@splitbrain.org> 602 * 603 * @return bool true on success, false on any error 604*/ 605function act_resendpwd(){ 606 global $lang; 607 global $conf; 608 global $auth; 609 610 if(!actionOK('resendpwd')) return false; 611 612 // should not be able to get here without modPass being possible... 613 if(!$auth->canDo('modPass')) { 614 msg($lang['resendna'],-1); 615 return false; 616 } 617 618 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']); 619 620 if($token){ 621 // we're in token phase 622 623 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 624 if(!@file_exists($tfile)){ 625 msg($lang['resendpwdbadauth'],-1); 626 return false; 627 } 628 $user = io_readfile($tfile); 629 @unlink($tfile); 630 $userinfo = $auth->getUserData($user); 631 if(!$userinfo['mail']) { 632 msg($lang['resendpwdnouser'], -1); 633 return false; 634 } 635 636 $pass = auth_pwgen(); 637 if (!$auth->modifyUser($user,array('pass' => $pass))) { 638 msg('error modifying user data',-1); 639 return false; 640 } 641 642 if (auth_sendPassword($user,$pass)) { 643 msg($lang['resendpwdsuccess'],1); 644 } else { 645 msg($lang['regmailfail'],-1); 646 } 647 return true; 648 649 } else { 650 // we're in request phase 651 652 if(!$_POST['save']) return false; 653 654 if (empty($_POST['login'])) { 655 msg($lang['resendpwdmissing'], -1); 656 return false; 657 } else { 658 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 659 $user = cleanID($_POST['login']); 660 } 661 662 $userinfo = $auth->getUserData($user); 663 if(!$userinfo['mail']) { 664 msg($lang['resendpwdnouser'], -1); 665 return false; 666 } 667 668 // generate auth token 669 $token = md5(auth_cookiesalt().$user); //secret but user based 670 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 671 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&'); 672 673 io_saveFile($tfile,$user); 674 675 $text = rawLocale('pwconfirm'); 676 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 677 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 678 $text = str_replace('@LOGIN@',$user,$text); 679 $text = str_replace('@TITLE@',$conf['title'],$text); 680 $text = str_replace('@CONFIRM@',$url,$text); 681 682 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 683 $lang['regpwmail'], 684 $text, 685 $conf['mailfrom'])){ 686 msg($lang['resendpwdconfirm'],1); 687 }else{ 688 msg($lang['regmailfail'],-1); 689 } 690 return true; 691 } 692 693 return false; // never reached 694} 695 696/** 697 * Uses a regular expresion to check if a given mail address is valid 698 * 699 * May not be completly RFC conform! 700 * 701 * @link http://www.webmasterworld.com/forum88/135.htm 702 * 703 * @param string $email the address to check 704 * @return bool true if address is valid 705 */ 706function isvalidemail($email){ 707 return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email); 708} 709 710/** 711 * Encrypts a password using the given method and salt 712 * 713 * If the selected method needs a salt and none was given, a random one 714 * is chosen. 715 * 716 * The following methods are understood: 717 * 718 * smd5 - Salted MD5 hashing 719 * md5 - Simple MD5 hashing 720 * sha1 - SHA1 hashing 721 * ssha - Salted SHA1 hashing 722 * crypt - Unix crypt 723 * mysql - MySQL password (old method) 724 * my411 - MySQL 4.1.1 password 725 * 726 * @author Andreas Gohr <andi@splitbrain.org> 727 * @return string The crypted password 728 */ 729function auth_cryptPassword($clear,$method='',$salt=''){ 730 global $conf; 731 if(empty($method)) $method = $conf['passcrypt']; 732 733 //prepare a salt 734 if(empty($salt)) $salt = md5(uniqid(rand(), true)); 735 736 switch(strtolower($method)){ 737 case 'smd5': 738 return crypt($clear,'$1$'.substr($salt,0,8).'$'); 739 case 'md5': 740 return md5($clear); 741 case 'sha1': 742 return sha1($clear); 743 case 'ssha': 744 $salt=substr($salt,0,4); 745 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt); 746 case 'crypt': 747 return crypt($clear,substr($salt,0,2)); 748 case 'mysql': 749 //from http://www.php.net/mysql comment by <soren at byu dot edu> 750 $nr=0x50305735; 751 $nr2=0x12345671; 752 $add=7; 753 $charArr = preg_split("//", $clear); 754 foreach ($charArr as $char) { 755 if (($char == '') || ($char == ' ') || ($char == '\t')) continue; 756 $charVal = ord($char); 757 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 758 $nr2 += ($nr2 << 8) ^ $nr; 759 $add += $charVal; 760 } 761 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 762 case 'my411': 763 return '*'.sha1(pack("H*", sha1($clear))); 764 default: 765 msg("Unsupported crypt method $method",-1); 766 } 767} 768 769/** 770 * Verifies a cleartext password against a crypted hash 771 * 772 * The method and salt used for the crypted hash is determined automatically 773 * then the clear text password is crypted using the same method. If both hashs 774 * match true is is returned else false 775 * 776 * @author Andreas Gohr <andi@splitbrain.org> 777 * @return bool 778 */ 779function auth_verifyPassword($clear,$crypt){ 780 $method=''; 781 $salt=''; 782 783 //determine the used method and salt 784 $len = strlen($crypt); 785 if(substr($crypt,0,3) == '$1$'){ 786 $method = 'smd5'; 787 $salt = substr($crypt,3,8); 788 }elseif(substr($crypt,0,6) == '{SSHA}'){ 789 $method = 'ssha'; 790 $salt = substr(base64_decode(substr($crypt, 6)),20); 791 }elseif($len == 32){ 792 $method = 'md5'; 793 }elseif($len == 40){ 794 $method = 'sha1'; 795 }elseif($len == 16){ 796 $method = 'mysql'; 797 }elseif($len == 41 && $crypt[0] == '*'){ 798 $method = 'my411'; 799 }else{ 800 $method = 'crypt'; 801 $salt = substr($crypt,0,2); 802 } 803 804 //crypt and compare 805 if(auth_cryptPassword($clear,$method,$salt) === $crypt){ 806 return true; 807 } 808 return false; 809} 810 811//Setup VIM: ex: et ts=2 enc=utf-8 : 812