xref: /dokuwiki/inc/auth.php (revision d4f83172d9533c4d84f450fe22ef630816b21d75)
1ed7b5f09Sandi<?php
2*d4f83172SAndreas 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 */
12*d4f83172SAndreas 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
566416b708SMichael Hamann    if (!isset($auth) || !$auth) {
573094e817SAndreas Gohr        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
9481e99965SPhy    $ok = null;
958eca974cSAndreas Gohr    if (!is_null($auth) && $auth->canDo('external')) {
9681e99965SPhy        $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
9781e99965SPhy    }
9881e99965SPhy
9981e99965SPhy    if ($ok === null) {
10081e99965SPhy        // external trust mechanism not in place, or returns no result,
10181e99965SPhy        // then attempt auth_login
10224870174SAndreas Gohr        $evdata = [
103bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
104bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
105bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
106bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
10724870174SAndreas Gohr        ];
108cbb44eabSAndreas Gohr        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
109f5cb575dSAndreas Gohr    }
110f5cb575dSAndreas Gohr
11116905344SAndreas Gohr    //load ACL into a global array XXX
11275c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
113ab5d26daSAndreas Gohr
114ab5d26daSAndreas Gohr    return true;
11575c93b77SAndreas Gohr}
11675c93b77SAndreas Gohr
11775c93b77SAndreas Gohr/**
11875c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
11975c93b77SAndreas Gohr *
12075c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12142ea7f44SGerrit Uitslag *
122ab5d26daSAndreas Gohr * @return array
12375c93b77SAndreas Gohr */
124d868eb89SAndreas Gohrfunction auth_loadACL()
125d868eb89SAndreas Gohr{
12675c93b77SAndreas Gohr    global $config_cascade;
127b78bf706Sromain    global $USERINFO;
128585bf44eSChristopher Smith    /* @var Input $INPUT */
129585bf44eSChristopher Smith    global $INPUT;
13075c93b77SAndreas Gohr
13124870174SAndreas Gohr    if (!is_readable($config_cascade['acl']['default'])) return [];
13275c93b77SAndreas Gohr
13375c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13475c93b77SAndreas Gohr
13524870174SAndreas Gohr    $out = [];
1369ce556d2SAndreas Gohr    foreach ($acl as $line) {
1379ce556d2SAndreas Gohr        $line = trim($line);
1382401f18dSSyntaxseed        if (empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
13924870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/', $line, 2);
14032e82180SAndreas Gohr
141443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
142ad3d68d7SChristopher Smith        if (strstr($line, '%USER%')) {
143ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
144585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
145ad3d68d7SChristopher Smith
146585bf44eSChristopher Smith            $id   = str_replace('%USER%', cleanID($INPUT->server->str('REMOTE_USER')), $id);
147585bf44eSChristopher Smith            $rest = str_replace('%USER%', auth_nameencode($INPUT->server->str('REMOTE_USER')), $rest);
148ad3d68d7SChristopher Smith        }
149ad3d68d7SChristopher Smith
150ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1519ce556d2SAndreas Gohr        if (strstr($line, '%GROUP%')) {
152ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
15306f34f54SPhy            if (isset($USERINFO['grps'])) {
1549ce556d2SAndreas Gohr                foreach ((array) $USERINFO['grps'] as $grp) {
155b78bf706Sromain                    $nid   = str_replace('%GROUP%', cleanID($grp), $id);
15632e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%', '@' . auth_nameencode($grp), $rest);
15732e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
158b78bf706Sromain                }
15906f34f54SPhy            }
16032e82180SAndreas Gohr        } else {
16132e82180SAndreas Gohr            $out[] = "$id\t$rest";
162a8fe108bSGuy Brand        }
16311799630Sandi    }
1649ce556d2SAndreas Gohr
16532e82180SAndreas Gohr    return $out;
166f3f0262cSandi}
167f3f0262cSandi
168ab5d26daSAndreas Gohr/**
169ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
170ab5d26daSAndreas Gohr *
17142ea7f44SGerrit Uitslag * @param array $evdata
172ab5d26daSAndreas Gohr * @return bool
173ab5d26daSAndreas Gohr */
174d868eb89SAndreas Gohrfunction auth_login_wrapper($evdata)
175d868eb89SAndreas Gohr{
176ab5d26daSAndreas Gohr    return auth_login(
177ab5d26daSAndreas Gohr        $evdata['user'],
178b5ee21aaSAdrian Lang        $evdata['password'],
179b5ee21aaSAdrian Lang        $evdata['sticky'],
180ab5d26daSAndreas Gohr        $evdata['silent']
181ab5d26daSAndreas Gohr    );
182b5ee21aaSAdrian Lang}
183b5ee21aaSAdrian Lang
184f3f0262cSandi/**
185f3f0262cSandi * This tries to login the user based on the sent auth credentials
186f3f0262cSandi *
187f3f0262cSandi * The authentication works like this: if a username was given
18815fae107Sandi * a new login is assumed and user/password are checked. If they
18915fae107Sandi * are correct the password is encrypted with blowfish and stored
19015fae107Sandi * together with the username in a cookie - the same info is stored
19115fae107Sandi * in the session, too. Additonally a browserID is stored in the
19215fae107Sandi * session.
19315fae107Sandi *
19415fae107Sandi * If no username was given the cookie is checked: if the username,
19515fae107Sandi * crypted password and browserID match between session and cookie
19615fae107Sandi * no further testing is done and the user is accepted
19715fae107Sandi *
19815fae107Sandi * If a cookie was found but no session info was availabe the
199136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
20015fae107Sandi * together with username rechecked by calling this function again.
201f3f0262cSandi *
202f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
203f3f0262cSandi * are set.
20415fae107Sandi *
20515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20615fae107Sandi *
20715fae107Sandi * @param   string  $user    Username
20815fae107Sandi * @param   string  $pass    Cleartext Password
20915fae107Sandi * @param   bool    $sticky  Cookie should not expire
210f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
21115fae107Sandi * @return  bool             true on successful auth
212f3f0262cSandi */
213d868eb89SAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false)
214d868eb89SAndreas Gohr{
215f3f0262cSandi    global $USERINFO;
216f3f0262cSandi    global $conf;
217f3f0262cSandi    global $lang;
218e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
219cd52f92dSchris    global $auth;
220585bf44eSChristopher Smith    /* @var Input $INPUT */
221585bf44eSChristopher Smith    global $INPUT;
222ab5d26daSAndreas Gohr
223beca106aSAdrian Lang    if (!$auth) return false;
224beca106aSAdrian Lang
225bbbd6568SAndreas Gohr    if (!empty($user)) {
226132bdbfeSandi        //usual login
2275e9e1054SAndreas Gohr        if (!empty($pass) && $auth->checkPass($user, $pass)) {
228132bdbfeSandi            // make logininfo globally available
229585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
23030d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
23104369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
232132bdbfeSandi            return true;
233f3f0262cSandi        } else {
234f3f0262cSandi            //invalid credentials - log off
235f8b1e4e7SAndreas Gohr            if (!$silent) {
236f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
237f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
238f8b1e4e7SAndreas Gohr            }
239f3f0262cSandi            auth_logoff();
240132bdbfeSandi            return false;
241f3f0262cSandi        }
242f3f0262cSandi    } else {
243132bdbfeSandi        // read cookie information
24424870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
245132bdbfeSandi        if ($user && $pass) {
246132bdbfeSandi            // we got a cookie - see if we can trust it
247fa7c70ffSAdrian Lang
248fa7c70ffSAdrian Lang            // get session info
2490058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
250fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
2517d34963bSAndreas Gohr                if (
2527d34963bSAndreas Gohr                    isset($session) &&
2537172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2544c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
255132bdbfeSandi                    ($session['user'] == $user) &&
256234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
257ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
258ab5d26daSAndreas Gohr                ) {
259132bdbfeSandi                    // he has session, cookie and browser right - let him in
260585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
261132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
262132bdbfeSandi                    return true;
263132bdbfeSandi                }
2640058ae75SDamien Regad            }
265f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26630d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26704369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
268f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
269132bdbfeSandi        }
270132bdbfeSandi    }
271f3f0262cSandi    //just to be sure
272883179a4SAndreas Gohr    auth_logoff(true);
273132bdbfeSandi    return false;
274f3f0262cSandi}
275132bdbfeSandi
276132bdbfeSandi/**
277136ce040Sandi * Builds a pseudo UID from browser and IP data
278132bdbfeSandi *
279132bdbfeSandi * This is neither unique nor unfakable - still it adds some
280136ce040Sandi * security. Using the first part of the IP makes sure
28180b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
28215fae107Sandi *
28315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
28415fae107Sandi *
285b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
286132bdbfeSandi */
287d868eb89SAndreas Gohrfunction auth_browseruid()
288d868eb89SAndreas Gohr{
289585bf44eSChristopher Smith    /* @var Input $INPUT */
290585bf44eSChristopher Smith    global $INPUT;
291585bf44eSChristopher Smith
2922f9daf16SAndreas Gohr    $ip = clientIP(true);
293b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
294b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
295b7c67f83SAndreas Gohr
296b7c67f83SAndreas Gohr    $uid = implode("\n", [
297b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
298b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
299b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
300b7c67f83SAndreas Gohr    ]);
301b13c0e1aSAdaKaleh    return hash('sha256', $uid);
302132bdbfeSandi}
303132bdbfeSandi
304132bdbfeSandi/**
305132bdbfeSandi * Creates a random key to encrypt the password in cookies
30615fae107Sandi *
30715fae107Sandi * This function tries to read the password for encrypting
30898407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30915fae107Sandi * if no such file is found a random key is created and
31015fae107Sandi * and stored in this file.
31115fae107Sandi *
31215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31342ea7f44SGerrit Uitslag *
31432ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
31530d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
31615fae107Sandi * @return  string
317132bdbfeSandi */
318d868eb89SAndreas Gohrfunction auth_cookiesalt($addsession = false, $secure = false)
319d868eb89SAndreas Gohr{
320a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
321fe745becSMichael Große        return 'test';
322a1fe3c9cSMichael Große    }
323132bdbfeSandi    global $conf;
32498407a7aSandi    $file = $conf['metadir'] . '/_htcookiesalt';
32530d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
32630d544a4SMichael Hamann        $file = $conf['metadir'] . '/_htcookiesalt2';
32730d544a4SMichael Hamann    }
328132bdbfeSandi    $salt = io_readFile($file);
329132bdbfeSandi    if (empty($salt)) {
33030d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
331132bdbfeSandi        io_saveFile($file, $salt);
332132bdbfeSandi    }
33332ed2b36SAndreas Gohr    if ($addsession) {
33432ed2b36SAndreas Gohr        $salt .= session_id();
33532ed2b36SAndreas Gohr    }
336132bdbfeSandi    return $salt;
337f3f0262cSandi}
338f3f0262cSandi
339f3f0262cSandi/**
3407a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
341483b6238SMichael Hamann *
3427a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34342ea7f44SGerrit Uitslag *
3447a33d2f8SNiklas Keller * @param int $length number of bytes
3457a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
346483b6238SMichael Hamann */
347d868eb89SAndreas Gohrfunction auth_randombytes($length)
348d868eb89SAndreas Gohr{
3497a33d2f8SNiklas Keller    return random_bytes($length);
350483b6238SMichael Hamann}
351483b6238SMichael Hamann
352483b6238SMichael Hamann/**
3537a33d2f8SNiklas Keller * Cryptographically secure random number generator.
354483b6238SMichael Hamann *
3557a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
35642ea7f44SGerrit Uitslag *
357483b6238SMichael Hamann * @param int $min
358483b6238SMichael Hamann * @param int $max
359483b6238SMichael Hamann * @return int
360483b6238SMichael Hamann */
361d868eb89SAndreas Gohrfunction auth_random($min, $max)
362d868eb89SAndreas Gohr{
3637a33d2f8SNiklas Keller    return random_int($min, $max);
364483b6238SMichael Hamann}
365483b6238SMichael Hamann
366483b6238SMichael Hamann/**
36704369c3eSMichael Hamann * Encrypt data using the given secret using AES
36804369c3eSMichael Hamann *
36904369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
37004369c3eSMichael Hamann * using pbkdf2.
37104369c3eSMichael Hamann *
37204369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
37304369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
37404369c3eSMichael Hamann * @return string The ciphertext
37504369c3eSMichael Hamann */
376d868eb89SAndreas Gohrfunction auth_encrypt($data, $secret)
377d868eb89SAndreas Gohr{
37804369c3eSMichael Hamann    $iv     = auth_randombytes(16);
37924870174SAndreas Gohr    $cipher = new AES();
38004369c3eSMichael Hamann    $cipher->setPassword($secret);
38104369c3eSMichael Hamann
3827b650cefSMichael Hamann    /*
3837b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3847b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3857b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3867b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3877b650cefSMichael Hamann    */
38804369c3eSMichael Hamann    return $cipher->encrypt($iv . $data);
38904369c3eSMichael Hamann}
39004369c3eSMichael Hamann
39104369c3eSMichael Hamann/**
39204369c3eSMichael Hamann * Decrypt the given AES ciphertext
39304369c3eSMichael Hamann *
39404369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
39504369c3eSMichael Hamann *
39604369c3eSMichael Hamann * @param string $ciphertext The encrypted data
39704369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
39804369c3eSMichael Hamann * @return string The decrypted data
39904369c3eSMichael Hamann */
400d868eb89SAndreas Gohrfunction auth_decrypt($ciphertext, $secret)
401d868eb89SAndreas Gohr{
4027b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
40324870174SAndreas Gohr    $cipher = new AES();
40404369c3eSMichael Hamann    $cipher->setPassword($secret);
4057b650cefSMichael Hamann    $cipher->setIV($iv);
40604369c3eSMichael Hamann
4077b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
40804369c3eSMichael Hamann}
40904369c3eSMichael Hamann
41004369c3eSMichael Hamann/**
411883179a4SAndreas Gohr * Log out the current user
412883179a4SAndreas Gohr *
413f3f0262cSandi * This clears all authentication data and thus log the user
414883179a4SAndreas Gohr * off. It also clears session data.
41515fae107Sandi *
41615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
41742ea7f44SGerrit Uitslag *
418883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
419f3f0262cSandi */
420d868eb89SAndreas Gohrfunction auth_logoff($keepbc = false)
421d868eb89SAndreas Gohr{
422f3f0262cSandi    global $conf;
423f3f0262cSandi    global $USERINFO;
424e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4255298a619SAndreas Gohr    global $auth;
426585bf44eSChristopher Smith    /* @var Input $INPUT */
427585bf44eSChristopher Smith    global $INPUT;
42837065e65Sandi
429d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
430e9621d07SAndreas Gohr    @session_start();
431e9621d07SAndreas Gohr
432e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['user']))
433e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
434e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
435e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
436e71ce681SAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['auth']['info']))
437e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
438883179a4SAndreas Gohr    if (!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
439e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
440585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
441132bdbfeSandi    $USERINFO = null; //FIXME
442f5c6743cSAndreas Gohr
44373ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
444bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
445bf8392ebSAndreas Gohr        'expires' => time() - 600000,
446bf8392ebSAndreas Gohr        'path' => $cookieDir,
447bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
448bf8392ebSAndreas Gohr        'httponly' => true,
449486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
450bf8392ebSAndreas Gohr    ]);
4515298a619SAndreas Gohr
452880f62faSAndreas Gohr    if ($auth) $auth->logOff();
453f3f0262cSandi}
454f3f0262cSandi
455f3f0262cSandi/**
456f8cc712eSAndreas Gohr * Check if a user is a manager
457f8cc712eSAndreas Gohr *
458f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
459f8cc712eSAndreas Gohr * user.
460f8cc712eSAndreas Gohr *
461f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
462f8cc712eSAndreas Gohr *
463ab5d26daSAndreas Gohr * @param string $user Username
464ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
465ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
46610396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
467ab5d26daSAndreas Gohr * @return bool
46896348f27SAndreas Gohr * @see    auth_isadmin
46996348f27SAndreas Gohr *
47096348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
471f8cc712eSAndreas Gohr */
472d868eb89SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache = false)
473d868eb89SAndreas Gohr{
474f8cc712eSAndreas Gohr    global $conf;
475f8cc712eSAndreas Gohr    global $USERINFO;
476e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
477d752aedeSAndreas Gohr    global $auth;
478585bf44eSChristopher Smith    /* @var Input $INPUT */
479585bf44eSChristopher Smith    global $INPUT;
480585bf44eSChristopher Smith
481f8cc712eSAndreas Gohr
482beca106aSAdrian Lang    if (!$auth) return false;
483c66972f2SAdrian Lang    if (is_null($user)) {
484585bf44eSChristopher Smith        if (!$INPUT->server->has('REMOTE_USER')) {
485c66972f2SAdrian Lang            return false;
486c66972f2SAdrian Lang        } else {
487585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
488c66972f2SAdrian Lang        }
489c66972f2SAdrian Lang    }
490d6dc956fSAndreas Gohr    if (is_null($groups)) {
4911525c228SAnna Dabrowska        // checking the logged in user, or another one?
4921525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
4931525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
49466b108d6SAnna Dabrowska        } else {
4956cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
4966cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
49766b108d6SAnna Dabrowska        }
498e259aa79SAndreas Gohr    }
499e259aa79SAndreas Gohr
50096348f27SAndreas Gohr    // prefer cached result
50196348f27SAndreas Gohr    static $cache = [];
50210396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
50396348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
504d6dc956fSAndreas Gohr        // check superuser match
50596348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
50600ce12daSChris Smith
50796348f27SAndreas Gohr        // check managers
50896348f27SAndreas Gohr        if (!$ok && !$adminonly) {
50996348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
51096348f27SAndreas Gohr        }
51196348f27SAndreas Gohr
51296348f27SAndreas Gohr        $cache[$cachekey] = $ok;
51396348f27SAndreas Gohr    }
51496348f27SAndreas Gohr
51596348f27SAndreas Gohr    return $cache[$cachekey];
516f8cc712eSAndreas Gohr}
517f8cc712eSAndreas Gohr
518f8cc712eSAndreas Gohr/**
519f8cc712eSAndreas Gohr * Check if a user is admin
520f8cc712eSAndreas Gohr *
521f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
522f8cc712eSAndreas Gohr *
523f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
524f8cc712eSAndreas Gohr *
52596348f27SAndreas Gohr * @param string $user Username
52696348f27SAndreas Gohr * @param array $groups List of groups the user is in
52710396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
52896348f27SAndreas Gohr * @return bool
529f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
530ab5d26daSAndreas Gohr * @see auth_ismanager()
53142ea7f44SGerrit Uitslag *
532f8cc712eSAndreas Gohr */
533d868eb89SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache = false)
534d868eb89SAndreas Gohr{
53596348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
536f8cc712eSAndreas Gohr}
537f8cc712eSAndreas Gohr
538d6dc956fSAndreas Gohr/**
539d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
540d6dc956fSAndreas Gohr * users and groups to determine membership status
541d6dc956fSAndreas Gohr *
542d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
543d6dc956fSAndreas Gohr *
54442ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
54542ea7f44SGerrit Uitslag * @param string $user       user to match against
54642ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5475446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
548d6dc956fSAndreas Gohr */
549d868eb89SAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups)
550d868eb89SAndreas Gohr{
551e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
552d6dc956fSAndreas Gohr    global $auth;
553d6dc956fSAndreas Gohr    if (!$auth) return false;
554d6dc956fSAndreas Gohr
555d6dc956fSAndreas Gohr    // clean user and groups
5564f56ecbfSAdrian Lang    if (!$auth->isCaseSensitive()) {
55724870174SAndreas Gohr        $user   = PhpString::strtolower($user);
55824870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
559d6dc956fSAndreas Gohr    }
560d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
56124870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
562d6dc956fSAndreas Gohr
563d6dc956fSAndreas Gohr    // extract the memberlist
564d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
565d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
566d6dc956fSAndreas Gohr    $members = array_unique($members);
567d6dc956fSAndreas Gohr    $members = array_filter($members);
568d6dc956fSAndreas Gohr
569d6dc956fSAndreas Gohr    // compare cleaned values
570d6dc956fSAndreas Gohr    foreach ($members as $member) {
571e5204a12SJurgen Hart        if ($member == '@ALL') return true;
57224870174SAndreas Gohr        if (!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
573d6dc956fSAndreas Gohr        if ($member[0] == '@') {
574d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
575d6dc956fSAndreas Gohr            if (in_array($member, $groups)) return true;
576d6dc956fSAndreas Gohr        } else {
577d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
578d6dc956fSAndreas Gohr            if ($member == $user) return true;
579d6dc956fSAndreas Gohr        }
580d6dc956fSAndreas Gohr    }
581d6dc956fSAndreas Gohr
582d6dc956fSAndreas Gohr    // still here? not a member!
583d6dc956fSAndreas Gohr    return false;
584d6dc956fSAndreas Gohr}
585d6dc956fSAndreas Gohr
586f8cc712eSAndreas Gohr/**
58715fae107Sandi * Convinience function for auth_aclcheck()
58815fae107Sandi *
58915fae107Sandi * This checks the permissions for the current user
59015fae107Sandi *
59115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59215fae107Sandi *
5931698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
59415fae107Sandi * @return int          permission level
595f3f0262cSandi */
596d868eb89SAndreas Gohrfunction auth_quickaclcheck($id)
597d868eb89SAndreas Gohr{
598f3f0262cSandi    global $conf;
599f3f0262cSandi    global $USERINFO;
600585bf44eSChristopher Smith    /* @var Input $INPUT */
601585bf44eSChristopher Smith    global $INPUT;
602f3f0262cSandi    # if no ACL is used always return upload rights
603f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
60424870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
605f3f0262cSandi}
606f3f0262cSandi
607f3f0262cSandi/**
608c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
60915fae107Sandi *
61015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
61142ea7f44SGerrit Uitslag *
612c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
6131698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
61415fae107Sandi * @param  string       $user   Username
6153272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
61615fae107Sandi * @return int             permission level
617f3f0262cSandi */
618d868eb89SAndreas Gohrfunction auth_aclcheck($id, $user, $groups)
619d868eb89SAndreas Gohr{
62024870174SAndreas Gohr    $data = [
621bf8f8509SAndreas Gohr        'id'     => $id ?? '',
622c17acc9fSAndreas Gohr        'user'   => $user,
623c17acc9fSAndreas Gohr        'groups' => $groups
62424870174SAndreas Gohr    ];
625c17acc9fSAndreas Gohr
626cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
627c17acc9fSAndreas Gohr}
628c17acc9fSAndreas Gohr
629c17acc9fSAndreas Gohr/**
630c17acc9fSAndreas Gohr * default ACL check method
631c17acc9fSAndreas Gohr *
632c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
633c17acc9fSAndreas Gohr *
634c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
63542ea7f44SGerrit Uitslag *
636c17acc9fSAndreas Gohr * @param  array $data event data
637c17acc9fSAndreas Gohr * @return int   permission level
638c17acc9fSAndreas Gohr */
639d868eb89SAndreas Gohrfunction auth_aclcheck_cb($data)
640d868eb89SAndreas Gohr{
641c17acc9fSAndreas Gohr    $id     =& $data['id'];
642c17acc9fSAndreas Gohr    $user   =& $data['user'];
643c17acc9fSAndreas Gohr    $groups =& $data['groups'];
644c17acc9fSAndreas Gohr
645f3f0262cSandi    global $conf;
646f3f0262cSandi    global $AUTH_ACL;
647e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
648d752aedeSAndreas Gohr    global $auth;
649f3f0262cSandi
65085d03f68SAndreas Gohr    // if no ACL is used always return upload rights
651f3f0262cSandi    if (!$conf['useacl']) return AUTH_UPLOAD;
652beca106aSAdrian Lang    if (!$auth) return AUTH_NONE;
653bf8f8509SAndreas Gohr    if (!is_array($AUTH_ACL)) return AUTH_NONE;
654f3f0262cSandi
655074cf26bSandi    //make sure groups is an array
65624870174SAndreas Gohr    if (!is_array($groups)) $groups = [];
657074cf26bSandi
65885d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
659ab5d26daSAndreas Gohr    if (auth_isadmin($user, $groups)) {
660ab5d26daSAndreas Gohr        return AUTH_ADMIN;
661ab5d26daSAndreas Gohr    }
66285d03f68SAndreas Gohr
663eb3ce0d5SKazutaka Miyasaka    if (!$auth->isCaseSensitive()) {
66424870174SAndreas Gohr        $user   = PhpString::strtolower($user);
66524870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
666eb3ce0d5SKazutaka Miyasaka    }
66737ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
66824870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
66985d03f68SAndreas Gohr
6706c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
67137ff2261SSascha Klopp    foreach ($groups as &$group) {
67237ff2261SSascha Klopp        $group = '@' . auth_nameencode($group);
67310a76f6fSfrank    }
67410a76f6fSfrank
675f3f0262cSandi    $ns   = getNS($id);
676f3f0262cSandi    $perm = -1;
677f3f0262cSandi
678f3f0262cSandi    //add ALL group
679f3f0262cSandi    $groups[] = '@ALL';
68037ff2261SSascha Klopp
681f3f0262cSandi    //add User
68234aeb4afSAndreas Gohr    if ($user) $groups[] = $user;
683f3f0262cSandi
684f3f0262cSandi    //check exact match first
68521c3090aSChristopher Smith    $matches = preg_grep('/^' . preg_quote($id, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
686f3f0262cSandi    if (count($matches)) {
687f3f0262cSandi        foreach ($matches as $match) {
688f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
68921c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
690eb3ce0d5SKazutaka Miyasaka            if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
69124870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
692eb3ce0d5SKazutaka Miyasaka            }
69348d7b7a6SDominik Eckelmann            if (!in_array($acl[1], $groups)) {
69448d7b7a6SDominik Eckelmann                continue;
69548d7b7a6SDominik Eckelmann            }
6968ef6b7caSandi            if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
697f3f0262cSandi            if ($acl[2] > $perm) {
698f3f0262cSandi                $perm = $acl[2];
699f3f0262cSandi            }
700f3f0262cSandi        }
701f3f0262cSandi        if ($perm > -1) {
702f3f0262cSandi            //we had a match - return it
703def492a2SGuillaume Turri            return (int) $perm;
704f3f0262cSandi        }
705f3f0262cSandi    }
706f3f0262cSandi
707f3f0262cSandi    //still here? do the namespace checks
708f3f0262cSandi    if ($ns) {
7093e304b55SMichael Hamann        $path = $ns . ':*';
710f3f0262cSandi    } else {
7113e304b55SMichael Hamann        $path = '*'; //root document
712f3f0262cSandi    }
713f3f0262cSandi
714f3f0262cSandi    do {
71521c3090aSChristopher Smith        $matches = preg_grep('/^' . preg_quote($path, '/') . '[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
716f3f0262cSandi        if (count($matches)) {
717f3f0262cSandi            foreach ($matches as $match) {
718f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
71921c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
720eb3ce0d5SKazutaka Miyasaka                if (!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
72124870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
722eb3ce0d5SKazutaka Miyasaka                }
72348d7b7a6SDominik Eckelmann                if (!in_array($acl[1], $groups)) {
72448d7b7a6SDominik Eckelmann                    continue;
72548d7b7a6SDominik Eckelmann                }
7268ef6b7caSandi                if ($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
727f3f0262cSandi                if ($acl[2] > $perm) {
728f3f0262cSandi                    $perm = $acl[2];
729f3f0262cSandi                }
730f3f0262cSandi            }
731f3f0262cSandi            //we had a match - return it
73248d7b7a6SDominik Eckelmann            if ($perm != -1) {
733def492a2SGuillaume Turri                return (int) $perm;
734f3f0262cSandi            }
73548d7b7a6SDominik Eckelmann        }
736f3f0262cSandi        //get next higher namespace
737f3f0262cSandi        $ns = getNS($ns);
738f3f0262cSandi
7393e304b55SMichael Hamann        if ($path != '*') {
7403e304b55SMichael Hamann            $path = $ns . ':*';
7413e304b55SMichael Hamann            if ($path == ':*') $path = '*';
742f3f0262cSandi        } else {
743f3f0262cSandi            //we did this already
744f3f0262cSandi            //looks like there is something wrong with the ACL
745f3f0262cSandi            //break here
746d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
747d5ce66f6SAndreas Gohr            return AUTH_NONE;
748f3f0262cSandi        }
749f3f0262cSandi    } while (1); //this should never loop endless
750ab5d26daSAndreas Gohr    return AUTH_NONE;
751f3f0262cSandi}
752f3f0262cSandi
753f3f0262cSandi/**
7546c2bb100SAndreas Gohr * Encode ASCII special chars
7556c2bb100SAndreas Gohr *
7566c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7576c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7586c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7596c2bb100SAndreas Gohr * urlencoding!).
7606c2bb100SAndreas Gohr *
7616c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7626c2bb100SAndreas Gohr *
7636c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7646c2bb100SAndreas Gohr * @see rawurldecode()
76542ea7f44SGerrit Uitslag *
76642ea7f44SGerrit Uitslag * @param string $name
76742ea7f44SGerrit Uitslag * @param bool $skip_group
76842ea7f44SGerrit Uitslag * @return string
7696c2bb100SAndreas Gohr */
770d868eb89SAndreas Gohrfunction auth_nameencode($name, $skip_group = false)
771d868eb89SAndreas Gohr{
772a424cd8eSchris    global $cache_authname;
773a424cd8eSchris    $cache =& $cache_authname;
77431784267SAndreas Gohr    $name  = (string) $name;
775a424cd8eSchris
77680601d26SAndreas Gohr    // never encode wildcard FS#1955
77780601d26SAndreas Gohr    if ($name == '%USER%') return $name;
778b78bf706Sromain    if ($name == '%GROUP%') return $name;
77980601d26SAndreas Gohr
780a424cd8eSchris    if (!isset($cache[$name][$skip_group])) {
7812401f18dSSyntaxseed        if ($skip_group && $name[0] == '@') {
78230f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@' . preg_replace_callback(
78330f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
784dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
785dccd6b2bSAndreas Gohr                substr($name, 1)
786ab5d26daSAndreas Gohr            );
787e838fc2eSAndreas Gohr        } else {
78830f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
78930f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
790dccd6b2bSAndreas Gohr                'auth_nameencode_callback',
791dccd6b2bSAndreas Gohr                $name
792ab5d26daSAndreas Gohr            );
793e838fc2eSAndreas Gohr        }
7946c2bb100SAndreas Gohr    }
7956c2bb100SAndreas Gohr
796a424cd8eSchris    return $cache[$name][$skip_group];
797a424cd8eSchris}
798a424cd8eSchris
79904d68ae4SGerrit Uitslag/**
80004d68ae4SGerrit Uitslag * callback encodes the matches
80104d68ae4SGerrit Uitslag *
80204d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
80304d68ae4SGerrit Uitslag * @return string
80404d68ae4SGerrit Uitslag */
805d868eb89SAndreas Gohrfunction auth_nameencode_callback($matches)
806d868eb89SAndreas Gohr{
80730f6faf0SChristopher Smith    return '%' . dechex(ord(substr($matches[1], -1)));
80830f6faf0SChristopher Smith}
80930f6faf0SChristopher Smith
8106c2bb100SAndreas Gohr/**
811f3f0262cSandi * Create a pronouncable password
812f3f0262cSandi *
8138a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
8148a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
8158a285f7fSAndreas Gohr *
81615fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
81715fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
8188a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
81915fae107Sandi *
8208a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
82115fae107Sandi * @return string  pronouncable password
822f3f0262cSandi */
823d868eb89SAndreas Gohrfunction auth_pwgen($foruser = '')
824d868eb89SAndreas Gohr{
82524870174SAndreas Gohr    $data = [
826d628dcf3SAndreas Gohr        'password' => '',
827d628dcf3SAndreas Gohr        'foruser'  => $foruser
82824870174SAndreas Gohr    ];
8298a285f7fSAndreas Gohr
830e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8318a285f7fSAndreas Gohr    if ($evt->advise_before(true)) {
832f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
833f3f0262cSandi        $v = 'aeiou'; //vowels
834f3f0262cSandi        $a = $c . $v; //both
835987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
836f3f0262cSandi
837987c8d26SAndreas Gohr        //use thre syllables...
838987c8d26SAndreas Gohr        for ($i = 0; $i < 3; $i++) {
839483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
840483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
841483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
842f3f0262cSandi        }
843987c8d26SAndreas Gohr        //... and add a nice number and special
84443f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)] . auth_random(10, 99);
8458a285f7fSAndreas Gohr    }
8468a285f7fSAndreas Gohr    $evt->advise_after();
847f3f0262cSandi
8488a285f7fSAndreas Gohr    return $data['password'];
849f3f0262cSandi}
850f3f0262cSandi
851f3f0262cSandi/**
852f3f0262cSandi * Sends a password to the given user
853f3f0262cSandi *
85415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
85542ea7f44SGerrit Uitslag *
856ab5d26daSAndreas Gohr * @param string $user Login name of the user
857ab5d26daSAndreas Gohr * @param string $password The new password in clear text
85815fae107Sandi * @return bool  true on success
859f3f0262cSandi */
860d868eb89SAndreas Gohrfunction auth_sendPassword($user, $password)
861d868eb89SAndreas Gohr{
862f3f0262cSandi    global $lang;
863e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
864cd52f92dSchris    global $auth;
865beca106aSAdrian Lang    if (!$auth) return false;
866cd52f92dSchris
867d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8682dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
869f3f0262cSandi
87087ddda95Sandi    if (!$userinfo['mail']) return false;
871f3f0262cSandi
872f3f0262cSandi    $text = rawLocale('password');
87324870174SAndreas Gohr    $trep = [
874d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
875d7169d19SAndreas Gohr        'LOGIN'    => $user,
876d7169d19SAndreas Gohr        'PASSWORD' => $password
87724870174SAndreas Gohr    ];
878f3f0262cSandi
879d7169d19SAndreas Gohr    $mail = new Mailer();
880102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']) . ' <' . $userinfo['mail'] . '>');
881d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
882d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
883d7169d19SAndreas Gohr    return $mail->send();
884f3f0262cSandi}
885f3f0262cSandi
886f3f0262cSandi/**
88715fae107Sandi * Register a new user
888f3f0262cSandi *
88915fae107Sandi * This registers a new user - Data is read directly from $_POST
89015fae107Sandi *
89115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
89242ea7f44SGerrit Uitslag *
89315fae107Sandi * @return bool  true on success, false on any error
894f3f0262cSandi */
895d868eb89SAndreas Gohrfunction register()
896d868eb89SAndreas Gohr{
897f3f0262cSandi    global $lang;
898eb5d07e4Sjan    global $conf;
899e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
900cd52f92dSchris    global $auth;
90164273335SAndreas Gohr    global $INPUT;
902f3f0262cSandi
90364273335SAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9043a48618aSAnika Henke    if (!actionOK('register')) return false;
905640145a5Sandi
90664273335SAndreas Gohr    // gather input
90764273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
90864273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
90964273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
91064273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
91164273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
912d752aedeSAndreas Gohr
91364273335SAndreas Gohr    if (empty($login) || empty($fullname) || empty($email)) {
914f3f0262cSandi        msg($lang['regmissing'], -1);
915f3f0262cSandi        return false;
916f3f0262cSandi    }
917f3f0262cSandi
918cab2716aSmatthias.grimm    if ($conf['autopasswd']) {
9198a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
92064273335SAndreas Gohr    } elseif (empty($pass) || empty($passchk)) {
921bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
922cab2716aSmatthias.grimm        return false;
92364273335SAndreas Gohr    } elseif ($pass != $passchk) {
924bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
925cab2716aSmatthias.grimm        return false;
926cab2716aSmatthias.grimm    }
927cab2716aSmatthias.grimm
928f3f0262cSandi    //check mail
92964273335SAndreas Gohr    if (!mail_isvalid($email)) {
930f3f0262cSandi        msg($lang['regbadmail'], -1);
931f3f0262cSandi        return false;
932f3f0262cSandi    }
933f3f0262cSandi
934f3f0262cSandi    //okay try to create the user
93524870174SAndreas Gohr    if (!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
936db9faf02SPatrick Brown        msg($lang['regfail'], -1);
937f3f0262cSandi        return false;
938f3f0262cSandi    }
939f3f0262cSandi
940790b7720SAndreas Gohr    // send notification about the new user
94175d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
94275d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
94302a498e7Schris
944790b7720SAndreas Gohr    // are we done?
945cab2716aSmatthias.grimm    if (!$conf['autopasswd']) {
946cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
947cab2716aSmatthias.grimm        return true;
948cab2716aSmatthias.grimm    }
949cab2716aSmatthias.grimm
950790b7720SAndreas Gohr    // autogenerated password? then send password to user
95164273335SAndreas Gohr    if (auth_sendPassword($login, $pass)) {
952f3f0262cSandi        msg($lang['regsuccess'], 1);
953f3f0262cSandi        return true;
954f3f0262cSandi    } else {
955f3f0262cSandi        msg($lang['regmailfail'], -1);
956f3f0262cSandi        return false;
957f3f0262cSandi    }
958f3f0262cSandi}
959f3f0262cSandi
96010a76f6fSfrank/**
9618b06d178Schris * Update user profile
9628b06d178Schris *
9638b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9648b06d178Schris */
965d868eb89SAndreas Gohrfunction updateprofile()
966d868eb89SAndreas Gohr{
9678b06d178Schris    global $conf;
9688b06d178Schris    global $lang;
969e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
970cd52f92dSchris    global $auth;
971bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
972bcc94b2cSAndreas Gohr    global $INPUT;
9738b06d178Schris
974bcc94b2cSAndreas Gohr    if (!$INPUT->post->bool('save')) return false;
9751b2a85e8SAndreas Gohr    if (!checkSecurityToken()) return false;
9768b06d178Schris
9773a48618aSAnika Henke    if (!actionOK('profile')) {
9788b06d178Schris        msg($lang['profna'], -1);
9798b06d178Schris        return false;
9808b06d178Schris    }
9818b06d178Schris
98224870174SAndreas Gohr    $changes         = [];
983bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
984bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
985bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
986bcc94b2cSAndreas Gohr
987bcc94b2cSAndreas Gohr    // check misspelled passwords
988bcc94b2cSAndreas Gohr    if ($changes['pass'] != $INPUT->post->str('passchk')) {
989bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9908b06d178Schris        return false;
9918b06d178Schris    }
9928b06d178Schris
9938b06d178Schris    // clean fullname and email
994bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
995bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9968b06d178Schris
997bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
9987d34963bSAndreas Gohr    if (
9997d34963bSAndreas Gohr        (empty($changes['name']) && $auth->canDo('modName')) ||
1000bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
1001ab5d26daSAndreas Gohr    ) {
10028b06d178Schris        msg($lang['profnoempty'], -1);
10038b06d178Schris        return false;
10048b06d178Schris    }
1005bcc94b2cSAndreas Gohr    if (!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
10068b06d178Schris        msg($lang['regbadmail'], -1);
10078b06d178Schris        return false;
10088b06d178Schris    }
10098b06d178Schris
1010bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
10114c21b7eeSAndreas Gohr
1012bcc94b2cSAndreas Gohr    // check for unavailable capabilities
1013bcc94b2cSAndreas Gohr    if (!$auth->canDo('modName')) unset($changes['name']);
1014bcc94b2cSAndreas Gohr    if (!$auth->canDo('modMail')) unset($changes['mail']);
1015bcc94b2cSAndreas Gohr    if (!$auth->canDo('modPass')) unset($changes['pass']);
1016bcc94b2cSAndreas Gohr
1017bcc94b2cSAndreas Gohr    // anything to do?
101824870174SAndreas Gohr    if ($changes === []) {
10198b06d178Schris        msg($lang['profnochange'], -1);
10208b06d178Schris        return false;
10218b06d178Schris    }
10228b06d178Schris
10238b06d178Schris    if ($conf['profileconfirm']) {
1024585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
102571422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
10268b06d178Schris            return false;
10278b06d178Schris        }
10288b06d178Schris    }
10298b06d178Schris
103024870174SAndreas Gohr    if (!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1031db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1032db9faf02SPatrick Brown        return false;
1033db9faf02SPatrick Brown    }
1034db9faf02SPatrick Brown
103532ed2b36SAndreas Gohr    if ($changes['pass']) {
1036c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1037a19c9aa0SGerrit Uitslag        [/* user */, $sticky, /* pass */] = auth_getCookie();
103804369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1039585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1040c276e9e8SMarcel Pennewiss    } else {
1041c276e9e8SMarcel Pennewiss        // make sure the session is writable
1042c276e9e8SMarcel Pennewiss        @session_start();
1043c276e9e8SMarcel Pennewiss        // invalidate session cache
1044c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1045c276e9e8SMarcel Pennewiss        session_write_close();
104632ed2b36SAndreas Gohr    }
1047c276e9e8SMarcel Pennewiss
104825b2a98cSMichael Klier    return true;
1049a0b5b007SChris Smith}
1050ab5d26daSAndreas Gohr
105104d68ae4SGerrit Uitslag/**
105204d68ae4SGerrit Uitslag * Delete the current logged-in user
105304d68ae4SGerrit Uitslag *
105404d68ae4SGerrit Uitslag * @return bool true on success, false on any error
105504d68ae4SGerrit Uitslag */
1056d868eb89SAndreas Gohrfunction auth_deleteprofile()
1057d868eb89SAndreas Gohr{
10582a7abf2dSChristopher Smith    global $conf;
10592a7abf2dSChristopher Smith    global $lang;
1060e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10612a7abf2dSChristopher Smith    global $auth;
10622a7abf2dSChristopher Smith    /* @var Input $INPUT */
10632a7abf2dSChristopher Smith    global $INPUT;
10642a7abf2dSChristopher Smith
10652a7abf2dSChristopher Smith    if (!$INPUT->post->bool('delete')) return false;
10662a7abf2dSChristopher Smith    if (!checkSecurityToken()) return false;
10672a7abf2dSChristopher Smith
10682a7abf2dSChristopher Smith    // action prevented or auth module disallows
10692a7abf2dSChristopher Smith    if (!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10702a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10712a7abf2dSChristopher Smith        return false;
10722a7abf2dSChristopher Smith    }
10732a7abf2dSChristopher Smith
10742a7abf2dSChristopher Smith    if (!$INPUT->post->bool('confirm_delete')) {
10752a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10762a7abf2dSChristopher Smith        return false;
10772a7abf2dSChristopher Smith    }
10782a7abf2dSChristopher Smith
10792a7abf2dSChristopher Smith    if ($conf['profileconfirm']) {
1080585bf44eSChristopher Smith        if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10812a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10822a7abf2dSChristopher Smith            return false;
10832a7abf2dSChristopher Smith        }
10842a7abf2dSChristopher Smith    }
10852a7abf2dSChristopher Smith
108624870174SAndreas Gohr    $deleted = [];
1087585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
108824870174SAndreas Gohr    if ($auth->triggerUserMod('delete', [$deleted])) {
10892a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10902a7abf2dSChristopher Smith        auth_logoff();
10912a7abf2dSChristopher Smith        return true;
10922a7abf2dSChristopher Smith    }
10932a7abf2dSChristopher Smith
10942a7abf2dSChristopher Smith    return false;
10952a7abf2dSChristopher Smith}
10962a7abf2dSChristopher Smith
10978b06d178Schris/**
10988b06d178Schris * Send a  new password
10998b06d178Schris *
11001d5856cfSAndreas Gohr * This function handles both phases of the password reset:
11011d5856cfSAndreas Gohr *
11021d5856cfSAndreas Gohr *   - handling the first request of password reset
11031d5856cfSAndreas Gohr *   - validating the password reset auth token
11041d5856cfSAndreas Gohr *
11058b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
11068b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
11071d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11088b06d178Schris *
11098b06d178Schris * @return bool true on success, false on any error
11108b06d178Schris */
1111d868eb89SAndreas Gohrfunction act_resendpwd()
1112d868eb89SAndreas Gohr{
11138b06d178Schris    global $lang;
11148b06d178Schris    global $conf;
1115e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1116cd52f92dSchris    global $auth;
1117bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1118bcc94b2cSAndreas Gohr    global $INPUT;
11198b06d178Schris
11203a48618aSAnika Henke    if (!actionOK('resendpwd')) {
11218b06d178Schris        msg($lang['resendna'], -1);
11228b06d178Schris        return false;
11238b06d178Schris    }
11248b06d178Schris
1125bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
11268b06d178Schris
11271d5856cfSAndreas Gohr    if ($token) {
1128cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
11291d5856cfSAndreas Gohr
11302401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
113179e79377SAndreas Gohr        if (!file_exists($tfile)) {
11321d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1133bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11341d5856cfSAndreas Gohr            return false;
11351d5856cfSAndreas Gohr        }
11368a9735e3SAndreas Gohr        // token is only valid for 3 days
11378a9735e3SAndreas Gohr        if ((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
11388a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1139bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11401d5856cfSAndreas Gohr            @unlink($tfile);
11418a9735e3SAndreas Gohr            return false;
11428a9735e3SAndreas Gohr        }
11438a9735e3SAndreas Gohr
11448b06d178Schris        $user     = io_readfile($tfile);
11452dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11468b06d178Schris        if (!$userinfo['mail']) {
11478b06d178Schris            msg($lang['resendpwdnouser'], -1);
11488b06d178Schris            return false;
11498b06d178Schris        }
11508b06d178Schris
1151cc204bbdSAndreas Gohr        if (!$conf['autopasswd']) { // we let the user choose a password
1152bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1153bcc94b2cSAndreas Gohr
1154cc204bbdSAndreas Gohr            // password given correctly?
1155bcc94b2cSAndreas Gohr            if (!$pass) return false;
1156bcc94b2cSAndreas Gohr            if ($pass != $INPUT->str('passchk')) {
1157451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1158cc204bbdSAndreas Gohr                return false;
1159cc204bbdSAndreas Gohr            }
1160cc204bbdSAndreas Gohr
1161bcc94b2cSAndreas Gohr            // change it
116224870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1163db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1164cc204bbdSAndreas Gohr                return false;
1165cc204bbdSAndreas Gohr            }
1166cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
11678a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
116824870174SAndreas Gohr            if (!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1169db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11708b06d178Schris                return false;
11718b06d178Schris            }
11728b06d178Schris
11738b06d178Schris            if (auth_sendPassword($user, $pass)) {
11748b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11758b06d178Schris            } else {
11768b06d178Schris                msg($lang['regmailfail'], -1);
11778b06d178Schris            }
1178cc204bbdSAndreas Gohr        }
1179cc204bbdSAndreas Gohr
1180cc204bbdSAndreas Gohr        @unlink($tfile);
11818b06d178Schris        return true;
11821d5856cfSAndreas Gohr    } else {
11831d5856cfSAndreas Gohr        // we're in request phase
11841d5856cfSAndreas Gohr
1185bcc94b2cSAndreas Gohr        if (!$INPUT->post->bool('save')) return false;
11861d5856cfSAndreas Gohr
1187bcc94b2cSAndreas Gohr        if (!$INPUT->post->str('login')) {
11881d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11891d5856cfSAndreas Gohr            return false;
11901d5856cfSAndreas Gohr        } else {
1191bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11921d5856cfSAndreas Gohr        }
11931d5856cfSAndreas Gohr
11942dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11951d5856cfSAndreas Gohr        if (!$userinfo['mail']) {
11961d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11971d5856cfSAndreas Gohr            return false;
11981d5856cfSAndreas Gohr        }
11991d5856cfSAndreas Gohr
12001d5856cfSAndreas Gohr        // generate auth token
1201483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
12022401f18dSSyntaxseed        $tfile = $conf['cachedir'] . '/' . $token[0] . '/' . $token . '.pwauth';
120324870174SAndreas Gohr        $url   = wl('', ['do' => 'resendpwd', 'pwauth' => $token], true, '&');
12041d5856cfSAndreas Gohr
12051d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
12061d5856cfSAndreas Gohr
12071d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
120824870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
12091d5856cfSAndreas Gohr
1210d7169d19SAndreas Gohr        $mail = new Mailer();
1211d7169d19SAndreas Gohr        $mail->to($userinfo['name'] . ' <' . $userinfo['mail'] . '>');
1212d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1213d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1214d7169d19SAndreas Gohr        if ($mail->send()) {
12151d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
12161d5856cfSAndreas Gohr        } else {
12171d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
12181d5856cfSAndreas Gohr        }
12191d5856cfSAndreas Gohr        return true;
12201d5856cfSAndreas Gohr    }
1221ab5d26daSAndreas Gohr    // never reached
12228b06d178Schris}
12238b06d178Schris
12248b06d178Schris/**
1225b0855b11Sandi * Encrypts a password using the given method and salt
1226b0855b11Sandi *
1227b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1228b0855b11Sandi * is chosen.
1229b0855b11Sandi *
1230b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
123142ea7f44SGerrit Uitslag *
1232ab5d26daSAndreas Gohr * @param string $clear The clear text password
1233ab5d26daSAndreas Gohr * @param string $method The hashing method
1234ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1235b0855b11Sandi * @return  string  The crypted password
1236b0855b11Sandi */
1237d868eb89SAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null)
1238d868eb89SAndreas Gohr{
1239b0855b11Sandi    global $conf;
1240b0855b11Sandi    if (empty($method)) $method = $conf['passcrypt'];
124110a76f6fSfrank
12423a0a2d05SAndreas Gohr    $pass = new PassHash();
12433a0a2d05SAndreas Gohr    $call = 'hash_' . $method;
1244b0855b11Sandi
12453a0a2d05SAndreas Gohr    if (!method_exists($pass, $call)) {
1246b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12473a0a2d05SAndreas Gohr        return false;
1248b0855b11Sandi    }
12493a0a2d05SAndreas Gohr
12503a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1251b0855b11Sandi}
1252b0855b11Sandi
1253b0855b11Sandi/**
1254b0855b11Sandi * Verifies a cleartext password against a crypted hash
1255b0855b11Sandi *
1256b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
125742ea7f44SGerrit Uitslag *
1258ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1259ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1260ab5d26daSAndreas Gohr * @return bool true if both match
1261b0855b11Sandi */
1262d868eb89SAndreas Gohrfunction auth_verifyPassword($clear, $crypt)
1263d868eb89SAndreas Gohr{
12643a0a2d05SAndreas Gohr    $pass = new PassHash();
12653a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1266b0855b11Sandi}
1267340756e4Sandi
1268a0b5b007SChris Smith/**
1269a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1270a0b5b007SChris Smith *
1271a0b5b007SChris Smith * @param string  $user       username
1272a0b5b007SChris Smith * @param string  $pass       encrypted password
1273a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1274ab5d26daSAndreas Gohr * @return bool
1275a0b5b007SChris Smith */
1276d868eb89SAndreas Gohrfunction auth_setCookie($user, $pass, $sticky)
1277d868eb89SAndreas Gohr{
1278a0b5b007SChris Smith    global $conf;
1279e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1280a0b5b007SChris Smith    global $auth;
128179d00841SOliver Geisen    global $USERINFO;
1282a0b5b007SChris Smith
1283beca106aSAdrian Lang    if (!$auth) return false;
1284a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1285a0b5b007SChris Smith
1286a0b5b007SChris Smith    // set cookie
1287645c0a36SAndreas Gohr    $cookie    = base64_encode($user) . '|' . ((int) $sticky) . '|' . base64_encode($pass);
128873ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1289c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1290bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1291bf8392ebSAndreas Gohr        'expires' => $time,
1292bf8392ebSAndreas Gohr        'path' => $cookieDir,
1293bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1294bf8392ebSAndreas Gohr        'httponly' => true,
1295486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1296bf8392ebSAndreas Gohr    ]);
129755a71a16SGerrit Uitslag
1298a0b5b007SChris Smith    // set session
1299a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1300234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1301a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1302a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1303a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1304ab5d26daSAndreas Gohr
1305ab5d26daSAndreas Gohr    return true;
1306a0b5b007SChris Smith}
1307a0b5b007SChris Smith
1308645c0a36SAndreas Gohr/**
1309645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1310645c0a36SAndreas Gohr *
1311645c0a36SAndreas Gohr * @returns array
1312645c0a36SAndreas Gohr */
1313d868eb89SAndreas Gohrfunction auth_getCookie()
1314d868eb89SAndreas Gohr{
1315c66972f2SAdrian Lang    if (!isset($_COOKIE[DOKU_COOKIE])) {
131624870174SAndreas Gohr        return [null, null, null];
1317c66972f2SAdrian Lang    }
131824870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1319645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1320645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1321645c0a36SAndreas Gohr    $user   = base64_decode($user);
132224870174SAndreas Gohr    return [$user, $sticky, $pass];
1323645c0a36SAndreas Gohr}
1324645c0a36SAndreas Gohr
1325e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1326