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