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 11 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
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
144 changes: 144 additions & 0 deletions lib/private/Session/CryptoSessionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?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 SessionHandler;
use function explode;
use function implode;
use function json_decode;
use function OCP\Log\logger;
use function session_decode;
use function session_encode;

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 IRequest $request) {
}

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

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

/**
* Read and decrypt session data
*
* The decryption passphrase is encoded in the id since Nextcloud 31. For
* backwards compatibility after upgrade we also read the pass phrase from
* the old cookie and try to restore session from the legacy format.
*
* @param string $id
*
* @return false|string
*/
public function read(string $id): false|string {
[$sessionId, $passphrase] = $this->parseId($id);

/**
* Legacy handling
*
* @TODO remove in Nextcloud 32
*/
if ($passphrase === null) {
if (($passphrase = $this->request->getCookie(CryptoWrapper::COOKIE_NAME)) === false) {
// No passphrase in the ID or an old cookie. Time to give up.
return false;
}

// Read the encrypted and encoded data
$serializedData = parent::read($sessionId);
if ($serializedData === '') {
// Nothing to decode or decrypt
return '';
}
// Back up the superglobal before we decode/restore the legacy session data
// This is necessary because session_decode populates the superglobals
// We restore the old state end the end (the final block, also run in
// case of an error)
$globalBackup = $_SESSION;
try {
if (!session_decode($serializedData)) {
// Bail if we can't decode the data
return false;
}
$encryptedData = $_SESSION['encrypted_session_data'];
try {
$sessionValues = json_decode(
$this->crypto->decrypt($encryptedData, $passphrase),
true,
512,
JSON_THROW_ON_ERROR,
);
foreach ($sessionValues as $key => $value) {
$_SESSION[$key] = $value;
}
} catch (Exception $e) {
logger('core')->critical('Could not decrypt or decode encrypted legacy session data', [
'exception' => $e,
'sessionId' => $sessionId,
]);
}
return session_encode();
} finally {
foreach (array_keys($_SESSION) as $key) {

Check failure on line 107 in lib/private/Session/CryptoSessionHandler.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

InvalidScalarArgument

lib/private/Session/CryptoSessionHandler.php:107:25: InvalidScalarArgument: Argument 1 of array_keys expects array<array-key, mixed>, but possibly undefined array<array-key, mixed> provided (see https://psalm.dev/012)
Fixed Show fixed Hide fixed
unset($_SESSION[$key]);
}
foreach ($globalBackup as $key => $value) {
$_SESSION[$key] = $value;
}
$_SESSION = $globalBackup;
}
}

$read = parent::read($sessionId);
return $read;
}

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

if ($passphrase === null) {
$passphrase = $this->request->getCookie(CryptoWrapper::COOKIE_NAME);
// return false;
}

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

public function close(): bool {

Check failure on line 140 in lib/private/Session/CryptoSessionHandler.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

InvalidReturnType

lib/private/Session/CryptoSessionHandler.php:140:27: InvalidReturnType: Not all code paths of OC\Session\CryptoSessionHandler::close end in a return statement, return type bool expected (see https://psalm.dev/011)
Fixed Show fixed Hide fixed
parent::close();
}

}
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
Loading
Loading