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 25*527ad715STobias Bengfortconst UNUSABLE_PASSWORD = '!unusable'; 26*527ad715STobias Bengfort 2716905344SAndreas Gohr/** 2816905344SAndreas Gohr * Initialize the auth system. 2916905344SAndreas Gohr * 3016905344SAndreas Gohr * This function is automatically called at the end of init.php 3116905344SAndreas Gohr * 3216905344SAndreas Gohr * This used to be the main() of the auth.php 3316905344SAndreas Gohr * 3416905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader 3516905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions 36ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK 37ab5d26daSAndreas Gohr * @return bool 3816905344SAndreas Gohr */ 39d868eb89SAndreas Gohrfunction auth_setup() 40d868eb89SAndreas Gohr{ 41742c66f8Schris global $conf; 42e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 4303c4aec3Schris global $auth; 44bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 45bcc94b2cSAndreas Gohr global $INPUT; 469a9714acSDominik Eckelmann global $AUTH_ACL; 479a9714acSDominik Eckelmann global $lang; 483a7140a1SAndreas Gohr /* @var PluginController $plugin_controller */ 499c29eea5SJan Schumann global $plugin_controller; 5024870174SAndreas Gohr $AUTH_ACL = []; 5103c4aec3Schris 52b9cda918SAndreas Gohr // unset REMOTE_USER if empty 53b9cda918SAndreas Gohr if ($INPUT->server->str('REMOTE_USER') === '') { 54b9cda918SAndreas Gohr $INPUT->server->remove('REMOTE_USER'); 55b9cda918SAndreas Gohr } 56b9cda918SAndreas Gohr 5716905344SAndreas Gohr if (!$conf['useacl']) return false; 5816905344SAndreas Gohr 599c29eea5SJan Schumann // try to load auth backend from plugins 609c29eea5SJan Schumann foreach ($plugin_controller->getList('auth') as $plugin) { 619c29eea5SJan Schumann if ($conf['authtype'] === $plugin) { 62f4476bd9SJan Schumann $auth = $plugin_controller->load('auth', $plugin); 639c29eea5SJan Schumann break; 649c29eea5SJan Schumann } 659c29eea5SJan Schumann } 668b06d178Schris 676547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) { 6871c734a9SGerrit Uitslag msg($lang['authtempfail'], -1); 693094e817SAndreas Gohr return false; 703094e817SAndreas Gohr } 718b06d178Schris 726416b708SMichael Hamann if ($auth->success == false) { 730f4f4adfSAndreas Gohr // degrade to unauthenticated user 74ecad51ddSAndreas Gohr $auth = null; 750f4f4adfSAndreas Gohr auth_logoff(); 76cd52f92dSchris msg($lang['authtempfail'], -1); 776416b708SMichael Hamann return false; 78d2dde4ebSMatthias Grimm } 7916905344SAndreas Gohr 8016905344SAndreas Gohr // do the login either by cookie or provided credentials XXX 81bcc94b2cSAndreas Gohr $INPUT->set('http_credentials', false); 82bcc94b2cSAndreas Gohr if (!$conf['rememberme']) $INPUT->set('r', false); 83bbbd6568SAndreas Gohr 8462bf3ac0SDamien Regad // Populate Basic Auth user/password from Authorization header 8562bf3ac0SDamien Regad // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION 8662bf3ac0SDamien Regad $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION'); 8762bf3ac0SDamien Regad if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) { 8862bf3ac0SDamien Regad $userpass = explode(':', base64_decode($matches[1])); 8924870174SAndreas Gohr [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass; 90528ddc7cSAndreas Gohr } 91528ddc7cSAndreas Gohr 921e8c9c90SAndreas Gohr // if no credentials were given try to use HTTP auth (for SSO) 9303062864SAndreas Gohr if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) { 9403062864SAndreas Gohr $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER')); 9503062864SAndreas Gohr $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW')); 96bcc94b2cSAndreas Gohr $INPUT->set('http_credentials', true); 971e8c9c90SAndreas Gohr } 981e8c9c90SAndreas Gohr 99395c2f0fSAndreas Gohr // apply cleaning (auth specific user names, remove control chars) 10093a7873eSAndreas Gohr if (true === $auth->success) { 101395c2f0fSAndreas Gohr $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u')))); 102395c2f0fSAndreas Gohr $INPUT->set('p', stripctl($INPUT->str('p'))); 103f4476bd9SJan Schumann } 104191bb90aSAndreas Gohr 105455aa67eSAndreas Gohr if (!auth_tokenlogin()) { 10681e99965SPhy $ok = null; 107455aa67eSAndreas Gohr 1088407f251Ssplitbrain if ($auth->canDo('external')) { 10981e99965SPhy $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r')); 11081e99965SPhy } 11181e99965SPhy 11281e99965SPhy if ($ok === null) { 11381e99965SPhy // external trust mechanism not in place, or returns no result, 11481e99965SPhy // then attempt auth_login 11524870174SAndreas Gohr $evdata = [ 116bcc94b2cSAndreas Gohr 'user' => $INPUT->str('u'), 117bcc94b2cSAndreas Gohr 'password' => $INPUT->str('p'), 118bcc94b2cSAndreas Gohr 'sticky' => $INPUT->bool('r'), 119bcc94b2cSAndreas Gohr 'silent' => $INPUT->bool('http_credentials') 12024870174SAndreas Gohr ]; 121cbb44eabSAndreas Gohr Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper'); 122f5cb575dSAndreas Gohr } 123455aa67eSAndreas Gohr } 124f5cb575dSAndreas Gohr 12516905344SAndreas Gohr //load ACL into a global array XXX 12675c93b77SAndreas Gohr $AUTH_ACL = auth_loadACL(); 127ab5d26daSAndreas Gohr 128ab5d26daSAndreas Gohr return true; 12975c93b77SAndreas Gohr} 13075c93b77SAndreas Gohr 13175c93b77SAndreas Gohr/** 13275c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards 13375c93b77SAndreas Gohr * 13475c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 13542ea7f44SGerrit Uitslag * 136ab5d26daSAndreas Gohr * @return array 13775c93b77SAndreas Gohr */ 138d868eb89SAndreas Gohrfunction auth_loadACL() 139d868eb89SAndreas Gohr{ 14075c93b77SAndreas Gohr global $config_cascade; 141b78bf706Sromain global $USERINFO; 142585bf44eSChristopher Smith /* @var Input $INPUT */ 143585bf44eSChristopher Smith global $INPUT; 14475c93b77SAndreas Gohr 14524870174SAndreas Gohr if (!is_readable($config_cascade['acl']['default'])) return []; 14675c93b77SAndreas Gohr 14775c93b77SAndreas Gohr $acl = file($config_cascade['acl']['default']); 14875c93b77SAndreas Gohr 14924870174SAndreas Gohr $out = []; 1509ce556d2SAndreas Gohr foreach ($acl as $line) { 1519ce556d2SAndreas Gohr $line = trim($line); 1522401f18dSSyntaxseed if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments 15324870174SAndreas Gohr [$id, $rest] = preg_split('/[ \t]+/', $line, 2); 15432e82180SAndreas Gohr 155443e135dSChristopher Smith // substitute user wildcard first (its 1:1) 156ad3d68d7SChristopher Smith if (strstr($line, '%USER%')) { 157ad3d68d7SChristopher Smith // if user is not logged in, this ACL line is meaningless - skip it 158585bf44eSChristopher Smith if (!$INPUT->server->has('REMOTE_USER')) continue; 159ad3d68d7SChristopher Smith 160585bf44eSChristopher Smith $id = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id); 161585bf44eSChristopher Smith $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest); 162ad3d68d7SChristopher Smith } 163ad3d68d7SChristopher Smith 164ad3d68d7SChristopher Smith // substitute group wildcard (its 1:m) 1659ce556d2SAndreas Gohr if (strstr($line, '%GROUP%')) { 166ad3d68d7SChristopher Smith // if user is not logged in, grps is empty, no output will be added (i.e. skipped) 16706f34f54SPhy if (isset($USERINFO['grps'])) { 1689ce556d2SAndreas Gohr foreach ((array) $USERINFO['grps'] as $grp) { 169b78bf706Sromain $nid = str_replace('%GROUP%', cleanID($grp), $id); 17032e82180SAndreas Gohr $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest); 17132e82180SAndreas Gohr $out[] = "$nid\t$nrest"; 172b78bf706Sromain } 17306f34f54SPhy } 17432e82180SAndreas Gohr } else { 17532e82180SAndreas Gohr $out[] = "$id\t$rest"; 176a8fe108bSGuy Brand } 17711799630Sandi } 1789ce556d2SAndreas Gohr 17932e82180SAndreas Gohr return $out; 180f3f0262cSandi} 181f3f0262cSandi 182ab5d26daSAndreas Gohr/** 183455aa67eSAndreas Gohr * Try a token login 184455aa67eSAndreas Gohr * 185455aa67eSAndreas Gohr * @return bool true if token login succeeded 186455aa67eSAndreas Gohr */ 187cf927d07Ssplitbrainfunction auth_tokenlogin() 188cf927d07Ssplitbrain{ 189455aa67eSAndreas Gohr global $USERINFO; 190455aa67eSAndreas Gohr global $INPUT; 191455aa67eSAndreas Gohr /** @var DokuWiki_Auth_Plugin $auth */ 192455aa67eSAndreas Gohr global $auth; 193455aa67eSAndreas Gohr if (!$auth) return false; 194455aa67eSAndreas Gohr 1957ffd5bd2SAndreas Gohr // get the headers, either from Apache or from $_SERVER 1966fdb83b6SAndreas Gohr if (function_exists('getallheaders')) { 1976fdb83b6SAndreas Gohr $headers = array_change_key_case(getallheaders()); 198455aa67eSAndreas Gohr } else { 1997ffd5bd2SAndreas Gohr $headers = []; 2007ffd5bd2SAndreas Gohr foreach ($_SERVER as $key => $value) { 2017ffd5bd2SAndreas Gohr if (substr($key, 0, 5) === 'HTTP_') { 2027ffd5bd2SAndreas Gohr $headers[strtolower(substr($key, 5))] = $value; 203455aa67eSAndreas Gohr } 2047ffd5bd2SAndreas Gohr } 2057ffd5bd2SAndreas Gohr } 2067ffd5bd2SAndreas Gohr 2077ffd5bd2SAndreas Gohr // check authorization header 2087ffd5bd2SAndreas Gohr if (isset($headers['authorization'])) { 2097ffd5bd2SAndreas Gohr [$type, $token] = sexplode(' ', $headers['authorization'], 2); 2107ffd5bd2SAndreas Gohr if ($type !== 'Bearer') $token = ''; // not the token we want 2117ffd5bd2SAndreas Gohr } 2127ffd5bd2SAndreas Gohr 2137ffd5bd2SAndreas Gohr // check x-dokuwiki-token header 2147ffd5bd2SAndreas Gohr if (isset($headers['x-dokuwiki-token'])) { 2157ffd5bd2SAndreas Gohr $token = $headers['x-dokuwiki-token']; 2167ffd5bd2SAndreas Gohr } 2177ffd5bd2SAndreas Gohr 2187ffd5bd2SAndreas Gohr if (empty($token)) return false; 219455aa67eSAndreas Gohr 220455aa67eSAndreas Gohr // check token 221455aa67eSAndreas Gohr try { 222cf927d07Ssplitbrain $authtoken = JWT::validate($token); 223455aa67eSAndreas Gohr } catch (Exception $e) { 224455aa67eSAndreas Gohr msg(hsc($e->getMessage()), -1); 225455aa67eSAndreas Gohr return false; 226455aa67eSAndreas Gohr } 227455aa67eSAndreas Gohr 228455aa67eSAndreas Gohr // fetch user info from backend 229455aa67eSAndreas Gohr $user = $authtoken->getUser(); 230455aa67eSAndreas Gohr $USERINFO = $auth->getUserData($user); 231455aa67eSAndreas Gohr if (!$USERINFO) return false; 232455aa67eSAndreas Gohr 233455aa67eSAndreas Gohr // the code is correct, set up user 234455aa67eSAndreas Gohr $INPUT->server->set('REMOTE_USER', $user); 235455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 236455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope'; 237455aa67eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 238455aa67eSAndreas Gohr 239455aa67eSAndreas Gohr return true; 240455aa67eSAndreas Gohr} 241455aa67eSAndreas Gohr 242455aa67eSAndreas Gohr/** 243ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK 244ab5d26daSAndreas Gohr * 24542ea7f44SGerrit Uitslag * @param array $evdata 246ab5d26daSAndreas Gohr * @return bool 2474dc42f7fSGerrit Uitslag * @throws Exception 248ab5d26daSAndreas Gohr */ 249d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata) 250d868eb89SAndreas Gohr{ 251ab5d26daSAndreas Gohr return auth_login( 252ab5d26daSAndreas Gohr $evdata['user'], 253b5ee21aaSAdrian Lang $evdata['password'], 254b5ee21aaSAdrian Lang $evdata['sticky'], 255ab5d26daSAndreas Gohr $evdata['silent'] 256ab5d26daSAndreas Gohr ); 257b5ee21aaSAdrian Lang} 258b5ee21aaSAdrian Lang 259f3f0262cSandi/** 260f3f0262cSandi * This tries to login the user based on the sent auth credentials 261f3f0262cSandi * 262f3f0262cSandi * The authentication works like this: if a username was given 26315fae107Sandi * a new login is assumed and user/password are checked. If they 26415fae107Sandi * are correct the password is encrypted with blowfish and stored 26515fae107Sandi * together with the username in a cookie - the same info is stored 26615fae107Sandi * in the session, too. Additonally a browserID is stored in the 26715fae107Sandi * session. 26815fae107Sandi * 26915fae107Sandi * If no username was given the cookie is checked: if the username, 27015fae107Sandi * crypted password and browserID match between session and cookie 27115fae107Sandi * no further testing is done and the user is accepted 27215fae107Sandi * 27315fae107Sandi * If a cookie was found but no session info was availabe the 274136ce040Sandi * blowfish encrypted password from the cookie is decrypted and 27515fae107Sandi * together with username rechecked by calling this function again. 276f3f0262cSandi * 277f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 278f3f0262cSandi * are set. 27915fae107Sandi * 28015fae107Sandi * @param string $user Username 28115fae107Sandi * @param string $pass Cleartext Password 28215fae107Sandi * @param bool $sticky Cookie should not expire 283f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth 28415fae107Sandi * @return bool true on successful auth 2854dc42f7fSGerrit Uitslag * @throws Exception 2864dc42f7fSGerrit Uitslag * 2874dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 288f3f0262cSandi */ 289d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) 290d868eb89SAndreas Gohr{ 291f3f0262cSandi global $USERINFO; 292f3f0262cSandi global $conf; 293f3f0262cSandi global $lang; 294e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 295cd52f92dSchris global $auth; 296585bf44eSChristopher Smith /* @var Input $INPUT */ 297585bf44eSChristopher Smith global $INPUT; 298ab5d26daSAndreas Gohr 2996547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 300beca106aSAdrian Lang 301bbbd6568SAndreas Gohr if (!empty($user)) { 302132bdbfeSandi //usual login 3035e9e1054SAndreas Gohr if (!empty($pass) && $auth->checkPass($user, $pass)) { 304132bdbfeSandi // make logininfo globally available 305585bf44eSChristopher Smith $INPUT->server->set('REMOTE_USER', $user); 30630d544a4SMichael Hamann $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 30704369c3eSMichael Hamann auth_setCookie($user, auth_encrypt($pass, $secret), $sticky); 308132bdbfeSandi return true; 309f3f0262cSandi } else { 310f3f0262cSandi //invalid credentials - log off 311f8b1e4e7SAndreas Gohr if (!$silent) { 312f8b1e4e7SAndreas Gohr http_status(403, 'Login failed'); 313f8b1e4e7SAndreas Gohr msg($lang['badlogin'], -1); 314f8b1e4e7SAndreas Gohr } 315f3f0262cSandi auth_logoff(); 316132bdbfeSandi return false; 317f3f0262cSandi } 318f3f0262cSandi } else { 319132bdbfeSandi // read cookie information 32024870174SAndreas Gohr [$user, $sticky, $pass] = auth_getCookie(); 321132bdbfeSandi if ($user && $pass) { 322132bdbfeSandi // we got a cookie - see if we can trust it 323fa7c70ffSAdrian Lang 324fa7c70ffSAdrian Lang // get session info 3250058ae75SDamien Regad if (isset($_SESSION[DOKU_COOKIE])) { 326fa7c70ffSAdrian Lang $session = $_SESSION[DOKU_COOKIE]['auth']; 3277d34963bSAndreas Gohr if ( 3287d34963bSAndreas Gohr isset($session) && 3297172dbc0SAndreas Gohr $auth->useSessionCache($user) && 3304c989037SChris Smith ($session['time'] >= time() - $conf['auth_security_timeout']) && 331132bdbfeSandi ($session['user'] == $user) && 332234ce57eSAndreas Gohr ($session['pass'] == sha1($pass)) && //still crypted 333ab5d26daSAndreas Gohr ($session['buid'] == auth_browseruid()) 334ab5d26daSAndreas Gohr ) { 335132bdbfeSandi // he has session, cookie and browser right - let him in 336585bf44eSChristopher Smith $INPUT->server->set('REMOTE_USER', $user); 337132bdbfeSandi $USERINFO = $session['info']; //FIXME move all references to session 338132bdbfeSandi return true; 339132bdbfeSandi } 3400058ae75SDamien Regad } 341f112c2faSAndreas Gohr // no we don't trust it yet - recheck pass but silent 34230d544a4SMichael Hamann $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session 34304369c3eSMichael Hamann $pass = auth_decrypt($pass, $secret); 344f112c2faSAndreas Gohr return auth_login($user, $pass, $sticky, true); 345132bdbfeSandi } 346132bdbfeSandi } 347f3f0262cSandi //just to be sure 348883179a4SAndreas Gohr auth_logoff(true); 349132bdbfeSandi return false; 350f3f0262cSandi} 351132bdbfeSandi 352132bdbfeSandi/** 353136ce040Sandi * Builds a pseudo UID from browser and IP data 354132bdbfeSandi * 355132bdbfeSandi * This is neither unique nor unfakable - still it adds some 356136ce040Sandi * security. Using the first part of the IP makes sure 35780b4f376SAndreas Gohr * proxy farms like AOLs are still okay. 35815fae107Sandi * 35915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 36015fae107Sandi * 361b13c0e1aSAdaKaleh * @return string a SHA256 sum of various browser headers 362132bdbfeSandi */ 363d868eb89SAndreas Gohrfunction auth_browseruid() 364d868eb89SAndreas Gohr{ 365585bf44eSChristopher Smith /* @var Input $INPUT */ 366585bf44eSChristopher Smith global $INPUT; 367585bf44eSChristopher Smith 3682f9daf16SAndreas Gohr $ip = clientIP(true); 369b13c0e1aSAdaKaleh // convert IP string to packed binary representation 370b13c0e1aSAdaKaleh $pip = inet_pton($ip); 371b7c67f83SAndreas Gohr 372b7c67f83SAndreas Gohr $uid = implode("\n", [ 373b7c67f83SAndreas Gohr $INPUT->server->str('HTTP_USER_AGENT'), 374b7c67f83SAndreas Gohr $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'), 375b7c67f83SAndreas Gohr substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6) 376b7c67f83SAndreas Gohr ]); 377b13c0e1aSAdaKaleh return hash('sha256', $uid); 378132bdbfeSandi} 379132bdbfeSandi 380132bdbfeSandi/** 381132bdbfeSandi * Creates a random key to encrypt the password in cookies 38215fae107Sandi * 38315fae107Sandi * This function tries to read the password for encrypting 38498407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt' 38515fae107Sandi * if no such file is found a random key is created and 38615fae107Sandi * and stored in this file. 38715fae107Sandi * 38832ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt 38930d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value 39015fae107Sandi * @return string 3914dc42f7fSGerrit Uitslag * @throws Exception 3924dc42f7fSGerrit Uitslag * 3934dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 394132bdbfeSandi */ 395d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false) 396d868eb89SAndreas Gohr{ 397a1fe3c9cSMichael Große if (defined('SIMPLE_TEST')) { 398fe745becSMichael Große return 'test'; 399a1fe3c9cSMichael Große } 400132bdbfeSandi global $conf; 40198407a7aSandi $file = $conf['metadir'] . '/_htcookiesalt'; 40230d544a4SMichael Hamann if ($secure || !file_exists($file)) { 40330d544a4SMichael Hamann $file = $conf['metadir'] . '/_htcookiesalt2'; 40430d544a4SMichael Hamann } 405132bdbfeSandi $salt = io_readFile($file); 406132bdbfeSandi if (empty($salt)) { 40730d544a4SMichael Hamann $salt = bin2hex(auth_randombytes(64)); 408132bdbfeSandi io_saveFile($file, $salt); 409132bdbfeSandi } 41032ed2b36SAndreas Gohr if ($addsession) { 41132ed2b36SAndreas Gohr $salt .= session_id(); 41232ed2b36SAndreas Gohr } 413132bdbfeSandi return $salt; 414f3f0262cSandi} 415f3f0262cSandi 416f3f0262cSandi/** 4177a33d2f8SNiklas Keller * Return cryptographically secure random bytes. 418483b6238SMichael Hamann * 4197a33d2f8SNiklas Keller * @param int $length number of bytes 4207a33d2f8SNiklas Keller * @return string cryptographically secure random bytes 4214dc42f7fSGerrit Uitslag * @throws Exception 4224dc42f7fSGerrit Uitslag * 4234dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com> 424483b6238SMichael Hamann */ 425d868eb89SAndreas Gohrfunction auth_randombytes($length) 426d868eb89SAndreas Gohr{ 4277a33d2f8SNiklas Keller return random_bytes($length); 428483b6238SMichael Hamann} 429483b6238SMichael Hamann 430483b6238SMichael Hamann/** 4317a33d2f8SNiklas Keller * Cryptographically secure random number generator. 432483b6238SMichael Hamann * 433483b6238SMichael Hamann * @param int $min 434483b6238SMichael Hamann * @param int $max 435483b6238SMichael Hamann * @return int 4364dc42f7fSGerrit Uitslag * @throws Exception 4374dc42f7fSGerrit Uitslag * 4384dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com> 439483b6238SMichael Hamann */ 440d868eb89SAndreas Gohrfunction auth_random($min, $max) 441d868eb89SAndreas Gohr{ 4427a33d2f8SNiklas Keller return random_int($min, $max); 443483b6238SMichael Hamann} 444483b6238SMichael Hamann 445483b6238SMichael Hamann/** 44604369c3eSMichael Hamann * Encrypt data using the given secret using AES 44704369c3eSMichael Hamann * 44804369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived 44904369c3eSMichael Hamann * using pbkdf2. 45004369c3eSMichael Hamann * 45104369c3eSMichael Hamann * @param string $data The data that shall be encrypted 45204369c3eSMichael Hamann * @param string $secret The secret/password that shall be used 45304369c3eSMichael Hamann * @return string The ciphertext 4544dc42f7fSGerrit Uitslag * @throws Exception 45504369c3eSMichael Hamann */ 456d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret) 457d868eb89SAndreas Gohr{ 45804369c3eSMichael Hamann $iv = auth_randombytes(16); 459927933f5SAndreas Gohr $cipher = new AES('cbc'); 46047e9ed0eSAndreas Gohr $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 461927933f5SAndreas Gohr $cipher->setIV($iv); 46204369c3eSMichael Hamann 4637b650cefSMichael Hamann /* 4647b650cefSMichael Hamann this uses the encrypted IV as IV as suggested in 4657b650cefSMichael Hamann http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C 4667b650cefSMichael Hamann for unique but necessarily random IVs. The resulting ciphertext is 4677b650cefSMichael Hamann compatible to ciphertext that was created using a "normal" IV. 4687b650cefSMichael Hamann */ 46904369c3eSMichael Hamann return $cipher->encrypt($iv . $data); 47004369c3eSMichael Hamann} 47104369c3eSMichael Hamann 47204369c3eSMichael Hamann/** 47304369c3eSMichael Hamann * Decrypt the given AES ciphertext 47404369c3eSMichael Hamann * 47504369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2 47604369c3eSMichael Hamann * 47704369c3eSMichael Hamann * @param string $ciphertext The encrypted data 47804369c3eSMichael Hamann * @param string $secret The secret/password that shall be used 4791cedacf2SAndreas Gohr * @return string|null The decrypted data 48004369c3eSMichael Hamann */ 481d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret) 482d868eb89SAndreas Gohr{ 4837b650cefSMichael Hamann $iv = substr($ciphertext, 0, 16); 484927933f5SAndreas Gohr $cipher = new AES('cbc'); 48547e9ed0eSAndreas Gohr $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib'); 4867b650cefSMichael Hamann $cipher->setIV($iv); 48704369c3eSMichael Hamann 4881cedacf2SAndreas Gohr try { 4897b650cefSMichael Hamann return $cipher->decrypt(substr($ciphertext, 16)); 4901cedacf2SAndreas Gohr } catch (BadDecryptionException $e) { 4911cedacf2SAndreas Gohr ErrorHandler::logException($e); 4921cedacf2SAndreas Gohr return null; 4931cedacf2SAndreas Gohr } 49404369c3eSMichael Hamann} 49504369c3eSMichael Hamann 49604369c3eSMichael Hamann/** 497883179a4SAndreas Gohr * Log out the current user 498883179a4SAndreas Gohr * 499f3f0262cSandi * This clears all authentication data and thus log the user 500883179a4SAndreas Gohr * off. It also clears session data. 50115fae107Sandi * 50215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 50342ea7f44SGerrit Uitslag * 504883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared 505f3f0262cSandi */ 506d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false) 507d868eb89SAndreas Gohr{ 508f3f0262cSandi global $conf; 509f3f0262cSandi global $USERINFO; 510e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 5115298a619SAndreas Gohr global $auth; 512585bf44eSChristopher Smith /* @var Input $INPUT */ 513585bf44eSChristopher Smith global $INPUT; 51437065e65Sandi 515d4869846SAndreas Gohr // make sure the session is writable (it usually is) 516e9621d07SAndreas Gohr @session_start(); 517e9621d07SAndreas Gohr 518e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 519e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['user']); 520e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 521e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 522e71ce681SAndreas Gohr if (isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 523e71ce681SAndreas Gohr unset($_SESSION[DOKU_COOKIE]['auth']['info']); 524883179a4SAndreas Gohr if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc'])) 525e16eccb7SGuy Brand unset($_SESSION[DOKU_COOKIE]['bc']); 526585bf44eSChristopher Smith $INPUT->server->remove('REMOTE_USER'); 527132bdbfeSandi $USERINFO = null; //FIXME 528f5c6743cSAndreas Gohr 52973ab87deSGabriel Birke $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 530bf8392ebSAndreas Gohr setcookie(DOKU_COOKIE, '', [ 531bf8392ebSAndreas Gohr 'expires' => time() - 600000, 532bf8392ebSAndreas Gohr 'path' => $cookieDir, 533bf8392ebSAndreas Gohr 'secure' => ($conf['securecookie'] && is_ssl()), 534bf8392ebSAndreas Gohr 'httponly' => true, 535486f82fcSAndreas Gohr 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 536bf8392ebSAndreas Gohr ]); 5375298a619SAndreas Gohr 5386547cfc7SGerrit Uitslag if ($auth instanceof AuthPlugin) { 5396547cfc7SGerrit Uitslag $auth->logOff(); 5406547cfc7SGerrit Uitslag } 541f3f0262cSandi} 542f3f0262cSandi 543f3f0262cSandi/** 544f8cc712eSAndreas Gohr * Check if a user is a manager 545f8cc712eSAndreas Gohr * 546f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current 547f8cc712eSAndreas Gohr * user. 548f8cc712eSAndreas Gohr * 549f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too 550f8cc712eSAndreas Gohr * 551ab5d26daSAndreas Gohr * @param string $user Username 552ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in 553ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin 55410396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache 555ab5d26daSAndreas Gohr * @return bool 55696348f27SAndreas Gohr * @see auth_isadmin 55796348f27SAndreas Gohr * 55896348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 559f8cc712eSAndreas Gohr */ 560d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false) 561d868eb89SAndreas Gohr{ 562f8cc712eSAndreas Gohr global $conf; 563f8cc712eSAndreas Gohr global $USERINFO; 564e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 565d752aedeSAndreas Gohr global $auth; 566585bf44eSChristopher Smith /* @var Input $INPUT */ 567585bf44eSChristopher Smith global $INPUT; 568585bf44eSChristopher Smith 569f8cc712eSAndreas Gohr 5706547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 571c66972f2SAdrian Lang if (is_null($user)) { 572585bf44eSChristopher Smith if (!$INPUT->server->has('REMOTE_USER')) { 573c66972f2SAdrian Lang return false; 574c66972f2SAdrian Lang } else { 575585bf44eSChristopher Smith $user = $INPUT->server->str('REMOTE_USER'); 576c66972f2SAdrian Lang } 577c66972f2SAdrian Lang } 578d6dc956fSAndreas Gohr if (is_null($groups)) { 5791525c228SAnna Dabrowska // checking the logged in user, or another one? 5801525c228SAnna Dabrowska if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) { 5811525c228SAnna Dabrowska $groups = (array) $USERINFO['grps']; 58266b108d6SAnna Dabrowska } else { 5836cf7b139SAndreas Gohr $groups = $auth->getUserData($user); 5846cf7b139SAndreas Gohr $groups = $groups ? $groups['grps'] : []; 58566b108d6SAnna Dabrowska } 586e259aa79SAndreas Gohr } 587e259aa79SAndreas Gohr 58896348f27SAndreas Gohr // prefer cached result 58996348f27SAndreas Gohr static $cache = []; 59010396f77SAndreas Gohr $cachekey = serialize([$user, $adminonly, $groups]); 59196348f27SAndreas Gohr if (!isset($cache[$cachekey]) || $recache) { 592d6dc956fSAndreas Gohr // check superuser match 59396348f27SAndreas Gohr $ok = auth_isMember($conf['superuser'], $user, $groups); 59400ce12daSChris Smith 59596348f27SAndreas Gohr // check managers 59696348f27SAndreas Gohr if (!$ok && !$adminonly) { 59796348f27SAndreas Gohr $ok = auth_isMember($conf['manager'], $user, $groups); 59896348f27SAndreas Gohr } 59996348f27SAndreas Gohr 60096348f27SAndreas Gohr $cache[$cachekey] = $ok; 60196348f27SAndreas Gohr } 60296348f27SAndreas Gohr 60396348f27SAndreas Gohr return $cache[$cachekey]; 604f8cc712eSAndreas Gohr} 605f8cc712eSAndreas Gohr 606f8cc712eSAndreas Gohr/** 607f8cc712eSAndreas Gohr * Check if a user is admin 608f8cc712eSAndreas Gohr * 609f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true 610f8cc712eSAndreas Gohr * 611f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too 612f8cc712eSAndreas Gohr * 61396348f27SAndreas Gohr * @param string $user Username 61496348f27SAndreas Gohr * @param array $groups List of groups the user is in 61510396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache 61696348f27SAndreas Gohr * @return bool 617f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 618ab5d26daSAndreas Gohr * @see auth_ismanager() 61942ea7f44SGerrit Uitslag * 620f8cc712eSAndreas Gohr */ 621d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false) 622d868eb89SAndreas Gohr{ 62396348f27SAndreas Gohr return auth_ismanager($user, $groups, true, $recache); 624f8cc712eSAndreas Gohr} 625f8cc712eSAndreas Gohr 626d6dc956fSAndreas Gohr/** 627d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of 628d6dc956fSAndreas Gohr * users and groups to determine membership status 629d6dc956fSAndreas Gohr * 630d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded. 631d6dc956fSAndreas Gohr * 63242ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups 63342ea7f44SGerrit Uitslag * @param string $user user to match against 63442ea7f44SGerrit Uitslag * @param array $groups groups the user is member of 6355446f3ffSDominik Eckelmann * @return bool true for membership acknowledged 636d6dc956fSAndreas Gohr */ 637d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) 638d868eb89SAndreas Gohr{ 639e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 640d6dc956fSAndreas Gohr global $auth; 6416547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 642d6dc956fSAndreas Gohr 643d6dc956fSAndreas Gohr // clean user and groups 6444f56ecbfSAdrian Lang if (!$auth->isCaseSensitive()) { 64524870174SAndreas Gohr $user = PhpString::strtolower($user); 64624870174SAndreas Gohr $groups = array_map([PhpString::class, 'strtolower'], $groups); 647d6dc956fSAndreas Gohr } 648d6dc956fSAndreas Gohr $user = $auth->cleanUser($user); 64924870174SAndreas Gohr $groups = array_map([$auth, 'cleanGroup'], $groups); 650d6dc956fSAndreas Gohr 651d6dc956fSAndreas Gohr // extract the memberlist 652d6dc956fSAndreas Gohr $members = explode(',', $memberlist); 653d6dc956fSAndreas Gohr $members = array_map('trim', $members); 654d6dc956fSAndreas Gohr $members = array_unique($members); 655d6dc956fSAndreas Gohr $members = array_filter($members); 656d6dc956fSAndreas Gohr 657d6dc956fSAndreas Gohr // compare cleaned values 658d6dc956fSAndreas Gohr foreach ($members as $member) { 659e5204a12SJurgen Hart if ($member == '@ALL') return true; 66024870174SAndreas Gohr if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member); 661d6dc956fSAndreas Gohr if ($member[0] == '@') { 662d6dc956fSAndreas Gohr $member = $auth->cleanGroup(substr($member, 1)); 663d6dc956fSAndreas Gohr if (in_array($member, $groups)) return true; 664d6dc956fSAndreas Gohr } else { 665d6dc956fSAndreas Gohr $member = $auth->cleanUser($member); 666d6dc956fSAndreas Gohr if ($member == $user) return true; 667d6dc956fSAndreas Gohr } 668d6dc956fSAndreas Gohr } 669d6dc956fSAndreas Gohr 670d6dc956fSAndreas Gohr // still here? not a member! 671d6dc956fSAndreas Gohr return false; 672d6dc956fSAndreas Gohr} 673d6dc956fSAndreas Gohr 674f8cc712eSAndreas Gohr/** 67515fae107Sandi * Convinience function for auth_aclcheck() 67615fae107Sandi * 67715fae107Sandi * This checks the permissions for the current user 67815fae107Sandi * 67915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 68015fae107Sandi * 6811698b983Smichael * @param string $id page ID (needs to be resolved and cleaned) 68215fae107Sandi * @return int permission level 683f3f0262cSandi */ 684d868eb89SAndreas Gohrfunction auth_quickaclcheck($id) 685d868eb89SAndreas Gohr{ 686f3f0262cSandi global $conf; 687f3f0262cSandi global $USERINFO; 688585bf44eSChristopher Smith /* @var Input $INPUT */ 689585bf44eSChristopher Smith global $INPUT; 690f3f0262cSandi # if no ACL is used always return upload rights 691f3f0262cSandi if (!$conf['useacl']) return AUTH_UPLOAD; 69224870174SAndreas Gohr return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []); 693f3f0262cSandi} 694f3f0262cSandi 695f3f0262cSandi/** 696c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace 69715fae107Sandi * 69815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 69942ea7f44SGerrit Uitslag * 700c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK 7011698b983Smichael * @param string $id page ID (needs to be resolved and cleaned) 70215fae107Sandi * @param string $user Username 7033272d797SAndreas Gohr * @param array|null $groups Array of groups the user is in 70415fae107Sandi * @return int permission level 705f3f0262cSandi */ 706d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups) 707d868eb89SAndreas Gohr{ 70824870174SAndreas Gohr $data = [ 709bf8f8509SAndreas Gohr 'id' => $id ?? '', 710c17acc9fSAndreas Gohr 'user' => $user, 711c17acc9fSAndreas Gohr 'groups' => $groups 71224870174SAndreas Gohr ]; 713c17acc9fSAndreas Gohr 714cbb44eabSAndreas Gohr return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb'); 715c17acc9fSAndreas Gohr} 716c17acc9fSAndreas Gohr 717c17acc9fSAndreas Gohr/** 718c17acc9fSAndreas Gohr * default ACL check method 719c17acc9fSAndreas Gohr * 720c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead 721c17acc9fSAndreas Gohr * 722c17acc9fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 72342ea7f44SGerrit Uitslag * 724c17acc9fSAndreas Gohr * @param array $data event data 725c17acc9fSAndreas Gohr * @return int permission level 726c17acc9fSAndreas Gohr */ 727d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data) 728d868eb89SAndreas Gohr{ 729c17acc9fSAndreas Gohr $id =& $data['id']; 730c17acc9fSAndreas Gohr $user =& $data['user']; 731c17acc9fSAndreas Gohr $groups =& $data['groups']; 732c17acc9fSAndreas Gohr 733f3f0262cSandi global $conf; 734f3f0262cSandi global $AUTH_ACL; 735e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 736d752aedeSAndreas Gohr global $auth; 737f3f0262cSandi 73885d03f68SAndreas Gohr // if no ACL is used always return upload rights 739f3f0262cSandi if (!$conf['useacl']) return AUTH_UPLOAD; 7406547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return AUTH_NONE; 741bf8f8509SAndreas Gohr if (!is_array($AUTH_ACL)) return AUTH_NONE; 742f3f0262cSandi 743074cf26bSandi //make sure groups is an array 74424870174SAndreas Gohr if (!is_array($groups)) $groups = []; 745074cf26bSandi 74685d03f68SAndreas Gohr //if user is superuser or in superusergroup return 255 (acl_admin) 747ab5d26daSAndreas Gohr if (auth_isadmin($user, $groups)) { 748ab5d26daSAndreas Gohr return AUTH_ADMIN; 749ab5d26daSAndreas Gohr } 75085d03f68SAndreas Gohr 751eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive()) { 75224870174SAndreas Gohr $user = PhpString::strtolower($user); 75324870174SAndreas Gohr $groups = array_map([PhpString::class, 'strtolower'], $groups); 754eb3ce0d5SKazutaka Miyasaka } 75537ff2261SSascha Klopp $user = auth_nameencode($auth->cleanUser($user)); 75624870174SAndreas Gohr $groups = array_map([$auth, 'cleanGroup'], $groups); 75785d03f68SAndreas Gohr 7586c2bb100SAndreas Gohr //prepend groups with @ and nameencode 75937ff2261SSascha Klopp foreach ($groups as &$group) { 76037ff2261SSascha Klopp $group = '@' . auth_nameencode($group); 76110a76f6fSfrank } 76210a76f6fSfrank 763f3f0262cSandi $ns = getNS($id); 764f3f0262cSandi $perm = -1; 765f3f0262cSandi 766f3f0262cSandi //add ALL group 767f3f0262cSandi $groups[] = '@ALL'; 76837ff2261SSascha Klopp 769f3f0262cSandi //add User 77034aeb4afSAndreas Gohr if ($user) $groups[] = $user; 771f3f0262cSandi 772f3f0262cSandi //check exact match first 77321c3090aSChristopher Smith $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 774f3f0262cSandi if (count($matches)) { 775f3f0262cSandi foreach ($matches as $match) { 776f3f0262cSandi $match = preg_replace('/#.*$/', '', $match); //ignore comments 77721c3090aSChristopher Smith $acl = preg_split('/[ \t]+/', $match); 778eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 77924870174SAndreas Gohr $acl[1] = PhpString::strtolower($acl[1]); 780eb3ce0d5SKazutaka Miyasaka } 78148d7b7a6SDominik Eckelmann if (!in_array($acl[1], $groups)) { 78248d7b7a6SDominik Eckelmann continue; 78348d7b7a6SDominik Eckelmann } 7848ef6b7caSandi if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 785f3f0262cSandi if ($acl[2] > $perm) { 786f3f0262cSandi $perm = $acl[2]; 787f3f0262cSandi } 788f3f0262cSandi } 789f3f0262cSandi if ($perm > -1) { 790f3f0262cSandi //we had a match - return it 791def492a2SGuillaume Turri return (int) $perm; 792f3f0262cSandi } 793f3f0262cSandi } 794f3f0262cSandi 795f3f0262cSandi //still here? do the namespace checks 796f3f0262cSandi if ($ns) { 7973e304b55SMichael Hamann $path = $ns . ':*'; 798f3f0262cSandi } else { 7993e304b55SMichael Hamann $path = '*'; //root document 800f3f0262cSandi } 801f3f0262cSandi 802f3f0262cSandi do { 80321c3090aSChristopher Smith $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL); 804f3f0262cSandi if (count($matches)) { 805f3f0262cSandi foreach ($matches as $match) { 806f3f0262cSandi $match = preg_replace('/#.*$/', '', $match); //ignore comments 80721c3090aSChristopher Smith $acl = preg_split('/[ \t]+/', $match); 808eb3ce0d5SKazutaka Miyasaka if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') { 80924870174SAndreas Gohr $acl[1] = PhpString::strtolower($acl[1]); 810eb3ce0d5SKazutaka Miyasaka } 81148d7b7a6SDominik Eckelmann if (!in_array($acl[1], $groups)) { 81248d7b7a6SDominik Eckelmann continue; 81348d7b7a6SDominik Eckelmann } 8148ef6b7caSandi if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 815f3f0262cSandi if ($acl[2] > $perm) { 816f3f0262cSandi $perm = $acl[2]; 817f3f0262cSandi } 818f3f0262cSandi } 819f3f0262cSandi //we had a match - return it 82048d7b7a6SDominik Eckelmann if ($perm != -1) { 821def492a2SGuillaume Turri return (int) $perm; 822f3f0262cSandi } 82348d7b7a6SDominik Eckelmann } 824f3f0262cSandi //get next higher namespace 825f3f0262cSandi $ns = getNS($ns); 826f3f0262cSandi 8273e304b55SMichael Hamann if ($path != '*') { 8283e304b55SMichael Hamann $path = $ns . ':*'; 8293e304b55SMichael Hamann if ($path == ':*') $path = '*'; 830f3f0262cSandi } else { 831f3f0262cSandi //we did this already 832f3f0262cSandi //looks like there is something wrong with the ACL 833f3f0262cSandi //break here 834d5ce66f6SAndreas Gohr msg('No ACL setup yet! Denying access to everyone.'); 835d5ce66f6SAndreas Gohr return AUTH_NONE; 836f3f0262cSandi } 837f3f0262cSandi } while (1); //this should never loop endless 838ab5d26daSAndreas Gohr return AUTH_NONE; 839f3f0262cSandi} 840f3f0262cSandi 841f3f0262cSandi/** 8426c2bb100SAndreas Gohr * Encode ASCII special chars 8436c2bb100SAndreas Gohr * 8446c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames 8456c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars 8466c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual 8476c2bb100SAndreas Gohr * urlencoding!). 8486c2bb100SAndreas Gohr * 8496c2bb100SAndreas Gohr * Decoding can be done with rawurldecode 8506c2bb100SAndreas Gohr * 8516c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de> 8526c2bb100SAndreas Gohr * @see rawurldecode() 85342ea7f44SGerrit Uitslag * 85442ea7f44SGerrit Uitslag * @param string $name 85542ea7f44SGerrit Uitslag * @param bool $skip_group 85642ea7f44SGerrit Uitslag * @return string 8576c2bb100SAndreas Gohr */ 858d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false) 859d868eb89SAndreas Gohr{ 860a424cd8eSchris global $cache_authname; 861a424cd8eSchris $cache =& $cache_authname; 86231784267SAndreas Gohr $name = (string) $name; 863a424cd8eSchris 86480601d26SAndreas Gohr // never encode wildcard FS#1955 86580601d26SAndreas Gohr if ($name == '%USER%') return $name; 866b78bf706Sromain if ($name == '%GROUP%') return $name; 86780601d26SAndreas Gohr 868a424cd8eSchris if (!isset($cache[$name][$skip_group])) { 8692401f18dSSyntaxseed if ($skip_group && $name[0] == '@') { 87030f6faf0SChristopher Smith $cache[$name][$skip_group] = '@' . preg_replace_callback( 87130f6faf0SChristopher Smith '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 872dccd6b2bSAndreas Gohr 'auth_nameencode_callback', 873dccd6b2bSAndreas Gohr substr($name, 1) 874ab5d26daSAndreas Gohr ); 875e838fc2eSAndreas Gohr } else { 87630f6faf0SChristopher Smith $cache[$name][$skip_group] = preg_replace_callback( 87730f6faf0SChristopher Smith '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/', 878dccd6b2bSAndreas Gohr 'auth_nameencode_callback', 879dccd6b2bSAndreas Gohr $name 880ab5d26daSAndreas Gohr ); 881e838fc2eSAndreas Gohr } 8826c2bb100SAndreas Gohr } 8836c2bb100SAndreas Gohr 884a424cd8eSchris return $cache[$name][$skip_group]; 885a424cd8eSchris} 886a424cd8eSchris 88704d68ae4SGerrit Uitslag/** 88804d68ae4SGerrit Uitslag * callback encodes the matches 88904d68ae4SGerrit Uitslag * 89004d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms 89104d68ae4SGerrit Uitslag * @return string 89204d68ae4SGerrit Uitslag */ 893d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches) 894d868eb89SAndreas Gohr{ 89530f6faf0SChristopher Smith return '%' . dechex(ord(substr($matches[1], -1))); 89630f6faf0SChristopher Smith} 89730f6faf0SChristopher Smith 8986c2bb100SAndreas Gohr/** 899f3f0262cSandi * Create a pronouncable password 900f3f0262cSandi * 9018a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password 9028a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation 9038a285f7fSAndreas Gohr * 9044dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated 9054dc42f7fSGerrit Uitslag * @return string pronouncable password 9064dc42f7fSGerrit Uitslag * @throws Exception 9074dc42f7fSGerrit Uitslag * 90815fae107Sandi * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 9098a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE 91015fae107Sandi * 9114dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 912f3f0262cSandi */ 913d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '') 914d868eb89SAndreas Gohr{ 91524870174SAndreas Gohr $data = [ 916d628dcf3SAndreas Gohr 'password' => '', 917d628dcf3SAndreas Gohr 'foruser' => $foruser 91824870174SAndreas Gohr ]; 9198a285f7fSAndreas Gohr 920e1d9dcc8SAndreas Gohr $evt = new Event('AUTH_PASSWORD_GENERATE', $data); 9218a285f7fSAndreas Gohr if ($evt->advise_before(true)) { 922f3f0262cSandi $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 923f3f0262cSandi $v = 'aeiou'; //vowels 924f3f0262cSandi $a = $c . $v; //both 925987c8d26SAndreas Gohr $s = '!$%&?+*~#-_:.;,'; // specials 926f3f0262cSandi 927987c8d26SAndreas Gohr //use thre syllables... 928987c8d26SAndreas Gohr for ($i = 0; $i < 3; $i++) { 929483b6238SMichael Hamann $data['password'] .= $c[auth_random(0, strlen($c) - 1)]; 930483b6238SMichael Hamann $data['password'] .= $v[auth_random(0, strlen($v) - 1)]; 931483b6238SMichael Hamann $data['password'] .= $a[auth_random(0, strlen($a) - 1)]; 932f3f0262cSandi } 933987c8d26SAndreas Gohr //... and add a nice number and special 93443f71e05Ssdavis80 $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99); 9358a285f7fSAndreas Gohr } 9368a285f7fSAndreas Gohr $evt->advise_after(); 937f3f0262cSandi 9388a285f7fSAndreas Gohr return $data['password']; 939f3f0262cSandi} 940f3f0262cSandi 941f3f0262cSandi/** 942f3f0262cSandi * Sends a password to the given user 943f3f0262cSandi * 94415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org> 94542ea7f44SGerrit Uitslag * 946ab5d26daSAndreas Gohr * @param string $user Login name of the user 947ab5d26daSAndreas Gohr * @param string $password The new password in clear text 94815fae107Sandi * @return bool true on success 949f3f0262cSandi */ 950d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password) 951d868eb89SAndreas Gohr{ 952f3f0262cSandi global $lang; 953e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 954cd52f92dSchris global $auth; 9556547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 956cd52f92dSchris 957d752aedeSAndreas Gohr $user = $auth->cleanUser($user); 9584dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 959f3f0262cSandi 96087ddda95Sandi if (!$userinfo['mail']) return false; 961f3f0262cSandi 962f3f0262cSandi $text = rawLocale('password'); 96324870174SAndreas Gohr $trep = [ 964d7169d19SAndreas Gohr 'FULLNAME' => $userinfo['name'], 965d7169d19SAndreas Gohr 'LOGIN' => $user, 966d7169d19SAndreas Gohr 'PASSWORD' => $password 96724870174SAndreas Gohr ]; 968f3f0262cSandi 969d7169d19SAndreas Gohr $mail = new Mailer(); 970102cdbd7SLarsGit223 $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>'); 971d7169d19SAndreas Gohr $mail->subject($lang['regpwmail']); 972d7169d19SAndreas Gohr $mail->setBody($text, $trep); 973d7169d19SAndreas Gohr return $mail->send(); 974f3f0262cSandi} 975f3f0262cSandi 976f3f0262cSandi/** 97715fae107Sandi * Register a new user 978f3f0262cSandi * 97915fae107Sandi * This registers a new user - Data is read directly from $_POST 98015fae107Sandi * 98115fae107Sandi * @return bool true on success, false on any error 9824dc42f7fSGerrit Uitslag * @throws Exception 9834dc42f7fSGerrit Uitslag * 9844dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 985f3f0262cSandi */ 986d868eb89SAndreas Gohrfunction register() 987d868eb89SAndreas Gohr{ 988f3f0262cSandi global $lang; 989eb5d07e4Sjan global $conf; 9904dc42f7fSGerrit Uitslag /* @var AuthPlugin $auth */ 991cd52f92dSchris global $auth; 99264273335SAndreas Gohr global $INPUT; 993f3f0262cSandi 99464273335SAndreas Gohr if (!$INPUT->post->bool('save')) return false; 9953a48618aSAnika Henke if (!actionOK('register')) return false; 996640145a5Sandi 99764273335SAndreas Gohr // gather input 99864273335SAndreas Gohr $login = trim($auth->cleanUser($INPUT->post->str('login'))); 99964273335SAndreas Gohr $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname'))); 100064273335SAndreas Gohr $email = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email'))); 100164273335SAndreas Gohr $pass = $INPUT->post->str('pass'); 100264273335SAndreas Gohr $passchk = $INPUT->post->str('passchk'); 1003d752aedeSAndreas Gohr 100464273335SAndreas Gohr if (empty($login) || empty($fullname) || empty($email)) { 1005f3f0262cSandi msg($lang['regmissing'], -1); 1006f3f0262cSandi return false; 1007f3f0262cSandi } 1008f3f0262cSandi 1009cab2716aSmatthias.grimm if ($conf['autopasswd']) { 10108a285f7fSAndreas Gohr $pass = auth_pwgen($login); // automatically generate password 101164273335SAndreas Gohr } elseif (empty($pass) || empty($passchk)) { 1012bf12ec81Sjan msg($lang['regmissing'], -1); // complain about missing passwords 1013cab2716aSmatthias.grimm return false; 101464273335SAndreas Gohr } elseif ($pass != $passchk) { 1015bf12ec81Sjan msg($lang['regbadpass'], -1); // complain about misspelled passwords 1016cab2716aSmatthias.grimm return false; 1017cab2716aSmatthias.grimm } 1018cab2716aSmatthias.grimm 1019f3f0262cSandi //check mail 102064273335SAndreas Gohr if (!mail_isvalid($email)) { 1021f3f0262cSandi msg($lang['regbadmail'], -1); 1022f3f0262cSandi return false; 1023f3f0262cSandi } 1024f3f0262cSandi 1025f3f0262cSandi //okay try to create the user 102624870174SAndreas Gohr if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) { 1027db9faf02SPatrick Brown msg($lang['regfail'], -1); 1028f3f0262cSandi return false; 1029f3f0262cSandi } 1030f3f0262cSandi 1031790b7720SAndreas Gohr // send notification about the new user 103275d66495SMichael Große $subscription = new RegistrationSubscriptionSender(); 103375d66495SMichael Große $subscription->sendRegister($login, $fullname, $email); 103402a498e7Schris 1035790b7720SAndreas Gohr // are we done? 1036cab2716aSmatthias.grimm if (!$conf['autopasswd']) { 1037cab2716aSmatthias.grimm msg($lang['regsuccess2'], 1); 1038cab2716aSmatthias.grimm return true; 1039cab2716aSmatthias.grimm } 1040cab2716aSmatthias.grimm 1041790b7720SAndreas Gohr // autogenerated password? then send password to user 104264273335SAndreas Gohr if (auth_sendPassword($login, $pass)) { 1043f3f0262cSandi msg($lang['regsuccess'], 1); 1044f3f0262cSandi return true; 1045f3f0262cSandi } else { 1046f3f0262cSandi msg($lang['regmailfail'], -1); 1047f3f0262cSandi return false; 1048f3f0262cSandi } 1049f3f0262cSandi} 1050f3f0262cSandi 105110a76f6fSfrank/** 10528b06d178Schris * Update user profile 10538b06d178Schris * 10544dc42f7fSGerrit Uitslag * @throws Exception 10554dc42f7fSGerrit Uitslag * 10568b06d178Schris * @author Christopher Smith <chris@jalakai.co.uk> 10578b06d178Schris */ 1058d868eb89SAndreas Gohrfunction updateprofile() 1059d868eb89SAndreas Gohr{ 10608b06d178Schris global $conf; 10618b06d178Schris global $lang; 1062e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1063cd52f92dSchris global $auth; 1064bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 1065bcc94b2cSAndreas Gohr global $INPUT; 10668b06d178Schris 1067bcc94b2cSAndreas Gohr if (!$INPUT->post->bool('save')) return false; 10681b2a85e8SAndreas Gohr if (!checkSecurityToken()) return false; 10698b06d178Schris 10703a48618aSAnika Henke if (!actionOK('profile')) { 10718b06d178Schris msg($lang['profna'], -1); 10728b06d178Schris return false; 10738b06d178Schris } 10748b06d178Schris 107524870174SAndreas Gohr $changes = []; 1076bcc94b2cSAndreas Gohr $changes['pass'] = $INPUT->post->str('newpass'); 1077bcc94b2cSAndreas Gohr $changes['name'] = $INPUT->post->str('fullname'); 1078bcc94b2cSAndreas Gohr $changes['mail'] = $INPUT->post->str('email'); 1079bcc94b2cSAndreas Gohr 1080bcc94b2cSAndreas Gohr // check misspelled passwords 1081bcc94b2cSAndreas Gohr if ($changes['pass'] != $INPUT->post->str('passchk')) { 1082bcc94b2cSAndreas Gohr msg($lang['regbadpass'], -1); 10838b06d178Schris return false; 10848b06d178Schris } 10858b06d178Schris 10868b06d178Schris // clean fullname and email 1087bcc94b2cSAndreas Gohr $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name'])); 1088bcc94b2cSAndreas Gohr $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail'])); 10898b06d178Schris 1090bcc94b2cSAndreas Gohr // no empty name and email (except the backend doesn't support them) 10917d34963bSAndreas Gohr if ( 10927d34963bSAndreas Gohr (empty($changes['name']) && $auth->canDo('modName')) || 1093bcc94b2cSAndreas Gohr (empty($changes['mail']) && $auth->canDo('modMail')) 1094ab5d26daSAndreas Gohr ) { 10958b06d178Schris msg($lang['profnoempty'], -1); 10968b06d178Schris return false; 10978b06d178Schris } 1098bcc94b2cSAndreas Gohr if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) { 10998b06d178Schris msg($lang['regbadmail'], -1); 11008b06d178Schris return false; 11018b06d178Schris } 11028b06d178Schris 1103bcc94b2cSAndreas Gohr $changes = array_filter($changes); 11044c21b7eeSAndreas Gohr 1105bcc94b2cSAndreas Gohr // check for unavailable capabilities 1106bcc94b2cSAndreas Gohr if (!$auth->canDo('modName')) unset($changes['name']); 1107bcc94b2cSAndreas Gohr if (!$auth->canDo('modMail')) unset($changes['mail']); 1108bcc94b2cSAndreas Gohr if (!$auth->canDo('modPass')) unset($changes['pass']); 1109bcc94b2cSAndreas Gohr 1110bcc94b2cSAndreas Gohr // anything to do? 111124870174SAndreas Gohr if ($changes === []) { 11128b06d178Schris msg($lang['profnochange'], -1); 11138b06d178Schris return false; 11148b06d178Schris } 11158b06d178Schris 11168b06d178Schris if ($conf['profileconfirm']) { 1117585bf44eSChristopher Smith if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 111871422fc8SChristopher Smith msg($lang['badpassconfirm'], -1); 11198b06d178Schris return false; 11208b06d178Schris } 11218b06d178Schris } 11228b06d178Schris 112324870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) { 1124db9faf02SPatrick Brown msg($lang['proffail'], -1); 1125db9faf02SPatrick Brown return false; 1126db9faf02SPatrick Brown } 1127db9faf02SPatrick Brown 112867efd1edSPieter Hollants if (array_key_exists('pass', $changes) && $changes['pass']) { 1129c276e9e8SMarcel Pennewiss // update cookie and session with the changed data 1130a19c9aa0SGerrit Uitslag [/* user */, $sticky, /* pass */] = auth_getCookie(); 113104369c3eSMichael Hamann $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true)); 1132585bf44eSChristopher Smith auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky); 1133c276e9e8SMarcel Pennewiss } else { 1134c276e9e8SMarcel Pennewiss // make sure the session is writable 1135c276e9e8SMarcel Pennewiss @session_start(); 1136c276e9e8SMarcel Pennewiss // invalidate session cache 1137c276e9e8SMarcel Pennewiss $_SESSION[DOKU_COOKIE]['auth']['time'] = 0; 1138c276e9e8SMarcel Pennewiss session_write_close(); 113932ed2b36SAndreas Gohr } 1140c276e9e8SMarcel Pennewiss 114125b2a98cSMichael Klier return true; 1142a0b5b007SChris Smith} 1143ab5d26daSAndreas Gohr 114404d68ae4SGerrit Uitslag/** 114504d68ae4SGerrit Uitslag * Delete the current logged-in user 114604d68ae4SGerrit Uitslag * 114704d68ae4SGerrit Uitslag * @return bool true on success, false on any error 114804d68ae4SGerrit Uitslag */ 1149d868eb89SAndreas Gohrfunction auth_deleteprofile() 1150d868eb89SAndreas Gohr{ 11512a7abf2dSChristopher Smith global $conf; 11522a7abf2dSChristopher Smith global $lang; 11534dc42f7fSGerrit Uitslag /* @var AuthPlugin $auth */ 11542a7abf2dSChristopher Smith global $auth; 11552a7abf2dSChristopher Smith /* @var Input $INPUT */ 11562a7abf2dSChristopher Smith global $INPUT; 11572a7abf2dSChristopher Smith 11582a7abf2dSChristopher Smith if (!$INPUT->post->bool('delete')) return false; 11592a7abf2dSChristopher Smith if (!checkSecurityToken()) return false; 11602a7abf2dSChristopher Smith 11612a7abf2dSChristopher Smith // action prevented or auth module disallows 11622a7abf2dSChristopher Smith if (!actionOK('profile_delete') || !$auth->canDo('delUser')) { 11632a7abf2dSChristopher Smith msg($lang['profnodelete'], -1); 11642a7abf2dSChristopher Smith return false; 11652a7abf2dSChristopher Smith } 11662a7abf2dSChristopher Smith 11672a7abf2dSChristopher Smith if (!$INPUT->post->bool('confirm_delete')) { 11682a7abf2dSChristopher Smith msg($lang['profconfdeletemissing'], -1); 11692a7abf2dSChristopher Smith return false; 11702a7abf2dSChristopher Smith } 11712a7abf2dSChristopher Smith 11722a7abf2dSChristopher Smith if ($conf['profileconfirm']) { 1173585bf44eSChristopher Smith if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) { 11742a7abf2dSChristopher Smith msg($lang['badpassconfirm'], -1); 11752a7abf2dSChristopher Smith return false; 11762a7abf2dSChristopher Smith } 11772a7abf2dSChristopher Smith } 11782a7abf2dSChristopher Smith 117924870174SAndreas Gohr $deleted = []; 1180585bf44eSChristopher Smith $deleted[] = $INPUT->server->str('REMOTE_USER'); 118124870174SAndreas Gohr if ($auth->triggerUserMod('delete', [$deleted])) { 11822a7abf2dSChristopher Smith // force and immediate logout including removing the sticky cookie 11832a7abf2dSChristopher Smith auth_logoff(); 11842a7abf2dSChristopher Smith return true; 11852a7abf2dSChristopher Smith } 11862a7abf2dSChristopher Smith 11872a7abf2dSChristopher Smith return false; 11882a7abf2dSChristopher Smith} 11892a7abf2dSChristopher Smith 11908b06d178Schris/** 11918b06d178Schris * Send a new password 11928b06d178Schris * 11931d5856cfSAndreas Gohr * This function handles both phases of the password reset: 11941d5856cfSAndreas Gohr * 11951d5856cfSAndreas Gohr * - handling the first request of password reset 11961d5856cfSAndreas Gohr * - validating the password reset auth token 11971d5856cfSAndreas Gohr * 11984dc42f7fSGerrit Uitslag * @return bool true on success, false on any error 11994dc42f7fSGerrit Uitslag * @throws Exception 12004dc42f7fSGerrit Uitslag * 12014dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 12028b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info> 12038b06d178Schris * @author Chris Smith <chris@jalakai.co.uk> 12048b06d178Schris */ 1205d868eb89SAndreas Gohrfunction act_resendpwd() 1206d868eb89SAndreas Gohr{ 12078b06d178Schris global $lang; 12088b06d178Schris global $conf; 1209e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1210cd52f92dSchris global $auth; 1211bcc94b2cSAndreas Gohr /* @var Input $INPUT */ 1212bcc94b2cSAndreas Gohr global $INPUT; 12138b06d178Schris 12143a48618aSAnika Henke if (!actionOK('resendpwd')) { 12158b06d178Schris msg($lang['resendna'], -1); 12168b06d178Schris return false; 12178b06d178Schris } 12188b06d178Schris 1219bcc94b2cSAndreas Gohr $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth')); 12208b06d178Schris 12211d5856cfSAndreas Gohr if ($token) { 1222cc204bbdSAndreas Gohr // we're in token phase - get user info from token 12231d5856cfSAndreas Gohr 12242401f18dSSyntaxseed $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 122579e79377SAndreas Gohr if (!file_exists($tfile)) { 12261d5856cfSAndreas Gohr msg($lang['resendpwdbadauth'], -1); 1227bcc94b2cSAndreas Gohr $INPUT->remove('pwauth'); 12281d5856cfSAndreas Gohr return false; 12291d5856cfSAndreas Gohr } 12308a9735e3SAndreas Gohr // token is only valid for 3 days 12318a9735e3SAndreas Gohr if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) { 12328a9735e3SAndreas Gohr msg($lang['resendpwdbadauth'], -1); 1233bcc94b2cSAndreas Gohr $INPUT->remove('pwauth'); 12341d5856cfSAndreas Gohr @unlink($tfile); 12358a9735e3SAndreas Gohr return false; 12368a9735e3SAndreas Gohr } 12378a9735e3SAndreas Gohr 12388b06d178Schris $user = io_readfile($tfile); 12394dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 12408b06d178Schris if (!$userinfo['mail']) { 12418b06d178Schris msg($lang['resendpwdnouser'], -1); 12428b06d178Schris return false; 12438b06d178Schris } 12448b06d178Schris 1245cc204bbdSAndreas Gohr if (!$conf['autopasswd']) { // we let the user choose a password 1246bcc94b2cSAndreas Gohr $pass = $INPUT->str('pass'); 1247bcc94b2cSAndreas Gohr 1248cc204bbdSAndreas Gohr // password given correctly? 1249bcc94b2cSAndreas Gohr if (!$pass) return false; 1250bcc94b2cSAndreas Gohr if ($pass != $INPUT->str('passchk')) { 1251451e1b4dSAndreas Gohr msg($lang['regbadpass'], -1); 1252cc204bbdSAndreas Gohr return false; 1253cc204bbdSAndreas Gohr } 1254cc204bbdSAndreas Gohr 1255bcc94b2cSAndreas Gohr // change it 125624870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1257db9faf02SPatrick Brown msg($lang['proffail'], -1); 1258cc204bbdSAndreas Gohr return false; 1259cc204bbdSAndreas Gohr } 1260cc204bbdSAndreas Gohr } else { // autogenerate the password and send by mail 12618a285f7fSAndreas Gohr $pass = auth_pwgen($user); 126224870174SAndreas Gohr if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) { 1263db9faf02SPatrick Brown msg($lang['proffail'], -1); 12648b06d178Schris return false; 12658b06d178Schris } 12668b06d178Schris 12678b06d178Schris if (auth_sendPassword($user, $pass)) { 12688b06d178Schris msg($lang['resendpwdsuccess'], 1); 12698b06d178Schris } else { 12708b06d178Schris msg($lang['regmailfail'], -1); 12718b06d178Schris } 1272cc204bbdSAndreas Gohr } 1273cc204bbdSAndreas Gohr 1274cc204bbdSAndreas Gohr @unlink($tfile); 12758b06d178Schris return true; 12761d5856cfSAndreas Gohr } else { 12771d5856cfSAndreas Gohr // we're in request phase 12781d5856cfSAndreas Gohr 1279bcc94b2cSAndreas Gohr if (!$INPUT->post->bool('save')) return false; 12801d5856cfSAndreas Gohr 1281bcc94b2cSAndreas Gohr if (!$INPUT->post->str('login')) { 12821d5856cfSAndreas Gohr msg($lang['resendpwdmissing'], -1); 12831d5856cfSAndreas Gohr return false; 12841d5856cfSAndreas Gohr } else { 1285bcc94b2cSAndreas Gohr $user = trim($auth->cleanUser($INPUT->post->str('login'))); 12861d5856cfSAndreas Gohr } 12871d5856cfSAndreas Gohr 12884dc42f7fSGerrit Uitslag $userinfo = $auth->getUserData($user, false); 12891d5856cfSAndreas Gohr if (!$userinfo['mail']) { 12901d5856cfSAndreas Gohr msg($lang['resendpwdnouser'], -1); 12911d5856cfSAndreas Gohr return false; 12921d5856cfSAndreas Gohr } 12931d5856cfSAndreas Gohr 12941d5856cfSAndreas Gohr // generate auth token 1295483b6238SMichael Hamann $token = md5(auth_randombytes(16)); // random secret 12962401f18dSSyntaxseed $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth'; 129724870174SAndreas Gohr $url = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&'); 12981d5856cfSAndreas Gohr 12991d5856cfSAndreas Gohr io_saveFile($tfile, $user); 13001d5856cfSAndreas Gohr 13011d5856cfSAndreas Gohr $text = rawLocale('pwconfirm'); 130224870174SAndreas Gohr $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN' => $user, 'CONFIRM' => $url]; 13031d5856cfSAndreas Gohr 1304d7169d19SAndreas Gohr $mail = new Mailer(); 1305d7169d19SAndreas Gohr $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>'); 1306d7169d19SAndreas Gohr $mail->subject($lang['regpwmail']); 1307d7169d19SAndreas Gohr $mail->setBody($text, $trep); 1308d7169d19SAndreas Gohr if ($mail->send()) { 13091d5856cfSAndreas Gohr msg($lang['resendpwdconfirm'], 1); 13101d5856cfSAndreas Gohr } else { 13111d5856cfSAndreas Gohr msg($lang['regmailfail'], -1); 13121d5856cfSAndreas Gohr } 13131d5856cfSAndreas Gohr return true; 13141d5856cfSAndreas Gohr } 1315ab5d26daSAndreas Gohr // never reached 13168b06d178Schris} 13178b06d178Schris 13188b06d178Schris/** 1319b0855b11Sandi * Encrypts a password using the given method and salt 1320b0855b11Sandi * 1321b0855b11Sandi * If the selected method needs a salt and none was given, a random one 1322b0855b11Sandi * is chosen. 1323b0855b11Sandi * 1324b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org> 132542ea7f44SGerrit Uitslag * 1326ab5d26daSAndreas Gohr * @param string $clear The clear text password 1327ab5d26daSAndreas Gohr * @param string $method The hashing method 1328ab5d26daSAndreas Gohr * @param string $salt A salt, null for random 1329b0855b11Sandi * @return string The crypted password 1330b0855b11Sandi */ 1331d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) 1332d868eb89SAndreas Gohr{ 1333b0855b11Sandi global $conf; 1334*527ad715STobias Bengfort 1335*527ad715STobias Bengfort if ($clear === null) { 1336*527ad715STobias Bengfort return UNUSABLE_PASSWORD; 1337*527ad715STobias Bengfort } 1338*527ad715STobias Bengfort 1339b0855b11Sandi if (empty($method)) $method = $conf['passcrypt']; 134010a76f6fSfrank 13413a0a2d05SAndreas Gohr $pass = new PassHash(); 13423a0a2d05SAndreas Gohr $call = 'hash_' . $method; 1343b0855b11Sandi 13443a0a2d05SAndreas Gohr if (!method_exists($pass, $call)) { 1345b0855b11Sandi msg("Unsupported crypt method $method", -1); 13463a0a2d05SAndreas Gohr return false; 1347b0855b11Sandi } 13483a0a2d05SAndreas Gohr 13493a0a2d05SAndreas Gohr return $pass->$call($clear, $salt); 1350b0855b11Sandi} 1351b0855b11Sandi 1352b0855b11Sandi/** 1353b0855b11Sandi * Verifies a cleartext password against a crypted hash 1354b0855b11Sandi * 1355ab5d26daSAndreas Gohr * @param string $clear The clear text password 1356ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with 1357ab5d26daSAndreas Gohr * @return bool true if both match 13584dc42f7fSGerrit Uitslag * @throws Exception 13594dc42f7fSGerrit Uitslag * 13604dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org> 1361b0855b11Sandi */ 1362d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt) 1363d868eb89SAndreas Gohr{ 1364*527ad715STobias Bengfort if ($crypt === UNUSABLE_PASSWORD) { 1365*527ad715STobias Bengfort return false; 1366*527ad715STobias Bengfort } 1367*527ad715STobias Bengfort 13683a0a2d05SAndreas Gohr $pass = new PassHash(); 13693a0a2d05SAndreas Gohr return $pass->verify_hash($clear, $crypt); 1370b0855b11Sandi} 1371340756e4Sandi 1372a0b5b007SChris Smith/** 1373a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session 1374a0b5b007SChris Smith * 1375a0b5b007SChris Smith * @param string $user username 1376a0b5b007SChris Smith * @param string $pass encrypted password 1377a0b5b007SChris Smith * @param bool $sticky whether or not the cookie will last beyond the session 1378ab5d26daSAndreas Gohr * @return bool 1379a0b5b007SChris Smith */ 1380d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky) 1381d868eb89SAndreas Gohr{ 1382a0b5b007SChris Smith global $conf; 1383e1d9dcc8SAndreas Gohr /* @var AuthPlugin $auth */ 1384a0b5b007SChris Smith global $auth; 138579d00841SOliver Geisen global $USERINFO; 1386a0b5b007SChris Smith 13876547cfc7SGerrit Uitslag if (!$auth instanceof AuthPlugin) return false; 1388a0b5b007SChris Smith $USERINFO = $auth->getUserData($user); 1389a0b5b007SChris Smith 1390a0b5b007SChris Smith // set cookie 1391645c0a36SAndreas Gohr $cookie = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass); 139273ab87deSGabriel Birke $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 1393c66972f2SAdrian Lang $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year 1394bf8392ebSAndreas Gohr setcookie(DOKU_COOKIE, $cookie, [ 1395bf8392ebSAndreas Gohr 'expires' => $time, 1396bf8392ebSAndreas Gohr 'path' => $cookieDir, 1397bf8392ebSAndreas Gohr 'secure' => ($conf['securecookie'] && is_ssl()), 1398bf8392ebSAndreas Gohr 'httponly' => true, 1399486f82fcSAndreas Gohr 'samesite' => $conf['samesitecookie'] ?: null, // null means browser default 1400bf8392ebSAndreas Gohr ]); 140155a71a16SGerrit Uitslag 1402a0b5b007SChris Smith // set session 1403a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 1404234ce57eSAndreas Gohr $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass); 1405a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 1406a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 1407a0b5b007SChris Smith $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 1408ab5d26daSAndreas Gohr 1409ab5d26daSAndreas Gohr return true; 1410a0b5b007SChris Smith} 1411a0b5b007SChris Smith 1412645c0a36SAndreas Gohr/** 1413645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie 1414645c0a36SAndreas Gohr * 1415645c0a36SAndreas Gohr * @returns array 1416645c0a36SAndreas Gohr */ 1417d868eb89SAndreas Gohrfunction auth_getCookie() 1418d868eb89SAndreas Gohr{ 1419c66972f2SAdrian Lang if (!isset($_COOKIE[DOKU_COOKIE])) { 142024870174SAndreas Gohr return [null, null, null]; 1421c66972f2SAdrian Lang } 142224870174SAndreas Gohr [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, ''); 1423645c0a36SAndreas Gohr $sticky = (bool) $sticky; 1424645c0a36SAndreas Gohr $pass = base64_decode($pass); 1425645c0a36SAndreas Gohr $user = base64_decode($user); 142624870174SAndreas Gohr return [$user, $sticky, $pass]; 1427645c0a36SAndreas Gohr} 1428645c0a36SAndreas Gohr 1429e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 : 1430