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 7 commits into
base: master
Choose a base branch
from
6 changes: 5 additions & 1 deletion 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 @@ -141,7 +142,7 @@
// slash which is required by URL generation.
if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
substr($_SERVER['REQUEST_URI'], -1) !== '/') {
header('Location: '.\OC::$WEBROOT.'/');

Check failure on line 145 in lib/base.php

View workflow job for this annotation

GitHub Actions / static-code-analysis-security

TaintedHeader

lib/base.php:145:12: TaintedHeader: Detected tainted header (see https://psalm.dev/256)
exit();
}
}
Expand Down Expand Up @@ -223,7 +224,7 @@
throw new Exception('Not installed');
} else {
$url = OC::$WEBROOT . '/index.php';
header('Location: ' . $url);

Check failure on line 227 in lib/base.php

View workflow job for this annotation

GitHub Actions / static-code-analysis-security

TaintedHeader

lib/base.php:227:12: TaintedHeader: Detected tainted header (see https://psalm.dev/256)
}
exit();
}
Expand Down Expand Up @@ -361,6 +362,9 @@
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 Expand Up @@ -658,7 +662,7 @@
if (!function_exists('simplexml_load_file')) {
throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
}

OC_App::loadApps(['session']);
if (!self::$CLI) {
self::initSession();
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 @@ -1871,9 +1871,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 @@ -1904,9 +1904,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
107 changes: 107 additions & 0 deletions lib/private/Session/CryptoSessionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

declare(strict_types=1);

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

namespace OC\Session;

use Exception;
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 json_decode;
use function OCP\Log\logger;
use function session_decode;
use function session_encode;
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
*/
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
*/
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);
}

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];
}

}
4 changes: 2 additions & 2 deletions lib/private/Session/CryptoWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ public function __construct(IConfig $config,
* @return ISession
*/
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
3 changes: 2 additions & 1 deletion lib/private/Session/Internal.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,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