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