xref: /dokuwiki/inc/auth.php (revision 1cedacf229f1294fea53b494765c47559d8a3e86)
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
13*1cedacf2SAndreas Gohruse dokuwiki\ErrorHandler;
14cf927d07Ssplitbrainuse dokuwiki\JWT;
1524870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1696348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1796348f27SAndreas Gohruse dokuwiki\Extension\Event;
1896348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
19c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
2075d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
21927933f5SAndreas Gohruse phpseclib3\Crypt\AES;
22927933f5SAndreas Gohruse phpseclib3\Crypt\Common\SymmetricKey;
23*1cedacf2SAndreas Gohruse phpseclib3\Exception\BadDecryptionException;
24c3cc6e05SAndreas Gohr
2516905344SAndreas Gohr/**
2616905344SAndreas Gohr * Initialize the auth system.
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * This function is automatically called at the end of init.php
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * This used to be the main() of the auth.php
3116905344SAndreas Gohr *
3216905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3316905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
34ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
35ab5d26daSAndreas Gohr * @return bool
3616905344SAndreas Gohr */
37d868eb89SAndreas Gohrfunction auth_setup()
38d868eb89SAndreas Gohr{
39742c66f8Schris    global $conf;
40e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4103c4aec3Schris    global $auth;
42bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
43bcc94b2cSAndreas Gohr    global $INPUT;
449a9714acSDominik Eckelmann    global $AUTH_ACL;
459a9714acSDominik Eckelmann    global $lang;
463a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
479c29eea5SJan Schumann    global $plugin_controller;
4824870174SAndreas Gohr    $AUTH_ACL = [];
4903c4aec3Schris
5016905344SAndreas Gohr    if (!$conf['useacl']) return false;
5116905344SAndreas Gohr
529c29eea5SJan Schumann    // try to load auth backend from plugins
539c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
549c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
55f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
569c29eea5SJan Schumann            break;
579c29eea5SJan Schumann        }
589c29eea5SJan Schumann    }
598b06d178Schris
606547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) {
6171c734a9SGerrit Uitslag        msg($lang['authtempfail'], -1);
623094e817SAndreas Gohr        return false;
633094e817SAndreas Gohr    }
648b06d178Schris
656416b708SMichael Hamann    if ($auth->success == false) {
660f4f4adfSAndreas Gohr        // degrade to unauthenticated user
67ecad51ddSAndreas Gohr        $auth = null;
680f4f4adfSAndreas Gohr        auth_logoff();
69cd52f92dSchris        msg($lang['authtempfail'], -1);
706416b708SMichael Hamann        return false;
71d2dde4ebSMatthias Grimm    }
7216905344SAndreas Gohr
7316905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
74bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
75bcc94b2cSAndreas Gohr    if (!$conf['rememberme']) $INPUT->set('r', false);
76bbbd6568SAndreas Gohr
7762bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
7862bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
7962bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
8062bf3ac0SDamien Regad    if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
8162bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
8224870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
83528ddc7cSAndreas Gohr    }
84528ddc7cSAndreas Gohr
851e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
8603062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
8703062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
8803062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
89bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
901e8c9c90SAndreas Gohr    }
911e8c9c90SAndreas Gohr
92395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9393a7873eSAndreas Gohr    if (true === $auth->success) {
94395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
95395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
96f4476bd9SJan Schumann    }
97191bb90aSAndreas Gohr
98455aa67eSAndreas Gohr    if (!auth_tokenlogin()) {
9981e99965SPhy        $ok = null;
100455aa67eSAndreas Gohr
1016547cfc7SGerrit Uitslag        if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
10281e99965SPhy            $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
10381e99965SPhy        }
10481e99965SPhy
10581e99965SPhy        if ($ok === null) {
10681e99965SPhy            // external trust mechanism not in place, or returns no result,
10781e99965SPhy            // then attempt auth_login
10824870174SAndreas Gohr            $evdata = [
109bcc94b2cSAndreas Gohr                'user' => $INPUT->str('u'),
110bcc94b2cSAndreas Gohr                'password' => $INPUT->str('p'),
111bcc94b2cSAndreas Gohr                'sticky' => $INPUT->bool('r'),
112bcc94b2cSAndreas Gohr                'silent' => $INPUT->bool('http_credentials')
11324870174SAndreas Gohr            ];
114cbb44eabSAndreas Gohr            Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
115f5cb575dSAndreas Gohr        }
116455aa67eSAndreas Gohr    }
117f5cb575dSAndreas Gohr
11816905344SAndreas Gohr    //load ACL into a global array XXX
11975c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
120ab5d26daSAndreas Gohr
121ab5d26daSAndreas Gohr    return true;
12275c93b77SAndreas Gohr}
12375c93b77SAndreas Gohr
12475c93b77SAndreas Gohr/**
12575c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12675c93b77SAndreas Gohr *
12775c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12842ea7f44SGerrit Uitslag *
129ab5d26daSAndreas Gohr * @return array
13075c93b77SAndreas Gohr */
131d868eb89SAndreas Gohrfunction auth_loadACL()
132d868eb89SAndreas Gohr{
13375c93b77SAndreas Gohr    global $config_cascade;
134b78bf706Sromain    global $USERINFO;
135585bf44eSChristopher Smith    /* @var Input $INPUT */
136585bf44eSChristopher Smith    global $INPUT;
13775c93b77SAndreas Gohr
13824870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
13975c93b77SAndreas Gohr
14075c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
14175c93b77SAndreas Gohr
14224870174SAndreas Gohr    $out = [];
1439ce556d2SAndreas Gohr    foreach ($acl as $line) {
1449ce556d2SAndreas Gohr        $line = trim($line);
1452401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
14624870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
14732e82180SAndreas Gohr
148443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
149ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
150ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
151585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
152ad3d68d7SChristopher Smith
153585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
154585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
155ad3d68d7SChristopher Smith        }
156ad3d68d7SChristopher Smith
157ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1589ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
159ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
16006f34f54SPhy            if (isset($USERINFO['grps'])) {
1619ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
162b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
16332e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
16432e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
165b78bf706Sromain                }
16606f34f54SPhy            }
16732e82180SAndreas Gohr        } else {
16832e82180SAndreas Gohr            $out[] = "$id\t$rest";
169a8fe108bSGuy Brand        }
17011799630Sandi    }
1719ce556d2SAndreas Gohr
17232e82180SAndreas Gohr    return $out;
173f3f0262cSandi}
174f3f0262cSandi
175ab5d26daSAndreas Gohr/**
176455aa67eSAndreas Gohr * Try a token login
177455aa67eSAndreas Gohr *
178455aa67eSAndreas Gohr * @return bool true if token login succeeded
179455aa67eSAndreas Gohr */
180cf927d07Ssplitbrainfunction auth_tokenlogin()
181cf927d07Ssplitbrain{
182455aa67eSAndreas Gohr    global $USERINFO;
183455aa67eSAndreas Gohr    global $INPUT;
184455aa67eSAndreas Gohr    /** @var DokuWiki_Auth_Plugin $auth */
185455aa67eSAndreas Gohr    global $auth;
186455aa67eSAndreas Gohr    if (!$auth) return false;
187455aa67eSAndreas Gohr
188455aa67eSAndreas Gohr    // see if header has token
189455aa67eSAndreas Gohr    $header = '';
1906fdb83b6SAndreas Gohr    if (function_exists('getallheaders')) {
191455aa67eSAndreas Gohr        // Authorization headers are not in $_SERVER for mod_php
1926fdb83b6SAndreas Gohr        $headers = array_change_key_case(getallheaders());
193d26e5a24SAndreas Gohr        if (isset($headers['authorization'])) $header = $headers['authorization'];
194455aa67eSAndreas Gohr    } else {
195455aa67eSAndreas Gohr        $header = $INPUT->server->str('HTTP_AUTHORIZATION');
196455aa67eSAndreas Gohr    }
197455aa67eSAndreas Gohr    if (!$header) return false;
198cf927d07Ssplitbrain    [$type, $token] = sexplode(' ', $header, 2);
199455aa67eSAndreas Gohr    if ($type !== 'Bearer') return false;
200455aa67eSAndreas Gohr
201455aa67eSAndreas Gohr    // check token
202455aa67eSAndreas Gohr    try {
203cf927d07Ssplitbrain        $authtoken = JWT::validate($token);
204455aa67eSAndreas Gohr    } catch (Exception $e) {
205455aa67eSAndreas Gohr        msg(hsc($e->getMessage()), -1);
206455aa67eSAndreas Gohr        return false;
207455aa67eSAndreas Gohr    }
208455aa67eSAndreas Gohr
209455aa67eSAndreas Gohr    // fetch user info from backend
210455aa67eSAndreas Gohr    $user = $authtoken->getUser();
211455aa67eSAndreas Gohr    $USERINFO = $auth->getUserData($user);
212455aa67eSAndreas Gohr    if (!$USERINFO) return false;
213455aa67eSAndreas Gohr
214455aa67eSAndreas Gohr    // the code is correct, set up user
215455aa67eSAndreas Gohr    $INPUT->server->set('REMOTE_USER', $user);
216455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
217455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
218455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
219455aa67eSAndreas Gohr
220455aa67eSAndreas Gohr    return true;
221455aa67eSAndreas Gohr}
222455aa67eSAndreas Gohr
223455aa67eSAndreas Gohr/**
224ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
225ab5d26daSAndreas Gohr *
22642ea7f44SGerrit Uitslag * @param array $evdata
227ab5d26daSAndreas Gohr * @return bool
2284dc42f7fSGerrit Uitslag * @throws Exception
229ab5d26daSAndreas Gohr */
230d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
231d868eb89SAndreas Gohr{
232ab5d26daSAndreas Gohr    return auth_login(
233ab5d26daSAndreas Gohr        $evdata['user'],
234b5ee21aaSAdrian Lang        $evdata['password'],
235b5ee21aaSAdrian Lang        $evdata['sticky'],
236ab5d26daSAndreas Gohr        $evdata['silent']
237ab5d26daSAndreas Gohr    );
238b5ee21aaSAdrian Lang}
239b5ee21aaSAdrian Lang
240f3f0262cSandi/**
241f3f0262cSandi * This tries to login the user based on the sent auth credentials
242f3f0262cSandi *
243f3f0262cSandi * The authentication works like this: if a username was given
24415fae107Sandi * a new login is assumed and user/password are checked. If they
24515fae107Sandi * are correct the password is encrypted with blowfish and stored
24615fae107Sandi * together with the username in a cookie - the same info is stored
24715fae107Sandi * in the session, too. Additonally a browserID is stored in the
24815fae107Sandi * session.
24915fae107Sandi *
25015fae107Sandi * If no username was given the cookie is checked: if the username,
25115fae107Sandi * crypted password and browserID match between session and cookie
25215fae107Sandi * no further testing is done and the user is accepted
25315fae107Sandi *
25415fae107Sandi * If a cookie was found but no session info was availabe the
255136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
25615fae107Sandi * together with username rechecked by calling this function again.
257f3f0262cSandi *
258f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
259f3f0262cSandi * are set.
26015fae107Sandi *
26115fae107Sandi * @param string $user Username
26215fae107Sandi * @param string $pass Cleartext Password
26315fae107Sandi * @param bool $sticky Cookie should not expire
264f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
26515fae107Sandi * @return bool true on successful auth
2664dc42f7fSGerrit Uitslag * @throws Exception
2674dc42f7fSGerrit Uitslag *
2684dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
269f3f0262cSandi */
270d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
271d868eb89SAndreas Gohr{
272f3f0262cSandi    global $USERINFO;
273f3f0262cSandi    global $conf;
274f3f0262cSandi    global $lang;
275e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
276cd52f92dSchris    global $auth;
277585bf44eSChristopher Smith    /* @var Input $INPUT */
278585bf44eSChristopher Smith    global $INPUT;
279ab5d26daSAndreas Gohr
2806547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
281beca106aSAdrian Lang
282bbbd6568SAndreas Gohr    if (!empty($user)) {
283132bdbfeSandi        //usual login
2845e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
285132bdbfeSandi            // make logininfo globally available
286585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
28730d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
28804369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
289132bdbfeSandi            return true;
290f3f0262cSandi        } else {
291f3f0262cSandi            //invalid credentials - log off
292f8b1e4e7SAndreas Gohr            if (!$silent) {
293f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
294f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
295f8b1e4e7SAndreas Gohr            }
296f3f0262cSandi            auth_logoff();
297132bdbfeSandi            return false;
298f3f0262cSandi        }
299f3f0262cSandi    } else {
300132bdbfeSandi        // read cookie information
30124870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
302132bdbfeSandi        if ($user && $pass) {
303132bdbfeSandi            // we got a cookie - see if we can trust it
304fa7c70ffSAdrian Lang
305fa7c70ffSAdrian Lang            // get session info
3060058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
307fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
3087d34963bSAndreas Gohr                if (
3097d34963bSAndreas Gohr                    isset($session) &&
3107172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3114c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
312132bdbfeSandi                    ($session['user'] == $user) &&
313234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
314ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
315ab5d26daSAndreas Gohr                ) {
316132bdbfeSandi                    // he has session, cookie and browser right - let him in
317585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
318132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
319132bdbfeSandi                    return true;
320132bdbfeSandi                }
3210058ae75SDamien Regad            }
322f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
32330d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
32404369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
325f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
326132bdbfeSandi        }
327132bdbfeSandi    }
328f3f0262cSandi    //just to be sure
329883179a4SAndreas Gohr    auth_logoff(true);
330132bdbfeSandi    return false;
331f3f0262cSandi}
332132bdbfeSandi
333132bdbfeSandi/**
334136ce040Sandi * Builds a pseudo UID from browser and IP data
335132bdbfeSandi *
336132bdbfeSandi * This is neither unique nor unfakable - still it adds some
337136ce040Sandi * security. Using the first part of the IP makes sure
33880b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
33915fae107Sandi *
34015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
34115fae107Sandi *
342b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
343132bdbfeSandi */
344d868eb89SAndreas Gohrfunction auth_browseruid()
345d868eb89SAndreas Gohr{
346585bf44eSChristopher Smith    /* @var Input $INPUT */
347585bf44eSChristopher Smith    global $INPUT;
348585bf44eSChristopher Smith
3492f9daf16SAndreas Gohr    $ip = clientIP(true);
350b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
351b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
352b7c67f83SAndreas Gohr
353b7c67f83SAndreas Gohr    $uid = implode("\n", [
354b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
355b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
356b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
357b7c67f83SAndreas Gohr    ]);
358b13c0e1aSAdaKaleh    return hash('sha256', $uid);
359132bdbfeSandi}
360132bdbfeSandi
361132bdbfeSandi/**
362132bdbfeSandi * Creates a random key to encrypt the password in cookies
36315fae107Sandi *
36415fae107Sandi * This function tries to read the password for encrypting
36598407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
36615fae107Sandi * if no such file is found a random key is created and
36715fae107Sandi * and stored in this file.
36815fae107Sandi *
36932ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
37030d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
37115fae107Sandi * @return  string
3724dc42f7fSGerrit Uitslag * @throws Exception
3734dc42f7fSGerrit Uitslag *
3744dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
375132bdbfeSandi */
376d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
377d868eb89SAndreas Gohr{
378a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
379fe745becSMichael Große        return 'test';
380a1fe3c9cSMichael Große    }
381132bdbfeSandi    global $conf;
38298407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
38330d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
38430d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
38530d544a4SMichael Hamann    }
386132bdbfeSandi    $salt = io_readFile($file);
387132bdbfeSandi    if (empty($salt)) {
38830d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
389132bdbfeSandi        io_saveFile($file, $salt);
390132bdbfeSandi    }
39132ed2b36SAndreas Gohr    if ($addsession) {
39232ed2b36SAndreas Gohr        $salt .= session_id();
39332ed2b36SAndreas Gohr    }
394132bdbfeSandi    return $salt;
395f3f0262cSandi}
396f3f0262cSandi
397f3f0262cSandi/**
3987a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
399483b6238SMichael Hamann *
4007a33d2f8SNiklas Keller * @param int $length number of bytes
4017a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
4024dc42f7fSGerrit Uitslag * @throws Exception
4034dc42f7fSGerrit Uitslag *
4044dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
405483b6238SMichael Hamann */
406d868eb89SAndreas Gohrfunction auth_randombytes($length)
407d868eb89SAndreas Gohr{
4087a33d2f8SNiklas Keller    return random_bytes($length);
409483b6238SMichael Hamann}
410483b6238SMichael Hamann
411483b6238SMichael Hamann/**
4127a33d2f8SNiklas Keller * Cryptographically secure random number generator.
413483b6238SMichael Hamann *
414483b6238SMichael Hamann * @param int $min
415483b6238SMichael Hamann * @param int $max
416483b6238SMichael Hamann * @return int
4174dc42f7fSGerrit Uitslag * @throws Exception
4184dc42f7fSGerrit Uitslag *
4194dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
420483b6238SMichael Hamann */
421d868eb89SAndreas Gohrfunction auth_random($min, $max)
422d868eb89SAndreas Gohr{
4237a33d2f8SNiklas Keller    return random_int($min, $max);
424483b6238SMichael Hamann}
425483b6238SMichael Hamann
426483b6238SMichael Hamann/**
42704369c3eSMichael Hamann * Encrypt data using the given secret using AES
42804369c3eSMichael Hamann *
42904369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
43004369c3eSMichael Hamann * using pbkdf2.
43104369c3eSMichael Hamann *
43204369c3eSMichael Hamann * @param string $data The data that shall be encrypted
43304369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
43404369c3eSMichael Hamann * @return string The ciphertext
4354dc42f7fSGerrit Uitslag * @throws Exception
43604369c3eSMichael Hamann */
437d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
438d868eb89SAndreas Gohr{
43904369c3eSMichael Hamann    $iv     = auth_randombytes(16);
440927933f5SAndreas Gohr    $cipher = new AES('cbc');
44147e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
442927933f5SAndreas Gohr    $cipher->setIV($iv);
44304369c3eSMichael Hamann
4447b650cefSMichael Hamann    /*
4457b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4467b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4477b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4487b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4497b650cefSMichael Hamann    */
45004369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
45104369c3eSMichael Hamann}
45204369c3eSMichael Hamann
45304369c3eSMichael Hamann/**
45404369c3eSMichael Hamann * Decrypt the given AES ciphertext
45504369c3eSMichael Hamann *
45604369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
45704369c3eSMichael Hamann *
45804369c3eSMichael Hamann * @param string $ciphertext The encrypted data
45904369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
460*1cedacf2SAndreas Gohr * @return string|null The decrypted data
46104369c3eSMichael Hamann */
462d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
463d868eb89SAndreas Gohr{
4647b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
465927933f5SAndreas Gohr    $cipher = new AES('cbc');
46647e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
4677b650cefSMichael Hamann    $cipher->setIV($iv);
46804369c3eSMichael Hamann
469*1cedacf2SAndreas Gohr    try {
4707b650cefSMichael Hamann        return $cipher->decrypt(substr($ciphertext, 16));
471*1cedacf2SAndreas Gohr    } catch (BadDecryptionException $e) {
472*1cedacf2SAndreas Gohr        ErrorHandler::logException($e);
473*1cedacf2SAndreas Gohr        return null;
474*1cedacf2SAndreas Gohr    }
47504369c3eSMichael Hamann}
47604369c3eSMichael Hamann
47704369c3eSMichael Hamann/**
478883179a4SAndreas Gohr * Log out the current user
479883179a4SAndreas Gohr *
480f3f0262cSandi * This clears all authentication data and thus log the user
481883179a4SAndreas Gohr * off. It also clears session data.
48215fae107Sandi *
48315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
48442ea7f44SGerrit Uitslag *
485883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
486f3f0262cSandi */
487d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
488d868eb89SAndreas Gohr{
489f3f0262cSandi    global $conf;
490f3f0262cSandi    global $USERINFO;
491e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4925298a619SAndreas Gohr    global $auth;
493585bf44eSChristopher Smith    /* @var Input $INPUT */
494585bf44eSChristopher Smith    global $INPUT;
49537065e65Sandi
496d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
497e9621d07SAndreas Gohr    @session_start();
498e9621d07SAndreas Gohr
499e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
500e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
501e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
502e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
503e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
504e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
505883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
506e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
507585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
508132bdbfeSandi    $USERINFO = null; //FIXME
509f5c6743cSAndreas Gohr
51073ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
511bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
512bf8392ebSAndreas Gohr        'expires' => time() - 600000,
513bf8392ebSAndreas Gohr        'path' => $cookieDir,
514bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
515bf8392ebSAndreas Gohr        'httponly' => true,
516486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
517bf8392ebSAndreas Gohr    ]);
5185298a619SAndreas Gohr
5196547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5206547cfc7SGerrit Uitslag        $auth->logOff();
5216547cfc7SGerrit Uitslag    }
522f3f0262cSandi}
523f3f0262cSandi
524f3f0262cSandi/**
525f8cc712eSAndreas Gohr * Check if a user is a manager
526f8cc712eSAndreas Gohr *
527f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
528f8cc712eSAndreas Gohr * user.
529f8cc712eSAndreas Gohr *
530f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
531f8cc712eSAndreas Gohr *
532ab5d26daSAndreas Gohr * @param string $user Username
533ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
534ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
53510396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
536ab5d26daSAndreas Gohr * @return bool
53796348f27SAndreas Gohr * @see    auth_isadmin
53896348f27SAndreas Gohr *
53996348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
540f8cc712eSAndreas Gohr */
541d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
542d868eb89SAndreas Gohr{
543f8cc712eSAndreas Gohr    global $conf;
544f8cc712eSAndreas Gohr    global $USERINFO;
545e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
546d752aedeSAndreas Gohr    global $auth;
547585bf44eSChristopher Smith    /* @var Input $INPUT */
548585bf44eSChristopher Smith    global $INPUT;
549585bf44eSChristopher Smith
550f8cc712eSAndreas Gohr
5516547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
552c66972f2SAdrian Lang    if (is_null($user)) {
553585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
554c66972f2SAdrian Lang            return false;
555c66972f2SAdrian Lang        } else {
556585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
557c66972f2SAdrian Lang        }
558c66972f2SAdrian Lang    }
559d6dc956fSAndreas Gohr    if (is_null($groups)) {
5601525c228SAnna Dabrowska        // checking the logged in user, or another one?
5611525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5621525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
56366b108d6SAnna Dabrowska        } else {
5646cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5656cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
56666b108d6SAnna Dabrowska        }
567e259aa79SAndreas Gohr    }
568e259aa79SAndreas Gohr
56996348f27SAndreas Gohr    // prefer cached result
57096348f27SAndreas Gohr    static $cache = [];
57110396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
57296348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
573d6dc956fSAndreas Gohr        // check superuser match
57496348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
57500ce12daSChris Smith
57696348f27SAndreas Gohr        // check managers
57796348f27SAndreas Gohr        if (!$ok && !$adminonly) {
57896348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
57996348f27SAndreas Gohr        }
58096348f27SAndreas Gohr
58196348f27SAndreas Gohr        $cache[$cachekey] = $ok;
58296348f27SAndreas Gohr    }
58396348f27SAndreas Gohr
58496348f27SAndreas Gohr    return $cache[$cachekey];
585f8cc712eSAndreas Gohr}
586f8cc712eSAndreas Gohr
587f8cc712eSAndreas Gohr/**
588f8cc712eSAndreas Gohr * Check if a user is admin
589f8cc712eSAndreas Gohr *
590f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
591f8cc712eSAndreas Gohr *
592f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
593f8cc712eSAndreas Gohr *
59496348f27SAndreas Gohr * @param string $user Username
59596348f27SAndreas Gohr * @param array $groups List of groups the user is in
59610396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
59796348f27SAndreas Gohr * @return bool
598f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
599ab5d26daSAndreas Gohr * @see auth_ismanager()
60042ea7f44SGerrit Uitslag *
601f8cc712eSAndreas Gohr */
602d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
603d868eb89SAndreas Gohr{
60496348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
605f8cc712eSAndreas Gohr}
606f8cc712eSAndreas Gohr
607d6dc956fSAndreas Gohr/**
608d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
609d6dc956fSAndreas Gohr * users and groups to determine membership status
610d6dc956fSAndreas Gohr *
611d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
612d6dc956fSAndreas Gohr *
61342ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
61442ea7f44SGerrit Uitslag * @param string $user       user to match against
61542ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6165446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
617d6dc956fSAndreas Gohr */
618d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
619d868eb89SAndreas Gohr{
620e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
621d6dc956fSAndreas Gohr    global $auth;
6226547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
623d6dc956fSAndreas Gohr
624d6dc956fSAndreas Gohr    // clean user and groups
6254f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
62624870174SAndreas Gohr        $user   = PhpString::strtolower($user);
62724870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
628d6dc956fSAndreas Gohr    }
629d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
63024870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
631d6dc956fSAndreas Gohr
632d6dc956fSAndreas Gohr    // extract the memberlist
633d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
634d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
635d6dc956fSAndreas Gohr    $members = array_unique($members);
636d6dc956fSAndreas Gohr    $members = array_filter($members);
637d6dc956fSAndreas Gohr
638d6dc956fSAndreas Gohr    // compare cleaned values
639d6dc956fSAndreas Gohr    foreach ($members as $member) {
640e5204a12SJurgen Hart        if ($member == '@ALL') return true;
64124870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
642d6dc956fSAndreas Gohr        if ($member[0] == '@') {
643d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
644d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
645d6dc956fSAndreas Gohr        } else {
646d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
647d6dc956fSAndreas Gohr            if ($member == $user) return true;
648d6dc956fSAndreas Gohr        }
649d6dc956fSAndreas Gohr    }
650d6dc956fSAndreas Gohr
651d6dc956fSAndreas Gohr    // still here? not a member!
652d6dc956fSAndreas Gohr    return false;
653d6dc956fSAndreas Gohr}
654d6dc956fSAndreas Gohr
655f8cc712eSAndreas Gohr/**
65615fae107Sandi * Convinience function for auth_aclcheck()
65715fae107Sandi *
65815fae107Sandi * This checks the permissions for the current user
65915fae107Sandi *
66015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
66115fae107Sandi *
6621698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
66315fae107Sandi * @return int          permission level
664f3f0262cSandi */
665d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
666d868eb89SAndreas Gohr{
667f3f0262cSandi    global $conf;
668f3f0262cSandi    global $USERINFO;
669585bf44eSChristopher Smith    /* @var Input $INPUT */
670585bf44eSChristopher Smith    global $INPUT;
671f3f0262cSandi    # if no ACL is used always return upload rights
672f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
67324870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
674f3f0262cSandi}
675f3f0262cSandi
676f3f0262cSandi/**
677c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
67815fae107Sandi *
67915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
68042ea7f44SGerrit Uitslag *
681c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6821698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
68315fae107Sandi * @param  string       $user   Username
6843272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
68515fae107Sandi * @return int             permission level
686f3f0262cSandi */
687d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
688d868eb89SAndreas Gohr{
68924870174SAndreas Gohr    $data = [
690bf8f8509SAndreas Gohr        'id'     => $id ?? '',
691c17acc9fSAndreas Gohr        'user'   => $user,
692c17acc9fSAndreas Gohr        'groups' => $groups
69324870174SAndreas Gohr    ];
694c17acc9fSAndreas Gohr
695cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
696c17acc9fSAndreas Gohr}
697c17acc9fSAndreas Gohr
698c17acc9fSAndreas Gohr/**
699c17acc9fSAndreas Gohr * default ACL check method
700c17acc9fSAndreas Gohr *
701c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
702c17acc9fSAndreas Gohr *
703c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
70442ea7f44SGerrit Uitslag *
705c17acc9fSAndreas Gohr * @param  array $data event data
706c17acc9fSAndreas Gohr * @return int   permission level
707c17acc9fSAndreas Gohr */
708d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
709d868eb89SAndreas Gohr{
710c17acc9fSAndreas Gohr    $id     =& $data['id'];
711c17acc9fSAndreas Gohr    $user   =& $data['user'];
712c17acc9fSAndreas Gohr    $groups =& $data['groups'];
713c17acc9fSAndreas Gohr
714f3f0262cSandi    global $conf;
715f3f0262cSandi    global $AUTH_ACL;
716e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
717d752aedeSAndreas Gohr    global $auth;
718f3f0262cSandi
71985d03f68SAndreas Gohr    // if no ACL is used always return upload rights
720f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7216547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
722bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
723f3f0262cSandi
724074cf26bSandi    //make sure groups is an array
72524870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
726074cf26bSandi
72785d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
728ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
729ab5d26daSAndreas Gohr        return AUTH_ADMIN;
730ab5d26daSAndreas Gohr    }
73185d03f68SAndreas Gohr
732eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
73324870174SAndreas Gohr        $user   = PhpString::strtolower($user);
73424870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
735eb3ce0d5SKazutaka Miyasaka    }
73637ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
73724870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
73885d03f68SAndreas Gohr
7396c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
74037ff2261SSascha Klopp    foreach ($groups as &$group) {
74137ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
74210a76f6fSfrank    }
74310a76f6fSfrank
744f3f0262cSandi    $ns   = getNS($id);
745f3f0262cSandi    $perm = -1;
746f3f0262cSandi
747f3f0262cSandi    //add ALL group
748f3f0262cSandi    $groups[] = '@ALL';
74937ff2261SSascha Klopp
750f3f0262cSandi    //add User
75134aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
752f3f0262cSandi
753f3f0262cSandi    //check exact match first
75421c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
755f3f0262cSandi    if (count($matches)) {
756f3f0262cSandi        foreach ($matches as $match) {
757f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
75821c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
759eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
76024870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
761eb3ce0d5SKazutaka Miyasaka            }
76248d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
76348d7b7a6SDominik Eckelmann                continue;
76448d7b7a6SDominik Eckelmann            }
7658ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
766f3f0262cSandi            if ($acl[2] > $perm) {
767f3f0262cSandi                $perm = $acl[2];
768f3f0262cSandi            }
769f3f0262cSandi        }
770f3f0262cSandi        if ($perm > -1) {
771f3f0262cSandi            //we had a match - return it
772def492a2SGuillaume Turri            return (int) $perm;
773f3f0262cSandi        }
774f3f0262cSandi    }
775f3f0262cSandi
776f3f0262cSandi    //still here? do the namespace checks
777f3f0262cSandi    if ($ns) {
7783e304b55SMichael Hamann        $path = $ns . ':*';
779f3f0262cSandi    } else {
7803e304b55SMichael Hamann        $path = '*'; //root document
781f3f0262cSandi    }
782f3f0262cSandi
783f3f0262cSandi    do {
78421c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
785f3f0262cSandi        if (count($matches)) {
786f3f0262cSandi            foreach ($matches as $match) {
787f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
78821c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
789eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
79024870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
791eb3ce0d5SKazutaka Miyasaka                }
79248d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
79348d7b7a6SDominik Eckelmann                    continue;
79448d7b7a6SDominik Eckelmann                }
7958ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
796f3f0262cSandi                if ($acl[2] > $perm) {
797f3f0262cSandi                    $perm = $acl[2];
798f3f0262cSandi                }
799f3f0262cSandi            }
800f3f0262cSandi            //we had a match - return it
80148d7b7a6SDominik Eckelmann            if ($perm != -1) {
802def492a2SGuillaume Turri                return (int) $perm;
803f3f0262cSandi            }
80448d7b7a6SDominik Eckelmann        }
805f3f0262cSandi        //get next higher namespace
806f3f0262cSandi        $ns = getNS($ns);
807f3f0262cSandi
8083e304b55SMichael Hamann        if ($path != '*') {
8093e304b55SMichael Hamann            $path = $ns . ':*';
8103e304b55SMichael Hamann            if ($path == ':*') $path = '*';
811f3f0262cSandi        } else {
812f3f0262cSandi            //we did this already
813f3f0262cSandi            //looks like there is something wrong with the ACL
814f3f0262cSandi            //break here
815d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
816d5ce66f6SAndreas Gohr            return AUTH_NONE;
817f3f0262cSandi        }
818f3f0262cSandi    } while (1); //this should never loop endless
819ab5d26daSAndreas Gohr    return AUTH_NONE;
820f3f0262cSandi}
821f3f0262cSandi
822f3f0262cSandi/**
8236c2bb100SAndreas Gohr * Encode ASCII special chars
8246c2bb100SAndreas Gohr *
8256c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8266c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8276c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8286c2bb100SAndreas Gohr * urlencoding!).
8296c2bb100SAndreas Gohr *
8306c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8316c2bb100SAndreas Gohr *
8326c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8336c2bb100SAndreas Gohr * @see rawurldecode()
83442ea7f44SGerrit Uitslag *
83542ea7f44SGerrit Uitslag * @param string $name
83642ea7f44SGerrit Uitslag * @param bool $skip_group
83742ea7f44SGerrit Uitslag * @return string
8386c2bb100SAndreas Gohr */
839d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
840d868eb89SAndreas Gohr{
841a424cd8eSchris    global $cache_authname;
842a424cd8eSchris    $cache =& $cache_authname;
84331784267SAndreas Gohr    $name  = (string) $name;
844a424cd8eSchris
84580601d26SAndreas Gohr    // never encode wildcard FS#1955
84680601d26SAndreas Gohr    if ($name == '%USER%') return $name;
847b78bf706Sromain    if ($name == '%GROUP%') return $name;
84880601d26SAndreas Gohr
849a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8502401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
85130f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
85230f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
853dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
854dccd6b2bSAndreas Gohr                substr($name, 1)
855ab5d26daSAndreas Gohr            );
856e838fc2eSAndreas Gohr        } else {
85730f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
85830f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
859dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
860dccd6b2bSAndreas Gohr                $name
861ab5d26daSAndreas Gohr            );
862e838fc2eSAndreas Gohr        }
8636c2bb100SAndreas Gohr    }
8646c2bb100SAndreas Gohr
865a424cd8eSchris    return $cache[$name][$skip_group];
866a424cd8eSchris}
867a424cd8eSchris
86804d68ae4SGerrit Uitslag/**
86904d68ae4SGerrit Uitslag * callback encodes the matches
87004d68ae4SGerrit Uitslag *
87104d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
87204d68ae4SGerrit Uitslag * @return string
87304d68ae4SGerrit Uitslag */
874d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
875d868eb89SAndreas Gohr{
87630f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
87730f6faf0SChristopher Smith}
87830f6faf0SChristopher Smith
8796c2bb100SAndreas Gohr/**
880f3f0262cSandi * Create a pronouncable password
881f3f0262cSandi *
8828a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
8838a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
8848a285f7fSAndreas Gohr *
8854dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
8864dc42f7fSGerrit Uitslag * @return string  pronouncable password
8874dc42f7fSGerrit Uitslag * @throws Exception
8884dc42f7fSGerrit Uitslag *
88915fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
8908a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
89115fae107Sandi *
8924dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
893f3f0262cSandi */
894d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
895d868eb89SAndreas Gohr{
89624870174SAndreas Gohr    $data = [
897d628dcf3SAndreas Gohr        'password' => '',
898d628dcf3SAndreas Gohr        'foruser'  => $foruser
89924870174SAndreas Gohr    ];
9008a285f7fSAndreas Gohr
901e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
9028a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
903f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
904f3f0262cSandi        $v = 'aeiou'; //vowels
905f3f0262cSandi        $a = $c . $v; //both
906987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
907f3f0262cSandi
908987c8d26SAndreas Gohr        //use thre syllables...
909987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
910483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
911483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
912483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
913f3f0262cSandi        }
914987c8d26SAndreas Gohr        //... and add a nice number and special
91543f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9168a285f7fSAndreas Gohr    }
9178a285f7fSAndreas Gohr    $evt->advise_after();
918f3f0262cSandi
9198a285f7fSAndreas Gohr    return $data['password'];
920f3f0262cSandi}
921f3f0262cSandi
922f3f0262cSandi/**
923f3f0262cSandi * Sends a password to the given user
924f3f0262cSandi *
92515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
92642ea7f44SGerrit Uitslag *
927ab5d26daSAndreas Gohr * @param string $user Login name of the user
928ab5d26daSAndreas Gohr * @param string $password The new password in clear text
92915fae107Sandi * @return bool  true on success
930f3f0262cSandi */
931d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
932d868eb89SAndreas Gohr{
933f3f0262cSandi    global $lang;
934e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
935cd52f92dSchris    global $auth;
9366547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
937cd52f92dSchris
938d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9394dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
940f3f0262cSandi
94187ddda95Sandi    if (!$userinfo['mail']) return false;
942f3f0262cSandi
943f3f0262cSandi    $text = rawLocale('password');
94424870174SAndreas Gohr    $trep = [
945d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
946d7169d19SAndreas Gohr        'LOGIN'    => $user,
947d7169d19SAndreas Gohr        'PASSWORD' => $password
94824870174SAndreas Gohr    ];
949f3f0262cSandi
950d7169d19SAndreas Gohr    $mail = new Mailer();
951102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
952d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
953d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
954d7169d19SAndreas Gohr    return $mail->send();
955f3f0262cSandi}
956f3f0262cSandi
957f3f0262cSandi/**
95815fae107Sandi * Register a new user
959f3f0262cSandi *
96015fae107Sandi * This registers a new user - Data is read directly from $_POST
96115fae107Sandi *
96215fae107Sandi * @return bool  true on success, false on any error
9634dc42f7fSGerrit Uitslag * @throws Exception
9644dc42f7fSGerrit Uitslag *
9654dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
966f3f0262cSandi */
967d868eb89SAndreas Gohrfunction register()
968d868eb89SAndreas Gohr{
969f3f0262cSandi    global $lang;
970eb5d07e4Sjan    global $conf;
9714dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
972cd52f92dSchris    global $auth;
97364273335SAndreas Gohr    global $INPUT;
974f3f0262cSandi
97564273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9763a48618aSAnika Henke    if (!actionOK('register')) return false;
977640145a5Sandi
97864273335SAndreas Gohr    // gather input
97964273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
98064273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
98164273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
98264273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
98364273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
984d752aedeSAndreas Gohr
98564273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
986f3f0262cSandi        msg($lang['regmissing'], -1);
987f3f0262cSandi        return false;
988f3f0262cSandi    }
989f3f0262cSandi
990cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
9918a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
99264273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
993bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
994cab2716aSmatthias.grimm        return false;
99564273335SAndreas Gohr    } elseif ($pass != $passchk) {
996bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
997cab2716aSmatthias.grimm        return false;
998cab2716aSmatthias.grimm    }
999cab2716aSmatthias.grimm
1000f3f0262cSandi    //check mail
100164273335SAndreas Gohr    if (!mail_isvalid($email)) {
1002f3f0262cSandi        msg($lang['regbadmail'], -1);
1003f3f0262cSandi        return false;
1004f3f0262cSandi    }
1005f3f0262cSandi
1006f3f0262cSandi    //okay try to create the user
100724870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1008db9faf02SPatrick Brown        msg($lang['regfail'], -1);
1009f3f0262cSandi        return false;
1010f3f0262cSandi    }
1011f3f0262cSandi
1012790b7720SAndreas Gohr    // send notification about the new user
101375d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
101475d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
101502a498e7Schris
1016790b7720SAndreas Gohr    // are we done?
1017cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1018cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1019cab2716aSmatthias.grimm        return true;
1020cab2716aSmatthias.grimm    }
1021cab2716aSmatthias.grimm
1022790b7720SAndreas Gohr    // autogenerated password? then send password to user
102364273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1024f3f0262cSandi        msg($lang['regsuccess'], 1);
1025f3f0262cSandi        return true;
1026f3f0262cSandi    } else {
1027f3f0262cSandi        msg($lang['regmailfail'], -1);
1028f3f0262cSandi        return false;
1029f3f0262cSandi    }
1030f3f0262cSandi}
1031f3f0262cSandi
103210a76f6fSfrank/**
10338b06d178Schris * Update user profile
10348b06d178Schris *
10354dc42f7fSGerrit Uitslag * @throws Exception
10364dc42f7fSGerrit Uitslag *
10378b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10388b06d178Schris */
1039d868eb89SAndreas Gohrfunction updateprofile()
1040d868eb89SAndreas Gohr{
10418b06d178Schris    global $conf;
10428b06d178Schris    global $lang;
1043e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1044cd52f92dSchris    global $auth;
1045bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1046bcc94b2cSAndreas Gohr    global $INPUT;
10478b06d178Schris
1048bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10491b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10508b06d178Schris
10513a48618aSAnika Henke    if (!actionOK('profile')) {
10528b06d178Schris        msg($lang['profna'], -1);
10538b06d178Schris        return false;
10548b06d178Schris    }
10558b06d178Schris
105624870174SAndreas Gohr    $changes         = [];
1057bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1058bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1059bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1060bcc94b2cSAndreas Gohr
1061bcc94b2cSAndreas Gohr    // check misspelled passwords
1062bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1063bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10648b06d178Schris        return false;
10658b06d178Schris    }
10668b06d178Schris
10678b06d178Schris    // clean fullname and email
1068bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1069bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10708b06d178Schris
1071bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
10727d34963bSAndreas Gohr    if (
10737d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1074bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1075ab5d26daSAndreas Gohr    ) {
10768b06d178Schris        msg($lang['profnoempty'], -1);
10778b06d178Schris        return false;
10788b06d178Schris    }
1079bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10808b06d178Schris        msg($lang['regbadmail'], -1);
10818b06d178Schris        return false;
10828b06d178Schris    }
10838b06d178Schris
1084bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
10854c21b7eeSAndreas Gohr
1086bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1087bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1088bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1089bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1090bcc94b2cSAndreas Gohr
1091bcc94b2cSAndreas Gohr    // anything to do?
109224870174SAndreas Gohr    if ($changes === []) {
10938b06d178Schris        msg($lang['profnochange'], -1);
10948b06d178Schris        return false;
10958b06d178Schris    }
10968b06d178Schris
10978b06d178Schris    if ($conf['profileconfirm']) {
1098585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
109971422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
11008b06d178Schris            return false;
11018b06d178Schris        }
11028b06d178Schris    }
11038b06d178Schris
110424870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1105db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1106db9faf02SPatrick Brown        return false;
1107db9faf02SPatrick Brown    }
1108db9faf02SPatrick Brown
110967efd1edSPieter Hollants    if (array_key_exists('pass', $changes) && $changes['pass']) {
1110c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1111a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
111204369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1113585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1114c276e9e8SMarcel Pennewiss    } else {
1115c276e9e8SMarcel Pennewiss        // make sure the session is writable
1116c276e9e8SMarcel Pennewiss        @session_start();
1117c276e9e8SMarcel Pennewiss        // invalidate session cache
1118c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1119c276e9e8SMarcel Pennewiss        session_write_close();
112032ed2b36SAndreas Gohr    }
1121c276e9e8SMarcel Pennewiss
112225b2a98cSMichael Klier    return true;
1123a0b5b007SChris Smith}
1124ab5d26daSAndreas Gohr
112504d68ae4SGerrit Uitslag/**
112604d68ae4SGerrit Uitslag * Delete the current logged-in user
112704d68ae4SGerrit Uitslag *
112804d68ae4SGerrit Uitslag * @return bool true on success, false on any error
112904d68ae4SGerrit Uitslag */
1130d868eb89SAndreas Gohrfunction auth_deleteprofile()
1131d868eb89SAndreas Gohr{
11322a7abf2dSChristopher Smith    global $conf;
11332a7abf2dSChristopher Smith    global $lang;
11344dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11352a7abf2dSChristopher Smith    global $auth;
11362a7abf2dSChristopher Smith    /* @var Input $INPUT */
11372a7abf2dSChristopher Smith    global $INPUT;
11382a7abf2dSChristopher Smith
11392a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11402a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11412a7abf2dSChristopher Smith
11422a7abf2dSChristopher Smith    // action prevented or auth module disallows
11432a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11442a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11452a7abf2dSChristopher Smith        return false;
11462a7abf2dSChristopher Smith    }
11472a7abf2dSChristopher Smith
11482a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11492a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11502a7abf2dSChristopher Smith        return false;
11512a7abf2dSChristopher Smith    }
11522a7abf2dSChristopher Smith
11532a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1154585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11552a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11562a7abf2dSChristopher Smith            return false;
11572a7abf2dSChristopher Smith        }
11582a7abf2dSChristopher Smith    }
11592a7abf2dSChristopher Smith
116024870174SAndreas Gohr    $deleted = [];
1161585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
116224870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
11632a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11642a7abf2dSChristopher Smith        auth_logoff();
11652a7abf2dSChristopher Smith        return true;
11662a7abf2dSChristopher Smith    }
11672a7abf2dSChristopher Smith
11682a7abf2dSChristopher Smith    return false;
11692a7abf2dSChristopher Smith}
11702a7abf2dSChristopher Smith
11718b06d178Schris/**
11728b06d178Schris * Send a  new password
11738b06d178Schris *
11741d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11751d5856cfSAndreas Gohr *
11761d5856cfSAndreas Gohr *   - handling the first request of password reset
11771d5856cfSAndreas Gohr *   - validating the password reset auth token
11781d5856cfSAndreas Gohr *
11794dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
11804dc42f7fSGerrit Uitslag * @throws Exception
11814dc42f7fSGerrit Uitslag *
11824dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
11838b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
11848b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
11858b06d178Schris */
1186d868eb89SAndreas Gohrfunction act_resendpwd()
1187d868eb89SAndreas Gohr{
11888b06d178Schris    global $lang;
11898b06d178Schris    global $conf;
1190e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1191cd52f92dSchris    global $auth;
1192bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1193bcc94b2cSAndreas Gohr    global $INPUT;
11948b06d178Schris
11953a48618aSAnika Henke    if (!actionOK('resendpwd')) {
11968b06d178Schris        msg($lang['resendna'], -1);
11978b06d178Schris        return false;
11988b06d178Schris    }
11998b06d178Schris
1200bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
12018b06d178Schris
12021d5856cfSAndreas Gohr    if ($token) {
1203cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
12041d5856cfSAndreas Gohr
12052401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
120679e79377SAndreas Gohr        if (!file_exists($tfile)) {
12071d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1208bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12091d5856cfSAndreas Gohr            return false;
12101d5856cfSAndreas Gohr        }
12118a9735e3SAndreas Gohr        // token is only valid for 3 days
12128a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12138a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1214bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12151d5856cfSAndreas Gohr            @unlink($tfile);
12168a9735e3SAndreas Gohr            return false;
12178a9735e3SAndreas Gohr        }
12188a9735e3SAndreas Gohr
12198b06d178Schris        $user     = io_readfile($tfile);
12204dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12218b06d178Schris        if (!$userinfo['mail']) {
12228b06d178Schris            msg($lang['resendpwdnouser'], -1);
12238b06d178Schris            return false;
12248b06d178Schris        }
12258b06d178Schris
1226cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1227bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1228bcc94b2cSAndreas Gohr
1229cc204bbdSAndreas Gohr            // password given correctly?
1230bcc94b2cSAndreas Gohr            if (!$pass) return false;
1231bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1232451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1233cc204bbdSAndreas Gohr                return false;
1234cc204bbdSAndreas Gohr            }
1235cc204bbdSAndreas Gohr
1236bcc94b2cSAndreas Gohr            // change it
123724870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1238db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1239cc204bbdSAndreas Gohr                return false;
1240cc204bbdSAndreas Gohr            }
1241cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12428a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
124324870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1244db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12458b06d178Schris                return false;
12468b06d178Schris            }
12478b06d178Schris
12488b06d178Schris            if (auth_sendPassword($user, $pass)) {
12498b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12508b06d178Schris            } else {
12518b06d178Schris                msg($lang['regmailfail'], -1);
12528b06d178Schris            }
1253cc204bbdSAndreas Gohr        }
1254cc204bbdSAndreas Gohr
1255cc204bbdSAndreas Gohr        @unlink($tfile);
12568b06d178Schris        return true;
12571d5856cfSAndreas Gohr    } else {
12581d5856cfSAndreas Gohr        // we're in request phase
12591d5856cfSAndreas Gohr
1260bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
12611d5856cfSAndreas Gohr
1262bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
12631d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12641d5856cfSAndreas Gohr            return false;
12651d5856cfSAndreas Gohr        } else {
1266bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12671d5856cfSAndreas Gohr        }
12681d5856cfSAndreas Gohr
12694dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12701d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
12711d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12721d5856cfSAndreas Gohr            return false;
12731d5856cfSAndreas Gohr        }
12741d5856cfSAndreas Gohr
12751d5856cfSAndreas Gohr        // generate auth token
1276483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12772401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
127824870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
12791d5856cfSAndreas Gohr
12801d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12811d5856cfSAndreas Gohr
12821d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
128324870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
12841d5856cfSAndreas Gohr
1285d7169d19SAndreas Gohr        $mail = new Mailer();
1286d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1287d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1288d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1289d7169d19SAndreas Gohr        if ($mail->send()) {
12901d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
12911d5856cfSAndreas Gohr        } else {
12921d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
12931d5856cfSAndreas Gohr        }
12941d5856cfSAndreas Gohr        return true;
12951d5856cfSAndreas Gohr    }
1296ab5d26daSAndreas Gohr    // never reached
12978b06d178Schris}
12988b06d178Schris
12998b06d178Schris/**
1300b0855b11Sandi * Encrypts a password using the given method and salt
1301b0855b11Sandi *
1302b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1303b0855b11Sandi * is chosen.
1304b0855b11Sandi *
1305b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
130642ea7f44SGerrit Uitslag *
1307ab5d26daSAndreas Gohr * @param string $clear The clear text password
1308ab5d26daSAndreas Gohr * @param string $method The hashing method
1309ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1310b0855b11Sandi * @return  string  The crypted password
1311b0855b11Sandi */
1312d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1313d868eb89SAndreas Gohr{
1314b0855b11Sandi    global $conf;
1315b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
131610a76f6fSfrank
13173a0a2d05SAndreas Gohr    $pass = new PassHash();
13183a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1319b0855b11Sandi
13203a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1321b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13223a0a2d05SAndreas Gohr        return false;
1323b0855b11Sandi    }
13243a0a2d05SAndreas Gohr
13253a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1326b0855b11Sandi}
1327b0855b11Sandi
1328b0855b11Sandi/**
1329b0855b11Sandi * Verifies a cleartext password against a crypted hash
1330b0855b11Sandi *
1331ab5d26daSAndreas Gohr * @param string $clear The clear text password
1332ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1333ab5d26daSAndreas Gohr * @return bool true if both match
13344dc42f7fSGerrit Uitslag * @throws Exception
13354dc42f7fSGerrit Uitslag *
13364dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1337b0855b11Sandi */
1338d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1339d868eb89SAndreas Gohr{
13403a0a2d05SAndreas Gohr    $pass = new PassHash();
13413a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1342b0855b11Sandi}
1343340756e4Sandi
1344a0b5b007SChris Smith/**
1345a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1346a0b5b007SChris Smith *
1347a0b5b007SChris Smith * @param string  $user       username
1348a0b5b007SChris Smith * @param string  $pass       encrypted password
1349a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1350ab5d26daSAndreas Gohr * @return bool
1351a0b5b007SChris Smith */
1352d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1353d868eb89SAndreas Gohr{
1354a0b5b007SChris Smith    global $conf;
1355e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1356a0b5b007SChris Smith    global $auth;
135779d00841SOliver Geisen    global $USERINFO;
1358a0b5b007SChris Smith
13596547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1360a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1361a0b5b007SChris Smith
1362a0b5b007SChris Smith    // set cookie
1363645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
136473ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1365c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1366bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1367bf8392ebSAndreas Gohr        'expires' => $time,
1368bf8392ebSAndreas Gohr        'path' => $cookieDir,
1369bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1370bf8392ebSAndreas Gohr        'httponly' => true,
1371486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1372bf8392ebSAndreas Gohr    ]);
137355a71a16SGerrit Uitslag
1374a0b5b007SChris Smith    // set session
1375a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1376234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1377a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1378a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1379a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1380ab5d26daSAndreas Gohr
1381ab5d26daSAndreas Gohr    return true;
1382a0b5b007SChris Smith}
1383a0b5b007SChris Smith
1384645c0a36SAndreas Gohr/**
1385645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1386645c0a36SAndreas Gohr *
1387645c0a36SAndreas Gohr * @returns array
1388645c0a36SAndreas Gohr */
1389d868eb89SAndreas Gohrfunction auth_getCookie()
1390d868eb89SAndreas Gohr{
1391c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
139224870174SAndreas Gohr        return [null, null, null];
1393c66972f2SAdrian Lang    }
139424870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1395645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1396645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1397645c0a36SAndreas Gohr    $user   = base64_decode($user);
139824870174SAndreas Gohr    return [$user, $sticky, $pass];
1399645c0a36SAndreas Gohr}
1400645c0a36SAndreas Gohr
1401e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1402