aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Security
diff options
context:
space:
mode:
Diffstat (limited to 'lib/private/Security')
-rw-r--r--lib/private/Security/Bruteforce/Throttler.php112
-rw-r--r--lib/private/Security/Hasher.php8
-rw-r--r--lib/private/Security/IdentityProof/Manager.php26
-rw-r--r--lib/private/Security/Ip/BruteforceAllowList.php57
-rw-r--r--lib/private/Security/Normalizer/IpAddress.php28
-rw-r--r--lib/private/Security/RateLimiting/Limiter.php7
-rw-r--r--lib/private/Security/Signature/Model/SignedRequest.php4
-rw-r--r--lib/private/Security/VerificationToken/VerificationToken.php6
8 files changed, 149 insertions, 99 deletions
diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php
index 924ae3685f3..574f6c80c3f 100644
--- a/lib/private/Security/Bruteforce/Throttler.php
+++ b/lib/private/Security/Bruteforce/Throttler.php
@@ -9,6 +9,7 @@ declare(strict_types=1);
namespace OC\Security\Bruteforce;
use OC\Security\Bruteforce\Backend\IBackend;
+use OC\Security\Ip\BruteforceAllowList;
use OC\Security\Normalizer\IpAddress;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
@@ -32,14 +33,13 @@ use Psr\Log\LoggerInterface;
class Throttler implements IThrottler {
/** @var bool[] */
private array $hasAttemptsDeleted = [];
- /** @var bool[] */
- private array $ipIsWhitelisted = [];
public function __construct(
private ITimeFactory $timeFactory,
private LoggerInterface $logger,
private IConfig $config,
private IBackend $backend,
+ private BruteforceAllowList $allowList,
) {
}
@@ -83,70 +83,7 @@ class Throttler implements IThrottler {
* Check if the IP is whitelisted
*/
public function isBypassListed(string $ip): bool {
- if (isset($this->ipIsWhitelisted[$ip])) {
- return $this->ipIsWhitelisted[$ip];
- }
-
- if (!$this->config->getSystemValueBool('auth.bruteforce.protection.enabled', true)) {
- $this->ipIsWhitelisted[$ip] = true;
- return true;
- }
-
- $keys = $this->config->getAppKeys('bruteForce');
- $keys = array_filter($keys, function ($key) {
- return str_starts_with($key, 'whitelist_');
- });
-
- if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
- $type = 4;
- } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
- $type = 6;
- } else {
- $this->ipIsWhitelisted[$ip] = false;
- return false;
- }
-
- $ip = inet_pton($ip);
-
- foreach ($keys as $key) {
- $cidr = $this->config->getAppValue('bruteForce', $key, null);
-
- $cx = explode('/', $cidr);
- $addr = $cx[0];
- $mask = (int)$cx[1];
-
- // Do not compare ipv4 to ipv6
- if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ||
- ($type === 6 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
- continue;
- }
-
- $addr = inet_pton($addr);
-
- $valid = true;
- for ($i = 0; $i < $mask; $i++) {
- $part = ord($addr[(int)($i / 8)]);
- $orig = ord($ip[(int)($i / 8)]);
-
- $bitmask = 1 << (7 - ($i % 8));
-
- $part = $part & $bitmask;
- $orig = $orig & $bitmask;
-
- if ($part !== $orig) {
- $valid = false;
- break;
- }
- }
-
- if ($valid === true) {
- $this->ipIsWhitelisted[$ip] = true;
- return true;
- }
- }
-
- $this->ipIsWhitelisted[$ip] = false;
- return false;
+ return $this->allowList->isBypassListed($ip);
}
/**
@@ -190,6 +127,13 @@ class Throttler implements IThrottler {
*/
public function getDelay(string $ip, string $action = ''): int {
$attempts = $this->getAttempts($ip, $action);
+ return $this->calculateDelay($attempts);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public function calculateDelay(int $attempts): int {
if ($attempts === 0) {
return 0;
}
@@ -262,25 +206,31 @@ class Throttler implements IThrottler {
* {@inheritDoc}
*/
public function sleepDelayOrThrowOnMax(string $ip, string $action = ''): int {
- $delay = $this->getDelay($ip, $action);
- if (($delay === self::MAX_DELAY_MS) && $this->getAttempts($ip, $action, 0.5) > $this->config->getSystemValueInt('auth.bruteforce.max-attempts', self::MAX_ATTEMPTS)) {
- $this->logger->info('IP address blocked because it reached the maximum failed attempts in the last 30 minutes [action: {action}, ip: {ip}]', [
- 'action' => $action,
- 'ip' => $ip,
- ]);
- // If the ip made too many attempts within the last 30 mins we don't execute anymore
- throw new MaxDelayReached('Reached maximum delay');
- }
- if ($delay > 100) {
- $this->logger->info('IP address throttled because it reached the attempts limit in the last 30 minutes [action: {action}, delay: {delay}, ip: {ip}]', [
+ $maxAttempts = $this->config->getSystemValueInt('auth.bruteforce.max-attempts', self::MAX_ATTEMPTS);
+ $attempts = $this->getAttempts($ip, $action);
+ if ($attempts > $maxAttempts) {
+ $attempts30mins = $this->getAttempts($ip, $action, 0.5);
+ if ($attempts30mins > $maxAttempts) {
+ $this->logger->info('IP address blocked because it reached the maximum failed attempts in the last 30 minutes [action: {action}, attempts: {attempts}, ip: {ip}]', [
+ 'action' => $action,
+ 'ip' => $ip,
+ 'attempts' => $attempts30mins,
+ ]);
+ // If the ip made too many attempts within the last 30 mins we don't execute anymore
+ throw new MaxDelayReached('Reached maximum delay');
+ }
+
+ $this->logger->info('IP address throttled because it reached the attempts limit in the last 12 hours [action: {action}, attempts: {attempts}, ip: {ip}]', [
'action' => $action,
'ip' => $ip,
- 'delay' => $delay,
+ 'attempts' => $attempts,
]);
}
- if (!$this->config->getSystemValueBool('auth.bruteforce.protection.testing')) {
- usleep($delay * 1000);
+
+ if ($attempts > 0) {
+ return $this->calculateDelay($attempts);
}
- return $delay;
+
+ return 0;
}
}
diff --git a/lib/private/Security/Hasher.php b/lib/private/Security/Hasher.php
index ba661f5a356..722fdab902f 100644
--- a/lib/private/Security/Hasher.php
+++ b/lib/private/Security/Hasher.php
@@ -106,8 +106,8 @@ class Hasher implements IHasher {
// Verify whether it matches a legacy PHPass or SHA1 string
$hashLength = \strlen($hash);
- if (($hashLength === 60 && password_verify($message . $this->legacySalt, $hash)) ||
- ($hashLength === 40 && hash_equals($hash, sha1($message)))) {
+ if (($hashLength === 60 && password_verify($message . $this->legacySalt, $hash))
+ || ($hashLength === 40 && hash_equals($hash, sha1($message)))) {
$newHash = $this->hash($message);
return true;
}
@@ -115,8 +115,8 @@ class Hasher implements IHasher {
// Verify whether it matches a legacy PHPass or SHA1 string
// Retry with empty passwordsalt for cases where it was not set
$hashLength = \strlen($hash);
- if (($hashLength === 60 && password_verify($message, $hash)) ||
- ($hashLength === 40 && hash_equals($hash, sha1($message)))) {
+ if (($hashLength === 60 && password_verify($message, $hash))
+ || ($hashLength === 40 && hash_equals($hash, sha1($message)))) {
$newHash = $this->hash($message);
return true;
}
diff --git a/lib/private/Security/IdentityProof/Manager.php b/lib/private/Security/IdentityProof/Manager.php
index 935c18bb81d..c16b8314beb 100644
--- a/lib/private/Security/IdentityProof/Manager.php
+++ b/lib/private/Security/IdentityProof/Manager.php
@@ -11,6 +11,8 @@ namespace OC\Security\IdentityProof;
use OC\Files\AppData\Factory;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
+use OCP\ICache;
+use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IUser;
use OCP\Security\ICrypto;
@@ -19,13 +21,17 @@ use Psr\Log\LoggerInterface;
class Manager {
private IAppData $appData;
+ protected ICache $cache;
+
public function __construct(
Factory $appDataFactory,
private ICrypto $crypto,
private IConfig $config,
private LoggerInterface $logger,
+ private ICacheFactory $cacheFactory,
) {
$this->appData = $appDataFactory->get('identityproof');
+ $this->cache = $this->cacheFactory->createDistributed('identityproof::');
}
/**
@@ -96,12 +102,24 @@ class Manager {
*/
protected function retrieveKey(string $id): Key {
try {
+ $cachedPublicKey = $this->cache->get($id . '-public');
+ $cachedPrivateKey = $this->cache->get($id . '-private');
+
+ if ($cachedPublicKey !== null && $cachedPrivateKey !== null) {
+ $decryptedPrivateKey = $this->crypto->decrypt($cachedPrivateKey);
+
+ return new Key($cachedPublicKey, $decryptedPrivateKey);
+ }
+
$folder = $this->appData->getFolder($id);
- $privateKey = $this->crypto->decrypt(
- $folder->getFile('private')->getContent()
- );
+ $privateKey = $folder->getFile('private')->getContent();
$publicKey = $folder->getFile('public')->getContent();
- return new Key($publicKey, $privateKey);
+
+ $this->cache->set($id . '-public', $publicKey);
+ $this->cache->set($id . '-private', $privateKey);
+
+ $decryptedPrivateKey = $this->crypto->decrypt($privateKey);
+ return new Key($publicKey, $decryptedPrivateKey);
} catch (\Exception $e) {
return $this->generateKey($id);
}
diff --git a/lib/private/Security/Ip/BruteforceAllowList.php b/lib/private/Security/Ip/BruteforceAllowList.php
new file mode 100644
index 00000000000..fb837690a7b
--- /dev/null
+++ b/lib/private/Security/Ip/BruteforceAllowList.php
@@ -0,0 +1,57 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+namespace OC\Security\Ip;
+
+use OCP\IAppConfig;
+use OCP\Security\Ip\IFactory;
+
+class BruteforceAllowList {
+ /** @var array<string, bool> */
+ protected array $ipIsAllowListed = [];
+
+ public function __construct(
+ private readonly IAppConfig $appConfig,
+ private readonly IFactory $factory,
+ ) {
+ }
+
+ /**
+ * Check if the IP is allowed to bypass bruteforce protection
+ */
+ public function isBypassListed(string $ip): bool {
+ if (isset($this->ipIsAllowListed[$ip])) {
+ return $this->ipIsAllowListed[$ip];
+ }
+
+ try {
+ $address = $this->factory->addressFromString($ip);
+ } catch (\InvalidArgumentException) {
+ $this->ipIsAllowListed[$ip] = false;
+ return false;
+ }
+
+ foreach ($this->appConfig->searchKeys('bruteForce', 'whitelist_') as $key) {
+ $rangeString = $this->appConfig->getValueString('bruteForce', $key);
+ try {
+ $range = $this->factory->rangeFromString($rangeString);
+ } catch (\InvalidArgumentException) {
+ continue;
+ }
+
+ $allowed = $range->contains($address);
+ if ($allowed) {
+ $this->ipIsAllowListed[$ip] = true;
+ return true;
+ }
+ }
+
+ $this->ipIsAllowListed[$ip] = false;
+ return false;
+ }
+}
diff --git a/lib/private/Security/Normalizer/IpAddress.php b/lib/private/Security/Normalizer/IpAddress.php
index e9232c5fe9f..4d33a7bd632 100644
--- a/lib/private/Security/Normalizer/IpAddress.php
+++ b/lib/private/Security/Normalizer/IpAddress.php
@@ -8,6 +8,8 @@ declare(strict_types=1);
*/
namespace OC\Security\Normalizer;
+use OCP\IConfig;
+
/**
* Class IpAddress is used for normalizing IPv4 and IPv6 addresses in security
* relevant contexts in Nextcloud.
@@ -24,7 +26,8 @@ class IpAddress {
}
/**
- * Return the given subnet for an IPv6 address (64 first bits)
+ * Return the given subnet for an IPv6 address
+ * Rely on security.ipv6_normalized_subnet_size, defaults to 56
*/
private function getIPv6Subnet(string $ip): string {
if ($ip[0] === '[' && $ip[-1] === ']') { // If IP is with brackets, for example [::1]
@@ -35,10 +38,25 @@ class IpAddress {
$ip = substr($ip, 0, $pos - 1);
}
- $binary = \inet_pton($ip);
- $mask = inet_pton('FFFF:FFFF:FFFF:FFFF::');
+ $config = \OCP\Server::get(IConfig::class);
+ $maskSize = min(64, $config->getSystemValueInt('security.ipv6_normalized_subnet_size', 56));
+ $maskSize = max(32, $maskSize);
+ if (PHP_INT_SIZE === 4) {
+ if ($maskSize === 64) {
+ $value = -1;
+ } elseif ($maskSize === 63) {
+ $value = PHP_INT_MAX;
+ } else {
+ $value = (1 << $maskSize - 32) - 1;
+ }
+ // as long as we support 32bit PHP we cannot use the `P` pack formatter (and not overflow 32bit integer)
+ $mask = pack('VVVV', -1, $value, 0, 0);
+ } else {
+ $mask = pack('VVP', (1 << 32) - 1, (1 << $maskSize - 32) - 1, 0);
+ }
- return inet_ntop($binary & $mask) . '/64';
+ $binary = \inet_pton($ip);
+ return inet_ntop($binary & $mask) . '/' . $maskSize;
}
/**
@@ -63,7 +81,7 @@ class IpAddress {
/**
- * Gets either the /32 (IPv4) or the /64 (IPv6) subnet of an IP address
+ * Gets either the /32 (IPv4) or the /56 (default for IPv6) subnet of an IP address
*/
public function getSubnet(): string {
if (filter_var($this->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
diff --git a/lib/private/Security/RateLimiting/Limiter.php b/lib/private/Security/RateLimiting/Limiter.php
index b7ac26d9132..316becfa009 100644
--- a/lib/private/Security/RateLimiting/Limiter.php
+++ b/lib/private/Security/RateLimiting/Limiter.php
@@ -13,10 +13,12 @@ use OC\Security\RateLimiting\Backend\IBackend;
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
use OCP\IUser;
use OCP\Security\RateLimiting\ILimiter;
+use Psr\Log\LoggerInterface;
class Limiter implements ILimiter {
public function __construct(
private IBackend $backend,
+ private LoggerInterface $logger,
) {
}
@@ -32,6 +34,11 @@ class Limiter implements ILimiter {
): void {
$existingAttempts = $this->backend->getAttempts($methodIdentifier, $userIdentifier);
if ($existingAttempts >= $limit) {
+ $this->logger->info('Request blocked because it exceeds the rate limit [method: {method}, limit: {limit}, period: {period}]', [
+ 'method' => $methodIdentifier,
+ 'limit' => $limit,
+ 'period' => $period,
+ ]);
throw new RateLimitExceededException();
}
diff --git a/lib/private/Security/Signature/Model/SignedRequest.php b/lib/private/Security/Signature/Model/SignedRequest.php
index f30935e83b1..12a43f32bcc 100644
--- a/lib/private/Security/Signature/Model/SignedRequest.php
+++ b/lib/private/Security/Signature/Model/SignedRequest.php
@@ -74,8 +74,8 @@ class SignedRequest implements ISignedRequest, JsonSerializable {
*/
public function getDigest(): string {
if ($this->digest === '') {
- $this->digest = $this->digestAlgorithm->value . '=' .
- base64_encode(hash($this->digestAlgorithm->getHashingAlgorithm(), $this->body, true));
+ $this->digest = $this->digestAlgorithm->value . '='
+ . base64_encode(hash($this->digestAlgorithm->getHashingAlgorithm(), $this->body, true));
}
return $this->digest;
}
diff --git a/lib/private/Security/VerificationToken/VerificationToken.php b/lib/private/Security/VerificationToken/VerificationToken.php
index 1995b482597..89f45180359 100644
--- a/lib/private/Security/VerificationToken/VerificationToken.php
+++ b/lib/private/Security/VerificationToken/VerificationToken.php
@@ -85,9 +85,9 @@ class VerificationToken implements IVerificationToken {
): string {
$token = $this->secureRandom->generate(
21,
- ISecureRandom::CHAR_DIGITS .
- ISecureRandom::CHAR_LOWER .
- ISecureRandom::CHAR_UPPER
+ ISecureRandom::CHAR_DIGITS
+ . ISecureRandom::CHAR_LOWER
+ . ISecureRandom::CHAR_UPPER
);
$tokenValue = $this->timeFactory->getTime() . ':' . $token;
$encryptedValue = $this->crypto->encrypt($tokenValue, $passwordPrefix . $this->config->getSystemValueString('secret'));