Skip to content
26 changes: 21 additions & 5 deletions lib/private/Security/SecureRandom.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016-2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
Expand All @@ -13,17 +13,33 @@
use Random\Randomizer;

/**
* Class SecureRandom provides a wrapper around the random_int function to generate
* secure random strings. This use the native CSPRNG.
* Secure random string generator recommended for tokens, passwords, secrets, and similar security use cases.
*
* @see \OCP\Security\ISecureRandom
*/
class SecureRandom implements ISecureRandom {
#[\Override]
public function generate(
int $length,
string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
string $characters = ISecureRandom::CHAR_BASE64_RFC4648,
): string {
if ($length <= 0) {
throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
throw new \LengthException(
'Invalid length specified: ' . $length . ' must be greater than 0'
);
}

if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This turns input that has worked since 8.0 into an exception in a public API, e.g. overlapping concatenations like ISecureRandom::CHAR_ALPHANUMERIC . ISecureRandom::CHAR_DIGITS or small sets like '01'.

I agree duplicates are a bug (they skew the distribution), but for apps this is a hard break without notice. What do you think about deduplicating (count_chars($characters, 3)) or logging a deprecation for now, and throwing only in a later release? Either way it should go into the developer upgrade notes for 36.

// Check for ASCII-only (no multibyte characters)
!mb_check_encoding($characters, 'ASCII')
// Check for uniqueness: number of unique bytes must equal original length
|| strlen(count_chars($characters, 3)) !== strlen($characters)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This check rejects one of our own constants: ISecureRandom::CHAR_SYMBOLS is 34 bytes but has only 32 unique characters, because the single-quoted literal contains the backslash three times (\", \\ and [\] each leave one). So every generate($n, ISecureRandom::CHAR_SYMBOLS) throws now.

In server this breaks UsersController::addUser() in provisioning_api: when a user is created with an email but no password and no password_policy listener provides one, the fallback generate(1, ISecureRandom::CHAR_SYMBOLS) throws and the user is not created.

Could you fix the constant? Then it is exactly the 32 ASCII punctuation characters:

public const CHAR_SYMBOLS = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';

AbstractDatabase::generateDbPassword() then needs '"' instead of '\"' in its str_replace(), otherwise " ends up in generated database passwords.

// Check minimum length
|| strlen($characters) < 4
) {
throw new \InvalidArgumentException(
'Character set must be ASCII-only, unique, and at least four characters long.'
);
}

/** @var non-empty-string $result */
Expand Down
57 changes: 40 additions & 17 deletions lib/public/Security/ISecureRandom.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,23 @@
namespace OCP\Security;

/**
* Class SecureRandom provides a wrapper around the random_int function to generate
* secure random strings. For PHP 7 the native CSPRNG is used, older versions do
* use a fallback.
* Secure random string generator for tokens, passwords, secrets, and similar security use cases.
*
* Usage:
* \OCP\Server::get(ISecureRandom::class)->generate(10);
* Uses PHP's native CSPRNG through Random\Randomizer.
* @link https://www.php.net/manual/en/class.random-randomizer.php
*
* By default, uses the RFC 4648 Base64 alphabet for random string generation, and allows
* custom character sets if desired.
*
* Example usage:
* - Typical (if ISecureRandom $random is provided by DI):
* `$secret = $this->random->generate(48);`
* - Non-DI:
* `$secret = \OCP\Server::get(\OCP\Security\ISecureRandom::class)->generate(48);`
* @since 8.0.0
*/
interface ISecureRandom {
/**
* Flags for characters that can be used for <code>generate($length, $characters)</code>
* @since 8.0.0
*/
public const CHAR_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Expand All @@ -47,22 +52,40 @@ interface ISecureRandom {
public const CHAR_ALPHANUMERIC = self::CHAR_UPPER . self::CHAR_LOWER . self::CHAR_DIGITS;

/**
* Characters that can be used for <code>generate($length, $characters)</code>, to
* generate human-readable random strings. Lower- and upper-case characters and digits
* are included. Characters which are ambiguous are excluded, such as I, l, and 1 and so on.
*
* Lowercase, uppercase characters, and digits. Ambiguous characters are excluded (e.g., I, l, and 1).
* @since 23.0.0
*/
public const CHAR_HUMAN_READABLE = 'abcdefgijkmnopqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789';

/**
* Generate a random string of specified length.
* @param int $length The length of the generated string
* @param string $characters An optional list of characters to use if no character list is
* specified all valid base64 characters are used.
* @return non-empty-string
* Standard Base64 alphabet per RFC4648.
* @link https://datatracker.ietf.org/doc/html/rfc4648#section-4
* @since 36.0.0
*/
public const CHAR_BASE64_RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

/**
* Generate a secure random string of the specified length.
*
* Security notes:
* - For most secure applications (tokens, passwords, CSRF values), an ample and diverse
* character set, such as the default CHAR_BASE64_RFC4648, is typically a good choice.
* - Overly small (<4), non-unique, or multibyte character sets weaken security and are not permitted.
*
* @param int $length Number of characters (must be > 0).
* @param string $characters Optional list of unique, single-byte (ASCII) characters
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set should contain at least 4

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The implementation enforces the minimum, so this is a "must":

Suggested change
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set should contain at least 4
* to use. Defaults to the CHAR_BASE64_RFC4648 alphabet. A custom set must contain at least 4

Also "which all meet the requirements" only holds once CHAR_SYMBOLS is fixed, and not for concatenations of overlapping constants. Maybe worth mentioning that.

* characters, and must not contain duplicates or multibyte (non-ASCII) characters. It is strongly
* recommended to use predefined constants from ISecureRandom, which all meet the requirements.
* @return non-empty-string The randomly generated string.
* @throws \LengthException If $length <= 0.
* @throws \InvalidArgumentException if $characters contains non-ASCII characters, duplicates,
* or fewer than 4 unique characters.
* @since 36.0.0 $characters must be at least 4 characters long, ASCII-only and must not contain duplicates.
* @since 8.0.0
*/
public function generate(int $length,
string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string;
public function generate(
int $length,
string $characters = ISecureRandom::CHAR_BASE64_RFC4648,
): string;
}
55 changes: 52 additions & 3 deletions tests/lib/Security/SecureRandomTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ class SecureRandomTest extends \Test\TestCase {
public static function stringGenerationProvider(): array {
return [
[1, 1],
[16, 16],
[31, 31],
[64, 64],
[128, 128],
[256, 256],
[1024, 1024],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we keep one large length? Otherwise nothing covers long outputs anymore.

Suggested change
[1024, 1024],
[1024, 1024],
[64000, 64000],

[2048, 2048],
[64000, 64000],
];
}

Expand Down Expand Up @@ -82,4 +82,53 @@ public function testInvalidLengths($length): void {
$generator = $this->rng;
$generator->generate($length);
}

public static function invalidCharProviders(): array {
return [
'invalid_too_short' => ['abc'],
'invalid_duplicates' => ['aabcd'],
'invalid_non_ascii' => ["abcd\xf0"],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('invalidCharProviders')]
public function testInvalidCharacterSets(string $invalidCharset): void {
$this->expectException(\InvalidArgumentException::class);
$this->rng->generate(10, $invalidCharset);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please add a test that runs generate() with every predefined constant. It would have caught the CHAR_SYMBOLS issue (the mocked ISecureRandom in the provisioning_api tests cannot):

Suggested change
}
}
public static function predefinedCharsets(): array {
return [
['CHAR_UPPER'],
['CHAR_LOWER'],
['CHAR_DIGITS'],
['CHAR_SYMBOLS'],
['CHAR_ALPHANUMERIC'],
['CHAR_HUMAN_READABLE'],
['CHAR_BASE64_RFC4648'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('predefinedCharsets')]
public function testPredefinedCharsets(string $constant): void {
$charset = constant('OCP\Security\ISecureRandom::' . $constant);
$randomString = $this->rng->generate(100, $charset);
$this->assertSame(100, strlen($randomString));
$this->assertSame('', str_replace(str_split($charset), '', $randomString));
}


public function testDefaultCharsetBase64Characters(): void {
$randomString = $this->rng->generate(100);
$this->assertMatchesRegularExpression('/^[A-Za-z0-9\+\/]{100}$/', $randomString);
}

public function testAllOutputsAreUnique(): void {
// While collisions are technically possible, extremely unlikely for these sizes
$first = $this->rng->generate(1000);
$second = $this->rng->generate(1000);
$this->assertNotEquals($first, $second, 'Random output should not be repeated.');
}

public function testMinimumValidCharset(): void {
$charset = 'abcd';
$randomString = $this->rng->generate(500, $charset);
$this->assertMatchesRegularExpression('/^[abcd]{500}$/', $randomString);
}

public function testLargeCustomCharset(): void {
$charset = '';
for ($i = 32; $i <= 126; $i++) { // all printable ASCII
$charset .= chr($i);
}
$randomString = $this->rng->generate(200, $charset);
foreach (str_split($randomString) as $char) {
$this->assertStringContainsString($char, $charset);
}
}

public function testUserProvidedValidCharset(): void {
$charset = '@#$!';
$randomString = $this->rng->generate(64, $charset);
$this->assertMatchesRegularExpression('/^[@#$!]{64}$/', $randomString);
}
}
Loading