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