Skip to content
Closed
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
93 changes: 93 additions & 0 deletions core/Command/Security/BruteforceStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Robin Appelman <[email protected]>
*
* @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\Core\Command\Security;

use OC\Core\Command\Base;
use OC\Security\Bruteforce\Throttler;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class BruteforceStatus extends Base {
public function __construct(
protected Throttler $throttler,
) {
parent::__construct();
}

protected function configure(): void {
parent::configure();
$this
->setName('security:bruteforce:status')
->setDescription('List bruteforce attempts summary')
->addOption('ipaddress', 'i', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Only list attempts from the specified ip range in CIDR notation')
->addOption('action', 'a', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Only list attempts for the specified action')
->addOption('count', 'c', InputOption::VALUE_REQUIRED, 'Only list a limited number of items with the most occurrences');
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$ips = $input->getOption('ipaddress');
$actions = $input->getOption('action');
$count = $input->getOption('count');

$summary = $this->throttler->summarizeAttempts();

if ($ips) {
$summary = array_filter($summary, function (array $item) use ($ips) {
return $this->throttler->inSubnets($item['ip'], $ips);
});
}

if ($actions) {
$actions = array_map(function (string $action) {
return strtolower($action);
}, $actions);
$summary = array_filter($summary, function (array $item) use ($actions) {
$lowerAction = strtolower($item['action']);
foreach ($actions as $action) {
return str_contains($lowerAction, $action);
}
return false;
});
}

if ($count) {
$summary = array_slice($summary, 0, $count);
}

if ($input->getOption('output') === self::OUTPUT_FORMAT_JSON || $input->getOption('output') === self::OUTPUT_FORMAT_JSON_PRETTY) {
$this->writeArrayInOutputFormat($input, $output, $summary);
} else {
$table = new Table($output);
$table
->setHeaders(['IP', 'Action', 'Count'])
->setRows(array_map(function (array $item) {
return [$item['ip'], $item['action'], $item['count']];
}, $summary));
$table->render();
}
return 0;
}
}
2 changes: 1 addition & 1 deletion core/Command/Security/ResetBruteforceAttempts.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function __construct(
protected function configure() {
$this
->setName('security:bruteforce:reset')
->setDescription('resets bruteforce attemps for given IP address')
->setDescription('resets bruteforce attempts for given IP address')
->addArgument(
'ipaddress',
InputArgument::REQUIRED,
Expand Down
3 changes: 3 additions & 0 deletions core/register_command.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/

use OC\Core\Command\Security\BruteforceStatus;
use Psr\Log\LoggerInterface;

$application->add(new \Stecman\Component\Symfony\Console\BashCompletion\CompletionCommand());
Expand Down Expand Up @@ -210,6 +212,7 @@
$application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager()));
$application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager()));
$application->add(new OC\Core\Command\Security\ResetBruteforceAttempts(\OC::$server->getBruteForceThrottler()));
$application->add(\OC::$server->get(BruteforceStatus::class));
} else {
$application->add(\OC::$server->get(\OC\Core\Command\Maintenance\Install::class));
}
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,7 @@
'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\\BruteforceStatus' => $baseDir . '/core/Command/Security/BruteforceStatus.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',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,7 @@ 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\\BruteforceStatus' => __DIR__ . '/../../..' . '/core/Command/Security/BruteforceStatus.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',
Expand Down
107 changes: 69 additions & 38 deletions lib/private/Security/Bruteforce/Throttler.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OC\Security\Bruteforce;

