diff options
author | Joas Schilling <213943+nickvergessen@users.noreply.github.com> | 2023-08-23 08:43:01 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-08-23 08:43:01 +0200 |
commit | d12b56bf633dcd5ed34e1a1ff7b1b3a8c1114add (patch) | |
tree | a60c1bfbf64bba852b69772adfeb43bbd375391c /lib | |
parent | 7ef9721347c18c915ae0e6f236c6d41246021595 (diff) | |
parent | 26832ec5da999068ef838f570c7a3ba912c47cdf (diff) | |
download | nextcloud-server-d12b56bf633dcd5ed34e1a1ff7b1b3a8c1114add.tar.gz nextcloud-server-d12b56bf633dcd5ed34e1a1ff7b1b3a8c1114add.zip |
Merge pull request #39997 from nextcloud/backport/39870/stable27
[stable27] feat(security): Add a bruteforce protection backend base on memcache
Diffstat (limited to 'lib')
-rw-r--r-- | lib/composer/composer/autoload_classmap.php | 6 | ||||
-rw-r--r-- | lib/composer/composer/autoload_static.php | 6 | ||||
-rw-r--r-- | lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php | 14 | ||||
-rw-r--r-- | lib/private/Security/Bruteforce/Backend/DatabaseBackend.php | 116 | ||||
-rw-r--r-- | lib/private/Security/Bruteforce/Backend/IBackend.php | 82 | ||||
-rw-r--r-- | lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php | 161 | ||||
-rw-r--r-- | lib/private/Security/Bruteforce/Capabilities.php | 33 | ||||
-rw-r--r-- | lib/private/Security/Bruteforce/Throttler.php | 211 | ||||
-rw-r--r-- | lib/private/Server.php | 12 | ||||
-rw-r--r-- | lib/public/Security/Bruteforce/IThrottler.php | 29 |
10 files changed, 511 insertions, 159 deletions
diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index b8c864abe4d..5b543ad55b9 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -1002,10 +1002,11 @@ return array( 'OC\\Core\\Command\\Preview\\Generate' => $baseDir . '/core/Command/Preview/Generate.php', 'OC\\Core\\Command\\Preview\\Repair' => $baseDir . '/core/Command/Preview/Repair.php', 'OC\\Core\\Command\\Preview\\ResetRenderedTexts' => $baseDir . '/core/Command/Preview/ResetRenderedTexts.php', + 'OC\\Core\\Command\\Security\\BruteforceAttempts' => $baseDir . '/core/Command/Security/BruteforceAttempts.php', + 'OC\\Core\\Command\\Security\\BruteforceResetAttempts' => $baseDir . '/core/Command/Security/BruteforceResetAttempts.php', 'OC\\Core\\Command\\Security\\ImportCertificate' => $baseDir . '/core/Command/Security/ImportCertificate.php', 'OC\\Core\\Command\\Security\\ListCertificates' => $baseDir . '/core/Command/Security/ListCertificates.php', 'OC\\Core\\Command\\Security\\RemoveCertificate' => $baseDir . '/core/Command/Security/RemoveCertificate.php', - 'OC\\Core\\Command\\Security\\ResetBruteforceAttempts' => $baseDir . '/core/Command/Security/ResetBruteforceAttempts.php', 'OC\\Core\\Command\\Status' => $baseDir . '/core/Command/Status.php', 'OC\\Core\\Command\\SystemTag\\Add' => $baseDir . '/core/Command/SystemTag/Add.php', 'OC\\Core\\Command\\SystemTag\\Delete' => $baseDir . '/core/Command/SystemTag/Delete.php', @@ -1565,6 +1566,9 @@ return array( 'OC\\Search\\Result\\Image' => $baseDir . '/lib/private/Search/Result/Image.php', 'OC\\Search\\SearchComposer' => $baseDir . '/lib/private/Search/SearchComposer.php', 'OC\\Search\\SearchQuery' => $baseDir . '/lib/private/Search/SearchQuery.php', + 'OC\\Security\\Bruteforce\\Backend\\DatabaseBackend' => $baseDir . '/lib/private/Security/Bruteforce/Backend/DatabaseBackend.php', + 'OC\\Security\\Bruteforce\\Backend\\IBackend' => $baseDir . '/lib/private/Security/Bruteforce/Backend/IBackend.php', + 'OC\\Security\\Bruteforce\\Backend\\MemoryCacheBackend' => $baseDir . '/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php', 'OC\\Security\\Bruteforce\\Capabilities' => $baseDir . '/lib/private/Security/Bruteforce/Capabilities.php', 'OC\\Security\\Bruteforce\\CleanupJob' => $baseDir . '/lib/private/Security/Bruteforce/CleanupJob.php', 'OC\\Security\\Bruteforce\\Throttler' => $baseDir . '/lib/private/Security/Bruteforce/Throttler.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index e099accf683..19e2f3393d6 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -1035,10 +1035,11 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OC\\Core\\Command\\Preview\\Generate' => __DIR__ . '/../../..' . '/core/Command/Preview/Generate.php', 'OC\\Core\\Command\\Preview\\Repair' => __DIR__ . '/../../..' . '/core/Command/Preview/Repair.php', 'OC\\Core\\Command\\Preview\\ResetRenderedTexts' => __DIR__ . '/../../..' . '/core/Command/Preview/ResetRenderedTexts.php', + 'OC\\Core\\Command\\Security\\BruteforceAttempts' => __DIR__ . '/../../..' . '/core/Command/Security/BruteforceAttempts.php', + 'OC\\Core\\Command\\Security\\BruteforceResetAttempts' => __DIR__ . '/../../..' . '/core/Command/Security/BruteforceResetAttempts.php', 'OC\\Core\\Command\\Security\\ImportCertificate' => __DIR__ . '/../../..' . '/core/Command/Security/ImportCertificate.php', 'OC\\Core\\Command\\Security\\ListCertificates' => __DIR__ . '/../../..' . '/core/Command/Security/ListCertificates.php', 'OC\\Core\\Command\\Security\\RemoveCertificate' => __DIR__ . '/../../..' . '/core/Command/Security/RemoveCertificate.php', - 'OC\\Core\\Command\\Security\\ResetBruteforceAttempts' => __DIR__ . '/../../..' . '/core/Command/Security/ResetBruteforceAttempts.php', 'OC\\Core\\Command\\Status' => __DIR__ . '/../../..' . '/core/Command/Status.php', 'OC\\Core\\Command\\SystemTag\\Add' => __DIR__ . '/../../..' . '/core/Command/SystemTag/Add.php', 'OC\\Core\\Command\\SystemTag\\Delete' => __DIR__ . '/../../..' . '/core/Command/SystemTag/Delete.php', @@ -1598,6 +1599,9 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OC\\Search\\Result\\Image' => __DIR__ . '/../../..' . '/lib/private/Search/Result/Image.php', 'OC\\Search\\SearchComposer' => __DIR__ . '/../../..' . '/lib/private/Search/SearchComposer.php', 'OC\\Search\\SearchQuery' => __DIR__ . '/../../..' . '/lib/private/Search/SearchQuery.php', + 'OC\\Security\\Bruteforce\\Backend\\DatabaseBackend' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/Backend/DatabaseBackend.php', + 'OC\\Security\\Bruteforce\\Backend\\IBackend' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/Backend/IBackend.php', + 'OC\\Security\\Bruteforce\\Backend\\MemoryCacheBackend' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php', 'OC\\Security\\Bruteforce\\Capabilities' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/Capabilities.php', 'OC\\Security\\Bruteforce\\CleanupJob' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/CleanupJob.php', 'OC\\Security\\Bruteforce\\Throttler' => __DIR__ . '/../../..' . '/lib/private/Security/Bruteforce/Throttler.php', diff --git a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php index 2ecd26a68e1..a0b915588ad 100644 --- a/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php +++ b/lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php @@ -51,6 +51,8 @@ use ReflectionMethod; * @package OC\AppFramework\Middleware\Security */ class BruteForceMiddleware extends Middleware { + private int $delaySlept = 0; + public function __construct( protected ControllerMethodReflector $reflector, protected Throttler $throttler, @@ -67,7 +69,7 @@ class BruteForceMiddleware extends Middleware { if ($this->reflector->hasAnnotation('BruteForceProtection')) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); - $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), $action); + $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), $action); } else { $reflectionMethod = new ReflectionMethod($controller, $methodName); $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class); @@ -79,7 +81,7 @@ class BruteForceMiddleware extends Middleware { /** @var BruteForceProtection $protection */ $protection = $attribute->newInstance(); $action = $protection->getAction(); - $this->throttler->sleepDelayOrThrowOnMax($remoteAddress, $action); + $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($remoteAddress, $action); } } } @@ -95,7 +97,7 @@ class BruteForceMiddleware extends Middleware { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $ip = $this->request->getRemoteAddress(); $this->throttler->registerAttempt($action, $ip, $response->getThrottleMetadata()); - $this->throttler->sleepDelayOrThrowOnMax($ip, $action); + $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($ip, $action); } else { $reflectionMethod = new ReflectionMethod($controller, $methodName); $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class); @@ -111,7 +113,7 @@ class BruteForceMiddleware extends Middleware { if (!isset($metaData['action']) || $metaData['action'] === $action) { $this->throttler->registerAttempt($action, $ip, $metaData); - $this->throttler->sleepDelayOrThrowOnMax($ip, $action); + $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($ip, $action); } } } else { @@ -127,6 +129,10 @@ class BruteForceMiddleware extends Middleware { } } + if ($this->delaySlept) { + $response->addHeader('X-Nextcloud-Bruteforce-Throttled', $this->delaySlept . 'ms'); + } + return parent::afterController($controller, $methodName, $response); } diff --git a/lib/private/Security/Bruteforce/Backend/DatabaseBackend.php b/lib/private/Security/Bruteforce/Backend/DatabaseBackend.php new file mode 100644 index 00000000000..04f2a7b6397 --- /dev/null +++ b/lib/private/Security/Bruteforce/Backend/DatabaseBackend.php @@ -0,0 +1,116 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OC\Security\Bruteforce\Backend; + +use OCP\IDBConnection; + +class DatabaseBackend implements IBackend { + private const TABLE_NAME = 'bruteforce_attempts'; + + public function __construct( + private IDBConnection $db, + ) { + } + + /** + * {@inheritDoc} + */ + public function getAttempts( + string $ipSubnet, + int $maxAgeTimestamp, + ?string $action = null, + ?array $metadata = null, + ): int { + $query = $this->db->getQueryBuilder(); + $query->select($query->func()->count('*', 'attempts')) + ->from(self::TABLE_NAME) + ->where($query->expr()->gt('occurred', $query->createNamedParameter($maxAgeTimestamp))) + ->andWhere($query->expr()->eq('subnet', $query->createNamedParameter($ipSubnet))); + + if ($action !== null) { + $query->andWhere($query->expr()->eq('action', $query->createNamedParameter($action))); + + if ($metadata !== null) { + $query->andWhere($query->expr()->eq('metadata', $query->createNamedParameter(json_encode($metadata)))); + } + } + + $result = $query->executeQuery(); + $row = $result->fetch(); + $result->closeCursor(); + + return (int) $row['attempts']; + } + + /** + * {@inheritDoc} + */ + public function resetAttempts( + string $ipSubnet, + ?string $action = null, + ?array $metadata = null, + ): void { + $query = $this->db->getQueryBuilder(); + $query->delete(self::TABLE_NAME) + ->where($query->expr()->eq('subnet', $query->createNamedParameter($ipSubnet))); + + if ($action !== null) { + $query->andWhere($query->expr()->eq('action', $query->createNamedParameter($action))); + + if ($metadata !== null) { + $query->andWhere($query->expr()->eq('metadata', $query->createNamedParameter(json_encode($metadata)))); + } + } + + $query->executeStatement(); + } + + /** + * {@inheritDoc} + */ + public function registerAttempt( + string $ip, + string $ipSubnet, + int $timestamp, + string $action, + array $metadata = [], + ): void { + $values = [ + 'ip' => $ip, + 'subnet' => $ipSubnet, + 'action' => $action, + 'metadata' => json_encode($metadata), + 'occurred' => $timestamp, + ]; + + $qb = $this->db->getQueryBuilder(); + $qb->insert(self::TABLE_NAME); + foreach ($values as $column => $value) { + $qb->setValue($column, $qb->createNamedParameter($value)); + } + $qb->executeStatement(); + } +} diff --git a/lib/private/Security/Bruteforce/Backend/IBackend.php b/lib/private/Security/Bruteforce/Backend/IBackend.php new file mode 100644 index 00000000000..4b40262e645 --- /dev/null +++ b/lib/private/Security/Bruteforce/Backend/IBackend.php @@ -0,0 +1,82 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OC\Security\Bruteforce\Backend; + +/** + * Interface IBackend defines a storage backend for the bruteforce data. It + * should be noted that writing and reading brute force data is an expensive + * operation and one should thus make sure to only use sufficient fast backends. + */ +interface IBackend { + /** + * Gets the number of attempts for the specified subnet (and further filters) + * + * @param string $ipSubnet + * @param int $maxAgeTimestamp + * @param ?string $action Optional action to further limit attempts + * @param ?array $metadata Optional metadata stored to further limit attempts (Only considered when $action is set) + * @return int + * @since 28.0.0 + */ + public function getAttempts( + string $ipSubnet, + int $maxAgeTimestamp, + ?string $action = null, + ?array $metadata = null, + ): int; + + /** + * Reset the attempts for the specified subnet (and further filters) + * + * @param string $ipSubnet + * @param ?string $action Optional action to further limit attempts + * @param ?array $metadata Optional metadata stored to further limit attempts(Only considered when $action is set) + * @since 28.0.0 + */ + public function resetAttempts( + string $ipSubnet, + ?string $action = null, + ?array $metadata = null, + ): void; + + /** + * Register a failed attempt to bruteforce a security control + * + * @param string $ip + * @param string $ipSubnet + * @param int $timestamp + * @param string $action + * @param array $metadata Optional metadata stored to further limit attempts when getting + * @since 28.0.0 + */ + public function registerAttempt( + string $ip, + string $ipSubnet, + int $timestamp, + string $action, + array $metadata = [], + ): void; +} diff --git a/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php b/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php new file mode 100644 index 00000000000..432e99700fe --- /dev/null +++ b/lib/private/Security/Bruteforce/Backend/MemoryCacheBackend.php @@ -0,0 +1,161 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OC\Security\Bruteforce\Backend; + +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\ICache; +use OCP\ICacheFactory; + +class MemoryCacheBackend implements IBackend { + private ICache $cache; + + public function __construct( + ICacheFactory $cacheFactory, + private ITimeFactory $timeFactory, + ) { + $this->cache = $cacheFactory->createDistributed(__CLASS__); + } + + private function hash( + null|string|array $data, + ): ?string { + if ($data === null) { + return null; + } + if (!is_string($data)) { + $data = json_encode($data); + } + return hash('sha1', $data); + } + + private function getExistingAttempts(string $identifier): array { + $cachedAttempts = $this->cache->get($identifier); + if ($cachedAttempts === null) { + return []; + } + + $cachedAttempts = json_decode($cachedAttempts, true); + if (\is_array($cachedAttempts)) { + return $cachedAttempts; + } + + return []; + } + + /** + * {@inheritDoc} + */ + public function getAttempts( + string $ipSubnet, + int $maxAgeTimestamp, + ?string $action = null, + ?array $metadata = null, + ): int { + $identifier = $this->hash($ipSubnet); + $actionHash = $this->hash($action); + $metadataHash = $this->hash($metadata); + $existingAttempts = $this->getExistingAttempts($identifier); + + $count = 0; + foreach ($existingAttempts as $info) { + [$occurredTime, $attemptAction, $attemptMetadata] = explode('#', $info, 3); + if ($action === null || $attemptAction === $actionHash) { + if ($metadata === null || $attemptMetadata === $metadataHash) { + if ($occurredTime > $maxAgeTimestamp) { + $count++; + } + } + } + } + + return $count; + } + + /** + * {@inheritDoc} + */ + public function resetAttempts( + string $ipSubnet, + ?string $action = null, + ?array $metadata = null, + ): void { + $identifier = $this->hash($ipSubnet); + if ($action === null) { + $this->cache->remove($identifier); + } else { + $actionHash = $this->hash($action); + $metadataHash = $this->hash($metadata); + $existingAttempts = $this->getExistingAttempts($identifier); + $maxAgeTimestamp = $this->timeFactory->getTime() - 12 * 3600; + + foreach ($existingAttempts as $key => $info) { + [$occurredTime, $attemptAction, $attemptMetadata] = explode('#', $info, 3); + if ($attemptAction === $actionHash) { + if ($metadata === null || $attemptMetadata === $metadataHash) { + unset($existingAttempts[$key]); + } elseif ($occurredTime < $maxAgeTimestamp) { + unset($existingAttempts[$key]); + } + } + } + + if (!empty($existingAttempts)) { + $this->cache->set($identifier, json_encode($existingAttempts), 12 * 3600); + } else { + $this->cache->remove($identifier); + } + } + } + + /** + * {@inheritDoc} + */ + public function registerAttempt( + string $ip, + string $ipSubnet, + int $timestamp, + string $action, + array $metadata = [], + ): void { + $identifier = $this->hash($ipSubnet); + $existingAttempts = $this->getExistingAttempts($identifier); + $maxAgeTimestamp = $this->timeFactory->getTime() - 12 * 3600; + + // Unset all attempts that are already expired + foreach ($existingAttempts as $key => $info) { + [$occurredTime,] = explode('#', $info, 3); + if ($occurredTime < $maxAgeTimestamp) { + unset($existingAttempts[$key]); + } + } + $existingAttempts = array_values($existingAttempts); + + // Store the new attempt + $existingAttempts[] = $timestamp . '#' . $this->hash($action) . '#' . $this->hash($metadata); + + $this->cache->set($identifier, json_encode($existingAttempts), 12 * 3600); + } +} diff --git a/lib/private/Security/Bruteforce/Capabilities.php b/lib/private/Security/Bruteforce/Capabilities.php index 60cf3086f2d..b50eea0b7af 100644 --- a/lib/private/Security/Bruteforce/Capabilities.php +++ b/lib/private/Security/Bruteforce/Capabilities.php @@ -3,9 +3,11 @@ declare(strict_types=1); /** + * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com> * @copyright Copyright (c) 2017 Roeland Jago Douma <roeland@famdouma.nl> * * @author J0WI <J0WI@users.noreply.github.com> + * @author Joas Schilling <coding@schilljs.com> * @author Julius Härtl <jus@bitgrid.net> * @author Roeland Jago Douma <roeland@famdouma.nl> * @@ -30,35 +32,24 @@ namespace OC\Security\Bruteforce; use OCP\Capabilities\IPublicCapability; use OCP\Capabilities\IInitialStateExcludedCapability; use OCP\IRequest; +use OCP\Security\Bruteforce\IThrottler; class Capabilities implements IPublicCapability, IInitialStateExcludedCapability { - /** @var IRequest */ - private $request; - - /** @var Throttler */ - private $throttler; + public function __construct( + private IRequest $request, + private IThrottler $throttler, + ) { + } /** - * Capabilities constructor. - * - * @param IRequest $request - * @param Throttler $throttler + * @return array{bruteforce: array{delay: int, allow-listed: bool}} */ - public function __construct(IRequest $request, - Throttler $throttler) { - $this->request = $request; - $this->throttler = $throttler; - } - public function getCapabilities(): array { - if (version_compare(\OC::$server->getConfig()->getSystemValueString('version', '0.0.0.0'), '12.0.0.0', '<')) { - return []; - } - return [ 'bruteforce' => [ - 'delay' => $this->throttler->getDelay($this->request->getRemoteAddress()) - ] + 'delay' => $this->throttler->getDelay($this->request->getRemoteAddress()), + 'allow-listed' => $this->throttler->isBypassListed($this->request->getRemoteAddress()), + ], ]; } } diff --git a/lib/private/Security/Bruteforce/Throttler.php b/lib/private/Security/Bruteforce/Throttler.php index d5fd0984baa..a0cc5ae4ecb 100644 --- a/lib/private/Security/Bruteforce/Throttler.php +++ b/lib/private/Security/Bruteforce/Throttler.php @@ -3,6 +3,7 @@ declare(strict_types=1); /** + * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com> * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> * * @author Bjoern Schiessle <bjoern@schiessle.org> @@ -32,10 +33,10 @@ declare(strict_types=1); */ namespace OC\Security\Bruteforce; +use OC\Security\Bruteforce\Backend\IBackend; use OC\Security\Normalizer\IpAddress; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; -use OCP\IDBConnection; use OCP\Security\Bruteforce\IThrottler; use OCP\Security\Bruteforce\MaxDelayReached; use Psr\Log\LoggerInterface; @@ -54,59 +55,21 @@ use Psr\Log\LoggerInterface; * @package OC\Security\Bruteforce */ class Throttler implements IThrottler { - public const LOGIN_ACTION = 'login'; - - /** @var IDBConnection */ - private $db; - /** @var ITimeFactory */ - private $timeFactory; - private LoggerInterface $logger; - /** @var IConfig */ - private $config; /** @var bool[] */ - private $hasAttemptsDeleted = []; - - public function __construct(IDBConnection $db, - ITimeFactory $timeFactory, - LoggerInterface $logger, - IConfig $config) { - $this->db = $db; - $this->timeFactory = $timeFactory; - $this->logger = $logger; - $this->config = $config; - } - - /** - * Convert a number of seconds into the appropriate DateInterval - * - * @param int $expire - * @return \DateInterval - */ - private function getCutoff(int $expire): \DateInterval { - $d1 = new \DateTime(); - $d2 = clone $d1; - $d2->sub(new \DateInterval('PT' . $expire . 'S')); - return $d2->diff($d1); - } - - /** - * Calculate the cut off timestamp - * - * @param float $maxAgeHours - * @return int - */ - private function getCutoffTimestamp(float $maxAgeHours = 12.0): int { - return (new \DateTime()) - ->sub($this->getCutoff((int) ($maxAgeHours * 3600))) - ->getTimestamp(); + private array $hasAttemptsDeleted = []; + /** @var bool[] */ + private array $ipIsWhitelisted = []; + + public function __construct( + private ITimeFactory $timeFactory, + private LoggerInterface $logger, + private IConfig $config, + private IBackend $backend, + ) { } /** - * Register a failed attempt to bruteforce a security control - * - * @param string $action - * @param string $ip - * @param array $metadata Optional metadata logged to the database + * {@inheritDoc} */ public function registerAttempt(string $action, string $ip, @@ -117,13 +80,9 @@ class Throttler implements IThrottler { } $ipAddress = new IpAddress($ip); - $values = [ - 'action' => $action, - 'occurred' => $this->timeFactory->getTime(), - 'ip' => (string)$ipAddress, - 'subnet' => $ipAddress->getSubnet(), - 'metadata' => json_encode($metadata), - ]; + if ($this->isBypassListed((string)$ipAddress)) { + return; + } $this->logger->notice( sprintf( @@ -136,12 +95,13 @@ class Throttler implements IThrottler { ] ); - $qb = $this->db->getQueryBuilder(); - $qb->insert('bruteforce_attempts'); - foreach ($values as $column => $value) { - $qb->setValue($column, $qb->createNamedParameter($value)); - } - $qb->execute(); + $this->backend->registerAttempt( + (string)$ipAddress, + $ipAddress->getSubnet(), + $this->timeFactory->getTime(), + $action, + $metadata + ); } /** @@ -150,8 +110,13 @@ class Throttler implements IThrottler { * @param string $ip * @return bool */ - private function isIPWhitelisted(string $ip): bool { + 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; } @@ -165,6 +130,7 @@ class Throttler implements IThrottler { } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $type = 6; } else { + $this->ipIsWhitelisted[$ip] = false; return false; } @@ -202,20 +168,26 @@ class Throttler implements IThrottler { } if ($valid === true) { + $this->ipIsWhitelisted[$ip] = true; return true; } } + $this->ipIsWhitelisted[$ip] = false; return false; } /** - * Get the throttling delay (in milliseconds) - * - * @param string $ip - * @param string $action optionally filter by action - * @param float $maxAgeHours - * @return int + * {@inheritDoc} + */ + public function showBruteforceWarning(string $ip, string $action = ''): bool { + $attempts = $this->getAttempts($ip, $action); + // 4 failed attempts is the last delay below 5 seconds + return $attempts >= 4; + } + + /** + * {@inheritDoc} */ public function getAttempts(string $ip, string $action = '', float $maxAgeHours = 12): int { if ($maxAgeHours > 48) { @@ -228,35 +200,21 @@ class Throttler implements IThrottler { } $ipAddress = new IpAddress($ip); - if ($this->isIPWhitelisted((string)$ipAddress)) { + if ($this->isBypassListed((string)$ipAddress)) { return 0; } - $cutoffTime = $this->getCutoffTimestamp($maxAgeHours); - - $qb = $this->db->getQueryBuilder(); - $qb->select($qb->func()->count('*', 'attempts')) - ->from('bruteforce_attempts') - ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime))) - ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet()))); - - if ($action !== '') { - $qb->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action))); - } - - $result = $qb->execute(); - $row = $result->fetch(); - $result->closeCursor(); + $maxAgeTimestamp = (int) ($this->timeFactory->getTime() - 3600 * $maxAgeHours); - return (int) $row['attempts']; + return $this->backend->getAttempts( + $ipAddress->getSubnet(), + $maxAgeTimestamp, + $action !== '' ? $action : null, + ); } /** - * Get the throttling delay (in milliseconds) - * - * @param string $ip - * @param string $action optionally filter by action - * @return int + * {@inheritDoc} */ public function getDelay(string $ip, string $action = ''): int { $attempts = $this->getAttempts($ip, $action); @@ -278,69 +236,58 @@ class Throttler implements IThrottler { } /** - * Reset the throttling delay for an IP address, action and metadata - * - * @param string $ip - * @param string $action - * @param array $metadata + * {@inheritDoc} */ public function resetDelay(string $ip, string $action, array $metadata): void { - $ipAddress = new IpAddress($ip); - if ($this->isIPWhitelisted((string)$ipAddress)) { + // No need to log if the bruteforce protection is disabled + if (!$this->config->getSystemValueBool('auth.bruteforce.protection.enabled', true)) { return; } - $cutoffTime = $this->getCutoffTimestamp(); - - $qb = $this->db->getQueryBuilder(); - $qb->delete('bruteforce_attempts') - ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime))) - ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet()))) - ->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action))) - ->andWhere($qb->expr()->eq('metadata', $qb->createNamedParameter(json_encode($metadata)))); + $ipAddress = new IpAddress($ip); + if ($this->isBypassListed((string)$ipAddress)) { + return; + } - $qb->executeStatement(); + $this->backend->resetAttempts( + $ipAddress->getSubnet(), + $action, + $metadata, + ); $this->hasAttemptsDeleted[$action] = true; } /** - * Reset the throttling delay for an IP address - * - * @param string $ip + * {@inheritDoc} */ public function resetDelayForIP(string $ip): void { - $cutoffTime = $this->getCutoffTimestamp(); + // No need to log if the bruteforce protection is disabled + if (!$this->config->getSystemValueBool('auth.bruteforce.protection.enabled', true)) { + return; + } - $qb = $this->db->getQueryBuilder(); - $qb->delete('bruteforce_attempts') - ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime))) - ->andWhere($qb->expr()->eq('ip', $qb->createNamedParameter($ip))); + $ipAddress = new IpAddress($ip); + if ($this->isBypassListed((string)$ipAddress)) { + return; + } - $qb->execute(); + $this->backend->resetAttempts($ipAddress->getSubnet()); } /** - * Will sleep for the defined amount of time - * - * @param string $ip - * @param string $action optionally filter by action - * @return int the time spent sleeping + * {@inheritDoc} */ public function sleepDelay(string $ip, string $action = ''): int { $delay = $this->getDelay($ip, $action); - usleep($delay * 1000); + if (!$this->config->getSystemValueBool('auth.bruteforce.protection.testing')) { + usleep($delay * 1000); + } return $delay; } /** - * Will sleep for the defined amount of time unless maximum was reached in the last 30 minutes - * In this case a "429 Too Many Request" exception is thrown - * - * @param string $ip - * @param string $action optionally filter by action - * @return int the time spent sleeping - * @throws MaxDelayReached when reached the maximum + * {@inheritDoc} */ public function sleepDelayOrThrowOnMax(string $ip, string $action = ''): int { $delay = $this->getDelay($ip, $action); @@ -359,7 +306,9 @@ class Throttler implements IThrottler { 'delay' => $delay, ]); } - usleep($delay * 1000); + if (!$this->config->getSystemValueBool('auth.bruteforce.protection.testing')) { + usleep($delay * 1000); + } return $delay; } } diff --git a/lib/private/Server.php b/lib/private/Server.php index 516dc0b6e8b..bb073891d03 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -1011,6 +1011,18 @@ class Server extends ServerContainer implements IServerContainer { /** @deprecated 19.0.0 */ $this->registerDeprecatedAlias('Throttler', Throttler::class); $this->registerAlias(IThrottler::class, Throttler::class); + + $this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) { + $config = $c->get(\OCP\IConfig::class); + if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) { + $backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class); + } else { + $backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class); + } + + return $backend; + }); + $this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) { // IConfig and IAppManager requires a working database. This code // might however be called when ownCloud is not yet setup. diff --git a/lib/public/Security/Bruteforce/IThrottler.php b/lib/public/Security/Bruteforce/IThrottler.php index 6f492d6c59d..620a53fd354 100644 --- a/lib/public/Security/Bruteforce/IThrottler.php +++ b/lib/public/Security/Bruteforce/IThrottler.php @@ -40,16 +40,19 @@ namespace OCP\Security\Bruteforce; interface IThrottler { /** * @since 25.0.0 + * @deprecated 28.0.0 */ public const MAX_DELAY = 25; /** * @since 25.0.0 + * @deprecated 28.0.0 */ public const MAX_DELAY_MS = 25000; // in milliseconds /** * @since 25.0.0 + * @deprecated 28.0.0 */ public const MAX_ATTEMPTS = 10; @@ -58,11 +61,21 @@ interface IThrottler { * * @param string $action * @param string $ip - * @param array $metadata Optional metadata logged to the database + * @param array $metadata Optional metadata logged with the attempt * @since 25.0.0 */ public function registerAttempt(string $action, string $ip, array $metadata = []): void; + + /** + * Check if the IP is allowed to bypass the brute force protection + * + * @param string $ip + * @return bool + * @since 28.0.0 + */ + public function isBypassListed(string $ip): bool; + /** * Get the throttling delay (in milliseconds) * @@ -71,16 +84,28 @@ interface IThrottler { * @param float $maxAgeHours * @return int * @since 25.0.0 + * @deprecated 28.0.0 This method is considered internal as of Nextcloud 28. Use {@see showBruteforceWarning()} to decide whether a warning should be shown. */ public function getAttempts(string $ip, string $action = '', float $maxAgeHours = 12): int; /** + * Whether a warning should be shown about the throttle + * + * @param string $ip + * @param string $action optionally filter by action + * @return bool + * @since 28.0.0 + */ + public function showBruteforceWarning(string $ip, string $action = ''): bool; + + /** * Get the throttling delay (in milliseconds) * * @param string $ip * @param string $action optionally filter by action * @return int * @since 25.0.0 + * @deprecated 28.0.0 This method is considered internal as of Nextcloud 28. Use {@see showBruteforceWarning()} to decide whether a warning should be shown. */ public function getDelay(string $ip, string $action = ''): int; @@ -99,6 +124,7 @@ interface IThrottler { * * @param string $ip * @since 25.0.0 + * @deprecated 28.0.0 This method is considered internal as of Nextcloud 28. Use {@see resetDelay()} and only reset the entries of your action and metadata */ public function resetDelayForIP(string $ip): void; @@ -109,6 +135,7 @@ interface IThrottler { * @param string $action optionally filter by action * @return int the time spent sleeping * @since 25.0.0 + * @deprecated 28.0.0 Use {@see sleepDelayOrThrowOnMax()} instead and abort handling the request when it throws */ public function sleepDelay(string $ip, string $action = ''): int; |