[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> auth.php (source)

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