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