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