From 2ac93a3419a47b4254ed260df57b955df039f970 Mon Sep 17 00:00:00 2001 From: Robin Delattre Date: Sun, 11 Oct 2026 21:46:17 +0200 Subject: [PATCH 1/2] perf(crypto): reuse the key for consecutive operations Assisted-by: Codex:GPT-6 Signed-off-by: Robin Delattre --- lib/private/Security/Crypto.php | 26 +++++-- tests/lib/Security/CryptoTest.php | 123 ++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 8 deletions(-) diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index 8db44ecee00b6..821d20808fd3b 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -28,6 +28,7 @@ */ class Crypto implements ICrypto { private AES $cipher; + private ?string $cipherPasswordHash = null; private int $ivLength = 16; public function __construct( @@ -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); @@ -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) { @@ -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); diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php index 4c1035996fd70..536bd60516d0a 100644 --- a/tests/lib/Security/CryptoTest.php +++ b/tests/lib/Security/CryptoTest.php @@ -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 { @@ -129,4 +130,126 @@ 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')); + } + + 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; + } } From 2d5ebe97d79192d924136a6f4f6ff98f313f4317 Mon Sep 17 00:00:00 2001 From: Robin Delattre Date: Wed, 18 Nov 2026 20:56:31 +0100 Subject: [PATCH 2/2] test(crypto): cover key reuse boundaries and add a synthetic benchmark Make the repeated-field workload independently reproducible without accessing instance configuration or vault data, and cover malformed input and key/field boundaries. Assisted-by: Codex:GPT-6 Signed-off-by: Robin Delattre --- tests/benchmarks/README.md | 41 +++++++++++ tests/benchmarks/crypto.php | 112 ++++++++++++++++++++++++++++++ tests/lib/Security/CryptoTest.php | 34 +++++++++ 3 files changed, 187 insertions(+) create mode 100644 tests/benchmarks/README.md create mode 100644 tests/benchmarks/crypto.php diff --git a/tests/benchmarks/README.md b/tests/benchmarks/README.md new file mode 100644 index 0000000000000..08738523cf1e0 --- /dev/null +++ b/tests/benchmarks/README.md @@ -0,0 +1,41 @@ + + +# 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. diff --git a/tests/benchmarks/crypto.php b/tests/benchmarks/crypto.php new file mode 100644 index 0000000000000..ad8b5a739a44e --- /dev/null +++ b/tests/benchmarks/crypto.php @@ -0,0 +1,112 @@ +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); +} diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php index 536bd60516d0a..0ed823a2edf42 100644 --- a/tests/lib/Security/CryptoTest.php +++ b/tests/lib/Security/CryptoTest.php @@ -235,6 +235,40 @@ public function testLegacyEmptySecretFallbackCanReplaceTheCurrentKey(): void { $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);