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