[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/inc/ -> auth.php (source)

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