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