xref: /dokuwiki/inc/auth.php (revision d26e5a249c08175c8e21d18171117a817c2d5280)
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
1324870174SAndreas Gohruse phpseclib\Crypt\AES;
1424870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1596348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1696348f27SAndreas Gohruse dokuwiki\Extension\Event;
1796348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
18c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
1975d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
20c3cc6e05SAndreas Gohr
2116905344SAndreas Gohr/**
2216905344SAndreas Gohr * Initialize the auth system.
2316905344SAndreas Gohr *
2416905344SAndreas Gohr * This function is automatically called at the end of init.php
2516905344SAndreas Gohr *
2616905344SAndreas Gohr * This used to be the main() of the auth.php
2716905344SAndreas Gohr *
2816905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
2916905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
30ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
31ab5d26daSAndreas Gohr * @return bool
3216905344SAndreas Gohr */
33d868eb89SAndreas Gohrfunction auth_setup()
34d868eb89SAndreas Gohr{
35742c66f8Schris    global $conf;
36e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
3703c4aec3Schris    global $auth;
38bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
39bcc94b2cSAndreas Gohr    global $INPUT;
409a9714acSDominik Eckelmann    global $AUTH_ACL;
419a9714acSDominik Eckelmann    global $lang;
423a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
439c29eea5SJan Schumann    global $plugin_controller;
4424870174SAndreas Gohr    $AUTH_ACL = [];
4503c4aec3Schris
4616905344SAndreas Gohr    if (!$conf['useacl']) return false;
4716905344SAndreas Gohr
489c29eea5SJan Schumann    // try to load auth backend from plugins
499c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
509c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
51f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
529c29eea5SJan Schumann            break;
539c29eea5SJan Schumann        }
549c29eea5SJan Schumann    }
558b06d178Schris
566547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) {
5771c734a9SGerrit Uitslag        msg($lang['authtempfail'], -1);
583094e817SAndreas Gohr        return false;
593094e817SAndreas Gohr    }
608b06d178Schris
616416b708SMichael Hamann    if ($auth->success == false) {
620f4f4adfSAndreas Gohr        // degrade to unauthenticated user
63ecad51ddSAndreas Gohr        $auth = null;
640f4f4adfSAndreas Gohr        auth_logoff();
65cd52f92dSchris        msg($lang['authtempfail'], -1);
666416b708SMichael Hamann        return false;
67d2dde4ebSMatthias Grimm    }
6816905344SAndreas Gohr
6916905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
70bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
71bcc94b2cSAndreas Gohr    if (!$conf['rememberme']) $INPUT->set('r', false);
72bbbd6568SAndreas Gohr
7362bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
7462bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
7562bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
7662bf3ac0SDamien Regad    if (preg_match('~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches)) {
7762bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
7824870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
79528ddc7cSAndreas Gohr    }
80528ddc7cSAndreas Gohr
811e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
8203062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
8303062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
8403062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
85bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
861e8c9c90SAndreas Gohr    }
871e8c9c90SAndreas Gohr
88395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
8993a7873eSAndreas Gohr    if (true === $auth->success) {
90395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
92f4476bd9SJan Schumann    }
93191bb90aSAndreas Gohr
94455aa67eSAndreas Gohr    if(!auth_tokenlogin()) {
9581e99965SPhy        $ok = null;
96455aa67eSAndreas Gohr
976547cfc7SGerrit Uitslag        if ($auth instanceof AuthPlugin && $auth->canDo('external')) {
9881e99965SPhy            $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
9981e99965SPhy        }
10081e99965SPhy
10181e99965SPhy        if ($ok === null) {
10281e99965SPhy            // external trust mechanism not in place, or returns no result,
10381e99965SPhy            // then attempt auth_login
10424870174SAndreas Gohr            $evdata = [
105bcc94b2cSAndreas Gohr                'user' => $INPUT->str('u'),
106bcc94b2cSAndreas Gohr                'password' => $INPUT->str('p'),
107bcc94b2cSAndreas Gohr                'sticky' => $INPUT->bool('r'),
108bcc94b2cSAndreas Gohr                'silent' => $INPUT->bool('http_credentials')
10924870174SAndreas Gohr            ];
110cbb44eabSAndreas Gohr            Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
111f5cb575dSAndreas Gohr        }
112455aa67eSAndreas Gohr    }
113f5cb575dSAndreas Gohr
11416905344SAndreas Gohr    //load ACL into a global array XXX
11575c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
116ab5d26daSAndreas Gohr
117ab5d26daSAndreas Gohr    return true;
11875c93b77SAndreas Gohr}
11975c93b77SAndreas Gohr
12075c93b77SAndreas Gohr/**
12175c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
12275c93b77SAndreas Gohr *
12375c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12442ea7f44SGerrit Uitslag *
125ab5d26daSAndreas Gohr * @return array
12675c93b77SAndreas Gohr */
127d868eb89SAndreas Gohrfunction auth_loadACL()
128d868eb89SAndreas Gohr{
12975c93b77SAndreas Gohr    global $config_cascade;
130b78bf706Sromain    global $USERINFO;
131585bf44eSChristopher Smith    /* @var Input $INPUT */
132585bf44eSChristopher Smith    global $INPUT;
13375c93b77SAndreas Gohr
13424870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
13575c93b77SAndreas Gohr
13675c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13775c93b77SAndreas Gohr
13824870174SAndreas Gohr    $out = [];
1399ce556d2SAndreas Gohr    foreach ($acl as $line) {
1409ce556d2SAndreas Gohr        $line = trim($line);
1412401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
14224870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
14332e82180SAndreas Gohr
144443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
145ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
146ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
147585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
148ad3d68d7SChristopher Smith
149585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
150585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
151ad3d68d7SChristopher Smith        }
152ad3d68d7SChristopher Smith
153ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1549ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
155ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
15606f34f54SPhy            if (isset($USERINFO['grps'])) {
1579ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
158b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
15932e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
16032e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
161b78bf706Sromain                }
16206f34f54SPhy            }
16332e82180SAndreas Gohr        } else {
16432e82180SAndreas Gohr            $out[] = "$id\t$rest";
165a8fe108bSGuy Brand        }
16611799630Sandi    }
1679ce556d2SAndreas Gohr
16832e82180SAndreas Gohr    return $out;
169f3f0262cSandi}
170f3f0262cSandi
171ab5d26daSAndreas Gohr/**
172455aa67eSAndreas Gohr * Try a token login
173455aa67eSAndreas Gohr *
174455aa67eSAndreas Gohr * @return bool true if token login succeeded
175455aa67eSAndreas Gohr */
176455aa67eSAndreas Gohrfunction auth_tokenlogin() {
177455aa67eSAndreas Gohr    global $USERINFO;
178455aa67eSAndreas Gohr    global $INPUT;
179455aa67eSAndreas Gohr    /** @var DokuWiki_Auth_Plugin $auth */
180455aa67eSAndreas Gohr    global $auth;
181455aa67eSAndreas Gohr    if(!$auth) return false;
182455aa67eSAndreas Gohr
183455aa67eSAndreas Gohr    // see if header has token
184455aa67eSAndreas Gohr    $header = '';
185455aa67eSAndreas Gohr    if(function_exists('apache_request_headers')) {
186455aa67eSAndreas Gohr        // Authorization headers are not in $_SERVER for mod_php
187*d26e5a24SAndreas Gohr        $headers = array_change_key_case(apache_request_headers());
188*d26e5a24SAndreas Gohr        if(isset($headers['authorization'])) $header = $headers['authorization'];
189455aa67eSAndreas Gohr    } else {
190455aa67eSAndreas Gohr        $header = $INPUT->server->str('HTTP_AUTHORIZATION');
191455aa67eSAndreas Gohr    }
192455aa67eSAndreas Gohr    if(!$header) return false;
193455aa67eSAndreas Gohr    list($type, $token) = sexplode(' ', $header, 2);
194455aa67eSAndreas Gohr    if($type !== 'Bearer') return false;
195455aa67eSAndreas Gohr
196455aa67eSAndreas Gohr    // check token
197455aa67eSAndreas Gohr    try {
198455aa67eSAndreas Gohr        $authtoken = \dokuwiki\JWT::validate($token);
199455aa67eSAndreas Gohr    } catch (Exception $e) {
200455aa67eSAndreas Gohr        msg(hsc($e->getMessage()), -1);
201455aa67eSAndreas Gohr        return false;
202455aa67eSAndreas Gohr    }
203455aa67eSAndreas Gohr
204455aa67eSAndreas Gohr    // fetch user info from backend
205455aa67eSAndreas Gohr    $user = $authtoken->getUser();
206455aa67eSAndreas Gohr    $USERINFO = $auth->getUserData($user);
207455aa67eSAndreas Gohr    if(!$USERINFO) return false;
208455aa67eSAndreas Gohr
209455aa67eSAndreas Gohr    // the code is correct, set up user
210455aa67eSAndreas Gohr    $INPUT->server->set('REMOTE_USER', $user);
211455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
212455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = 'nope';
213455aa67eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
214455aa67eSAndreas Gohr
215455aa67eSAndreas Gohr    return true;
216455aa67eSAndreas Gohr}
217455aa67eSAndreas Gohr
218455aa67eSAndreas Gohr/**
219ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
220ab5d26daSAndreas Gohr *
22142ea7f44SGerrit Uitslag * @param array $evdata
222ab5d26daSAndreas Gohr * @return bool
2234dc42f7fSGerrit Uitslag * @throws Exception
224ab5d26daSAndreas Gohr */
225d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
226d868eb89SAndreas Gohr{
227ab5d26daSAndreas Gohr    return auth_login(
228ab5d26daSAndreas Gohr        $evdata['user'],
229b5ee21aaSAdrian Lang        $evdata['password'],
230b5ee21aaSAdrian Lang        $evdata['sticky'],
231ab5d26daSAndreas Gohr        $evdata['silent']
232ab5d26daSAndreas Gohr    );
233b5ee21aaSAdrian Lang}
234b5ee21aaSAdrian Lang
235f3f0262cSandi/**
236f3f0262cSandi * This tries to login the user based on the sent auth credentials
237f3f0262cSandi *
238f3f0262cSandi * The authentication works like this: if a username was given
23915fae107Sandi * a new login is assumed and user/password are checked. If they
24015fae107Sandi * are correct the password is encrypted with blowfish and stored
24115fae107Sandi * together with the username in a cookie - the same info is stored
24215fae107Sandi * in the session, too. Additonally a browserID is stored in the
24315fae107Sandi * session.
24415fae107Sandi *
24515fae107Sandi * If no username was given the cookie is checked: if the username,
24615fae107Sandi * crypted password and browserID match between session and cookie
24715fae107Sandi * no further testing is done and the user is accepted
24815fae107Sandi *
24915fae107Sandi * If a cookie was found but no session info was availabe the
250136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
25115fae107Sandi * together with username rechecked by calling this function again.
252f3f0262cSandi *
253f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
254f3f0262cSandi * are set.
25515fae107Sandi *
25615fae107Sandi * @param string $user Username
25715fae107Sandi * @param string $pass Cleartext Password
25815fae107Sandi * @param bool $sticky Cookie should not expire
259f112c2faSAndreas Gohr * @param bool $silent Don't show error on bad auth
26015fae107Sandi * @return bool true on successful auth
2614dc42f7fSGerrit Uitslag * @throws Exception
2624dc42f7fSGerrit Uitslag *
2634dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
264f3f0262cSandi */
265d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
266d868eb89SAndreas Gohr{
267f3f0262cSandi    global $USERINFO;
268f3f0262cSandi    global $conf;
269f3f0262cSandi    global $lang;
270e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
271cd52f92dSchris    global $auth;
272585bf44eSChristopher Smith    /* @var Input $INPUT */
273585bf44eSChristopher Smith    global $INPUT;
274ab5d26daSAndreas Gohr
2756547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
276beca106aSAdrian Lang
277bbbd6568SAndreas Gohr    if (!empty($user)) {
278132bdbfeSandi        //usual login
2795e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
280132bdbfeSandi            // make logininfo globally available
281585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
28230d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
28304369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
284132bdbfeSandi            return true;
285f3f0262cSandi        } else {
286f3f0262cSandi            //invalid credentials - log off
287f8b1e4e7SAndreas Gohr            if (!$silent) {
288f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
289f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
290f8b1e4e7SAndreas Gohr            }
291f3f0262cSandi            auth_logoff();
292132bdbfeSandi            return false;
293f3f0262cSandi        }
294f3f0262cSandi    } else {
295132bdbfeSandi        // read cookie information
29624870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
297132bdbfeSandi        if ($user && $pass) {
298132bdbfeSandi            // we got a cookie - see if we can trust it
299fa7c70ffSAdrian Lang
300fa7c70ffSAdrian Lang            // get session info
3010058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
302fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
3037d34963bSAndreas Gohr                if (
3047d34963bSAndreas Gohr                    isset($session) &&
3057172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
3064c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
307132bdbfeSandi                    ($session['user'] == $user) &&
308234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
309ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
310ab5d26daSAndreas Gohr                ) {
311132bdbfeSandi                    // he has session, cookie and browser right - let him in
312585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
313132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
314132bdbfeSandi                    return true;
315132bdbfeSandi                }
3160058ae75SDamien Regad            }
317f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
31830d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
31904369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
320f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
321132bdbfeSandi        }
322132bdbfeSandi    }
323f3f0262cSandi    //just to be sure
324883179a4SAndreas Gohr    auth_logoff(true);
325132bdbfeSandi    return false;
326f3f0262cSandi}
327132bdbfeSandi
328132bdbfeSandi/**
329136ce040Sandi * Builds a pseudo UID from browser and IP data
330132bdbfeSandi *
331132bdbfeSandi * This is neither unique nor unfakable - still it adds some
332136ce040Sandi * security. Using the first part of the IP makes sure
33380b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
33415fae107Sandi *
33515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
33615fae107Sandi *
337b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
338132bdbfeSandi */
339d868eb89SAndreas Gohrfunction auth_browseruid()
340d868eb89SAndreas Gohr{
341585bf44eSChristopher Smith    /* @var Input $INPUT */
342585bf44eSChristopher Smith    global $INPUT;
343585bf44eSChristopher Smith
3442f9daf16SAndreas Gohr    $ip = clientIP(true);
345b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
346b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
347b7c67f83SAndreas Gohr
348b7c67f83SAndreas Gohr    $uid = implode("\n", [
349b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
350b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
351b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
352b7c67f83SAndreas Gohr    ]);
353b13c0e1aSAdaKaleh    return hash('sha256', $uid);
354132bdbfeSandi}
355132bdbfeSandi
356132bdbfeSandi/**
357132bdbfeSandi * Creates a random key to encrypt the password in cookies
35815fae107Sandi *
35915fae107Sandi * This function tries to read the password for encrypting
36098407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
36115fae107Sandi * if no such file is found a random key is created and
36215fae107Sandi * and stored in this file.
36315fae107Sandi *
36432ed2b36SAndreas Gohr * @param bool $addsession if true, the sessionid is added to the salt
36530d544a4SMichael Hamann * @param bool $secure if security is more important than keeping the old value
36615fae107Sandi * @return  string
3674dc42f7fSGerrit Uitslag * @throws Exception
3684dc42f7fSGerrit Uitslag *
3694dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
370132bdbfeSandi */
371d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
372d868eb89SAndreas Gohr{
373a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
374fe745becSMichael Große        return 'test';
375a1fe3c9cSMichael Große    }
376132bdbfeSandi    global $conf;
37798407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
37830d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
37930d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
38030d544a4SMichael Hamann    }
381132bdbfeSandi    $salt = io_readFile($file);
382132bdbfeSandi    if (empty($salt)) {
38330d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
384132bdbfeSandi        io_saveFile($file, $salt);
385132bdbfeSandi    }
38632ed2b36SAndreas Gohr    if ($addsession) {
38732ed2b36SAndreas Gohr        $salt .= session_id();
38832ed2b36SAndreas Gohr    }
389132bdbfeSandi    return $salt;
390f3f0262cSandi}
391f3f0262cSandi
392f3f0262cSandi/**
3937a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
394483b6238SMichael Hamann *
3957a33d2f8SNiklas Keller * @param int $length number of bytes
3967a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
3974dc42f7fSGerrit Uitslag * @throws Exception
3984dc42f7fSGerrit Uitslag *
3994dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
400483b6238SMichael Hamann */
401d868eb89SAndreas Gohrfunction auth_randombytes($length)
402d868eb89SAndreas Gohr{
4037a33d2f8SNiklas Keller    return random_bytes($length);
404483b6238SMichael Hamann}
405483b6238SMichael Hamann
406483b6238SMichael Hamann/**
4077a33d2f8SNiklas Keller * Cryptographically secure random number generator.
408483b6238SMichael Hamann *
409483b6238SMichael Hamann * @param int $min
410483b6238SMichael Hamann * @param int $max
411483b6238SMichael Hamann * @return int
4124dc42f7fSGerrit Uitslag * @throws Exception
4134dc42f7fSGerrit Uitslag *
4144dc42f7fSGerrit Uitslag * @author Niklas Keller <me@kelunik.com>
415483b6238SMichael Hamann */
416d868eb89SAndreas Gohrfunction auth_random($min, $max)
417d868eb89SAndreas Gohr{
4187a33d2f8SNiklas Keller    return random_int($min, $max);
419483b6238SMichael Hamann}
420483b6238SMichael Hamann
421483b6238SMichael Hamann/**
42204369c3eSMichael Hamann * Encrypt data using the given secret using AES
42304369c3eSMichael Hamann *
42404369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
42504369c3eSMichael Hamann * using pbkdf2.
42604369c3eSMichael Hamann *
42704369c3eSMichael Hamann * @param string $data The data that shall be encrypted
42804369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
42904369c3eSMichael Hamann * @return string The ciphertext
4304dc42f7fSGerrit Uitslag * @throws Exception
43104369c3eSMichael Hamann */
432d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
433d868eb89SAndreas Gohr{
43404369c3eSMichael Hamann    $iv     = auth_randombytes(16);
43524870174SAndreas Gohr    $cipher = new AES();
43604369c3eSMichael Hamann    $cipher->setPassword($secret);
43704369c3eSMichael Hamann
4387b650cefSMichael Hamann    /*
4397b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
4407b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
4417b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
4427b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
4437b650cefSMichael Hamann    */
44404369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
44504369c3eSMichael Hamann}
44604369c3eSMichael Hamann
44704369c3eSMichael Hamann/**
44804369c3eSMichael Hamann * Decrypt the given AES ciphertext
44904369c3eSMichael Hamann *
45004369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
45104369c3eSMichael Hamann *
45204369c3eSMichael Hamann * @param string $ciphertext The encrypted data
45304369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
45404369c3eSMichael Hamann * @return string The decrypted data
45504369c3eSMichael Hamann */
456d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
457d868eb89SAndreas Gohr{
4587b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
45924870174SAndreas Gohr    $cipher = new AES();
46004369c3eSMichael Hamann    $cipher->setPassword($secret);
4617b650cefSMichael Hamann    $cipher->setIV($iv);
46204369c3eSMichael Hamann
4637b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
46404369c3eSMichael Hamann}
46504369c3eSMichael Hamann
46604369c3eSMichael Hamann/**
467883179a4SAndreas Gohr * Log out the current user
468883179a4SAndreas Gohr *
469f3f0262cSandi * This clears all authentication data and thus log the user
470883179a4SAndreas Gohr * off. It also clears session data.
47115fae107Sandi *
47215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
47342ea7f44SGerrit Uitslag *
474883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
475f3f0262cSandi */
476d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
477d868eb89SAndreas Gohr{
478f3f0262cSandi    global $conf;
479f3f0262cSandi    global $USERINFO;
480e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4815298a619SAndreas Gohr    global $auth;
482585bf44eSChristopher Smith    /* @var Input $INPUT */
483585bf44eSChristopher Smith    global $INPUT;
48437065e65Sandi
485d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
486e9621d07SAndreas Gohr    @session_start();
487e9621d07SAndreas Gohr
488e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
489e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
490e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
491e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
492e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
493e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
494883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
495e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
496585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
497132bdbfeSandi    $USERINFO = null; //FIXME
498f5c6743cSAndreas Gohr
49973ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
500bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
501bf8392ebSAndreas Gohr        'expires' => time() - 600000,
502bf8392ebSAndreas Gohr        'path' => $cookieDir,
503bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
504bf8392ebSAndreas Gohr        'httponly' => true,
505486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
506bf8392ebSAndreas Gohr    ]);
5075298a619SAndreas Gohr
5086547cfc7SGerrit Uitslag    if ($auth instanceof AuthPlugin) {
5096547cfc7SGerrit Uitslag        $auth->logOff();
5106547cfc7SGerrit Uitslag    }
511f3f0262cSandi}
512f3f0262cSandi
513f3f0262cSandi/**
514f8cc712eSAndreas Gohr * Check if a user is a manager
515f8cc712eSAndreas Gohr *
516f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
517f8cc712eSAndreas Gohr * user.
518f8cc712eSAndreas Gohr *
519f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
520f8cc712eSAndreas Gohr *
521ab5d26daSAndreas Gohr * @param string $user Username
522ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
523ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
52410396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
525ab5d26daSAndreas Gohr * @return bool
52696348f27SAndreas Gohr * @see    auth_isadmin
52796348f27SAndreas Gohr *
52896348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
529f8cc712eSAndreas Gohr */
530d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
531d868eb89SAndreas Gohr{
532f8cc712eSAndreas Gohr    global $conf;
533f8cc712eSAndreas Gohr    global $USERINFO;
534e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
535d752aedeSAndreas Gohr    global $auth;
536585bf44eSChristopher Smith    /* @var Input $INPUT */
537585bf44eSChristopher Smith    global $INPUT;
538585bf44eSChristopher Smith
539f8cc712eSAndreas Gohr
5406547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
541c66972f2SAdrian Lang    if (is_null($user)) {
542585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
543c66972f2SAdrian Lang            return false;
544c66972f2SAdrian Lang        } else {
545585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
546c66972f2SAdrian Lang        }
547c66972f2SAdrian Lang    }
548d6dc956fSAndreas Gohr    if (is_null($groups)) {
5491525c228SAnna Dabrowska        // checking the logged in user, or another one?
5501525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
5511525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
55266b108d6SAnna Dabrowska        } else {
5536cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
5546cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
55566b108d6SAnna Dabrowska        }
556e259aa79SAndreas Gohr    }
557e259aa79SAndreas Gohr
55896348f27SAndreas Gohr    // prefer cached result
55996348f27SAndreas Gohr    static $cache = [];
56010396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
56196348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
562d6dc956fSAndreas Gohr        // check superuser match
56396348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
56400ce12daSChris Smith
56596348f27SAndreas Gohr        // check managers
56696348f27SAndreas Gohr        if (!$ok && !$adminonly) {
56796348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
56896348f27SAndreas Gohr        }
56996348f27SAndreas Gohr
57096348f27SAndreas Gohr        $cache[$cachekey] = $ok;
57196348f27SAndreas Gohr    }
57296348f27SAndreas Gohr
57396348f27SAndreas Gohr    return $cache[$cachekey];
574f8cc712eSAndreas Gohr}
575f8cc712eSAndreas Gohr
576f8cc712eSAndreas Gohr/**
577f8cc712eSAndreas Gohr * Check if a user is admin
578f8cc712eSAndreas Gohr *
579f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
580f8cc712eSAndreas Gohr *
581f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
582f8cc712eSAndreas Gohr *
58396348f27SAndreas Gohr * @param string $user Username
58496348f27SAndreas Gohr * @param array $groups List of groups the user is in
58510396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
58696348f27SAndreas Gohr * @return bool
587f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
588ab5d26daSAndreas Gohr * @see auth_ismanager()
58942ea7f44SGerrit Uitslag *
590f8cc712eSAndreas Gohr */
591d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
592d868eb89SAndreas Gohr{
59396348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
594f8cc712eSAndreas Gohr}
595f8cc712eSAndreas Gohr
596d6dc956fSAndreas Gohr/**
597d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
598d6dc956fSAndreas Gohr * users and groups to determine membership status
599d6dc956fSAndreas Gohr *
600d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
601d6dc956fSAndreas Gohr *
60242ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
60342ea7f44SGerrit Uitslag * @param string $user       user to match against
60442ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
6055446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
606d6dc956fSAndreas Gohr */
607d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
608d868eb89SAndreas Gohr{
609e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
610d6dc956fSAndreas Gohr    global $auth;
6116547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
612d6dc956fSAndreas Gohr
613d6dc956fSAndreas Gohr    // clean user and groups
6144f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
61524870174SAndreas Gohr        $user   = PhpString::strtolower($user);
61624870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
617d6dc956fSAndreas Gohr    }
618d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
61924870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
620d6dc956fSAndreas Gohr
621d6dc956fSAndreas Gohr    // extract the memberlist
622d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
623d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
624d6dc956fSAndreas Gohr    $members = array_unique($members);
625d6dc956fSAndreas Gohr    $members = array_filter($members);
626d6dc956fSAndreas Gohr
627d6dc956fSAndreas Gohr    // compare cleaned values
628d6dc956fSAndreas Gohr    foreach ($members as $member) {
629e5204a12SJurgen Hart        if ($member == '@ALL') return true;
63024870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
631d6dc956fSAndreas Gohr        if ($member[0] == '@') {
632d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
633d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
634d6dc956fSAndreas Gohr        } else {
635d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
636d6dc956fSAndreas Gohr            if ($member == $user) return true;
637d6dc956fSAndreas Gohr        }
638d6dc956fSAndreas Gohr    }
639d6dc956fSAndreas Gohr
640d6dc956fSAndreas Gohr    // still here? not a member!
641d6dc956fSAndreas Gohr    return false;
642d6dc956fSAndreas Gohr}
643d6dc956fSAndreas Gohr
644f8cc712eSAndreas Gohr/**
64515fae107Sandi * Convinience function for auth_aclcheck()
64615fae107Sandi *
64715fae107Sandi * This checks the permissions for the current user
64815fae107Sandi *
64915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
65015fae107Sandi *
6511698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
65215fae107Sandi * @return int          permission level
653f3f0262cSandi */
654d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
655d868eb89SAndreas Gohr{
656f3f0262cSandi    global $conf;
657f3f0262cSandi    global $USERINFO;
658585bf44eSChristopher Smith    /* @var Input $INPUT */
659585bf44eSChristopher Smith    global $INPUT;
660f3f0262cSandi    # if no ACL is used always return upload rights
661f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
66224870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
663f3f0262cSandi}
664f3f0262cSandi
665f3f0262cSandi/**
666c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
66715fae107Sandi *
66815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
66942ea7f44SGerrit Uitslag *
670c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6711698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
67215fae107Sandi * @param  string       $user   Username
6733272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
67415fae107Sandi * @return int             permission level
675f3f0262cSandi */
676d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
677d868eb89SAndreas Gohr{
67824870174SAndreas Gohr    $data = [
679bf8f8509SAndreas Gohr        'id'     => $id ?? '',
680c17acc9fSAndreas Gohr        'user'   => $user,
681c17acc9fSAndreas Gohr        'groups' => $groups
68224870174SAndreas Gohr    ];
683c17acc9fSAndreas Gohr
684cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
685c17acc9fSAndreas Gohr}
686c17acc9fSAndreas Gohr
687c17acc9fSAndreas Gohr/**
688c17acc9fSAndreas Gohr * default ACL check method
689c17acc9fSAndreas Gohr *
690c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
691c17acc9fSAndreas Gohr *
692c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
69342ea7f44SGerrit Uitslag *
694c17acc9fSAndreas Gohr * @param  array $data event data
695c17acc9fSAndreas Gohr * @return int   permission level
696c17acc9fSAndreas Gohr */
697d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
698d868eb89SAndreas Gohr{
699c17acc9fSAndreas Gohr    $id     =& $data['id'];
700c17acc9fSAndreas Gohr    $user   =& $data['user'];
701c17acc9fSAndreas Gohr    $groups =& $data['groups'];
702c17acc9fSAndreas Gohr
703f3f0262cSandi    global $conf;
704f3f0262cSandi    global $AUTH_ACL;
705e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
706d752aedeSAndreas Gohr    global $auth;
707f3f0262cSandi
70885d03f68SAndreas Gohr    // if no ACL is used always return upload rights
709f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
7106547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return AUTH_NONE;
711bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
712f3f0262cSandi
713074cf26bSandi    //make sure groups is an array
71424870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
715074cf26bSandi
71685d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
717ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
718ab5d26daSAndreas Gohr        return AUTH_ADMIN;
719ab5d26daSAndreas Gohr    }
72085d03f68SAndreas Gohr
721eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
72224870174SAndreas Gohr        $user   = PhpString::strtolower($user);
72324870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
724eb3ce0d5SKazutaka Miyasaka    }
72537ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
72624870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
72785d03f68SAndreas Gohr
7286c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
72937ff2261SSascha Klopp    foreach ($groups as &$group) {
73037ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
73110a76f6fSfrank    }
73210a76f6fSfrank
733f3f0262cSandi    $ns   = getNS($id);
734f3f0262cSandi    $perm = -1;
735f3f0262cSandi
736f3f0262cSandi    //add ALL group
737f3f0262cSandi    $groups[] = '@ALL';
73837ff2261SSascha Klopp
739f3f0262cSandi    //add User
74034aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
741f3f0262cSandi
742f3f0262cSandi    //check exact match first
74321c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
744f3f0262cSandi    if (count($matches)) {
745f3f0262cSandi        foreach ($matches as $match) {
746f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
74721c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
748eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
74924870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
750eb3ce0d5SKazutaka Miyasaka            }
75148d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
75248d7b7a6SDominik Eckelmann                continue;
75348d7b7a6SDominik Eckelmann            }
7548ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
755f3f0262cSandi            if ($acl[2] > $perm) {
756f3f0262cSandi                $perm = $acl[2];
757f3f0262cSandi            }
758f3f0262cSandi        }
759f3f0262cSandi        if ($perm > -1) {
760f3f0262cSandi            //we had a match - return it
761def492a2SGuillaume Turri            return (int) $perm;
762f3f0262cSandi        }
763f3f0262cSandi    }
764f3f0262cSandi
765f3f0262cSandi    //still here? do the namespace checks
766f3f0262cSandi    if ($ns) {
7673e304b55SMichael Hamann        $path = $ns . ':*';
768f3f0262cSandi    } else {
7693e304b55SMichael Hamann        $path = '*'; //root document
770f3f0262cSandi    }
771f3f0262cSandi
772f3f0262cSandi    do {
77321c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
774f3f0262cSandi        if (count($matches)) {
775f3f0262cSandi            foreach ($matches as $match) {
776f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
77721c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
778eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
77924870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
780eb3ce0d5SKazutaka Miyasaka                }
78148d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
78248d7b7a6SDominik Eckelmann                    continue;
78348d7b7a6SDominik Eckelmann                }
7848ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
785f3f0262cSandi                if ($acl[2] > $perm) {
786f3f0262cSandi                    $perm = $acl[2];
787f3f0262cSandi                }
788f3f0262cSandi            }
789f3f0262cSandi            //we had a match - return it
79048d7b7a6SDominik Eckelmann            if ($perm != -1) {
791def492a2SGuillaume Turri                return (int) $perm;
792f3f0262cSandi            }
79348d7b7a6SDominik Eckelmann        }
794f3f0262cSandi        //get next higher namespace
795f3f0262cSandi        $ns = getNS($ns);
796f3f0262cSandi
7973e304b55SMichael Hamann        if ($path != '*') {
7983e304b55SMichael Hamann            $path = $ns . ':*';
7993e304b55SMichael Hamann            if ($path == ':*') $path = '*';
800f3f0262cSandi        } else {
801f3f0262cSandi            //we did this already
802f3f0262cSandi            //looks like there is something wrong with the ACL
803f3f0262cSandi            //break here
804d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
805d5ce66f6SAndreas Gohr            return AUTH_NONE;
806f3f0262cSandi        }
807f3f0262cSandi    } while (1); //this should never loop endless
808ab5d26daSAndreas Gohr    return AUTH_NONE;
809f3f0262cSandi}
810f3f0262cSandi
811f3f0262cSandi/**
8126c2bb100SAndreas Gohr * Encode ASCII special chars
8136c2bb100SAndreas Gohr *
8146c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
8156c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
8166c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
8176c2bb100SAndreas Gohr * urlencoding!).
8186c2bb100SAndreas Gohr *
8196c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
8206c2bb100SAndreas Gohr *
8216c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
8226c2bb100SAndreas Gohr * @see rawurldecode()
82342ea7f44SGerrit Uitslag *
82442ea7f44SGerrit Uitslag * @param string $name
82542ea7f44SGerrit Uitslag * @param bool $skip_group
82642ea7f44SGerrit Uitslag * @return string
8276c2bb100SAndreas Gohr */
828d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
829d868eb89SAndreas Gohr{
830a424cd8eSchris    global $cache_authname;
831a424cd8eSchris    $cache =& $cache_authname;
83231784267SAndreas Gohr    $name  = (string) $name;
833a424cd8eSchris
83480601d26SAndreas Gohr    // never encode wildcard FS#1955
83580601d26SAndreas Gohr    if ($name == '%USER%') return $name;
836b78bf706Sromain    if ($name == '%GROUP%') return $name;
83780601d26SAndreas Gohr
838a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
8392401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
84030f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
84130f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
842dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
843dccd6b2bSAndreas Gohr                substr($name, 1)
844ab5d26daSAndreas Gohr            );
845e838fc2eSAndreas Gohr        } else {
84630f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
84730f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
848dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
849dccd6b2bSAndreas Gohr                $name
850ab5d26daSAndreas Gohr            );
851e838fc2eSAndreas Gohr        }
8526c2bb100SAndreas Gohr    }
8536c2bb100SAndreas Gohr
854a424cd8eSchris    return $cache[$name][$skip_group];
855a424cd8eSchris}
856a424cd8eSchris
85704d68ae4SGerrit Uitslag/**
85804d68ae4SGerrit Uitslag * callback encodes the matches
85904d68ae4SGerrit Uitslag *
86004d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
86104d68ae4SGerrit Uitslag * @return string
86204d68ae4SGerrit Uitslag */
863d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
864d868eb89SAndreas Gohr{
86530f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
86630f6faf0SChristopher Smith}
86730f6faf0SChristopher Smith
8686c2bb100SAndreas Gohr/**
869f3f0262cSandi * Create a pronouncable password
870f3f0262cSandi *
8718a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
8728a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
8738a285f7fSAndreas Gohr *
8744dc42f7fSGerrit Uitslag * @param string $foruser username for which the password is generated
8754dc42f7fSGerrit Uitslag * @return string  pronouncable password
8764dc42f7fSGerrit Uitslag * @throws Exception
8774dc42f7fSGerrit Uitslag *
87815fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
8798a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
88015fae107Sandi *
8814dc42f7fSGerrit Uitslag * @author   Andreas Gohr <andi@splitbrain.org>
882f3f0262cSandi */
883d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
884d868eb89SAndreas Gohr{
88524870174SAndreas Gohr    $data = [
886d628dcf3SAndreas Gohr        'password' => '',
887d628dcf3SAndreas Gohr        'foruser'  => $foruser
88824870174SAndreas Gohr    ];
8898a285f7fSAndreas Gohr
890e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8918a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
892f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
893f3f0262cSandi        $v = 'aeiou'; //vowels
894f3f0262cSandi        $a = $c . $v; //both
895987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
896f3f0262cSandi
897987c8d26SAndreas Gohr        //use thre syllables...
898987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
899483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
900483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
901483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
902f3f0262cSandi        }
903987c8d26SAndreas Gohr        //... and add a nice number and special
90443f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
9058a285f7fSAndreas Gohr    }
9068a285f7fSAndreas Gohr    $evt->advise_after();
907f3f0262cSandi
9088a285f7fSAndreas Gohr    return $data['password'];
909f3f0262cSandi}
910f3f0262cSandi
911f3f0262cSandi/**
912f3f0262cSandi * Sends a password to the given user
913f3f0262cSandi *
91415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
91542ea7f44SGerrit Uitslag *
916ab5d26daSAndreas Gohr * @param string $user Login name of the user
917ab5d26daSAndreas Gohr * @param string $password The new password in clear text
91815fae107Sandi * @return bool  true on success
919f3f0262cSandi */
920d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
921d868eb89SAndreas Gohr{
922f3f0262cSandi    global $lang;
923e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
924cd52f92dSchris    global $auth;
9256547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
926cd52f92dSchris
927d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
9284dc42f7fSGerrit Uitslag    $userinfo = $auth->getUserData($user, false);
929f3f0262cSandi
93087ddda95Sandi    if (!$userinfo['mail']) return false;
931f3f0262cSandi
932f3f0262cSandi    $text = rawLocale('password');
93324870174SAndreas Gohr    $trep = [
934d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
935d7169d19SAndreas Gohr        'LOGIN'    => $user,
936d7169d19SAndreas Gohr        'PASSWORD' => $password
93724870174SAndreas Gohr    ];
938f3f0262cSandi
939d7169d19SAndreas Gohr    $mail = new Mailer();
940102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
941d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
942d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
943d7169d19SAndreas Gohr    return $mail->send();
944f3f0262cSandi}
945f3f0262cSandi
946f3f0262cSandi/**
94715fae107Sandi * Register a new user
948f3f0262cSandi *
94915fae107Sandi * This registers a new user - Data is read directly from $_POST
95015fae107Sandi *
95115fae107Sandi * @return bool  true on success, false on any error
9524dc42f7fSGerrit Uitslag * @throws Exception
9534dc42f7fSGerrit Uitslag *
9544dc42f7fSGerrit Uitslag * @author  Andreas Gohr <andi@splitbrain.org>
955f3f0262cSandi */
956d868eb89SAndreas Gohrfunction register()
957d868eb89SAndreas Gohr{
958f3f0262cSandi    global $lang;
959eb5d07e4Sjan    global $conf;
9604dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
961cd52f92dSchris    global $auth;
96264273335SAndreas Gohr    global $INPUT;
963f3f0262cSandi
96464273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9653a48618aSAnika Henke    if (!actionOK('register')) return false;
966640145a5Sandi
96764273335SAndreas Gohr    // gather input
96864273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
96964273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
97064273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
97164273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
97264273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
973d752aedeSAndreas Gohr
97464273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
975f3f0262cSandi        msg($lang['regmissing'], -1);
976f3f0262cSandi        return false;
977f3f0262cSandi    }
978f3f0262cSandi
979cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
9808a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
98164273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
982bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
983cab2716aSmatthias.grimm        return false;
98464273335SAndreas Gohr    } elseif ($pass != $passchk) {
985bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
986cab2716aSmatthias.grimm        return false;
987cab2716aSmatthias.grimm    }
988cab2716aSmatthias.grimm
989f3f0262cSandi    //check mail
99064273335SAndreas Gohr    if (!mail_isvalid($email)) {
991f3f0262cSandi        msg($lang['regbadmail'], -1);
992f3f0262cSandi        return false;
993f3f0262cSandi    }
994f3f0262cSandi
995f3f0262cSandi    //okay try to create the user
99624870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
997db9faf02SPatrick Brown        msg($lang['regfail'], -1);
998f3f0262cSandi        return false;
999f3f0262cSandi    }
1000f3f0262cSandi
1001790b7720SAndreas Gohr    // send notification about the new user
100275d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
100375d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
100402a498e7Schris
1005790b7720SAndreas Gohr    // are we done?
1006cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
1007cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
1008cab2716aSmatthias.grimm        return true;
1009cab2716aSmatthias.grimm    }
1010cab2716aSmatthias.grimm
1011790b7720SAndreas Gohr    // autogenerated password? then send password to user
101264273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
1013f3f0262cSandi        msg($lang['regsuccess'], 1);
1014f3f0262cSandi        return true;
1015f3f0262cSandi    } else {
1016f3f0262cSandi        msg($lang['regmailfail'], -1);
1017f3f0262cSandi        return false;
1018f3f0262cSandi    }
1019f3f0262cSandi}
1020f3f0262cSandi
102110a76f6fSfrank/**
10228b06d178Schris * Update user profile
10238b06d178Schris *
10244dc42f7fSGerrit Uitslag * @throws Exception
10254dc42f7fSGerrit Uitslag *
10268b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
10278b06d178Schris */
1028d868eb89SAndreas Gohrfunction updateprofile()
1029d868eb89SAndreas Gohr{
10308b06d178Schris    global $conf;
10318b06d178Schris    global $lang;
1032e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1033cd52f92dSchris    global $auth;
1034bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1035bcc94b2cSAndreas Gohr    global $INPUT;
10368b06d178Schris
1037bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
10381b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
10398b06d178Schris
10403a48618aSAnika Henke    if (!actionOK('profile')) {
10418b06d178Schris        msg($lang['profna'], -1);
10428b06d178Schris        return false;
10438b06d178Schris    }
10448b06d178Schris
104524870174SAndreas Gohr    $changes         = [];
1046bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
1047bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
1048bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
1049bcc94b2cSAndreas Gohr
1050bcc94b2cSAndreas Gohr    // check misspelled passwords
1051bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
1052bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
10538b06d178Schris        return false;
10548b06d178Schris    }
10558b06d178Schris
10568b06d178Schris    // clean fullname and email
1057bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1058bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
10598b06d178Schris
1060bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
10617d34963bSAndreas Gohr    if (
10627d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1063bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1064ab5d26daSAndreas Gohr    ) {
10658b06d178Schris        msg($lang['profnoempty'], -1);
10668b06d178Schris        return false;
10678b06d178Schris    }
1068bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10698b06d178Schris        msg($lang['regbadmail'], -1);
10708b06d178Schris        return false;
10718b06d178Schris    }
10728b06d178Schris
1073bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
10744c21b7eeSAndreas Gohr
1075bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1076bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1077bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1078bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1079bcc94b2cSAndreas Gohr
1080bcc94b2cSAndreas Gohr    // anything to do?
108124870174SAndreas Gohr    if ($changes === []) {
10828b06d178Schris        msg($lang['profnochange'], -1);
10838b06d178Schris        return false;
10848b06d178Schris    }
10858b06d178Schris
10868b06d178Schris    if ($conf['profileconfirm']) {
1087585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
108871422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
10898b06d178Schris            return false;
10908b06d178Schris        }
10918b06d178Schris    }
10928b06d178Schris
109324870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1094db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1095db9faf02SPatrick Brown        return false;
1096db9faf02SPatrick Brown    }
1097db9faf02SPatrick Brown
109832ed2b36SAndreas Gohr    if ($changes['pass']) {
1099c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1100a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
110104369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1102585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1103c276e9e8SMarcel Pennewiss    } else {
1104c276e9e8SMarcel Pennewiss        // make sure the session is writable
1105c276e9e8SMarcel Pennewiss        @session_start();
1106c276e9e8SMarcel Pennewiss        // invalidate session cache
1107c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1108c276e9e8SMarcel Pennewiss        session_write_close();
110932ed2b36SAndreas Gohr    }
1110c276e9e8SMarcel Pennewiss
111125b2a98cSMichael Klier    return true;
1112a0b5b007SChris Smith}
1113ab5d26daSAndreas Gohr
111404d68ae4SGerrit Uitslag/**
111504d68ae4SGerrit Uitslag * Delete the current logged-in user
111604d68ae4SGerrit Uitslag *
111704d68ae4SGerrit Uitslag * @return bool true on success, false on any error
111804d68ae4SGerrit Uitslag */
1119d868eb89SAndreas Gohrfunction auth_deleteprofile()
1120d868eb89SAndreas Gohr{
11212a7abf2dSChristopher Smith    global $conf;
11222a7abf2dSChristopher Smith    global $lang;
11234dc42f7fSGerrit Uitslag    /* @var AuthPlugin $auth */
11242a7abf2dSChristopher Smith    global $auth;
11252a7abf2dSChristopher Smith    /* @var Input $INPUT */
11262a7abf2dSChristopher Smith    global $INPUT;
11272a7abf2dSChristopher Smith
11282a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
11292a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
11302a7abf2dSChristopher Smith
11312a7abf2dSChristopher Smith    // action prevented or auth module disallows
11322a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
11332a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
11342a7abf2dSChristopher Smith        return false;
11352a7abf2dSChristopher Smith    }
11362a7abf2dSChristopher Smith
11372a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
11382a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
11392a7abf2dSChristopher Smith        return false;
11402a7abf2dSChristopher Smith    }
11412a7abf2dSChristopher Smith
11422a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1143585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
11442a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
11452a7abf2dSChristopher Smith            return false;
11462a7abf2dSChristopher Smith        }
11472a7abf2dSChristopher Smith    }
11482a7abf2dSChristopher Smith
114924870174SAndreas Gohr    $deleted = [];
1150585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
115124870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
11522a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
11532a7abf2dSChristopher Smith        auth_logoff();
11542a7abf2dSChristopher Smith        return true;
11552a7abf2dSChristopher Smith    }
11562a7abf2dSChristopher Smith
11572a7abf2dSChristopher Smith    return false;
11582a7abf2dSChristopher Smith}
11592a7abf2dSChristopher Smith
11608b06d178Schris/**
11618b06d178Schris * Send a  new password
11628b06d178Schris *
11631d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11641d5856cfSAndreas Gohr *
11651d5856cfSAndreas Gohr *   - handling the first request of password reset
11661d5856cfSAndreas Gohr *   - validating the password reset auth token
11671d5856cfSAndreas Gohr *
11684dc42f7fSGerrit Uitslag * @return bool true on success, false on any error
11694dc42f7fSGerrit Uitslag * @throws Exception
11704dc42f7fSGerrit Uitslag *
11714dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
11728b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
11738b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
11748b06d178Schris */
1175d868eb89SAndreas Gohrfunction act_resendpwd()
1176d868eb89SAndreas Gohr{
11778b06d178Schris    global $lang;
11788b06d178Schris    global $conf;
1179e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1180cd52f92dSchris    global $auth;
1181bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1182bcc94b2cSAndreas Gohr    global $INPUT;
11838b06d178Schris
11843a48618aSAnika Henke    if (!actionOK('resendpwd')) {
11858b06d178Schris        msg($lang['resendna'], -1);
11868b06d178Schris        return false;
11878b06d178Schris    }
11888b06d178Schris
1189bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
11908b06d178Schris
11911d5856cfSAndreas Gohr    if ($token) {
1192cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
11931d5856cfSAndreas Gohr
11942401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
119579e79377SAndreas Gohr        if (!file_exists($tfile)) {
11961d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1197bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11981d5856cfSAndreas Gohr            return false;
11991d5856cfSAndreas Gohr        }
12008a9735e3SAndreas Gohr        // token is only valid for 3 days
12018a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
12028a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1203bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
12041d5856cfSAndreas Gohr            @unlink($tfile);
12058a9735e3SAndreas Gohr            return false;
12068a9735e3SAndreas Gohr        }
12078a9735e3SAndreas Gohr
12088b06d178Schris        $user     = io_readfile($tfile);
12094dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12108b06d178Schris        if (!$userinfo['mail']) {
12118b06d178Schris            msg($lang['resendpwdnouser'], -1);
12128b06d178Schris            return false;
12138b06d178Schris        }
12148b06d178Schris
1215cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1216bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1217bcc94b2cSAndreas Gohr
1218cc204bbdSAndreas Gohr            // password given correctly?
1219bcc94b2cSAndreas Gohr            if (!$pass) return false;
1220bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1221451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1222cc204bbdSAndreas Gohr                return false;
1223cc204bbdSAndreas Gohr            }
1224cc204bbdSAndreas Gohr
1225bcc94b2cSAndreas Gohr            // change it
122624870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1227db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1228cc204bbdSAndreas Gohr                return false;
1229cc204bbdSAndreas Gohr            }
1230cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
12318a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
123224870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1233db9faf02SPatrick Brown                msg($lang['proffail'], -1);
12348b06d178Schris                return false;
12358b06d178Schris            }
12368b06d178Schris
12378b06d178Schris            if (auth_sendPassword($user, $pass)) {
12388b06d178Schris                msg($lang['resendpwdsuccess'], 1);
12398b06d178Schris            } else {
12408b06d178Schris                msg($lang['regmailfail'], -1);
12418b06d178Schris            }
1242cc204bbdSAndreas Gohr        }
1243cc204bbdSAndreas Gohr
1244cc204bbdSAndreas Gohr        @unlink($tfile);
12458b06d178Schris        return true;
12461d5856cfSAndreas Gohr    } else {
12471d5856cfSAndreas Gohr        // we're in request phase
12481d5856cfSAndreas Gohr
1249bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
12501d5856cfSAndreas Gohr
1251bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
12521d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
12531d5856cfSAndreas Gohr            return false;
12541d5856cfSAndreas Gohr        } else {
1255bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
12561d5856cfSAndreas Gohr        }
12571d5856cfSAndreas Gohr
12584dc42f7fSGerrit Uitslag        $userinfo = $auth->getUserData($user, false);
12591d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
12601d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
12611d5856cfSAndreas Gohr            return false;
12621d5856cfSAndreas Gohr        }
12631d5856cfSAndreas Gohr
12641d5856cfSAndreas Gohr        // generate auth token
1265483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12662401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
126724870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
12681d5856cfSAndreas Gohr
12691d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12701d5856cfSAndreas Gohr
12711d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
127224870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
12731d5856cfSAndreas Gohr
1274d7169d19SAndreas Gohr        $mail = new Mailer();
1275d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1276d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1277d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1278d7169d19SAndreas Gohr        if ($mail->send()) {
12791d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
12801d5856cfSAndreas Gohr        } else {
12811d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
12821d5856cfSAndreas Gohr        }
12831d5856cfSAndreas Gohr        return true;
12841d5856cfSAndreas Gohr    }
1285ab5d26daSAndreas Gohr    // never reached
12868b06d178Schris}
12878b06d178Schris
12888b06d178Schris/**
1289b0855b11Sandi * Encrypts a password using the given method and salt
1290b0855b11Sandi *
1291b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1292b0855b11Sandi * is chosen.
1293b0855b11Sandi *
1294b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
129542ea7f44SGerrit Uitslag *
1296ab5d26daSAndreas Gohr * @param string $clear The clear text password
1297ab5d26daSAndreas Gohr * @param string $method The hashing method
1298ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1299b0855b11Sandi * @return  string  The crypted password
1300b0855b11Sandi */
1301d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1302d868eb89SAndreas Gohr{
1303b0855b11Sandi    global $conf;
1304b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
130510a76f6fSfrank
13063a0a2d05SAndreas Gohr    $pass = new PassHash();
13073a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1308b0855b11Sandi
13093a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1310b0855b11Sandi        msg("Unsupported crypt method $method", -1);
13113a0a2d05SAndreas Gohr        return false;
1312b0855b11Sandi    }
13133a0a2d05SAndreas Gohr
13143a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1315b0855b11Sandi}
1316b0855b11Sandi
1317b0855b11Sandi/**
1318b0855b11Sandi * Verifies a cleartext password against a crypted hash
1319b0855b11Sandi *
1320ab5d26daSAndreas Gohr * @param string $clear The clear text password
1321ab5d26daSAndreas Gohr * @param string $crypt The hash to compare with
1322ab5d26daSAndreas Gohr * @return bool true if both match
13234dc42f7fSGerrit Uitslag * @throws Exception
13244dc42f7fSGerrit Uitslag *
13254dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
1326b0855b11Sandi */
1327d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1328d868eb89SAndreas Gohr{
13293a0a2d05SAndreas Gohr    $pass = new PassHash();
13303a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1331b0855b11Sandi}
1332340756e4Sandi
1333a0b5b007SChris Smith/**
1334a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1335a0b5b007SChris Smith *
1336a0b5b007SChris Smith * @param string  $user       username
1337a0b5b007SChris Smith * @param string  $pass       encrypted password
1338a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1339ab5d26daSAndreas Gohr * @return bool
1340a0b5b007SChris Smith */
1341d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1342d868eb89SAndreas Gohr{
1343a0b5b007SChris Smith    global $conf;
1344e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1345a0b5b007SChris Smith    global $auth;
134679d00841SOliver Geisen    global $USERINFO;
1347a0b5b007SChris Smith
13486547cfc7SGerrit Uitslag    if (!$auth instanceof AuthPlugin) return false;
1349a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1350a0b5b007SChris Smith
1351a0b5b007SChris Smith    // set cookie
1352645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
135373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1354c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1355bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1356bf8392ebSAndreas Gohr        'expires' => $time,
1357bf8392ebSAndreas Gohr        'path' => $cookieDir,
1358bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1359bf8392ebSAndreas Gohr        'httponly' => true,
1360486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1361bf8392ebSAndreas Gohr    ]);
136255a71a16SGerrit Uitslag
1363a0b5b007SChris Smith    // set session
1364a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1365234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1366a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1367a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1368a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1369ab5d26daSAndreas Gohr
1370ab5d26daSAndreas Gohr    return true;
1371a0b5b007SChris Smith}
1372a0b5b007SChris Smith
1373645c0a36SAndreas Gohr/**
1374645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1375645c0a36SAndreas Gohr *
1376645c0a36SAndreas Gohr * @returns array
1377645c0a36SAndreas Gohr */
1378d868eb89SAndreas Gohrfunction auth_getCookie()
1379d868eb89SAndreas Gohr{
1380c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
138124870174SAndreas Gohr        return [null, null, null];
1382c66972f2SAdrian Lang    }
138324870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1384645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1385645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1386645c0a36SAndreas Gohr    $user   = base64_decode($user);
138724870174SAndreas Gohr    return [$user, $sticky, $pass];
1388645c0a36SAndreas Gohr}
1389645c0a36SAndreas Gohr
1390e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1391