diff options
Diffstat (limited to 'lib/private/Session')
-rw-r--r-- | lib/private/Session/CryptoSessionData.php | 233 | ||||
-rw-r--r-- | lib/private/Session/CryptoWrapper.php | 80 | ||||
-rw-r--r-- | lib/private/Session/Internal.php | 231 | ||||
-rw-r--r-- | lib/private/Session/Memory.php | 88 | ||||
-rw-r--r-- | lib/private/Session/Session.php | 60 |
5 files changed, 692 insertions, 0 deletions
diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php new file mode 100644 index 00000000000..323253af534 --- /dev/null +++ b/lib/private/Session/CryptoSessionData.php @@ -0,0 +1,233 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ +namespace OC\Session; + +use OCP\ISession; +use OCP\Security\ICrypto; +use OCP\Session\Exceptions\SessionNotAvailableException; +use function json_decode; +use function OCP\Log\logger; + +/** + * Class CryptoSessionData + * + * @package OC\Session + * @template-implements \ArrayAccess<string,mixed> + */ +class CryptoSessionData implements \ArrayAccess, ISession { + /** @var ISession */ + protected $session; + /** @var \OCP\Security\ICrypto */ + protected $crypto; + /** @var string */ + protected $passphrase; + /** @var array */ + protected $sessionValues; + /** @var bool */ + protected $isModified = false; + public const encryptedSessionName = 'encrypted_session_data'; + + /** + * @param ISession $session + * @param ICrypto $crypto + * @param string $passphrase + */ + public function __construct(ISession $session, + ICrypto $crypto, + string $passphrase) { + $this->crypto = $crypto; + $this->session = $session; + $this->passphrase = $passphrase; + $this->initializeSession(); + } + + /** + * Close session if class gets destructed + */ + public function __destruct() { + try { + $this->close(); + } catch (SessionNotAvailableException $e) { + // This exception can occur if session is already closed + // So it is safe to ignore it and let the garbage collector to proceed + } + } + + protected function initializeSession() { + $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: ''; + if ($encryptedSessionData === '') { + // Nothing to decrypt + $this->sessionValues = []; + } else { + try { + $this->sessionValues = json_decode( + $this->crypto->decrypt($encryptedSessionData, $this->passphrase), + true, + 512, + JSON_THROW_ON_ERROR, + ); + } catch (\Exception $e) { + logger('core')->critical('Could not decrypt or decode encrypted session data', [ + 'exception' => $e, + ]); + $this->sessionValues = []; + $this->regenerateId(true, false); + } + } + } + + /** + * Set a value in the session + * + * @param string $key + * @param mixed $value + */ + public function set(string $key, $value) { + if ($this->get($key) === $value) { + // Do not write the session if the value hasn't changed to avoid reopening + return; + } + + $reopened = $this->reopen(); + $this->sessionValues[$key] = $value; + $this->isModified = true; + if ($reopened) { + $this->close(); + } + } + + /** + * Get a value from the session + * + * @param string $key + * @return string|null Either the value or null + */ + public function get(string $key) { + if (isset($this->sessionValues[$key])) { + return $this->sessionValues[$key]; + } + + return null; + } + + /** + * Check if a named key exists in the session + * + * @param string $key + * @return bool + */ + public function exists(string $key): bool { + return isset($this->sessionValues[$key]); + } + + /** + * Remove a $key/$value pair from the session + * + * @param string $key + */ + public function remove(string $key) { + $reopened = $this->reopen(); + $this->isModified = true; + unset($this->sessionValues[$key]); + if ($reopened) { + $this->close(); + } + } + + /** + * Reset and recreate the session + */ + public function clear() { + $reopened = $this->reopen(); + $requesttoken = $this->get('requesttoken'); + $this->sessionValues = []; + if ($requesttoken !== null) { + $this->set('requesttoken', $requesttoken); + } + $this->isModified = true; + $this->session->clear(); + if ($reopened) { + $this->close(); + } + } + + public function reopen(): bool { + $reopened = $this->session->reopen(); + if ($reopened) { + $this->initializeSession(); + } + return $reopened; + } + + /** + * Wrapper around session_regenerate_id + * + * @param bool $deleteOldSession Whether to delete the old associated session file or not. + * @param bool $updateToken Wheater to update the associated auth token + * @return void + */ + public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) { + $this->session->regenerateId($deleteOldSession, $updateToken); + } + + /** + * Wrapper around session_id + * + * @return string + * @throws SessionNotAvailableException + * @since 9.1.0 + */ + public function getId(): string { + return $this->session->getId(); + } + + /** + * Close the session and release the lock, also writes all changed data in batch + */ + public function close() { + if ($this->isModified) { + $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase); + $this->session->set(self::encryptedSessionName, $encryptedValue); + $this->isModified = false; + } + $this->session->close(); + } + + /** + * @param mixed $offset + * @return bool + */ + public function offsetExists($offset): bool { + return $this->exists($offset); + } + + /** + * @param mixed $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) { + return $this->get($offset); + } + + /** + * @param mixed $offset + * @param mixed $value + */ + public function offsetSet($offset, $value): void { + $this->set($offset, $value); + } + + /** + * @param mixed $offset + */ + public function offsetUnset($offset): void { + $this->remove($offset); + } +} diff --git a/lib/private/Session/CryptoWrapper.php b/lib/private/Session/CryptoWrapper.php new file mode 100644 index 00000000000..40c2ba6adf3 --- /dev/null +++ b/lib/private/Session/CryptoWrapper.php @@ -0,0 +1,80 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ + +namespace OC\Session; + +use OCP\IRequest; +use OCP\ISession; +use OCP\Security\ICrypto; +use OCP\Security\ISecureRandom; + +/** + * Class CryptoWrapper provides some rough basic level of additional security by + * storing the session data in an encrypted form. + * + * The content of the session is encrypted using another cookie sent by the browser. + * One should note that an adversary with access to the source code or the system + * memory is still able to read the original session ID from the users' request. + * This thus can not be considered a strong security measure one should consider + * it as an additional small security obfuscation layer to comply with compliance + * guidelines. + * + * TODO: Remove this in a future release with an approach such as + * https://github.com/owncloud/core/pull/17866 + * + * @package OC\Session + */ +class CryptoWrapper { + /** @var string */ + public const COOKIE_NAME = 'oc_sessionPassphrase'; + + protected string $passphrase; + + public function __construct( + protected ICrypto $crypto, + ISecureRandom $random, + IRequest $request, + ) { + $passphrase = $request->getCookie(self::COOKIE_NAME); + if ($passphrase === null) { + $passphrase = $random->generate(128); + $secureCookie = $request->getServerProtocol() === 'https'; + // FIXME: Required for CI + if (!defined('PHPUNIT_RUN')) { + $webRoot = \OC::$WEBROOT; + if ($webRoot === '') { + $webRoot = '/'; + } + + setcookie( + self::COOKIE_NAME, + $passphrase, + [ + 'expires' => 0, + 'path' => $webRoot, + 'domain' => \OCP\Server::get(\OCP\IConfig::class)->getSystemValueString('cookie_domain'), + 'secure' => $secureCookie, + 'httponly' => true, + 'samesite' => 'Lax', + ] + ); + } + } + $this->passphrase = $passphrase; + } + + public function wrapSession(ISession $session): ISession { + if (!($session instanceof CryptoSessionData)) { + return new CryptoSessionData($session, $this->crypto, $this->passphrase); + } + + return $session; + } +} diff --git a/lib/private/Session/Internal.php b/lib/private/Session/Internal.php new file mode 100644 index 00000000000..b465bcd3eda --- /dev/null +++ b/lib/private/Session/Internal.php @@ -0,0 +1,231 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ +namespace OC\Session; + +use OC\Authentication\Token\IProvider; +use OCP\Authentication\Exceptions\InvalidTokenException; +use OCP\ILogger; +use OCP\Session\Exceptions\SessionNotAvailableException; +use Psr\Log\LoggerInterface; +use function call_user_func_array; +use function microtime; + +/** + * Class Internal + * + * wrap php's internal session handling into the Session interface + * + * @package OC\Session + */ +class Internal extends Session { + /** + * @param string $name + * @throws \Exception + */ + public function __construct( + string $name, + private ?LoggerInterface $logger, + ) { + set_error_handler([$this, 'trapError']); + $this->invoke('session_name', [$name]); + $this->invoke('session_cache_limiter', ['']); + try { + $this->startSession(); + } catch (\Exception $e) { + setcookie($this->invoke('session_name'), '', -1, \OC::$WEBROOT ?: '/'); + } + restore_error_handler(); + if (!isset($_SESSION)) { + throw new \Exception('Failed to start session'); + } + } + + /** + * @param string $key + * @param integer $value + */ + public function set(string $key, $value) { + $reopened = $this->reopen(); + $_SESSION[$key] = $value; + if ($reopened) { + $this->close(); + } + } + + /** + * @param string $key + * @return mixed + */ + public function get(string $key) { + if (!$this->exists($key)) { + return null; + } + return $_SESSION[$key]; + } + + /** + * @param string $key + * @return bool + */ + public function exists(string $key): bool { + return isset($_SESSION[$key]); + } + + /** + * @param string $key + */ + public function remove(string $key) { + if (isset($_SESSION[$key])) { + unset($_SESSION[$key]); + } + } + + public function clear() { + $this->reopen(); + $this->invoke('session_unset'); + $this->regenerateId(); + $this->invoke('session_write_close'); + $this->startSession(true); + $_SESSION = []; + } + + public function close() { + $this->invoke('session_write_close'); + parent::close(); + } + + /** + * Wrapper around session_regenerate_id + * + * @param bool $deleteOldSession Whether to delete the old associated session file or not. + * @param bool $updateToken Whether to update the associated auth token + * @return void + */ + public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) { + $this->reopen(); + $oldId = null; + + if ($updateToken) { + // Get the old id to update the token + try { + $oldId = $this->getId(); + } catch (SessionNotAvailableException $e) { + // We can't update a token if there is no previous id + $updateToken = false; + } + } + + try { + @session_regenerate_id($deleteOldSession); + } catch (\Error $e) { + $this->trapError($e->getCode(), $e->getMessage()); + } + + if ($updateToken) { + // Get the new id to update the token + $newId = $this->getId(); + + /** @var IProvider $tokenProvider */ + $tokenProvider = \OCP\Server::get(IProvider::class); + + try { + $tokenProvider->renewSessionToken($oldId, $newId); + } catch (InvalidTokenException $e) { + // Just ignore + } + } + } + + /** + * Wrapper around session_id + * + * @return string + * @throws SessionNotAvailableException + * @since 9.1.0 + */ + public function getId(): string { + $id = $this->invoke('session_id', [], true); + if ($id === '') { + throw new SessionNotAvailableException(); + } + return $id; + } + + /** + * @throws \Exception + */ + public function reopen(): bool { + if ($this->sessionClosed) { + $this->startSession(false, false); + $this->sessionClosed = false; + return true; + } + + return false; + } + + /** + * @param int $errorNumber + * @param string $errorString + * @throws \ErrorException + */ + public function trapError(int $errorNumber, string $errorString) { + if ($errorNumber & E_ERROR) { + throw new \ErrorException($errorString); + } + } + + /** + * @param string $functionName the full session_* function name + * @param array $parameters + * @param bool $silence whether to suppress warnings + * @throws \ErrorException via trapError + * @return mixed + */ + private function invoke(string $functionName, array $parameters = [], bool $silence = false) { + try { + $timeBefore = microtime(true); + if ($silence) { + $result = @call_user_func_array($functionName, $parameters); + } else { + $result = call_user_func_array($functionName, $parameters); + } + $timeAfter = microtime(true); + $timeSpent = $timeAfter - $timeBefore; + if ($timeSpent > 0.1) { + $logLevel = match (true) { + $timeSpent > 25 => ILogger::ERROR, + $timeSpent > 10 => ILogger::WARN, + $timeSpent > 0.5 => ILogger::INFO, + default => ILogger::DEBUG, + }; + $this->logger?->log( + $logLevel, + "Slow session operation $functionName detected", + [ + 'parameters' => $parameters, + 'timeSpent' => $timeSpent, + ], + ); + } + return $result; + } catch (\Error $e) { + $this->trapError($e->getCode(), $e->getMessage()); + } + } + + private function startSession(bool $silence = false, bool $readAndClose = true) { + $sessionParams = ['cookie_samesite' => 'Lax']; + if (\OC::hasSessionRelaxedExpiry()) { + $sessionParams['read_and_close'] = $readAndClose; + } + $this->invoke('session_start', [$sessionParams], $silence); + } +} diff --git a/lib/private/Session/Memory.php b/lib/private/Session/Memory.php new file mode 100644 index 00000000000..395711836f5 --- /dev/null +++ b/lib/private/Session/Memory.php @@ -0,0 +1,88 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ +namespace OC\Session; + +use OCP\Session\Exceptions\SessionNotAvailableException; + +/** + * Class Internal + * + * store session data in an in-memory array, not persistent + * + * @package OC\Session + */ +class Memory extends Session { + protected $data; + + /** + * @param string $key + * @param integer $value + */ + public function set(string $key, $value) { + $this->data[$key] = $value; + } + + /** + * @param string $key + * @return mixed + */ + public function get(string $key) { + if (!$this->exists($key)) { + return null; + } + return $this->data[$key]; + } + + /** + * @param string $key + * @return bool + */ + public function exists(string $key): bool { + return isset($this->data[$key]); + } + + /** + * @param string $key + */ + public function remove(string $key) { + unset($this->data[$key]); + } + + public function clear() { + $this->data = []; + } + + /** + * Stub since the session ID does not need to get regenerated for the cache + * + * @param bool $deleteOldSession + */ + public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) { + } + + /** + * Wrapper around session_id + * + * @return string + * @throws SessionNotAvailableException + * @since 9.1.0 + */ + public function getId(): string { + throw new SessionNotAvailableException('Memory session does not have an ID'); + } + + /** + * Helper function for PHPUnit execution - don't use in non-test code + */ + public function reopen(): bool { + $reopened = $this->sessionClosed; + $this->sessionClosed = false; + return $reopened; + } +} diff --git a/lib/private/Session/Session.php b/lib/private/Session/Session.php new file mode 100644 index 00000000000..b7510b63683 --- /dev/null +++ b/lib/private/Session/Session.php @@ -0,0 +1,60 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ +namespace OC\Session; + +use OCP\ISession; + +/** + * @template-implements \ArrayAccess<string,mixed> + */ +abstract class Session implements \ArrayAccess, ISession { + /** + * @var bool + */ + protected $sessionClosed = false; + + /** + * @param mixed $offset + * @return bool + */ + public function offsetExists($offset): bool { + return $this->exists($offset); + } + + /** + * @param mixed $offset + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) { + return $this->get($offset); + } + + /** + * @param mixed $offset + * @param mixed $value + */ + public function offsetSet($offset, $value): void { + $this->set($offset, $value); + } + + /** + * @param mixed $offset + */ + public function offsetUnset($offset): void { + $this->remove($offset); + } + + /** + * Close the session and release the lock + */ + public function close() { + $this->sessionClosed = true; + } +} |