xref: /dokuwiki/inc/auth.php (revision b9cda918faccf704038ebb05823e6e2e9afc5507)
1ed7b5f09Sandi<?php
2d4f83172SAndreas Gohr
315fae107Sandi/**
415fae107Sandi * Authentication library
515fae107Sandi *
615fae107Sandi * Including this file will automatically try to login
715fae107Sandi * a user by calling auth_login()
815fae107Sandi *
915fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
1015fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1115fae107Sandi */
12d4f83172SAndreas Gohr
131cedacf2SAndreas Gohruse dokuwiki\ErrorHandler;
14cf927d07Ssplitbrainuse dokuwiki\JWT;
1524870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1696348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1796348f27SAndreas Gohruse dokuwiki\Extension\Event;
1896348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
19c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
2075d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
21927933f5SAndreas Gohruse phpseclib3\Crypt\AES;
22927933f5SAndreas Gohruse phpseclib3\Crypt\Common\SymmetricKey;
231cedacf2SAndreas Gohruse phpseclib3\Exception\BadDecryptionException;
24c3cc6e05SAndreas Gohr
2516905344SAndreas Gohr/**
2616905344SAndreas Gohr * Initialize the auth system.
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * This function is automatically called at the end of init.php
2916905344SAndreas Gohr *
3016905344SAndreas Gohr * This used to be the main() of the auth.php
3116905344SAndreas Gohr *
3216905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3316905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
34ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
35ab5d26daSAndreas Gohr * @return bool
3616905344SAndreas Gohr */
37d868eb89SAndreas Gohrfunction auth_setup()
38d868eb89SAndreas Gohr{
39742c66f8Schris    global $conf;
40e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4103c4aec3Schris    global $auth;
42bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
43bcc94b2cSAndreas Gohr    global $INPUT;
449a9714acSDominik Eckelmann    global $AUTH_ACL;
459a9714acSDominik Eckelmann    global $lang;
463a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
479c29eea5SJan Schumann    global $plugin_controller;
4824870174SAndreas Gohr    $AUTH_ACL = [];
4903c4aec3Schris
50*b9cda918SAndreas Gohr    // unset REMOTE_USER if empty
51*b9cda918SAndreas Gohr    if ($INPUT->server->str('REMOTE_USER') === '') {
52*b9cda918SAndreas Gohr        $INPUT->server->remove('REMOTE_USER');
53*b9cda918SAndreas Gohr    }
54*b9cda918SAndreas Gohr
5516905344SAndreas Gohr    if (!$conf['useacl']) return false;
5616905344SAndreas Gohr
579c29eea5SJan Schumann    // try to load auth backend from plugins
589c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
599c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
60f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
619c29eea5SJan Schumann            break;
629c29eea5SJan Schumann        }
639c29eea5SJan Schumann    }
648b06d178Schris
656547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) {
6671c734a9SGerrit Uitslag        msg($lang['authtempfail'], -1);
673094e817SAndreas Gohr        return false;
683094e817SAndreas Gohr    }
698b06d178Schris
706416b708SMichael Hamann    if ($auth->success == false) {
710f4f4adfSAndreas Gohr        // degrade to unauthenticated user
72ecad51ddSAndreas Gohr        $auth = null;
730f4f4adfSAndreas Gohr        auth_logoff();
74cd52f92dSchris        msg($lang['authtempfail'], -1);
756416b708SMichael Hamann        return false;
76d2dde4ebSMatthias Grimm    }
7716905344SAndreas Gohr
7816905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
79bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
80bcc94b2cSAndreas Gohr    if (!$conf['rememberme']) $INPUT->set('r', false);
81bbbd6568SAndreas Gohr
8262bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
8362bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
8462bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
8562bf3ac0SDamien Regad    if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
8662bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
8724870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
88528ddc7cSAndreas Gohr    }
89528ddc7cSAndreas Gohr
901e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
9103062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
9203062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
9303062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
94bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
951e8c9c90SAndreas Gohr    }
961e8c9c90SAndreas Gohr
97395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9893a7873eSAndreas Gohr    if (true === $auth->success) {
99395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
100395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
101f4476bd9SJan Schumann    }
102191bb90aSAndreas Gohr
103455aa67eSAndreas Gohr    if (!auth_tokenlogin()) {
10481e99965SPhy        $ok = null;
105455aa67eSAndreas Gohr
1066547cfc7SGerrit Uitslag        if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
10781e99965SPhy            $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
10881e99965SPhy        }
10981e99965SPhy
11081e99965SPhy        if ($ok === null) {
11181e99965SPhy            // external trust mechanism not in place, or returns no result,
11281e99965SPhy            // then attempt auth_login
11324870174SAndreas Gohr            $evdata = [
114bcc94b2cSAndreas Gohr                'user' => $INPUT->str('u'),
115bcc94b2cSAndreas Gohr                'password' => $INPUT->str('p'),
116bcc94b2cSAndreas Gohr                'sticky' => $INPUT->bool('r'),
117bcc94b2cSAndreas Gohr                'silent' => $INPUT->bool('http_credentials')
11824870174SAndreas Gohr            ];
119cbb44eabSAndreas Gohr            Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
120f5cb575dSAndreas Gohr        }
121455aa67eSAndreas Gohr    }
122f5cb575dSAndreas Gohr
12316905344SAndreas Gohr    //load ACL into a global array XXX
12475c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
125ab5d26daSAndreas Gohr
126ab5d26daSAndreas Gohr    return true;
12775c93b77SAndreas Gohr}
12875c93b77SAndreas Gohr
12975c93b77SAndreas Gohr/**
13075c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
13175c93b77SAndreas Gohr *
13275c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13342ea7f44SGerrit Uitslag *
134ab5d26daSAndreas Gohr * @return array
13575c93b77SAndreas Gohr */
136d868eb89SAndreas Gohrfunction auth_loadACL()
137d868eb89SAndreas Gohr{
13875c93b77SAndreas Gohr    global $config_cascade;
139b78bf706Sromain    global $USERINFO;
140585bf44eSChristopher Smith    /* @var Input $INPUT */
141585bf44eSChristopher Smith    global $INPUT;
14275c93b77SAndreas Gohr
14324870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
14475c93b77SAndreas Gohr
14575c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
14675c93b77SAndreas Gohr
14724870174SAndreas Gohr    $out = [];
1489ce556d2SAndreas Gohr    foreach ($acl as $line) {
1499ce556d2SAndreas Gohr        $line = trim($line);
1502401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
15124870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
15232e82180SAndreas Gohr
153443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
154ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
155ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
156585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
157ad3d68d7SChristopher Smith
158585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
159585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
160ad3d68d7SChristopher Smith        }
161ad3d68d7SChristopher Smith
162ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1639ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
164ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
16506f34f54SPhy            if (isset($USERINFO['grps'])) {
1669ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
167b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
16832e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
16932e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
170b78bf706Sromain                }
17106f34f54SPhy            }
17232e82180SAndreas Gohr        } else {
17332e82180SAndreas Gohr            $out[] = "$id\t$rest";
174a8fe108bSGuy Brand        }
17511799630Sandi    }
1769ce556d2SAndreas Gohr
17732e82180SAndreas Gohr    return $out;
178f3f0262cSandi}
179f3f0262cSandi
180ab5d26daSAndreas Gohr/**
181455aa67eSAndreas Gohr * Try a token login
182455aa67eSAndreas Gohr *
183455aa67eSAndreas Gohr * @return bool true if token login succeeded
184455aa67eSAndreas Gohr */
185cf927d07Ssplitbrainfunction auth_tokenlogin()
186cf927d07Ssplitbrain{
187455aa67eSAndreas Gohr    global $USERINFO;
188455aa67eSAndreas Gohr    global $INPUT;
189455aa67eSAndreas Gohr    /** @var DokuWiki_Auth_Plugin $auth */
190455aa67eSAndreas Gohr    global $auth;
191455aa67eSAndreas Gohr    if (!$auth) return false;
192455aa67eSAndreas Gohr
1937ffd5bd2SAndreas Gohr    // get the headers, either from Apache or from $_SERVER
1946fdb83b6SAndreas Gohr    if (function_exists('getallheaders')) {
1956fdb83b6SAndreas Gohr        $headers = array_change_key_case(getallheaders());
196455aa67eSAndreas Gohr    } else {
1977ffd5bd2SAndreas Gohr        $headers = [];
1987ffd5bd2SAndreas Gohr        foreach ($_SERVER as $key => $value) {
1997ffd5bd2SAndreas Gohr            if (substr($key, 0, 5) === 'HTTP_') {
2007ffd5bd2SAndreas Gohr                $headers[strtolower(substr($key, 5))] = $value;
201455aa67eSAndreas Gohr            }
2027ffd5bd2SAndreas Gohr        }
2037ffd5bd2SAndreas Gohr    }
2047ffd5bd2SAndreas Gohr
2057ffd5bd2SAndreas Gohr    // check authorization header
2067ffd5bd2SAndreas Gohr    if (isset($headers['authorization'])) {
2077ffd5bd2SAndreas Gohr        [$type, $token] = sexplode(' ', $headers['authorization'], 2);
2087ffd5bd2SAndreas Gohr        if ($type !== 'Bearer') $token = ''; // not the token we want
2097ffd5bd2SAndreas Gohr    }
2107ffd5bd2SAndreas Gohr
2117ffd5bd2SAndreas Gohr    // check x-dokuwiki-token header
2127ffd5bd2SAndreas Gohr    if (isset($headers['x-dokuwiki-token'])) {
2137ffd5bd2SAndreas Gohr        $token = $headers['x-dokuwiki-token'];
2147ffd5bd2SAndreas Gohr    }
2157ffd5bd2SAndreas Gohr
2167ffd5bd2SAndreas Gohr    if (empty($token)) return false;
217455aa67eSAndreas Gohr
218455aa67eSAndreas Gohr    // check token
219455aa67eSAndreas Gohr    try {
220cf927d07Ssplitbrain        $authtoken = JWT::validate($token);
221455aa67eSAndreas Gohr    } catch (Exception $e) {
222455aa67eSAndreas Gohr        msg(hsc($e->getMessage()), -1);
223455aa67eSAndreas Gohr        return false;
224455aa67eSAndreas Gohr    }
225455aa67eSAndreas Gohr
226455aa67eSAndreas Gohr    // fetch user info from backend
227455aa67eSAndreas Gohr    $user = $authtoken->getUser();
228455aa67eSAndreas Gohr    $USERINFO = $auth->getUserData($user);
229455aa67eSAndreas Gohr    if (!$USERINFO) return false;
230455aa67eSAndreas Gohr
231455aa67eSAndreas Gohr    // the code is correct, set up user
232455aa67eSAndreas Gohr    $INPUT->server->set('REMOTE_USER', $user);
233455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
234455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
235455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
236455aa67eSAndreas Gohr
237455aa67eSAndreas Gohr    return true;
238455aa67eSAndreas Gohr}
239455aa67eSAndreas Gohr
240455aa67eSAndreas Gohr/**
241ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
242ab5d26daSAndreas Gohr *
24342ea7f44SGerrit Uitslag * @param array $evdata
244ab5d26daSAndreas Gohr * @return bool
2454dc42f7fSGerrit Uitslag * @throws Exception
246ab5d26daSAndreas Gohr */
247d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
248d868eb89SAndreas Gohr{
249ab5d26daSAndreas Gohr    return auth_login(
250ab5d26daSAndreas Gohr        $evdata['user'],
251b5ee21aaSAdrian Lang        $evdata['password'],
252b5ee21aaSAdrian Lang        $evdata['sticky'],
253ab5d26daSAndreas Gohr        $evdata['silent']
254ab5d26daSAndreas Gohr    );
255b5ee21aaSAdrian Lang}
256b5ee21aaSAdrian Lang
257f3f0262cSandi/**
258f3f0262cSandi * This tries to login the user based on the sent auth credentials
259f3f0262cSandi *
260f3f0262cSandi * The authentication works like this: if a username was given
26115fae107Sandi * a new login is assumed and user/password are checked. If they
26215fae107Sandi * are correct the password is encrypted with blowfish and stored
26315fae107Sandi * together with the username in a cookie - the same info is stored
26415fae107Sandi * in the session, too. Additonally a browserID is stored in the
26515fae107Sandi * session.
26615fae107Sandi *
26715fae107Sandi * If no username was given the cookie is checked: if the username,
26815fae107Sandi * crypted password and browserID match between session and cookie
26915fae107Sandi * no further testing is done and the user is accepted
27015fae107Sandi *
27115fae107Sandi * If a cookie was found but no session info was availabe the
272136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
27315fae107Sandi * together with username rechecked by calling this function again.
274f3f0262cSandi *
275f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
276f3f0262cSandi * are set.
27715fae107Sandi *
27815fae107Sandi * @param string $user Username
27915fae107Sandi * @param string $pass Cleartext Password
28015fae107Sandi * @param bool $sticky Cookie should not expire
281f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
28215fae107Sandi * @return bool true on successful auth
2834dc42f7fSGerrit Uitslag * @throws Exception
2844dc42f7fSGerrit Uitslag *
2854dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
286f3f0262cSandi */
287d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
288d868eb89SAndreas Gohr{
289f3f0262cSandi    global $USERINFO;
290f3f0262cSandi    global $conf;
291f3f0262cSandi    global $lang;
292e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
293cd52f92dSchris    global $auth;
294585bf44eSChristopher Smith    /* @var Input $INPUT */
295585bf44eSChristopher Smith    global $INPUT;
296ab5d26daSAndreas Gohr
2976547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
298beca106aSAdrian Lang
299bbbd6568SAndreas Gohr    if (!empty($user)) {
300132bdbfeSandi        //usual login
3015e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
302132bdbfeSandi            // make logininfo globally available
303585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
30430d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
30504369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
306132bdbfeSandi            return true;
307f3f0262cSandi        } else {
308f3f0262cSandi            //invalid credentials - log off
309f8b1e4e7SAndreas Gohr            if (!$silent) {
310f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
311f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
312f8b1e4e7SAndreas Gohr            }
313f3f0262cSandi            auth_logoff();
314132bdbfeSandi            return false;
315f3f0262cSandi        }
316f3f0262cSandi    } else {
317132bdbfeSandi        // read cookie information
31824870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
319132bdbfeSandi        if ($user && $pass) {
320132bdbfeSandi            // we got a cookie - see if we can trust it
321fa7c70ffSAdrian Lang
322fa7c70ffSAdrian Lang            // get session info
3230058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
324fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
3257d34963bSAndreas Gohr                if (
3267d34963bSAndreas Gohr                    isset($session) &&
3277172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3284c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
329132bdbfeSandi                    ($session['user'] == $user) &&
330234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
331ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
332ab5d26daSAndreas Gohr                ) {
333132bdbfeSandi                    // he has session, cookie and browser right - let him in
334585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
335132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
336132bdbfeSandi                    return true;
337132bdbfeSandi                }
3380058ae75SDamien Regad            }
339f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
34030d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
34104369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
342f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
343132bdbfeSandi        }
344132bdbfeSandi    }
345f3f0262cSandi    //just to be sure
346883179a4SAndreas Gohr    auth_logoff(true);
347132bdbfeSandi    return false;
348f3f0262cSandi}
349132bdbfeSandi
350132bdbfeSandi/**
351136ce040Sandi * Builds a pseudo UID from browser and IP data
352132bdbfeSandi *
353132bdbfeSandi * This is neither unique nor unfakable - still it adds some
354136ce040Sandi * security. Using the first part of the IP makes sure
35580b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
35615fae107Sandi *
35715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
35815fae107Sandi *
359b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
360132bdbfeSandi */
361d868eb89SAndreas Gohrfunction auth_browseruid()
362d868eb89SAndreas Gohr{
363585bf44eSChristopher Smith    /* @var Input $INPUT */
364585bf44eSChristopher Smith    global $INPUT;
365585bf44eSChristopher Smith
3662f9daf16SAndreas Gohr    $ip = clientIP(true);
367b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
368b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
369b7c67f83SAndreas Gohr
370b7c67f83SAndreas Gohr    $uid = implode("\n", [
371b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
372b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
373b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
374b7c67f83SAndreas Gohr    ]);
375b13c0e1aSAdaKaleh    return hash('sha256', $uid);
376132bdbfeSandi}
377132bdbfeSandi
378132bdbfeSandi/**
379132bdbfeSandi * Creates a random key to encrypt the password in cookies
38015fae107Sandi *
38115fae107Sandi * This function tries to read the password for encrypting
38298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
38315fae107Sandi * if no such file is found a random key is created and
38415fae107Sandi * and stored in this file.
38515fae107Sandi *
38632ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
38730d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
38815fae107Sandi * @return  string
3894dc42f7fSGerrit Uitslag * @throws Exception
3904dc42f7fSGerrit Uitslag *
3914dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
392132bdbfeSandi */
393d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
394d868eb89SAndreas Gohr{
395a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
396fe745becSMichael Große        return 'test';
397a1fe3c9cSMichael Große    }
398132bdbfeSandi    global $conf;
39998407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
40030d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
40130d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
40230d544a4SMichael Hamann    }
403132bdbfeSandi    $salt = io_readFile($file);
404132bdbfeSandi    if (empty($salt)) {
40530d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
406132bdbfeSandi        io_saveFile($file, $salt);
407132bdbfeSandi    }
40832ed2b36SAndreas Gohr    if ($addsession) {
40932ed2b36SAndreas Gohr        $salt .= session_id();
41032ed2b36SAndreas Gohr    }
411132bdbfeSandi    return $salt;
412f3f0262cSandi}
413f3f0262cSandi
414f3f0262cSandi/**
4157a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
416483b6238SMichael Hamann *
4177a33d2f8SNiklas Keller * @param int $length number of bytes
4187a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
4194dc42f7fSGerrit Uitslag * @throws Exception
4204dc42f7fSGerrit Uitslag *
4214dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
422483b6238SMichael Hamann */
423d868eb89SAndreas Gohrfunction auth_randombytes($length)
424d868eb89SAndreas Gohr{
4257a33d2f8SNiklas Keller    return random_bytes($length);
426483b6238SMichael Hamann}
427483b6238SMichael Hamann
428483b6238SMichael Hamann/**
4297a33d2f8SNiklas Keller * Cryptographically secure random number generator.
430483b6238SMichael Hamann *
431483b6238SMichael Hamann * @param int $min
432483b6238SMichael Hamann * @param int $max
433483b6238SMichael Hamann * @return int
4344dc42f7fSGerrit Uitslag * @throws Exception
4354dc42f7fSGerrit Uitslag *
4364dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
437483b6238SMichael Hamann */
438d868eb89SAndreas Gohrfunction auth_random($min, $max)
439d868eb89SAndreas Gohr{
4407a33d2f8SNiklas Keller    return random_int($min, $max);
441483b6238SMichael Hamann}
442483b6238SMichael Hamann
443483b6238SMichael Hamann/**
44404369c3eSMichael Hamann * Encrypt data using the given secret using AES
44504369c3eSMichael Hamann *
44604369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
44704369c3eSMichael Hamann * using pbkdf2.
44804369c3eSMichael Hamann *
44904369c3eSMichael Hamann * @param string $data The data that shall be encrypted
45004369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
45104369c3eSMichael Hamann * @return string The ciphertext
4524dc42f7fSGerrit Uitslag * @throws Exception
45304369c3eSMichael Hamann */
454d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
455d868eb89SAndreas Gohr{
45604369c3eSMichael Hamann    $iv     = auth_randombytes(16);
457927933f5SAndreas Gohr    $cipher = new AES('cbc');
45847e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
459927933f5SAndreas Gohr    $cipher->setIV($iv);
46004369c3eSMichael Hamann
4617b650cefSMichael Hamann    /*
4627b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4637b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4647b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4657b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4667b650cefSMichael Hamann    */
46704369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
46804369c3eSMichael Hamann}
46904369c3eSMichael Hamann
47004369c3eSMichael Hamann/**
47104369c3eSMichael Hamann * Decrypt the given AES ciphertext
47204369c3eSMichael Hamann *
47304369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
47404369c3eSMichael Hamann *
47504369c3eSMichael Hamann * @param string $ciphertext The encrypted data
47604369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
4771cedacf2SAndreas Gohr * @return string|null The decrypted data
47804369c3eSMichael Hamann */
479d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
480d868eb89SAndreas Gohr{
4817b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
482927933f5SAndreas Gohr    $cipher = new AES('cbc');
48347e9ed0eSAndreas Gohr    $cipher->setPassword($secret, 'pbkdf2', 'sha1', 'phpseclib');
4847b650cefSMichael Hamann    $cipher->setIV($iv);
48504369c3eSMichael Hamann
4861cedacf2SAndreas Gohr    try {
4877b650cefSMichael Hamann        return $cipher->decrypt(substr($ciphertext, 16));
4881cedacf2SAndreas Gohr    } catch (BadDecryptionException $e) {
4891cedacf2SAndreas Gohr        ErrorHandler::logException($e);
4901cedacf2SAndreas Gohr        return null;
4911cedacf2SAndreas Gohr    }
49204369c3eSMichael Hamann}
49304369c3eSMichael Hamann
49404369c3eSMichael Hamann/**
495883179a4SAndreas Gohr * Log out the current user
496883179a4SAndreas Gohr *
497f3f0262cSandi * This clears all authentication data and thus log the user
498883179a4SAndreas Gohr * off. It also clears session data.
49915fae107Sandi *
50015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
50142ea7f44SGerrit Uitslag *
502883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
503f3f0262cSandi */
504d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
505d868eb89SAndreas Gohr{
506f3f0262cSandi    global $conf;
507f3f0262cSandi    global $USERINFO;
508e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
5095298a619SAndreas Gohr    global $auth;
510585bf44eSChristopher Smith    /* @var Input $INPUT */
511585bf44eSChristopher Smith    global $INPUT;
51237065e65Sandi
513d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
514e9621d07SAndreas Gohr    @session_start();
515e9621d07SAndreas Gohr
516e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
517e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
518e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
519e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
520e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
521e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
522883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
523e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
524585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
525132bdbfeSandi    $USERINFO = null; //FIXME
526f5c6743cSAndreas Gohr
52773ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
528bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
529bf8392ebSAndreas Gohr        'expires' => time() - 600000,
530bf8392ebSAndreas Gohr        'path' => $cookieDir,
531bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
532bf8392ebSAndreas Gohr        'httponly' => true,
533486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
534bf8392ebSAndreas Gohr    ]);
5355298a619SAndreas Gohr
5366547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5376547cfc7SGerrit Uitslag        $auth->logOff();
5386547cfc7SGerrit Uitslag    }
539f3f0262cSandi}
540f3f0262cSandi
541f3f0262cSandi/**
542f8cc712eSAndreas Gohr * Check if a user is a manager
543f8cc712eSAndreas Gohr *
544f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
545f8cc712eSAndreas Gohr * user.
546f8cc712eSAndreas Gohr *
547f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
548f8cc712eSAndreas Gohr *
549ab5d26daSAndreas Gohr * @param string $user Username
550ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
551ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
55210396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
553ab5d26daSAndreas Gohr * @return bool
55496348f27SAndreas Gohr * @see    auth_isadmin
55596348f27SAndreas Gohr *
55696348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
557f8cc712eSAndreas Gohr */
558d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
559d868eb89SAndreas Gohr{
560f8cc712eSAndreas Gohr    global $conf;
561f8cc712eSAndreas Gohr    global $USERINFO;
562e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
563d752aedeSAndreas Gohr    global $auth;
564585bf44eSChristopher Smith    /* @var Input $INPUT */
565585bf44eSChristopher Smith    global $INPUT;
566585bf44eSChristopher Smith
567f8cc712eSAndreas Gohr
5686547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
569c66972f2SAdrian Lang    if (is_null($user)) {
570585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
571c66972f2SAdrian Lang            return false;
572c66972f2SAdrian Lang        } else {
573585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
574c66972f2SAdrian Lang        }
575c66972f2SAdrian Lang    }
576d6dc956fSAndreas Gohr    if (is_null($groups)) {
5771525c228SAnna Dabrowska        // checking the logged in user, or another one?
5781525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5791525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
58066b108d6SAnna Dabrowska        } else {
5816cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5826cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
58366b108d6SAnna Dabrowska        }
584e259aa79SAndreas Gohr    }
585e259aa79SAndreas Gohr
58696348f27SAndreas Gohr    // prefer cached result
58796348f27SAndreas Gohr    static $cache = [];
58810396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
58996348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
590d6dc956fSAndreas Gohr        // check superuser match
59196348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
59200ce12daSChris Smith
59396348f27SAndreas Gohr        // check managers
59496348f27SAndreas Gohr        if (!$ok && !$adminonly) {
59596348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
59696348f27SAndreas Gohr        }
59796348f27SAndreas Gohr
59896348f27SAndreas Gohr        $cache[$cachekey] = $ok;
59996348f27SAndreas Gohr    }
60096348f27SAndreas Gohr
60196348f27SAndreas Gohr    return $cache[$cachekey];
602f8cc712eSAndreas Gohr}
603f8cc712eSAndreas Gohr
604f8cc712eSAndreas Gohr/**
605f8cc712eSAndreas Gohr * Check if a user is admin
606f8cc712eSAndreas Gohr *
607f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
608f8cc712eSAndreas Gohr *
609f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
610f8cc712eSAndreas Gohr *
61196348f27SAndreas Gohr * @param string $user Username
61296348f27SAndreas Gohr * @param array $groups List of groups the user is in
61310396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
61496348f27SAndreas Gohr * @return bool
615f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
616ab5d26daSAndreas Gohr * @see auth_ismanager()
61742ea7f44SGerrit Uitslag *
618f8cc712eSAndreas Gohr */
619d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
620d868eb89SAndreas Gohr{
62196348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
622f8cc712eSAndreas Gohr}
623f8cc712eSAndreas Gohr
624d6dc956fSAndreas Gohr/**
625d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
626d6dc956fSAndreas Gohr * users and groups to determine membership status
627d6dc956fSAndreas Gohr *
628d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
629d6dc956fSAndreas Gohr *
63042ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
63142ea7f44SGerrit Uitslag * @param string $user       user to match against
63242ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6335446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
634d6dc956fSAndreas Gohr */
635d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
636d868eb89SAndreas Gohr{
637e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
638d6dc956fSAndreas Gohr    global $auth;
6396547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
640d6dc956fSAndreas Gohr
641d6dc956fSAndreas Gohr    // clean user and groups
6424f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
64324870174SAndreas Gohr        $user   = PhpString::strtolower($user);
64424870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
645d6dc956fSAndreas Gohr    }
646d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
64724870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
648d6dc956fSAndreas Gohr
649d6dc956fSAndreas Gohr    // extract the memberlist
650d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
651d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
652d6dc956fSAndreas Gohr    $members = array_unique($members);
653d6dc956fSAndreas Gohr    $members = array_filter($members);
654d6dc956fSAndreas Gohr
655d6dc956fSAndreas Gohr    // compare cleaned values
656d6dc956fSAndreas Gohr    foreach ($members as $member) {
657e5204a12SJurgen Hart        if ($member == '@ALL') return true;
65824870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
659d6dc956fSAndreas Gohr        if ($member[0] == '@') {
660d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
661d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
662d6dc956fSAndreas Gohr        } else {
663d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
664d6dc956fSAndreas Gohr            if ($member == $user) return true;
665d6dc956fSAndreas Gohr        }
666d6dc956fSAndreas Gohr    }
667d6dc956fSAndreas Gohr
668d6dc956fSAndreas Gohr    // still here? not a member!
669d6dc956fSAndreas Gohr    return false;
670d6dc956fSAndreas Gohr}
671d6dc956fSAndreas Gohr
672f8cc712eSAndreas Gohr/**
67315fae107Sandi * Convinience function for auth_aclcheck()
67415fae107Sandi *
67515fae107Sandi * This checks the permissions for the current user
67615fae107Sandi *
67715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
67815fae107Sandi *
6791698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
68015fae107Sandi * @return int          permission level
681f3f0262cSandi */
682d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
683d868eb89SAndreas Gohr{
684f3f0262cSandi    global $conf;
685f3f0262cSandi    global $USERINFO;
686585bf44eSChristopher Smith    /* @var Input $INPUT */
687585bf44eSChristopher Smith    global $INPUT;
688f3f0262cSandi    # if no ACL is used always return upload rights
689f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
69024870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
691f3f0262cSandi}
692f3f0262cSandi
693f3f0262cSandi/**
694c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
69515fae107Sandi *
69615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
69742ea7f44SGerrit Uitslag *
698c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6991698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
70015fae107Sandi * @param  string       $user   Username
7013272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
70215fae107Sandi * @return int             permission level
703f3f0262cSandi */
704d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
705d868eb89SAndreas Gohr{
70624870174SAndreas Gohr    $data = [
707bf8f8509SAndreas Gohr        'id'     => $id ?? '',
708c17acc9fSAndreas Gohr        'user'   => $user,
709c17acc9fSAndreas Gohr        'groups' => $groups
71024870174SAndreas Gohr    ];
711c17acc9fSAndreas Gohr
712cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
713c17acc9fSAndreas Gohr}
714c17acc9fSAndreas Gohr
715c17acc9fSAndreas Gohr/**
716c17acc9fSAndreas Gohr * default ACL check method
717c17acc9fSAndreas Gohr *
718c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
719c17acc9fSAndreas Gohr *
720c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
72142ea7f44SGerrit Uitslag *
722c17acc9fSAndreas Gohr * @param  array $data event data
723c17acc9fSAndreas Gohr * @return int   permission level
724c17acc9fSAndreas Gohr */
725d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
726d868eb89SAndreas Gohr{
727c17acc9fSAndreas Gohr    $id     =& $data['id'];
728c17acc9fSAndreas Gohr    $user   =& $data['user'];
729c17acc9fSAndreas Gohr    $groups =& $data['groups'];
730c17acc9fSAndreas Gohr
731f3f0262cSandi    global $conf;
732f3f0262cSandi    global $AUTH_ACL;
733e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
734d752aedeSAndreas Gohr    global $auth;
735f3f0262cSandi
73685d03f68SAndreas Gohr    // if no ACL is used always return upload rights
737f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7386547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
739bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
740f3f0262cSandi
741074cf26bSandi    //make sure groups is an array
74224870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
743074cf26bSandi
74485d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
745ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
746ab5d26daSAndreas Gohr        return AUTH_ADMIN;
747ab5d26daSAndreas Gohr    }
74885d03f68SAndreas Gohr
749eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
75024870174SAndreas Gohr        $user   = PhpString::strtolower($user);
75124870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
752eb3ce0d5SKazutaka Miyasaka    }
75337ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
75424870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
75585d03f68SAndreas Gohr
7566c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
75737ff2261SSascha Klopp    foreach ($groups as &$group) {
75837ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
75910a76f6fSfrank    }
76010a76f6fSfrank
761f3f0262cSandi    $ns   = getNS($id);
762f3f0262cSandi    $perm = -1;
763f3f0262cSandi
764f3f0262cSandi    //add ALL group
765f3f0262cSandi    $groups[] = '@ALL';
76637ff2261SSascha Klopp
767f3f0262cSandi    //add User
76834aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
769f3f0262cSandi
770f3f0262cSandi    //check exact match first
77121c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
772f3f0262cSandi    if (count($matches)) {
773f3f0262cSandi        foreach ($matches as $match) {
774f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
77521c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
776eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
77724870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
778eb3ce0d5SKazutaka Miyasaka            }
77948d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
78048d7b7a6SDominik Eckelmann                continue;
78148d7b7a6SDominik Eckelmann            }
7828ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
783f3f0262cSandi            if ($acl[2] > $perm) {
784f3f0262cSandi                $perm = $acl[2];
785f3f0262cSandi            }
786f3f0262cSandi        }
787f3f0262cSandi        if ($perm > -1) {
788f3f0262cSandi            //we had a match - return it
789def492a2SGuillaume Turri            return (int) $perm;
790f3f0262cSandi        }
791f3f0262cSandi    }
792f3f0262cSandi
793f3f0262cSandi    //still here? do the namespace checks
794f3f0262cSandi    if ($ns) {
7953e304b55SMichael Hamann        $path = $ns . ':*';
796f3f0262cSandi    } else {
7973e304b55SMichael Hamann        $path = '*'; //root document
798f3f0262cSandi    }
799f3f0262cSandi
800f3f0262cSandi    do {
80121c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
802f3f0262cSandi        if (count($matches)) {
803f3f0262cSandi            foreach ($matches as $match) {
804f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
80521c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
806eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
80724870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
808eb3ce0d5SKazutaka Miyasaka                }
80948d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
81048d7b7a6SDominik Eckelmann                    continue;
81148d7b7a6SDominik Eckelmann                }
8128ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
813f3f0262cSandi                if ($acl[2] > $perm) {
814f3f0262cSandi                    $perm = $acl[2];
815f3f0262cSandi                }
816f3f0262cSandi            }
817f3f0262cSandi            //we had a match - return it
81848d7b7a6SDominik Eckelmann            if ($perm != -1) {
819def492a2SGuillaume Turri                return (int) $perm;
820f3f0262cSandi            }
82148d7b7a6SDominik Eckelmann        }
822f3f0262cSandi        //get next higher namespace
823f3f0262cSandi        $ns = getNS($ns);
824f3f0262cSandi
8253e304b55SMichael Hamann        if ($path != '*') {
8263e304b55SMichael Hamann            $path = $ns . ':*';
8273e304b55SMichael Hamann            if ($path == ':*') $path = '*';
828f3f0262cSandi        } else {
829f3f0262cSandi            //we did this already
830f3f0262cSandi            //looks like there is something wrong with the ACL
831f3f0262cSandi            //break here
832d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
833d5ce66f6SAndreas Gohr            return AUTH_NONE;
834f3f0262cSandi        }
835f3f0262cSandi    } while (1); //this should never loop endless
836ab5d26daSAndreas Gohr    return AUTH_NONE;
837f3f0262cSandi}
838f3f0262cSandi
839f3f0262cSandi/**
8406c2bb100SAndreas Gohr * Encode ASCII special chars
8416c2bb100SAndreas Gohr *
8426c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8436c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8446c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8456c2bb100SAndreas Gohr * urlencoding!).
8466c2bb100SAndreas Gohr *
8476c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8486c2bb100SAndreas Gohr *
8496c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8506c2bb100SAndreas Gohr * @see rawurldecode()
85142ea7f44SGerrit Uitslag *
85242ea7f44SGerrit Uitslag * @param string $name
85342ea7f44SGerrit Uitslag * @param bool $skip_group
85442ea7f44SGerrit Uitslag * @return string
8556c2bb100SAndreas Gohr */
856d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
857d868eb89SAndreas Gohr{
858a424cd8eSchris    global $cache_authname;
859a424cd8eSchris    $cache =& $cache_authname;
86031784267SAndreas Gohr    $name  = (string) $name;
861a424cd8eSchris
86280601d26SAndreas Gohr    // never encode wildcard FS#1955
86380601d26SAndreas Gohr    if ($name == '%USER%') return $name;
864b78bf706Sromain    if ($name == '%GROUP%') return $name;
86580601d26SAndreas Gohr
866a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8672401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
86830f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
86930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
870dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
871dccd6b2bSAndreas Gohr                substr($name, 1)
872ab5d26daSAndreas Gohr            );
873e838fc2eSAndreas Gohr        } else {
87430f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
87530f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
876dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
877dccd6b2bSAndreas Gohr                $name
878ab5d26daSAndreas Gohr            );
879e838fc2eSAndreas Gohr        }
8806c2bb100SAndreas Gohr    }
8816c2bb100SAndreas Gohr
882a424cd8eSchris    return $cache[$name][$skip_group];
883a424cd8eSchris}
884a424cd8eSchris
88504d68ae4SGerrit Uitslag/**
88604d68ae4SGerrit Uitslag * callback encodes the matches
88704d68ae4SGerrit Uitslag *
88804d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
88904d68ae4SGerrit Uitslag * @return string
89004d68ae4SGerrit Uitslag */
891d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
892d868eb89SAndreas Gohr{
89330f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
89430f6faf0SChristopher Smith}
89530f6faf0SChristopher Smith
8966c2bb100SAndreas Gohr/**
897f3f0262cSandi * Create a pronouncable password
898f3f0262cSandi *
8998a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
9008a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
9018a285f7fSAndreas Gohr *
9024dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
9034dc42f7fSGerrit Uitslag * @return string  pronouncable password
9044dc42f7fSGerrit Uitslag * @throws Exception
9054dc42f7fSGerrit Uitslag *
90615fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
9078a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
90815fae107Sandi *
9094dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
910f3f0262cSandi */
911d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
912d868eb89SAndreas Gohr{
91324870174SAndreas Gohr    $data = [
914d628dcf3SAndreas Gohr        'password' => '',
915d628dcf3SAndreas Gohr        'foruser'  => $foruser
91624870174SAndreas Gohr    ];
9178a285f7fSAndreas Gohr
918e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
9198a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
920f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
921f3f0262cSandi        $v = 'aeiou'; //vowels
922f3f0262cSandi        $a = $c . $v; //both
923987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
924f3f0262cSandi
925987c8d26SAndreas Gohr        //use thre syllables...
926987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
927483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
928483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
929483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
930f3f0262cSandi        }
931987c8d26SAndreas Gohr        //... and add a nice number and special
93243f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9338a285f7fSAndreas Gohr    }
9348a285f7fSAndreas Gohr    $evt->advise_after();
935f3f0262cSandi
9368a285f7fSAndreas Gohr    return $data['password'];
937f3f0262cSandi}
938f3f0262cSandi
939f3f0262cSandi/**
940f3f0262cSandi * Sends a password to the given user
941f3f0262cSandi *
94215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
94342ea7f44SGerrit Uitslag *
944ab5d26daSAndreas Gohr * @param string $user Login name of the user
945ab5d26daSAndreas Gohr * @param string $password The new password in clear text
94615fae107Sandi * @return bool  true on success
947f3f0262cSandi */
948d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
949d868eb89SAndreas Gohr{
950f3f0262cSandi    global $lang;
951e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
952cd52f92dSchris    global $auth;
9536547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
954cd52f92dSchris
955d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9564dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
957f3f0262cSandi
95887ddda95Sandi    if (!$userinfo['mail']) return false;
959f3f0262cSandi
960f3f0262cSandi    $text = rawLocale('password');
96124870174SAndreas Gohr    $trep = [
962d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
963d7169d19SAndreas Gohr        'LOGIN'    => $user,
964d7169d19SAndreas Gohr        'PASSWORD' => $password
96524870174SAndreas Gohr    ];
966f3f0262cSandi
967d7169d19SAndreas Gohr    $mail = new Mailer();
968102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
969d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
970d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
971d7169d19SAndreas Gohr    return $mail->send();
972f3f0262cSandi}
973f3f0262cSandi
974f3f0262cSandi/**
97515fae107Sandi * Register a new user
976f3f0262cSandi *
97715fae107Sandi * This registers a new user - Data is read directly from $_POST
97815fae107Sandi *
97915fae107Sandi * @return bool  true on success, false on any error
9804dc42f7fSGerrit Uitslag * @throws Exception
9814dc42f7fSGerrit Uitslag *
9824dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
983f3f0262cSandi */
984d868eb89SAndreas Gohrfunction register()
985d868eb89SAndreas Gohr{
986f3f0262cSandi    global $lang;
987eb5d07e4Sjan    global $conf;
9884dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
989cd52f92dSchris    global $auth;
99064273335SAndreas Gohr    global $INPUT;
991f3f0262cSandi
99264273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9933a48618aSAnika Henke    if (!actionOK('register')) return false;
994640145a5Sandi
99564273335SAndreas Gohr    // gather input
99664273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
99764273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
99864273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
99964273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
100064273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
1001d752aedeSAndreas Gohr
100264273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
1003f3f0262cSandi        msg($lang['regmissing'], -1);
1004f3f0262cSandi        return false;
1005f3f0262cSandi    }
1006f3f0262cSandi
1007cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
10088a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
100964273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
1010bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
1011cab2716aSmatthias.grimm        return false;
101264273335SAndreas Gohr    } elseif ($pass != $passchk) {
1013bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
1014cab2716aSmatthias.grimm        return false;
1015cab2716aSmatthias.grimm    }
1016cab2716aSmatthias.grimm
1017f3f0262cSandi    //check mail
101864273335SAndreas Gohr    if (!mail_isvalid($email)) {
1019f3f0262cSandi        msg($lang['regbadmail'], -1);
1020f3f0262cSandi        return false;
1021f3f0262cSandi    }
1022f3f0262cSandi
1023f3f0262cSandi    //okay try to create the user
102424870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
1025db9faf02SPatrick Brown        msg($lang['regfail'], -1);
1026f3f0262cSandi        return false;
1027f3f0262cSandi    }
1028f3f0262cSandi
1029790b7720SAndreas Gohr    // send notification about the new user
103075d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
103175d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
103202a498e7Schris
1033790b7720SAndreas Gohr    // are we done?
1034cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1035cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1036cab2716aSmatthias.grimm        return true;
1037cab2716aSmatthias.grimm    }
1038cab2716aSmatthias.grimm
1039790b7720SAndreas Gohr    // autogenerated password? then send password to user
104064273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1041f3f0262cSandi        msg($lang['regsuccess'], 1);
1042f3f0262cSandi        return true;
1043f3f0262cSandi    } else {
1044f3f0262cSandi        msg($lang['regmailfail'], -1);
1045f3f0262cSandi        return false;
1046f3f0262cSandi    }
1047f3f0262cSandi}
1048f3f0262cSandi
104910a76f6fSfrank/**
10508b06d178Schris * Update user profile
10518b06d178Schris *
10524dc42f7fSGerrit Uitslag * @throws Exception
10534dc42f7fSGerrit Uitslag *
10548b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10558b06d178Schris */
1056d868eb89SAndreas Gohrfunction updateprofile()
1057d868eb89SAndreas Gohr{
10588b06d178Schris    global $conf;
10598b06d178Schris    global $lang;
1060e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1061cd52f92dSchris    global $auth;
1062bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1063bcc94b2cSAndreas Gohr    global $INPUT;
10648b06d178Schris
1065bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10661b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10678b06d178Schris
10683a48618aSAnika Henke    if (!actionOK('profile')) {
10698b06d178Schris        msg($lang['profna'], -1);
10708b06d178Schris        return false;
10718b06d178Schris    }
10728b06d178Schris
107324870174SAndreas Gohr    $changes         = [];
1074bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1075bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1076bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1077bcc94b2cSAndreas Gohr
1078bcc94b2cSAndreas Gohr    // check misspelled passwords
1079bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1080bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10818b06d178Schris        return false;
10828b06d178Schris    }
10838b06d178Schris
10848b06d178Schris    // clean fullname and email
1085bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1086bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10878b06d178Schris
1088bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
10897d34963bSAndreas Gohr    if (
10907d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1091bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1092ab5d26daSAndreas Gohr    ) {
10938b06d178Schris        msg($lang['profnoempty'], -1);
10948b06d178Schris        return false;
10958b06d178Schris    }
1096bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10978b06d178Schris        msg($lang['regbadmail'], -1);
10988b06d178Schris        return false;
10998b06d178Schris    }
11008b06d178Schris
1101bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
11024c21b7eeSAndreas Gohr
1103bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1104bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1105bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1106bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1107bcc94b2cSAndreas Gohr
1108bcc94b2cSAndreas Gohr    // anything to do?
110924870174SAndreas Gohr    if ($changes === []) {
11108b06d178Schris        msg($lang['profnochange'], -1);
11118b06d178Schris        return false;
11128b06d178Schris    }
11138b06d178Schris
11148b06d178Schris    if ($conf['profileconfirm']) {
1115585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
111671422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
11178b06d178Schris            return false;
11188b06d178Schris        }
11198b06d178Schris    }
11208b06d178Schris
112124870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1122db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1123db9faf02SPatrick Brown        return false;
1124db9faf02SPatrick Brown    }
1125db9faf02SPatrick Brown
112667efd1edSPieter Hollants    if (array_key_exists('pass', $changes) && $changes['pass']) {
1127c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1128a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
112904369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1130585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1131c276e9e8SMarcel Pennewiss    } else {
1132c276e9e8SMarcel Pennewiss        // make sure the session is writable
1133c276e9e8SMarcel Pennewiss        @session_start();
1134c276e9e8SMarcel Pennewiss        // invalidate session cache
1135c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1136c276e9e8SMarcel Pennewiss        session_write_close();
113732ed2b36SAndreas Gohr    }
1138c276e9e8SMarcel Pennewiss
113925b2a98cSMichael Klier    return true;
1140a0b5b007SChris Smith}
1141ab5d26daSAndreas Gohr
114204d68ae4SGerrit Uitslag/**
114304d68ae4SGerrit Uitslag * Delete the current logged-in user
114404d68ae4SGerrit Uitslag *
114504d68ae4SGerrit Uitslag * @return bool true on success, false on any error
114604d68ae4SGerrit Uitslag */
1147d868eb89SAndreas Gohrfunction auth_deleteprofile()
1148d868eb89SAndreas Gohr{
11492a7abf2dSChristopher Smith    global $conf;
11502a7abf2dSChristopher Smith    global $lang;
11514dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11522a7abf2dSChristopher Smith    global $auth;
11532a7abf2dSChristopher Smith    /* @var Input $INPUT */
11542a7abf2dSChristopher Smith    global $INPUT;
11552a7abf2dSChristopher Smith
11562a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11572a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11582a7abf2dSChristopher Smith
11592a7abf2dSChristopher Smith    // action prevented or auth module disallows
11602a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11612a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11622a7abf2dSChristopher Smith        return false;
11632a7abf2dSChristopher Smith    }
11642a7abf2dSChristopher Smith
11652a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11662a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11672a7abf2dSChristopher Smith        return false;
11682a7abf2dSChristopher Smith    }
11692a7abf2dSChristopher Smith
11702a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1171585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11722a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11732a7abf2dSChristopher Smith            return false;
11742a7abf2dSChristopher Smith        }
11752a7abf2dSChristopher Smith    }
11762a7abf2dSChristopher Smith
117724870174SAndreas Gohr    $deleted = [];
1178585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
117924870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
11802a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11812a7abf2dSChristopher Smith        auth_logoff();
11822a7abf2dSChristopher Smith        return true;
11832a7abf2dSChristopher Smith    }
11842a7abf2dSChristopher Smith
11852a7abf2dSChristopher Smith    return false;
11862a7abf2dSChristopher Smith}
11872a7abf2dSChristopher Smith
11888b06d178Schris/**
11898b06d178Schris * Send a  new password
11908b06d178Schris *
11911d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11921d5856cfSAndreas Gohr *
11931d5856cfSAndreas Gohr *   - handling the first request of password reset
11941d5856cfSAndreas Gohr *   - validating the password reset auth token
11951d5856cfSAndreas Gohr *
11964dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
11974dc42f7fSGerrit Uitslag * @throws Exception
11984dc42f7fSGerrit Uitslag *
11994dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
12008b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
12018b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
12028b06d178Schris */
1203d868eb89SAndreas Gohrfunction act_resendpwd()
1204d868eb89SAndreas Gohr{
12058b06d178Schris    global $lang;
12068b06d178Schris    global $conf;
1207e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1208cd52f92dSchris    global $auth;
1209bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1210bcc94b2cSAndreas Gohr    global $INPUT;
12118b06d178Schris
12123a48618aSAnika Henke    if (!actionOK('resendpwd')) {
12138b06d178Schris        msg($lang['resendna'], -1);
12148b06d178Schris        return false;
12158b06d178Schris    }
12168b06d178Schris
1217bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
12188b06d178Schris
12191d5856cfSAndreas Gohr    if ($token) {
1220cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
12211d5856cfSAndreas Gohr
12222401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
122379e79377SAndreas Gohr        if (!file_exists($tfile)) {
12241d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1225bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12261d5856cfSAndreas Gohr            return false;
12271d5856cfSAndreas Gohr        }
12288a9735e3SAndreas Gohr        // token is only valid for 3 days
12298a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12308a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1231bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12321d5856cfSAndreas Gohr            @unlink($tfile);
12338a9735e3SAndreas Gohr            return false;
12348a9735e3SAndreas Gohr        }
12358a9735e3SAndreas Gohr
12368b06d178Schris        $user     = io_readfile($tfile);
12374dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12388b06d178Schris        if (!$userinfo['mail']) {
12398b06d178Schris            msg($lang['resendpwdnouser'], -1);
12408b06d178Schris            return false;
12418b06d178Schris        }
12428b06d178Schris
1243cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1244bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1245bcc94b2cSAndreas Gohr
1246cc204bbdSAndreas Gohr            // password given correctly?
1247bcc94b2cSAndreas Gohr            if (!$pass) return false;
1248bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1249451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1250cc204bbdSAndreas Gohr                return false;
1251cc204bbdSAndreas Gohr            }
1252cc204bbdSAndreas Gohr
1253bcc94b2cSAndreas Gohr            // change it
125424870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1255db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1256cc204bbdSAndreas Gohr                return false;
1257cc204bbdSAndreas Gohr            }
1258cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12598a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
126024870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1261db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12628b06d178Schris                return false;
12638b06d178Schris            }
12648b06d178Schris
12658b06d178Schris            if (auth_sendPassword($user, $pass)) {
12668b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12678b06d178Schris            } else {
12688b06d178Schris                msg($lang['regmailfail'], -1);
12698b06d178Schris            }
1270cc204bbdSAndreas Gohr        }
1271cc204bbdSAndreas Gohr
1272cc204bbdSAndreas Gohr        @unlink($tfile);
12738b06d178Schris        return true;
12741d5856cfSAndreas Gohr    } else {
12751d5856cfSAndreas Gohr        // we're in request phase
12761d5856cfSAndreas Gohr
1277bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
12781d5856cfSAndreas Gohr
1279bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
12801d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12811d5856cfSAndreas Gohr            return false;
12821d5856cfSAndreas Gohr        } else {
1283bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12841d5856cfSAndreas Gohr        }
12851d5856cfSAndreas Gohr
12864dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12871d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
12881d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12891d5856cfSAndreas Gohr            return false;
12901d5856cfSAndreas Gohr        }
12911d5856cfSAndreas Gohr
12921d5856cfSAndreas Gohr        // generate auth token
1293483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12942401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
129524870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
12961d5856cfSAndreas Gohr
12971d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12981d5856cfSAndreas Gohr
12991d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
130024870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
13011d5856cfSAndreas Gohr
1302d7169d19SAndreas Gohr        $mail = new Mailer();
1303d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1304d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1305d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1306d7169d19SAndreas Gohr        if ($mail->send()) {
13071d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
13081d5856cfSAndreas Gohr        } else {
13091d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
13101d5856cfSAndreas Gohr        }
13111d5856cfSAndreas Gohr        return true;
13121d5856cfSAndreas Gohr    }
1313ab5d26daSAndreas Gohr    // never reached
13148b06d178Schris}
13158b06d178Schris
13168b06d178Schris/**
1317b0855b11Sandi * Encrypts a password using the given method and salt
1318b0855b11Sandi *
1319b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1320b0855b11Sandi * is chosen.
1321b0855b11Sandi *
1322b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
132342ea7f44SGerrit Uitslag *
1324ab5d26daSAndreas Gohr * @param string $clear The clear text password
1325ab5d26daSAndreas Gohr * @param string $method The hashing method
1326ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1327b0855b11Sandi * @return  string  The crypted password
1328b0855b11Sandi */
1329d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1330d868eb89SAndreas Gohr{
1331b0855b11Sandi    global $conf;
1332b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
133310a76f6fSfrank
13343a0a2d05SAndreas Gohr    $pass = new PassHash();
13353a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1336b0855b11Sandi
13373a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1338b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13393a0a2d05SAndreas Gohr        return false;
1340b0855b11Sandi    }
13413a0a2d05SAndreas Gohr
13423a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1343b0855b11Sandi}
1344b0855b11Sandi
1345b0855b11Sandi/**
1346b0855b11Sandi * Verifies a cleartext password against a crypted hash
1347b0855b11Sandi *
1348ab5d26daSAndreas Gohr * @param string $clear The clear text password
1349ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1350ab5d26daSAndreas Gohr * @return bool true if both match
13514dc42f7fSGerrit Uitslag * @throws Exception
13524dc42f7fSGerrit Uitslag *
13534dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1354b0855b11Sandi */
1355d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1356d868eb89SAndreas Gohr{
13573a0a2d05SAndreas Gohr    $pass = new PassHash();
13583a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1359b0855b11Sandi}
1360340756e4Sandi
1361a0b5b007SChris Smith/**
1362a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1363a0b5b007SChris Smith *
1364a0b5b007SChris Smith * @param string  $user       username
1365a0b5b007SChris Smith * @param string  $pass       encrypted password
1366a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1367ab5d26daSAndreas Gohr * @return bool
1368a0b5b007SChris Smith */
1369d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1370d868eb89SAndreas Gohr{
1371a0b5b007SChris Smith    global $conf;
1372e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1373a0b5b007SChris Smith    global $auth;
137479d00841SOliver Geisen    global $USERINFO;
1375a0b5b007SChris Smith
13766547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1377a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1378a0b5b007SChris Smith
1379a0b5b007SChris Smith    // set cookie
1380645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
138173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1382c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1383bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1384bf8392ebSAndreas Gohr        'expires' => $time,
1385bf8392ebSAndreas Gohr        'path' => $cookieDir,
1386bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1387bf8392ebSAndreas Gohr        'httponly' => true,
1388486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1389bf8392ebSAndreas Gohr    ]);
139055a71a16SGerrit Uitslag
1391a0b5b007SChris Smith    // set session
1392a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1393234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1394a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1395a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1396a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1397ab5d26daSAndreas Gohr
1398ab5d26daSAndreas Gohr    return true;
1399a0b5b007SChris Smith}
1400a0b5b007SChris Smith
1401645c0a36SAndreas Gohr/**
1402645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1403645c0a36SAndreas Gohr *
1404645c0a36SAndreas Gohr * @returns array
1405645c0a36SAndreas Gohr */
1406d868eb89SAndreas Gohrfunction auth_getCookie()
1407d868eb89SAndreas Gohr{
1408c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
140924870174SAndreas Gohr        return [null, null, null];
1410c66972f2SAdrian Lang    }
141124870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1412645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1413645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1414645c0a36SAndreas Gohr    $user   = base64_decode($user);
141524870174SAndreas Gohr    return [$user, $sticky, $pass];
1416645c0a36SAndreas Gohr}
1417645c0a36SAndreas Gohr
1418e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1419