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