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