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