Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(session): Make session encryption more robust #47396

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/base.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
use OC\Encryption\HookManager;
use OC\Session\CryptoSessionHandler;
use OC\Share20\Hooks;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Group\Events\UserRemovedEvent;
Expand Down Expand Up @@ -363,6 +364,9 @@ private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
public static function initSession(): void {
$request = Server::get(IRequest::class);

$cryptoHandler = Server::get(CryptoSessionHandler::class);
session_set_save_handler($cryptoHandler, true);

// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
// TODO: for further information.
Expand Down
3 changes: 2 additions & 1 deletion lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1905,9 +1905,10 @@
'OC\\ServerContainer' => $baseDir . '/lib/private/ServerContainer.php',
'OC\\ServerNotAvailableException' => $baseDir . '/lib/private/ServerNotAvailableException.php',
'OC\\ServiceUnavailableException' => $baseDir . '/lib/private/ServiceUnavailableException.php',
'OC\\Session\\CryptoSessionData' => $baseDir . '/lib/private/Session/CryptoSessionData.php',
'OC\\Session\\CryptoSessionHandler' => $baseDir . '/lib/private/Session/CryptoSessionHandler.php',
'OC\\Session\\CryptoWrapper' => $baseDir . '/lib/private/Session/CryptoWrapper.php',
'OC\\Session\\Internal' => $baseDir . '/lib/private/Session/Internal.php',
'OC\\Session\\LegacyCryptoSessionData' => $baseDir . '/lib/private/Session/LegacyCryptoSessionData.php',
'OC\\Session\\Memory' => $baseDir . '/lib/private/Session/Memory.php',
'OC\\Session\\Session' => $baseDir . '/lib/private/Session/Session.php',
'OC\\Settings\\AuthorizedGroup' => $baseDir . '/lib/private/Settings/AuthorizedGroup.php',
Expand Down
3 changes: 2 additions & 1 deletion lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1938,9 +1938,10 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\ServerContainer' => __DIR__ . '/../../..' . '/lib/private/ServerContainer.php',
'OC\\ServerNotAvailableException' => __DIR__ . '/../../..' . '/lib/private/ServerNotAvailableException.php',
'OC\\ServiceUnavailableException' => __DIR__ . '/../../..' . '/lib/private/ServiceUnavailableException.php',
'OC\\Session\\CryptoSessionData' => __DIR__ . '/../../..' . '/lib/private/Session/CryptoSessionData.php',
'OC\\Session\\CryptoSessionHandler' => __DIR__ . '/../../..' . '/lib/private/Session/CryptoSessionHandler.php',
'OC\\Session\\CryptoWrapper' => __DIR__ . '/../../..' . '/lib/private/Session/CryptoWrapper.php',
'OC\\Session\\Internal' => __DIR__ . '/../../..' . '/lib/private/Session/Internal.php',
'OC\\Session\\LegacyCryptoSessionData' => __DIR__ . '/../../..' . '/lib/private/Session/LegacyCryptoSessionData.php',
'OC\\Session\\Memory' => __DIR__ . '/../../..' . '/lib/private/Session/Memory.php',
'OC\\Session\\Session' => __DIR__ . '/../../..' . '/lib/private/Session/Session.php',
'OC\\Settings\\AuthorizedGroup' => __DIR__ . '/../../..' . '/lib/private/Settings/AuthorizedGroup.php',
Expand Down
111 changes: 111 additions & 0 deletions lib/private/Session/CryptoSessionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/

namespace OC\Session;

use OCP\IRequest;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
use SessionHandler;
use function explode;
use function implode;
use function strlen;

class CryptoSessionHandler extends SessionHandler {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately writing unit tests is not an option for a session handler because PHP sessions have so many side effects. E.g. an actual session has to be opened to test read/write, but you can't close and re-open the session because opening a session sets a header, and setting headers is not possible once any kind of output was written 🫠


public function __construct(private ISecureRandom $secureRandom,
private ICrypto $crypto,
private LoggerInterface $logger,
private IRequest $request) {
}

public function create_sid(): string {
$id = parent::create_sid();
$passphrase = $this->secureRandom->generate(128);
return implode('|', [$id, $passphrase]);
}

/**
* Read and decrypt session data
*
* @param string $id
*
* @return false|string
*
* @codeCoverageIgnore
*/
public function read(string $id): false|string {
[$sessionId, $passphrase] = self::parseId($id);
if ($passphrase === null) {
$passphrase = $this->request->getCookie(CryptoWrapper::COOKIE_NAME);
if ($passphrase === null) {
$this->logger->debug('Reading unencrypted session data', [
'sessionId' => $id,
]);
return parent::read($sessionId);
}
}

$encryptedData = parent::read($sessionId);
if ($encryptedData === '') {
return '';
}
return $this->crypto->decrypt($encryptedData, $passphrase);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: catch decryption error, log and continue with empty session data

}

/**
* Encrypt and write session data
*
* @param string $id
* @param string $data
*
* @return bool
*
* @codeCoverageIgnore
*/
public function write(string $id, string $data): bool {
[$sessionId, $passphrase] = self::parseId($id);

if ($passphrase === null) {
$passphrase = $this->request->getCookie(CryptoWrapper::COOKIE_NAME);
if ($passphrase === null) {
$this->logger->warning('Can not write session because there is no passphrase', [
'sessionId' => $id,
'dataLength' => strlen($data),
]);
return false;
}
}

$encryptedData = $this->crypto->encrypt($data, $passphrase);

return parent::write($sessionId, $encryptedData);
}

/**
* @return bool
*
* @codeCoverageIgnore
*/
public function close(): bool {
Fixed Show fixed Hide fixed
return parent::close();
}

/**
* @param string $id
*
* @return array{0: string, 1: ?string}
*/
public static function parseId(string $id): array {
$parts = explode('|', $id, 2);
return [$parts[0], $parts[1] ?? null];
}

}
31 changes: 8 additions & 23 deletions lib/private/Session/CryptoWrapper.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
Expand Down Expand Up @@ -28,8 +30,10 @@
* https://github.com/owncloud/core/pull/17866
*
* @package OC\Session
* @deprecated
*/
class CryptoWrapper {
/** @deprecated 31.0.0 */
public const COOKIE_NAME = 'oc_sessionPassphrase';

/** @var IConfig */
Expand All @@ -48,6 +52,7 @@ class CryptoWrapper {
* @param ICrypto $crypto
* @param ISecureRandom $random
* @param IRequest $request
* @depreacted 31.0.0
*/
public function __construct(IConfig $config,
ICrypto $crypto,
Expand All @@ -61,37 +66,17 @@ public function __construct(IConfig $config,
$this->passphrase = $request->getCookie(self::COOKIE_NAME);
} else {
$this->passphrase = $this->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,
$this->passphrase,
[
'expires' => 0,
'path' => $webRoot,
'domain' => '',
'secure' => $secureCookie,
'httponly' => true,
'samesite' => 'Lax',
]
);
}
}
}

/**
* @param ISession $session
* @return ISession
* @deprecated 31.0.0
*/
public function wrapSession(ISession $session) {
if (!($session instanceof CryptoSessionData)) {
return new CryptoSessionData($session, $this->crypto, $this->passphrase);
if (!($session instanceof LegacyCryptoSessionData)) {
return new LegacyCryptoSessionData($session, $this->crypto, $this->passphrase);
}

return $session;
Expand Down
4 changes: 3 additions & 1 deletion lib/private/Session/Internal.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use OC\Authentication\Token\IProvider;
use OCP\Authentication\Exceptions\InvalidTokenException;
use OCP\IConfig;
use OCP\ILogger;
use OCP\Session\Exceptions\SessionNotAvailableException;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -155,7 +156,8 @@ public function getId(): string {
if ($id === '') {
throw new SessionNotAvailableException();
}
return $id;
// Only return the ID part, not the passphrase
return CryptoSessionHandler::parseId($id)[0];
}

/**
Expand Down
Loading
Loading