use OC\Security\Normalizer\IpAddress;
Expand Down Expand Up @@ -66,10 +67,12 @@ class Throttler implements IThrottler {
/** @var bool[] */
private $hasAttemptsDeleted = [];

public function __construct(IDBConnection $db,
ITimeFactory $timeFactory,
LoggerInterface $logger,
IConfig $config) {
public function __construct(
IDBConnection $db,
ITimeFactory $timeFactory,
LoggerInterface $logger,
IConfig $config
) {
$this->db = $db;
$this->timeFactory = $timeFactory;
$this->logger = $logger;
Expand Down Expand Up @@ -97,7 +100,7 @@ private function getCutoff(int $expire): \DateInterval {
*/
private function getCutoffTimestamp(float $maxAgeHours = 12.0): int {
return (new \DateTime())
->sub($this->getCutoff((int) ($maxAgeHours * 3600)))
->sub($this->getCutoff((int)($maxAgeHours * 3600)))
->getTimestamp();
}

Expand All @@ -108,9 +111,11 @@ private function getCutoffTimestamp(float $maxAgeHours = 12.0): int {
* @param string $ip
* @param array $metadata Optional metadata logged to the database
*/
public function registerAttempt(string $action,
string $ip,
array $metadata = []): void {
public function registerAttempt(
string $action,
string $ip,
array $metadata = []
): void {
// No need to log if the bruteforce protection is disabled
if (!$this->config->getSystemValueBool('auth.bruteforce.protection.enabled', true)) {
return;
Expand Down Expand Up @@ -159,7 +164,19 @@ private function isIPWhitelisted(string $ip): bool {
$keys = array_filter($keys, function ($key) {
return str_starts_with($key, 'whitelist_');
});
$subnets = array_map(function ($key) {
return $this->config->getAppValue('bruteForce', $key, null);
}, $keys);

return $this->inSubnets($ip, $subnets);
}

/**
* @param string $ip
* @param string[] $subnets
* @return bool
*/
public function inSubnets(string $ip, array $subnets): bool {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$type = 4;
} elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
Expand All @@ -170,43 +187,44 @@ private function isIPWhitelisted(string $ip): bool {

$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;
foreach ($subnets as $cidr) {
if ($this->inSubnet($ip, $cidr, $type)) {
return true;
}
}
return false;
}

$addr = inet_pton($addr);
private function inSubnet(string $ip, string $cidr, int $type): bool {
$cx = explode('/', $cidr);
$addr = $cx[0];

$valid = true;
for ($i = 0; $i < $mask; $i++) {
$part = ord($addr[(int)($i / 8)]);
$orig = ord($ip[(int)($i / 8)]);
// 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))) {
return false;
}

$bitmask = 1 << (7 - ($i % 8));
$addr = inet_pton($addr);
if (count($cx) === 1) {
return $ip === $addr;
}
$mask = (int)$cx[1];

$part = $part & $bitmask;
$orig = $orig & $bitmask;
for ($i = 0; $i < $mask; $i++) {
$part = ord($addr[(int)($i / 8)]);
$orig = ord($ip[(int)($i / 8)]);

if ($part !== $orig) {
$valid = false;
break;
}
}
$bitmask = 1 << (7 - ($i % 8));

if ($valid === true) {
return true;
$part = $part & $bitmask;
$orig = $orig & $bitmask;

if ($part !== $orig) {
return false;
}
}

return false;
return true;
}

/**
Expand Down Expand Up @@ -248,7 +266,7 @@ public function getAttempts(string $ip, string $action = '', float $maxAgeHours
$row = $result->fetch();
$result->closeCursor();

return (int) $row['attempts'];
return (int)$row['attempts'];
}

/**
Expand All @@ -274,7 +292,7 @@ public function getDelay(string $ip, string $action = ''): int {
if ($delay > self::MAX_DELAY) {
return self::MAX_DELAY_MS;
}
return (int) \ceil($delay * 1000);
return (int)\ceil($delay * 1000);
}

/**
Expand Down Expand Up @@ -362,4 +380,17 @@ public function sleepDelayOrThrowOnMax(string $ip, string $action = ''): int {
usleep($delay * 1000);
return $delay;
}

/**
* @return array{'action': string, ip: string, count: int}[]
*/
public function summarizeAttempts(): array {
$query = $this->db->getQueryBuilder();
$query->select(['action', 'ip'])
->selectAlias($query->func()->count('id'), 'count')
->from('bruteforce_attempts')
->groupBy(['action', 'ip'])
->orderBy($query->func()->count('id'));
return $query->executeQuery()->fetchAll();
Copy link
Contributor

Choose a reason for hiding this comment

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

No closeCursor call needed here?

}
}