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