xref: /dokuwiki/inc/auth.php (revision cf927d07914d82d58a7663afc5d95be13e10f1a3)
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*cf927d07Ssplitbrainuse dokuwiki\JWT;
1424870174SAndreas Gohruse phpseclib\Crypt\AES;
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;
21c3cc6e05SAndreas Gohr
2216905344SAndreas Gohr/**
2316905344SAndreas Gohr * Initialize the auth system.
2416905344SAndreas Gohr *
2516905344SAndreas Gohr * This function is automatically called at the end of init.php
2616905344SAndreas Gohr *
2716905344SAndreas Gohr * This used to be the main() of the auth.php
2816905344SAndreas Gohr *
2916905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
3016905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
31ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
32ab5d26daSAndreas Gohr * @return bool
3316905344SAndreas Gohr */
34d868eb89SAndreas Gohrfunction auth_setup()
35d868eb89SAndreas Gohr{
36742c66f8Schris    global $conf;
37e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
3803c4aec3Schris    global $auth;
39bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
40bcc94b2cSAndreas Gohr    global $INPUT;
419a9714acSDominik Eckelmann    global $AUTH_ACL;
429a9714acSDominik Eckelmann    global $lang;
433a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
449c29eea5SJan Schumann    global $plugin_controller;
4524870174SAndreas Gohr    $AUTH_ACL = [];
4603c4aec3Schris
4716905344SAndreas Gohr    if (!$conf['useacl']) return false;
4816905344SAndreas Gohr
499c29eea5SJan Schumann    // try to load auth backend from plugins
509c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
519c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
52f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
539c29eea5SJan Schumann            break;
549c29eea5SJan Schumann        }
559c29eea5SJan Schumann    }
568b06d178Schris
576547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) {
5871c734a9SGerrit Uitslag        msg($lang['authtempfail'], -1);
593094e817SAndreas Gohr        return false;
603094e817SAndreas Gohr    }
618b06d178Schris
626416b708SMichael Hamann    if ($auth->success == false) {
630f4f4adfSAndreas Gohr        // degrade to unauthenticated user
64ecad51ddSAndreas Gohr        $auth = null;
650f4f4adfSAndreas Gohr        auth_logoff();
66cd52f92dSchris        msg($lang['authtempfail'], -1);
676416b708SMichael Hamann        return false;
68d2dde4ebSMatthias Grimm    }
6916905344SAndreas Gohr
7016905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
71bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
72bcc94b2cSAndreas Gohr    if (!$conf['rememberme']) $INPUT->set('r', false);
73bbbd6568SAndreas Gohr
7462bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
7562bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
7662bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
7762bf3ac0SDamien Regad    if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
7862bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
7924870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
80528ddc7cSAndreas Gohr    }
81528ddc7cSAndreas Gohr
821e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
8303062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
8403062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
8503062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
86bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
871e8c9c90SAndreas Gohr    }
881e8c9c90SAndreas Gohr
89395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
9093a7873eSAndreas Gohr    if (true === $auth->success) {
91395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
92395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
93f4476bd9SJan Schumann    }
94191bb90aSAndreas Gohr
95455aa67eSAndreas Gohr    if (!auth_tokenlogin()) {
9681e99965SPhy        $ok = null;
97455aa67eSAndreas Gohr
986547cfc7SGerrit Uitslag        if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
9981e99965SPhy            $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
10081e99965SPhy        }
10181e99965SPhy
10281e99965SPhy        if ($ok === null) {
10381e99965SPhy            // external trust mechanism not in place, or returns no result,
10481e99965SPhy            // then attempt auth_login
10524870174SAndreas Gohr            $evdata = [
106bcc94b2cSAndreas Gohr                'user' => $INPUT->str('u'),
107bcc94b2cSAndreas Gohr                'password' => $INPUT->str('p'),
108bcc94b2cSAndreas Gohr                'sticky' => $INPUT->bool('r'),
109bcc94b2cSAndreas Gohr                'silent' => $INPUT->bool('http_credentials')
11024870174SAndreas Gohr            ];
111cbb44eabSAndreas Gohr            Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
112f5cb575dSAndreas Gohr        }
113455aa67eSAndreas Gohr    }
114f5cb575dSAndreas Gohr
11516905344SAndreas Gohr    //load ACL into a global array XXX
11675c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
117ab5d26daSAndreas Gohr
118ab5d26daSAndreas Gohr    return true;
11975c93b77SAndreas Gohr}
12075c93b77SAndreas Gohr
12175c93b77SAndreas Gohr/**
12275c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12375c93b77SAndreas Gohr *
12475c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12542ea7f44SGerrit Uitslag *
126ab5d26daSAndreas Gohr * @return array
12775c93b77SAndreas Gohr */
128d868eb89SAndreas Gohrfunction auth_loadACL()
129d868eb89SAndreas Gohr{
13075c93b77SAndreas Gohr    global $config_cascade;
131b78bf706Sromain    global $USERINFO;
132585bf44eSChristopher Smith    /* @var Input $INPUT */
133585bf44eSChristopher Smith    global $INPUT;
13475c93b77SAndreas Gohr
13524870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
13675c93b77SAndreas Gohr
13775c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13875c93b77SAndreas Gohr
13924870174SAndreas Gohr    $out = [];
1409ce556d2SAndreas Gohr    foreach ($acl as $line) {
1419ce556d2SAndreas Gohr        $line = trim($line);
1422401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
14324870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
14432e82180SAndreas Gohr
145443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
146ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
147ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
148585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
149ad3d68d7SChristopher Smith
150585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
151585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
152ad3d68d7SChristopher Smith        }
153ad3d68d7SChristopher Smith
154ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1559ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
156ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
15706f34f54SPhy            if (isset($USERINFO['grps'])) {
1589ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
159b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
16032e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
16132e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
162b78bf706Sromain                }
16306f34f54SPhy            }
16432e82180SAndreas Gohr        } else {
16532e82180SAndreas Gohr            $out[] = "$id\t$rest";
166a8fe108bSGuy Brand        }
16711799630Sandi    }
1689ce556d2SAndreas Gohr
16932e82180SAndreas Gohr    return $out;
170f3f0262cSandi}
171f3f0262cSandi
172ab5d26daSAndreas Gohr/**
173455aa67eSAndreas Gohr * Try a token login
174455aa67eSAndreas Gohr *
175455aa67eSAndreas Gohr * @return bool true if token login succeeded
176455aa67eSAndreas Gohr */
177*cf927d07Ssplitbrainfunction auth_tokenlogin()
178*cf927d07Ssplitbrain{
179455aa67eSAndreas Gohr    global $USERINFO;
180455aa67eSAndreas Gohr    global $INPUT;
181455aa67eSAndreas Gohr    /** @var DokuWiki_Auth_Plugin $auth */
182455aa67eSAndreas Gohr    global $auth;
183455aa67eSAndreas Gohr    if (!$auth) return false;
184455aa67eSAndreas Gohr
185455aa67eSAndreas Gohr    // see if header has token
186455aa67eSAndreas Gohr    $header = '';
1876fdb83b6SAndreas Gohr    if (function_exists('getallheaders')) {
188455aa67eSAndreas Gohr        // Authorization headers are not in $_SERVER for mod_php
1896fdb83b6SAndreas Gohr        $headers = array_change_key_case(getallheaders());
190d26e5a24SAndreas Gohr        if (isset($headers['authorization'])) $header = $headers['authorization'];
191455aa67eSAndreas Gohr    } else {
192455aa67eSAndreas Gohr        $header = $INPUT->server->str('HTTP_AUTHORIZATION');
193455aa67eSAndreas Gohr    }
194455aa67eSAndreas Gohr    if (!$header) return false;
195*cf927d07Ssplitbrain    [$type, $token] = sexplode(' ', $header, 2);
196455aa67eSAndreas Gohr    if ($type !== 'Bearer') return false;
197455aa67eSAndreas Gohr
198455aa67eSAndreas Gohr    // check token
199455aa67eSAndreas Gohr    try {
200*cf927d07Ssplitbrain        $authtoken = JWT::validate($token);
201455aa67eSAndreas Gohr    } catch (Exception $e) {
202455aa67eSAndreas Gohr        msg(hsc($e->getMessage()), -1);
203455aa67eSAndreas Gohr        return false;
204455aa67eSAndreas Gohr    }
205455aa67eSAndreas Gohr
206455aa67eSAndreas Gohr    // fetch user info from backend
207455aa67eSAndreas Gohr    $user = $authtoken->getUser();
208455aa67eSAndreas Gohr    $USERINFO = $auth->getUserData($user);
209455aa67eSAndreas Gohr    if (!$USERINFO) return false;
210455aa67eSAndreas Gohr
211455aa67eSAndreas Gohr    // the code is correct, set up user
212455aa67eSAndreas Gohr    $INPUT->server->set('REMOTE_USER', $user);
213455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
214455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
215455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
216455aa67eSAndreas Gohr
217455aa67eSAndreas Gohr    return true;
218455aa67eSAndreas Gohr}
219455aa67eSAndreas Gohr
220455aa67eSAndreas Gohr/**
221ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
222ab5d26daSAndreas Gohr *
22342ea7f44SGerrit Uitslag * @param array $evdata
224ab5d26daSAndreas Gohr * @return bool
2254dc42f7fSGerrit Uitslag * @throws Exception
226ab5d26daSAndreas Gohr */
227d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
228d868eb89SAndreas Gohr{
229ab5d26daSAndreas Gohr    return auth_login(
230ab5d26daSAndreas Gohr        $evdata['user'],
231b5ee21aaSAdrian Lang        $evdata['password'],
232b5ee21aaSAdrian Lang        $evdata['sticky'],
233ab5d26daSAndreas Gohr        $evdata['silent']
234ab5d26daSAndreas Gohr    );
235b5ee21aaSAdrian Lang}
236b5ee21aaSAdrian Lang
237f3f0262cSandi/**
238f3f0262cSandi * This tries to login the user based on the sent auth credentials
239f3f0262cSandi *
240f3f0262cSandi * The authentication works like this: if a username was given
24115fae107Sandi * a new login is assumed and user/password are checked. If they
24215fae107Sandi * are correct the password is encrypted with blowfish and stored
24315fae107Sandi * together with the username in a cookie - the same info is stored
24415fae107Sandi * in the session, too. Additonally a browserID is stored in the
24515fae107Sandi * session.
24615fae107Sandi *
24715fae107Sandi * If no username was given the cookie is checked: if the username,
24815fae107Sandi * crypted password and browserID match between session and cookie
24915fae107Sandi * no further testing is done and the user is accepted
25015fae107Sandi *
25115fae107Sandi * If a cookie was found but no session info was availabe the
252136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
25315fae107Sandi * together with username rechecked by calling this function again.
254f3f0262cSandi *
255f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
256f3f0262cSandi * are set.
25715fae107Sandi *
25815fae107Sandi * @param string $user Username
25915fae107Sandi * @param string $pass Cleartext Password
26015fae107Sandi * @param bool $sticky Cookie should not expire
261f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
26215fae107Sandi * @return bool true on successful auth
2634dc42f7fSGerrit Uitslag * @throws Exception
2644dc42f7fSGerrit Uitslag *
2654dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
266f3f0262cSandi */
267d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
268d868eb89SAndreas Gohr{
269f3f0262cSandi    global $USERINFO;
270f3f0262cSandi    global $conf;
271f3f0262cSandi    global $lang;
272e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
273cd52f92dSchris    global $auth;
274585bf44eSChristopher Smith    /* @var Input $INPUT */
275585bf44eSChristopher Smith    global $INPUT;
276ab5d26daSAndreas Gohr
2776547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
278beca106aSAdrian Lang
279bbbd6568SAndreas Gohr    if (!empty($user)) {
280132bdbfeSandi        //usual login
2815e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
282132bdbfeSandi            // make logininfo globally available
283585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
28430d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
28504369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
286132bdbfeSandi            return true;
287f3f0262cSandi        } else {
288f3f0262cSandi            //invalid credentials - log off
289f8b1e4e7SAndreas Gohr            if (!$silent) {
290f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
291f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
292f8b1e4e7SAndreas Gohr            }
293f3f0262cSandi            auth_logoff();
294132bdbfeSandi            return false;
295f3f0262cSandi        }
296f3f0262cSandi    } else {
297132bdbfeSandi        // read cookie information
29824870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
299132bdbfeSandi        if ($user && $pass) {
300132bdbfeSandi            // we got a cookie - see if we can trust it
301fa7c70ffSAdrian Lang
302fa7c70ffSAdrian Lang            // get session info
3030058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
304fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
3057d34963bSAndreas Gohr                if (
3067d34963bSAndreas Gohr                    isset($session) &&
3077172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3084c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
309132bdbfeSandi                    ($session['user'] == $user) &&
310234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
311ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
312ab5d26daSAndreas Gohr                ) {
313132bdbfeSandi                    // he has session, cookie and browser right - let him in
314585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
315132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
316132bdbfeSandi                    return true;
317132bdbfeSandi                }
3180058ae75SDamien Regad            }
319f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
32030d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
32104369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
322f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
323132bdbfeSandi        }
324132bdbfeSandi    }
325f3f0262cSandi    //just to be sure
326883179a4SAndreas Gohr    auth_logoff(true);
327132bdbfeSandi    return false;
328f3f0262cSandi}
329132bdbfeSandi
330132bdbfeSandi/**
331136ce040Sandi * Builds a pseudo UID from browser and IP data
332132bdbfeSandi *
333132bdbfeSandi * This is neither unique nor unfakable - still it adds some
334136ce040Sandi * security. Using the first part of the IP makes sure
33580b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
33615fae107Sandi *
33715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
33815fae107Sandi *
339b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
340132bdbfeSandi */
341d868eb89SAndreas Gohrfunction auth_browseruid()
342d868eb89SAndreas Gohr{
343585bf44eSChristopher Smith    /* @var Input $INPUT */
344585bf44eSChristopher Smith    global $INPUT;
345585bf44eSChristopher Smith
3462f9daf16SAndreas Gohr    $ip = clientIP(true);
347b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
348b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
349b7c67f83SAndreas Gohr
350b7c67f83SAndreas Gohr    $uid = implode("\n", [
351b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
352b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
353b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
354b7c67f83SAndreas Gohr    ]);
355b13c0e1aSAdaKaleh    return hash('sha256', $uid);
356132bdbfeSandi}
357132bdbfeSandi
358132bdbfeSandi/**
359132bdbfeSandi * Creates a random key to encrypt the password in cookies
36015fae107Sandi *
36115fae107Sandi * This function tries to read the password for encrypting
36298407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
36315fae107Sandi * if no such file is found a random key is created and
36415fae107Sandi * and stored in this file.
36515fae107Sandi *
36632ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
36730d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
36815fae107Sandi * @return  string
3694dc42f7fSGerrit Uitslag * @throws Exception
3704dc42f7fSGerrit Uitslag *
3714dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
372132bdbfeSandi */
373d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
374d868eb89SAndreas Gohr{
375a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
376fe745becSMichael Große        return 'test';
377a1fe3c9cSMichael Große    }
378132bdbfeSandi    global $conf;
37998407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
38030d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
38130d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
38230d544a4SMichael Hamann    }
383132bdbfeSandi    $salt = io_readFile($file);
384132bdbfeSandi    if (empty($salt)) {
38530d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
386132bdbfeSandi        io_saveFile($file, $salt);
387132bdbfeSandi    }
38832ed2b36SAndreas Gohr    if ($addsession) {
38932ed2b36SAndreas Gohr        $salt .= session_id();
39032ed2b36SAndreas Gohr    }
391132bdbfeSandi    return $salt;
392f3f0262cSandi}
393f3f0262cSandi
394f3f0262cSandi/**
3957a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
396483b6238SMichael Hamann *
3977a33d2f8SNiklas Keller * @param int $length number of bytes
3987a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
3994dc42f7fSGerrit Uitslag * @throws Exception
4004dc42f7fSGerrit Uitslag *
4014dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
402483b6238SMichael Hamann */
403d868eb89SAndreas Gohrfunction auth_randombytes($length)
404d868eb89SAndreas Gohr{
4057a33d2f8SNiklas Keller    return random_bytes($length);
406483b6238SMichael Hamann}
407483b6238SMichael Hamann
408483b6238SMichael Hamann/**
4097a33d2f8SNiklas Keller * Cryptographically secure random number generator.
410483b6238SMichael Hamann *
411483b6238SMichael Hamann * @param int $min
412483b6238SMichael Hamann * @param int $max
413483b6238SMichael Hamann * @return int
4144dc42f7fSGerrit Uitslag * @throws Exception
4154dc42f7fSGerrit Uitslag *
4164dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
417483b6238SMichael Hamann */
418d868eb89SAndreas Gohrfunction auth_random($min, $max)
419d868eb89SAndreas Gohr{
4207a33d2f8SNiklas Keller    return random_int($min, $max);
421483b6238SMichael Hamann}
422483b6238SMichael Hamann
423483b6238SMichael Hamann/**
42404369c3eSMichael Hamann * Encrypt data using the given secret using AES
42504369c3eSMichael Hamann *
42604369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
42704369c3eSMichael Hamann * using pbkdf2.
42804369c3eSMichael Hamann *
42904369c3eSMichael Hamann * @param string $data The data that shall be encrypted
43004369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
43104369c3eSMichael Hamann * @return string The ciphertext
4324dc42f7fSGerrit Uitslag * @throws Exception
43304369c3eSMichael Hamann */
434d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
435d868eb89SAndreas Gohr{
43604369c3eSMichael Hamann    $iv     = auth_randombytes(16);
43724870174SAndreas Gohr    $cipher = new AES();
43804369c3eSMichael Hamann    $cipher->setPassword($secret);
43904369c3eSMichael Hamann
4407b650cefSMichael Hamann    /*
4417b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4427b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4437b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4447b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4457b650cefSMichael Hamann    */
44604369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
44704369c3eSMichael Hamann}
44804369c3eSMichael Hamann
44904369c3eSMichael Hamann/**
45004369c3eSMichael Hamann * Decrypt the given AES ciphertext
45104369c3eSMichael Hamann *
45204369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
45304369c3eSMichael Hamann *
45404369c3eSMichael Hamann * @param string $ciphertext The encrypted data
45504369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
45604369c3eSMichael Hamann * @return string The decrypted data
45704369c3eSMichael Hamann */
458d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
459d868eb89SAndreas Gohr{
4607b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
46124870174SAndreas Gohr    $cipher = new AES();
46204369c3eSMichael Hamann    $cipher->setPassword($secret);
4637b650cefSMichael Hamann    $cipher->setIV($iv);
46404369c3eSMichael Hamann
4657b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
46604369c3eSMichael Hamann}
46704369c3eSMichael Hamann
46804369c3eSMichael Hamann/**
469883179a4SAndreas Gohr * Log out the current user
470883179a4SAndreas Gohr *
471f3f0262cSandi * This clears all authentication data and thus log the user
472883179a4SAndreas Gohr * off. It also clears session data.
47315fae107Sandi *
47415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47542ea7f44SGerrit Uitslag *
476883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
477f3f0262cSandi */
478d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
479d868eb89SAndreas Gohr{
480f3f0262cSandi    global $conf;
481f3f0262cSandi    global $USERINFO;
482e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4835298a619SAndreas Gohr    global $auth;
484585bf44eSChristopher Smith    /* @var Input $INPUT */
485585bf44eSChristopher Smith    global $INPUT;
48637065e65Sandi
487d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
488e9621d07SAndreas Gohr    @session_start();
489e9621d07SAndreas Gohr
490e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
491e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
492e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
493e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
494e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
495e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
496883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
497e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
498585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
499132bdbfeSandi    $USERINFO = null; //FIXME
500f5c6743cSAndreas Gohr
50173ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
502bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
503bf8392ebSAndreas Gohr        'expires' => time() - 600000,
504bf8392ebSAndreas Gohr        'path' => $cookieDir,
505bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
506bf8392ebSAndreas Gohr        'httponly' => true,
507486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
508bf8392ebSAndreas Gohr    ]);
5095298a619SAndreas Gohr
5106547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5116547cfc7SGerrit Uitslag        $auth->logOff();
5126547cfc7SGerrit Uitslag    }
513f3f0262cSandi}
514f3f0262cSandi
515f3f0262cSandi/**
516f8cc712eSAndreas Gohr * Check if a user is a manager
517f8cc712eSAndreas Gohr *
518f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
519f8cc712eSAndreas Gohr * user.
520f8cc712eSAndreas Gohr *
521f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
522f8cc712eSAndreas Gohr *
523ab5d26daSAndreas Gohr * @param string $user Username
524ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
525ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
52610396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
527ab5d26daSAndreas Gohr * @return bool
52896348f27SAndreas Gohr * @see    auth_isadmin
52996348f27SAndreas Gohr *
53096348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
531f8cc712eSAndreas Gohr */
532d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
533d868eb89SAndreas Gohr{
534f8cc712eSAndreas Gohr    global $conf;
535f8cc712eSAndreas Gohr    global $USERINFO;
536e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
537d752aedeSAndreas Gohr    global $auth;
538585bf44eSChristopher Smith    /* @var Input $INPUT */
539585bf44eSChristopher Smith    global $INPUT;
540585bf44eSChristopher Smith
541f8cc712eSAndreas Gohr
5426547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
543c66972f2SAdrian Lang    if (is_null($user)) {
544585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
545c66972f2SAdrian Lang            return false;
546c66972f2SAdrian Lang        } else {
547585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
548c66972f2SAdrian Lang        }
549c66972f2SAdrian Lang    }
550d6dc956fSAndreas Gohr    if (is_null($groups)) {
5511525c228SAnna Dabrowska        // checking the logged in user, or another one?
5521525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5531525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
55466b108d6SAnna Dabrowska        } else {
5556cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5566cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
55766b108d6SAnna Dabrowska        }
558e259aa79SAndreas Gohr    }
559e259aa79SAndreas Gohr
56096348f27SAndreas Gohr    // prefer cached result
56196348f27SAndreas Gohr    static $cache = [];
56210396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
56396348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
564d6dc956fSAndreas Gohr        // check superuser match
56596348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
56600ce12daSChris Smith
56796348f27SAndreas Gohr        // check managers
56896348f27SAndreas Gohr        if (!$ok && !$adminonly) {
56996348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
57096348f27SAndreas Gohr        }
57196348f27SAndreas Gohr
57296348f27SAndreas Gohr        $cache[$cachekey] = $ok;
57396348f27SAndreas Gohr    }
57496348f27SAndreas Gohr
57596348f27SAndreas Gohr    return $cache[$cachekey];
576f8cc712eSAndreas Gohr}
577f8cc712eSAndreas Gohr
578f8cc712eSAndreas Gohr/**
579f8cc712eSAndreas Gohr * Check if a user is admin
580f8cc712eSAndreas Gohr *
581f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
582f8cc712eSAndreas Gohr *
583f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
584f8cc712eSAndreas Gohr *
58596348f27SAndreas Gohr * @param string $user Username
58696348f27SAndreas Gohr * @param array $groups List of groups the user is in
58710396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
58896348f27SAndreas Gohr * @return bool
589f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
590ab5d26daSAndreas Gohr * @see auth_ismanager()
59142ea7f44SGerrit Uitslag *
592f8cc712eSAndreas Gohr */
593d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
594d868eb89SAndreas Gohr{
59596348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
596f8cc712eSAndreas Gohr}
597f8cc712eSAndreas Gohr
598d6dc956fSAndreas Gohr/**
599d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
600d6dc956fSAndreas Gohr * users and groups to determine membership status
601d6dc956fSAndreas Gohr *
602d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
603d6dc956fSAndreas Gohr *
60442ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
60542ea7f44SGerrit Uitslag * @param string $user       user to match against
60642ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6075446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
608d6dc956fSAndreas Gohr */
609d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
610d868eb89SAndreas Gohr{
611e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
612d6dc956fSAndreas Gohr    global $auth;
6136547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
614d6dc956fSAndreas Gohr
615d6dc956fSAndreas Gohr    // clean user and groups
6164f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
61724870174SAndreas Gohr        $user   = PhpString::strtolower($user);
61824870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
619d6dc956fSAndreas Gohr    }
620d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
62124870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
622d6dc956fSAndreas Gohr
623d6dc956fSAndreas Gohr    // extract the memberlist
624d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
625d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
626d6dc956fSAndreas Gohr    $members = array_unique($members);
627d6dc956fSAndreas Gohr    $members = array_filter($members);
628d6dc956fSAndreas Gohr
629d6dc956fSAndreas Gohr    // compare cleaned values
630d6dc956fSAndreas Gohr    foreach ($members as $member) {
631e5204a12SJurgen Hart        if ($member == '@ALL') return true;
63224870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
633d6dc956fSAndreas Gohr        if ($member[0] == '@') {
634d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
635d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
636d6dc956fSAndreas Gohr        } else {
637d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
638d6dc956fSAndreas Gohr            if ($member == $user) return true;
639d6dc956fSAndreas Gohr        }
640d6dc956fSAndreas Gohr    }
641d6dc956fSAndreas Gohr
642d6dc956fSAndreas Gohr    // still here? not a member!
643d6dc956fSAndreas Gohr    return false;
644d6dc956fSAndreas Gohr}
645d6dc956fSAndreas Gohr
646f8cc712eSAndreas Gohr/**
64715fae107Sandi * Convinience function for auth_aclcheck()
64815fae107Sandi *
64915fae107Sandi * This checks the permissions for the current user
65015fae107Sandi *
65115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
65215fae107Sandi *
6531698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
65415fae107Sandi * @return int          permission level
655f3f0262cSandi */
656d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
657d868eb89SAndreas Gohr{
658f3f0262cSandi    global $conf;
659f3f0262cSandi    global $USERINFO;
660585bf44eSChristopher Smith    /* @var Input $INPUT */
661585bf44eSChristopher Smith    global $INPUT;
662f3f0262cSandi    # if no ACL is used always return upload rights
663f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
66424870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
665f3f0262cSandi}
666f3f0262cSandi
667f3f0262cSandi/**
668c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
66915fae107Sandi *
67015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
67142ea7f44SGerrit Uitslag *
672c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6731698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
67415fae107Sandi * @param  string       $user   Username
6753272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
67615fae107Sandi * @return int             permission level
677f3f0262cSandi */
678d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
679d868eb89SAndreas Gohr{
68024870174SAndreas Gohr    $data = [
681bf8f8509SAndreas Gohr        'id'     => $id ?? '',
682c17acc9fSAndreas Gohr        'user'   => $user,
683c17acc9fSAndreas Gohr        'groups' => $groups
68424870174SAndreas Gohr    ];
685c17acc9fSAndreas Gohr
686cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
687c17acc9fSAndreas Gohr}
688c17acc9fSAndreas Gohr
689c17acc9fSAndreas Gohr/**
690c17acc9fSAndreas Gohr * default ACL check method
691c17acc9fSAndreas Gohr *
692c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
693c17acc9fSAndreas Gohr *
694c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
69542ea7f44SGerrit Uitslag *
696c17acc9fSAndreas Gohr * @param  array $data event data
697c17acc9fSAndreas Gohr * @return int   permission level
698c17acc9fSAndreas Gohr */
699d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
700d868eb89SAndreas Gohr{
701c17acc9fSAndreas Gohr    $id     =& $data['id'];
702c17acc9fSAndreas Gohr    $user   =& $data['user'];
703c17acc9fSAndreas Gohr    $groups =& $data['groups'];
704c17acc9fSAndreas Gohr
705f3f0262cSandi    global $conf;
706f3f0262cSandi    global $AUTH_ACL;
707e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
708d752aedeSAndreas Gohr    global $auth;
709f3f0262cSandi
71085d03f68SAndreas Gohr    // if no ACL is used always return upload rights
711f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7126547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
713bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
714f3f0262cSandi
715074cf26bSandi    //make sure groups is an array
71624870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
717074cf26bSandi
71885d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
719ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
720ab5d26daSAndreas Gohr        return AUTH_ADMIN;
721ab5d26daSAndreas Gohr    }
72285d03f68SAndreas Gohr
723eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
72424870174SAndreas Gohr        $user   = PhpString::strtolower($user);
72524870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
726eb3ce0d5SKazutaka Miyasaka    }
72737ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
72824870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
72985d03f68SAndreas Gohr
7306c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
73137ff2261SSascha Klopp    foreach ($groups as &$group) {
73237ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
73310a76f6fSfrank    }
73410a76f6fSfrank
735f3f0262cSandi    $ns   = getNS($id);
736f3f0262cSandi    $perm = -1;
737f3f0262cSandi
738f3f0262cSandi    //add ALL group
739f3f0262cSandi    $groups[] = '@ALL';
74037ff2261SSascha Klopp
741f3f0262cSandi    //add User
74234aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
743f3f0262cSandi
744f3f0262cSandi    //check exact match first
74521c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
746f3f0262cSandi    if (count($matches)) {
747f3f0262cSandi        foreach ($matches as $match) {
748f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
74921c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
750eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
75124870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
752eb3ce0d5SKazutaka Miyasaka            }
75348d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
75448d7b7a6SDominik Eckelmann                continue;
75548d7b7a6SDominik Eckelmann            }
7568ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
757f3f0262cSandi            if ($acl[2] > $perm) {
758f3f0262cSandi                $perm = $acl[2];
759f3f0262cSandi            }
760f3f0262cSandi        }
761f3f0262cSandi        if ($perm > -1) {
762f3f0262cSandi            //we had a match - return it
763def492a2SGuillaume Turri            return (int) $perm;
764f3f0262cSandi        }
765f3f0262cSandi    }
766f3f0262cSandi
767f3f0262cSandi    //still here? do the namespace checks
768f3f0262cSandi    if ($ns) {
7693e304b55SMichael Hamann        $path = $ns . ':*';
770f3f0262cSandi    } else {
7713e304b55SMichael Hamann        $path = '*'; //root document
772f3f0262cSandi    }
773f3f0262cSandi
774f3f0262cSandi    do {
77521c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
776f3f0262cSandi        if (count($matches)) {
777f3f0262cSandi            foreach ($matches as $match) {
778f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
77921c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
780eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
78124870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
782eb3ce0d5SKazutaka Miyasaka                }
78348d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
78448d7b7a6SDominik Eckelmann                    continue;
78548d7b7a6SDominik Eckelmann                }
7868ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
787f3f0262cSandi                if ($acl[2] > $perm) {
788f3f0262cSandi                    $perm = $acl[2];
789f3f0262cSandi                }
790f3f0262cSandi            }
791f3f0262cSandi            //we had a match - return it
79248d7b7a6SDominik Eckelmann            if ($perm != -1) {
793def492a2SGuillaume Turri                return (int) $perm;
794f3f0262cSandi            }
79548d7b7a6SDominik Eckelmann        }
796f3f0262cSandi        //get next higher namespace
797f3f0262cSandi        $ns = getNS($ns);
798f3f0262cSandi
7993e304b55SMichael Hamann        if ($path != '*') {
8003e304b55SMichael Hamann            $path = $ns . ':*';
8013e304b55SMichael Hamann            if ($path == ':*') $path = '*';
802f3f0262cSandi        } else {
803f3f0262cSandi            //we did this already
804f3f0262cSandi            //looks like there is something wrong with the ACL
805f3f0262cSandi            //break here
806d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
807d5ce66f6SAndreas Gohr            return AUTH_NONE;
808f3f0262cSandi        }
809f3f0262cSandi    } while (1); //this should never loop endless
810ab5d26daSAndreas Gohr    return AUTH_NONE;
811f3f0262cSandi}
812f3f0262cSandi
813f3f0262cSandi/**
8146c2bb100SAndreas Gohr * Encode ASCII special chars
8156c2bb100SAndreas Gohr *
8166c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8176c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8186c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8196c2bb100SAndreas Gohr * urlencoding!).
8206c2bb100SAndreas Gohr *
8216c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8226c2bb100SAndreas Gohr *
8236c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8246c2bb100SAndreas Gohr * @see rawurldecode()
82542ea7f44SGerrit Uitslag *
82642ea7f44SGerrit Uitslag * @param string $name
82742ea7f44SGerrit Uitslag * @param bool $skip_group
82842ea7f44SGerrit Uitslag * @return string
8296c2bb100SAndreas Gohr */
830d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
831d868eb89SAndreas Gohr{
832a424cd8eSchris    global $cache_authname;
833a424cd8eSchris    $cache =& $cache_authname;
83431784267SAndreas Gohr    $name  = (string) $name;
835a424cd8eSchris
83680601d26SAndreas Gohr    // never encode wildcard FS#1955
83780601d26SAndreas Gohr    if ($name == '%USER%') return $name;
838b78bf706Sromain    if ($name == '%GROUP%') return $name;
83980601d26SAndreas Gohr
840a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8412401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
84230f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
84330f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
844dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
845dccd6b2bSAndreas Gohr                substr($name, 1)
846ab5d26daSAndreas Gohr            );
847e838fc2eSAndreas Gohr        } else {
84830f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
84930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
850dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
851dccd6b2bSAndreas Gohr                $name
852ab5d26daSAndreas Gohr            );
853e838fc2eSAndreas Gohr        }
8546c2bb100SAndreas Gohr    }
8556c2bb100SAndreas Gohr
856a424cd8eSchris    return $cache[$name][$skip_group];
857a424cd8eSchris}
858a424cd8eSchris
85904d68ae4SGerrit Uitslag/**
86004d68ae4SGerrit Uitslag * callback encodes the matches
86104d68ae4SGerrit Uitslag *
86204d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
86304d68ae4SGerrit Uitslag * @return string
86404d68ae4SGerrit Uitslag */
865d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
866d868eb89SAndreas Gohr{
86730f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
86830f6faf0SChristopher Smith}
86930f6faf0SChristopher Smith
8706c2bb100SAndreas Gohr/**
871f3f0262cSandi * Create a pronouncable password
872f3f0262cSandi *
8738a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
8748a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
8758a285f7fSAndreas Gohr *
8764dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
8774dc42f7fSGerrit Uitslag * @return string  pronouncable password
8784dc42f7fSGerrit Uitslag * @throws Exception
8794dc42f7fSGerrit Uitslag *
88015fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
8818a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
88215fae107Sandi *
8834dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
884f3f0262cSandi */
885d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
886d868eb89SAndreas Gohr{
88724870174SAndreas Gohr    $data = [
888d628dcf3SAndreas Gohr        'password' => '',
889d628dcf3SAndreas Gohr        'foruser'  => $foruser
89024870174SAndreas Gohr    ];
8918a285f7fSAndreas Gohr
892e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8938a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
894f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
895f3f0262cSandi        $v = 'aeiou'; //vowels
896f3f0262cSandi        $a = $c . $v; //both
897987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
898f3f0262cSandi
899987c8d26SAndreas Gohr        //use thre syllables...
900987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
901483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
902483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
903483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
904f3f0262cSandi        }
905987c8d26SAndreas Gohr        //... and add a nice number and special
90643f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9078a285f7fSAndreas Gohr    }
9088a285f7fSAndreas Gohr    $evt->advise_after();
909f3f0262cSandi
9108a285f7fSAndreas Gohr    return $data['password'];
911f3f0262cSandi}
912f3f0262cSandi
913f3f0262cSandi/**
914f3f0262cSandi * Sends a password to the given user
915f3f0262cSandi *
91615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
91742ea7f44SGerrit Uitslag *
918ab5d26daSAndreas Gohr * @param string $user Login name of the user
919ab5d26daSAndreas Gohr * @param string $password The new password in clear text
92015fae107Sandi * @return bool  true on success
921f3f0262cSandi */
922d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
923d868eb89SAndreas Gohr{
924f3f0262cSandi    global $lang;
925e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
926cd52f92dSchris    global $auth;
9276547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
928cd52f92dSchris
929d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9304dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
931f3f0262cSandi
93287ddda95Sandi    if (!$userinfo['mail']) return false;
933f3f0262cSandi
934f3f0262cSandi    $text = rawLocale('password');
93524870174SAndreas Gohr    $trep = [
936d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
937d7169d19SAndreas Gohr        'LOGIN'    => $user,
938d7169d19SAndreas Gohr        'PASSWORD' => $password
93924870174SAndreas Gohr    ];
940f3f0262cSandi
941d7169d19SAndreas Gohr    $mail = new Mailer();
942102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
943d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
944d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
945d7169d19SAndreas Gohr    return $mail->send();
946f3f0262cSandi}
947f3f0262cSandi
948f3f0262cSandi/**
94915fae107Sandi * Register a new user
950f3f0262cSandi *
95115fae107Sandi * This registers a new user - Data is read directly from $_POST
95215fae107Sandi *
95315fae107Sandi * @return bool  true on success, false on any error
9544dc42f7fSGerrit Uitslag * @throws Exception
9554dc42f7fSGerrit Uitslag *
9564dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
957f3f0262cSandi */
958d868eb89SAndreas Gohrfunction register()
959d868eb89SAndreas Gohr{
960f3f0262cSandi    global $lang;
961eb5d07e4Sjan    global $conf;
9624dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
963cd52f92dSchris    global $auth;
96464273335SAndreas Gohr    global $INPUT;
965f3f0262cSandi
96664273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9673a48618aSAnika Henke    if (!actionOK('register')) return false;
968640145a5Sandi
96964273335SAndreas Gohr    // gather input
97064273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
97164273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
97264273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
97364273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
97464273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
975d752aedeSAndreas Gohr
97664273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
977f3f0262cSandi        msg($lang['regmissing'], -1);
978f3f0262cSandi        return false;
979f3f0262cSandi    }
980f3f0262cSandi
981cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
9828a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
98364273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
984bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
985cab2716aSmatthias.grimm        return false;
98664273335SAndreas Gohr    } elseif ($pass != $passchk) {
987bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
988cab2716aSmatthias.grimm        return false;
989cab2716aSmatthias.grimm    }
990cab2716aSmatthias.grimm
991f3f0262cSandi    //check mail
99264273335SAndreas Gohr    if (!mail_isvalid($email)) {
993f3f0262cSandi        msg($lang['regbadmail'], -1);
994f3f0262cSandi        return false;
995f3f0262cSandi    }
996f3f0262cSandi
997f3f0262cSandi    //okay try to create the user
99824870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
999db9faf02SPatrick Brown        msg($lang['regfail'], -1);
1000f3f0262cSandi        return false;
1001f3f0262cSandi    }
1002f3f0262cSandi
1003790b7720SAndreas Gohr    // send notification about the new user
100475d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
100575d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
100602a498e7Schris
1007790b7720SAndreas Gohr    // are we done?
1008cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1009cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1010cab2716aSmatthias.grimm        return true;
1011cab2716aSmatthias.grimm    }
1012cab2716aSmatthias.grimm
1013790b7720SAndreas Gohr    // autogenerated password? then send password to user
101464273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1015f3f0262cSandi        msg($lang['regsuccess'], 1);
1016f3f0262cSandi        return true;
1017f3f0262cSandi    } else {
1018f3f0262cSandi        msg($lang['regmailfail'], -1);
1019f3f0262cSandi        return false;
1020f3f0262cSandi    }
1021f3f0262cSandi}
1022f3f0262cSandi
102310a76f6fSfrank/**
10248b06d178Schris * Update user profile
10258b06d178Schris *
10264dc42f7fSGerrit Uitslag * @throws Exception
10274dc42f7fSGerrit Uitslag *
10288b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10298b06d178Schris */
1030d868eb89SAndreas Gohrfunction updateprofile()
1031d868eb89SAndreas Gohr{
10328b06d178Schris    global $conf;
10338b06d178Schris    global $lang;
1034e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1035cd52f92dSchris    global $auth;
1036bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1037bcc94b2cSAndreas Gohr    global $INPUT;
10388b06d178Schris
1039bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10401b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10418b06d178Schris
10423a48618aSAnika Henke    if (!actionOK('profile')) {
10438b06d178Schris        msg($lang['profna'], -1);
10448b06d178Schris        return false;
10458b06d178Schris    }
10468b06d178Schris
104724870174SAndreas Gohr    $changes         = [];
1048bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1049bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1050bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1051bcc94b2cSAndreas Gohr
1052bcc94b2cSAndreas Gohr    // check misspelled passwords
1053bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1054bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10558b06d178Schris        return false;
10568b06d178Schris    }
10578b06d178Schris
10588b06d178Schris    // clean fullname and email
1059bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1060bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10618b06d178Schris
1062bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
10637d34963bSAndreas Gohr    if (
10647d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1065bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1066ab5d26daSAndreas Gohr    ) {
10678b06d178Schris        msg($lang['profnoempty'], -1);
10688b06d178Schris        return false;
10698b06d178Schris    }
1070bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10718b06d178Schris        msg($lang['regbadmail'], -1);
10728b06d178Schris        return false;
10738b06d178Schris    }
10748b06d178Schris
1075bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
10764c21b7eeSAndreas Gohr
1077bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1078bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1079bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1080bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1081bcc94b2cSAndreas Gohr
1082bcc94b2cSAndreas Gohr    // anything to do?
108324870174SAndreas Gohr    if ($changes === []) {
10848b06d178Schris        msg($lang['profnochange'], -1);
10858b06d178Schris        return false;
10868b06d178Schris    }
10878b06d178Schris
10888b06d178Schris    if ($conf['profileconfirm']) {
1089585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
109071422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
10918b06d178Schris            return false;
10928b06d178Schris        }
10938b06d178Schris    }
10948b06d178Schris
109524870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1096db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1097db9faf02SPatrick Brown        return false;
1098db9faf02SPatrick Brown    }
1099db9faf02SPatrick Brown
110067efd1edSPieter Hollants    if (array_key_exists('pass', $changes) && $changes['pass']) {
1101c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1102a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
110304369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1104585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1105c276e9e8SMarcel Pennewiss    } else {
1106c276e9e8SMarcel Pennewiss        // make sure the session is writable
1107c276e9e8SMarcel Pennewiss        @session_start();
1108c276e9e8SMarcel Pennewiss        // invalidate session cache
1109c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1110c276e9e8SMarcel Pennewiss        session_write_close();
111132ed2b36SAndreas Gohr    }
1112c276e9e8SMarcel Pennewiss
111325b2a98cSMichael Klier    return true;
1114a0b5b007SChris Smith}
1115ab5d26daSAndreas Gohr
111604d68ae4SGerrit Uitslag/**
111704d68ae4SGerrit Uitslag * Delete the current logged-in user
111804d68ae4SGerrit Uitslag *
111904d68ae4SGerrit Uitslag * @return bool true on success, false on any error
112004d68ae4SGerrit Uitslag */
1121d868eb89SAndreas Gohrfunction auth_deleteprofile()
1122d868eb89SAndreas Gohr{
11232a7abf2dSChristopher Smith    global $conf;
11242a7abf2dSChristopher Smith    global $lang;
11254dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11262a7abf2dSChristopher Smith    global $auth;
11272a7abf2dSChristopher Smith    /* @var Input $INPUT */
11282a7abf2dSChristopher Smith    global $INPUT;
11292a7abf2dSChristopher Smith
11302a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11312a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11322a7abf2dSChristopher Smith
11332a7abf2dSChristopher Smith    // action prevented or auth module disallows
11342a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11352a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11362a7abf2dSChristopher Smith        return false;
11372a7abf2dSChristopher Smith    }
11382a7abf2dSChristopher Smith
11392a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11402a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11412a7abf2dSChristopher Smith        return false;
11422a7abf2dSChristopher Smith    }
11432a7abf2dSChristopher Smith
11442a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1145585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11462a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11472a7abf2dSChristopher Smith            return false;
11482a7abf2dSChristopher Smith        }
11492a7abf2dSChristopher Smith    }
11502a7abf2dSChristopher Smith
115124870174SAndreas Gohr    $deleted = [];
1152585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
115324870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
11542a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11552a7abf2dSChristopher Smith        auth_logoff();
11562a7abf2dSChristopher Smith        return true;
11572a7abf2dSChristopher Smith    }
11582a7abf2dSChristopher Smith
11592a7abf2dSChristopher Smith    return false;
11602a7abf2dSChristopher Smith}
11612a7abf2dSChristopher Smith
11628b06d178Schris/**
11638b06d178Schris * Send a  new password
11648b06d178Schris *
11651d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11661d5856cfSAndreas Gohr *
11671d5856cfSAndreas Gohr *   - handling the first request of password reset
11681d5856cfSAndreas Gohr *   - validating the password reset auth token
11691d5856cfSAndreas Gohr *
11704dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
11714dc42f7fSGerrit Uitslag * @throws Exception
11724dc42f7fSGerrit Uitslag *
11734dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
11748b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
11758b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
11768b06d178Schris */
1177d868eb89SAndreas Gohrfunction act_resendpwd()
1178d868eb89SAndreas Gohr{
11798b06d178Schris    global $lang;
11808b06d178Schris    global $conf;
1181e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1182cd52f92dSchris    global $auth;
1183bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1184bcc94b2cSAndreas Gohr    global $INPUT;
11858b06d178Schris
11863a48618aSAnika Henke    if (!actionOK('resendpwd')) {
11878b06d178Schris        msg($lang['resendna'], -1);
11888b06d178Schris        return false;
11898b06d178Schris    }
11908b06d178Schris
1191bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
11928b06d178Schris
11931d5856cfSAndreas Gohr    if ($token) {
1194cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
11951d5856cfSAndreas Gohr
11962401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
119779e79377SAndreas Gohr        if (!file_exists($tfile)) {
11981d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1199bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12001d5856cfSAndreas Gohr            return false;
12011d5856cfSAndreas Gohr        }
12028a9735e3SAndreas Gohr        // token is only valid for 3 days
12038a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12048a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1205bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12061d5856cfSAndreas Gohr            @unlink($tfile);
12078a9735e3SAndreas Gohr            return false;
12088a9735e3SAndreas Gohr        }
12098a9735e3SAndreas Gohr
12108b06d178Schris        $user     = io_readfile($tfile);
12114dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12128b06d178Schris        if (!$userinfo['mail']) {
12138b06d178Schris            msg($lang['resendpwdnouser'], -1);
12148b06d178Schris            return false;
12158b06d178Schris        }
12168b06d178Schris
1217cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1218bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1219bcc94b2cSAndreas Gohr
1220cc204bbdSAndreas Gohr            // password given correctly?
1221bcc94b2cSAndreas Gohr            if (!$pass) return false;
1222bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1223451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1224cc204bbdSAndreas Gohr                return false;
1225cc204bbdSAndreas Gohr            }
1226cc204bbdSAndreas Gohr
1227bcc94b2cSAndreas Gohr            // change it
122824870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1229db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1230cc204bbdSAndreas Gohr                return false;
1231cc204bbdSAndreas Gohr            }
1232cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12338a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
123424870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1235db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12368b06d178Schris                return false;
12378b06d178Schris            }
12388b06d178Schris
12398b06d178Schris            if (auth_sendPassword($user, $pass)) {
12408b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12418b06d178Schris            } else {
12428b06d178Schris                msg($lang['regmailfail'], -1);
12438b06d178Schris            }
1244cc204bbdSAndreas Gohr        }
1245cc204bbdSAndreas Gohr
1246cc204bbdSAndreas Gohr        @unlink($tfile);
12478b06d178Schris        return true;
12481d5856cfSAndreas Gohr    } else {
12491d5856cfSAndreas Gohr        // we're in request phase
12501d5856cfSAndreas Gohr
1251bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
12521d5856cfSAndreas Gohr
1253bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
12541d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12551d5856cfSAndreas Gohr            return false;
12561d5856cfSAndreas Gohr        } else {
1257bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12581d5856cfSAndreas Gohr        }
12591d5856cfSAndreas Gohr
12604dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12611d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
12621d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12631d5856cfSAndreas Gohr            return false;
12641d5856cfSAndreas Gohr        }
12651d5856cfSAndreas Gohr
12661d5856cfSAndreas Gohr        // generate auth token
1267483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12682401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
126924870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
12701d5856cfSAndreas Gohr
12711d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12721d5856cfSAndreas Gohr
12731d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
127424870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
12751d5856cfSAndreas Gohr
1276d7169d19SAndreas Gohr        $mail = new Mailer();
1277d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1278d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1279d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1280d7169d19SAndreas Gohr        if ($mail->send()) {
12811d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
12821d5856cfSAndreas Gohr        } else {
12831d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
12841d5856cfSAndreas Gohr        }
12851d5856cfSAndreas Gohr        return true;
12861d5856cfSAndreas Gohr    }
1287ab5d26daSAndreas Gohr    // never reached
12888b06d178Schris}
12898b06d178Schris
12908b06d178Schris/**
1291b0855b11Sandi * Encrypts a password using the given method and salt
1292b0855b11Sandi *
1293b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1294b0855b11Sandi * is chosen.
1295b0855b11Sandi *
1296b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
129742ea7f44SGerrit Uitslag *
1298ab5d26daSAndreas Gohr * @param string $clear The clear text password
1299ab5d26daSAndreas Gohr * @param string $method The hashing method
1300ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1301b0855b11Sandi * @return  string  The crypted password
1302b0855b11Sandi */
1303d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1304d868eb89SAndreas Gohr{
1305b0855b11Sandi    global $conf;
1306b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
130710a76f6fSfrank
13083a0a2d05SAndreas Gohr    $pass = new PassHash();
13093a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1310b0855b11Sandi
13113a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1312b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13133a0a2d05SAndreas Gohr        return false;
1314b0855b11Sandi    }
13153a0a2d05SAndreas Gohr
13163a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1317b0855b11Sandi}
1318b0855b11Sandi
1319b0855b11Sandi/**
1320b0855b11Sandi * Verifies a cleartext password against a crypted hash
1321b0855b11Sandi *
1322ab5d26daSAndreas Gohr * @param string $clear The clear text password
1323ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1324ab5d26daSAndreas Gohr * @return bool true if both match
13254dc42f7fSGerrit Uitslag * @throws Exception
13264dc42f7fSGerrit Uitslag *
13274dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1328b0855b11Sandi */
1329d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1330d868eb89SAndreas Gohr{
13313a0a2d05SAndreas Gohr    $pass = new PassHash();
13323a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1333b0855b11Sandi}
1334340756e4Sandi
1335a0b5b007SChris Smith/**
1336a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1337a0b5b007SChris Smith *
1338a0b5b007SChris Smith * @param string  $user       username
1339a0b5b007SChris Smith * @param string  $pass       encrypted password
1340a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1341ab5d26daSAndreas Gohr * @return bool
1342a0b5b007SChris Smith */
1343d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1344d868eb89SAndreas Gohr{
1345a0b5b007SChris Smith    global $conf;
1346e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1347a0b5b007SChris Smith    global $auth;
134879d00841SOliver Geisen    global $USERINFO;
1349a0b5b007SChris Smith
13506547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1351a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1352a0b5b007SChris Smith
1353a0b5b007SChris Smith    // set cookie
1354645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
135573ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1356c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1357bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1358bf8392ebSAndreas Gohr        'expires' => $time,
1359bf8392ebSAndreas Gohr        'path' => $cookieDir,
1360bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1361bf8392ebSAndreas Gohr        'httponly' => true,
1362486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1363bf8392ebSAndreas Gohr    ]);
136455a71a16SGerrit Uitslag
1365a0b5b007SChris Smith    // set session
1366a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1367234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1368a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1369a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1370a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1371ab5d26daSAndreas Gohr
1372ab5d26daSAndreas Gohr    return true;
1373a0b5b007SChris Smith}
1374a0b5b007SChris Smith
1375645c0a36SAndreas Gohr/**
1376645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1377645c0a36SAndreas Gohr *
1378645c0a36SAndreas Gohr * @returns array
1379645c0a36SAndreas Gohr */
1380d868eb89SAndreas Gohrfunction auth_getCookie()
1381d868eb89SAndreas Gohr{
1382c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
138324870174SAndreas Gohr        return [null, null, null];
1384c66972f2SAdrian Lang    }
138524870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1386645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1387645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1388645c0a36SAndreas Gohr    $user   = base64_decode($user);
138924870174SAndreas Gohr    return [$user, $sticky, $pass];
1390645c0a36SAndreas Gohr}
1391645c0a36SAndreas Gohr
1392e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1393