1ed7b5f09Sandi<?php 2d4f83172SAndreas Gohr 315fae107Sandi/** 415fae107Sandi * Authentication library 515fae107Sandi * 615fae107Sandi * Including this file will automatically try to login 715fae107Sandi * a user by calling auth_login() 815fae107Sandi * 915fae107Sandi * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 1015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 1115fae107Sandi */ 12d4f83172SAndreas Gohr 131cedacf2SAndreas Gohruse dokuwiki\ErrorHandler; 14cf927d07Ssplitbrainuse dokuwiki\JWT; 1524870174SAndreas Gohruse dokuwiki\Utf8\PhpString; 1696348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin; 1796348f27SAndreas Gohruse dokuwiki\Extension\Event; 1896348f27SAndreas Gohruse dokuwiki\Extension\PluginController; 19c3cc6e05SAndreas Gohruse dokuwiki\PassHash; 2075d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender; 21927933f5SAndreas Gohruse phpseclib3\Crypt\AES; 22927933f5SAndreas Gohruse phpseclib3\Crypt\Common\SymmetricKey; 231cedacf2SAndreas Gohruse phpseclib3\Exception\BadDecryptionException; 24c3cc6e05SAndreas Gohr 2516905344SAndreas Gohr/** 2616905344SAndreas Gohr * Initialize the auth system. 2716905344SAndreas Gohr * 2816905344SAndreas Gohr * This function is automatically called at the end of init.php 2916905344SAndreas Gohr * 3016905344SAndreas Gohr * This used to be the main() of the auth.php 3116905344SAndreas Gohr * 3216905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader 3316905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions 34ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK 35ab5d26daSAndreas Gohr * @return bool 3616905344SAndreas Gohr */ 37d868eb89SAndreas Gohrfunction auth_setup() 38d868eb89SAndreas Gohr{ 39742c66f8Schris global $conf; 40e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 4103c4aec3Schris global $auth; 42bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 43bcc94b2cSAndreas Gohr global $INPUT; 449a9714acSDominik Eckelmann global $AUTH_ACL; 459a9714acSDominik Eckelmann global $lang; 463a7140a1SAndreas Gohr /* @var PluginController $plugin_controller */ 479c29eea5SJan Schumann global $plugin_controller; 4824870174SAndreas Gohr $AUTH_ACL = []; 4903c4aec3Schris 50b9cda918SAndreas Gohr // unset REMOTE_USER if empty 51b9cda918SAndreas Gohr if ($INPUT->server->str('REMOTE_USER') === '') { 52b9cda918SAndreas Gohr $INPUT->server->remove('REMOTE_USER'); 53b9cda918SAndreas Gohr } 54b9cda918SAndreas Gohr 5516905344SAndreas Gohr if (!$conf['useacl']) return false; 5616905344SAndreas Gohr 579c29eea5SJan Schumann // try to load auth backend from plugins 589c29eea5SJan Schumann foreach ($plugin_controller->getList('auth') as $plugin) { 599c29eea5SJan Schumann if ($conf['authtype'] === $plugin) { 60f4476bd9SJan Schumann $auth = $plugin_controller->load('auth', $plugin); 619c29eea5SJan Schumann break; 629c29eea5SJan Schumann } 639c29eea5SJan Schumann } 648b06d178Schris 656547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) { 6671c734a9SGerrit Uitslag msg($lang['authtempfail'], -1); 673094e817SAndreas Gohr return false; 683094e817SAndreas Gohr } 698b06d178Schris 706416b708SMichael Hamann if ($auth->success == false) { 710f4f4adfSAndreas Gohr // degrade to unauthenticated user 72ecad51ddSAndreas Gohr $auth = null; 730f4f4adfSAndreas Gohr auth_logoff(); 74cd52f92dSchris msg($lang['authtempfail'], -1); 756416b708SMichael Hamann return false; 76d2dde4ebSMatthias Grimm } 7716905344SAndreas Gohr 7816905344SAndreas Gohr // do the login either by cookie or provided credentials XXX 79bcc94b2cSAndreas Gohr $INPUT->set('http_credentials', false); 80bcc94b2cSAndreas Gohr if (!$conf['rememberme']) $INPUT->set('r', false); 81bbbd6568SAndreas Gohr 8262bf3ac0SDamien Regad // Populate Basic Auth user/password from Authorization header 8362bf3ac0SDamien Regad // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION 8462bf3ac0SDamien Regad $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION'); 8562bf3ac0SDamien Regad if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) { 8662bf3ac0SDamien Regad $userpass = explode(':', base64_decode($matches[1])); 8724870174SAndreas Gohr [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass; 88528ddc7cSAndreas Gohr } 89528ddc7cSAndreas Gohr 901e8c9c90SAndreas Gohr // if no credentials were given try to use HTTP auth (for SSO) 9103062864SAndreas Gohr if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) { 9203062864SAndreas Gohr $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER')); 9303062864SAndreas Gohr $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW')); 94bcc94b2cSAndreas Gohr $INPUT->set('http_credentials', true); 951e8c9c90SAndreas Gohr } 961e8c9c90SAndreas Gohr 97395c2f0fSAndreas Gohr // apply cleaning (auth specific user names, remove control chars) 9893a7873eSAndreas Gohr if (true === $auth->success) { 99395c2f0fSAndreas Gohr $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); 100395c2f0fSAndreas Gohr $INPUT->set('p', stripctl($INPUT->str('p'))); 101f4476bd9SJan Schumann } 102191bb90aSAndreas Gohr 103455aa67eSAndreas Gohr if (!auth_tokenlogin()) { 10481e99965SPhy $ok = null; 105455aa67eSAndreas Gohr 1068407f251Ssplitbrain if ($auth->canDo('external')) { 10781e99965SPhy $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); 10881e99965SPhy } 10981e99965SPhy 11081e99965SPhy if ($ok === null) { 11181e99965SPhy // external trust mechanism not in place, or returns no result, 11281e99965SPhy // then attempt auth_login 11324870174SAndreas Gohr $evdata = [ 114bcc94b2cSAndreas Gohr 'user' => $INPUT->str('u'), 115bcc94b2cSAndreas Gohr 'password' => $INPUT->str('p'), 116bcc94b2cSAndreas Gohr 'sticky' => $INPUT->bool('r'), 117bcc94b2cSAndreas Gohr 'silent' => $INPUT->bool('http_credentials') 11824870174SAndreas Gohr ]; 119cbb44eabSAndreas Gohr Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); 120f5cb575dSAndreas Gohr } 121455aa67eSAndreas Gohr } 122f5cb575dSAndreas Gohr 12316905344SAndreas Gohr //load ACL into a global array XXX 12475c93b77SAndreas Gohr $AUTH_ACL = auth_loadACL(); 125ab5d26daSAndreas Gohr 126ab5d26daSAndreas Gohr return true; 12775c93b77SAndreas Gohr} 12875c93b77SAndreas Gohr 12975c93b77SAndreas Gohr/** 13075c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards 13175c93b77SAndreas Gohr * 13275c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 13342ea7f44SGerrit Uitslag * 134ab5d26daSAndreas Gohr * @return array 13575c93b77SAndreas Gohr */ 136d868eb89SAndreas Gohrfunction auth_loadACL() 137d868eb89SAndreas Gohr{ 13875c93b77SAndreas Gohr global $config_cascade; 139b78bf706Sromain global $USERINFO; 140585bf44eSChristopher Smith /* @var Input $INPUT */ 141585bf44eSChristopher Smith global $INPUT; 14275c93b77SAndreas Gohr 14324870174SAndreas Gohr if (!is_readable($config_cascade['acl']['default'])) return []; 14475c93b77SAndreas Gohr 14575c93b77SAndreas Gohr $acl = file($config_cascade['acl']['default']); 14675c93b77SAndreas Gohr 14724870174SAndreas Gohr $out = []; 1489ce556d2SAndreas Gohr foreach ($acl as $line) { 1499ce556d2SAndreas Gohr $line = trim($line); 1502401f18dSSyntaxseed if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments 15124870174SAndreas Gohr [$id, $rest] = preg_split('/[ \t]+/', $line, 2); 15232e82180SAndreas Gohr 153443e135dSChristopher Smith // substitute user wildcard first (its 1:1) 154ad3d68d7SChristopher Smith if (strstr($line, '%USER%')) { 155ad3d68d7SChristopher Smith // if user is not logged in, this ACL line is meaningless - skip it 156585bf44eSChristopher Smith if (!$INPUT->server->has('REMOTE_USER')) continue; 157ad3d68d7SChristopher Smith 158585bf44eSChristopher Smith $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id); 159585bf44eSChristopher Smith $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest); 160ad3d68d7SChristopher Smith } 161ad3d68d7SChristopher Smith 162ad3d68d7SChristopher Smith // substitute group wildcard (its 1:m) 1639ce556d2SAndreas Gohr if (strstr($line, '%GROUP%')) { 164ad3d68d7SChristopher Smith // if user is not logged in, grps is empty, no output will be added (i.e. skipped) 16506f34f54SPhy if (isset($USERINFO['grps'])) { 1669ce556d2SAndreas Gohr foreach ((array) $USERINFO['grps'] as $grp) { 167b78bf706Sromain $nid = str_replace('%GROUP%', cleanID($grp), $id); 16832e82180SAndreas Gohr $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest); 16932e82180SAndreas Gohr $out[] = "$nid\t$nrest"; 170b78bf706Sromain } 17106f34f54SPhy } 17232e82180SAndreas Gohr } else { 17332e82180SAndreas Gohr $out[] = "$id\t$rest"; 174a8fe108bSGuy Brand } 17511799630Sandi } 1769ce556d2SAndreas Gohr 17732e82180SAndreas Gohr return $out; 178f3f0262cSandi} 179f3f0262cSandi 180ab5d26daSAndreas Gohr/** 181455aa67eSAndreas Gohr * Try a token login 182455aa67eSAndreas Gohr * 183455aa67eSAndreas Gohr * @return bool true if token login succeeded 184455aa67eSAndreas Gohr */ 185cf927d07Ssplitbrainfunction auth_tokenlogin() 186cf927d07Ssplitbrain{ 187455aa67eSAndreas Gohr global $USERINFO; 188455aa67eSAndreas Gohr global $INPUT; 189455aa67eSAndreas Gohr /** @var DokuWiki_Auth_Plugin $auth */ 190455aa67eSAndreas Gohr global $auth; 191455aa67eSAndreas Gohr if (!$auth) return false; 192455aa67eSAndreas Gohr 1937ffd5bd2SAndreas Gohr $headers = []; 194*0a302752SAndreas Gohr 195*0a302752SAndreas Gohr // try to get the headers from Apache 196*0a302752SAndreas Gohr if (function_exists('getallheaders')) { 197*0a302752SAndreas Gohr $headers = getallheaders(); 198*0a302752SAndreas Gohr if (is_array($headers)) { 199*0a302752SAndreas Gohr $headers = array_change_key_case($headers); 200*0a302752SAndreas Gohr } 201*0a302752SAndreas Gohr } 202*0a302752SAndreas Gohr 203*0a302752SAndreas Gohr // get the headers from $_SERVER 204*0a302752SAndreas Gohr if (!$headers) { 2057ffd5bd2SAndreas Gohr foreach ($_SERVER as $key => $value) { 2067ffd5bd2SAndreas Gohr if (substr($key, 0, 5) === 'HTTP_') { 2077ffd5bd2SAndreas Gohr $headers[strtolower(substr($key, 5))] = $value; 208455aa67eSAndreas Gohr } 2097ffd5bd2SAndreas Gohr } 2107ffd5bd2SAndreas Gohr } 2117ffd5bd2SAndreas Gohr 2127ffd5bd2SAndreas Gohr // check authorization header 2137ffd5bd2SAndreas Gohr if (isset($headers['authorization'])) { 2147ffd5bd2SAndreas Gohr [$type, $token] = sexplode(' ', $headers['authorization'], 2); 2157ffd5bd2SAndreas Gohr if ($type !== 'Bearer') $token = ''; // not the token we want 2167ffd5bd2SAndreas Gohr } 2177ffd5bd2SAndreas Gohr 2187ffd5bd2SAndreas Gohr // check x-dokuwiki-token header 2197ffd5bd2SAndreas Gohr if (isset($headers['x-dokuwiki-token'])) { 2207ffd5bd2SAndreas Gohr $token = $headers['x-dokuwiki-token']; 2217ffd5bd2SAndreas Gohr } 2227ffd5bd2SAndreas Gohr 2237ffd5bd2SAndreas Gohr if (empty($token)) return false; 224455aa67eSAndreas Gohr 225455aa67eSAndreas Gohr // check token 226455aa67eSAndreas Gohr try { 227cf927d07Ssplitbrain $authtoken = JWT::validate($token); 228455aa67eSAndreas Gohr } catch (Exception $e) { 229455aa67eSAndreas Gohr msg(hsc($e->getMessage()), -1); 230455aa67eSAndreas Gohr return false; 231455aa67eSAndreas Gohr } 232455aa67eSAndreas Gohr 233455aa67eSAndreas Gohr // fetch user info from backend 234455aa67eSAndreas Gohr $user = $authtoken->getUser(); 235455aa67eSAndreas Gohr $USERINFO = $auth->getUserData($user); 236455aa67eSAndreas Gohr if (!$USERINFO) return false; 237455aa67eSAndreas Gohr 238455aa67eSAndreas Gohr // the code is correct, set up user 239455aa67eSAndreas Gohr $INPUT->server->set('REMOTE_USER', $user); 240455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 241455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope'; 242455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 243455aa67eSAndreas Gohr 244455aa67eSAndreas Gohr return true; 245455aa67eSAndreas Gohr} 246455aa67eSAndreas Gohr 247455aa67eSAndreas Gohr/** 248ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK 249ab5d26daSAndreas Gohr * 25042ea7f44SGerrit Uitslag * @param array $evdata 251ab5d26daSAndreas Gohr * @return bool 2524dc42f7fSGerrit Uitslag * @throws Exception 253ab5d26daSAndreas Gohr */ 254d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata) 255d868eb89SAndreas Gohr{ 256ab5d26daSAndreas Gohr return auth_login( 257ab5d26daSAndreas Gohr $evdata['user'], 258b5ee21aaSAdrian Lang $evdata['password'], 259b5ee21aaSAdrian Lang $evdata['sticky'], 260ab5d26daSAndreas Gohr $evdata['silent'] 261ab5d26daSAndreas Gohr ); 262b5ee21aaSAdrian Lang} 263b5ee21aaSAdrian Lang 264f3f0262cSandi/** 265f3f0262cSandi * This tries to login the user based on the sent auth credentials 266f3f0262cSandi * 267f3f0262cSandi * The authentication works like this: if a username was given 26815fae107Sandi * a new login is assumed and user/password are checked. If they 26915fae107Sandi * are correct the password is encrypted with blowfish and stored 27015fae107Sandi * together with the username in a cookie - the same info is stored 27115fae107Sandi * in the session, too. Additonally a browserID is stored in the 27215fae107Sandi * session. 27315fae107Sandi * 27415fae107Sandi * If no username was given the cookie is checked: if the username, 27515fae107Sandi * crypted password and browserID match between session and cookie 27615fae107Sandi * no further testing is done and the user is accepted 27715fae107Sandi * 27815fae107Sandi * If a cookie was found but no session info was availabe the 279136ce040Sandi * blowfish encrypted password from the cookie is decrypted and 28015fae107Sandi * together with username rechecked by calling this function again. 281f3f0262cSandi * 282f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 283f3f0262cSandi * are set. 28415fae107Sandi * 28515fae107Sandi * @param string $user Username 28615fae107Sandi * @param string $pass Cleartext Password 28715fae107Sandi * @param bool $sticky Cookie should not expire 288f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth 28915fae107Sandi * @return bool true on successful auth 2904dc42f7fSGerrit Uitslag * @throws Exception 2914dc42f7fSGerrit Uitslag * 2924dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 293f3f0262cSandi */ 294d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) 295d868eb89SAndreas Gohr{ 296f3f0262cSandi global $USERINFO; 297f3f0262cSandi global $conf; 298f3f0262cSandi global $lang; 299e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 300cd52f92dSchris global $auth; 301585bf44eSChristopher Smith /* @var Input $INPUT */ 302585bf44eSChristopher Smith global $INPUT; 303ab5d26daSAndreas Gohr 3046547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 305beca106aSAdrian Lang 306bbbd6568SAndreas Gohr if (!empty($user)) { 307132bdbfeSandi //usual login 3085e9e1054SAndreas Gohr if (!empty($pass) && $auth->checkPass($user, $pass)) { 309132bdbfeSandi // make logininfo globally available 310585bf44eSChristopher Smith $INPUT->server->set('REMOTE_USER', $user); 31130d544a4SMichael Hamann $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 31204369c3eSMichael Hamann auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); 313132bdbfeSandi return true; 314f3f0262cSandi } else { 315f3f0262cSandi //invalid credentials - log off 316f8b1e4e7SAndreas Gohr if (!$silent) { 317f8b1e4e7SAndreas Gohr http_status(403, 'Login failed'); 318f8b1e4e7SAndreas Gohr msg($lang['badlogin'], -1); 319f8b1e4e7SAndreas Gohr } 320f3f0262cSandi auth_logoff(); 321132bdbfeSandi return false; 322f3f0262cSandi } 323f3f0262cSandi } else { 324132bdbfeSandi // read cookie information 32524870174SAndreas Gohr [$user, $sticky, $pass] = auth_getCookie(); 326132bdbfeSandi if ($user && $pass) { 327132bdbfeSandi // we got a cookie - see if we can trust it 328fa7c70ffSAdrian Lang 329fa7c70ffSAdrian Lang // get session info 3300058ae75SDamien Regad if (isset($_SESSION[DOKU_COOKIE])) { 331fa7c70ffSAdrian Lang $session = $_SESSION[DOKU_COOKIE]['auth']; 3327d34963bSAndreas Gohr if ( 3337d34963bSAndreas Gohr isset($session) && 3347172dbc0SAndreas Gohr $auth->useSessionCache($user) && 3354c989037SChris Smith ($session['time'] >= time() - $conf['auth_security_timeout']) && 336132bdbfeSandi ($session['user'] == $user) && 337234ce57eSAndreas Gohr ($session['pass'] == sha1($pass)) && //still crypted 338ab5d26daSAndreas Gohr ($session['buid'] == auth_browseruid()) 339ab5d26daSAndreas Gohr ) { 340132bdbfeSandi // he has session, cookie and browser right - let him in 341585bf44eSChristopher Smith $INPUT->server->set('REMOTE_USER', $user); 342132bdbfeSandi $USERINFO = $session['info']; //FIXME move all references to session 343132bdbfeSandi return true; 344132bdbfeSandi } 3450058ae75SDamien Regad } 346f112c2faSAndreas Gohr // no we don't trust it yet - recheck pass but silent 34730d544a4SMichael Hamann $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 34804369c3eSMichael Hamann $pass = auth_decrypt($pass, $secret); 349f112c2faSAndreas Gohr return auth_login($user, $pass, $sticky, true); 350132bdbfeSandi } 351132bdbfeSandi } 352f3f0262cSandi //just to be sure 353883179a4SAndreas Gohr auth_logoff(true); 354132bdbfeSandi return false; 355f3f0262cSandi} 356132bdbfeSandi 357132bdbfeSandi/** 358136ce040Sandi * Builds a pseudo UID from browser and IP data 359132bdbfeSandi * 360132bdbfeSandi * This is neither unique nor unfakable - still it adds some 361136ce040Sandi * security. Using the first part of the IP makes sure 36280b4f376SAndreas Gohr * proxy farms like AOLs are still okay. 36315fae107Sandi * 36415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 36515fae107Sandi * 366b13c0e1aSAdaKaleh * @return string a SHA256 sum of various browser headers 367132bdbfeSandi */ 368d868eb89SAndreas Gohrfunction auth_browseruid() 369d868eb89SAndreas Gohr{ 370585bf44eSChristopher Smith /* @var Input $INPUT */ 371585bf44eSChristopher Smith global $INPUT; 372585bf44eSChristopher Smith 3732f9daf16SAndreas Gohr $ip = clientIP(true); 374b13c0e1aSAdaKaleh // convert IP string to packed binary representation 375b13c0e1aSAdaKaleh $pip = inet_pton($ip); 376b7c67f83SAndreas Gohr 377b7c67f83SAndreas Gohr $uid = implode("\n", [ 378b7c67f83SAndreas Gohr $INPUT->server->str('HTTP_USER_AGENT'), 379b7c67f83SAndreas Gohr $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'), 380b7c67f83SAndreas Gohr substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6) 381b7c67f83SAndreas Gohr ]); 382b13c0e1aSAdaKaleh return hash('sha256', $uid); 383132bdbfeSandi} 384132bdbfeSandi 385132bdbfeSandi/** 386132bdbfeSandi * Creates a random key to encrypt the password in cookies 38715fae107Sandi * 38815fae107Sandi * This function tries to read the password for encrypting 38998407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt' 39015fae107Sandi * if no such file is found a random key is created and 39115fae107Sandi * and stored in this file. 39215fae107Sandi * 39332ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt 39430d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value 39515fae107Sandi * @return string 3964dc42f7fSGerrit Uitslag * @throws Exception 3974dc42f7fSGerrit Uitslag * 3984dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 399132bdbfeSandi */ 400d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false) 401d868eb89SAndreas Gohr{ 402a1fe3c9cSMichael Große if (defined('SIMPLE_TEST')) { 403fe745becSMichael Große return 'test'; 404a1fe3c9cSMichael Große } 405132bdbfeSandi global $conf; 40698407a7aSandi $file = $conf['metadir'] . '/_htcookiesalt'; 40730d544a4SMichael Hamann if ($secure || !file_exists($file)) { 40830d544a4SMichael Hamann $file = $conf['metadir'] . '/_htcookiesalt2'; 40930d544a4SMichael Hamann } 410132bdbfeSandi $salt = io_readFile($file); 411132bdbfeSandi if (empty($salt)) { 41230d544a4SMichael Hamann $salt = bin2hex(auth_randombytes(64)); 413132bdbfeSandi io_saveFile($file, $salt); 414132bdbfeSandi } 41532ed2b36SAndreas Gohr if ($addsession) { 41632ed2b36SAndreas Gohr $salt .= session_id(); 41732ed2b36SAndreas Gohr } 418132bdbfeSandi return $salt; 419f3f0262cSandi} 420f3f0262cSandi 421f3f0262cSandi/** 4227a33d2f8SNiklas Keller * Return cryptographically secure random bytes. 423483b6238SMichael Hamann * 4247a33d2f8SNiklas Keller * @param int $length number of bytes 4257a33d2f8SNiklas Keller * @return string cryptographically secure random bytes 4264dc42f7fSGerrit Uitslag * @throws Exception 4274dc42f7fSGerrit Uitslag * 4284dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com> 429483b6238SMichael Hamann */ 430d868eb89SAndreas Gohrfunction auth_randombytes($length) 431d868eb89SAndreas Gohr{ 4327a33d2f8SNiklas Keller return random_bytes($length); 433483b6238SMichael Hamann} 434483b6238SMichael Hamann 435483b6238SMichael Hamann/** 4367a33d2f8SNiklas Keller * Cryptographically secure random number generator. 437483b6238SMichael Hamann * 438483b6238SMichael Hamann * @param int $min 439483b6238SMichael Hamann * @param int $max 440483b6238SMichael Hamann * @return int 4414dc42f7fSGerrit Uitslag * @throws Exception 4424dc42f7fSGerrit Uitslag * 4434dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com> 444483b6238SMichael Hamann */ 445d868eb89SAndreas Gohrfunction auth_random($min, $max) 446d868eb89SAndreas Gohr{ 4477a33d2f8SNiklas Keller return random_int($min, $max); 448483b6238SMichael Hamann} 449483b6238SMichael Hamann 450483b6238SMichael Hamann/** 45104369c3eSMichael Hamann * Encrypt data using the given secret using AES 45204369c3eSMichael Hamann * 45304369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived 45404369c3eSMichael Hamann * using pbkdf2. 45504369c3eSMichael Hamann * 45604369c3eSMichael Hamann * @param string $data The data that shall be encrypted 45704369c3eSMichael Hamann * @param string $secret The secret/password that shall be used 45804369c3eSMichael Hamann * @return string The ciphertext 4594dc42f7fSGerrit Uitslag * @throws Exception 46004369c3eSMichael Hamann */ 461d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret) 462d868eb89SAndreas Gohr{ 46304369c3eSMichael Hamann $iv = auth_randombytes(16); 464927933f5SAndreas Gohr $cipher = new AES('cbc'); 46547e9ed0eSAndreas Gohr $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 466927933f5SAndreas Gohr $cipher->setIV($iv); 46704369c3eSMichael Hamann 4687b650cefSMichael Hamann /* 4697b650cefSMichael Hamann this uses the encrypted IV as IV as suggested in 4707b650cefSMichael Hamann http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C 4717b650cefSMichael Hamann for unique but necessarily random IVs. The resulting ciphertext is 4727b650cefSMichael Hamann compatible to ciphertext that was created using a "normal" IV. 4737b650cefSMichael Hamann */ 47404369c3eSMichael Hamann return $cipher->encrypt($iv . $data); 47504369c3eSMichael Hamann} 47604369c3eSMichael Hamann 47704369c3eSMichael Hamann/** 47804369c3eSMichael Hamann * Decrypt the given AES ciphertext 47904369c3eSMichael Hamann * 48004369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2 48104369c3eSMichael Hamann * 48204369c3eSMichael Hamann * @param string $ciphertext The encrypted data 48304369c3eSMichael Hamann * @param string $secret The secret/password that shall be used 4841cedacf2SAndreas Gohr * @return string|null The decrypted data 48504369c3eSMichael Hamann */ 486d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret) 487d868eb89SAndreas Gohr{ 4887b650cefSMichael Hamann $iv = substr($ciphertext, 0, 16); 489927933f5SAndreas Gohr $cipher = new AES('cbc'); 49047e9ed0eSAndreas Gohr $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 4917b650cefSMichael Hamann $cipher->setIV($iv); 49204369c3eSMichael Hamann 4931cedacf2SAndreas Gohr try { 4947b650cefSMichael Hamann return $cipher->decrypt(substr($ciphertext, 16)); 4951cedacf2SAndreas Gohr } catch (BadDecryptionException $e) { 4961cedacf2SAndreas Gohr ErrorHandler::logException($e); 4971cedacf2SAndreas Gohr return null; 4981cedacf2SAndreas Gohr } 49904369c3eSMichael Hamann} 50004369c3eSMichael Hamann 50104369c3eSMichael Hamann/** 502883179a4SAndreas Gohr * Log out the current user 503883179a4SAndreas Gohr * 504f3f0262cSandi * This clears all authentication data and thus log the user 505883179a4SAndreas Gohr * off. It also clears session data. 50615fae107Sandi * 50715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 50842ea7f44SGerrit Uitslag * 509883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared 510f3f0262cSandi */ 511d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false) 512d868eb89SAndreas Gohr{ 513f3f0262cSandi global $conf; 514f3f0262cSandi global $USERINFO; 515e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 5165298a619SAndreas Gohr global $auth; 517585bf44eSChristopher Smith /* @var Input $INPUT */ 518585bf44eSChristopher Smith global $INPUT; 51937065e65Sandi 520d4869846SAndreas Gohr // make sure the session is writable (it usually is) 521e9621d07SAndreas Gohr @session_start(); 522e9621d07SAndreas Gohr 523e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 524e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['user']); 525e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 526e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 527e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 528e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['info']); 529883179a4SAndreas Gohr if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 530e16eccb7SGuy Brand unset($_SESSION[DOKU_COOKIE]['bc']); 531585bf44eSChristopher Smith $INPUT->server->remove('REMOTE_USER'); 532132bdbfeSandi $USERINFO = null; //FIXME 533f5c6743cSAndreas Gohr 53473ab87deSGabriel Birke $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 535bf8392ebSAndreas Gohr setcookie(DOKU_COOKIE, '', [ 536bf8392ebSAndreas Gohr 'expires' => time() - 600000, 537bf8392ebSAndreas Gohr 'path' => $cookieDir, 538bf8392ebSAndreas Gohr 'secure' => ($conf['securecookie'] && is_ssl()), 539bf8392ebSAndreas Gohr 'httponly' => true, 540486f82fcSAndreas Gohr 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 541bf8392ebSAndreas Gohr ]); 5425298a619SAndreas Gohr 5436547cfc7SGerrit Uitslag if ($auth instanceof AuthPlugin) { 5446547cfc7SGerrit Uitslag $auth->logOff(); 5456547cfc7SGerrit Uitslag } 546f3f0262cSandi} 547f3f0262cSandi 548f3f0262cSandi/** 549f8cc712eSAndreas Gohr * Check if a user is a manager 550f8cc712eSAndreas Gohr * 551f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current 552f8cc712eSAndreas Gohr * user. 553f8cc712eSAndreas Gohr * 554f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too 555f8cc712eSAndreas Gohr * 556ab5d26daSAndreas Gohr * @param string $user Username 557ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in 558ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin 55910396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache 560ab5d26daSAndreas Gohr * @return bool 56196348f27SAndreas Gohr * @see auth_isadmin 56296348f27SAndreas Gohr * 56396348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 564f8cc712eSAndreas Gohr */ 565d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false) 566d868eb89SAndreas Gohr{ 567f8cc712eSAndreas Gohr global $conf; 568f8cc712eSAndreas Gohr global $USERINFO; 569e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 570d752aedeSAndreas Gohr global $auth; 571585bf44eSChristopher Smith /* @var Input $INPUT */ 572585bf44eSChristopher Smith global $INPUT; 573585bf44eSChristopher Smith 574f8cc712eSAndreas Gohr 5756547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 576c66972f2SAdrian Lang if (is_null($user)) { 577585bf44eSChristopher Smith if (!$INPUT->server->has('REMOTE_USER')) { 578c66972f2SAdrian Lang return false; 579c66972f2SAdrian Lang } else { 580585bf44eSChristopher Smith $user = $INPUT->server->str('REMOTE_USER'); 581c66972f2SAdrian Lang } 582c66972f2SAdrian Lang } 583d6dc956fSAndreas Gohr if (is_null($groups)) { 5841525c228SAnna Dabrowska // checking the logged in user, or another one? 5851525c228SAnna Dabrowska if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) { 5861525c228SAnna Dabrowska $groups = (array) $USERINFO['grps']; 58766b108d6SAnna Dabrowska } else { 5886cf7b139SAndreas Gohr $groups = $auth->getUserData($user); 5896cf7b139SAndreas Gohr $groups = $groups ? $groups['grps'] : []; 59066b108d6SAnna Dabrowska } 591e259aa79SAndreas Gohr } 592e259aa79SAndreas Gohr 59396348f27SAndreas Gohr // prefer cached result 59496348f27SAndreas Gohr static $cache = []; 59510396f77SAndreas Gohr $cachekey = serialize([$user, $adminonly, $groups]); 59696348f27SAndreas Gohr if (!isset($cache[$cachekey]) || $recache) { 597d6dc956fSAndreas Gohr // check superuser match 59896348f27SAndreas Gohr $ok = auth_isMember($conf['superuser'], $user, $groups); 59900ce12daSChris Smith 60096348f27SAndreas Gohr // check managers 60196348f27SAndreas Gohr if (!$ok && !$adminonly) { 60296348f27SAndreas Gohr $ok = auth_isMember($conf['manager'], $user, $groups); 60396348f27SAndreas Gohr } 60496348f27SAndreas Gohr 60596348f27SAndreas Gohr $cache[$cachekey] = $ok; 60696348f27SAndreas Gohr } 60796348f27SAndreas Gohr 60896348f27SAndreas Gohr return $cache[$cachekey]; 609f8cc712eSAndreas Gohr} 610f8cc712eSAndreas Gohr 611f8cc712eSAndreas Gohr/** 612f8cc712eSAndreas Gohr * Check if a user is admin 613f8cc712eSAndreas Gohr * 614f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true 615f8cc712eSAndreas Gohr * 616f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too 617f8cc712eSAndreas Gohr * 61896348f27SAndreas Gohr * @param string $user Username 61996348f27SAndreas Gohr * @param array $groups List of groups the user is in 62010396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache 62196348f27SAndreas Gohr * @return bool 622f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 623ab5d26daSAndreas Gohr * @see auth_ismanager() 62442ea7f44SGerrit Uitslag * 625f8cc712eSAndreas Gohr */ 626d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false) 627d868eb89SAndreas Gohr{ 62896348f27SAndreas Gohr return auth_ismanager($user, $groups, true, $recache); 629f8cc712eSAndreas Gohr} 630f8cc712eSAndreas Gohr 631d6dc956fSAndreas Gohr/** 632d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of 633d6dc956fSAndreas Gohr * users and groups to determine membership status 634d6dc956fSAndreas Gohr * 635d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded. 636d6dc956fSAndreas Gohr * 63742ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups 63842ea7f44SGerrit Uitslag * @param string $user user to match against 63942ea7f44SGerrit Uitslag * @param array $groups groups the user is member of 6405446f3ffSDominik Eckelmann * @return bool true for membership acknowledged 641d6dc956fSAndreas Gohr */ 642d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) 643d868eb89SAndreas Gohr{ 644e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 645d6dc956fSAndreas Gohr global $auth; 6466547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 647d6dc956fSAndreas Gohr 648d6dc956fSAndreas Gohr // clean user and groups 6494f56ecbfSAdrian Lang if (!$auth->isCaseSensitive()) { 65024870174SAndreas Gohr $user = PhpString::strtolower($user); 65124870174SAndreas Gohr $groups = array_map([PhpString::class, 'strtolower'], $groups); 652d6dc956fSAndreas Gohr } 653d6dc956fSAndreas Gohr $user = $auth->cleanUser($user); 65424870174SAndreas Gohr $groups = array_map([$auth, 'cleanGroup'], $groups); 655d6dc956fSAndreas Gohr 656d6dc956fSAndreas Gohr // extract the memberlist 657d6dc956fSAndreas Gohr $members = explode(',', $memberlist); 658d6dc956fSAndreas Gohr $members = array_map('trim', $members); 659d6dc956fSAndreas Gohr $members = array_unique($members); 660d6dc956fSAndreas Gohr $members = array_filter($members); 661d6dc956fSAndreas Gohr 662d6dc956fSAndreas Gohr // compare cleaned values 663d6dc956fSAndreas Gohr foreach ($members as $member) { 664e5204a12SJurgen Hart if ($member == '@ALL') return true; 66524870174SAndreas Gohr if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member); 666d6dc956fSAndreas Gohr if ($member[0] == '@') { 667d6dc956fSAndreas Gohr $member = $auth->cleanGroup(substr($member, 1)); 668d6dc956fSAndreas Gohr if (in_array($member, $groups)) return true; 669d6dc956fSAndreas Gohr } else { 670d6dc956fSAndreas Gohr $member = $auth->cleanUser($member); 671d6dc956fSAndreas Gohr if ($member == $user) return true; 672d6dc956fSAndreas Gohr } 673d6dc956fSAndreas Gohr } 674d6dc956fSAndreas Gohr 675d6dc956fSAndreas Gohr // still here? not a member! 676d6dc956fSAndreas Gohr return false; 677d6dc956fSAndreas Gohr} 678d6dc956fSAndreas Gohr 679f8cc712eSAndreas Gohr/** 68015fae107Sandi * Convinience function for auth_aclcheck() 68115fae107Sandi * 68215fae107Sandi * This checks the permissions for the current user 68315fae107Sandi * 68415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 68515fae107Sandi * 6861698b983Smichael * @param string $id page ID (needs to be resolved and cleaned) 68715fae107Sandi * @return int permission level 688f3f0262cSandi */ 689d868eb89SAndreas Gohrfunction auth_quickaclcheck($id) 690d868eb89SAndreas Gohr{ 691f3f0262cSandi global $conf; 692f3f0262cSandi global $USERINFO; 693585bf44eSChristopher Smith /* @var Input $INPUT */ 694585bf44eSChristopher Smith global $INPUT; 695f3f0262cSandi # if no ACL is used always return upload rights 696f3f0262cSandi if (!$conf['useacl']) return AUTH_UPLOAD; 69724870174SAndreas Gohr return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []); 698f3f0262cSandi} 699f3f0262cSandi 700f3f0262cSandi/** 701c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace 70215fae107Sandi * 70315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 70442ea7f44SGerrit Uitslag * 705c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK 7061698b983Smichael * @param string $id page ID (needs to be resolved and cleaned) 70715fae107Sandi * @param string $user Username 7083272d797SAndreas Gohr * @param array|null $groups Array of groups the user is in 70915fae107Sandi * @return int permission level 710f3f0262cSandi */ 711d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups) 712d868eb89SAndreas Gohr{ 71324870174SAndreas Gohr $data = [ 714bf8f8509SAndreas Gohr 'id' => $id ?? '', 715c17acc9fSAndreas Gohr 'user' => $user, 716c17acc9fSAndreas Gohr 'groups' => $groups 71724870174SAndreas Gohr ]; 718c17acc9fSAndreas Gohr 719cbb44eabSAndreas Gohr return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 720c17acc9fSAndreas Gohr} 721c17acc9fSAndreas Gohr 722c17acc9fSAndreas Gohr/** 723c17acc9fSAndreas Gohr * default ACL check method 724c17acc9fSAndreas Gohr * 725c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 726c17acc9fSAndreas Gohr * 727c17acc9fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 72842ea7f44SGerrit Uitslag * 729c17acc9fSAndreas Gohr * @param array $data event data 730c17acc9fSAndreas Gohr * @return int permission level 731c17acc9fSAndreas Gohr */ 732d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data) 733d868eb89SAndreas Gohr{ 734c17acc9fSAndreas Gohr $id =& $data['id']; 735c17acc9fSAndreas Gohr $user =& $data['user']; 736c17acc9fSAndreas Gohr $groups =& $data['groups']; 737c17acc9fSAndreas Gohr 738f3f0262cSandi global $conf; 739f3f0262cSandi global $AUTH_ACL; 740e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 741d752aedeSAndreas Gohr global $auth; 742f3f0262cSandi 74385d03f68SAndreas Gohr // if no ACL is used always return upload rights 744f3f0262cSandi if (!$conf['useacl']) return AUTH_UPLOAD; 7456547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return AUTH_NONE; 746bf8f8509SAndreas Gohr if (!is_array($AUTH_ACL)) return AUTH_NONE; 747f3f0262cSandi 748074cf26bSandi //make sure groups is an array 74924870174SAndreas Gohr if (!is_array($groups)) $groups = []; 750074cf26bSandi 75185d03f68SAndreas Gohr //if user is superuser or in superusergroup return 255 (acl_admin) 752ab5d26daSAndreas Gohr if (auth_isadmin($user, $groups)) { 753ab5d26daSAndreas Gohr return AUTH_ADMIN; 754ab5d26daSAndreas Gohr } 75585d03f68SAndreas Gohr 756eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive()) { 75724870174SAndreas Gohr $user = PhpString::strtolower($user); 75824870174SAndreas Gohr $groups = array_map([PhpString::class, 'strtolower'], $groups); 759eb3ce0d5SKazutaka Miyasaka } 76037ff2261SSascha Klopp $user = auth_nameencode($auth->cleanUser($user)); 76124870174SAndreas Gohr $groups = array_map([$auth, 'cleanGroup'], $groups); 76285d03f68SAndreas Gohr 7636c2bb100SAndreas Gohr //prepend groups with @ and nameencode 76437ff2261SSascha Klopp foreach ($groups as &$group) { 76537ff2261SSascha Klopp $group = '@' . auth_nameencode($group); 76610a76f6fSfrank } 76710a76f6fSfrank 768f3f0262cSandi $ns = getNS($id); 769f3f0262cSandi $perm = -1; 770f3f0262cSandi 771f3f0262cSandi //add ALL group 772f3f0262cSandi $groups[] = '@ALL'; 77337ff2261SSascha Klopp 774f3f0262cSandi //add User 77534aeb4afSAndreas Gohr if ($user) $groups[] = $user; 776f3f0262cSandi 777f3f0262cSandi //check exact match first 77821c3090aSChristopher Smith $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 779f3f0262cSandi if (count($matches)) { 780f3f0262cSandi foreach ($matches as $match) { 781f3f0262cSandi $match = preg_replace('/#.*$/', '', $match); //ignore comments 78221c3090aSChristopher Smith $acl = preg_split('/[ \t]+/', $match); 783eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 78424870174SAndreas Gohr $acl[1] = PhpString::strtolower($acl[1]); 785eb3ce0d5SKazutaka Miyasaka } 78648d7b7a6SDominik Eckelmann if (!in_array($acl[1], $groups)) { 78748d7b7a6SDominik Eckelmann continue; 78848d7b7a6SDominik Eckelmann } 7898ef6b7caSandi if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 790f3f0262cSandi if ($acl[2] > $perm) { 791f3f0262cSandi $perm = $acl[2]; 792f3f0262cSandi } 793f3f0262cSandi } 794f3f0262cSandi if ($perm > -1) { 795f3f0262cSandi //we had a match - return it 796def492a2SGuillaume Turri return (int) $perm; 797f3f0262cSandi } 798f3f0262cSandi } 799f3f0262cSandi 800f3f0262cSandi //still here? do the namespace checks 801f3f0262cSandi if ($ns) { 8023e304b55SMichael Hamann $path = $ns . ':*'; 803f3f0262cSandi } else { 8043e304b55SMichael Hamann $path = '*'; //root document 805f3f0262cSandi } 806f3f0262cSandi 807f3f0262cSandi do { 80821c3090aSChristopher Smith $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 809f3f0262cSandi if (count($matches)) { 810f3f0262cSandi foreach ($matches as $match) { 811f3f0262cSandi $match = preg_replace('/#.*$/', '', $match); //ignore comments 81221c3090aSChristopher Smith $acl = preg_split('/[ \t]+/', $match); 813eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 81424870174SAndreas Gohr $acl[1] = PhpString::strtolower($acl[1]); 815eb3ce0d5SKazutaka Miyasaka } 81648d7b7a6SDominik Eckelmann if (!in_array($acl[1], $groups)) { 81748d7b7a6SDominik Eckelmann continue; 81848d7b7a6SDominik Eckelmann } 8198ef6b7caSandi if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 820f3f0262cSandi if ($acl[2] > $perm) { 821f3f0262cSandi $perm = $acl[2]; 822f3f0262cSandi } 823f3f0262cSandi } 824f3f0262cSandi //we had a match - return it 82548d7b7a6SDominik Eckelmann if ($perm != -1) { 826def492a2SGuillaume Turri return (int) $perm; 827f3f0262cSandi } 82848d7b7a6SDominik Eckelmann } 829f3f0262cSandi //get next higher namespace 830f3f0262cSandi $ns = getNS($ns); 831f3f0262cSandi 8323e304b55SMichael Hamann if ($path != '*') { 8333e304b55SMichael Hamann $path = $ns . ':*'; 8343e304b55SMichael Hamann if ($path == ':*') $path = '*'; 835f3f0262cSandi } else { 836f3f0262cSandi //we did this already 837f3f0262cSandi //looks like there is something wrong with the ACL 838f3f0262cSandi //break here 839d5ce66f6SAndreas Gohr msg('No ACL setup yet! Denying access to everyone.'); 840d5ce66f6SAndreas Gohr return AUTH_NONE; 841f3f0262cSandi } 842f3f0262cSandi } while (1); //this should never loop endless 843ab5d26daSAndreas Gohr return AUTH_NONE; 844f3f0262cSandi} 845f3f0262cSandi 846f3f0262cSandi/** 8476c2bb100SAndreas Gohr * Encode ASCII special chars 8486c2bb100SAndreas Gohr * 8496c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames 8506c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars 8516c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual 8526c2bb100SAndreas Gohr * urlencoding!). 8536c2bb100SAndreas Gohr * 8546c2bb100SAndreas Gohr * Decoding can be done with rawurldecode 8556c2bb100SAndreas Gohr * 8566c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de> 8576c2bb100SAndreas Gohr * @see rawurldecode() 85842ea7f44SGerrit Uitslag * 85942ea7f44SGerrit Uitslag * @param string $name 86042ea7f44SGerrit Uitslag * @param bool $skip_group 86142ea7f44SGerrit Uitslag * @return string 8626c2bb100SAndreas Gohr */ 863d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false) 864d868eb89SAndreas Gohr{ 865a424cd8eSchris global $cache_authname; 866a424cd8eSchris $cache =& $cache_authname; 86731784267SAndreas Gohr $name = (string) $name; 868a424cd8eSchris 86980601d26SAndreas Gohr // never encode wildcard FS#1955 87080601d26SAndreas Gohr if ($name == '%USER%') return $name; 871b78bf706Sromain if ($name == '%GROUP%') return $name; 87280601d26SAndreas Gohr 873a424cd8eSchris if (!isset($cache[$name][$skip_group])) { 8742401f18dSSyntaxseed if ($skip_group && $name[0] == '@') { 87530f6faf0SChristopher Smith $cache[$name][$skip_group] = '@' . preg_replace_callback( 87630f6faf0SChristopher Smith '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 877dccd6b2bSAndreas Gohr 'auth_nameencode_callback', 878dccd6b2bSAndreas Gohr substr($name, 1) 879ab5d26daSAndreas Gohr ); 880e838fc2eSAndreas Gohr } else { 88130f6faf0SChristopher Smith $cache[$name][$skip_group] = preg_replace_callback( 88230f6faf0SChristopher Smith '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 883dccd6b2bSAndreas Gohr 'auth_nameencode_callback', 884dccd6b2bSAndreas Gohr $name 885ab5d26daSAndreas Gohr ); 886e838fc2eSAndreas Gohr } 8876c2bb100SAndreas Gohr } 8886c2bb100SAndreas Gohr 889a424cd8eSchris return $cache[$name][$skip_group]; 890a424cd8eSchris} 891a424cd8eSchris 89204d68ae4SGerrit Uitslag/** 89304d68ae4SGerrit Uitslag * callback encodes the matches 89404d68ae4SGerrit Uitslag * 89504d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms 89604d68ae4SGerrit Uitslag * @return string 89704d68ae4SGerrit Uitslag */ 898d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches) 899d868eb89SAndreas Gohr{ 90030f6faf0SChristopher Smith return '%' . dechex(ord(substr($matches[1], -1))); 90130f6faf0SChristopher Smith} 90230f6faf0SChristopher Smith 9036c2bb100SAndreas Gohr/** 904f3f0262cSandi * Create a pronouncable password 905f3f0262cSandi * 9068a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password 9078a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation 9088a285f7fSAndreas Gohr * 9094dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated 9104dc42f7fSGerrit Uitslag * @return string pronouncable password 9114dc42f7fSGerrit Uitslag * @throws Exception 9124dc42f7fSGerrit Uitslag * 91315fae107Sandi * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 9148a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE 91515fae107Sandi * 9164dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 917f3f0262cSandi */ 918d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '') 919d868eb89SAndreas Gohr{ 92024870174SAndreas Gohr $data = [ 921d628dcf3SAndreas Gohr 'password' => '', 922d628dcf3SAndreas Gohr 'foruser' => $foruser 92324870174SAndreas Gohr ]; 9248a285f7fSAndreas Gohr 925e1d9dcc8SAndreas Gohr $evt = new Event('AUTH_PASSWORD_GENERATE', $data); 9268a285f7fSAndreas Gohr if ($evt->advise_before(true)) { 927f3f0262cSandi $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 928f3f0262cSandi $v = 'aeiou'; //vowels 929f3f0262cSandi $a = $c . $v; //both 930987c8d26SAndreas Gohr $s = '!$%&?+*~#-_:.;,'; // specials 931f3f0262cSandi 932987c8d26SAndreas Gohr //use thre syllables... 933987c8d26SAndreas Gohr for ($i = 0; $i < 3; $i++) { 934483b6238SMichael Hamann $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 935483b6238SMichael Hamann $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 936483b6238SMichael Hamann $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 937f3f0262cSandi } 938987c8d26SAndreas Gohr //... and add a nice number and special 93943f71e05Ssdavis80 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99); 9408a285f7fSAndreas Gohr } 9418a285f7fSAndreas Gohr $evt->advise_after(); 942f3f0262cSandi 9438a285f7fSAndreas Gohr return $data['password']; 944f3f0262cSandi} 945f3f0262cSandi 946f3f0262cSandi/** 947f3f0262cSandi * Sends a password to the given user 948f3f0262cSandi * 94915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 95042ea7f44SGerrit Uitslag * 951ab5d26daSAndreas Gohr * @param string $user Login name of the user 952ab5d26daSAndreas Gohr * @param string $password The new password in clear text 95315fae107Sandi * @return bool true on success 954f3f0262cSandi */ 955d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password) 956d868eb89SAndreas Gohr{ 957f3f0262cSandi global $lang; 958e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 959cd52f92dSchris global $auth; 9606547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 961cd52f92dSchris 962d752aedeSAndreas Gohr $user = $auth->cleanUser($user); 9634dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 964f3f0262cSandi 96587ddda95Sandi if (!$userinfo['mail']) return false; 966f3f0262cSandi 967f3f0262cSandi $text = rawLocale('password'); 96824870174SAndreas Gohr $trep = [ 969d7169d19SAndreas Gohr 'FULLNAME' => $userinfo['name'], 970d7169d19SAndreas Gohr 'LOGIN' => $user, 971d7169d19SAndreas Gohr 'PASSWORD' => $password 97224870174SAndreas Gohr ]; 973f3f0262cSandi 974d7169d19SAndreas Gohr $mail = new Mailer(); 975102cdbd7SLarsGit223 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>'); 976d7169d19SAndreas Gohr $mail->subject($lang['regpwmail']); 977d7169d19SAndreas Gohr $mail->setBody($text, $trep); 978d7169d19SAndreas Gohr return $mail->send(); 979f3f0262cSandi} 980f3f0262cSandi 981f3f0262cSandi/** 98215fae107Sandi * Register a new user 983f3f0262cSandi * 98415fae107Sandi * This registers a new user - Data is read directly from $_POST 98515fae107Sandi * 98615fae107Sandi * @return bool true on success, false on any error 9874dc42f7fSGerrit Uitslag * @throws Exception 9884dc42f7fSGerrit Uitslag * 9894dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 990f3f0262cSandi */ 991d868eb89SAndreas Gohrfunction register() 992d868eb89SAndreas Gohr{ 993f3f0262cSandi global $lang; 994eb5d07e4Sjan global $conf; 9954dc42f7fSGerrit Uitslag /* @var AuthPlugin $auth */ 996cd52f92dSchris global $auth; 99764273335SAndreas Gohr global $INPUT; 998f3f0262cSandi 99964273335SAndreas Gohr if (!$INPUT->post->bool('save')) return false; 10003a48618aSAnika Henke if (!actionOK('register')) return false; 1001640145a5Sandi 100264273335SAndreas Gohr // gather input 100364273335SAndreas Gohr $login = trim($auth->cleanUser($INPUT->post->str('login'))); 100464273335SAndreas Gohr $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 100564273335SAndreas Gohr $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 100664273335SAndreas Gohr $pass = $INPUT->post->str('pass'); 100764273335SAndreas Gohr $passchk = $INPUT->post->str('passchk'); 1008d752aedeSAndreas Gohr 100964273335SAndreas Gohr if (empty($login) || empty($fullname) || empty($email)) { 1010f3f0262cSandi msg($lang['regmissing'], -1); 1011f3f0262cSandi return false; 1012f3f0262cSandi } 1013f3f0262cSandi 1014cab2716aSmatthias.grimm if ($conf['autopasswd']) { 10158a285f7fSAndreas Gohr $pass = auth_pwgen($login); // automatically generate password 101664273335SAndreas Gohr } elseif (empty($pass) || empty($passchk)) { 1017bf12ec81Sjan msg($lang['regmissing'], -1); // complain about missing passwords 1018cab2716aSmatthias.grimm return false; 101964273335SAndreas Gohr } elseif ($pass != $passchk) { 1020bf12ec81Sjan msg($lang['regbadpass'], -1); // complain about misspelled passwords 1021cab2716aSmatthias.grimm return false; 1022cab2716aSmatthias.grimm } 1023cab2716aSmatthias.grimm 1024f3f0262cSandi //check mail 102564273335SAndreas Gohr if (!mail_isvalid($email)) { 1026f3f0262cSandi msg($lang['regbadmail'], -1); 1027f3f0262cSandi return false; 1028f3f0262cSandi } 1029f3f0262cSandi 1030f3f0262cSandi //okay try to create the user 103124870174SAndreas Gohr if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) { 1032db9faf02SPatrick Brown msg($lang['regfail'], -1); 1033f3f0262cSandi return false; 1034f3f0262cSandi } 1035f3f0262cSandi 1036790b7720SAndreas Gohr // send notification about the new user 103775d66495SMichael Große $subscription = new RegistrationSubscriptionSender(); 103875d66495SMichael Große $subscription->sendRegister($login, $fullname, $email); 103902a498e7Schris 1040790b7720SAndreas Gohr // are we done? 1041cab2716aSmatthias.grimm if (!$conf['autopasswd']) { 1042cab2716aSmatthias.grimm msg($lang['regsuccess2'], 1); 1043cab2716aSmatthias.grimm return true; 1044cab2716aSmatthias.grimm } 1045cab2716aSmatthias.grimm 1046790b7720SAndreas Gohr // autogenerated password? then send password to user 104764273335SAndreas Gohr if (auth_sendPassword($login, $pass)) { 1048f3f0262cSandi msg($lang['regsuccess'], 1); 1049f3f0262cSandi return true; 1050f3f0262cSandi } else { 1051f3f0262cSandi msg($lang['regmailfail'], -1); 1052f3f0262cSandi return false; 1053f3f0262cSandi } 1054f3f0262cSandi} 1055f3f0262cSandi 105610a76f6fSfrank/** 10578b06d178Schris * Update user profile 10588b06d178Schris * 10594dc42f7fSGerrit Uitslag * @throws Exception 10604dc42f7fSGerrit Uitslag * 10618b06d178Schris * @author Christopher Smith <chris@jalakai.co.uk> 10628b06d178Schris */ 1063d868eb89SAndreas Gohrfunction updateprofile() 1064d868eb89SAndreas Gohr{ 10658b06d178Schris global $conf; 10668b06d178Schris global $lang; 1067e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1068cd52f92dSchris global $auth; 1069bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 1070bcc94b2cSAndreas Gohr global $INPUT; 10718b06d178Schris 1072bcc94b2cSAndreas Gohr if (!$INPUT->post->bool('save')) return false; 10731b2a85e8SAndreas Gohr if (!checkSecurityToken()) return false; 10748b06d178Schris 10753a48618aSAnika Henke if (!actionOK('profile')) { 10768b06d178Schris msg($lang['profna'], -1); 10778b06d178Schris return false; 10788b06d178Schris } 10798b06d178Schris 108024870174SAndreas Gohr $changes = []; 1081bcc94b2cSAndreas Gohr $changes['pass'] = $INPUT->post->str('newpass'); 1082bcc94b2cSAndreas Gohr $changes['name'] = $INPUT->post->str('fullname'); 1083bcc94b2cSAndreas Gohr $changes['mail'] = $INPUT->post->str('email'); 1084bcc94b2cSAndreas Gohr 1085bcc94b2cSAndreas Gohr // check misspelled passwords 1086bcc94b2cSAndreas Gohr if ($changes['pass'] != $INPUT->post->str('passchk')) { 1087bcc94b2cSAndreas Gohr msg($lang['regbadpass'], -1); 10888b06d178Schris return false; 10898b06d178Schris } 10908b06d178Schris 10918b06d178Schris // clean fullname and email 1092bcc94b2cSAndreas Gohr $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1093bcc94b2cSAndreas Gohr $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 10948b06d178Schris 1095bcc94b2cSAndreas Gohr // no empty name and email (except the backend doesn't support them) 10967d34963bSAndreas Gohr if ( 10977d34963bSAndreas Gohr (empty($changes['name']) && $auth->canDo('modName')) || 1098bcc94b2cSAndreas Gohr (empty($changes['mail']) && $auth->canDo('modMail')) 1099ab5d26daSAndreas Gohr ) { 11008b06d178Schris msg($lang['profnoempty'], -1); 11018b06d178Schris return false; 11028b06d178Schris } 1103bcc94b2cSAndreas Gohr if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 11048b06d178Schris msg($lang['regbadmail'], -1); 11058b06d178Schris return false; 11068b06d178Schris } 11078b06d178Schris 1108bcc94b2cSAndreas Gohr $changes = array_filter($changes); 11094c21b7eeSAndreas Gohr 1110bcc94b2cSAndreas Gohr // check for unavailable capabilities 1111bcc94b2cSAndreas Gohr if (!$auth->canDo('modName')) unset($changes['name']); 1112bcc94b2cSAndreas Gohr if (!$auth->canDo('modMail')) unset($changes['mail']); 1113bcc94b2cSAndreas Gohr if (!$auth->canDo('modPass')) unset($changes['pass']); 1114bcc94b2cSAndreas Gohr 1115bcc94b2cSAndreas Gohr // anything to do? 111624870174SAndreas Gohr if ($changes === []) { 11178b06d178Schris msg($lang['profnochange'], -1); 11188b06d178Schris return false; 11198b06d178Schris } 11208b06d178Schris 11218b06d178Schris if ($conf['profileconfirm']) { 1122585bf44eSChristopher Smith if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 112371422fc8SChristopher Smith msg($lang['badpassconfirm'], -1); 11248b06d178Schris return false; 11258b06d178Schris } 11268b06d178Schris } 11278b06d178Schris 112824870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) { 1129db9faf02SPatrick Brown msg($lang['proffail'], -1); 1130db9faf02SPatrick Brown return false; 1131db9faf02SPatrick Brown } 1132db9faf02SPatrick Brown 113367efd1edSPieter Hollants if (array_key_exists('pass', $changes) && $changes['pass']) { 1134c276e9e8SMarcel Pennewiss // update cookie and session with the changed data 1135a19c9aa0SGerrit Uitslag [/* user */, $sticky, /* pass */] = auth_getCookie(); 113604369c3eSMichael Hamann $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1137585bf44eSChristopher Smith auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1138c276e9e8SMarcel Pennewiss } else { 1139c276e9e8SMarcel Pennewiss // make sure the session is writable 1140c276e9e8SMarcel Pennewiss @session_start(); 1141c276e9e8SMarcel Pennewiss // invalidate session cache 1142c276e9e8SMarcel Pennewiss $_SESSION[DOKU_COOKIE]['auth']['time'] = 0; 1143c276e9e8SMarcel Pennewiss session_write_close(); 114432ed2b36SAndreas Gohr } 1145c276e9e8SMarcel Pennewiss 114625b2a98cSMichael Klier return true; 1147a0b5b007SChris Smith} 1148ab5d26daSAndreas Gohr 114904d68ae4SGerrit Uitslag/** 115004d68ae4SGerrit Uitslag * Delete the current logged-in user 115104d68ae4SGerrit Uitslag * 115204d68ae4SGerrit Uitslag * @return bool true on success, false on any error 115304d68ae4SGerrit Uitslag */ 1154d868eb89SAndreas Gohrfunction auth_deleteprofile() 1155d868eb89SAndreas Gohr{ 11562a7abf2dSChristopher Smith global $conf; 11572a7abf2dSChristopher Smith global $lang; 11584dc42f7fSGerrit Uitslag /* @var AuthPlugin $auth */ 11592a7abf2dSChristopher Smith global $auth; 11602a7abf2dSChristopher Smith /* @var Input $INPUT */ 11612a7abf2dSChristopher Smith global $INPUT; 11622a7abf2dSChristopher Smith 11632a7abf2dSChristopher Smith if (!$INPUT->post->bool('delete')) return false; 11642a7abf2dSChristopher Smith if (!checkSecurityToken()) return false; 11652a7abf2dSChristopher Smith 11662a7abf2dSChristopher Smith // action prevented or auth module disallows 11672a7abf2dSChristopher Smith if (!actionOK('profile_delete') || !$auth->canDo('delUser')) { 11682a7abf2dSChristopher Smith msg($lang['profnodelete'], -1); 11692a7abf2dSChristopher Smith return false; 11702a7abf2dSChristopher Smith } 11712a7abf2dSChristopher Smith 11722a7abf2dSChristopher Smith if (!$INPUT->post->bool('confirm_delete')) { 11732a7abf2dSChristopher Smith msg($lang['profconfdeletemissing'], -1); 11742a7abf2dSChristopher Smith return false; 11752a7abf2dSChristopher Smith } 11762a7abf2dSChristopher Smith 11772a7abf2dSChristopher Smith if ($conf['profileconfirm']) { 1178585bf44eSChristopher Smith if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 11792a7abf2dSChristopher Smith msg($lang['badpassconfirm'], -1); 11802a7abf2dSChristopher Smith return false; 11812a7abf2dSChristopher Smith } 11822a7abf2dSChristopher Smith } 11832a7abf2dSChristopher Smith 118424870174SAndreas Gohr $deleted = []; 1185585bf44eSChristopher Smith $deleted[] = $INPUT->server->str('REMOTE_USER'); 118624870174SAndreas Gohr if ($auth->triggerUserMod('delete', [$deleted])) { 11872a7abf2dSChristopher Smith // force and immediate logout including removing the sticky cookie 11882a7abf2dSChristopher Smith auth_logoff(); 11892a7abf2dSChristopher Smith return true; 11902a7abf2dSChristopher Smith } 11912a7abf2dSChristopher Smith 11922a7abf2dSChristopher Smith return false; 11932a7abf2dSChristopher Smith} 11942a7abf2dSChristopher Smith 11958b06d178Schris/** 11968b06d178Schris * Send a new password 11978b06d178Schris * 11981d5856cfSAndreas Gohr * This function handles both phases of the password reset: 11991d5856cfSAndreas Gohr * 12001d5856cfSAndreas Gohr * - handling the first request of password reset 12011d5856cfSAndreas Gohr * - validating the password reset auth token 12021d5856cfSAndreas Gohr * 12034dc42f7fSGerrit Uitslag * @return bool true on success, false on any error 12044dc42f7fSGerrit Uitslag * @throws Exception 12054dc42f7fSGerrit Uitslag * 12064dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 12078b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info> 12088b06d178Schris * @author Chris Smith <chris@jalakai.co.uk> 12098b06d178Schris */ 1210d868eb89SAndreas Gohrfunction act_resendpwd() 1211d868eb89SAndreas Gohr{ 12128b06d178Schris global $lang; 12138b06d178Schris global $conf; 1214e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1215cd52f92dSchris global $auth; 1216bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 1217bcc94b2cSAndreas Gohr global $INPUT; 12188b06d178Schris 12193a48618aSAnika Henke if (!actionOK('resendpwd')) { 12208b06d178Schris msg($lang['resendna'], -1); 12218b06d178Schris return false; 12228b06d178Schris } 12238b06d178Schris 1224bcc94b2cSAndreas Gohr $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 12258b06d178Schris 12261d5856cfSAndreas Gohr if ($token) { 1227cc204bbdSAndreas Gohr // we're in token phase - get user info from token 12281d5856cfSAndreas Gohr 12292401f18dSSyntaxseed $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 123079e79377SAndreas Gohr if (!file_exists($tfile)) { 12311d5856cfSAndreas Gohr msg($lang['resendpwdbadauth'], -1); 1232bcc94b2cSAndreas Gohr $INPUT->remove('pwauth'); 12331d5856cfSAndreas Gohr return false; 12341d5856cfSAndreas Gohr } 12358a9735e3SAndreas Gohr // token is only valid for 3 days 12368a9735e3SAndreas Gohr if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 12378a9735e3SAndreas Gohr msg($lang['resendpwdbadauth'], -1); 1238bcc94b2cSAndreas Gohr $INPUT->remove('pwauth'); 12391d5856cfSAndreas Gohr @unlink($tfile); 12408a9735e3SAndreas Gohr return false; 12418a9735e3SAndreas Gohr } 12428a9735e3SAndreas Gohr 12438b06d178Schris $user = io_readfile($tfile); 12444dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 12458b06d178Schris if (!$userinfo['mail']) { 12468b06d178Schris msg($lang['resendpwdnouser'], -1); 12478b06d178Schris return false; 12488b06d178Schris } 12498b06d178Schris 1250cc204bbdSAndreas Gohr if (!$conf['autopasswd']) { // we let the user choose a password 1251bcc94b2cSAndreas Gohr $pass = $INPUT->str('pass'); 1252bcc94b2cSAndreas Gohr 1253cc204bbdSAndreas Gohr // password given correctly? 1254bcc94b2cSAndreas Gohr if (!$pass) return false; 1255bcc94b2cSAndreas Gohr if ($pass != $INPUT->str('passchk')) { 1256451e1b4dSAndreas Gohr msg($lang['regbadpass'], -1); 1257cc204bbdSAndreas Gohr return false; 1258cc204bbdSAndreas Gohr } 1259cc204bbdSAndreas Gohr 1260bcc94b2cSAndreas Gohr // change it 126124870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1262db9faf02SPatrick Brown msg($lang['proffail'], -1); 1263cc204bbdSAndreas Gohr return false; 1264cc204bbdSAndreas Gohr } 1265cc204bbdSAndreas Gohr } else { // autogenerate the password and send by mail 12668a285f7fSAndreas Gohr $pass = auth_pwgen($user); 126724870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1268db9faf02SPatrick Brown msg($lang['proffail'], -1); 12698b06d178Schris return false; 12708b06d178Schris } 12718b06d178Schris 12728b06d178Schris if (auth_sendPassword($user, $pass)) { 12738b06d178Schris msg($lang['resendpwdsuccess'], 1); 12748b06d178Schris } else { 12758b06d178Schris msg($lang['regmailfail'], -1); 12768b06d178Schris } 1277cc204bbdSAndreas Gohr } 1278cc204bbdSAndreas Gohr 1279cc204bbdSAndreas Gohr @unlink($tfile); 12808b06d178Schris return true; 12811d5856cfSAndreas Gohr } else { 12821d5856cfSAndreas Gohr // we're in request phase 12831d5856cfSAndreas Gohr 1284bcc94b2cSAndreas Gohr if (!$INPUT->post->bool('save')) return false; 12851d5856cfSAndreas Gohr 1286bcc94b2cSAndreas Gohr if (!$INPUT->post->str('login')) { 12871d5856cfSAndreas Gohr msg($lang['resendpwdmissing'], -1); 12881d5856cfSAndreas Gohr return false; 12891d5856cfSAndreas Gohr } else { 1290bcc94b2cSAndreas Gohr $user = trim($auth->cleanUser($INPUT->post->str('login'))); 12911d5856cfSAndreas Gohr } 12921d5856cfSAndreas Gohr 12934dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 12941d5856cfSAndreas Gohr if (!$userinfo['mail']) { 12951d5856cfSAndreas Gohr msg($lang['resendpwdnouser'], -1); 12961d5856cfSAndreas Gohr return false; 12971d5856cfSAndreas Gohr } 12981d5856cfSAndreas Gohr 12991d5856cfSAndreas Gohr // generate auth token 1300483b6238SMichael Hamann $token = md5(auth_randombytes(16)); // random secret 13012401f18dSSyntaxseed $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 130224870174SAndreas Gohr $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&'); 13031d5856cfSAndreas Gohr 13041d5856cfSAndreas Gohr io_saveFile($tfile, $user); 13051d5856cfSAndreas Gohr 13061d5856cfSAndreas Gohr $text = rawLocale('pwconfirm'); 130724870174SAndreas Gohr $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url]; 13081d5856cfSAndreas Gohr 1309d7169d19SAndreas Gohr $mail = new Mailer(); 1310d7169d19SAndreas Gohr $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>'); 1311d7169d19SAndreas Gohr $mail->subject($lang['regpwmail']); 1312d7169d19SAndreas Gohr $mail->setBody($text, $trep); 1313d7169d19SAndreas Gohr if ($mail->send()) { 13141d5856cfSAndreas Gohr msg($lang['resendpwdconfirm'], 1); 13151d5856cfSAndreas Gohr } else { 13161d5856cfSAndreas Gohr msg($lang['regmailfail'], -1); 13171d5856cfSAndreas Gohr } 13181d5856cfSAndreas Gohr return true; 13191d5856cfSAndreas Gohr } 1320ab5d26daSAndreas Gohr // never reached 13218b06d178Schris} 13228b06d178Schris 13238b06d178Schris/** 1324b0855b11Sandi * Encrypts a password using the given method and salt 1325b0855b11Sandi * 1326b0855b11Sandi * If the selected method needs a salt and none was given, a random one 1327b0855b11Sandi * is chosen. 1328b0855b11Sandi * 13290ffe9fdaSTobias Bengfort * You can pass null as the password to create an unusable hash. 13300ffe9fdaSTobias Bengfort * 1331b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org> 133242ea7f44SGerrit Uitslag * 1333ab5d26daSAndreas Gohr * @param string $clear The clear text password 1334ab5d26daSAndreas Gohr * @param string $method The hashing method 1335ab5d26daSAndreas Gohr * @param string $salt A salt, null for random 1336b0855b11Sandi * @return string The crypted password 1337b0855b11Sandi */ 1338d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) 1339d868eb89SAndreas Gohr{ 1340b0855b11Sandi global $conf; 1341527ad715STobias Bengfort 1342527ad715STobias Bengfort if ($clear === null) { 1343b21b7935STobias Bengfort return DOKU_UNUSABLE_PASSWORD; 1344527ad715STobias Bengfort } 1345527ad715STobias Bengfort 1346b0855b11Sandi if (empty($method)) $method = $conf['passcrypt']; 134710a76f6fSfrank 13483a0a2d05SAndreas Gohr $pass = new PassHash(); 13493a0a2d05SAndreas Gohr $call = 'hash_' . $method; 1350b0855b11Sandi 13513a0a2d05SAndreas Gohr if (!method_exists($pass, $call)) { 1352b0855b11Sandi msg("Unsupported crypt method $method", -1); 13533a0a2d05SAndreas Gohr return false; 1354b0855b11Sandi } 13553a0a2d05SAndreas Gohr 13563a0a2d05SAndreas Gohr return $pass->$call($clear, $salt); 1357b0855b11Sandi} 1358b0855b11Sandi 1359b0855b11Sandi/** 1360b0855b11Sandi * Verifies a cleartext password against a crypted hash 1361b0855b11Sandi * 1362ab5d26daSAndreas Gohr * @param string $clear The clear text password 1363ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with 1364ab5d26daSAndreas Gohr * @return bool true if both match 13654dc42f7fSGerrit Uitslag * @throws Exception 13664dc42f7fSGerrit Uitslag * 13674dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 1368b0855b11Sandi */ 1369d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt) 1370d868eb89SAndreas Gohr{ 1371b21b7935STobias Bengfort if ($crypt === DOKU_UNUSABLE_PASSWORD) { 1372527ad715STobias Bengfort return false; 1373527ad715STobias Bengfort } 1374527ad715STobias Bengfort 13753a0a2d05SAndreas Gohr $pass = new PassHash(); 13763a0a2d05SAndreas Gohr return $pass->verify_hash($clear, $crypt); 1377b0855b11Sandi} 1378340756e4Sandi 1379a0b5b007SChris Smith/** 1380a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session 1381a0b5b007SChris Smith * 1382a0b5b007SChris Smith * @param string $user username 1383a0b5b007SChris Smith * @param string $pass encrypted password 1384a0b5b007SChris Smith * @param bool $sticky whether or not the cookie will last beyond the session 1385ab5d26daSAndreas Gohr * @return bool 1386a0b5b007SChris Smith */ 1387d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky) 1388d868eb89SAndreas Gohr{ 1389a0b5b007SChris Smith global $conf; 1390e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1391a0b5b007SChris Smith global $auth; 139279d00841SOliver Geisen global $USERINFO; 1393a0b5b007SChris Smith 13946547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 1395a0b5b007SChris Smith $USERINFO = $auth->getUserData($user); 1396a0b5b007SChris Smith 1397a0b5b007SChris Smith // set cookie 1398645c0a36SAndreas Gohr $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass); 139973ab87deSGabriel Birke $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1400c66972f2SAdrian Lang $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1401bf8392ebSAndreas Gohr setcookie(DOKU_COOKIE, $cookie, [ 1402bf8392ebSAndreas Gohr 'expires' => $time, 1403bf8392ebSAndreas Gohr 'path' => $cookieDir, 1404bf8392ebSAndreas Gohr 'secure' => ($conf['securecookie'] && is_ssl()), 1405bf8392ebSAndreas Gohr 'httponly' => true, 1406486f82fcSAndreas Gohr 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 1407bf8392ebSAndreas Gohr ]); 140855a71a16SGerrit Uitslag 1409a0b5b007SChris Smith // set session 1410a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1411234ce57eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1412a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1413a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1414a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1415ab5d26daSAndreas Gohr 1416ab5d26daSAndreas Gohr return true; 1417a0b5b007SChris Smith} 1418a0b5b007SChris Smith 1419645c0a36SAndreas Gohr/** 1420645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie 1421645c0a36SAndreas Gohr * 1422645c0a36SAndreas Gohr * @returns array 1423645c0a36SAndreas Gohr */ 1424d868eb89SAndreas Gohrfunction auth_getCookie() 1425d868eb89SAndreas Gohr{ 1426c66972f2SAdrian Lang if (!isset($_COOKIE[DOKU_COOKIE])) { 142724870174SAndreas Gohr return [null, null, null]; 1428c66972f2SAdrian Lang } 142924870174SAndreas Gohr [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, ''); 1430645c0a36SAndreas Gohr $sticky = (bool) $sticky; 1431645c0a36SAndreas Gohr $pass = base64_decode($pass); 1432645c0a36SAndreas Gohr $user = base64_decode($user); 143324870174SAndreas Gohr return [$user, $sticky, $pass]; 1434645c0a36SAndreas Gohr} 1435645c0a36SAndreas Gohr 1436e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 : 1437