xref: /dokuwiki/inc/auth.php (revision a18d5a45ddf6db8f235df0f115cd33c2211edf4e)
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 the given ID or its namespace
665 *
666 * @author  Andreas Gohr <andi@splitbrain.org>
667 * @triggers AUTH_ACL_CHECK
668 * @param  string       $id     page ID (needs to be resolved and cleaned)
669 * @param  string       $user   Username
670 * @param  array|null   $groups Array of groups the user is in
671 * @return int             permission level
672 */
673function auth_aclcheck($id, $user, $groups) {
674    $data = array(
675        'id'     => $id,
676        'user'   => $user,
677        'groups' => $groups
678    );
679
680    return trigger_event('AUTH_ACL_CHECK', $data, 'auth_aclcheck_cb');
681}
682
683/**
684 * default ACL check method
685 *
686 * DO NOT CALL DIRECTLY, use auth_aclcheck() instead
687 *
688 * @author  Andreas Gohr <andi@splitbrain.org>
689 * @param  array $data event data
690 * @return int   permission level
691 */
692function auth_aclcheck_cb($data) {
693    $id     =& $data['id'];
694    $user   =& $data['user'];
695    $groups =& $data['groups'];
696
697    global $conf;
698    global $AUTH_ACL;
699    /* @var DokuWiki_Auth_Plugin $auth */
700    global $auth;
701
702    // if no ACL is used always return upload rights
703    if(!$conf['useacl']) return AUTH_UPLOAD;
704    if(!$auth) return AUTH_NONE;
705
706    //make sure groups is an array
707    if(!is_array($groups)) $groups = array();
708
709    //if user is superuser or in superusergroup return 255 (acl_admin)
710    if(auth_isadmin($user, $groups)) {
711        return AUTH_ADMIN;
712    }
713
714    if(!$auth->isCaseSensitive()) {
715        $user   = utf8_strtolower($user);
716        $groups = array_map('utf8_strtolower', $groups);
717    }
718    $user   = $auth->cleanUser($user);
719    $groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
720    $user   = auth_nameencode($user);
721
722    //prepend groups with @ and nameencode
723    $cnt = count($groups);
724    for($i = 0; $i < $cnt; $i++) {
725        $groups[$i] = '@'.auth_nameencode($groups[$i]);
726    }
727
728    $ns   = getNS($id);
729    $perm = -1;
730
731    if($user || count($groups)) {
732        //add ALL group
733        $groups[] = '@ALL';
734        //add User
735        if($user) $groups[] = $user;
736    } else {
737        $groups[] = '@ALL';
738    }
739
740    //check exact match first
741    $matches = preg_grep('/^'.preg_quote($id, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
742    if(count($matches)) {
743        foreach($matches as $match) {
744            $match = preg_replace('/#.*$/', '', $match); //ignore comments
745            $acl   = preg_split('/[ \t]+/', $match);
746            if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
747                $acl[1] = utf8_strtolower($acl[1]);
748            }
749            if(!in_array($acl[1], $groups)) {
750                continue;
751            }
752            if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
753            if($acl[2] > $perm) {
754                $perm = $acl[2];
755            }
756        }
757        if($perm > -1) {
758            //we had a match - return it
759            return (int) $perm;
760        }
761    }
762
763    //still here? do the namespace checks
764    if($ns) {
765        $path = $ns.':*';
766    } else {
767        $path = '*'; //root document
768    }
769
770    do {
771        $matches = preg_grep('/^'.preg_quote($path, '/').'[ \t]+([^ \t]+)[ \t]+/', $AUTH_ACL);
772        if(count($matches)) {
773            foreach($matches as $match) {
774                $match = preg_replace('/#.*$/', '', $match); //ignore comments
775                $acl   = preg_split('/[ \t]+/', $match);
776                if(!$auth->isCaseSensitive() && $acl[1] !== '@ALL') {
777                    $acl[1] = utf8_strtolower($acl[1]);
778                }
779                if(!in_array($acl[1], $groups)) {
780                    continue;
781                }
782                if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
783                if($acl[2] > $perm) {
784                    $perm = $acl[2];
785                }
786            }
787            //we had a match - return it
788            if($perm != -1) {
789                return (int) $perm;
790            }
791        }
792        //get next higher namespace
793        $ns = getNS($ns);
794
795        if($path != '*') {
796            $path = $ns.':*';
797            if($path == ':*') $path = '*';
798        } else {
799            //we did this already
800            //looks like there is something wrong with the ACL
801            //break here
802            msg('No ACL setup yet! Denying access to everyone.');
803            return AUTH_NONE;
804        }
805    } while(1); //this should never loop endless
806    return AUTH_NONE;
807}
808
809/**
810 * Encode ASCII special chars
811 *
812 * Some auth backends allow special chars in their user and groupnames
813 * The special chars are encoded with this function. Only ASCII chars
814 * are encoded UTF-8 multibyte are left as is (different from usual
815 * urlencoding!).
816 *
817 * Decoding can be done with rawurldecode
818 *
819 * @author Andreas Gohr <gohr@cosmocode.de>
820 * @see rawurldecode()
821 */
822function auth_nameencode($name, $skip_group = false) {
823    global $cache_authname;
824    $cache =& $cache_authname;
825    $name  = (string) $name;
826
827    // never encode wildcard FS#1955
828    if($name == '%USER%') return $name;
829    if($name == '%GROUP%') return $name;
830
831    if(!isset($cache[$name][$skip_group])) {
832        if($skip_group && $name{0} == '@') {
833            $cache[$name][$skip_group] = '@'.preg_replace_callback(
834                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
835                'auth_nameencode_callback', substr($name, 1)
836            );
837        } else {
838            $cache[$name][$skip_group] = preg_replace_callback(
839                '/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/',
840                'auth_nameencode_callback', $name
841            );
842        }
843    }
844
845    return $cache[$name][$skip_group];
846}
847
848function auth_nameencode_callback($matches) {
849    return '%'.dechex(ord(substr($matches[1],-1)));
850}
851
852/**
853 * Create a pronouncable password
854 *
855 * The $foruser variable might be used by plugins to run additional password
856 * policy checks, but is not used by the default implementation
857 *
858 * @author   Andreas Gohr <andi@splitbrain.org>
859 * @link     http://www.phpbuilder.com/annotate/message.php3?id=1014451
860 * @triggers AUTH_PASSWORD_GENERATE
861 *
862 * @param  string $foruser username for which the password is generated
863 * @return string  pronouncable password
864 */
865function auth_pwgen($foruser = '') {
866    $data = array(
867        'password' => '',
868        'foruser'  => $foruser
869    );
870
871    $evt = new Doku_Event('AUTH_PASSWORD_GENERATE', $data);
872    if($evt->advise_before(true)) {
873        $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
874        $v = 'aeiou'; //vowels
875        $a = $c.$v; //both
876        $s = '!$%&?+*~#-_:.;,'; // specials
877
878        //use thre syllables...
879        for($i = 0; $i < 3; $i++) {
880            $data['password'] .= $c[auth_random(0, strlen($c) - 1)];
881            $data['password'] .= $v[auth_random(0, strlen($v) - 1)];
882            $data['password'] .= $a[auth_random(0, strlen($a) - 1)];
883        }
884        //... and add a nice number and special
885        $data['password'] .= auth_random(10, 99).$s[auth_random(0, strlen($s) - 1)];
886    }
887    $evt->advise_after();
888
889    return $data['password'];
890}
891
892/**
893 * Sends a password to the given user
894 *
895 * @author  Andreas Gohr <andi@splitbrain.org>
896 * @param string $user Login name of the user
897 * @param string $password The new password in clear text
898 * @return bool  true on success
899 */
900function auth_sendPassword($user, $password) {
901    global $lang;
902    /* @var DokuWiki_Auth_Plugin $auth */
903    global $auth;
904    if(!$auth) return false;
905
906    $user     = $auth->cleanUser($user);
907    $userinfo = $auth->getUserData($user);
908
909    if(!$userinfo['mail']) return false;
910
911    $text = rawLocale('password');
912    $trep = array(
913        'FULLNAME' => $userinfo['name'],
914        'LOGIN'    => $user,
915        'PASSWORD' => $password
916    );
917
918    $mail = new Mailer();
919    $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
920    $mail->subject($lang['regpwmail']);
921    $mail->setBody($text, $trep);
922    return $mail->send();
923}
924
925/**
926 * Register a new user
927 *
928 * This registers a new user - Data is read directly from $_POST
929 *
930 * @author  Andreas Gohr <andi@splitbrain.org>
931 * @return bool  true on success, false on any error
932 */
933function register() {
934    global $lang;
935    global $conf;
936    /* @var DokuWiki_Auth_Plugin $auth */
937    global $auth;
938    global $INPUT;
939
940    if(!$INPUT->post->bool('save')) return false;
941    if(!actionOK('register')) return false;
942
943    // gather input
944    $login    = trim($auth->cleanUser($INPUT->post->str('login')));
945    $fullname = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('fullname')));
946    $email    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $INPUT->post->str('email')));
947    $pass     = $INPUT->post->str('pass');
948    $passchk  = $INPUT->post->str('passchk');
949
950    if(empty($login) || empty($fullname) || empty($email)) {
951        msg($lang['regmissing'], -1);
952        return false;
953    }
954
955    if($conf['autopasswd']) {
956        $pass = auth_pwgen($login); // automatically generate password
957    } elseif(empty($pass) || empty($passchk)) {
958        msg($lang['regmissing'], -1); // complain about missing passwords
959        return false;
960    } elseif($pass != $passchk) {
961        msg($lang['regbadpass'], -1); // complain about misspelled passwords
962        return false;
963    }
964
965    //check mail
966    if(!mail_isvalid($email)) {
967        msg($lang['regbadmail'], -1);
968        return false;
969    }
970
971    //okay try to create the user
972    if(!$auth->triggerUserMod('create', array($login, $pass, $fullname, $email))) {
973        msg($lang['reguexists'], -1);
974        return false;
975    }
976
977    // send notification about the new user
978    $subscription = new Subscription();
979    $subscription->send_register($login, $fullname, $email);
980
981    // are we done?
982    if(!$conf['autopasswd']) {
983        msg($lang['regsuccess2'], 1);
984        return true;
985    }
986
987    // autogenerated password? then send password to user
988    if(auth_sendPassword($login, $pass)) {
989        msg($lang['regsuccess'], 1);
990        return true;
991    } else {
992        msg($lang['regmailfail'], -1);
993        return false;
994    }
995}
996
997/**
998 * Update user profile
999 *
1000 * @author    Christopher Smith <chris@jalakai.co.uk>
1001 */
1002function updateprofile() {
1003    global $conf;
1004    global $lang;
1005    /* @var DokuWiki_Auth_Plugin $auth */
1006    global $auth;
1007    /* @var Input $INPUT */
1008    global $INPUT;
1009
1010    if(!$INPUT->post->bool('save')) return false;
1011    if(!checkSecurityToken()) return false;
1012
1013    if(!actionOK('profile')) {
1014        msg($lang['profna'], -1);
1015        return false;
1016    }
1017
1018    $changes         = array();
1019    $changes['pass'] = $INPUT->post->str('newpass');
1020    $changes['name'] = $INPUT->post->str('fullname');
1021    $changes['mail'] = $INPUT->post->str('email');
1022
1023    // check misspelled passwords
1024    if($changes['pass'] != $INPUT->post->str('passchk')) {
1025        msg($lang['regbadpass'], -1);
1026        return false;
1027    }
1028
1029    // clean fullname and email
1030    $changes['name'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['name']));
1031    $changes['mail'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $changes['mail']));
1032
1033    // no empty name and email (except the backend doesn't support them)
1034    if((empty($changes['name']) && $auth->canDo('modName')) ||
1035        (empty($changes['mail']) && $auth->canDo('modMail'))
1036    ) {
1037        msg($lang['profnoempty'], -1);
1038        return false;
1039    }
1040    if(!mail_isvalid($changes['mail']) && $auth->canDo('modMail')) {
1041        msg($lang['regbadmail'], -1);
1042        return false;
1043    }
1044
1045    $changes = array_filter($changes);
1046
1047    // check for unavailable capabilities
1048    if(!$auth->canDo('modName')) unset($changes['name']);
1049    if(!$auth->canDo('modMail')) unset($changes['mail']);
1050    if(!$auth->canDo('modPass')) unset($changes['pass']);
1051
1052    // anything to do?
1053    if(!count($changes)) {
1054        msg($lang['profnochange'], -1);
1055        return false;
1056    }
1057
1058    if($conf['profileconfirm']) {
1059        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
1060            msg($lang['badpassconfirm'], -1);
1061            return false;
1062        }
1063    }
1064
1065    if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
1066        // update cookie and session with the changed data
1067        if($changes['pass']) {
1068            list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
1069            $pass = auth_encrypt($changes['pass'], auth_cookiesalt(!$sticky, true));
1070            auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
1071        }
1072        return true;
1073    }
1074
1075    return false;
1076}
1077
1078function auth_deleteprofile(){
1079    global $conf;
1080    global $lang;
1081    /* @var DokuWiki_Auth_Plugin $auth */
1082    global $auth;
1083    /* @var Input $INPUT */
1084    global $INPUT;
1085
1086    if(!$INPUT->post->bool('delete')) return false;
1087    if(!checkSecurityToken()) return false;
1088
1089    // action prevented or auth module disallows
1090    if(!actionOK('profile_delete') || !$auth->canDo('delUser')) {
1091        msg($lang['profnodelete'], -1);
1092        return false;
1093    }
1094
1095    if(!$INPUT->post->bool('confirm_delete')){
1096        msg($lang['profconfdeletemissing'], -1);
1097        return false;
1098    }
1099
1100    if($conf['profileconfirm']) {
1101        if(!$auth->checkPass($_SERVER['REMOTE_USER'], $INPUT->post->str('oldpass'))) {
1102            msg($lang['badpassconfirm'], -1);
1103            return false;
1104        }
1105    }
1106
1107    $deleted[] = $_SERVER['REMOTE_USER'];
1108    if($auth->triggerUserMod('delete', array($deleted))) {
1109        // force and immediate logout including removing the sticky cookie
1110        auth_logoff();
1111        return true;
1112    }
1113
1114    return false;
1115}
1116
1117/**
1118 * Send a  new password
1119 *
1120 * This function handles both phases of the password reset:
1121 *
1122 *   - handling the first request of password reset
1123 *   - validating the password reset auth token
1124 *
1125 * @author Benoit Chesneau <benoit@bchesneau.info>
1126 * @author Chris Smith <chris@jalakai.co.uk>
1127 * @author Andreas Gohr <andi@splitbrain.org>
1128 *
1129 * @return bool true on success, false on any error
1130 */
1131function act_resendpwd() {
1132    global $lang;
1133    global $conf;
1134    /* @var DokuWiki_Auth_Plugin $auth */
1135    global $auth;
1136    /* @var Input $INPUT */
1137    global $INPUT;
1138
1139    if(!actionOK('resendpwd')) {
1140        msg($lang['resendna'], -1);
1141        return false;
1142    }
1143
1144    $token = preg_replace('/[^a-f0-9]+/', '', $INPUT->str('pwauth'));
1145
1146    if($token) {
1147        // we're in token phase - get user info from token
1148
1149        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
1150        if(!@file_exists($tfile)) {
1151            msg($lang['resendpwdbadauth'], -1);
1152            $INPUT->remove('pwauth');
1153            return false;
1154        }
1155        // token is only valid for 3 days
1156        if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
1157            msg($lang['resendpwdbadauth'], -1);
1158            $INPUT->remove('pwauth');
1159            @unlink($tfile);
1160            return false;
1161        }
1162
1163        $user     = io_readfile($tfile);
1164        $userinfo = $auth->getUserData($user);
1165        if(!$userinfo['mail']) {
1166            msg($lang['resendpwdnouser'], -1);
1167            return false;
1168        }
1169
1170        if(!$conf['autopasswd']) { // we let the user choose a password
1171            $pass = $INPUT->str('pass');
1172
1173            // password given correctly?
1174            if(!$pass) return false;
1175            if($pass != $INPUT->str('passchk')) {
1176                msg($lang['regbadpass'], -1);
1177                return false;
1178            }
1179
1180            // change it
1181            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1182                msg('error modifying user data', -1);
1183                return false;
1184            }
1185
1186        } else { // autogenerate the password and send by mail
1187
1188            $pass = auth_pwgen($user);
1189            if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
1190                msg('error modifying user data', -1);
1191                return false;
1192            }
1193
1194            if(auth_sendPassword($user, $pass)) {
1195                msg($lang['resendpwdsuccess'], 1);
1196            } else {
1197                msg($lang['regmailfail'], -1);
1198            }
1199        }
1200
1201        @unlink($tfile);
1202        return true;
1203
1204    } else {
1205        // we're in request phase
1206
1207        if(!$INPUT->post->bool('save')) return false;
1208
1209        if(!$INPUT->post->str('login')) {
1210            msg($lang['resendpwdmissing'], -1);
1211            return false;
1212        } else {
1213            $user = trim($auth->cleanUser($INPUT->post->str('login')));
1214        }
1215
1216        $userinfo = $auth->getUserData($user);
1217        if(!$userinfo['mail']) {
1218            msg($lang['resendpwdnouser'], -1);
1219            return false;
1220        }
1221
1222        // generate auth token
1223        $token = md5(auth_randombytes(16)); // random secret
1224        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
1225        $url   = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
1226
1227        io_saveFile($tfile, $user);
1228
1229        $text = rawLocale('pwconfirm');
1230        $trep = array(
1231            'FULLNAME' => $userinfo['name'],
1232            'LOGIN'    => $user,
1233            'CONFIRM'  => $url
1234        );
1235
1236        $mail = new Mailer();
1237        $mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
1238        $mail->subject($lang['regpwmail']);
1239        $mail->setBody($text, $trep);
1240        if($mail->send()) {
1241            msg($lang['resendpwdconfirm'], 1);
1242        } else {
1243            msg($lang['regmailfail'], -1);
1244        }
1245        return true;
1246    }
1247    // never reached
1248}
1249
1250/**
1251 * Encrypts a password using the given method and salt
1252 *
1253 * If the selected method needs a salt and none was given, a random one
1254 * is chosen.
1255 *
1256 * @author  Andreas Gohr <andi@splitbrain.org>
1257 * @param string $clear The clear text password
1258 * @param string $method The hashing method
1259 * @param string $salt A salt, null for random
1260 * @return  string  The crypted password
1261 */
1262function auth_cryptPassword($clear, $method = '', $salt = null) {
1263    global $conf;
1264    if(empty($method)) $method = $conf['passcrypt'];
1265
1266    $pass = new PassHash();
1267    $call = 'hash_'.$method;
1268
1269    if(!method_exists($pass, $call)) {
1270        msg("Unsupported crypt method $method", -1);
1271        return false;
1272    }
1273
1274    return $pass->$call($clear, $salt);
1275}
1276
1277/**
1278 * Verifies a cleartext password against a crypted hash
1279 *
1280 * @author Andreas Gohr <andi@splitbrain.org>
1281 * @param  string $clear The clear text password
1282 * @param  string $crypt The hash to compare with
1283 * @return bool true if both match
1284 */
1285function auth_verifyPassword($clear, $crypt) {
1286    $pass = new PassHash();
1287    return $pass->verify_hash($clear, $crypt);
1288}
1289
1290/**
1291 * Set the authentication cookie and add user identification data to the session
1292 *
1293 * @param string  $user       username
1294 * @param string  $pass       encrypted password
1295 * @param bool    $sticky     whether or not the cookie will last beyond the session
1296 * @return bool
1297 */
1298function auth_setCookie($user, $pass, $sticky) {
1299    global $conf;
1300    /* @var DokuWiki_Auth_Plugin $auth */
1301    global $auth;
1302    global $USERINFO;
1303
1304    if(!$auth) return false;
1305    $USERINFO = $auth->getUserData($user);
1306
1307    // set cookie
1308    $cookie    = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1309    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1310    $time      = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
1311    if(version_compare(PHP_VERSION, '5.2.0', '>')) {
1312        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
1313    } else {
1314        setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1315    }
1316    // set session
1317    $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1318    $_SESSION[DOKU_COOKIE]['auth']['pass'] = sha1($pass);
1319    $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1320    $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1321    $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1322
1323    return true;
1324}
1325
1326/**
1327 * Returns the user, (encrypted) password and sticky bit from cookie
1328 *
1329 * @returns array
1330 */
1331function auth_getCookie() {
1332    if(!isset($_COOKIE[DOKU_COOKIE])) {
1333        return array(null, null, null);
1334    }
1335    list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
1336    $sticky = (bool) $sticky;
1337    $pass   = base64_decode($pass);
1338    $user   = base64_decode($user);
1339    return array($user, $sticky, $pass);
1340}
1341
1342//Setup VIM: ex: et ts=2 :
1343