1<?php
2/**
3 * Authentication library
4 *
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
7 *
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author     Andreas Gohr <andi@splitbrain.org>
10 */
11
12use dokuwiki\Extension\AuthPlugin;
13use dokuwiki\Extension\Event;
14use dokuwiki\Extension\PluginController;
15use dokuwiki\PassHash;
16use dokuwiki\Subscriptions\RegistrationSubscriptionSender;
17
18/**
19 * Initialize the auth system.
20 *
21 * This function is automatically called at the end of init.php
22 *
23 * This used to be the main() of the auth.php
24 *
25 * @todo backend loading maybe should be handled by the class autoloader
26 * @todo maybe split into multiple functions at the XXX marked positions
27 * @triggers AUTH_LOGIN_CHECK
28 * @return bool
29 */
30function auth_setup() {
31    global $conf;
32    /* @var AuthPlugin $auth */
33    global $auth;
34    /* @var Input $INPUT */
35    global $INPUT;
36    global $AUTH_ACL;
37    global $lang;
38    /* @var PluginController $plugin_controller */
39    global $plugin_controller;
40    $AUTH_ACL = array();
41
42    if(!$conf['useacl']) return false;
43
44    // try to load auth backend from plugins
45    foreach ($plugin_controller->getList('auth') as $plugin) {
46        if ($conf['authtype'] === $plugin) {
47            $auth = $plugin_controller->load('auth', $plugin);
48            break;
49        }
50    }
51
52    if(!isset($auth) || !$auth){
53        msg($lang['authtempfail'], -1);
54        return false;
55    }
56
57    if ($auth->success == false) {
58        // degrade to unauthenticated user
59        unset($auth);
60        auth_logoff();
61        msg($lang['authtempfail'], -1);
62        return false;
63    }
64
65    // do the login either by cookie or provided credentials XXX
66    $INPUT->set('http_credentials', false);
67    if(!$conf['rememberme']) $INPUT->set('r', false);
68
69    // handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
70    // the one presented at
71    // http://www.besthostratings.com/articles/http-auth-php-cgi.html is used
72    // for enabling HTTP authentication with CGI/SuExec)
73    if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
74        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
75    // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
76    if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
77        list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
78            explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
79    }
80
81    // if no credentials were given try to use HTTP auth (for SSO)
82    if(!$INPUT->str('u') && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
83        $INPUT->set('u', $_SERVER['PHP_AUTH_USER']);
84        $INPUT->set('p', $_SERVER['PHP_AUTH_PW']);
85        $INPUT->set('http_credentials', true);
86    }
87
88    // apply cleaning (auth specific user names, remove control chars)
89    if (true === $auth->success) {
90        $INPUT->set('u', $auth->cleanUser(stripctl($INPUT->str('u'))));
91        $INPUT->set('p', stripctl($INPUT->str('p')));
92    }
93
94    $ok = null;
95    if (!is_null($auth) && $auth->canDo('external')) {
96        $ok = $auth->trustExternal($INPUT->str('u'), $INPUT->str('p'), $INPUT->bool('r'));
97    }
98
99    if ($ok === null) {
100        // external trust mechanism not in place, or returns no result,
101        // then attempt auth_login
102        $evdata = array(
103            'user'     => $INPUT->str('u'),
104            'password' => $INPUT->str('p'),
105            'sticky'   => $INPUT->bool('r'),
106            'silent'   => $INPUT->bool('http_credentials')
107        );
108        Event::createAndTrigger('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
109    }
110
111    //load ACL into a global array XXX
112    $AUTH_ACL = auth_loadACL();
113
114    return true;
115}
116
117/**
118 * Loads the ACL setup and handle user wildcards
119 *
120 * @author Andreas Gohr <andi@splitbrain.org>
121 *
122 * @return array
123 */
124function auth_loadACL() {
125    global $config_cascade;
126    global $USERINFO;
127    /* @var Input $INPUT */
128    global $INPUT;
129
130    if(!is_readable($config_cascade['acl']['default'])) return array();
131
132    $acl = file($config_cascade['acl']['default']);
133
134    $out = array();
135    foreach($acl as $line) {
136        $line = trim($line);
137        if(empty($line) || ($line[0] == '#')) continue; // skip blank lines & comments
138        list($id,$rest) = preg_split('/[ \t]+/',$line,2);
139
140        // substitute user wildcard first (its 1:1)
141        if(strstr($line, '%USER%')){
142            // if user is not logged in, this ACL line is meaningless - skip it
143            if (!$INPUT->server->has('REMOTE_USER')) continue;
144
145            $id   = str_replace('%USER%',cleanID($INPUT->server->str('REMOTE_USER')),$id);
146            $rest = str_replace('%USER%',auth_nameencode($INPUT->server->str('REMOTE_USER')),$rest);
147        }
148
149        // substitute group wildcard (its 1:m)
150        if(strstr($line, '%GROUP%')){
151            // if user is not logged in, grps is empty, no output will be added (i.e. skipped)
152            if(isset($USERINFO['grps'])){
153                foreach((array) $USERINFO['grps'] as $grp){
154                    $nid   = str_replace('%GROUP%',cleanID($grp),$id);
155                    $nrest = str_replace('%GROUP%','@'.auth_nameencode($grp),$rest);
156                    $out[] = "$nid\t$nrest";
157                }
158            }
159        } else {
160            $out[] = "$id\t$rest";
161        }
162    }
163
164    return $out;
165}
166
167/**
168 * Event hook callback for AUTH_LOGIN_CHECK
169 *
170 * @param array $evdata
171 * @return bool
172 */
173function auth_login_wrapper($evdata) {
174    return auth_login(
175        $evdata['user'],
176        $evdata['password'],
177        $evdata['sticky'],
178        $evdata['silent']
179    );
180}
181
182/**
183 * This tries to login the user based on the sent auth credentials
184 *
185 * The authentication works like this: if a username was given
186 * a new login is assumed and user/password are checked. If they
187 * are correct the password is encrypted with blowfish and stored
188 * together with the username in a cookie - the same info is stored
189 * in the session, too. Additonally a browserID is stored in the
190 * session.
191 *
192 * If no username was given the cookie is checked: if the username,
193 * crypted password and browserID match between session and cookie
194 * no further testing is done and the user is accepted
195 *
196 * If a cookie was found but no session info was availabe the
197 * blowfish encrypted password from the cookie is decrypted and
198 * together with username rechecked by calling this function again.
199 *
200 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
201 * are set.
202 *
203 * @author  Andreas Gohr <andi@splitbrain.org>
204 *
205 * @param   string  $user    Username
206 * @param   string  $pass    Cleartext Password
207 * @param   bool    $sticky  Cookie should not expire
208 * @param   bool    $silent  Don't show error on bad auth
209 * @return  bool             true on successful auth
210 */
211function auth_login($user, $pass, $sticky = false, $silent = false) {
212    global $USERINFO;
213    global $conf;
214    global $lang;
215    /* @var AuthPlugin $auth */
216    global $auth;
217    /* @var Input $INPUT */
218    global $INPUT;
219
220    $sticky ? $sticky = true : $sticky = false; //sanity check
221
222    if(!$auth) return false;
223
224    if(!empty($user)) {
225        //usual login
226        if(!empty($pass) && $auth->checkPass($user, $pass)) {
227            // make logininfo globally available
228            $INPUT->server->set('REMOTE_USER', $user);
229            $secret                 = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
230            auth_setCookie($user, auth_encrypt($pass, $secret), $sticky);
231            return true;
232        } else {
233            //invalid credentials - log off
234            if(!$silent) {
235                http_status(403, 'Login failed');
236                msg($lang['badlogin'], -1);
237            }
238            auth_logoff();
239            return false;
240        }
241    } else {
242        // read cookie information
243        list($user, $sticky, $pass) = auth_getCookie();
244        if($user && $pass) {
245            // we got a cookie - see if we can trust it
246
247            // get session info
248            $session = $_SESSION[DOKU_COOKIE]['auth'];
249            if(isset($session) &&
250                $auth->useSessionCache($user) &&
251                ($session['time'] >= time() - $conf['auth_security_timeout']) &&
252                ($session['user'] == $user) &&
253                ($session['pass'] == sha1($pass)) && //still crypted
254                ($session['buid'] == auth_browseruid())
255            ) {
256
257                // he has session, cookie and browser right - let him in
258                $INPUT->server->set('REMOTE_USER', $user);
259                $USERINFO               = $session['info']; //FIXME move all references to session
260                return true;
261            }
262            // no we don't trust it yet - recheck pass but silent
263            $secret = auth_cookiesalt(!$sticky, true); //bind non-sticky to session
264            $pass   = auth_decrypt($pass, $secret);
265            return auth_login($user, $pass, $sticky, true);
266        }
267    }
268    //just to be sure
269    auth_logoff(true);
270    return false;
271}
272
273/**
274 * Builds a pseudo UID from browser and IP data
275 *
276 * This is neither unique nor unfakable - still it adds some
277 * security. Using the first part of the IP makes sure
278 * proxy farms like AOLs are still okay.
279 *
280 * @author  Andreas Gohr <andi@splitbrain.org>
281 *
282 * @return  string  a MD5 sum of various browser headers
283 */
284function auth_browseruid() {
285    /* @var Input $INPUT */
286    global $INPUT;
287
288    $ip  = clientIP(true);
289    $uid = '';
290    $uid .= $INPUT->server->str('HTTP_USER_AGENT');
291    $uid .= $INPUT->server->str('HTTP_ACCEPT_CHARSET');
292    $uid .= substr($ip, 0, strpos($ip, '.'));
293    $uid = strtolower($uid);
294    return md5($uid);
295}
296
297/**
298 * Creates a random key to encrypt the password in cookies
299 *
300 * This function tries to read the password for encrypting
301 * cookies from $conf['metadir'].'/_htcookiesalt'
302 * if no such file is found a random key is created and
303 * and stored in this file.
304 *
305 * @author  Andreas Gohr <andi@splitbrain.org>
306 *
307 * @param   bool $addsession if true, the sessionid is added to the salt
308 * @param   bool $secure     if security is more important than keeping the old value
309 * @return  string
310 */
311function auth_cookiesalt($addsession = false, $secure = false) {
312    if (defined('SIMPLE_TEST')) {
313        return 'test';
314    }
315    global $conf;
316    $file = $conf['metadir'].'/_htcookiesalt';
317    if ($secure || !file_exists($file)) {
318        $file = $conf['metadir'].'/_htcookiesalt2';
319    }
320    $salt = io_readFile($file);
321    if(empty($salt)) {
322        $salt = bin2hex(auth_randombytes(64));
323        io_saveFile($file, $salt);
324    }
325    if($addsession) {
326        $salt .= session_id();
327    }
328    return $salt;
329}
330
331/**
332 * Return cryptographically secure random bytes.
333 *
334 * @author Niklas Keller <me@kelunik.com>
335 *
336 * @param int $length number of bytes
337 * @return string cryptographically secure random bytes
338 */
339function auth_randombytes($length) {
340    return random_bytes($length);
341}
342
343/**
344 * Cryptographically secure random number generator.
345 *
346 * @author Niklas Keller <me@kelunik.com>
347 *
348 * @param int $min
349 * @param int $max
350 * @return int
351 */
352function auth_random($min, $max) {
353    return random_int($min, $max);
354}
355
356/**
357 * Encrypt data using the given secret using AES
358 *
359 * The mode is CBC with a random initialization vector, the key is derived
360 * using pbkdf2.
361 *
362 * @param string $data   The data that shall be encrypted
363 * @param string $secret The secret/password that shall be used
364 * @return string The ciphertext
365 */
366function auth_encrypt($data, $secret) {
367    $iv     = auth_randombytes(16);
368    $cipher = new \phpseclib\Crypt\AES();
369    $cipher->setPassword($secret);
370
371    /*
372    this uses the encrypted IV as IV as suggested in
373    http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, Appendix C
374    for unique but necessarily random IVs. The resulting ciphertext is
375    compatible to ciphertext that was created using a "normal" IV.
376    */
377    return $cipher->encrypt($iv.$data);
378}
379
380/**
381 * Decrypt the given AES ciphertext
382 *
383 * The mode is CBC, the key is derived using pbkdf2
384 *
385 * @param string $ciphertext The encrypted data
386 * @param string $secret     The secret/password that shall be used
387 * @return string The decrypted data
388 */
389function auth_decrypt($ciphertext, $secret) {
390    $iv     = substr($ciphertext, 0, 16);
391    $cipher = new \phpseclib\Crypt\AES();
392    $cipher->setPassword($secret);
393    $cipher->setIV($iv);
394
395    return $cipher->decrypt(substr($ciphertext, 16));
396}
397
398/**
399 * Log out the current user
400 *
401 * This clears all authentication data and thus log the user
402 * off. It also clears session data.
403 *
404 * @author  Andreas Gohr <andi@splitbrain.org>
405 *
406 * @param bool $keepbc - when true, the breadcrumb data is not cleared
407 */
408function auth_logoff($keepbc = false) {
409    global $conf;
410    global $USERINFO;
411    /* @var AuthPlugin $auth */
412    global $auth;
413    /* @var Input $INPUT */
414    global $INPUT;
415
416    // make sure the session is writable (it usually is)
417    @session_start();
418
419    if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
420        unset($_SESSION[DOKU_COOKIE]['auth']['user']);
421    if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
422        unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
423    if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
424        unset($_SESSION[DOKU_COOKIE]['auth']['info']);
425    if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
426        unset($_SESSION[DOKU_COOKIE]['bc']);
427    $INPUT->server->remove('REMOTE_USER');
428    $USERINFO = null; //FIXME
429
430    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
431    setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
432
433    if($auth) $auth->logOff();
434}
435
436/**
437 * Check if a user is a manager
438 *
439 * Should usually be called without any parameters to check the current
440 * user.
441 *
442 * The info is available through $INFO['ismanager'], too
443 *
444 * @param string $user Username
445 * @param array $groups List of groups the user is in
446 * @param bool $adminonly when true checks if user is admin
447 * @param bool $recache set to true to refresh the cache
448 * @return bool
449 * @see    auth_isadmin
450 *
451 * @author Andreas Gohr <andi@splitbrain.org>
452 */
453function auth_ismanager($user = null, $groups = null, $adminonly = false, $recache=false) {
454    global $conf;
455    global $USERINFO;
456    /* @var AuthPlugin $auth */
457    global $auth;
458    /* @var Input $INPUT */
459    global $INPUT;
460
461
462    if(!$auth) return false;
463    if(is_null($user)) {
464        if(!$INPUT->server->has('REMOTE_USER')) {
465            return false;
466        } else {
467            $user = $INPUT->server->str('REMOTE_USER');
468        }
469    }
470    if(is_null($groups)) {
471        $groups = $USERINFO ? (array) $USERINFO['grps'] : array();
472    }
473
474    // prefer cached result
475    static $cache = [];
476    $cachekey = serialize([$user, $adminonly, $groups]);
477    if (!isset($cache[$cachekey]) || $recache) {
478        // check superuser match
479        $ok = auth_isMember($conf['superuser'], $user, $groups);
480
481        // check managers
482        if (!$ok && !$adminonly) {
483            $ok = auth_isMember($conf['manager'], $user, $groups);
484        }
485
486        $cache[$cachekey] = $ok;
487    }
488
489    return $cache[$cachekey];
490}
491
492/**
493 * Check if a user is admin
494 *
495 * Alias to auth_ismanager with adminonly=true
496 *
497 * The info is available through $INFO['isadmin'], too
498 *
499 * @param string $user Username
500 * @param array $groups List of groups the user is in
501 * @param bool $recache set to true to refresh the cache
502 * @return bool
503 * @author Andreas Gohr <andi@splitbrain.org>
504 * @see auth_ismanager()
505 *
506 */
507function auth_isadmin($user = null, $groups = null, $recache=false) {
508    return auth_ismanager($user, $groups, true, $recache);
509}
510
511/**
512 * Match a user and his groups against a comma separated list of
513 * users and groups to determine membership status
514 *
515 * Note: all input should NOT be nameencoded.
516 *
517 * @param string $memberlist commaseparated list of allowed users and groups
518 * @param string $user       user to match against
519 * @param array  $groups     groups the user is member of
520 * @return bool       true for membership acknowledged
521 */
522function auth_isMember($memberlist, $user, array $groups) {
523    /* @var AuthPlugin $auth */
524    global $auth;
525    if(!$auth) return false;
526
527    // clean user and groups
528    if(!$auth->isCaseSensitive()) {
529        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
530        $groups = array_map('utf8_strtolower', $groups);
531    }
532    $user   = $auth->cleanUser($user);
533    $groups = array_map(array($auth, 'cleanGroup'), $groups);
534
535    // extract the memberlist
536    $members = explode(',', $memberlist);
537    $members = array_map('trim', $members);
538    $members = array_unique($members);
539    $members = array_filter($members);
540
541    // compare cleaned values
542    foreach($members as $member) {
543        if($member == '@ALL' ) return true;
544        if(!$auth->isCaseSensitive()) $member = \dokuwiki\Utf8\PhpString::strtolower($member);
545        if($member[0] == '@') {
546            $member = $auth->cleanGroup(substr($member, 1));
547            if(in_array($member, $groups)) return true;
548        } else {
549            $member = $auth->cleanUser($member);
550            if($member == $user) return true;
551        }
552    }
553
554    // still here? not a member!
555    return false;
556}
557
558/**
559 * Convinience function for auth_aclcheck()
560 *
561 * This checks the permissions for the current user
562 *
563 * @author  Andreas Gohr <andi@splitbrain.org>
564 *
565 * @param  string  $id  page ID (needs to be resolved and cleaned)
566 * @return int          permission level
567 */
568function auth_quickaclcheck($id) {
569    global $conf;
570    global $USERINFO;
571    /* @var Input $INPUT */
572    global $INPUT;
573    # if no ACL is used always return upload rights
574    if(!$conf['useacl']) return AUTH_UPLOAD;
575    return auth_aclcheck($id, $INPUT->server->str('REMOTE_USER'), is_array($USERINFO) ? $USERINFO['grps'] : array());
576}
577
578/**
579 * Returns the maximum rights a user has for the given ID or its namespace
580 *
581 * @author  Andreas Gohr <andi@splitbrain.org>
582 *
583 * @triggers AUTH_ACL_CHECK
584 * @param  string       $id     page ID (needs to be resolved and cleaned)
585 * @param  string       $user   Username
586 * @param  array|null   $groups Array of groups the user is in
587 * @return int             permission level
588 */
589function auth_aclcheck($id, $user, $groups) {
590    $data = array(
591        'id'     => $id,
592        'user'   => $user,
593        'groups' => $groups
594    );
595
596    return Event::createAndTrigger('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
597}
598
599/**
600 * default ACL check method
601 *
602 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
603 *
604 * @author  Andreas Gohr <andi@splitbrain.org>
605 *
606 * @param  array $data event data
607 * @return int   permission level
608 */
609function auth_aclcheck_cb($data) {
610    $id     =& $data['id'];
611    $user   =& $data['user'];
612    $groups =& $data['groups'];
613
614    global $conf;
615    global $AUTH_ACL;
616    /* @var AuthPlugin $auth */
617    global $auth;
618
619    // if no ACL is used always return upload rights
620    if(!$conf['useacl']) return AUTH_UPLOAD;
621    if(!$auth) return AUTH_NONE;
622
623    //make sure groups is an array
624    if(!is_array($groups)) $groups = array();
625
626    //if user is superuser or in superusergroup return 255 (acl_admin)
627    if(auth_isadmin($user, $groups)) {
628        return AUTH_ADMIN;
629    }
630
631    if(!$auth->isCaseSensitive()) {
632        $user   = \dokuwiki\Utf8\PhpString::strtolower($user);
633        $groups = array_map('utf8_strtolower', $groups);
634    }
635    $user   = auth_nameencode($auth->cleanUser($user));
636    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
637
638    //prepend groups with @ and nameencode
639    foreach($groups as &$group) {
640        $group = '@'.auth_nameencode($group);
641    }
642
643    $ns   = getNS($id);
644    $perm = -1;
645
646    //add ALL group
647    $groups[] = '@ALL';
648
649    //add User
650    if($user) $groups[] = $user;
651
652    //check exact match first
653    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
654    if(count($matches)) {
655        foreach($matches as $match) {
656            $match = preg_replace('/#.*$/', '', $match); //ignore comments
657            $acl   = preg_split('/[ \t]+/', $match);
658            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
659                $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
660            }
661            if(!in_array($acl[1], $groups)) {
662                continue;
663            }
664            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
665            if($acl[2] > $perm) {
666                $perm = $acl[2];
667            }
668        }
669        if($perm > -1) {
670            //we had a match - return it
671            return (int) $perm;
672        }
673    }
674
675    //still here? do the namespace checks
676    if($ns) {
677        $path = $ns.':*';
678    } else {
679        $path = '*'; //root document
680    }
681
682    do {
683        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
684        if(count($matches)) {
685            foreach($matches as $match) {
686                $match = preg_replace('/#.*$/', '', $match); //ignore comments
687                $acl   = preg_split('/[ \t]+/', $match);
688                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
689                    $acl[1] = \dokuwiki\Utf8\PhpString::strtolower($acl[1]);
690                }
691                if(!in_array($acl[1], $groups)) {
692                    continue;
693                }
694                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
695                if($acl[2] > $perm) {
696                    $perm = $acl[2];
697                }
698            }
699            //we had a match - return it
700            if($perm != -1) {
701                return (int) $perm;
702            }
703        }
704        //get next higher namespace
705        $ns = getNS($ns);
706
707        if($path != '*') {
708            $path = $ns.':*';
709            if($path == ':*') $path = '*';
710        } else {
711            //we did this already
712            //looks like there is something wrong with the ACL
713            //break here
714            msg('No ACL setup yet! Denying access to everyone.');
715            return AUTH_NONE;
716        }
717    } while(1); //this should never loop endless
718    return AUTH_NONE;
719}
720
721/**
722 * Encode ASCII special chars
723 *
724 * Some auth backends allow special chars in their user and groupnames
725 * The special chars are encoded with this function. Only ASCII chars
726 * are encoded UTF-8 multibyte are left as is (different from usual
727 * urlencoding!).
728 *
729 * Decoding can be done with rawurldecode
730 *
731 * @author Andreas Gohr <gohr@cosmocode.de>
732 * @see rawurldecode()
733 *
734 * @param string $name
735 * @param bool $skip_group
736 * @return string
737 */
738function auth_nameencode($name, $skip_group = false) {
739    global $cache_authname;
740    $cache =& $cache_authname;
741    $name  = (string) $name;
742
743    // never encode wildcard FS#1955
744    if($name == '%USER%') return $name;
745    if($name == '%GROUP%') return $name;
746
747    if(!isset($cache[$name][$skip_group])) {
748        if($skip_group && $name[0] == '@') {
749            $cache[$name][$skip_group] = '@'.preg_replace_callback(
750                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
751                'auth_nameencode_callback', substr($name, 1)
752            );
753        } else {
754            $cache[$name][$skip_group] = preg_replace_callback(
755                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
756                'auth_nameencode_callback', $name
757            );
758        }
759    }
760
761    return $cache[$name][$skip_group];
762}
763
764/**
765 * callback encodes the matches
766 *
767 * @param array $matches first complete match, next matching subpatterms
768 * @return string
769 */
770function auth_nameencode_callback($matches) {
771    return '%'.dechex(ord(substr($matches[1],-1)));
772}
773
774/**
775 * Create a pronouncable password
776 *
777 * The $foruser variable might be used by plugins to run additional password
778 * policy checks, but is not used by the default implementation
779 *
780 * @author   Andreas Gohr <andi@splitbrain.org>
781 * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
782 * @triggers AUTH_PASSWORD_GENERATE
783 *
784 * @param  string $foruser username for which the password is generated
785 * @return string  pronouncable password
786 */
787function auth_pwgen($foruser = '') {
788    $data = array(
789        'password' => '',
790        'foruser'  => $foruser
791    );
792
793    $evt = new Event('AUTH_PASSWORD_GENERATE', $data);
794    if($evt->advise_before(true)) {
795        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
796        $v = 'aeiou'; //vowels
797        $a = $c.$v; //both
798        $s = '!$%&?+*~#-_:.;,'; // specials
799
800        //use thre syllables...
801        for($i = 0; $i < 3; $i++) {
802            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
803            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
804            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
805        }
806        //... and add a nice number and special
807        $data['password'] .= $s[auth_random(0, strlen($s) - 1)].auth_random(10, 99);
808    }
809    $evt->advise_after();
810
811    return $data['password'];
812}
813
814/**
815 * Sends a password to the given user
816 *
817 * @author  Andreas Gohr <andi@splitbrain.org>
818 *
819 * @param string $user Login name of the user
820 * @param string $password The new password in clear text
821 * @return bool  true on success
822 */
823function auth_sendPassword($user, $password) {
824    global $lang;
825    /* @var AuthPlugin $auth */
826    global $auth;
827    if(!$auth) return false;
828
829    $user     = $auth->cleanUser($user);
830    $userinfo = $auth->getUserData($user, $requireGroups = false);
831
832    if(!$userinfo['mail']) return false;
833
834    $text = rawLocale('password');
835    $trep = array(
836        'FULLNAME' => $userinfo['name'],
837        'LOGIN'    => $user,
838        'PASSWORD' => $password
839    );
840
841    $mail = new Mailer();
842    $mail->to($mail->getCleanName($userinfo['name']).' <'.$userinfo['mail'].'>');
843    $mail->subject($lang['regpwmail']);
844    $mail->setBody($text, $trep);
845    return $mail->send();
846}
847
848/**
849 * Register a new user
850 *
851 * This registers a new user - Data is read directly from $_POST
852 *
853 * @author  Andreas Gohr <andi@splitbrain.org>
854 *
855 * @return bool  true on success, false on any error
856 */
857function register() {
858    global $lang;
859    global $conf;
860    /* @var \dokuwiki\Extension\AuthPlugin $auth */
861    global $auth;
862    global $INPUT;
863
864    if(!$INPUT->post->bool('save')) return false;
865    if(!actionOK('register')) return false;
866
867    // gather input
868    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
869    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
870    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
871    $pass     = $INPUT->post->str('pass');
872    $passchk  = $INPUT->post->str('passchk');
873
874    if(empty($login) || empty($fullname) || empty($email)) {
875        msg($lang['regmissing'], -1);
876        return false;
877    }
878
879    if($conf['autopasswd']) {
880        $pass = auth_pwgen($login); // automatically generate password
881    } elseif(empty($pass) || empty($passchk)) {
882        msg($lang['regmissing'], -1); // complain about missing passwords
883        return false;
884    } elseif($pass != $passchk) {
885        msg($lang['regbadpass'], -1); // complain about misspelled passwords
886        return false;
887    }
888
889    //check mail
890    if(!mail_isvalid($email)) {
891        msg($lang['regbadmail'], -1);
892        return false;
893    }
894
895    //okay try to create the user
896    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
897        msg($lang['regfail'], -1);
898        return false;
899    }
900
901    // send notification about the new user
902    $subscription = new RegistrationSubscriptionSender();
903    $subscription->sendRegister($login, $fullname, $email);
904
905    // are we done?
906    if(!$conf['autopasswd']) {
907        msg($lang['regsuccess2'], 1);
908        return true;
909    }
910
911    // autogenerated password? then send password to user
912    if(auth_sendPassword($login, $pass)) {
913        msg($lang['regsuccess'], 1);
914        return true;
915    } else {
916        msg($lang['regmailfail'], -1);
917        return false;
918    }
919}
920
921/**
922 * Update user profile
923 *
924 * @author    Christopher Smith <chris@jalakai.co.uk>
925 */
926function updateprofile() {
927    global $conf;
928    global $lang;
929    /* @var AuthPlugin $auth */
930    global $auth;
931    /* @var Input $INPUT */
932    global $INPUT;
933
934    if(!$INPUT->post->bool('save')) return false;
935    if(!checkSecurityToken()) return false;
936
937    if(!actionOK('profile')) {
938        msg($lang['profna'], -1);
939        return false;
940    }
941
942    $changes         = array();
943    $changes['pass'] = $INPUT->post->str('newpass');
944    $changes['name'] = $INPUT->post->str('fullname');
945    $changes['mail'] = $INPUT->post->str('email');
946
947    // check misspelled passwords
948    if($changes['pass'] != $INPUT->post->str('passchk')) {
949        msg($lang['regbadpass'], -1);
950        return false;
951    }
952
953    // clean fullname and email
954    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
955    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
956
957    // no empty name and email (except the backend doesn't support them)
958    if((empty($changes['name']) && $auth->canDo('modName')) ||
959        (empty($changes['mail']) && $auth->canDo('modMail'))
960    ) {
961        msg($lang['profnoempty'], -1);
962        return false;
963    }
964    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
965        msg($lang['regbadmail'], -1);
966        return false;
967    }
968
969    $changes = array_filter($changes);
970
971    // check for unavailable capabilities
972    if(!$auth->canDo('modName')) unset($changes['name']);
973    if(!$auth->canDo('modMail')) unset($changes['mail']);
974    if(!$auth->canDo('modPass')) unset($changes['pass']);
975
976    // anything to do?
977    if(!count($changes)) {
978        msg($lang['profnochange'], -1);
979        return false;
980    }
981
982    if($conf['profileconfirm']) {
983        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
984            msg($lang['badpassconfirm'], -1);
985            return false;
986        }
987    }
988
989    if(!$auth->triggerUserMod('modify', array($INPUT->server->str('REMOTE_USER'), &$changes))) {
990        msg($lang['proffail'], -1);
991        return false;
992    }
993
994    if($changes['pass']) {
995        // update cookie and session with the changed data
996        list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
997        $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
998        auth_setCookie($INPUT->server->str('REMOTE_USER'), $pass, (bool) $sticky);
999    } else {
1000        // make sure the session is writable
1001        @session_start();
1002        // invalidate session cache
1003        $_SESSION[DOKU_COOKIE]['auth']['time'] = 0;
1004        session_write_close();
1005    }
1006
1007    return true;
1008}
1009
1010/**
1011 * Delete the current logged-in user
1012 *
1013 * @return bool true on success, false on any error
1014 */
1015function auth_deleteprofile(){
1016    global $conf;
1017    global $lang;
1018    /* @var \dokuwiki\Extension\AuthPlugin $auth */
1019    global $auth;
1020    /* @var Input $INPUT */
1021    global $INPUT;
1022
1023    if(!$INPUT->post->bool('delete')) return false;
1024    if(!checkSecurityToken()) return false;
1025
1026    // action prevented or auth module disallows
1027    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1028        msg($lang['profnodelete'], -1);
1029        return false;
1030    }
1031
1032    if(!$INPUT->post->bool('confirm_delete')){
1033        msg($lang['profconfdeletemissing'], -1);
1034        return false;
1035    }
1036
1037    if($conf['profileconfirm']) {
1038        if(!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
1039            msg($lang['badpassconfirm'], -1);
1040            return false;
1041        }
1042    }
1043
1044    $deleted = array();
1045    $deleted[] = $INPUT->server->str('REMOTE_USER');
1046    if($auth->triggerUserMod('delete', array($deleted))) {
1047        // force and immediate logout including removing the sticky cookie
1048        auth_logoff();
1049        return true;
1050    }
1051
1052    return false;
1053}
1054
1055/**
1056 * Send a  new password
1057 *
1058 * This function handles both phases of the password reset:
1059 *
1060 *   - handling the first request of password reset
1061 *   - validating the password reset auth token
1062 *
1063 * @author Benoit Chesneau <benoit@bchesneau.info>
1064 * @author Chris Smith <chris@jalakai.co.uk>
1065 * @author Andreas Gohr <andi@splitbrain.org>
1066 *
1067 * @return bool true on success, false on any error
1068 */
1069function act_resendpwd() {
1070    global $lang;
1071    global $conf;
1072    /* @var AuthPlugin $auth */
1073    global $auth;
1074    /* @var Input $INPUT */
1075    global $INPUT;
1076
1077    if(!actionOK('resendpwd')) {
1078        msg($lang['resendna'], -1);
1079        return false;
1080    }
1081
1082    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1083
1084    if($token) {
1085        // we're in token phase - get user info from token
1086
1087        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1088        if(!file_exists($tfile)) {
1089            msg($lang['resendpwdbadauth'], -1);
1090            $INPUT->remove('pwauth');
1091            return false;
1092        }
1093        // token is only valid for 3 days
1094        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1095            msg($lang['resendpwdbadauth'], -1);
1096            $INPUT->remove('pwauth');
1097            @unlink($tfile);
1098            return false;
1099        }
1100
1101        $user     = io_readfile($tfile);
1102        $userinfo = $auth->getUserData($user, $requireGroups = false);
1103        if(!$userinfo['mail']) {
1104            msg($lang['resendpwdnouser'], -1);
1105            return false;
1106        }
1107
1108        if(!$conf['autopasswd']) { // we let the user choose a password
1109            $pass = $INPUT->str('pass');
1110
1111            // password given correctly?
1112            if(!$pass) return false;
1113            if($pass != $INPUT->str('passchk')) {
1114                msg($lang['regbadpass'], -1);
1115                return false;
1116            }
1117
1118            // change it
1119            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1120                msg($lang['proffail'], -1);
1121                return false;
1122            }
1123
1124        } else { // autogenerate the password and send by mail
1125
1126            $pass = auth_pwgen($user);
1127            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1128                msg($lang['proffail'], -1);
1129                return false;
1130            }
1131
1132            if(auth_sendPassword($user, $pass)) {
1133                msg($lang['resendpwdsuccess'], 1);
1134            } else {
1135                msg($lang['regmailfail'], -1);
1136            }
1137        }
1138
1139        @unlink($tfile);
1140        return true;
1141
1142    } else {
1143        // we're in request phase
1144
1145        if(!$INPUT->post->bool('save')) return false;
1146
1147        if(!$INPUT->post->str('login')) {
1148            msg($lang['resendpwdmissing'], -1);
1149            return false;
1150        } else {
1151            $user = trim($auth->cleanUser($INPUT->post->str('login')));
1152        }
1153
1154        $userinfo = $auth->getUserData($user, $requireGroups = false);
1155        if(!$userinfo['mail']) {
1156            msg($lang['resendpwdnouser'], -1);
1157            return false;
1158        }
1159
1160        // generate auth token
1161        $token = md5(auth_randombytes(16)); // random secret
1162        $tfile = $conf['cachedir'].'/'.$token[0].'/'.$token.'.pwauth';
1163        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1164
1165        io_saveFile($tfile, $user);
1166
1167        $text = rawLocale('pwconfirm');
1168        $trep = array(
1169            'FULLNAME' => $userinfo['name'],
1170            'LOGIN'    => $user,
1171            'CONFIRM'  => $url
1172        );
1173
1174        $mail = new Mailer();
1175        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1176        $mail->subject($lang['regpwmail']);
1177        $mail->setBody($text, $trep);
1178        if($mail->send()) {
1179            msg($lang['resendpwdconfirm'], 1);
1180        } else {
1181            msg($lang['regmailfail'], -1);
1182        }
1183        return true;
1184    }
1185    // never reached
1186}
1187
1188/**
1189 * Encrypts a password using the given method and salt
1190 *
1191 * If the selected method needs a salt and none was given, a random one
1192 * is chosen.
1193 *
1194 * @author  Andreas Gohr <andi@splitbrain.org>
1195 *
1196 * @param string $clear The clear text password
1197 * @param string $method The hashing method
1198 * @param string $salt A salt, null for random
1199 * @return  string  The crypted password
1200 */
1201function auth_cryptPassword($clear, $method = '', $salt = null) {
1202    global $conf;
1203    if(empty($method)) $method = $conf['passcrypt'];
1204
1205    $pass = new PassHash();
1206    $call = 'hash_'.$method;
1207
1208    if(!method_exists($pass, $call)) {
1209        msg("Unsupported crypt method $method", -1);
1210        return false;
1211    }
1212
1213    return $pass->$call($clear, $salt);
1214}
1215
1216/**
1217 * Verifies a cleartext password against a crypted hash
1218 *
1219 * @author Andreas Gohr <andi@splitbrain.org>
1220 *
1221 * @param  string $clear The clear text password
1222 * @param  string $crypt The hash to compare with
1223 * @return bool true if both match
1224 */
1225function auth_verifyPassword($clear, $crypt) {
1226    $pass = new PassHash();
1227    return $pass->verify_hash($clear, $crypt);
1228}
1229
1230/**
1231 * Set the authentication cookie and add user identification data to the session
1232 *
1233 * @param string  $user       username
1234 * @param string  $pass       encrypted password
1235 * @param bool    $sticky     whether or not the cookie will last beyond the session
1236 * @return bool
1237 */
1238function auth_setCookie($user, $pass, $sticky) {
1239    global $conf;
1240    /* @var AuthPlugin $auth */
1241    global $auth;
1242    global $USERINFO;
1243
1244    if(!$auth) return false;
1245    $USERINFO = $auth->getUserData($user);
1246
1247    // set cookie
1248    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1249    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1250    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1251    setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1252
1253    // set session
1254    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1255    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1256    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1257    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1258    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1259
1260    return true;
1261}
1262
1263/**
1264 * Returns the user, (encrypted) password and sticky bit from cookie
1265 *
1266 * @returns array
1267 */
1268function auth_getCookie() {
1269    if(!isset($_COOKIE[DOKU_COOKIE])) {
1270        return array(null, null, null);
1271    }
1272    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1273    $sticky = (bool) $sticky;
1274    $pass   = base64_decode($pass);
1275    $user   = base64_decode($user);
1276    return array($user, $sticky, $pass);
1277}
1278
1279//Setup VIM: ex: et ts=2 :
1280