xref: /dokuwiki/inc/auth.php (revision 9d1b64723676aa055991830d88f232fec75d8798)
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
139399c87eSsplitbrainuse dokuwiki\Ip;
141cedacf2SAndreas Gohruse dokuwiki\ErrorHandler;
15cf927d07Ssplitbrainuse dokuwiki\JWT;
1624870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1796348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1896348f27SAndreas Gohruse dokuwiki\Extension\Event;
1996348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
20c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
2175d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
22927933f5SAndreas Gohruse phpseclib3\Crypt\AES;
23927933f5SAndreas Gohruse phpseclib3\Crypt\Common\SymmetricKey;
241cedacf2SAndreas Gohruse phpseclib3\Exception\BadDecryptionException;
25c3cc6e05SAndreas Gohr
2616905344SAndreas Gohr/**
2716905344SAndreas Gohr * Initialize the auth system.
2816905344SAndreas Gohr *
2916905344SAndreas Gohr * This function is automatically called at the end of init.php
3016905344SAndreas Gohr *
3116905344SAndreas Gohr * This used to be the main() of the auth.php
3216905344SAndreas Gohr *
3316905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3416905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
35ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
36ab5d26daSAndreas Gohr * @return bool
3716905344SAndreas Gohr */
38d868eb89SAndreas Gohrfunction auth_setup()
39d868eb89SAndreas Gohr{
40742c66f8Schris    global $conf;
41e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4203c4aec3Schris    global $auth;
43bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
44bcc94b2cSAndreas Gohr    global $INPUT;
459a9714acSDominik Eckelmann    global $AUTH_ACL;
469a9714acSDominik Eckelmann    global $lang;
473a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
489c29eea5SJan Schumann    global $plugin_controller;
4924870174SAndreas Gohr    $AUTH_ACL = [];
5003c4aec3Schris
51b9cda918SAndreas Gohr    // unset REMOTE_USER if empty
52b9cda918SAndreas Gohr    if ($INPUT->server->str('REMOTE_USER') === '') {
53b9cda918SAndreas Gohr        $INPUT->server->remove('REMOTE_USER');
54b9cda918SAndreas Gohr    }
55b9cda918SAndreas Gohr
5616905344SAndreas Gohr    if (!$conf['useacl']) return false;
5716905344SAndreas Gohr
589c29eea5SJan Schumann    // try to load auth backend from plugins
599c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
609c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
61f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
629c29eea5SJan Schumann            break;
639c29eea5SJan Schumann        }
649c29eea5SJan Schumann    }
658b06d178Schris
666547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) {
6771c734a9SGerrit Uitslag        msg($lang['authtempfail'], -1);
683094e817SAndreas Gohr        return false;
693094e817SAndreas Gohr    }
708b06d178Schris
716416b708SMichael Hamann    if ($auth->success == false) {
720f4f4adfSAndreas Gohr        // degrade to unauthenticated user
73ecad51ddSAndreas Gohr        $auth = null;
740f4f4adfSAndreas Gohr        auth_logoff();
75cd52f92dSchris        msg($lang['authtempfail'], -1);
766416b708SMichael Hamann        return false;
77d2dde4ebSMatthias Grimm    }
7816905344SAndreas Gohr
7916905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
80bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
81bcc94b2cSAndreas Gohr    if (!$conf['rememberme']) $INPUT->set('r', false);
82bbbd6568SAndreas Gohr
8362bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
8462bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
8562bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
8662bf3ac0SDamien Regad    if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
8762bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
8824870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
89528ddc7cSAndreas Gohr    }
90528ddc7cSAndreas Gohr
911e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
9203062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
9303062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
9403062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
95bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
961e8c9c90SAndreas Gohr    }
971e8c9c90SAndreas Gohr
98395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9993a7873eSAndreas Gohr    if (true === $auth->success) {
100395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
101395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
102f4476bd9SJan Schumann    }
103191bb90aSAndreas Gohr
104455aa67eSAndreas Gohr    if (!auth_tokenlogin()) {
10581e99965SPhy        $ok = null;
106455aa67eSAndreas Gohr
1078407f251Ssplitbrain        if ($auth->canDo('external')) {
10881e99965SPhy            $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
10981e99965SPhy        }
11081e99965SPhy
11181e99965SPhy        if ($ok === null) {
11281e99965SPhy            // external trust mechanism not in place, or returns no result,
11381e99965SPhy            // then attempt auth_login
11424870174SAndreas Gohr            $evdata = [
115bcc94b2cSAndreas Gohr                'user' => $INPUT->str('u'),
116bcc94b2cSAndreas Gohr                'password' => $INPUT->str('p'),
117bcc94b2cSAndreas Gohr                'sticky' => $INPUT->bool('r'),
118bcc94b2cSAndreas Gohr                'silent' => $INPUT->bool('http_credentials')
11924870174SAndreas Gohr            ];
120cbb44eabSAndreas Gohr            Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
121f5cb575dSAndreas Gohr        }
122455aa67eSAndreas Gohr    }
123f5cb575dSAndreas Gohr
12416905344SAndreas Gohr    //load ACL into a global array XXX
12575c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
126ab5d26daSAndreas Gohr
127ab5d26daSAndreas Gohr    return true;
12875c93b77SAndreas Gohr}
12975c93b77SAndreas Gohr
13075c93b77SAndreas Gohr/**
13175c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
13275c93b77SAndreas Gohr *
13375c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13442ea7f44SGerrit Uitslag *
135ab5d26daSAndreas Gohr * @return array
13675c93b77SAndreas Gohr */
137d868eb89SAndreas Gohrfunction auth_loadACL()
138d868eb89SAndreas Gohr{
13975c93b77SAndreas Gohr    global $config_cascade;
140b78bf706Sromain    global $USERINFO;
141585bf44eSChristopher Smith    /* @var Input $INPUT */
142585bf44eSChristopher Smith    global $INPUT;
14375c93b77SAndreas Gohr
14424870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
14575c93b77SAndreas Gohr
14675c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
14775c93b77SAndreas Gohr
14824870174SAndreas Gohr    $out = [];
1499ce556d2SAndreas Gohr    foreach ($acl as $line) {
1509ce556d2SAndreas Gohr        $line = trim($line);
1512401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
15224870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
15332e82180SAndreas Gohr
154443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
155ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
156ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
157585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
158ad3d68d7SChristopher Smith
159585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
160585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
161ad3d68d7SChristopher Smith        }
162ad3d68d7SChristopher Smith
163ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1649ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
165ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
16606f34f54SPhy            if (isset($USERINFO['grps'])) {
1679ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
168b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
16932e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
17032e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
171b78bf706Sromain                }
17206f34f54SPhy            }
17332e82180SAndreas Gohr        } else {
17432e82180SAndreas Gohr            $out[] = "$id\t$rest";
175a8fe108bSGuy Brand        }
17611799630Sandi    }
1779ce556d2SAndreas Gohr
17832e82180SAndreas Gohr    return $out;
179f3f0262cSandi}
180f3f0262cSandi
181ab5d26daSAndreas Gohr/**
182455aa67eSAndreas Gohr * Try a token login
183455aa67eSAndreas Gohr *
184455aa67eSAndreas Gohr * @return bool true if token login succeeded
185455aa67eSAndreas Gohr */
186cf927d07Ssplitbrainfunction auth_tokenlogin()
187cf927d07Ssplitbrain{
188455aa67eSAndreas Gohr    global $USERINFO;
189455aa67eSAndreas Gohr    global $INPUT;
190455aa67eSAndreas Gohr    /** @var DokuWiki_Auth_Plugin $auth */
191455aa67eSAndreas Gohr    global $auth;
192455aa67eSAndreas Gohr    if (!$auth) return false;
193455aa67eSAndreas Gohr
1947ffd5bd2SAndreas Gohr    $headers = [];
1950a302752SAndreas Gohr
1960a302752SAndreas Gohr    // try to get the headers from Apache
1970a302752SAndreas Gohr    if (function_exists('getallheaders')) {
1980a302752SAndreas Gohr        $headers = getallheaders();
1990a302752SAndreas Gohr        if (is_array($headers)) {
2000a302752SAndreas Gohr            $headers = array_change_key_case($headers);
2010a302752SAndreas Gohr        }
2020a302752SAndreas Gohr    }
2030a302752SAndreas Gohr
2040a302752SAndreas Gohr    // get the headers from $_SERVER
2050a302752SAndreas Gohr    if (!$headers) {
2067ffd5bd2SAndreas Gohr        foreach ($_SERVER as $key => $value) {
2077ffd5bd2SAndreas Gohr            if (substr($key, 0, 5) === 'HTTP_') {
2087ffd5bd2SAndreas Gohr                $headers[strtolower(substr($key, 5))] = $value;
209455aa67eSAndreas Gohr            }
2107ffd5bd2SAndreas Gohr        }
2117ffd5bd2SAndreas Gohr    }
2127ffd5bd2SAndreas Gohr
2137ffd5bd2SAndreas Gohr    // check authorization header
2147ffd5bd2SAndreas Gohr    if (isset($headers['authorization'])) {
2157ffd5bd2SAndreas Gohr        [$type, $token] = sexplode(' ', $headers['authorization'], 2);
2167ffd5bd2SAndreas Gohr        if ($type !== 'Bearer') $token = ''; // not the token we want
2177ffd5bd2SAndreas Gohr    }
2187ffd5bd2SAndreas Gohr
2197ffd5bd2SAndreas Gohr    // check x-dokuwiki-token header
2207ffd5bd2SAndreas Gohr    if (isset($headers['x-dokuwiki-token'])) {
2217ffd5bd2SAndreas Gohr        $token = $headers['x-dokuwiki-token'];
2227ffd5bd2SAndreas Gohr    }
2237ffd5bd2SAndreas Gohr
2247ffd5bd2SAndreas Gohr    if (empty($token)) return false;
225455aa67eSAndreas Gohr
226455aa67eSAndreas Gohr    // check token
227455aa67eSAndreas Gohr    try {
228cf927d07Ssplitbrain        $authtoken = JWT::validate($token);
229455aa67eSAndreas Gohr    } catch (Exception $e) {
230455aa67eSAndreas Gohr        msg(hsc($e->getMessage()), -1);
231455aa67eSAndreas Gohr        return false;
232455aa67eSAndreas Gohr    }
233455aa67eSAndreas Gohr
234455aa67eSAndreas Gohr    // fetch user info from backend
235455aa67eSAndreas Gohr    $user = $authtoken->getUser();
236455aa67eSAndreas Gohr    $USERINFO = $auth->getUserData($user);
237455aa67eSAndreas Gohr    if (!$USERINFO) return false;
238455aa67eSAndreas Gohr
239455aa67eSAndreas Gohr    // the code is correct, set up user
240455aa67eSAndreas Gohr    $INPUT->server->set('REMOTE_USER', $user);
241455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
242455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
243455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
244455aa67eSAndreas Gohr
245455aa67eSAndreas Gohr    return true;
246455aa67eSAndreas Gohr}
247455aa67eSAndreas Gohr
248455aa67eSAndreas Gohr/**
249ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
250ab5d26daSAndreas Gohr *
25142ea7f44SGerrit Uitslag * @param array $evdata
252ab5d26daSAndreas Gohr * @return bool
2534dc42f7fSGerrit Uitslag * @throws Exception
254ab5d26daSAndreas Gohr */
255d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
256d868eb89SAndreas Gohr{
257ab5d26daSAndreas Gohr    return auth_login(
258ab5d26daSAndreas Gohr        $evdata['user'],
259b5ee21aaSAdrian Lang        $evdata['password'],
260b5ee21aaSAdrian Lang        $evdata['sticky'],
261ab5d26daSAndreas Gohr        $evdata['silent']
262ab5d26daSAndreas Gohr    );
263b5ee21aaSAdrian Lang}
264b5ee21aaSAdrian Lang
265f3f0262cSandi/**
266f3f0262cSandi * This tries to login the user based on the sent auth credentials
267f3f0262cSandi *
268f3f0262cSandi * The authentication works like this: if a username was given
26915fae107Sandi * a new login is assumed and user/password are checked. If they
27015fae107Sandi * are correct the password is encrypted with blowfish and stored
27115fae107Sandi * together with the username in a cookie - the same info is stored
27215fae107Sandi * in the session, too. Additonally a browserID is stored in the
27315fae107Sandi * session.
27415fae107Sandi *
27515fae107Sandi * If no username was given the cookie is checked: if the username,
27615fae107Sandi * crypted password and browserID match between session and cookie
27715fae107Sandi * no further testing is done and the user is accepted
27815fae107Sandi *
27915fae107Sandi * If a cookie was found but no session info was availabe the
280136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
28115fae107Sandi * together with username rechecked by calling this function again.
282f3f0262cSandi *
283f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
284f3f0262cSandi * are set.
28515fae107Sandi *
28615fae107Sandi * @param string $user Username
28715fae107Sandi * @param string $pass Cleartext Password
28815fae107Sandi * @param bool $sticky Cookie should not expire
289f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
29015fae107Sandi * @return bool true on successful auth
2914dc42f7fSGerrit Uitslag * @throws Exception
2924dc42f7fSGerrit Uitslag *
2934dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
294f3f0262cSandi */
295d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
296d868eb89SAndreas Gohr{
297f3f0262cSandi    global $USERINFO;
298f3f0262cSandi    global $conf;
299f3f0262cSandi    global $lang;
300e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
301cd52f92dSchris    global $auth;
302585bf44eSChristopher Smith    /* @var Input $INPUT */
303585bf44eSChristopher Smith    global $INPUT;
304ab5d26daSAndreas Gohr
3056547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
306beca106aSAdrian Lang
307bbbd6568SAndreas Gohr    if (!empty($user)) {
308132bdbfeSandi        //usual login
309f7f6f5fcSsplitbrain        if (!empty($pass)) usleep(random_int(0, 250)); // add a random delay to prevent timing attacks #4491
3105e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
311132bdbfeSandi            // make logininfo globally available
312585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
31330d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
31404369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
315132bdbfeSandi            return true;
316f3f0262cSandi        } else {
317f3f0262cSandi            //invalid credentials - log off
318f8b1e4e7SAndreas Gohr            if (!$silent) {
319f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
320f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
321f8b1e4e7SAndreas Gohr            }
322f3f0262cSandi            auth_logoff();
323132bdbfeSandi            return false;
324f3f0262cSandi        }
325f3f0262cSandi    } else {
326132bdbfeSandi        // read cookie information
32724870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
328132bdbfeSandi        if ($user && $pass) {
329132bdbfeSandi            // we got a cookie - see if we can trust it
330fa7c70ffSAdrian Lang
331fa7c70ffSAdrian Lang            // get session info
3320058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
333bc6b1759SAndreas Gohr                $session = $_SESSION[DOKU_COOKIE]['auth'] ?? [];
3347d34963bSAndreas Gohr                if (
335*9d1b6472SEduardo Mozart de Oliveira                    isset($session['user']) &&
336*9d1b6472SEduardo Mozart de Oliveira                    isset($session['pass']) &&
3377172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3384c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
339132bdbfeSandi                    ($session['user'] == $user) &&
340234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
341ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
342ab5d26daSAndreas Gohr                ) {
343132bdbfeSandi                    // he has session, cookie and browser right - let him in
344585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
345132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
346132bdbfeSandi                    return true;
347132bdbfeSandi                }
3480058ae75SDamien Regad            }
349f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
35030d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
35104369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
352f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
353132bdbfeSandi        }
354132bdbfeSandi    }
355f3f0262cSandi    //just to be sure
356883179a4SAndreas Gohr    auth_logoff(true);
357132bdbfeSandi    return false;
358f3f0262cSandi}
359132bdbfeSandi
360132bdbfeSandi/**
361136ce040Sandi * Builds a pseudo UID from browser and IP data
362132bdbfeSandi *
363132bdbfeSandi * This is neither unique nor unfakable - still it adds some
364136ce040Sandi * security. Using the first part of the IP makes sure
36580b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
36615fae107Sandi *
36715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
36815fae107Sandi *
369b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
370132bdbfeSandi */
371d868eb89SAndreas Gohrfunction auth_browseruid()
372d868eb89SAndreas Gohr{
373585bf44eSChristopher Smith    /* @var Input $INPUT */
374585bf44eSChristopher Smith    global $INPUT;
375585bf44eSChristopher Smith
3762f9daf16SAndreas Gohr    $ip = clientIP(true);
377b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
378b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
379b7c67f83SAndreas Gohr
380b7c67f83SAndreas Gohr    $uid = implode("\n", [
381b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
382b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
383b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
384b7c67f83SAndreas Gohr    ]);
385b13c0e1aSAdaKaleh    return hash('sha256', $uid);
386132bdbfeSandi}
387132bdbfeSandi
388132bdbfeSandi/**
389132bdbfeSandi * Creates a random key to encrypt the password in cookies
39015fae107Sandi *
39115fae107Sandi * This function tries to read the password for encrypting
39298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
39315fae107Sandi * if no such file is found a random key is created and
39415fae107Sandi * and stored in this file.
39515fae107Sandi *
39632ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
39730d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
39815fae107Sandi * @return  string
3994dc42f7fSGerrit Uitslag * @throws Exception
4004dc42f7fSGerrit Uitslag *
4014dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
402132bdbfeSandi */
403d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
404d868eb89SAndreas Gohr{
405a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
406fe745becSMichael Große        return 'test';
407a1fe3c9cSMichael Große    }
408132bdbfeSandi    global $conf;
40998407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
41030d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
41130d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
41230d544a4SMichael Hamann    }
413132bdbfeSandi    $salt = io_readFile($file);
414132bdbfeSandi    if (empty($salt)) {
41530d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
416132bdbfeSandi        io_saveFile($file, $salt);
417132bdbfeSandi    }
41832ed2b36SAndreas Gohr    if ($addsession) {
41932ed2b36SAndreas Gohr        $salt .= session_id();
42032ed2b36SAndreas Gohr    }
421132bdbfeSandi    return $salt;
422f3f0262cSandi}
423f3f0262cSandi
424f3f0262cSandi/**
4257a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
426483b6238SMichael Hamann *
4277a33d2f8SNiklas Keller * @param int $length number of bytes
4287a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
4294dc42f7fSGerrit Uitslag * @throws Exception
4304dc42f7fSGerrit Uitslag *
4314dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
432483b6238SMichael Hamann */
433d868eb89SAndreas Gohrfunction auth_randombytes($length)
434d868eb89SAndreas Gohr{
4357a33d2f8SNiklas Keller    return random_bytes($length);
436483b6238SMichael Hamann}
437483b6238SMichael Hamann
438483b6238SMichael Hamann/**
4397a33d2f8SNiklas Keller * Cryptographically secure random number generator.
440483b6238SMichael Hamann *
441483b6238SMichael Hamann * @param int $min
442483b6238SMichael Hamann * @param int $max
443483b6238SMichael Hamann * @return int
4444dc42f7fSGerrit Uitslag * @throws Exception
4454dc42f7fSGerrit Uitslag *
4464dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
447483b6238SMichael Hamann */
448d868eb89SAndreas Gohrfunction auth_random($min, $max)
449d868eb89SAndreas Gohr{
4507a33d2f8SNiklas Keller    return random_int($min, $max);
451483b6238SMichael Hamann}
452483b6238SMichael Hamann
453483b6238SMichael Hamann/**
45404369c3eSMichael Hamann * Encrypt data using the given secret using AES
45504369c3eSMichael Hamann *
45604369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
45704369c3eSMichael Hamann * using pbkdf2.
45804369c3eSMichael Hamann *
45904369c3eSMichael Hamann * @param string $data The data that shall be encrypted
46004369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
46104369c3eSMichael Hamann * @return string The ciphertext
4624dc42f7fSGerrit Uitslag * @throws Exception
46304369c3eSMichael Hamann */
464d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
465d868eb89SAndreas Gohr{
46604369c3eSMichael Hamann    $iv     = auth_randombytes(16);
467927933f5SAndreas Gohr    $cipher = new AES('cbc');
46847e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
469927933f5SAndreas Gohr    $cipher->setIV($iv);
47004369c3eSMichael Hamann
4717b650cefSMichael Hamann    /*
4727b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4737b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4747b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4757b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4767b650cefSMichael Hamann    */
47704369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
47804369c3eSMichael Hamann}
47904369c3eSMichael Hamann
48004369c3eSMichael Hamann/**
48104369c3eSMichael Hamann * Decrypt the given AES ciphertext
48204369c3eSMichael Hamann *
48304369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
48404369c3eSMichael Hamann *
48504369c3eSMichael Hamann * @param string $ciphertext The encrypted data
48604369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
4871cedacf2SAndreas Gohr * @return string|null The decrypted data
48804369c3eSMichael Hamann */
489d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
490d868eb89SAndreas Gohr{
4917b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
492927933f5SAndreas Gohr    $cipher = new AES('cbc');
49347e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
4947b650cefSMichael Hamann    $cipher->setIV($iv);
49504369c3eSMichael Hamann
4961cedacf2SAndreas Gohr    try {
4977b650cefSMichael Hamann        return $cipher->decrypt(substr($ciphertext, 16));
4981cedacf2SAndreas Gohr    } catch (BadDecryptionException $e) {
4991cedacf2SAndreas Gohr        ErrorHandler::logException($e);
5001cedacf2SAndreas Gohr        return null;
5011cedacf2SAndreas Gohr    }
50204369c3eSMichael Hamann}
50304369c3eSMichael Hamann
50404369c3eSMichael Hamann/**
505883179a4SAndreas Gohr * Log out the current user
506883179a4SAndreas Gohr *
507f3f0262cSandi * This clears all authentication data and thus log the user
508883179a4SAndreas Gohr * off. It also clears session data.
50915fae107Sandi *
51015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
51142ea7f44SGerrit Uitslag *
512883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
513f3f0262cSandi */
514d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
515d868eb89SAndreas Gohr{
516f3f0262cSandi    global $conf;
517f3f0262cSandi    global $USERINFO;
518e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
5195298a619SAndreas Gohr    global $auth;
520585bf44eSChristopher Smith    /* @var Input $INPUT */
521585bf44eSChristopher Smith    global $INPUT;
52237065e65Sandi
523d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
524e9621d07SAndreas Gohr    @session_start();
525e9621d07SAndreas Gohr
526e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
527e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
528e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
529e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
530e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
531e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
532883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
533e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
534585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
535132bdbfeSandi    $USERINFO = null; //FIXME
536f5c6743cSAndreas Gohr
53773ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
538bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
539bf8392ebSAndreas Gohr        'expires' => time() - 600000,
540bf8392ebSAndreas Gohr        'path' => $cookieDir,
5419399c87eSsplitbrain        'secure' => ($conf['securecookie'] && Ip::isSsl()),
542bf8392ebSAndreas Gohr        'httponly' => true,
543486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
544bf8392ebSAndreas Gohr    ]);
5455298a619SAndreas Gohr
5466547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5476547cfc7SGerrit Uitslag        $auth->logOff();
5486547cfc7SGerrit Uitslag    }
549f3f0262cSandi}
550f3f0262cSandi
551f3f0262cSandi/**
552f8cc712eSAndreas Gohr * Check if a user is a manager
553f8cc712eSAndreas Gohr *
554f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
555f8cc712eSAndreas Gohr * user.
556f8cc712eSAndreas Gohr *
557f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
558f8cc712eSAndreas Gohr *
559ab5d26daSAndreas Gohr * @param string $user Username
560ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
561ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
56210396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
563ab5d26daSAndreas Gohr * @return bool
56496348f27SAndreas Gohr * @see    auth_isadmin
56596348f27SAndreas Gohr *
56696348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
567f8cc712eSAndreas Gohr */
568d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
569d868eb89SAndreas Gohr{
570f8cc712eSAndreas Gohr    global $conf;
571f8cc712eSAndreas Gohr    global $USERINFO;
572e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
573d752aedeSAndreas Gohr    global $auth;
574585bf44eSChristopher Smith    /* @var Input $INPUT */
575585bf44eSChristopher Smith    global $INPUT;
576585bf44eSChristopher Smith
577f8cc712eSAndreas Gohr
5786547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
579c66972f2SAdrian Lang    if (is_null($user)) {
580585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
581c66972f2SAdrian Lang            return false;
582c66972f2SAdrian Lang        } else {
583585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
584c66972f2SAdrian Lang        }
585c66972f2SAdrian Lang    }
586d6dc956fSAndreas Gohr    if (is_null($groups)) {
5871525c228SAnna Dabrowska        // checking the logged in user, or another one?
5881525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5891525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
59066b108d6SAnna Dabrowska        } else {
5916cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5926cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
59366b108d6SAnna Dabrowska        }
594e259aa79SAndreas Gohr    }
595e259aa79SAndreas Gohr
59696348f27SAndreas Gohr    // prefer cached result
59796348f27SAndreas Gohr    static $cache = [];
59810396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
59996348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
600d6dc956fSAndreas Gohr        // check superuser match
60196348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
60200ce12daSChris Smith
60396348f27SAndreas Gohr        // check managers
60496348f27SAndreas Gohr        if (!$ok && !$adminonly) {
60596348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
60696348f27SAndreas Gohr        }
60796348f27SAndreas Gohr
60896348f27SAndreas Gohr        $cache[$cachekey] = $ok;
60996348f27SAndreas Gohr    }
61096348f27SAndreas Gohr
61196348f27SAndreas Gohr    return $cache[$cachekey];
612f8cc712eSAndreas Gohr}
613f8cc712eSAndreas Gohr
614f8cc712eSAndreas Gohr/**
615f8cc712eSAndreas Gohr * Check if a user is admin
616f8cc712eSAndreas Gohr *
617f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
618f8cc712eSAndreas Gohr *
619f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
620f8cc712eSAndreas Gohr *
62196348f27SAndreas Gohr * @param string $user Username
62296348f27SAndreas Gohr * @param array $groups List of groups the user is in
62310396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
62496348f27SAndreas Gohr * @return bool
625f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
626ab5d26daSAndreas Gohr * @see auth_ismanager()
62742ea7f44SGerrit Uitslag *
628f8cc712eSAndreas Gohr */
629d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
630d868eb89SAndreas Gohr{
63196348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
632f8cc712eSAndreas Gohr}
633f8cc712eSAndreas Gohr
634d6dc956fSAndreas Gohr/**
635d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
636d6dc956fSAndreas Gohr * users and groups to determine membership status
637d6dc956fSAndreas Gohr *
638d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
639d6dc956fSAndreas Gohr *
64042ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
64142ea7f44SGerrit Uitslag * @param string $user       user to match against
64242ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6435446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
644d6dc956fSAndreas Gohr */
645d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
646d868eb89SAndreas Gohr{
647e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
648d6dc956fSAndreas Gohr    global $auth;
6496547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
650d6dc956fSAndreas Gohr
651d6dc956fSAndreas Gohr    // clean user and groups
6524f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
65324870174SAndreas Gohr        $user   = PhpString::strtolower($user);
65424870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
655d6dc956fSAndreas Gohr    }
656d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
65724870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
658d6dc956fSAndreas Gohr
659d6dc956fSAndreas Gohr    // extract the memberlist
660d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
661d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
662d6dc956fSAndreas Gohr    $members = array_unique($members);
663d6dc956fSAndreas Gohr    $members = array_filter($members);
664d6dc956fSAndreas Gohr
665d6dc956fSAndreas Gohr    // compare cleaned values
666d6dc956fSAndreas Gohr    foreach ($members as $member) {
667e5204a12SJurgen Hart        if ($member == '@ALL') return true;
66824870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
669d6dc956fSAndreas Gohr        if ($member[0] == '@') {
670d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
671d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
672d6dc956fSAndreas Gohr        } else {
673d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
674d6dc956fSAndreas Gohr            if ($member == $user) return true;
675d6dc956fSAndreas Gohr        }
676d6dc956fSAndreas Gohr    }
677d6dc956fSAndreas Gohr
678d6dc956fSAndreas Gohr    // still here? not a member!
679d6dc956fSAndreas Gohr    return false;
680d6dc956fSAndreas Gohr}
681d6dc956fSAndreas Gohr
682f8cc712eSAndreas Gohr/**
68315fae107Sandi * Convinience function for auth_aclcheck()
68415fae107Sandi *
68515fae107Sandi * This checks the permissions for the current user
68615fae107Sandi *
68715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
68815fae107Sandi *
6891698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
69015fae107Sandi * @return int          permission level
691f3f0262cSandi */
692d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
693d868eb89SAndreas Gohr{
694f3f0262cSandi    global $conf;
695f3f0262cSandi    global $USERINFO;
696585bf44eSChristopher Smith    /* @var Input $INPUT */
697585bf44eSChristopher Smith    global $INPUT;
698f3f0262cSandi    # if no ACL is used always return upload rights
699f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
70024870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
701f3f0262cSandi}
702f3f0262cSandi
703f3f0262cSandi/**
704c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
70515fae107Sandi *
70615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
70742ea7f44SGerrit Uitslag *
708c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
7091698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
71015fae107Sandi * @param  string       $user   Username
7113272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
71215fae107Sandi * @return int             permission level
713f3f0262cSandi */
714d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
715d868eb89SAndreas Gohr{
71624870174SAndreas Gohr    $data = [
717bf8f8509SAndreas Gohr        'id'     => $id ?? '',
718c17acc9fSAndreas Gohr        'user'   => $user,
719c17acc9fSAndreas Gohr        'groups' => $groups
72024870174SAndreas Gohr    ];
721c17acc9fSAndreas Gohr
722cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
723c17acc9fSAndreas Gohr}
724c17acc9fSAndreas Gohr
725c17acc9fSAndreas Gohr/**
726c17acc9fSAndreas Gohr * default ACL check method
727c17acc9fSAndreas Gohr *
728c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
729c17acc9fSAndreas Gohr *
730c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
73142ea7f44SGerrit Uitslag *
732c17acc9fSAndreas Gohr * @param  array $data event data
733c17acc9fSAndreas Gohr * @return int   permission level
734c17acc9fSAndreas Gohr */
735d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
736d868eb89SAndreas Gohr{
737c17acc9fSAndreas Gohr    $id     =& $data['id'];
738c17acc9fSAndreas Gohr    $user   =& $data['user'];
739c17acc9fSAndreas Gohr    $groups =& $data['groups'];
740c17acc9fSAndreas Gohr
741f3f0262cSandi    global $conf;
742f3f0262cSandi    global $AUTH_ACL;
743e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
744d752aedeSAndreas Gohr    global $auth;
745f3f0262cSandi
74685d03f68SAndreas Gohr    // if no ACL is used always return upload rights
747f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7486547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
749bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
750f3f0262cSandi
751074cf26bSandi    //make sure groups is an array
75224870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
753074cf26bSandi
75485d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
755ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
756ab5d26daSAndreas Gohr        return AUTH_ADMIN;
757ab5d26daSAndreas Gohr    }
75885d03f68SAndreas Gohr
759eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
76024870174SAndreas Gohr        $user   = PhpString::strtolower($user);
76124870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
762eb3ce0d5SKazutaka Miyasaka    }
76337ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
76424870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
76585d03f68SAndreas Gohr
7666c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
76737ff2261SSascha Klopp    foreach ($groups as &$group) {
76837ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
76910a76f6fSfrank    }
77010a76f6fSfrank
771f3f0262cSandi    $ns   = getNS($id);
772f3f0262cSandi    $perm = -1;
773f3f0262cSandi
774f3f0262cSandi    //add ALL group
775f3f0262cSandi    $groups[] = '@ALL';
77637ff2261SSascha Klopp
777f3f0262cSandi    //add User
77834aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
779f3f0262cSandi
780f3f0262cSandi    //check exact match first
78121c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
782f3f0262cSandi    if (count($matches)) {
783f3f0262cSandi        foreach ($matches as $match) {
784f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
78521c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
786eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
78724870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
788eb3ce0d5SKazutaka Miyasaka            }
78948d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
79048d7b7a6SDominik Eckelmann                continue;
79148d7b7a6SDominik Eckelmann            }
7928ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
793f3f0262cSandi            if ($acl[2] > $perm) {
794f3f0262cSandi                $perm = $acl[2];
795f3f0262cSandi            }
796f3f0262cSandi        }
797f3f0262cSandi        if ($perm > -1) {
798f3f0262cSandi            //we had a match - return it
799def492a2SGuillaume Turri            return (int) $perm;
800f3f0262cSandi        }
801f3f0262cSandi    }
802f3f0262cSandi
803f3f0262cSandi    //still here? do the namespace checks
804f3f0262cSandi    if ($ns) {
8053e304b55SMichael Hamann        $path = $ns . ':*';
806f3f0262cSandi    } else {
8073e304b55SMichael Hamann        $path = '*'; //root document
808f3f0262cSandi    }
809f3f0262cSandi
810f3f0262cSandi    do {
81121c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
812f3f0262cSandi        if (count($matches)) {
813f3f0262cSandi            foreach ($matches as $match) {
814f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
81521c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
816eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
81724870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
818eb3ce0d5SKazutaka Miyasaka                }
81948d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
82048d7b7a6SDominik Eckelmann                    continue;
82148d7b7a6SDominik Eckelmann                }
8228ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
823f3f0262cSandi                if ($acl[2] > $perm) {
824f3f0262cSandi                    $perm = $acl[2];
825f3f0262cSandi                }
826f3f0262cSandi            }
827f3f0262cSandi            //we had a match - return it
82848d7b7a6SDominik Eckelmann            if ($perm != -1) {
829def492a2SGuillaume Turri                return (int) $perm;
830f3f0262cSandi            }
83148d7b7a6SDominik Eckelmann        }
832f3f0262cSandi        //get next higher namespace
833f3f0262cSandi        $ns = getNS($ns);
834f3f0262cSandi
8353e304b55SMichael Hamann        if ($path != '*') {
8363e304b55SMichael Hamann            $path = $ns . ':*';
8373e304b55SMichael Hamann            if ($path == ':*') $path = '*';
838f3f0262cSandi        } else {
839f3f0262cSandi            //we did this already
840f3f0262cSandi            //looks like there is something wrong with the ACL
841f3f0262cSandi            //break here
842d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
843d5ce66f6SAndreas Gohr            return AUTH_NONE;
844f3f0262cSandi        }
845f3f0262cSandi    } while (1); //this should never loop endless
846ab5d26daSAndreas Gohr    return AUTH_NONE;
847f3f0262cSandi}
848f3f0262cSandi
849f3f0262cSandi/**
8506c2bb100SAndreas Gohr * Encode ASCII special chars
8516c2bb100SAndreas Gohr *
8526c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8536c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8546c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8556c2bb100SAndreas Gohr * urlencoding!).
8566c2bb100SAndreas Gohr *
8576c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8586c2bb100SAndreas Gohr *
8596c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8606c2bb100SAndreas Gohr * @see rawurldecode()
86142ea7f44SGerrit Uitslag *
86242ea7f44SGerrit Uitslag * @param string $name
86342ea7f44SGerrit Uitslag * @param bool $skip_group
86442ea7f44SGerrit Uitslag * @return string
8656c2bb100SAndreas Gohr */
866d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
867d868eb89SAndreas Gohr{
868a424cd8eSchris    global $cache_authname;
869a424cd8eSchris    $cache =& $cache_authname;
87031784267SAndreas Gohr    $name  = (string) $name;
871a424cd8eSchris
87280601d26SAndreas Gohr    // never encode wildcard FS#1955
87380601d26SAndreas Gohr    if ($name == '%USER%') return $name;
874b78bf706Sromain    if ($name == '%GROUP%') return $name;
87580601d26SAndreas Gohr
876a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8772401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
87830f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
87930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
880dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
881dccd6b2bSAndreas Gohr                substr($name, 1)
882ab5d26daSAndreas Gohr            );
883e838fc2eSAndreas Gohr        } else {
88430f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
88530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
886dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
887dccd6b2bSAndreas Gohr                $name
888ab5d26daSAndreas Gohr            );
889e838fc2eSAndreas Gohr        }
8906c2bb100SAndreas Gohr    }
8916c2bb100SAndreas Gohr
892a424cd8eSchris    return $cache[$name][$skip_group];
893a424cd8eSchris}
894a424cd8eSchris
89504d68ae4SGerrit Uitslag/**
89604d68ae4SGerrit Uitslag * callback encodes the matches
89704d68ae4SGerrit Uitslag *
89804d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
89904d68ae4SGerrit Uitslag * @return string
90004d68ae4SGerrit Uitslag */
901d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
902d868eb89SAndreas Gohr{
90330f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
90430f6faf0SChristopher Smith}
90530f6faf0SChristopher Smith
9066c2bb100SAndreas Gohr/**
907f3f0262cSandi * Create a pronouncable password
908f3f0262cSandi *
9098a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
9108a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
9118a285f7fSAndreas Gohr *
9124dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
9134dc42f7fSGerrit Uitslag * @return string  pronouncable password
9144dc42f7fSGerrit Uitslag * @throws Exception
9154dc42f7fSGerrit Uitslag *
91615fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
9178a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
91815fae107Sandi *
9194dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
920f3f0262cSandi */
921d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
922d868eb89SAndreas Gohr{
92324870174SAndreas Gohr    $data = [
924d628dcf3SAndreas Gohr        'password' => '',
925d628dcf3SAndreas Gohr        'foruser'  => $foruser
92624870174SAndreas Gohr    ];
9278a285f7fSAndreas Gohr
928e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
9298a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
930f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
931f3f0262cSandi        $v = 'aeiou'; //vowels
932f3f0262cSandi        $a = $c . $v; //both
933987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
934f3f0262cSandi
935987c8d26SAndreas Gohr        //use thre syllables...
936987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
937483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
938483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
939483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
940f3f0262cSandi        }
941987c8d26SAndreas Gohr        //... and add a nice number and special
94243f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9438a285f7fSAndreas Gohr    }
9448a285f7fSAndreas Gohr    $evt->advise_after();
945f3f0262cSandi
9468a285f7fSAndreas Gohr    return $data['password'];
947f3f0262cSandi}
948f3f0262cSandi
949f3f0262cSandi/**
950f3f0262cSandi * Sends a password to the given user
951f3f0262cSandi *
95215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
95342ea7f44SGerrit Uitslag *
954ab5d26daSAndreas Gohr * @param string $user Login name of the user
955ab5d26daSAndreas Gohr * @param string $password The new password in clear text
95615fae107Sandi * @return bool  true on success
957f3f0262cSandi */
958d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
959d868eb89SAndreas Gohr{
960f3f0262cSandi    global $lang;
961e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
962cd52f92dSchris    global $auth;
9636547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
964cd52f92dSchris
965d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9664dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
967f3f0262cSandi
96887ddda95Sandi    if (!$userinfo['mail']) return false;
969f3f0262cSandi
970f3f0262cSandi    $text = rawLocale('password');
97124870174SAndreas Gohr    $trep = [
972d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
973d7169d19SAndreas Gohr        'LOGIN'    => $user,
974d7169d19SAndreas Gohr        'PASSWORD' => $password
97524870174SAndreas Gohr    ];
976f3f0262cSandi
977d7169d19SAndreas Gohr    $mail = new Mailer();
978102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
979d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
980d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
981d7169d19SAndreas Gohr    return $mail->send();
982f3f0262cSandi}
983f3f0262cSandi
984f3f0262cSandi/**
98515fae107Sandi * Register a new user
986f3f0262cSandi *
98715fae107Sandi * This registers a new user - Data is read directly from $_POST
98815fae107Sandi *
98915fae107Sandi * @return bool  true on success, false on any error
9904dc42f7fSGerrit Uitslag * @throws Exception
9914dc42f7fSGerrit Uitslag *
9924dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
993f3f0262cSandi */
994d868eb89SAndreas Gohrfunction register()
995d868eb89SAndreas Gohr{
996f3f0262cSandi    global $lang;
997eb5d07e4Sjan    global $conf;
9984dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
999cd52f92dSchris    global $auth;
100064273335SAndreas Gohr    global $INPUT;
1001f3f0262cSandi
100264273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10033a48618aSAnika Henke    if (!actionOK('register')) return false;
1004640145a5Sandi
100564273335SAndreas Gohr    // gather input
100664273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
100764273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
100864273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
100964273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
101064273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
1011d752aedeSAndreas Gohr
101264273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
1013f3f0262cSandi        msg($lang['regmissing'], -1);
1014f3f0262cSandi        return false;
1015f3f0262cSandi    }
1016f3f0262cSandi
1017cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
10188a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
101964273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
1020bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
1021cab2716aSmatthias.grimm        return false;
102264273335SAndreas Gohr    } elseif ($pass != $passchk) {
1023bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
1024cab2716aSmatthias.grimm        return false;
1025cab2716aSmatthias.grimm    }
1026cab2716aSmatthias.grimm
1027f3f0262cSandi    //check mail
102864273335SAndreas Gohr    if (!mail_isvalid($email)) {
1029f3f0262cSandi        msg($lang['regbadmail'], -1);
1030f3f0262cSandi        return false;
1031f3f0262cSandi    }
1032f3f0262cSandi
1033f3f0262cSandi    //okay try to create the user
103424870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1035db9faf02SPatrick Brown        msg($lang['regfail'], -1);
1036f3f0262cSandi        return false;
1037f3f0262cSandi    }
1038f3f0262cSandi
1039790b7720SAndreas Gohr    // send notification about the new user
104075d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
104175d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
104202a498e7Schris
1043790b7720SAndreas Gohr    // are we done?
1044cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1045cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1046cab2716aSmatthias.grimm        return true;
1047cab2716aSmatthias.grimm    }
1048cab2716aSmatthias.grimm
1049790b7720SAndreas Gohr    // autogenerated password? then send password to user
105064273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1051f3f0262cSandi        msg($lang['regsuccess'], 1);
1052f3f0262cSandi        return true;
1053f3f0262cSandi    } else {
1054f3f0262cSandi        msg($lang['regmailfail'], -1);
1055f3f0262cSandi        return false;
1056f3f0262cSandi    }
1057f3f0262cSandi}
1058f3f0262cSandi
105910a76f6fSfrank/**
10608b06d178Schris * Update user profile
10618b06d178Schris *
10624dc42f7fSGerrit Uitslag * @throws Exception
10634dc42f7fSGerrit Uitslag *
10648b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10658b06d178Schris */
1066d868eb89SAndreas Gohrfunction updateprofile()
1067d868eb89SAndreas Gohr{
10688b06d178Schris    global $conf;
10698b06d178Schris    global $lang;
1070e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1071cd52f92dSchris    global $auth;
1072bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1073bcc94b2cSAndreas Gohr    global $INPUT;
10748b06d178Schris
1075bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10761b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10778b06d178Schris
10783a48618aSAnika Henke    if (!actionOK('profile')) {
10798b06d178Schris        msg($lang['profna'], -1);
10808b06d178Schris        return false;
10818b06d178Schris    }
10828b06d178Schris
108324870174SAndreas Gohr    $changes         = [];
1084bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1085bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1086bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1087bcc94b2cSAndreas Gohr
1088bcc94b2cSAndreas Gohr    // check misspelled passwords
1089bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1090bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10918b06d178Schris        return false;
10928b06d178Schris    }
10938b06d178Schris
10948b06d178Schris    // clean fullname and email
1095bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1096bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10978b06d178Schris
1098bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
10997d34963bSAndreas Gohr    if (
11007d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1101bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1102ab5d26daSAndreas Gohr    ) {
11038b06d178Schris        msg($lang['profnoempty'], -1);
11048b06d178Schris        return false;
11058b06d178Schris    }
1106bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
11078b06d178Schris        msg($lang['regbadmail'], -1);
11088b06d178Schris        return false;
11098b06d178Schris    }
11108b06d178Schris
1111bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
11124c21b7eeSAndreas Gohr
1113bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1114bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1115bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1116bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1117bcc94b2cSAndreas Gohr
1118bcc94b2cSAndreas Gohr    // anything to do?
111924870174SAndreas Gohr    if ($changes === []) {
11208b06d178Schris        msg($lang['profnochange'], -1);
11218b06d178Schris        return false;
11228b06d178Schris    }
11238b06d178Schris
11248b06d178Schris    if ($conf['profileconfirm']) {
1125585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
112671422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
11278b06d178Schris            return false;
11288b06d178Schris        }
11298b06d178Schris    }
11308b06d178Schris
113124870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1132db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1133db9faf02SPatrick Brown        return false;
1134db9faf02SPatrick Brown    }
1135db9faf02SPatrick Brown
113667efd1edSPieter Hollants    if (array_key_exists('pass', $changes) && $changes['pass']) {
1137c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1138a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
113904369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1140585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1141c276e9e8SMarcel Pennewiss    } else {
1142c276e9e8SMarcel Pennewiss        // make sure the session is writable
1143c276e9e8SMarcel Pennewiss        @session_start();
1144c276e9e8SMarcel Pennewiss        // invalidate session cache
1145c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1146c276e9e8SMarcel Pennewiss        session_write_close();
114732ed2b36SAndreas Gohr    }
1148c276e9e8SMarcel Pennewiss
114925b2a98cSMichael Klier    return true;
1150a0b5b007SChris Smith}
1151ab5d26daSAndreas Gohr
115204d68ae4SGerrit Uitslag/**
115304d68ae4SGerrit Uitslag * Delete the current logged-in user
115404d68ae4SGerrit Uitslag *
115504d68ae4SGerrit Uitslag * @return bool true on success, false on any error
115604d68ae4SGerrit Uitslag */
1157d868eb89SAndreas Gohrfunction auth_deleteprofile()
1158d868eb89SAndreas Gohr{
11592a7abf2dSChristopher Smith    global $conf;
11602a7abf2dSChristopher Smith    global $lang;
11614dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11622a7abf2dSChristopher Smith    global $auth;
11632a7abf2dSChristopher Smith    /* @var Input $INPUT */
11642a7abf2dSChristopher Smith    global $INPUT;
11652a7abf2dSChristopher Smith
11662a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11672a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11682a7abf2dSChristopher Smith
11692a7abf2dSChristopher Smith    // action prevented or auth module disallows
11702a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11712a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11722a7abf2dSChristopher Smith        return false;
11732a7abf2dSChristopher Smith    }
11742a7abf2dSChristopher Smith
11752a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11762a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11772a7abf2dSChristopher Smith        return false;
11782a7abf2dSChristopher Smith    }
11792a7abf2dSChristopher Smith
11802a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1181585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11822a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11832a7abf2dSChristopher Smith            return false;
11842a7abf2dSChristopher Smith        }
11852a7abf2dSChristopher Smith    }
11862a7abf2dSChristopher Smith
118724870174SAndreas Gohr    $deleted = [];
1188585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
118924870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
11902a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11912a7abf2dSChristopher Smith        auth_logoff();
11922a7abf2dSChristopher Smith        return true;
11932a7abf2dSChristopher Smith    }
11942a7abf2dSChristopher Smith
11952a7abf2dSChristopher Smith    return false;
11962a7abf2dSChristopher Smith}
11972a7abf2dSChristopher Smith
11988b06d178Schris/**
11998b06d178Schris * Send a  new password
12008b06d178Schris *
12011d5856cfSAndreas Gohr * This function handles both phases of the password reset:
12021d5856cfSAndreas Gohr *
12031d5856cfSAndreas Gohr *   - handling the first request of password reset
12041d5856cfSAndreas Gohr *   - validating the password reset auth token
12051d5856cfSAndreas Gohr *
12064dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
12074dc42f7fSGerrit Uitslag * @throws Exception
12084dc42f7fSGerrit Uitslag *
12094dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
12108b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
12118b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
12128b06d178Schris */
1213d868eb89SAndreas Gohrfunction act_resendpwd()
1214d868eb89SAndreas Gohr{
12158b06d178Schris    global $lang;
12168b06d178Schris    global $conf;
1217e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1218cd52f92dSchris    global $auth;
1219bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1220bcc94b2cSAndreas Gohr    global $INPUT;
12218b06d178Schris
12223a48618aSAnika Henke    if (!actionOK('resendpwd')) {
12238b06d178Schris        msg($lang['resendna'], -1);
12248b06d178Schris        return false;
12258b06d178Schris    }
12268b06d178Schris
1227bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
12288b06d178Schris
12291d5856cfSAndreas Gohr    if ($token) {
1230cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
12311d5856cfSAndreas Gohr
12322401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
123379e79377SAndreas Gohr        if (!file_exists($tfile)) {
12341d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1235bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12361d5856cfSAndreas Gohr            return false;
12371d5856cfSAndreas Gohr        }
12388a9735e3SAndreas Gohr        // token is only valid for 3 days
12398a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12408a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1241bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12421d5856cfSAndreas Gohr            @unlink($tfile);
12438a9735e3SAndreas Gohr            return false;
12448a9735e3SAndreas Gohr        }
12458a9735e3SAndreas Gohr
12468b06d178Schris        $user     = io_readfile($tfile);
12474dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12488b06d178Schris        if (!$userinfo['mail']) {
12498b06d178Schris            msg($lang['resendpwdnouser'], -1);
12508b06d178Schris            return false;
12518b06d178Schris        }
12528b06d178Schris
1253cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1254bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1255bcc94b2cSAndreas Gohr
1256cc204bbdSAndreas Gohr            // password given correctly?
1257bcc94b2cSAndreas Gohr            if (!$pass) return false;
1258bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1259451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1260cc204bbdSAndreas Gohr                return false;
1261cc204bbdSAndreas Gohr            }
1262cc204bbdSAndreas Gohr
1263bcc94b2cSAndreas Gohr            // change it
126424870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1265db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1266cc204bbdSAndreas Gohr                return false;
1267cc204bbdSAndreas Gohr            }
1268cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12698a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
127024870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1271db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12728b06d178Schris                return false;
12738b06d178Schris            }
12748b06d178Schris
12758b06d178Schris            if (auth_sendPassword($user, $pass)) {
12768b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12778b06d178Schris            } else {
12788b06d178Schris                msg($lang['regmailfail'], -1);
12798b06d178Schris            }
1280cc204bbdSAndreas Gohr        }
1281cc204bbdSAndreas Gohr
1282cc204bbdSAndreas Gohr        @unlink($tfile);
12838b06d178Schris        return true;
12841d5856cfSAndreas Gohr    } else {
12851d5856cfSAndreas Gohr        // we're in request phase
12861d5856cfSAndreas Gohr
1287bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
12881d5856cfSAndreas Gohr
1289bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
12901d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12911d5856cfSAndreas Gohr            return false;
12921d5856cfSAndreas Gohr        } else {
1293bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12941d5856cfSAndreas Gohr        }
12951d5856cfSAndreas Gohr
12964dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12971d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
12981d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12991d5856cfSAndreas Gohr            return false;
13001d5856cfSAndreas Gohr        }
13011d5856cfSAndreas Gohr
13021d5856cfSAndreas Gohr        // generate auth token
1303483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
13042401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
130524870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
13061d5856cfSAndreas Gohr
13071d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
13081d5856cfSAndreas Gohr
13091d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
131024870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
13111d5856cfSAndreas Gohr
1312d7169d19SAndreas Gohr        $mail = new Mailer();
1313d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1314d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1315d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1316d7169d19SAndreas Gohr        if ($mail->send()) {
13171d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
13181d5856cfSAndreas Gohr        } else {
13191d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
13201d5856cfSAndreas Gohr        }
13211d5856cfSAndreas Gohr        return true;
13221d5856cfSAndreas Gohr    }
1323ab5d26daSAndreas Gohr    // never reached
13248b06d178Schris}
13258b06d178Schris
13268b06d178Schris/**
1327b0855b11Sandi * Encrypts a password using the given method and salt
1328b0855b11Sandi *
1329b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1330b0855b11Sandi * is chosen.
1331b0855b11Sandi *
13320ffe9fdaSTobias Bengfort * You can pass null as the password to create an unusable hash.
13330ffe9fdaSTobias Bengfort *
1334b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
133542ea7f44SGerrit Uitslag *
1336ab5d26daSAndreas Gohr * @param string $clear The clear text password
1337ab5d26daSAndreas Gohr * @param string $method The hashing method
1338ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1339b0855b11Sandi * @return  string  The crypted password
1340b0855b11Sandi */
1341d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1342d868eb89SAndreas Gohr{
1343b0855b11Sandi    global $conf;
1344527ad715STobias Bengfort
1345527ad715STobias Bengfort    if ($clear === null) {
1346b21b7935STobias Bengfort        return DOKU_UNUSABLE_PASSWORD;
1347527ad715STobias Bengfort    }
1348527ad715STobias Bengfort
1349b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
135010a76f6fSfrank
13513a0a2d05SAndreas Gohr    $pass = new PassHash();
13523a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1353b0855b11Sandi
13543a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1355b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13563a0a2d05SAndreas Gohr        return false;
1357b0855b11Sandi    }
13583a0a2d05SAndreas Gohr
13593a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1360b0855b11Sandi}
1361b0855b11Sandi
1362b0855b11Sandi/**
1363b0855b11Sandi * Verifies a cleartext password against a crypted hash
1364b0855b11Sandi *
1365ab5d26daSAndreas Gohr * @param string $clear The clear text password
1366ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1367ab5d26daSAndreas Gohr * @return bool true if both match
13684dc42f7fSGerrit Uitslag * @throws Exception
13694dc42f7fSGerrit Uitslag *
13704dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1371b0855b11Sandi */
1372d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1373d868eb89SAndreas Gohr{
1374b21b7935STobias Bengfort    if ($crypt === DOKU_UNUSABLE_PASSWORD) {
1375527ad715STobias Bengfort        return false;
1376527ad715STobias Bengfort    }
1377527ad715STobias Bengfort
13783a0a2d05SAndreas Gohr    $pass = new PassHash();
13793a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1380b0855b11Sandi}
1381340756e4Sandi
1382a0b5b007SChris Smith/**
1383a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1384a0b5b007SChris Smith *
1385a0b5b007SChris Smith * @param string  $user       username
1386a0b5b007SChris Smith * @param string  $pass       encrypted password
1387a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1388ab5d26daSAndreas Gohr * @return bool
1389a0b5b007SChris Smith */
1390d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1391d868eb89SAndreas Gohr{
1392a0b5b007SChris Smith    global $conf;
1393e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1394a0b5b007SChris Smith    global $auth;
139579d00841SOliver Geisen    global $USERINFO;
1396a0b5b007SChris Smith
13976547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1398a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1399a0b5b007SChris Smith
1400a0b5b007SChris Smith    // set cookie
1401645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
140273ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1403c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1404bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1405bf8392ebSAndreas Gohr        'expires' => $time,
1406bf8392ebSAndreas Gohr        'path' => $cookieDir,
14079399c87eSsplitbrain        'secure' => ($conf['securecookie'] && Ip::isSsl()),
1408bf8392ebSAndreas Gohr        'httponly' => true,
1409486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1410bf8392ebSAndreas Gohr    ]);
141155a71a16SGerrit Uitslag
1412a0b5b007SChris Smith    // set session
1413a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1414234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1415a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1416a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1417a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1418ab5d26daSAndreas Gohr
1419ab5d26daSAndreas Gohr    return true;
1420a0b5b007SChris Smith}
1421a0b5b007SChris Smith
1422645c0a36SAndreas Gohr/**
1423645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1424645c0a36SAndreas Gohr *
1425645c0a36SAndreas Gohr * @returns array
1426645c0a36SAndreas Gohr */
1427d868eb89SAndreas Gohrfunction auth_getCookie()
1428d868eb89SAndreas Gohr{
1429c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
143024870174SAndreas Gohr        return [null, null, null];
1431c66972f2SAdrian Lang    }
143224870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1433645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1434645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1435645c0a36SAndreas Gohr    $user   = base64_decode($user);
143624870174SAndreas Gohr    return [$user, $sticky, $pass];
1437645c0a36SAndreas Gohr}
1438645c0a36SAndreas Gohr
1439e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1440