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