xref: /dokuwiki/inc/auth.php (revision 24870174d2ee45460ba6bcfe5f5a0ae94715efd7)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Authentication library
415fae107Sandi *
515fae107Sandi * Including this file will automatically try to login
615fae107Sandi * a user by calling auth_login()
715fae107Sandi *
815fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
915fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1015fae107Sandi */
11*24870174SAndreas Gohruse phpseclib\Crypt\AES;
12*24870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1396348f27SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
1496348f27SAndreas Gohruse dokuwiki\Extension\Event;
1596348f27SAndreas Gohruse dokuwiki\Extension\PluginController;
16c3cc6e05SAndreas Gohruse dokuwiki\PassHash;
1775d66495SMichael Großeuse dokuwiki\Subscriptions\RegistrationSubscriptionSender;
18c3cc6e05SAndreas Gohr
1916905344SAndreas Gohr/**
2016905344SAndreas Gohr * Initialize the auth system.
2116905344SAndreas Gohr *
2216905344SAndreas Gohr * This function is automatically called at the end of init.php
2316905344SAndreas Gohr *
2416905344SAndreas Gohr * This used to be the main() of the auth.php
2516905344SAndreas Gohr *
2616905344SAndreas Gohr * @todo backend loading maybe should be handled by the class autoloader
2716905344SAndreas Gohr * @todo maybe split into multiple functions at the XXX marked positions
28ab5d26daSAndreas Gohr * @triggers AUTH_LOGIN_CHECK
29ab5d26daSAndreas Gohr * @return bool
3016905344SAndreas Gohr */
3116905344SAndreas Gohrfunction auth_setup() {
32742c66f8Schris    global $conf;
33e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
3403c4aec3Schris    global $auth;
35bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
36bcc94b2cSAndreas Gohr    global $INPUT;
379a9714acSDominik Eckelmann    global $AUTH_ACL;
389a9714acSDominik Eckelmann    global $lang;
393a7140a1SAndreas Gohr    /* @var PluginController $plugin_controller */
409c29eea5SJan Schumann    global $plugin_controller;
41*24870174SAndreas Gohr    $AUTH_ACL = [];
4203c4aec3Schris
4316905344SAndreas Gohr    if(!$conf['useacl']) return false;
4416905344SAndreas Gohr
459c29eea5SJan Schumann    // try to load auth backend from plugins
469c29eea5SJan Schumann    foreach ($plugin_controller->getList('auth') as $plugin) {
479c29eea5SJan Schumann        if ($conf['authtype'] === $plugin) {
48f4476bd9SJan Schumann            $auth = $plugin_controller->load('auth', $plugin);
499c29eea5SJan Schumann            break;
509c29eea5SJan Schumann        }
519c29eea5SJan Schumann    }
528b06d178Schris
536416b708SMichael Hamann    if(!isset($auth) || !$auth){
543094e817SAndreas Gohr        msg($lang['authtempfail'], -1);
553094e817SAndreas Gohr        return false;
563094e817SAndreas Gohr    }
578b06d178Schris
586416b708SMichael Hamann    if ($auth->success == false) {
590f4f4adfSAndreas Gohr        // degrade to unauthenticated user
60ecad51ddSAndreas Gohr        $auth = null;
610f4f4adfSAndreas Gohr        auth_logoff();
62cd52f92dSchris        msg($lang['authtempfail'], -1);
636416b708SMichael Hamann        return false;
64d2dde4ebSMatthias Grimm    }
6516905344SAndreas Gohr
6616905344SAndreas Gohr    // do the login either by cookie or provided credentials XXX
67bcc94b2cSAndreas Gohr    $INPUT->set('http_credentials', false);
68bcc94b2cSAndreas Gohr    if(!$conf['rememberme']) $INPUT->set('r', false);
69bbbd6568SAndreas Gohr
7062bf3ac0SDamien Regad    // Populate Basic Auth user/password from Authorization header
7162bf3ac0SDamien Regad    // Note: with FastCGI, data is in REDIRECT_HTTP_AUTHORIZATION instead of HTTP_AUTHORIZATION
7262bf3ac0SDamien Regad    $header = $INPUT->server->str('HTTP_AUTHORIZATION') ?: $INPUT->server->str('REDIRECT_HTTP_AUTHORIZATION');
7362bf3ac0SDamien Regad    if(preg_match( '~^Basic ([a-z\d/+]*={0,2})$~i', $header, $matches )) {
7462bf3ac0SDamien Regad        $userpass = explode(':', base64_decode($matches[1]));
75*24870174SAndreas Gohr        [$_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']] = $userpass;
76528ddc7cSAndreas Gohr    }
77528ddc7cSAndreas Gohr
781e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
7903062864SAndreas Gohr    if (!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($INPUT->server->str('PHP_AUTH_USER'))) {
8003062864SAndreas Gohr        $INPUT->set('u', $INPUT->server->str('PHP_AUTH_USER'));
8103062864SAndreas Gohr        $INPUT->set('p', $INPUT->server->str('PHP_AUTH_PW'));
82bcc94b2cSAndreas Gohr        $INPUT->set('http_credentials', true);
831e8c9c90SAndreas Gohr    }
841e8c9c90SAndreas Gohr
85395c2f0fSAndreas Gohr    // apply cleaning (auth specific user names, remove control chars)
8693a7873eSAndreas Gohr    if (true === $auth->success) {
87395c2f0fSAndreas Gohr        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
88395c2f0fSAndreas Gohr        $INPUT->set('p', stripctl($INPUT->str('p')));
89f4476bd9SJan Schumann    }
90191bb90aSAndreas Gohr
9181e99965SPhy    $ok = null;
928eca974cSAndreas Gohr    if (!is_null($auth) && $auth->canDo('external')) {
9381e99965SPhy        $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
9481e99965SPhy    }
9581e99965SPhy
9681e99965SPhy    if ($ok === null) {
9781e99965SPhy        // external trust mechanism not in place, or returns no result,
9881e99965SPhy        // then attempt auth_login
99*24870174SAndreas Gohr        $evdata = [
100bcc94b2cSAndreas Gohr            'user'     => $INPUT->str('u'),
101bcc94b2cSAndreas Gohr            'password' => $INPUT->str('p'),
102bcc94b2cSAndreas Gohr            'sticky'   => $INPUT->bool('r'),
103bcc94b2cSAndreas Gohr            'silent'   => $INPUT->bool('http_credentials')
104*24870174SAndreas Gohr        ];
105cbb44eabSAndreas Gohr        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
106f5cb575dSAndreas Gohr    }
107f5cb575dSAndreas Gohr
10816905344SAndreas Gohr    //load ACL into a global array XXX
10975c93b77SAndreas Gohr    $AUTH_ACL = auth_loadACL();
110ab5d26daSAndreas Gohr
111ab5d26daSAndreas Gohr    return true;
11275c93b77SAndreas Gohr}
11375c93b77SAndreas Gohr
11475c93b77SAndreas Gohr/**
11575c93b77SAndreas Gohr * Loads the ACL setup and handle user wildcards
11675c93b77SAndreas Gohr *
11775c93b77SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11842ea7f44SGerrit Uitslag *
119ab5d26daSAndreas Gohr * @return array
12075c93b77SAndreas Gohr */
12175c93b77SAndreas Gohrfunction auth_loadACL() {
12275c93b77SAndreas Gohr    global $config_cascade;
123b78bf706Sromain    global $USERINFO;
124585bf44eSChristopher Smith    /* @var Input $INPUT */
125585bf44eSChristopher Smith    global $INPUT;
12675c93b77SAndreas Gohr
127*24870174SAndreas Gohr    if(!is_readable($config_cascade['acl']['default'])) return [];
12875c93b77SAndreas Gohr
12975c93b77SAndreas Gohr    $acl = file($config_cascade['acl']['default']);
13075c93b77SAndreas Gohr
131*24870174SAndreas Gohr    $out = [];
1329ce556d2SAndreas Gohr    foreach($acl as $line) {
1339ce556d2SAndreas Gohr        $line = trim($line);
1342401f18dSSyntaxseed        if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
135*24870174SAndreas Gohr        [$id, $rest] = preg_split('/[ \t]+/',$line,2);
13632e82180SAndreas Gohr
137443e135dSChristopher Smith        // substitute user wildcard first (its 1:1)
138ad3d68d7SChristopher Smith        if(strstr($line, '%USER%')){
139ad3d68d7SChristopher Smith            // if user is not logged in, this ACL line is meaningless - skip it
140585bf44eSChristopher Smith            if (!$INPUT->server->has('REMOTE_USER')) continue;
141ad3d68d7SChristopher Smith
142585bf44eSChristopher Smith            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
143585bf44eSChristopher Smith            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
144ad3d68d7SChristopher Smith        }
145ad3d68d7SChristopher Smith
146ad3d68d7SChristopher Smith        // substitute group wildcard (its 1:m)
1479ce556d2SAndreas Gohr        if(strstr($line, '%GROUP%')){
148ad3d68d7SChristopher Smith            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
14906f34f54SPhy            if(isset($USERINFO['grps'])){
1509ce556d2SAndreas Gohr                foreach((array) $USERINFO['grps'] as $grp){
151b78bf706Sromain                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
15232e82180SAndreas Gohr                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
15332e82180SAndreas Gohr                    $out[] = "$nid\t$nrest";
154b78bf706Sromain                }
15506f34f54SPhy            }
15632e82180SAndreas Gohr        } else {
15732e82180SAndreas Gohr            $out[] = "$id\t$rest";
158a8fe108bSGuy Brand        }
15911799630Sandi    }
1609ce556d2SAndreas Gohr
16132e82180SAndreas Gohr    return $out;
162f3f0262cSandi}
163f3f0262cSandi
164ab5d26daSAndreas Gohr/**
165ab5d26daSAndreas Gohr * Event hook callback for AUTH_LOGIN_CHECK
166ab5d26daSAndreas Gohr *
16742ea7f44SGerrit Uitslag * @param array $evdata
168ab5d26daSAndreas Gohr * @return bool
169ab5d26daSAndreas Gohr */
170b5ee21aaSAdrian Langfunction auth_login_wrapper($evdata) {
171ab5d26daSAndreas Gohr    return auth_login(
172ab5d26daSAndreas Gohr        $evdata['user'],
173b5ee21aaSAdrian Lang        $evdata['password'],
174b5ee21aaSAdrian Lang        $evdata['sticky'],
175ab5d26daSAndreas Gohr        $evdata['silent']
176ab5d26daSAndreas Gohr    );
177b5ee21aaSAdrian Lang}
178b5ee21aaSAdrian Lang
179f3f0262cSandi/**
180f3f0262cSandi * This tries to login the user based on the sent auth credentials
181f3f0262cSandi *
182f3f0262cSandi * The authentication works like this: if a username was given
18315fae107Sandi * a new login is assumed and user/password are checked. If they
18415fae107Sandi * are correct the password is encrypted with blowfish and stored
18515fae107Sandi * together with the username in a cookie - the same info is stored
18615fae107Sandi * in the session, too. Additonally a browserID is stored in the
18715fae107Sandi * session.
18815fae107Sandi *
18915fae107Sandi * If no username was given the cookie is checked: if the username,
19015fae107Sandi * crypted password and browserID match between session and cookie
19115fae107Sandi * no further testing is done and the user is accepted
19215fae107Sandi *
19315fae107Sandi * If a cookie was found but no session info was availabe the
194136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
19515fae107Sandi * together with username rechecked by calling this function again.
196f3f0262cSandi *
197f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
198f3f0262cSandi * are set.
19915fae107Sandi *
20015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20115fae107Sandi *
20215fae107Sandi * @param   string  $user    Username
20315fae107Sandi * @param   string  $pass    Cleartext Password
20415fae107Sandi * @param   bool    $sticky  Cookie should not expire
205f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
20615fae107Sandi * @return  bool             true on successful auth
207f3f0262cSandi */
208f112c2faSAndreas Gohrfunction auth_login($user, $pass, $sticky = false, $silent = false) {
209f3f0262cSandi    global $USERINFO;
210f3f0262cSandi    global $conf;
211f3f0262cSandi    global $lang;
212e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
213cd52f92dSchris    global $auth;
214585bf44eSChristopher Smith    /* @var Input $INPUT */
215585bf44eSChristopher Smith    global $INPUT;
216ab5d26daSAndreas Gohr
217beca106aSAdrian Lang    if(!$auth) return false;
218beca106aSAdrian Lang
219bbbd6568SAndreas Gohr    if(!empty($user)) {
220132bdbfeSandi        //usual login
2215e9e1054SAndreas Gohr        if(!empty($pass) && $auth->checkPass($user, $pass)) {
222132bdbfeSandi            // make logininfo globally available
223585bf44eSChristopher Smith            $INPUT->server->set('REMOTE_USER', $user);
22430d544a4SMichael Hamann            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
22504369c3eSMichael Hamann            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
226132bdbfeSandi            return true;
227f3f0262cSandi        } else {
228f3f0262cSandi            //invalid credentials - log off
229f8b1e4e7SAndreas Gohr            if(!$silent) {
230f8b1e4e7SAndreas Gohr                http_status(403, 'Login failed');
231f8b1e4e7SAndreas Gohr                msg($lang['badlogin'], -1);
232f8b1e4e7SAndreas Gohr            }
233f3f0262cSandi            auth_logoff();
234132bdbfeSandi            return false;
235f3f0262cSandi        }
236f3f0262cSandi    } else {
237132bdbfeSandi        // read cookie information
238*24870174SAndreas Gohr        [$user, $sticky, $pass] = auth_getCookie();
239132bdbfeSandi        if($user && $pass) {
240132bdbfeSandi            // we got a cookie - see if we can trust it
241fa7c70ffSAdrian Lang
242fa7c70ffSAdrian Lang            // get session info
2430058ae75SDamien Regad            if (isset($_SESSION[DOKU_COOKIE])) {
244fa7c70ffSAdrian Lang                $session = $_SESSION[DOKU_COOKIE]['auth'];
245132bdbfeSandi                if (isset($session) &&
2467172dbc0SAndreas Gohr                    $auth->useSessionCache($user) &&
2474c989037SChris Smith                    ($session['time'] >= time() - $conf['auth_security_timeout']) &&
248132bdbfeSandi                    ($session['user'] == $user) &&
249234ce57eSAndreas Gohr                    ($session['pass'] == sha1($pass)) && //still crypted
250ab5d26daSAndreas Gohr                    ($session['buid'] == auth_browseruid())
251ab5d26daSAndreas Gohr                ) {
252234ce57eSAndreas Gohr
253132bdbfeSandi                    // he has session, cookie and browser right - let him in
254585bf44eSChristopher Smith                    $INPUT->server->set('REMOTE_USER', $user);
255132bdbfeSandi                    $USERINFO = $session['info']; //FIXME move all references to session
256132bdbfeSandi                    return true;
257132bdbfeSandi                }
2580058ae75SDamien Regad            }
259f112c2faSAndreas Gohr            // no we don't trust it yet - recheck pass but silent
26030d544a4SMichael Hamann            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
26104369c3eSMichael Hamann            $pass   = auth_decrypt($pass, $secret);
262f112c2faSAndreas Gohr            return auth_login($user, $pass, $sticky, true);
263132bdbfeSandi        }
264132bdbfeSandi    }
265f3f0262cSandi    //just to be sure
266883179a4SAndreas Gohr    auth_logoff(true);
267132bdbfeSandi    return false;
268f3f0262cSandi}
269132bdbfeSandi
270132bdbfeSandi/**
271136ce040Sandi * Builds a pseudo UID from browser and IP data
272132bdbfeSandi *
273132bdbfeSandi * This is neither unique nor unfakable - still it adds some
274136ce040Sandi * security. Using the first part of the IP makes sure
27580b4f376SAndreas Gohr * proxy farms like AOLs are still okay.
27615fae107Sandi *
27715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
27815fae107Sandi *
279b13c0e1aSAdaKaleh * @return  string  a SHA256 sum of various browser headers
280132bdbfeSandi */
281132bdbfeSandifunction auth_browseruid() {
282585bf44eSChristopher Smith    /* @var Input $INPUT */
283585bf44eSChristopher Smith    global $INPUT;
284585bf44eSChristopher Smith
2852f9daf16SAndreas Gohr    $ip = clientIP(true);
286b13c0e1aSAdaKaleh    // convert IP string to packed binary representation
287b13c0e1aSAdaKaleh    $pip = inet_pton($ip);
288b7c67f83SAndreas Gohr
289b7c67f83SAndreas Gohr    $uid = implode("\n", [
290b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_USER_AGENT'),
291b7c67f83SAndreas Gohr        $INPUT->server->str('HTTP_ACCEPT_LANGUAGE'),
292b7c67f83SAndreas Gohr        substr($pip, 0, strlen($pip) / 2), // use half of the IP address (works for both IPv4 and IPv6)
293b7c67f83SAndreas Gohr    ]);
294b13c0e1aSAdaKaleh    return hash('sha256', $uid);
295132bdbfeSandi}
296132bdbfeSandi
297132bdbfeSandi/**
298132bdbfeSandi * Creates a random key to encrypt the password in cookies
29915fae107Sandi *
30015fae107Sandi * This function tries to read the password for encrypting
30198407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
30215fae107Sandi * if no such file is found a random key is created and
30315fae107Sandi * and stored in this file.
30415fae107Sandi *
30515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30642ea7f44SGerrit Uitslag *
30732ed2b36SAndreas Gohr * @param   bool $addsession if true, the sessionid is added to the salt
30830d544a4SMichael Hamann * @param   bool $secure     if security is more important than keeping the old value
30915fae107Sandi * @return  string
310132bdbfeSandi */
31130d544a4SMichael Hamannfunction auth_cookiesalt($addsession = false, $secure = false) {
312a1fe3c9cSMichael Große    if (defined('SIMPLE_TEST')) {
313fe745becSMichael Große        return 'test';
314a1fe3c9cSMichael Große    }
315132bdbfeSandi    global $conf;
31698407a7aSandi    $file = $conf['metadir'].'/_htcookiesalt';
31730d544a4SMichael Hamann    if ($secure || !file_exists($file)) {
31830d544a4SMichael Hamann        $file = $conf['metadir'].'/_htcookiesalt2';
31930d544a4SMichael Hamann    }
320132bdbfeSandi    $salt = io_readFile($file);
321132bdbfeSandi    if(empty($salt)) {
32230d544a4SMichael Hamann        $salt = bin2hex(auth_randombytes(64));
323132bdbfeSandi        io_saveFile($file, $salt);
324132bdbfeSandi    }
32532ed2b36SAndreas Gohr    if($addsession) {
32632ed2b36SAndreas Gohr        $salt .= session_id();
32732ed2b36SAndreas Gohr    }
328132bdbfeSandi    return $salt;
329f3f0262cSandi}
330f3f0262cSandi
331f3f0262cSandi/**
3327a33d2f8SNiklas Keller * Return cryptographically secure random bytes.
333483b6238SMichael Hamann *
3347a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
33542ea7f44SGerrit Uitslag *
3367a33d2f8SNiklas Keller * @param int $length number of bytes
3377a33d2f8SNiklas Keller * @return string cryptographically secure random bytes
338483b6238SMichael Hamann */
339483b6238SMichael Hamannfunction auth_randombytes($length) {
3407a33d2f8SNiklas Keller    return random_bytes($length);
341483b6238SMichael Hamann}
342483b6238SMichael Hamann
343483b6238SMichael Hamann/**
3447a33d2f8SNiklas Keller * Cryptographically secure random number generator.
345483b6238SMichael Hamann *
3467a33d2f8SNiklas Keller * @author Niklas Keller <me@kelunik.com>
34742ea7f44SGerrit Uitslag *
348483b6238SMichael Hamann * @param int $min
349483b6238SMichael Hamann * @param int $max
350483b6238SMichael Hamann * @return int
351483b6238SMichael Hamann */
352483b6238SMichael Hamannfunction auth_random($min, $max) {
3537a33d2f8SNiklas Keller    return random_int($min, $max);
354483b6238SMichael Hamann}
355483b6238SMichael Hamann
356483b6238SMichael Hamann/**
35704369c3eSMichael Hamann * Encrypt data using the given secret using AES
35804369c3eSMichael Hamann *
35904369c3eSMichael Hamann * The mode is CBC with a random initialization vector, the key is derived
36004369c3eSMichael Hamann * using pbkdf2.
36104369c3eSMichael Hamann *
36204369c3eSMichael Hamann * @param string $data   The data that shall be encrypted
36304369c3eSMichael Hamann * @param string $secret The secret/password that shall be used
36404369c3eSMichael Hamann * @return string The ciphertext
36504369c3eSMichael Hamann */
36604369c3eSMichael Hamannfunction auth_encrypt($data, $secret) {
36704369c3eSMichael Hamann    $iv     = auth_randombytes(16);
368*24870174SAndreas Gohr    $cipher = new AES();
36904369c3eSMichael Hamann    $cipher->setPassword($secret);
37004369c3eSMichael Hamann
3717b650cefSMichael Hamann    /*
3727b650cefSMichael Hamann    this uses the encrypted IV as IV as suggested in
3737b650cefSMichael Hamann    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
3747b650cefSMichael Hamann    for unique but necessarily random IVs. The resulting ciphertext is
3757b650cefSMichael Hamann    compatible to ciphertext that was created using a "normal" IV.
3767b650cefSMichael Hamann    */
37704369c3eSMichael Hamann    return $cipher->encrypt($iv.$data);
37804369c3eSMichael Hamann}
37904369c3eSMichael Hamann
38004369c3eSMichael Hamann/**
38104369c3eSMichael Hamann * Decrypt the given AES ciphertext
38204369c3eSMichael Hamann *
38304369c3eSMichael Hamann * The mode is CBC, the key is derived using pbkdf2
38404369c3eSMichael Hamann *
38504369c3eSMichael Hamann * @param string $ciphertext The encrypted data
38604369c3eSMichael Hamann * @param string $secret     The secret/password that shall be used
38704369c3eSMichael Hamann * @return string The decrypted data
38804369c3eSMichael Hamann */
38904369c3eSMichael Hamannfunction auth_decrypt($ciphertext, $secret) {
3907b650cefSMichael Hamann    $iv     = substr($ciphertext, 0, 16);
391*24870174SAndreas Gohr    $cipher = new AES();
39204369c3eSMichael Hamann    $cipher->setPassword($secret);
3937b650cefSMichael Hamann    $cipher->setIV($iv);
39404369c3eSMichael Hamann
3957b650cefSMichael Hamann    return $cipher->decrypt(substr($ciphertext, 16));
39604369c3eSMichael Hamann}
39704369c3eSMichael Hamann
39804369c3eSMichael Hamann/**
399883179a4SAndreas Gohr * Log out the current user
400883179a4SAndreas Gohr *
401f3f0262cSandi * This clears all authentication data and thus log the user
402883179a4SAndreas Gohr * off. It also clears session data.
40315fae107Sandi *
40415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40542ea7f44SGerrit Uitslag *
406883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
407f3f0262cSandi */
408883179a4SAndreas Gohrfunction auth_logoff($keepbc = false) {
409f3f0262cSandi    global $conf;
410f3f0262cSandi    global $USERINFO;
411e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
4125298a619SAndreas Gohr    global $auth;
413585bf44eSChristopher Smith    /* @var Input $INPUT */
414585bf44eSChristopher Smith    global $INPUT;
41537065e65Sandi
416d4869846SAndreas Gohr    // make sure the session is writable (it usually is)
417e9621d07SAndreas Gohr    @session_start();
418e9621d07SAndreas Gohr
419e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
420e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
421e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
422e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
423e71ce681SAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
424e71ce681SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
425883179a4SAndreas Gohr    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
426e16eccb7SGuy Brand        unset($_SESSION[DOKU_COOKIE]['bc']);
427585bf44eSChristopher Smith    $INPUT->server->remove('REMOTE_USER');
428132bdbfeSandi    $USERINFO = null; //FIXME
429f5c6743cSAndreas Gohr
43073ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
431bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, '', [
432bf8392ebSAndreas Gohr        'expires' => time() - 600000,
433bf8392ebSAndreas Gohr        'path' => $cookieDir,
434bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
435bf8392ebSAndreas Gohr        'httponly' => true,
436486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
437bf8392ebSAndreas Gohr    ]);
4385298a619SAndreas Gohr
439880f62faSAndreas Gohr    if($auth) $auth->logOff();
440f3f0262cSandi}
441f3f0262cSandi
442f3f0262cSandi/**
443f8cc712eSAndreas Gohr * Check if a user is a manager
444f8cc712eSAndreas Gohr *
445f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
446f8cc712eSAndreas Gohr * user.
447f8cc712eSAndreas Gohr *
448f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
449f8cc712eSAndreas Gohr *
450ab5d26daSAndreas Gohr * @param string $user Username
451ab5d26daSAndreas Gohr * @param array $groups List of groups the user is in
452ab5d26daSAndreas Gohr * @param bool $adminonly when true checks if user is admin
45310396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
454ab5d26daSAndreas Gohr * @return bool
45596348f27SAndreas Gohr * @see    auth_isadmin
45696348f27SAndreas Gohr *
45796348f27SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
458f8cc712eSAndreas Gohr */
45996348f27SAndreas Gohrfunction auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
460f8cc712eSAndreas Gohr    global $conf;
461f8cc712eSAndreas Gohr    global $USERINFO;
462e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
463d752aedeSAndreas Gohr    global $auth;
464585bf44eSChristopher Smith    /* @var Input $INPUT */
465585bf44eSChristopher Smith    global $INPUT;
466585bf44eSChristopher Smith
467f8cc712eSAndreas Gohr
468beca106aSAdrian Lang    if(!$auth) return false;
469c66972f2SAdrian Lang    if(is_null($user)) {
470585bf44eSChristopher Smith        if(!$INPUT->server->has('REMOTE_USER')) {
471c66972f2SAdrian Lang            return false;
472c66972f2SAdrian Lang        } else {
473585bf44eSChristopher Smith            $user = $INPUT->server->str('REMOTE_USER');
474c66972f2SAdrian Lang        }
475c66972f2SAdrian Lang    }
476d6dc956fSAndreas Gohr    if (is_null($groups)) {
4771525c228SAnna Dabrowska        // checking the logged in user, or another one?
4781525c228SAnna Dabrowska        if ($USERINFO && $user === $INPUT->server->str('REMOTE_USER')) {
4791525c228SAnna Dabrowska            $groups =  (array) $USERINFO['grps'];
48066b108d6SAnna Dabrowska        } else {
4816cf7b139SAndreas Gohr            $groups = $auth->getUserData($user);
4826cf7b139SAndreas Gohr            $groups = $groups ? $groups['grps'] : [];
48366b108d6SAnna Dabrowska        }
484e259aa79SAndreas Gohr    }
485e259aa79SAndreas Gohr
48696348f27SAndreas Gohr    // prefer cached result
48796348f27SAndreas Gohr    static $cache = [];
48810396f77SAndreas Gohr    $cachekey = serialize([$user, $adminonly, $groups]);
48996348f27SAndreas Gohr    if (!isset($cache[$cachekey]) || $recache) {
490d6dc956fSAndreas Gohr        // check superuser match
49196348f27SAndreas Gohr        $ok = auth_isMember($conf['superuser'], $user, $groups);
49200ce12daSChris Smith
49396348f27SAndreas Gohr        // check managers
49496348f27SAndreas Gohr        if (!$ok && !$adminonly) {
49596348f27SAndreas Gohr            $ok = auth_isMember($conf['manager'], $user, $groups);
49696348f27SAndreas Gohr        }
49796348f27SAndreas Gohr
49896348f27SAndreas Gohr        $cache[$cachekey] = $ok;
49996348f27SAndreas Gohr    }
50096348f27SAndreas Gohr
50196348f27SAndreas Gohr    return $cache[$cachekey];
502f8cc712eSAndreas Gohr}
503f8cc712eSAndreas Gohr
504f8cc712eSAndreas Gohr/**
505f8cc712eSAndreas Gohr * Check if a user is admin
506f8cc712eSAndreas Gohr *
507f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
508f8cc712eSAndreas Gohr *
509f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
510f8cc712eSAndreas Gohr *
51196348f27SAndreas Gohr * @param string $user Username
51296348f27SAndreas Gohr * @param array $groups List of groups the user is in
51310396f77SAndreas Gohr * @param bool $recache set to true to refresh the cache
51496348f27SAndreas Gohr * @return bool
515f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
516ab5d26daSAndreas Gohr * @see auth_ismanager()
51742ea7f44SGerrit Uitslag *
518f8cc712eSAndreas Gohr */
51996348f27SAndreas Gohrfunction auth_isadmin($user = null, $groups = null, $recache=false) {
52096348f27SAndreas Gohr    return auth_ismanager($user, $groups, true, $recache);
521f8cc712eSAndreas Gohr}
522f8cc712eSAndreas Gohr
523d6dc956fSAndreas Gohr/**
524d6dc956fSAndreas Gohr * Match a user and his groups against a comma separated list of
525d6dc956fSAndreas Gohr * users and groups to determine membership status
526d6dc956fSAndreas Gohr *
527d6dc956fSAndreas Gohr * Note: all input should NOT be nameencoded.
528d6dc956fSAndreas Gohr *
52942ea7f44SGerrit Uitslag * @param string $memberlist commaseparated list of allowed users and groups
53042ea7f44SGerrit Uitslag * @param string $user       user to match against
53142ea7f44SGerrit Uitslag * @param array  $groups     groups the user is member of
5325446f3ffSDominik Eckelmann * @return bool       true for membership acknowledged
533d6dc956fSAndreas Gohr */
534d6dc956fSAndreas Gohrfunction auth_isMember($memberlist, $user, array $groups) {
535e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
536d6dc956fSAndreas Gohr    global $auth;
537d6dc956fSAndreas Gohr    if(!$auth) return false;
538d6dc956fSAndreas Gohr
539d6dc956fSAndreas Gohr    // clean user and groups
5404f56ecbfSAdrian Lang    if(!$auth->isCaseSensitive()) {
541*24870174SAndreas Gohr        $user   = PhpString::strtolower($user);
542*24870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
543d6dc956fSAndreas Gohr    }
544d6dc956fSAndreas Gohr    $user   = $auth->cleanUser($user);
545*24870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
546d6dc956fSAndreas Gohr
547d6dc956fSAndreas Gohr    // extract the memberlist
548d6dc956fSAndreas Gohr    $members = explode(',', $memberlist);
549d6dc956fSAndreas Gohr    $members = array_map('trim', $members);
550d6dc956fSAndreas Gohr    $members = array_unique($members);
551d6dc956fSAndreas Gohr    $members = array_filter($members);
552d6dc956fSAndreas Gohr
553d6dc956fSAndreas Gohr    // compare cleaned values
554d6dc956fSAndreas Gohr    foreach($members as $member) {
555e5204a12SJurgen Hart        if($member == '@ALL' ) return true;
556*24870174SAndreas Gohr        if(!$auth->isCaseSensitive()) $member = PhpString::strtolower($member);
557d6dc956fSAndreas Gohr        if($member[0] == '@') {
558d6dc956fSAndreas Gohr            $member = $auth->cleanGroup(substr($member, 1));
559d6dc956fSAndreas Gohr            if(in_array($member, $groups)) return true;
560d6dc956fSAndreas Gohr        } else {
561d6dc956fSAndreas Gohr            $member = $auth->cleanUser($member);
562d6dc956fSAndreas Gohr            if($member == $user) return true;
563d6dc956fSAndreas Gohr        }
564d6dc956fSAndreas Gohr    }
565d6dc956fSAndreas Gohr
566d6dc956fSAndreas Gohr    // still here? not a member!
567d6dc956fSAndreas Gohr    return false;
568d6dc956fSAndreas Gohr}
569d6dc956fSAndreas Gohr
570f8cc712eSAndreas Gohr/**
57115fae107Sandi * Convinience function for auth_aclcheck()
57215fae107Sandi *
57315fae107Sandi * This checks the permissions for the current user
57415fae107Sandi *
57515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57615fae107Sandi *
5771698b983Smichael * @param  string  $id  page ID (needs to be resolved and cleaned)
57815fae107Sandi * @return int          permission level
579f3f0262cSandi */
580f3f0262cSandifunction auth_quickaclcheck($id) {
581f3f0262cSandi    global $conf;
582f3f0262cSandi    global $USERINFO;
583585bf44eSChristopher Smith    /* @var Input $INPUT */
584585bf44eSChristopher Smith    global $INPUT;
585f3f0262cSandi    # if no ACL is used always return upload rights
586f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
587*24870174SAndreas Gohr    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : []);
588f3f0262cSandi}
589f3f0262cSandi
590f3f0262cSandi/**
591c17acc9fSAndreas Gohr * Returns the maximum rights a user has for the given ID or its namespace
59215fae107Sandi *
59315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59442ea7f44SGerrit Uitslag *
595c17acc9fSAndreas Gohr * @triggers AUTH_ACL_CHECK
5961698b983Smichael * @param  string       $id     page ID (needs to be resolved and cleaned)
59715fae107Sandi * @param  string       $user   Username
5983272d797SAndreas Gohr * @param  array|null   $groups Array of groups the user is in
59915fae107Sandi * @return int             permission level
600f3f0262cSandi */
601f3f0262cSandifunction auth_aclcheck($id, $user, $groups) {
602*24870174SAndreas Gohr    $data = [
603bf8f8509SAndreas Gohr        'id'     => $id ?? '',
604c17acc9fSAndreas Gohr        'user'   => $user,
605c17acc9fSAndreas Gohr        'groups' => $groups
606*24870174SAndreas Gohr    ];
607c17acc9fSAndreas Gohr
608cbb44eabSAndreas Gohr    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
609c17acc9fSAndreas Gohr}
610c17acc9fSAndreas Gohr
611c17acc9fSAndreas Gohr/**
612c17acc9fSAndreas Gohr * default ACL check method
613c17acc9fSAndreas Gohr *
614c17acc9fSAndreas Gohr * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
615c17acc9fSAndreas Gohr *
616c17acc9fSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
61742ea7f44SGerrit Uitslag *
618c17acc9fSAndreas Gohr * @param  array $data event data
619c17acc9fSAndreas Gohr * @return int   permission level
620c17acc9fSAndreas Gohr */
621c17acc9fSAndreas Gohrfunction auth_aclcheck_cb($data) {
622c17acc9fSAndreas Gohr    $id     =& $data['id'];
623c17acc9fSAndreas Gohr    $user   =& $data['user'];
624c17acc9fSAndreas Gohr    $groups =& $data['groups'];
625c17acc9fSAndreas Gohr
626f3f0262cSandi    global $conf;
627f3f0262cSandi    global $AUTH_ACL;
628e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
629d752aedeSAndreas Gohr    global $auth;
630f3f0262cSandi
63185d03f68SAndreas Gohr    // if no ACL is used always return upload rights
632f3f0262cSandi    if(!$conf['useacl']) return AUTH_UPLOAD;
633beca106aSAdrian Lang    if(!$auth) return AUTH_NONE;
634bf8f8509SAndreas Gohr    if(!is_array($AUTH_ACL)) return AUTH_NONE;
635f3f0262cSandi
636074cf26bSandi    //make sure groups is an array
637*24870174SAndreas Gohr    if(!is_array($groups)) $groups = [];
638074cf26bSandi
63985d03f68SAndreas Gohr    //if user is superuser or in superusergroup return 255 (acl_admin)
640ab5d26daSAndreas Gohr    if(auth_isadmin($user, $groups)) {
641ab5d26daSAndreas Gohr        return AUTH_ADMIN;
642ab5d26daSAndreas Gohr    }
64385d03f68SAndreas Gohr
644eb3ce0d5SKazutaka Miyasaka    if(!$auth->isCaseSensitive()) {
645*24870174SAndreas Gohr        $user   = PhpString::strtolower($user);
646*24870174SAndreas Gohr        $groups = array_map([PhpString::class, 'strtolower'], $groups);
647eb3ce0d5SKazutaka Miyasaka    }
64837ff2261SSascha Klopp    $user   = auth_nameencode($auth->cleanUser($user));
649*24870174SAndreas Gohr    $groups = array_map([$auth, 'cleanGroup'], $groups);
65085d03f68SAndreas Gohr
6516c2bb100SAndreas Gohr    //prepend groups with @ and nameencode
65237ff2261SSascha Klopp    foreach($groups as &$group) {
65337ff2261SSascha Klopp        $group = '@'.auth_nameencode($group);
65410a76f6fSfrank    }
65510a76f6fSfrank
656f3f0262cSandi    $ns   = getNS($id);
657f3f0262cSandi    $perm = -1;
658f3f0262cSandi
659f3f0262cSandi    //add ALL group
660f3f0262cSandi    $groups[] = '@ALL';
66137ff2261SSascha Klopp
662f3f0262cSandi    //add User
66334aeb4afSAndreas Gohr    if($user) $groups[] = $user;
664f3f0262cSandi
665f3f0262cSandi    //check exact match first
66621c3090aSChristopher Smith    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
667f3f0262cSandi    if(count($matches)) {
668f3f0262cSandi        foreach($matches as $match) {
669f3f0262cSandi            $match = preg_replace('/#.*$/', '', $match); //ignore comments
67021c3090aSChristopher Smith            $acl   = preg_split('/[ \t]+/', $match);
671eb3ce0d5SKazutaka Miyasaka            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
672*24870174SAndreas Gohr                $acl[1] = PhpString::strtolower($acl[1]);
673eb3ce0d5SKazutaka Miyasaka            }
67448d7b7a6SDominik Eckelmann            if(!in_array($acl[1], $groups)) {
67548d7b7a6SDominik Eckelmann                continue;
67648d7b7a6SDominik Eckelmann            }
6778ef6b7caSandi            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
678f3f0262cSandi            if($acl[2] > $perm) {
679f3f0262cSandi                $perm = $acl[2];
680f3f0262cSandi            }
681f3f0262cSandi        }
682f3f0262cSandi        if($perm > -1) {
683f3f0262cSandi            //we had a match - return it
684def492a2SGuillaume Turri            return (int) $perm;
685f3f0262cSandi        }
686f3f0262cSandi    }
687f3f0262cSandi
688f3f0262cSandi    //still here? do the namespace checks
689f3f0262cSandi    if($ns) {
6903e304b55SMichael Hamann        $path = $ns.':*';
691f3f0262cSandi    } else {
6923e304b55SMichael Hamann        $path = '*'; //root document
693f3f0262cSandi    }
694f3f0262cSandi
695f3f0262cSandi    do {
69621c3090aSChristopher Smith        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
697f3f0262cSandi        if(count($matches)) {
698f3f0262cSandi            foreach($matches as $match) {
699f3f0262cSandi                $match = preg_replace('/#.*$/', '', $match); //ignore comments
70021c3090aSChristopher Smith                $acl   = preg_split('/[ \t]+/', $match);
701eb3ce0d5SKazutaka Miyasaka                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
702*24870174SAndreas Gohr                    $acl[1] = PhpString::strtolower($acl[1]);
703eb3ce0d5SKazutaka Miyasaka                }
70448d7b7a6SDominik Eckelmann                if(!in_array($acl[1], $groups)) {
70548d7b7a6SDominik Eckelmann                    continue;
70648d7b7a6SDominik Eckelmann                }
7078ef6b7caSandi                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
708f3f0262cSandi                if($acl[2] > $perm) {
709f3f0262cSandi                    $perm = $acl[2];
710f3f0262cSandi                }
711f3f0262cSandi            }
712f3f0262cSandi            //we had a match - return it
71348d7b7a6SDominik Eckelmann            if($perm != -1) {
714def492a2SGuillaume Turri                return (int) $perm;
715f3f0262cSandi            }
71648d7b7a6SDominik Eckelmann        }
717f3f0262cSandi        //get next higher namespace
718f3f0262cSandi        $ns = getNS($ns);
719f3f0262cSandi
7203e304b55SMichael Hamann        if($path != '*') {
7213e304b55SMichael Hamann            $path = $ns.':*';
7223e304b55SMichael Hamann            if($path == ':*') $path = '*';
723f3f0262cSandi        } else {
724f3f0262cSandi            //we did this already
725f3f0262cSandi            //looks like there is something wrong with the ACL
726f3f0262cSandi            //break here
727d5ce66f6SAndreas Gohr            msg('No ACL setup yet! Denying access to everyone.');
728d5ce66f6SAndreas Gohr            return AUTH_NONE;
729f3f0262cSandi        }
730f3f0262cSandi    } while(1); //this should never loop endless
731ab5d26daSAndreas Gohr    return AUTH_NONE;
732f3f0262cSandi}
733f3f0262cSandi
734f3f0262cSandi/**
7356c2bb100SAndreas Gohr * Encode ASCII special chars
7366c2bb100SAndreas Gohr *
7376c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
7386c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
7396c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
7406c2bb100SAndreas Gohr * urlencoding!).
7416c2bb100SAndreas Gohr *
7426c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
7436c2bb100SAndreas Gohr *
7446c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
7456c2bb100SAndreas Gohr * @see rawurldecode()
74642ea7f44SGerrit Uitslag *
74742ea7f44SGerrit Uitslag * @param string $name
74842ea7f44SGerrit Uitslag * @param bool $skip_group
74942ea7f44SGerrit Uitslag * @return string
7506c2bb100SAndreas Gohr */
751e838fc2eSAndreas Gohrfunction auth_nameencode($name, $skip_group = false) {
752a424cd8eSchris    global $cache_authname;
753a424cd8eSchris    $cache =& $cache_authname;
75431784267SAndreas Gohr    $name  = (string) $name;
755a424cd8eSchris
75680601d26SAndreas Gohr    // never encode wildcard FS#1955
75780601d26SAndreas Gohr    if($name == '%USER%') return $name;
758b78bf706Sromain    if($name == '%GROUP%') return $name;
75980601d26SAndreas Gohr
760a424cd8eSchris    if(!isset($cache[$name][$skip_group])) {
7612401f18dSSyntaxseed        if($skip_group && $name[0] == '@') {
76230f6faf0SChristopher Smith            $cache[$name][$skip_group] = '@'.preg_replace_callback(
76330f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
76430f6faf0SChristopher Smith                'auth_nameencode_callback', substr($name, 1)
765ab5d26daSAndreas Gohr            );
766e838fc2eSAndreas Gohr        } else {
76730f6faf0SChristopher Smith            $cache[$name][$skip_group] = preg_replace_callback(
76830f6faf0SChristopher Smith                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
76930f6faf0SChristopher Smith                'auth_nameencode_callback', $name
770ab5d26daSAndreas Gohr            );
771e838fc2eSAndreas Gohr        }
7726c2bb100SAndreas Gohr    }
7736c2bb100SAndreas Gohr
774a424cd8eSchris    return $cache[$name][$skip_group];
775a424cd8eSchris}
776a424cd8eSchris
77704d68ae4SGerrit Uitslag/**
77804d68ae4SGerrit Uitslag * callback encodes the matches
77904d68ae4SGerrit Uitslag *
78004d68ae4SGerrit Uitslag * @param array $matches first complete match, next matching subpatterms
78104d68ae4SGerrit Uitslag * @return string
78204d68ae4SGerrit Uitslag */
78330f6faf0SChristopher Smithfunction auth_nameencode_callback($matches) {
78430f6faf0SChristopher Smith    return '%'.dechex(ord(substr($matches[1],-1)));
78530f6faf0SChristopher Smith}
78630f6faf0SChristopher Smith
7876c2bb100SAndreas Gohr/**
788f3f0262cSandi * Create a pronouncable password
789f3f0262cSandi *
7908a285f7fSAndreas Gohr * The $foruser variable might be used by plugins to run additional password
7918a285f7fSAndreas Gohr * policy checks, but is not used by the default implementation
7928a285f7fSAndreas Gohr *
79315fae107Sandi * @author   Andreas Gohr <andi@splitbrain.org>
79415fae107Sandi * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
7958a285f7fSAndreas Gohr * @triggers AUTH_PASSWORD_GENERATE
79615fae107Sandi *
7978a285f7fSAndreas Gohr * @param  string $foruser username for which the password is generated
79815fae107Sandi * @return string  pronouncable password
799f3f0262cSandi */
8008a285f7fSAndreas Gohrfunction auth_pwgen($foruser = '') {
801*24870174SAndreas Gohr    $data = [
802d628dcf3SAndreas Gohr        'password' => '',
803d628dcf3SAndreas Gohr        'foruser'  => $foruser
804*24870174SAndreas Gohr    ];
8058a285f7fSAndreas Gohr
806e1d9dcc8SAndreas Gohr    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
8078a285f7fSAndreas Gohr    if($evt->advise_before(true)) {
808f3f0262cSandi        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
809f3f0262cSandi        $v = 'aeiou'; //vowels
810f3f0262cSandi        $a = $c.$v; //both
811987c8d26SAndreas Gohr        $s = '!$%&?+*~#-_:.;,'; // specials
812f3f0262cSandi
813987c8d26SAndreas Gohr        //use thre syllables...
814987c8d26SAndreas Gohr        for($i = 0; $i < 3; $i++) {
815483b6238SMichael Hamann            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
816483b6238SMichael Hamann            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
817483b6238SMichael Hamann            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
818f3f0262cSandi        }
819987c8d26SAndreas Gohr        //... and add a nice number and special
82043f71e05Ssdavis80        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
8218a285f7fSAndreas Gohr    }
8228a285f7fSAndreas Gohr    $evt->advise_after();
823f3f0262cSandi
8248a285f7fSAndreas Gohr    return $data['password'];
825f3f0262cSandi}
826f3f0262cSandi
827f3f0262cSandi/**
828f3f0262cSandi * Sends a password to the given user
829f3f0262cSandi *
83015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
83142ea7f44SGerrit Uitslag *
832ab5d26daSAndreas Gohr * @param string $user Login name of the user
833ab5d26daSAndreas Gohr * @param string $password The new password in clear text
83415fae107Sandi * @return bool  true on success
835f3f0262cSandi */
836f3f0262cSandifunction auth_sendPassword($user, $password) {
837f3f0262cSandi    global $lang;
838e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
839cd52f92dSchris    global $auth;
840beca106aSAdrian Lang    if(!$auth) return false;
841cd52f92dSchris
842d752aedeSAndreas Gohr    $user     = $auth->cleanUser($user);
8432dc9e900SChristopher Smith    $userinfo = $auth->getUserData($user, $requireGroups = false);
844f3f0262cSandi
84587ddda95Sandi    if(!$userinfo['mail']) return false;
846f3f0262cSandi
847f3f0262cSandi    $text = rawLocale('password');
848*24870174SAndreas Gohr    $trep = [
849d7169d19SAndreas Gohr        'FULLNAME' => $userinfo['name'],
850d7169d19SAndreas Gohr        'LOGIN'    => $user,
851d7169d19SAndreas Gohr        'PASSWORD' => $password
852*24870174SAndreas Gohr    ];
853f3f0262cSandi
854d7169d19SAndreas Gohr    $mail = new Mailer();
855102cdbd7SLarsGit223    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
856d7169d19SAndreas Gohr    $mail->subject($lang['regpwmail']);
857d7169d19SAndreas Gohr    $mail->setBody($text, $trep);
858d7169d19SAndreas Gohr    return $mail->send();
859f3f0262cSandi}
860f3f0262cSandi
861f3f0262cSandi/**
86215fae107Sandi * Register a new user
863f3f0262cSandi *
86415fae107Sandi * This registers a new user - Data is read directly from $_POST
86515fae107Sandi *
86615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
86742ea7f44SGerrit Uitslag *
86815fae107Sandi * @return bool  true on success, false on any error
869f3f0262cSandi */
870f3f0262cSandifunction register() {
871f3f0262cSandi    global $lang;
872eb5d07e4Sjan    global $conf;
873e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
874cd52f92dSchris    global $auth;
87564273335SAndreas Gohr    global $INPUT;
876f3f0262cSandi
87764273335SAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
8783a48618aSAnika Henke    if(!actionOK('register')) return false;
879640145a5Sandi
88064273335SAndreas Gohr    // gather input
88164273335SAndreas Gohr    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
88264273335SAndreas Gohr    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
88364273335SAndreas Gohr    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
88464273335SAndreas Gohr    $pass     = $INPUT->post->str('pass');
88564273335SAndreas Gohr    $passchk  = $INPUT->post->str('passchk');
886d752aedeSAndreas Gohr
88764273335SAndreas Gohr    if(empty($login) || empty($fullname) || empty($email)) {
888f3f0262cSandi        msg($lang['regmissing'], -1);
889f3f0262cSandi        return false;
890f3f0262cSandi    }
891f3f0262cSandi
892cab2716aSmatthias.grimm    if($conf['autopasswd']) {
8938a285f7fSAndreas Gohr        $pass = auth_pwgen($login); // automatically generate password
89464273335SAndreas Gohr    } elseif(empty($pass) || empty($passchk)) {
895bf12ec81Sjan        msg($lang['regmissing'], -1); // complain about missing passwords
896cab2716aSmatthias.grimm        return false;
89764273335SAndreas Gohr    } elseif($pass != $passchk) {
898bf12ec81Sjan        msg($lang['regbadpass'], -1); // complain about misspelled passwords
899cab2716aSmatthias.grimm        return false;
900cab2716aSmatthias.grimm    }
901cab2716aSmatthias.grimm
902f3f0262cSandi    //check mail
90364273335SAndreas Gohr    if(!mail_isvalid($email)) {
904f3f0262cSandi        msg($lang['regbadmail'], -1);
905f3f0262cSandi        return false;
906f3f0262cSandi    }
907f3f0262cSandi
908f3f0262cSandi    //okay try to create the user
909*24870174SAndreas Gohr    if(!$auth->triggerUserMod('create', [$login, $pass, $fullname, $email])) {
910db9faf02SPatrick Brown        msg($lang['regfail'], -1);
911f3f0262cSandi        return false;
912f3f0262cSandi    }
913f3f0262cSandi
914790b7720SAndreas Gohr    // send notification about the new user
91575d66495SMichael Große    $subscription = new RegistrationSubscriptionSender();
91675d66495SMichael Große    $subscription->sendRegister($login, $fullname, $email);
91702a498e7Schris
918790b7720SAndreas Gohr    // are we done?
919cab2716aSmatthias.grimm    if(!$conf['autopasswd']) {
920cab2716aSmatthias.grimm        msg($lang['regsuccess2'], 1);
921cab2716aSmatthias.grimm        return true;
922cab2716aSmatthias.grimm    }
923cab2716aSmatthias.grimm
924790b7720SAndreas Gohr    // autogenerated password? then send password to user
92564273335SAndreas Gohr    if(auth_sendPassword($login, $pass)) {
926f3f0262cSandi        msg($lang['regsuccess'], 1);
927f3f0262cSandi        return true;
928f3f0262cSandi    } else {
929f3f0262cSandi        msg($lang['regmailfail'], -1);
930f3f0262cSandi        return false;
931f3f0262cSandi    }
932f3f0262cSandi}
933f3f0262cSandi
93410a76f6fSfrank/**
9358b06d178Schris * Update user profile
9368b06d178Schris *
9378b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
9388b06d178Schris */
9398b06d178Schrisfunction updateprofile() {
9408b06d178Schris    global $conf;
9418b06d178Schris    global $lang;
942e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
943cd52f92dSchris    global $auth;
944bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
945bcc94b2cSAndreas Gohr    global $INPUT;
9468b06d178Schris
947bcc94b2cSAndreas Gohr    if(!$INPUT->post->bool('save')) return false;
9481b2a85e8SAndreas Gohr    if(!checkSecurityToken()) return false;
9498b06d178Schris
9503a48618aSAnika Henke    if(!actionOK('profile')) {
9518b06d178Schris        msg($lang['profna'], -1);
9528b06d178Schris        return false;
9538b06d178Schris    }
9548b06d178Schris
955*24870174SAndreas Gohr    $changes         = [];
956bcc94b2cSAndreas Gohr    $changes['pass'] = $INPUT->post->str('newpass');
957bcc94b2cSAndreas Gohr    $changes['name'] = $INPUT->post->str('fullname');
958bcc94b2cSAndreas Gohr    $changes['mail'] = $INPUT->post->str('email');
959bcc94b2cSAndreas Gohr
960bcc94b2cSAndreas Gohr    // check misspelled passwords
961bcc94b2cSAndreas Gohr    if($changes['pass'] != $INPUT->post->str('passchk')) {
962bcc94b2cSAndreas Gohr        msg($lang['regbadpass'], -1);
9638b06d178Schris        return false;
9648b06d178Schris    }
9658b06d178Schris
9668b06d178Schris    // clean fullname and email
967bcc94b2cSAndreas Gohr    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
968bcc94b2cSAndreas Gohr    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
9698b06d178Schris
970bcc94b2cSAndreas Gohr    // no empty name and email (except the backend doesn't support them)
971bcc94b2cSAndreas Gohr    if((empty($changes['name']) && $auth->canDo('modName')) ||
972bcc94b2cSAndreas Gohr        (empty($changes['mail']) && $auth->canDo('modMail'))
973ab5d26daSAndreas Gohr    ) {
9748b06d178Schris        msg($lang['profnoempty'], -1);
9758b06d178Schris        return false;
9768b06d178Schris    }
977bcc94b2cSAndreas Gohr    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
9788b06d178Schris        msg($lang['regbadmail'], -1);
9798b06d178Schris        return false;
9808b06d178Schris    }
9818b06d178Schris
982bcc94b2cSAndreas Gohr    $changes = array_filter($changes);
9834c21b7eeSAndreas Gohr
984bcc94b2cSAndreas Gohr    // check for unavailable capabilities
985bcc94b2cSAndreas Gohr    if(!$auth->canDo('modName')) unset($changes['name']);
986bcc94b2cSAndreas Gohr    if(!$auth->canDo('modMail')) unset($changes['mail']);
987bcc94b2cSAndreas Gohr    if(!$auth->canDo('modPass')) unset($changes['pass']);
988bcc94b2cSAndreas Gohr
989bcc94b2cSAndreas Gohr    // anything to do?
990*24870174SAndreas Gohr    if($changes === []) {
9918b06d178Schris        msg($lang['profnochange'], -1);
9928b06d178Schris        return false;
9938b06d178Schris    }
9948b06d178Schris
9958b06d178Schris    if($conf['profileconfirm']) {
996585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
99771422fc8SChristopher Smith            msg($lang['badpassconfirm'], -1);
9988b06d178Schris            return false;
9998b06d178Schris        }
10008b06d178Schris    }
10018b06d178Schris
1002*24870174SAndreas Gohr    if(!$auth->triggerUserMod('modify', [$INPUT->server->str('REMOTE_USER'), &$changes])) {
1003db9faf02SPatrick Brown        msg($lang['proffail'], -1);
1004db9faf02SPatrick Brown        return false;
1005db9faf02SPatrick Brown    }
1006db9faf02SPatrick Brown
100732ed2b36SAndreas Gohr    if($changes['pass']) {
1008c276e9e8SMarcel Pennewiss        // update cookie and session with the changed data
1009*24870174SAndreas Gohr        [, $sticky, ] = auth_getCookie();
101004369c3eSMichael Hamann        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1011585bf44eSChristopher Smith        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
1012c276e9e8SMarcel Pennewiss    } else {
1013c276e9e8SMarcel Pennewiss        // make sure the session is writable
1014c276e9e8SMarcel Pennewiss        @session_start();
1015c276e9e8SMarcel Pennewiss        // invalidate session cache
1016c276e9e8SMarcel Pennewiss        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1017c276e9e8SMarcel Pennewiss        session_write_close();
101832ed2b36SAndreas Gohr    }
1019c276e9e8SMarcel Pennewiss
102025b2a98cSMichael Klier    return true;
1021a0b5b007SChris Smith}
1022ab5d26daSAndreas Gohr
102304d68ae4SGerrit Uitslag/**
102404d68ae4SGerrit Uitslag * Delete the current logged-in user
102504d68ae4SGerrit Uitslag *
102604d68ae4SGerrit Uitslag * @return bool true on success, false on any error
102704d68ae4SGerrit Uitslag */
10282a7abf2dSChristopher Smithfunction auth_deleteprofile(){
10292a7abf2dSChristopher Smith    global $conf;
10302a7abf2dSChristopher Smith    global $lang;
1031e1d9dcc8SAndreas Gohr    /* @var \dokuwiki\Extension\AuthPlugin $auth */
10322a7abf2dSChristopher Smith    global $auth;
10332a7abf2dSChristopher Smith    /* @var Input $INPUT */
10342a7abf2dSChristopher Smith    global $INPUT;
10352a7abf2dSChristopher Smith
10362a7abf2dSChristopher Smith    if(!$INPUT->post->bool('delete')) return false;
10372a7abf2dSChristopher Smith    if(!checkSecurityToken()) return false;
10382a7abf2dSChristopher Smith
10392a7abf2dSChristopher Smith    // action prevented or auth module disallows
10402a7abf2dSChristopher Smith    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
10412a7abf2dSChristopher Smith        msg($lang['profnodelete'], -1);
10422a7abf2dSChristopher Smith        return false;
10432a7abf2dSChristopher Smith    }
10442a7abf2dSChristopher Smith
10452a7abf2dSChristopher Smith    if(!$INPUT->post->bool('confirm_delete')){
10462a7abf2dSChristopher Smith        msg($lang['profconfdeletemissing'], -1);
10472a7abf2dSChristopher Smith        return false;
10482a7abf2dSChristopher Smith    }
10492a7abf2dSChristopher Smith
10502a7abf2dSChristopher Smith    if($conf['profileconfirm']) {
1051585bf44eSChristopher Smith        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
10522a7abf2dSChristopher Smith            msg($lang['badpassconfirm'], -1);
10532a7abf2dSChristopher Smith            return false;
10542a7abf2dSChristopher Smith        }
10552a7abf2dSChristopher Smith    }
10562a7abf2dSChristopher Smith
1057*24870174SAndreas Gohr    $deleted = [];
1058585bf44eSChristopher Smith    $deleted[] = $INPUT->server->str('REMOTE_USER');
1059*24870174SAndreas Gohr    if($auth->triggerUserMod('delete', [$deleted])) {
10602a7abf2dSChristopher Smith        // force and immediate logout including removing the sticky cookie
10612a7abf2dSChristopher Smith        auth_logoff();
10622a7abf2dSChristopher Smith        return true;
10632a7abf2dSChristopher Smith    }
10642a7abf2dSChristopher Smith
10652a7abf2dSChristopher Smith    return false;
10662a7abf2dSChristopher Smith}
10672a7abf2dSChristopher Smith
10688b06d178Schris/**
10698b06d178Schris * Send a  new password
10708b06d178Schris *
10711d5856cfSAndreas Gohr * This function handles both phases of the password reset:
10721d5856cfSAndreas Gohr *
10731d5856cfSAndreas Gohr *   - handling the first request of password reset
10741d5856cfSAndreas Gohr *   - validating the password reset auth token
10751d5856cfSAndreas Gohr *
10768b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
10778b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
10781d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10798b06d178Schris *
10808b06d178Schris * @return bool true on success, false on any error
10818b06d178Schris */
10828b06d178Schrisfunction act_resendpwd() {
10838b06d178Schris    global $lang;
10848b06d178Schris    global $conf;
1085e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1086cd52f92dSchris    global $auth;
1087bcc94b2cSAndreas Gohr    /* @var Input $INPUT */
1088bcc94b2cSAndreas Gohr    global $INPUT;
10898b06d178Schris
10903a48618aSAnika Henke    if(!actionOK('resendpwd')) {
10918b06d178Schris        msg($lang['resendna'], -1);
10928b06d178Schris        return false;
10938b06d178Schris    }
10948b06d178Schris
1095bcc94b2cSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
10968b06d178Schris
10971d5856cfSAndreas Gohr    if($token) {
1098cc204bbdSAndreas Gohr        // we're in token phase - get user info from token
10991d5856cfSAndreas Gohr
11002401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
110179e79377SAndreas Gohr        if(!file_exists($tfile)) {
11021d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1103bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11041d5856cfSAndreas Gohr            return false;
11051d5856cfSAndreas Gohr        }
11068a9735e3SAndreas Gohr        // token is only valid for 3 days
11078a9735e3SAndreas Gohr        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
11088a9735e3SAndreas Gohr            msg($lang['resendpwdbadauth'], -1);
1109bcc94b2cSAndreas Gohr            $INPUT->remove('pwauth');
11101d5856cfSAndreas Gohr            @unlink($tfile);
11118a9735e3SAndreas Gohr            return false;
11128a9735e3SAndreas Gohr        }
11138a9735e3SAndreas Gohr
11148b06d178Schris        $user     = io_readfile($tfile);
11152dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11168b06d178Schris        if(!$userinfo['mail']) {
11178b06d178Schris            msg($lang['resendpwdnouser'], -1);
11188b06d178Schris            return false;
11198b06d178Schris        }
11208b06d178Schris
1121cc204bbdSAndreas Gohr        if(!$conf['autopasswd']) { // we let the user choose a password
1122bcc94b2cSAndreas Gohr            $pass = $INPUT->str('pass');
1123bcc94b2cSAndreas Gohr
1124cc204bbdSAndreas Gohr            // password given correctly?
1125bcc94b2cSAndreas Gohr            if(!$pass) return false;
1126bcc94b2cSAndreas Gohr            if($pass != $INPUT->str('passchk')) {
1127451e1b4dSAndreas Gohr                msg($lang['regbadpass'], -1);
1128cc204bbdSAndreas Gohr                return false;
1129cc204bbdSAndreas Gohr            }
1130cc204bbdSAndreas Gohr
1131bcc94b2cSAndreas Gohr            // change it
1132*24870174SAndreas Gohr            if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1133db9faf02SPatrick Brown                msg($lang['proffail'], -1);
1134cc204bbdSAndreas Gohr                return false;
1135cc204bbdSAndreas Gohr            }
1136cc204bbdSAndreas Gohr
1137cc204bbdSAndreas Gohr        } else { // autogenerate the password and send by mail
1138cc204bbdSAndreas Gohr
11398a285f7fSAndreas Gohr            $pass = auth_pwgen($user);
1140*24870174SAndreas Gohr            if(!$auth->triggerUserMod('modify', [$user, ['pass' => $pass]])) {
1141db9faf02SPatrick Brown                msg($lang['proffail'], -1);
11428b06d178Schris                return false;
11438b06d178Schris            }
11448b06d178Schris
11458b06d178Schris            if(auth_sendPassword($user, $pass)) {
11468b06d178Schris                msg($lang['resendpwdsuccess'], 1);
11478b06d178Schris            } else {
11488b06d178Schris                msg($lang['regmailfail'], -1);
11498b06d178Schris            }
1150cc204bbdSAndreas Gohr        }
1151cc204bbdSAndreas Gohr
1152cc204bbdSAndreas Gohr        @unlink($tfile);
11538b06d178Schris        return true;
11541d5856cfSAndreas Gohr
11551d5856cfSAndreas Gohr    } else {
11561d5856cfSAndreas Gohr        // we're in request phase
11571d5856cfSAndreas Gohr
1158bcc94b2cSAndreas Gohr        if(!$INPUT->post->bool('save')) return false;
11591d5856cfSAndreas Gohr
1160bcc94b2cSAndreas Gohr        if(!$INPUT->post->str('login')) {
11611d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
11621d5856cfSAndreas Gohr            return false;
11631d5856cfSAndreas Gohr        } else {
1164bcc94b2cSAndreas Gohr            $user = trim($auth->cleanUser($INPUT->post->str('login')));
11651d5856cfSAndreas Gohr        }
11661d5856cfSAndreas Gohr
11672dc9e900SChristopher Smith        $userinfo = $auth->getUserData($user, $requireGroups = false);
11681d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
11691d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
11701d5856cfSAndreas Gohr            return false;
11711d5856cfSAndreas Gohr        }
11721d5856cfSAndreas Gohr
11731d5856cfSAndreas Gohr        // generate auth token
1174483b6238SMichael Hamann        $token = md5(auth_randombytes(16)); // random secret
11752401f18dSSyntaxseed        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1176*24870174SAndreas Gohr        $url   = wl('', ['do'=> 'resendpwd', 'pwauth'=> $token], true, '&');
11771d5856cfSAndreas Gohr
11781d5856cfSAndreas Gohr        io_saveFile($tfile, $user);
11791d5856cfSAndreas Gohr
11801d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
1181*24870174SAndreas Gohr        $trep = ['FULLNAME' => $userinfo['name'], 'LOGIN'    => $user, 'CONFIRM'  => $url];
11821d5856cfSAndreas Gohr
1183d7169d19SAndreas Gohr        $mail = new Mailer();
1184d7169d19SAndreas Gohr        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1185d7169d19SAndreas Gohr        $mail->subject($lang['regpwmail']);
1186d7169d19SAndreas Gohr        $mail->setBody($text, $trep);
1187d7169d19SAndreas Gohr        if($mail->send()) {
11881d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'], 1);
11891d5856cfSAndreas Gohr        } else {
11901d5856cfSAndreas Gohr            msg($lang['regmailfail'], -1);
11911d5856cfSAndreas Gohr        }
11921d5856cfSAndreas Gohr        return true;
11931d5856cfSAndreas Gohr    }
1194ab5d26daSAndreas Gohr    // never reached
11958b06d178Schris}
11968b06d178Schris
11978b06d178Schris/**
1198b0855b11Sandi * Encrypts a password using the given method and salt
1199b0855b11Sandi *
1200b0855b11Sandi * If the selected method needs a salt and none was given, a random one
1201b0855b11Sandi * is chosen.
1202b0855b11Sandi *
1203b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
120442ea7f44SGerrit Uitslag *
1205ab5d26daSAndreas Gohr * @param string $clear The clear text password
1206ab5d26daSAndreas Gohr * @param string $method The hashing method
1207ab5d26daSAndreas Gohr * @param string $salt A salt, null for random
1208b0855b11Sandi * @return  string  The crypted password
1209b0855b11Sandi */
1210577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear, $method = '', $salt = null) {
1211b0855b11Sandi    global $conf;
1212b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
121310a76f6fSfrank
12143a0a2d05SAndreas Gohr    $pass = new PassHash();
12153a0a2d05SAndreas Gohr    $call = 'hash_'.$method;
1216b0855b11Sandi
12173a0a2d05SAndreas Gohr    if(!method_exists($pass, $call)) {
1218b0855b11Sandi        msg("Unsupported crypt method $method", -1);
12193a0a2d05SAndreas Gohr        return false;
1220b0855b11Sandi    }
12213a0a2d05SAndreas Gohr
12223a0a2d05SAndreas Gohr    return $pass->$call($clear, $salt);
1223b0855b11Sandi}
1224b0855b11Sandi
1225b0855b11Sandi/**
1226b0855b11Sandi * Verifies a cleartext password against a crypted hash
1227b0855b11Sandi *
1228b0855b11Sandi * @author Andreas Gohr <andi@splitbrain.org>
122942ea7f44SGerrit Uitslag *
1230ab5d26daSAndreas Gohr * @param  string $clear The clear text password
1231ab5d26daSAndreas Gohr * @param  string $crypt The hash to compare with
1232ab5d26daSAndreas Gohr * @return bool true if both match
1233b0855b11Sandi */
1234b0855b11Sandifunction auth_verifyPassword($clear, $crypt) {
12353a0a2d05SAndreas Gohr    $pass = new PassHash();
12363a0a2d05SAndreas Gohr    return $pass->verify_hash($clear, $crypt);
1237b0855b11Sandi}
1238340756e4Sandi
1239a0b5b007SChris Smith/**
1240a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
1241a0b5b007SChris Smith *
1242a0b5b007SChris Smith * @param string  $user       username
1243a0b5b007SChris Smith * @param string  $pass       encrypted password
1244a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
1245ab5d26daSAndreas Gohr * @return bool
1246a0b5b007SChris Smith */
1247a0b5b007SChris Smithfunction auth_setCookie($user, $pass, $sticky) {
1248a0b5b007SChris Smith    global $conf;
1249e1d9dcc8SAndreas Gohr    /* @var AuthPlugin $auth */
1250a0b5b007SChris Smith    global $auth;
125179d00841SOliver Geisen    global $USERINFO;
1252a0b5b007SChris Smith
1253beca106aSAdrian Lang    if(!$auth) return false;
1254a0b5b007SChris Smith    $USERINFO = $auth->getUserData($user);
1255a0b5b007SChris Smith
1256a0b5b007SChris Smith    // set cookie
1257645c0a36SAndreas Gohr    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
125873ab87deSGabriel Birke    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1259c66972f2SAdrian Lang    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1260bf8392ebSAndreas Gohr    setcookie(DOKU_COOKIE, $cookie, [
1261bf8392ebSAndreas Gohr        'expires' => $time,
1262bf8392ebSAndreas Gohr        'path' => $cookieDir,
1263bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
1264bf8392ebSAndreas Gohr        'httponly' => true,
1265486f82fcSAndreas Gohr        'samesite' => $conf['samesitecookie'] ?: null, // null means browser default
1266bf8392ebSAndreas Gohr    ]);
126755a71a16SGerrit Uitslag
1268a0b5b007SChris Smith    // set session
1269a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1270234ce57eSAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1271a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1272a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1273a0b5b007SChris Smith    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1274ab5d26daSAndreas Gohr
1275ab5d26daSAndreas Gohr    return true;
1276a0b5b007SChris Smith}
1277a0b5b007SChris Smith
1278645c0a36SAndreas Gohr/**
1279645c0a36SAndreas Gohr * Returns the user, (encrypted) password and sticky bit from cookie
1280645c0a36SAndreas Gohr *
1281645c0a36SAndreas Gohr * @returns array
1282645c0a36SAndreas Gohr */
1283645c0a36SAndreas Gohrfunction auth_getCookie() {
1284c66972f2SAdrian Lang    if(!isset($_COOKIE[DOKU_COOKIE])) {
1285*24870174SAndreas Gohr        return [null, null, null];
1286c66972f2SAdrian Lang    }
1287*24870174SAndreas Gohr    [$user, $sticky, $pass] = sexplode('|', $_COOKIE[DOKU_COOKIE], 3, '');
1288645c0a36SAndreas Gohr    $sticky = (bool) $sticky;
1289645c0a36SAndreas Gohr    $pass   = base64_decode($pass);
1290645c0a36SAndreas Gohr    $user   = base64_decode($user);
1291*24870174SAndreas Gohr    return [$user, $sticky, $pass];
1292645c0a36SAndreas Gohr}
1293645c0a36SAndreas Gohr
1294e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1295