xref: /dokuwiki/inc/auth.php (revision 7e687fd85a40bd8453b39b64bae8e989ab32fd36)
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) {
207093fe67eSAndreas Gohr            if (str_starts_with($key, '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;
2449cdd189dSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
245455aa67eSAndreas Gohr
246455aa67eSAndreas Gohr    return true;
247455aa67eSAndreas Gohr}
248455aa67eSAndreas Gohr
249455aa67eSAndreas Gohr/**
250ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
251ab5d26daSAndreas Gohr *
25242ea7f44SGerrit Uitslag * @param array $evdata
253ab5d26daSAndreas Gohr * @return bool
2544dc42f7fSGerrit Uitslag * @throws Exception
255ab5d26daSAndreas Gohr */
256d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
257d868eb89SAndreas Gohr{
258ab5d26daSAndreas Gohr    return auth_login(
259ab5d26daSAndreas Gohr        $evdata['user'],
260b5ee21aaSAdrian Lang        $evdata['password'],
261b5ee21aaSAdrian Lang        $evdata['sticky'],
262ab5d26daSAndreas Gohr        $evdata['silent']
263ab5d26daSAndreas Gohr    );
264b5ee21aaSAdrian Lang}
265b5ee21aaSAdrian Lang
266f3f0262cSandi/**
267f3f0262cSandi * This tries to login the user based on the sent auth credentials
268f3f0262cSandi *
269f3f0262cSandi * The authentication works like this: if a username was given
27015fae107Sandi * a new login is assumed and user/password are checked. If they
27115fae107Sandi * are correct the password is encrypted with blowfish and stored
27215fae107Sandi * together with the username in a cookie - the same info is stored
27315fae107Sandi * in the session, too. Additonally a browserID is stored in the
27415fae107Sandi * session.
27515fae107Sandi *
27615fae107Sandi * If no username was given the cookie is checked: if the username,
27715fae107Sandi * crypted password and browserID match between session and cookie
27815fae107Sandi * no further testing is done and the user is accepted
27915fae107Sandi *
28015fae107Sandi * If a cookie was found but no session info was availabe the
281136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
28215fae107Sandi * together with username rechecked by calling this function again.
283f3f0262cSandi *
284f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
285f3f0262cSandi * are set.
28615fae107Sandi *
28715fae107Sandi * @param string $user Username
28815fae107Sandi * @param string $pass Cleartext Password
28915fae107Sandi * @param bool $sticky Cookie should not expire
290f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
29115fae107Sandi * @return bool true on successful auth
2924dc42f7fSGerrit Uitslag * @throws Exception
2934dc42f7fSGerrit Uitslag *
2944dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
295f3f0262cSandi */
296d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
297d868eb89SAndreas Gohr{
298f3f0262cSandi    global $USERINFO;
299f3f0262cSandi    global $conf;
300f3f0262cSandi    global $lang;
301e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
302cd52f92dSchris    global $auth;
303585bf44eSChristopher Smith    /* @var Input $INPUT */
304585bf44eSChristopher Smith    global $INPUT;
305ab5d26daSAndreas Gohr
3066547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
307beca106aSAdrian Lang
308bbbd6568SAndreas Gohr    if (!empty($user)) {
309132bdbfeSandi        //usual login
310f7f6f5fcSsplitbrain        if (!empty($pass)) usleep(random_int(0, 250)); // add a random delay to prevent timing attacks #4491
3115e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
312132bdbfeSandi            // make logininfo globally available
313585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
31430d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
31504369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
316132bdbfeSandi            return true;
317f3f0262cSandi        } else {
318f3f0262cSandi            //invalid credentials - log off
319f8b1e4e7SAndreas Gohr            if (!$silent) {
320f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
321f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
322f8b1e4e7SAndreas Gohr            }
323f3f0262cSandi            auth_logoff();
324132bdbfeSandi            return false;
325f3f0262cSandi        }
326f3f0262cSandi    } else {
327132bdbfeSandi        // read cookie information
32824870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
329132bdbfeSandi        if ($user && $pass) {
330132bdbfeSandi            // we got a cookie - see if we can trust it
331fa7c70ffSAdrian Lang
332fa7c70ffSAdrian Lang            // get session info
3330058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
334bc6b1759SAndreas Gohr                $session = $_SESSION[DOKU_COOKIE]['auth'] ?? [];
3357d34963bSAndreas Gohr                if (
3369d1b6472SEduardo Mozart de Oliveira                    isset($session['user']) &&
3379d1b6472SEduardo Mozart de Oliveira                    isset($session['pass']) &&
3387172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3394c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
340e4b0c5a0SAndreas Gohr                    ($session['user'] === $user) &&
341e4b0c5a0SAndreas Gohr                    ($session['pass'] === sha1($pass)) && //still crypted
342e4b0c5a0SAndreas Gohr                    ($session['buid'] === auth_browseruid())
343ab5d26daSAndreas Gohr                ) {
344132bdbfeSandi                    // he has session, cookie and browser right - let him in
345585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
346132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
347132bdbfeSandi                    return true;
348132bdbfeSandi                }
3490058ae75SDamien Regad            }
350f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
35130d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
35204369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
353f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
354132bdbfeSandi        }
355132bdbfeSandi    }
356f3f0262cSandi    //just to be sure
357883179a4SAndreas Gohr    auth_logoff(true);
358132bdbfeSandi    return false;
359f3f0262cSandi}
360132bdbfeSandi
361132bdbfeSandi/**
362136ce040Sandi * Builds a pseudo UID from browser and IP data
363132bdbfeSandi *
364132bdbfeSandi * This is neither unique nor unfakable - still it adds some
365136ce040Sandi * security. Using the first part of the IP makes sure
36680b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
36715fae107Sandi *
36815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
36915fae107Sandi *
370b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
371132bdbfeSandi */
372d868eb89SAndreas Gohrfunction auth_browseruid()
373d868eb89SAndreas Gohr{
374585bf44eSChristopher Smith    /* @var Input $INPUT */
375585bf44eSChristopher Smith    global $INPUT;
376585bf44eSChristopher Smith
3772f9daf16SAndreas Gohr    $ip = clientIP(true);
378b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
379b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
380b7c67f83SAndreas Gohr
381b7c67f83SAndreas Gohr    $uid = implode("\n", [
382b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
383b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
384b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
385b7c67f83SAndreas Gohr    ]);
386b13c0e1aSAdaKaleh    return hash('sha256', $uid);
387132bdbfeSandi}
388132bdbfeSandi
389132bdbfeSandi/**
390132bdbfeSandi * Creates a random key to encrypt the password in cookies
39115fae107Sandi *
39215fae107Sandi * This function tries to read the password for encrypting
39398407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
39415fae107Sandi * if no such file is found a random key is created and
39515fae107Sandi * and stored in this file.
39615fae107Sandi *
39732ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
39830d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
39915fae107Sandi * @return  string
4004dc42f7fSGerrit Uitslag * @throws Exception
4014dc42f7fSGerrit Uitslag *
4024dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
403132bdbfeSandi */
404d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
405d868eb89SAndreas Gohr{
406a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
407fe745becSMichael Große        return 'test';
408a1fe3c9cSMichael Große    }
409132bdbfeSandi    global $conf;
41098407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
41130d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
41230d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
41330d544a4SMichael Hamann    }
414132bdbfeSandi    $salt = io_readFile($file);
415132bdbfeSandi    if (empty($salt)) {
41630d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
417132bdbfeSandi        io_saveFile($file, $salt);
418132bdbfeSandi    }
41932ed2b36SAndreas Gohr    if ($addsession) {
42032ed2b36SAndreas Gohr        $salt .= session_id();
42132ed2b36SAndreas Gohr    }
422132bdbfeSandi    return $salt;
423f3f0262cSandi}
424f3f0262cSandi
425f3f0262cSandi/**
4267a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
427483b6238SMichael Hamann *
4287a33d2f8SNiklas Keller * @param int $length number of bytes
4297a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
4304dc42f7fSGerrit Uitslag * @throws Exception
4314dc42f7fSGerrit Uitslag *
4324dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
433483b6238SMichael Hamann */
434d868eb89SAndreas Gohrfunction auth_randombytes($length)
435d868eb89SAndreas Gohr{
4367a33d2f8SNiklas Keller    return random_bytes($length);
437483b6238SMichael Hamann}
438483b6238SMichael Hamann
439483b6238SMichael Hamann/**
4407a33d2f8SNiklas Keller * Cryptographically secure random number generator.
441483b6238SMichael Hamann *
442483b6238SMichael Hamann * @param int $min
443483b6238SMichael Hamann * @param int $max
444483b6238SMichael Hamann * @return int
4454dc42f7fSGerrit Uitslag * @throws Exception
4464dc42f7fSGerrit Uitslag *
4474dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
448483b6238SMichael Hamann */
449d868eb89SAndreas Gohrfunction auth_random($min, $max)
450d868eb89SAndreas Gohr{
4517a33d2f8SNiklas Keller    return random_int($min, $max);
452483b6238SMichael Hamann}
453483b6238SMichael Hamann
454483b6238SMichael Hamann/**
45504369c3eSMichael Hamann * Encrypt data using the given secret using AES
45604369c3eSMichael Hamann *
45704369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
45804369c3eSMichael Hamann * using pbkdf2.
45904369c3eSMichael Hamann *
46004369c3eSMichael Hamann * @param string $data The data that shall be encrypted
46104369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
46204369c3eSMichael Hamann * @return string The ciphertext
4634dc42f7fSGerrit Uitslag * @throws Exception
46404369c3eSMichael Hamann */
465d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
466d868eb89SAndreas Gohr{
46704369c3eSMichael Hamann    $iv     = auth_randombytes(16);
468927933f5SAndreas Gohr    $cipher = new AES('cbc');
46947e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
470927933f5SAndreas Gohr    $cipher->setIV($iv);
47104369c3eSMichael Hamann
4727b650cefSMichael Hamann    /*
4737b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4747b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4757b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4767b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4777b650cefSMichael Hamann    */
47804369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
47904369c3eSMichael Hamann}
48004369c3eSMichael Hamann
48104369c3eSMichael Hamann/**
48204369c3eSMichael Hamann * Decrypt the given AES ciphertext
48304369c3eSMichael Hamann *
48404369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
48504369c3eSMichael Hamann *
48604369c3eSMichael Hamann * @param string $ciphertext The encrypted data
48704369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
4881cedacf2SAndreas Gohr * @return string|null The decrypted data
48904369c3eSMichael Hamann */
490d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
491d868eb89SAndreas Gohr{
4927b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
493927933f5SAndreas Gohr    $cipher = new AES('cbc');
49447e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
4957b650cefSMichael Hamann    $cipher->setIV($iv);
49604369c3eSMichael Hamann
4971cedacf2SAndreas Gohr    try {
4987b650cefSMichael Hamann        return $cipher->decrypt(substr($ciphertext, 16));
4991cedacf2SAndreas Gohr    } catch (BadDecryptionException $e) {
5001cedacf2SAndreas Gohr        ErrorHandler::logException($e);
5011cedacf2SAndreas Gohr        return null;
5021cedacf2SAndreas Gohr    }
50304369c3eSMichael Hamann}
50404369c3eSMichael Hamann
50504369c3eSMichael Hamann/**
506883179a4SAndreas Gohr * Log out the current user
507883179a4SAndreas Gohr *
508f3f0262cSandi * This clears all authentication data and thus log the user
509883179a4SAndreas Gohr * off. It also clears session data.
51015fae107Sandi *
51115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
51242ea7f44SGerrit Uitslag *
513883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
514f3f0262cSandi */
515d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
516d868eb89SAndreas Gohr{
517f3f0262cSandi    global $conf;
518f3f0262cSandi    global $USERINFO;
519e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
5205298a619SAndreas Gohr    global $auth;
521585bf44eSChristopher Smith    /* @var Input $INPUT */
522585bf44eSChristopher Smith    global $INPUT;
52337065e65Sandi
524d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
525e9621d07SAndreas Gohr    @session_start();
526e9621d07SAndreas Gohr
527e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
528e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
529e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
530e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
531e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
532e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
533883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
534e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
535585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
536132bdbfeSandi    $USERINFO = null; //FIXME
537f5c6743cSAndreas Gohr
53873ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
539bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
540bf8392ebSAndreas Gohr        'expires' => time() - 600000,
541bf8392ebSAndreas Gohr        'path' => $cookieDir,
5429399c87eSsplitbrain        'secure' => ($conf['securecookie'] && Ip::isSsl()),
543bf8392ebSAndreas Gohr        'httponly' => true,
544486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
545bf8392ebSAndreas Gohr    ]);
5465298a619SAndreas Gohr
5476547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5486547cfc7SGerrit Uitslag        $auth->logOff();
5496547cfc7SGerrit Uitslag    }
550f3f0262cSandi}
551f3f0262cSandi
552f3f0262cSandi/**
553f8cc712eSAndreas Gohr * Check if a user is a manager
554f8cc712eSAndreas Gohr *
555f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
556f8cc712eSAndreas Gohr * user.
557f8cc712eSAndreas Gohr *
558f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
559f8cc712eSAndreas Gohr *
560ab5d26daSAndreas Gohr * @param string $user Username
561ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
562ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
56310396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
564ab5d26daSAndreas Gohr * @return bool
56596348f27SAndreas Gohr * @see    auth_isadmin
56696348f27SAndreas Gohr *
56796348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
568f8cc712eSAndreas Gohr */
569d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
570d868eb89SAndreas Gohr{
571f8cc712eSAndreas Gohr    global $conf;
572f8cc712eSAndreas Gohr    global $USERINFO;
573e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
574d752aedeSAndreas Gohr    global $auth;
575585bf44eSChristopher Smith    /* @var Input $INPUT */
576585bf44eSChristopher Smith    global $INPUT;
577585bf44eSChristopher Smith
578f8cc712eSAndreas Gohr
5796547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
580c66972f2SAdrian Lang    if (is_null($user)) {
581585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
582c66972f2SAdrian Lang            return false;
583c66972f2SAdrian Lang        } else {
584585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
585c66972f2SAdrian Lang        }
586c66972f2SAdrian Lang    }
587d6dc956fSAndreas Gohr    if (is_null($groups)) {
5881525c228SAnna Dabrowska        // checking the logged in user, or another one?
5891525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5901525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
59166b108d6SAnna Dabrowska        } else {
5926cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5936cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
59466b108d6SAnna Dabrowska        }
595e259aa79SAndreas Gohr    }
596e259aa79SAndreas Gohr
59796348f27SAndreas Gohr    // prefer cached result
59896348f27SAndreas Gohr    static $cache = [];
59910396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
60096348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
601d6dc956fSAndreas Gohr        // check superuser match
60296348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
60300ce12daSChris Smith
60496348f27SAndreas Gohr        // check managers
60596348f27SAndreas Gohr        if (!$ok && !$adminonly) {
60696348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
60796348f27SAndreas Gohr        }
60896348f27SAndreas Gohr
60996348f27SAndreas Gohr        $cache[$cachekey] = $ok;
61096348f27SAndreas Gohr    }
61196348f27SAndreas Gohr
61296348f27SAndreas Gohr    return $cache[$cachekey];
613f8cc712eSAndreas Gohr}
614f8cc712eSAndreas Gohr
615f8cc712eSAndreas Gohr/**
616f8cc712eSAndreas Gohr * Check if a user is admin
617f8cc712eSAndreas Gohr *
618f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
619f8cc712eSAndreas Gohr *
620f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
621f8cc712eSAndreas Gohr *
62296348f27SAndreas Gohr * @param string $user Username
62396348f27SAndreas Gohr * @param array $groups List of groups the user is in
62410396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
62596348f27SAndreas Gohr * @return bool
626f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
627ab5d26daSAndreas Gohr * @see auth_ismanager()
62842ea7f44SGerrit Uitslag *
629f8cc712eSAndreas Gohr */
630d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
631d868eb89SAndreas Gohr{
63296348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
633f8cc712eSAndreas Gohr}
634f8cc712eSAndreas Gohr
635d6dc956fSAndreas Gohr/**
636d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
637d6dc956fSAndreas Gohr * users and groups to determine membership status
638d6dc956fSAndreas Gohr *
639d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
640d6dc956fSAndreas Gohr *
64142ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
64242ea7f44SGerrit Uitslag * @param string $user       user to match against
64342ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6445446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
645d6dc956fSAndreas Gohr */
646d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
647d868eb89SAndreas Gohr{
648e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
649d6dc956fSAndreas Gohr    global $auth;
6506547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
651d6dc956fSAndreas Gohr
652d6dc956fSAndreas Gohr    // clean user and groups
6534f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
65424870174SAndreas Gohr        $user   = PhpString::strtolower($user);
655093fe67eSAndreas Gohr        $groups = array_map(PhpString::strtolower(...), $groups);
656d6dc956fSAndreas Gohr    }
657d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
658093fe67eSAndreas Gohr    $groups = array_map($auth->cleanGroup(...), $groups);
659d6dc956fSAndreas Gohr
660d6dc956fSAndreas Gohr    // extract the memberlist
661d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
662093fe67eSAndreas Gohr    $members = array_map(trim(...), $members);
663d6dc956fSAndreas Gohr    $members = array_unique($members);
664d6dc956fSAndreas Gohr    $members = array_filter($members);
665d6dc956fSAndreas Gohr
666d6dc956fSAndreas Gohr    // compare cleaned values
667d6dc956fSAndreas Gohr    foreach ($members as $member) {
668e5204a12SJurgen Hart        if ($member == '@ALL') return true;
66924870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
670d6dc956fSAndreas Gohr        if ($member[0] == '@') {
671d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
672d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
673d6dc956fSAndreas Gohr        } else {
674d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
675d6dc956fSAndreas Gohr            if ($member == $user) return true;
676d6dc956fSAndreas Gohr        }
677d6dc956fSAndreas Gohr    }
678d6dc956fSAndreas Gohr
679d6dc956fSAndreas Gohr    // still here? not a member!
680d6dc956fSAndreas Gohr    return false;
681d6dc956fSAndreas Gohr}
682d6dc956fSAndreas Gohr
683f8cc712eSAndreas Gohr/**
68415fae107Sandi * Convinience function for auth_aclcheck()
68515fae107Sandi *
68615fae107Sandi * This checks the permissions for the current user
68715fae107Sandi *
68815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
68915fae107Sandi *
6901698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
69115fae107Sandi * @return int          permission level
692f3f0262cSandi */
693d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
694d868eb89SAndreas Gohr{
695f3f0262cSandi    global $conf;
696f3f0262cSandi    global $USERINFO;
697585bf44eSChristopher Smith    /* @var Input $INPUT */
698585bf44eSChristopher Smith    global $INPUT;
699f3f0262cSandi    # if no ACL is used always return upload rights
700f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
70124870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
702f3f0262cSandi}
703f3f0262cSandi
704f3f0262cSandi/**
705*7e687fd8SAndreas Gohr * Build the ACL path for a media file.
706*7e687fd8SAndreas Gohr *
707*7e687fd8SAndreas Gohr * Media files do not have per-file ACLs; permissions are always evaluated against the namespace
708*7e687fd8SAndreas Gohr * they live in. This returns the namespace wildcard path (e.g. "wiki:*" or "*" for root-namespace
709*7e687fd8SAndreas Gohr * media) suitable for passing to auth_quickaclcheck() or auth_aclcheck().
710*7e687fd8SAndreas Gohr *
711*7e687fd8SAndreas Gohr * @param string $id media ID (needs to be resolved and cleaned)
712*7e687fd8SAndreas Gohr * @return string the ACL path to check
713*7e687fd8SAndreas Gohr */
714*7e687fd8SAndreas Gohrfunction mediaAclPath($id)
715*7e687fd8SAndreas Gohr{
716*7e687fd8SAndreas Gohr    return ltrim(getNS($id) . ':*', ':');
717*7e687fd8SAndreas Gohr}
718*7e687fd8SAndreas Gohr
719*7e687fd8SAndreas Gohr/**
720c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
72115fae107Sandi *
72215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
72342ea7f44SGerrit Uitslag *
724c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
7251698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
72615fae107Sandi * @param  string       $user   Username
7273272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
72815fae107Sandi * @return int             permission level
729f3f0262cSandi */
730d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
731d868eb89SAndreas Gohr{
73224870174SAndreas Gohr    $data = [
733bf8f8509SAndreas Gohr        'id'     => $id ?? '',
734c17acc9fSAndreas Gohr        'user'   => $user,
735c17acc9fSAndreas Gohr        'groups' => $groups
73624870174SAndreas Gohr    ];
737c17acc9fSAndreas Gohr
738cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
739c17acc9fSAndreas Gohr}
740c17acc9fSAndreas Gohr
741c17acc9fSAndreas Gohr/**
742c17acc9fSAndreas Gohr * default ACL check method
743c17acc9fSAndreas Gohr *
744c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
745c17acc9fSAndreas Gohr *
746c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
74742ea7f44SGerrit Uitslag *
748c17acc9fSAndreas Gohr * @param  array $data event data
749c17acc9fSAndreas Gohr * @return int   permission level
750c17acc9fSAndreas Gohr */
751d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
752d868eb89SAndreas Gohr{
753c17acc9fSAndreas Gohr    $id     =& $data['id'];
754c17acc9fSAndreas Gohr    $user   =& $data['user'];
755c17acc9fSAndreas Gohr    $groups =& $data['groups'];
756c17acc9fSAndreas Gohr
757f3f0262cSandi    global $conf;
758f3f0262cSandi    global $AUTH_ACL;
759e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
760d752aedeSAndreas Gohr    global $auth;
761f3f0262cSandi
76285d03f68SAndreas Gohr    // if no ACL is used always return upload rights
763f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7646547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
765bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
766f3f0262cSandi
767074cf26bSandi    //make sure groups is an array
76824870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
769074cf26bSandi
77085d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
771ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
772ab5d26daSAndreas Gohr        return AUTH_ADMIN;
773ab5d26daSAndreas Gohr    }
77485d03f68SAndreas Gohr
775eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
77624870174SAndreas Gohr        $user   = PhpString::strtolower($user);
777093fe67eSAndreas Gohr        $groups = array_map(PhpString::strtolower(...), $groups);
778eb3ce0d5SKazutaka Miyasaka    }
77937ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
780093fe67eSAndreas Gohr    $groups = array_map($auth->cleanGroup(...), $groups);
78185d03f68SAndreas Gohr
7826c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
78337ff2261SSascha Klopp    foreach ($groups as &$group) {
78437ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
78510a76f6fSfrank    }
78610a76f6fSfrank
787f3f0262cSandi    $ns   = getNS($id);
788f3f0262cSandi    $perm = -1;
789f3f0262cSandi
790f3f0262cSandi    //add ALL group
791f3f0262cSandi    $groups[] = '@ALL';
79237ff2261SSascha Klopp
793f3f0262cSandi    //add User
79434aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
795f3f0262cSandi
796f3f0262cSandi    //check exact match first
79721c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
798f3f0262cSandi    if (count($matches)) {
799f3f0262cSandi        foreach ($matches as $match) {
800f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
80121c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
802eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
80324870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
804eb3ce0d5SKazutaka Miyasaka            }
80548d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
80648d7b7a6SDominik Eckelmann                continue;
80748d7b7a6SDominik Eckelmann            }
8088ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
809f3f0262cSandi            if ($acl[2] > $perm) {
810f3f0262cSandi                $perm = $acl[2];
811f3f0262cSandi            }
812f3f0262cSandi        }
813f3f0262cSandi        if ($perm > -1) {
814f3f0262cSandi            //we had a match - return it
815def492a2SGuillaume Turri            return (int) $perm;
816f3f0262cSandi        }
817f3f0262cSandi    }
818f3f0262cSandi
819f3f0262cSandi    //still here? do the namespace checks
820f3f0262cSandi    if ($ns) {
8213e304b55SMichael Hamann        $path = $ns . ':*';
822f3f0262cSandi    } else {
8233e304b55SMichael Hamann        $path = '*'; //root document
824f3f0262cSandi    }
825f3f0262cSandi
826f3f0262cSandi    do {
82721c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
828f3f0262cSandi        if (count($matches)) {
829f3f0262cSandi            foreach ($matches as $match) {
830f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
83121c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
832eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
83324870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
834eb3ce0d5SKazutaka Miyasaka                }
83548d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
83648d7b7a6SDominik Eckelmann                    continue;
83748d7b7a6SDominik Eckelmann                }
8388ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
839f3f0262cSandi                if ($acl[2] > $perm) {
840f3f0262cSandi                    $perm = $acl[2];
841f3f0262cSandi                }
842f3f0262cSandi            }
843f3f0262cSandi            //we had a match - return it
84448d7b7a6SDominik Eckelmann            if ($perm != -1) {
845def492a2SGuillaume Turri                return (int) $perm;
846f3f0262cSandi            }
84748d7b7a6SDominik Eckelmann        }
848f3f0262cSandi        //get next higher namespace
849f3f0262cSandi        $ns = getNS($ns);
850f3f0262cSandi
8513e304b55SMichael Hamann        if ($path != '*') {
8523e304b55SMichael Hamann            $path = $ns . ':*';
8533e304b55SMichael Hamann            if ($path == ':*') $path = '*';
854f3f0262cSandi        } else {
855f3f0262cSandi            //we did this already
856f3f0262cSandi            //looks like there is something wrong with the ACL
857f3f0262cSandi            //break here
858d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
859d5ce66f6SAndreas Gohr            return AUTH_NONE;
860f3f0262cSandi        }
861f3f0262cSandi    } while (1); //this should never loop endless
862ab5d26daSAndreas Gohr    return AUTH_NONE;
863f3f0262cSandi}
864f3f0262cSandi
865f3f0262cSandi/**
8666c2bb100SAndreas Gohr * Encode ASCII special chars
8676c2bb100SAndreas Gohr *
8686c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8696c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8706c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8716c2bb100SAndreas Gohr * urlencoding!).
8726c2bb100SAndreas Gohr *
8736c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8746c2bb100SAndreas Gohr *
8756c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8766c2bb100SAndreas Gohr * @see rawurldecode()
87742ea7f44SGerrit Uitslag *
87842ea7f44SGerrit Uitslag * @param string $name
87942ea7f44SGerrit Uitslag * @param bool $skip_group
88042ea7f44SGerrit Uitslag * @return string
8816c2bb100SAndreas Gohr */
882d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
883d868eb89SAndreas Gohr{
884a424cd8eSchris    global $cache_authname;
885a424cd8eSchris    $cache =& $cache_authname;
88631784267SAndreas Gohr    $name  = (string) $name;
887a424cd8eSchris
88880601d26SAndreas Gohr    // never encode wildcard FS#1955
88980601d26SAndreas Gohr    if ($name == '%USER%') return $name;
890b78bf706Sromain    if ($name == '%GROUP%') return $name;
89180601d26SAndreas Gohr
892a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8932401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
89430f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
89530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
896093fe67eSAndreas Gohr                auth_nameencode_callback(...),
897dccd6b2bSAndreas Gohr                substr($name, 1)
898ab5d26daSAndreas Gohr            );
899e838fc2eSAndreas Gohr        } else {
90030f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
90130f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
902093fe67eSAndreas Gohr                auth_nameencode_callback(...),
903dccd6b2bSAndreas Gohr                $name
904ab5d26daSAndreas Gohr            );
905e838fc2eSAndreas Gohr        }
9066c2bb100SAndreas Gohr    }
9076c2bb100SAndreas Gohr
908a424cd8eSchris    return $cache[$name][$skip_group];
909a424cd8eSchris}
910a424cd8eSchris
91104d68ae4SGerrit Uitslag/**
91204d68ae4SGerrit Uitslag * callback encodes the matches
91304d68ae4SGerrit Uitslag *
91404d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
91504d68ae4SGerrit Uitslag * @return string
91604d68ae4SGerrit Uitslag */
917d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
918d868eb89SAndreas Gohr{
91930f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
92030f6faf0SChristopher Smith}
92130f6faf0SChristopher Smith
9226c2bb100SAndreas Gohr/**
923f3f0262cSandi * Create a pronouncable password
924f3f0262cSandi *
9258a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
9268a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
9278a285f7fSAndreas Gohr *
9284dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
9294dc42f7fSGerrit Uitslag * @return string  pronouncable password
9304dc42f7fSGerrit Uitslag * @throws Exception
9314dc42f7fSGerrit Uitslag *
93215fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
9338a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
93415fae107Sandi *
9354dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
936f3f0262cSandi */
937d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
938d868eb89SAndreas Gohr{
93924870174SAndreas Gohr    $data = [
940d628dcf3SAndreas Gohr        'password' => '',
941d628dcf3SAndreas Gohr        'foruser'  => $foruser
94224870174SAndreas Gohr    ];
9438a285f7fSAndreas Gohr
944e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
9458a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
946f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
947f3f0262cSandi        $v = 'aeiou'; //vowels
948f3f0262cSandi        $a = $c . $v; //both
949987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
950f3f0262cSandi
951987c8d26SAndreas Gohr        //use thre syllables...
952987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
953483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
954483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
955483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
956f3f0262cSandi        }
957987c8d26SAndreas Gohr        //... and add a nice number and special
95843f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9598a285f7fSAndreas Gohr    }
9608a285f7fSAndreas Gohr    $evt->advise_after();
961f3f0262cSandi
9628a285f7fSAndreas Gohr    return $data['password'];
963f3f0262cSandi}
964f3f0262cSandi
965f3f0262cSandi/**
966f3f0262cSandi * Sends a password to the given user
967f3f0262cSandi *
96815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
96942ea7f44SGerrit Uitslag *
970ab5d26daSAndreas Gohr * @param string $user Login name of the user
971ab5d26daSAndreas Gohr * @param string $password The new password in clear text
97215fae107Sandi * @return bool  true on success
973f3f0262cSandi */
974d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
975d868eb89SAndreas Gohr{
976f3f0262cSandi    global $lang;
977e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
978cd52f92dSchris    global $auth;
9796547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
980cd52f92dSchris
981d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9824dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
983f3f0262cSandi
98487ddda95Sandi    if (!$userinfo['mail']) return false;
985f3f0262cSandi
986f3f0262cSandi    $text = rawLocale('password');
98724870174SAndreas Gohr    $trep = [
988d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
989d7169d19SAndreas Gohr        'LOGIN'    => $user,
990d7169d19SAndreas Gohr        'PASSWORD' => $password
99124870174SAndreas Gohr    ];
992f3f0262cSandi
993d7169d19SAndreas Gohr    $mail = new Mailer();
994102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
995d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
996d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
997d7169d19SAndreas Gohr    return $mail->send();
998f3f0262cSandi}
999f3f0262cSandi
1000f3f0262cSandi/**
100115fae107Sandi * Register a new user
1002f3f0262cSandi *
100315fae107Sandi * This registers a new user - Data is read directly from $_POST
100415fae107Sandi *
100515fae107Sandi * @return bool  true on success, false on any error
10064dc42f7fSGerrit Uitslag * @throws Exception
10074dc42f7fSGerrit Uitslag *
10084dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
1009f3f0262cSandi */
1010d868eb89SAndreas Gohrfunction register()
1011d868eb89SAndreas Gohr{
1012f3f0262cSandi    global $lang;
1013eb5d07e4Sjan    global $conf;
10144dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
1015cd52f92dSchris    global $auth;
101664273335SAndreas Gohr    global $INPUT;
1017f3f0262cSandi
101864273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10193a48618aSAnika Henke    if (!actionOK('register')) return false;
1020640145a5Sandi
102164273335SAndreas Gohr    // gather input
102264273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
102364273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
102464273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
102564273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
102664273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
1027d752aedeSAndreas Gohr
102864273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
1029f3f0262cSandi        msg($lang['regmissing'], -1);
1030f3f0262cSandi        return false;
1031f3f0262cSandi    }
1032f3f0262cSandi
1033cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
10348a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
103564273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
1036bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
1037cab2716aSmatthias.grimm        return false;
103864273335SAndreas Gohr    } elseif ($pass != $passchk) {
1039bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
1040cab2716aSmatthias.grimm        return false;
1041cab2716aSmatthias.grimm    }
1042cab2716aSmatthias.grimm
1043f3f0262cSandi    //check mail
104464273335SAndreas Gohr    if (!mail_isvalid($email)) {
1045f3f0262cSandi        msg($lang['regbadmail'], -1);
1046f3f0262cSandi        return false;
1047f3f0262cSandi    }
1048f3f0262cSandi
1049f3f0262cSandi    //okay try to create the user
105024870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1051db9faf02SPatrick Brown        msg($lang['regfail'], -1);
1052f3f0262cSandi        return false;
1053f3f0262cSandi    }
1054f3f0262cSandi
1055790b7720SAndreas Gohr    // send notification about the new user
105675d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
105775d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
105802a498e7Schris
1059790b7720SAndreas Gohr    // are we done?
1060cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1061cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1062cab2716aSmatthias.grimm        return true;
1063cab2716aSmatthias.grimm    }
1064cab2716aSmatthias.grimm
1065790b7720SAndreas Gohr    // autogenerated password? then send password to user
106664273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1067f3f0262cSandi        msg($lang['regsuccess'], 1);
1068f3f0262cSandi        return true;
1069f3f0262cSandi    } else {
1070f3f0262cSandi        msg($lang['regmailfail'], -1);
1071f3f0262cSandi        return false;
1072f3f0262cSandi    }
1073f3f0262cSandi}
1074f3f0262cSandi
107510a76f6fSfrank/**
10768b06d178Schris * Update user profile
10778b06d178Schris *
10784dc42f7fSGerrit Uitslag * @throws Exception
10794dc42f7fSGerrit Uitslag *
10808b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10818b06d178Schris */
1082d868eb89SAndreas Gohrfunction updateprofile()
1083d868eb89SAndreas Gohr{
10848b06d178Schris    global $conf;
10858b06d178Schris    global $lang;
1086e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1087cd52f92dSchris    global $auth;
1088bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1089bcc94b2cSAndreas Gohr    global $INPUT;
10908b06d178Schris
1091bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10921b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10938b06d178Schris
10943a48618aSAnika Henke    if (!actionOK('profile')) {
10958b06d178Schris        msg($lang['profna'], -1);
10968b06d178Schris        return false;
10978b06d178Schris    }
10988b06d178Schris
109924870174SAndreas Gohr    $changes         = [];
1100bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1101bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1102bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1103bcc94b2cSAndreas Gohr
1104bcc94b2cSAndreas Gohr    // check misspelled passwords
1105bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1106bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
11078b06d178Schris        return false;
11088b06d178Schris    }
11098b06d178Schris
11108b06d178Schris    // clean fullname and email
1111bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1112bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
11138b06d178Schris
1114bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
11157d34963bSAndreas Gohr    if (
11167d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1117bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1118ab5d26daSAndreas Gohr    ) {
11198b06d178Schris        msg($lang['profnoempty'], -1);
11208b06d178Schris        return false;
11218b06d178Schris    }
1122bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
11238b06d178Schris        msg($lang['regbadmail'], -1);
11248b06d178Schris        return false;
11258b06d178Schris    }
11268b06d178Schris
1127bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
11284c21b7eeSAndreas Gohr
1129bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1130bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1131bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1132bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1133bcc94b2cSAndreas Gohr
1134bcc94b2cSAndreas Gohr    // anything to do?
113524870174SAndreas Gohr    if ($changes === []) {
11368b06d178Schris        msg($lang['profnochange'], -1);
11378b06d178Schris        return false;
11388b06d178Schris    }
11398b06d178Schris
11408b06d178Schris    if ($conf['profileconfirm']) {
1141585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
114271422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
11438b06d178Schris            return false;
11448b06d178Schris        }
11458b06d178Schris    }
11468b06d178Schris
114724870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1148db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1149db9faf02SPatrick Brown        return false;
1150db9faf02SPatrick Brown    }
1151db9faf02SPatrick Brown
115267efd1edSPieter Hollants    if (array_key_exists('pass', $changes) && $changes['pass']) {
1153c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1154a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
115504369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1156585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1157c276e9e8SMarcel Pennewiss    } else {
1158c276e9e8SMarcel Pennewiss        // make sure the session is writable
1159c276e9e8SMarcel Pennewiss        @session_start();
1160c276e9e8SMarcel Pennewiss        // invalidate session cache
1161c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1162c276e9e8SMarcel Pennewiss        session_write_close();
116332ed2b36SAndreas Gohr    }
1164c276e9e8SMarcel Pennewiss
116525b2a98cSMichael Klier    return true;
1166a0b5b007SChris Smith}
1167ab5d26daSAndreas Gohr
116804d68ae4SGerrit Uitslag/**
116904d68ae4SGerrit Uitslag * Delete the current logged-in user
117004d68ae4SGerrit Uitslag *
117104d68ae4SGerrit Uitslag * @return bool true on success, false on any error
117204d68ae4SGerrit Uitslag */
1173d868eb89SAndreas Gohrfunction auth_deleteprofile()
1174d868eb89SAndreas Gohr{
11752a7abf2dSChristopher Smith    global $conf;
11762a7abf2dSChristopher Smith    global $lang;
11774dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11782a7abf2dSChristopher Smith    global $auth;
11792a7abf2dSChristopher Smith    /* @var Input $INPUT */
11802a7abf2dSChristopher Smith    global $INPUT;
11812a7abf2dSChristopher Smith
11822a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11832a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11842a7abf2dSChristopher Smith
11852a7abf2dSChristopher Smith    // action prevented or auth module disallows
11862a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11872a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11882a7abf2dSChristopher Smith        return false;
11892a7abf2dSChristopher Smith    }
11902a7abf2dSChristopher Smith
11912a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11922a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11932a7abf2dSChristopher Smith        return false;
11942a7abf2dSChristopher Smith    }
11952a7abf2dSChristopher Smith
11962a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1197585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11982a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11992a7abf2dSChristopher Smith            return false;
12002a7abf2dSChristopher Smith        }
12012a7abf2dSChristopher Smith    }
12022a7abf2dSChristopher Smith
120324870174SAndreas Gohr    $deleted = [];
1204585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
120524870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
12062a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
12072a7abf2dSChristopher Smith        auth_logoff();
12082a7abf2dSChristopher Smith        return true;
12092a7abf2dSChristopher Smith    }
12102a7abf2dSChristopher Smith
12112a7abf2dSChristopher Smith    return false;
12122a7abf2dSChristopher Smith}
12132a7abf2dSChristopher Smith
12148b06d178Schris/**
12158b06d178Schris * Send a  new password
12168b06d178Schris *
12171d5856cfSAndreas Gohr * This function handles both phases of the password reset:
12181d5856cfSAndreas Gohr *
12191d5856cfSAndreas Gohr *   - handling the first request of password reset
12201d5856cfSAndreas Gohr *   - validating the password reset auth token
12211d5856cfSAndreas Gohr *
12224dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
12234dc42f7fSGerrit Uitslag * @throws Exception
12244dc42f7fSGerrit Uitslag *
12254dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
12268b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
12278b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
12288b06d178Schris */
1229d868eb89SAndreas Gohrfunction act_resendpwd()
1230d868eb89SAndreas Gohr{
12318b06d178Schris    global $lang;
12328b06d178Schris    global $conf;
1233e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1234cd52f92dSchris    global $auth;
1235bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1236bcc94b2cSAndreas Gohr    global $INPUT;
12378b06d178Schris
12383a48618aSAnika Henke    if (!actionOK('resendpwd')) {
12398b06d178Schris        msg($lang['resendna'], -1);
12408b06d178Schris        return false;
12418b06d178Schris    }
12428b06d178Schris
1243bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
12448b06d178Schris
12451d5856cfSAndreas Gohr    if ($token) {
1246cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
12471d5856cfSAndreas Gohr
12482401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
124979e79377SAndreas Gohr        if (!file_exists($tfile)) {
12501d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1251bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12521d5856cfSAndreas Gohr            return false;
12531d5856cfSAndreas Gohr        }
12548a9735e3SAndreas Gohr        // token is only valid for 3 days
12558a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12568a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1257bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12581d5856cfSAndreas Gohr            @unlink($tfile);
12598a9735e3SAndreas Gohr            return false;
12608a9735e3SAndreas Gohr        }
12618a9735e3SAndreas Gohr
12628b06d178Schris        $user     = io_readfile($tfile);
12634dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12648b06d178Schris        if (!$userinfo['mail']) {
12658b06d178Schris            msg($lang['resendpwdnouser'], -1);
12668b06d178Schris            return false;
12678b06d178Schris        }
12688b06d178Schris
1269cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1270bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1271bcc94b2cSAndreas Gohr
1272cc204bbdSAndreas Gohr            // password given correctly?
1273bcc94b2cSAndreas Gohr            if (!$pass) return false;
1274bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1275451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1276cc204bbdSAndreas Gohr                return false;
1277cc204bbdSAndreas Gohr            }
1278cc204bbdSAndreas Gohr
1279bcc94b2cSAndreas Gohr            // change it
128024870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1281db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1282cc204bbdSAndreas Gohr                return false;
1283cc204bbdSAndreas Gohr            }
1284cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12858a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
128624870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1287db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12888b06d178Schris                return false;
12898b06d178Schris            }
12908b06d178Schris
12918b06d178Schris            if (auth_sendPassword($user, $pass)) {
12928b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12938b06d178Schris            } else {
12948b06d178Schris                msg($lang['regmailfail'], -1);
12958b06d178Schris            }
1296cc204bbdSAndreas Gohr        }
1297cc204bbdSAndreas Gohr
1298cc204bbdSAndreas Gohr        @unlink($tfile);
12998b06d178Schris        return true;
13001d5856cfSAndreas Gohr    } else {
13011d5856cfSAndreas Gohr        // we're in request phase
13021d5856cfSAndreas Gohr
1303bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
13041d5856cfSAndreas Gohr
1305bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
13061d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
13071d5856cfSAndreas Gohr            return false;
13081d5856cfSAndreas Gohr        } else {
1309bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
13101d5856cfSAndreas Gohr        }
13111d5856cfSAndreas Gohr
13124dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
13131d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
13141d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
13151d5856cfSAndreas Gohr            return false;
13161d5856cfSAndreas Gohr        }
13171d5856cfSAndreas Gohr
13181d5856cfSAndreas Gohr        // generate auth token
1319483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
13202401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
132124870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
13221d5856cfSAndreas Gohr
13231d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
13241d5856cfSAndreas Gohr
13251d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
132624870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
13271d5856cfSAndreas Gohr
1328d7169d19SAndreas Gohr        $mail = new Mailer();
1329d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1330d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1331d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1332d7169d19SAndreas Gohr        if ($mail->send()) {
13331d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
13341d5856cfSAndreas Gohr        } else {
13351d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
13361d5856cfSAndreas Gohr        }
13371d5856cfSAndreas Gohr        return true;
13381d5856cfSAndreas Gohr    }
1339ab5d26daSAndreas Gohr    // never reached
13408b06d178Schris}
13418b06d178Schris
13428b06d178Schris/**
1343b0855b11Sandi * Encrypts a password using the given method and salt
1344b0855b11Sandi *
1345b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1346b0855b11Sandi * is chosen.
1347b0855b11Sandi *
13480ffe9fdaSTobias Bengfort * You can pass null as the password to create an unusable hash.
13490ffe9fdaSTobias Bengfort *
1350b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
135142ea7f44SGerrit Uitslag *
1352ab5d26daSAndreas Gohr * @param string $clear The clear text password
1353ab5d26daSAndreas Gohr * @param string $method The hashing method
1354ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1355b0855b11Sandi * @return  string  The crypted password
1356b0855b11Sandi */
1357d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1358d868eb89SAndreas Gohr{
1359b0855b11Sandi    global $conf;
1360527ad715STobias Bengfort
1361527ad715STobias Bengfort    if ($clear === null) {
1362b21b7935STobias Bengfort        return DOKU_UNUSABLE_PASSWORD;
1363527ad715STobias Bengfort    }
1364527ad715STobias Bengfort
1365b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
136610a76f6fSfrank
13673a0a2d05SAndreas Gohr    $pass = new PassHash();
13683a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1369b0855b11Sandi
13703a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1371b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13723a0a2d05SAndreas Gohr        return false;
1373b0855b11Sandi    }
13743a0a2d05SAndreas Gohr
13753a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1376b0855b11Sandi}
1377b0855b11Sandi
1378b0855b11Sandi/**
1379b0855b11Sandi * Verifies a cleartext password against a crypted hash
1380b0855b11Sandi *
1381ab5d26daSAndreas Gohr * @param string $clear The clear text password
1382ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1383ab5d26daSAndreas Gohr * @return bool true if both match
13844dc42f7fSGerrit Uitslag * @throws Exception
13854dc42f7fSGerrit Uitslag *
13864dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1387b0855b11Sandi */
1388d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1389d868eb89SAndreas Gohr{
1390b21b7935STobias Bengfort    if ($crypt === DOKU_UNUSABLE_PASSWORD) {
1391527ad715STobias Bengfort        return false;
1392527ad715STobias Bengfort    }
1393527ad715STobias Bengfort
13943a0a2d05SAndreas Gohr    $pass = new PassHash();
13953a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1396b0855b11Sandi}
1397340756e4Sandi
1398a0b5b007SChris Smith/**
1399a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1400a0b5b007SChris Smith *
1401a0b5b007SChris Smith * @param string  $user       username
1402a0b5b007SChris Smith * @param string  $pass       encrypted password
1403a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1404ab5d26daSAndreas Gohr * @return bool
1405a0b5b007SChris Smith */
1406d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1407d868eb89SAndreas Gohr{
1408a0b5b007SChris Smith    global $conf;
1409e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1410a0b5b007SChris Smith    global $auth;
141179d00841SOliver Geisen    global $USERINFO;
1412a0b5b007SChris Smith
14136547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1414a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1415a0b5b007SChris Smith
1416a0b5b007SChris Smith    // set cookie
1417645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
141873ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1419c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1420bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1421bf8392ebSAndreas Gohr        'expires' => $time,
1422bf8392ebSAndreas Gohr        'path' => $cookieDir,
14239399c87eSsplitbrain        'secure' => ($conf['securecookie'] && Ip::isSsl()),
1424bf8392ebSAndreas Gohr        'httponly' => true,
1425486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1426bf8392ebSAndreas Gohr    ]);
142755a71a16SGerrit Uitslag
1428a0b5b007SChris Smith    // set session
1429a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1430234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1431a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1432a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1433a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1434ab5d26daSAndreas Gohr
1435ab5d26daSAndreas Gohr    return true;
1436a0b5b007SChris Smith}
1437a0b5b007SChris Smith
1438645c0a36SAndreas Gohr/**
1439645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1440645c0a36SAndreas Gohr *
1441645c0a36SAndreas Gohr * @returns array
1442645c0a36SAndreas Gohr */
1443d868eb89SAndreas Gohrfunction auth_getCookie()
1444d868eb89SAndreas Gohr{
1445c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
144624870174SAndreas Gohr        return [null, null, null];
1447c66972f2SAdrian Lang    }
144824870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1449645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1450645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1451645c0a36SAndreas Gohr    $user   = base64_decode($user);
145224870174SAndreas Gohr    return [$user, $sticky, $pass];
1453645c0a36SAndreas Gohr}
1454645c0a36SAndreas Gohr
1455e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1456