Skip to content
Open
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
26 changes: 18 additions & 8 deletions lib/private/Security/Crypto.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
*/
class Crypto implements ICrypto {
private AES $cipher;
private ?string $cipherPasswordHash = null;
private int $ivLength = 16;

public function __construct(
Expand Down Expand Up @@ -77,11 +78,7 @@ public function encrypt(
$password = $this->config->getSystemValueString('secret');
}
$keyMaterial = hash_hkdf('sha512', $password);
// Pin the PBKDF2 parameters to phpseclib v2 defaults ('sha1' hash, 'phpseclib' salt).
// phpseclib v3 changed the default salt to 'phpseclib/salt', which would derive a
// different AES key and break decryption of previously stored ciphertexts.
// TODO: We should put our own salt into the HKDF derivation to avoid this dependency on phpseclib's defaults!
$this->cipher->setPassword(substr($keyMaterial, 0, 32), 'pbkdf2', 'sha1', 'phpseclib');
$this->setCipherPassword(substr($keyMaterial, 0, 32));

$iv = \random_bytes($this->ivLength);
$this->cipher->setIV($iv);
Expand Down Expand Up @@ -176,9 +173,7 @@ private function decryptWithoutSecret(string $authenticatedCiphertext, string $p
$hmacKey = substr($keyMaterial, 32);
}
}
// Match the v2-compatible PBKDF2 parameters used in encrypt(), see the note there.
// TODO: We should put our own salt into the HKDF derivation to avoid this dependency on phpseclib's defaults!
$this->cipher->setPassword($encryptionKey, 'pbkdf2', 'sha1', 'phpseclib');
$this->setCipherPassword($encryptionKey);
$this->cipher->setIV($iv);

if ($isOwnCloudV2Migration) {
Expand All @@ -200,6 +195,21 @@ private function decryptWithoutSecret(string $authenticatedCiphertext, string $p
return $result;
}

private function setCipherPassword(#[SensitiveParameter] string $password): void {
// Keep only one fingerprint; the derived key remains in the cipher.
$passwordHash = hash('sha256', $password, true);
if ($this->cipherPasswordHash !== null && hash_equals($this->cipherPasswordHash, $passwordHash)) {
return;
}

// Pin the PBKDF2 parameters to phpseclib v2 defaults ('sha1' hash, 'phpseclib' salt).
// phpseclib v3 changed the default salt to 'phpseclib/salt', which would derive a
// different AES key and break decryption of previously stored ciphertexts.
// TODO: We should put our own salt into the HKDF derivation to avoid this dependency on phpseclib's defaults!
$this->cipher->setPassword($password, 'pbkdf2', 'sha1', 'phpseclib');
$this->cipherPasswordHash = $passwordHash;
}

private function hex2bin(string $hex): string {
if (!ctype_xdigit($hex)) {
throw new \RuntimeException('String contains non hex chars: ' . $hex);
Expand Down
41 changes: 41 additions & 0 deletions tests/benchmarks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!--
SPDX-FileCopyrightText: 2026 Nextcloud contributors
SPDX-License-Identifier: AGPL-3.0-or-later
-->

# Crypto key-derivation benchmark

The Passwords app decrypts six fields consecutively with the same key material.
This benchmark measures that workload using only synthetic keys and fields.
It verifies every decrypted value, counts `AES::setPassword()` calls and reports
three runs for 1, 100 and 344 revisions.

The script loads the source autoloaders, not `lib/base.php` or instance
configuration. Its configuration stub never calls the parent constructor and
returns only the supplied defaults. It does not access a database, vault or
network, and prints no keys, ciphertexts or plaintexts. Fixture creation is
outside the measured section; each run uses a fresh reader.

From a checkout with its pinned `3rdparty` submodule initialized:

```sh
php tests/benchmarks/crypto.php
```

To compare an earlier implementation while keeping dependencies identical,
extract its public source and run each implementation in a separate process:

```sh
git show 25900f62b68ae912780116ba8879d014ba2602ba:lib/private/Security/Crypto.php > /tmp/Crypto.before.php
php tests/benchmarks/crypto.php . /tmp/Crypto.before.php
php tests/benchmarks/crypto.php
```

Only pass trusted PHP source to the optional second argument. Neither command
changes the checkout's runtime files. JSON includes the loaded source's SHA-256
so results can be matched to the implementation.

For 344 revisions with six fields, the original derives 2,064 keys; the proposed
implementation derives 344. Durations depend on PHP, CPU and system load. This
benchmark does not measure HTTP, SQL or browser rendering; there is no timing
threshold in the unit tests.
112 changes: 112 additions & 0 deletions tests/benchmarks/crypto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

use OC\AllConfig;
use OC\Security\Crypto;
use phpseclib3\Crypt\AES;

// CLI only: no instance bootstrap, database, configuration or vault data.
if (PHP_SAPI !== 'cli') {
exit(1);
}

error_reporting(0);
ob_start();

/** @return array{Crypto, AES} */
function createSyntheticCrypto(): array {
$config = new class extends AllConfig {
public function __construct() {
}

public function getSystemValue($key, $default = '') {
return $default;
}

public function getSystemValueString(string $key, string $default = ''): string {
return $default;
}
};
$cipher = new class('cbc') extends AES {
public int $calls = 0;
public float $seconds = 0;

public function setPassword($password, $method = 'pbkdf2', ...$arguments) {
$start = hrtime(true);
$result = parent::setPassword($password, $method, ...$arguments);
$this->seconds += (hrtime(true) - $start) / 1e9;
$this->calls++;
return $result;
}
};
$crypto = new Crypto($config);
(new ReflectionProperty(Crypto::class, 'cipher'))->setValue($crypto, $cipher);
return [$crypto, $cipher];
}

try {
$root = realpath($argv[1] ?? dirname(__DIR__, 2));
$source = realpath($argv[2] ?? $root . '/lib/private/Security/Crypto.php');
if ($root === false || $source === false || !is_file($source)
|| !is_file($root . '/lib/composer/autoload.php')
|| !is_file($root . '/3rdparty/autoload.php')) {
throw new RuntimeException('Nextcloud sources and third-party dependencies are required');
}
require_once $root . '/lib/composer/autoload.php';
require_once $root . '/3rdparty/autoload.php';
require_once $source;

$report = [
'php_version' => PHP_VERSION,
'crypto_sha256' => hash_file('sha256', $source),
'data' => 'synthetic only',
'fields_per_revision' => 6,
'samples' => [],
];
[$writer] = createSyntheticCrypto();
foreach ([1, 100, 344] as $count) {
$fixtures = [];
for ($revision = 0; $revision < $count; $revision++) {
$key = str_repeat('Synthetic key material / ', 128) . $revision;
$fields = [];
for ($field = 0; $field < 6; $field++) {
$fields[] = $writer->encrypt('Synthetic field ' . $field, $key);
}
$fixtures[] = [$key, $fields];
}

$runs = [];
for ($round = 0; $round < 3; $round++) {
[$reader, $cipher] = createSyntheticCrypto();
$start = hrtime(true);
foreach ($fixtures as [$key, $fields]) {
foreach ($fields as $field => $value) {
if ($reader->decrypt($value, $key) !== 'Synthetic field ' . $field) {
throw new RuntimeException('Fixture mismatch');
}
}
}
$runs[] = [
'wall_ms' => round((hrtime(true) - $start) / 1e6, 2),
'set_password_calls' => $cipher->calls,
'set_password_ms' => round($cipher->seconds * 1000, 2),
];
}
$report['samples'][] = ['revisions' => $count, 'runs' => $runs];
}
$report['fixture_comparisons_passed'] = true;
ob_end_clean();
echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . "\n";
} catch (Throwable) {
while (ob_get_level()) {
ob_end_clean();
}
echo json_encode(['error' => 'benchmark_failed']) . "\n";
exit(1);
}
157 changes: 157 additions & 0 deletions tests/lib/Security/CryptoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use OC\Security\Crypto;
use OCP\IConfig;
use OCP\Server;
use phpseclib3\Crypt\AES;

class CryptoTest extends \Test\TestCase {
public static function defaultEncryptionProvider(): array {
Expand Down Expand Up @@ -129,4 +130,160 @@ public function testVersion3CiphertextDecryptsToCorrectPlaintext(): void {
)
);
}

public static function consecutivePasswordProvider(): array {
return [[''], ['explicit-password']];
}

#[\PHPUnit\Framework\Attributes\DataProvider('consecutivePasswordProvider')]
public function testDecryptConsecutiveFieldsDerivesKeyOnce(string $password): void {
$writer = $this->createCryptoWithDerivationCount(1);
$ciphertexts = [];
for ($field = 0; $field < 6; $field++) {
$ciphertexts[] = $writer->encrypt('field ' . $field, $password);
}

$reader = $this->createCryptoWithDerivationCount(1);
foreach ($ciphertexts as $field => $ciphertext) {
$this->assertSame('field ' . $field, $reader->decrypt($ciphertext, $password));
}
}

public function testAlternatingPasswordsDeriveAgain(): void {
$first = $this->crypto->encrypt('first', 'password-A');
$second = $this->crypto->encrypt('second', 'password-B');
$reader = $this->createCryptoWithDerivationCount(3);

$this->assertSame('first', $reader->decrypt($first, 'password-A'));
$this->assertSame('second', $reader->decrypt($second, 'password-B'));
$this->assertSame('first', $reader->decrypt($first, 'password-A'));
}

public function testAlternatingEncryptDecryptKeepsCurrentKeyAndRefreshesIv(): void {
$crypto = $this->createCryptoWithDerivationCount(1);
$ivs = [];
for ($field = 0; $field < 6; $field++) {
$ciphertext = $crypto->encrypt('same plaintext', 'same-password');
$ivs[] = explode('|', $ciphertext)[1];
$this->assertSame('same plaintext', $crypto->decrypt($ciphertext, 'same-password'));
}
$this->assertCount(6, array_unique($ivs));
}

public function testLegacyAndVersion3DeriveDifferentKeys(): void {
$legacy = 'e16599188e3d212f5c7f17fdc2abca46|M1WfLAxbcAmITeD6|509457885d6ca5e6c3bfd3741852687a7f2bffce197f8d5ae97b65818b15a1b7f616b68326ff312371540f4ca8ac55f8e2de4aa13aab3474bd3431e51214e3ee';
$current = $this->crypto->encrypt('current', 'mypass');
$reader = $this->createCryptoWithDerivationCount(3);

$this->assertSame('current', $reader->decrypt($current, 'mypass'));
$this->assertSame('legacy test', $reader->decrypt($legacy, 'mypass'));
$this->assertSame('current', $reader->decrypt($current, 'mypass'));
}

public function testReusedKeyStillRejectsTamperedCiphertextIvAndHmac(): void {
$ciphertext = $this->crypto->encrypt('plaintext', 'password');
$reader = $this->createCryptoWithDerivationCount(1);
$this->assertSame('plaintext', $reader->decrypt($ciphertext, 'password'));

foreach ([0, 1, 2] as $part) {
$parts = explode('|', $ciphertext);
$parts[$part][0] = $parts[$part][0] === '0' ? '1' : '0';
try {
$reader->decrypt(implode('|', $parts), 'password');
$this->fail('Tampered ciphertext was accepted');
} catch (\RuntimeException $e) {
$this->assertSame('HMAC does not match.', $e->getMessage());
}
$this->assertSame('plaintext', $reader->decrypt($ciphertext, 'password'));
}
}

public function testWrongPasswordDoesNotPoisonKeyReuse(): void {
$ciphertext = $this->crypto->encrypt('plaintext', 'password');
$reader = $this->createCryptoWithDerivationCount(3);
$this->assertSame('plaintext', $reader->decrypt($ciphertext, 'password'));
try {
$reader->decrypt($ciphertext, 'wrong-password');
$this->fail('Wrong password was accepted');
} catch (\RuntimeException $e) {
$this->assertSame('HMAC does not match.', $e->getMessage());
}
$this->assertSame('plaintext', $reader->decrypt($ciphertext, 'password'));
}

public function testChangedDefaultSecretDerivesAgain(): void {
$first = $this->crypto->encrypt('first', 'secret-A');
$second = $this->crypto->encrypt('second', 'secret-B');
$config = $this->createMock(IConfig::class);
$config->method('getSystemValue')->with('secret')->willReturnOnConsecutiveCalls('secret-A', 'secret-B');
$reader = $this->createCryptoWithDerivationCount(2, $config);

$this->assertSame('first', $reader->decrypt($first));
$this->assertSame('second', $reader->decrypt($second));
}

public function testLegacyEmptySecretFallbackCanReplaceTheCurrentKey(): void {
$reader = $this->createCryptoWithDerivationCount(2);
$cipher = new AES('cbc');
$cipher->setPassword('', 'pbkdf2', 'sha1', 'phpseclib');
$iv = str_repeat("\0", 16);
$cipher->setIV($iv);
$ciphertext = bin2hex($cipher->encrypt('empty-key fixture'));
$iv = bin2hex($iv);
$hmac = bin2hex($reader->calculateHMAC($ciphertext . $iv, 'configured-secret'));

$this->assertSame('empty-key fixture', $reader->decrypt($ciphertext . '|' . $iv . '|' . $hmac . '|2'));
}

public function testKeyReusePreservesBoundaryValuesAcrossKeyChanges(): void {
$plaintexts = ['', "\0", str_repeat('x', 16), str_repeat('y', 17), 'Français 日本語', str_repeat("\0\xff", 512)];
$passwords = ['', 'A', 'B', 'A', str_repeat('same-prefix', 100) . 'a', str_repeat('same-prefix', 100) . 'b', str_repeat("\0\xfe", 32)];
$writer = $this->createCryptoWithDerivationCount(count($passwords));
$reader = $this->createCryptoWithDerivationCount(count($passwords));

foreach ($passwords as $password) {
foreach ($plaintexts as $plaintext) {
$first = $writer->encrypt($plaintext, $password);
$second = $reader->encrypt($plaintext, $password);
$this->assertSame($plaintext, $reader->decrypt($first, $password));
$this->assertSame($plaintext, $writer->decrypt($second, $password));
$this->assertSame($plaintext, $reader->decrypt($first, $password));
$this->assertSame('3', explode('|', $second)[3]);
$this->assertNotSame(explode('|', $first)[1], explode('|', $second)[1]);
}
}
}

public function testMalformedInputDoesNotPoisonKeyReuse(): void {
$ciphertext = $this->crypto->encrypt('synthetic plaintext', 'key');
$reader = $this->createCryptoWithDerivationCount(1);
foreach (['', '1|2', 'gg|00|00|3', '0|00|00|3', '00|00|00|3|extra'] as $malformed) {
$rejected = false;
try {
$reader->decrypt($malformed, 'key');
} catch (\Exception) {
$rejected = true;
}
$this->assertTrue($rejected, 'Malformed input accepted');
$this->assertSame('synthetic plaintext', $reader->decrypt($ciphertext, 'key'));
}
}

private function createCryptoWithDerivationCount(int $count, ?IConfig $config = null): Crypto {
if ($config === null) {
$config = $this->createMock(IConfig::class);
$config->method('getSystemValue')->with('secret')->willReturn('configured-secret');
$config->method('getSystemValueString')->with('secret')->willReturn('configured-secret');
}
$crypto = new Crypto($config);
$cipher = $this->getMockBuilder(AES::class)
->setConstructorArgs(['cbc'])
->onlyMethods(['setPassword'])
->getMock();
$cipher->expects($this->exactly($count))
->method('setPassword')
->willReturnCallback(fn (...$parameters) => (new \ReflectionMethod(AES::class, 'setPassword'))->invokeArgs($cipher, $parameters));
$this->invokePrivate($crypto, 'cipher', [$cipher]);
return $crypto;
}
}