diff --git a/CHANGELOG b/CHANGELOG index 8398119..78b41d8 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -13,6 +13,15 @@ longer overrides getItems() just to call the parent, and purging the failed logins or the user name statistics reports any error, not only an exception, instead of ending in Joomla's error page + - Code clean-up (issue #283, C14): the purge of old blocks no longer + makes an address forget its history. A slow attacker - one block every + five weeks, with the default purge age of four - never reached + "block permanently after n blocks" or doubled the duration, because + the blocks that were counted were deleted first. The purge now counts + the blocks it deletes (except those an administrator lifted, which + didn't count before either) in a small table of offences per address, + #__bfstop_offence, which is kept for a year after an address's latest + block, and for at most 10000 addresses - phpstan (level 5, with a baseline) runs in CI, against the types of the Joomla! classes (issue #283) - The daily maintenance - purging old failed logins, blocks and unblock diff --git a/library/src/Repository/BlockRepository.php b/library/src/Repository/BlockRepository.php index 630082b..2404eb4 100644 --- a/library/src/Repository/BlockRepository.php +++ b/library/src/Repository/BlockRepository.php @@ -34,6 +34,19 @@ class BlockRepository extends AddressTableRepository private const LiftTable = '#__bfstop_unblock'; + // what the purge keeps of the blocks it deletes, per address (issue + // #283, C14): how many there were, and when the latest began. Without it + // an attacker who comes back every few weeks - the purge age is 4 weeks + // by default - would never reach maxBlocksBefore or escalate the duration + private const OffenceTable = '#__bfstop_offence'; + // how long an address is remembered after its latest block began, and + // the most addresses remembered (there is one row per address, and a + // client with an IPv6 network can be blocked from another one each time) + public const OffenceMemoryDays = 365; + public const OffenceMaxRows = 10000; + // ended blocks folded into the offences in one transaction + private const PurgeBatch = 500; + // SQL for "the block t is active at :now"; names of columns and tables only private function activeCondition($block, $lifted) { @@ -164,7 +177,8 @@ public function add($ipaddress, $duration) /** * How many blocks of $ipaddress there have been, the lifted ones (by an * administrator, not by the user through the link of a mail) not counted: - * what the next block's duration is based on. + * what the next block's duration is based on. The blocks the purge has + * deleted are counted too, from the offences it has kept of them. * * Fail-open: 0 (no earlier blocks, so the shortest duration). */ @@ -177,6 +191,10 @@ public function countPrevious($ipaddress) ->where($this->db->quoteName('ipaddress').' = :ip') ->where('NOT EXISTS (SELECT 1 FROM #__bfstop_unblock u WHERE '.self::Table.'.id = u.block_id AND source = '.self::LiftedByAdministrator.')'); $values['ip'] = (string) $ipaddress; + // the offences in the same query: this runs for every block + $query->clear('select')->select('COUNT(*) + COALESCE((SELECT o.blocks FROM '.self::OffenceTable. + ' o WHERE o.ipaddress = :offenceip), 0)'); + $values['offenceip'] = (string) $ipaddress; return $this->count($query, $values); }, 0); } @@ -198,18 +216,34 @@ public function countCreatedInWindow($time, $minutes) /** * Deletes the blocks which ended before $date, and the records of lifting - * which belong to no block (any more). Fail-open: the next run does it. + * which belong to no block (any more). The blocks which were not lifted by + * an administrator are counted in the offences of their addresses first, + * so that countPrevious() still knows of them. + * Fail-open: the next run does it. */ public function purgeEndedBefore($date) { $this->failOpen('purgeEndedBefore', function () use ($date) { - $query = $this->db->createQuery() - ->delete($this->db->quoteName(self::Table)) - ->where($this->db->quoteName('duration').' != 0') - ->where($this->addMinutesSql('crdate', 'duration').' < :date'); - $values = array('date' => (string) $date); - $this->execute($query, $values); + for ($round = 0; $round < 1000; ++$round) + { + $query = $this->db->createQuery() + ->select($this->db->quoteName(array('id', 'ipaddress', 'crdate'))) + ->from($this->db->quoteName(self::Table)) + ->where($this->db->quoteName('duration').' != 0') + ->where($this->addMinutesSql('crdate', 'duration').' < :date') + ->order($this->db->quoteName('id')); + $ended = $this->objects($query, array('date' => (string) $date), 0, self::PurgeBatch); + if (count($ended) === 0) + { + break; + } + $this->foldAndDelete($ended); + if (count($ended) < self::PurgeBatch) + { + break; + } + } $this->execute($this->db->createQuery() ->delete('#__bfstop_unblock') @@ -217,6 +251,83 @@ public function purgeEndedBefore($date) }, null); } + /** + * Counts the $blocks (objects with id, ipaddress and crdate) which an + * administrator hasn't lifted in the offences of their addresses, and + * deletes them all - in one transaction, so that a failure between the + * two doesn't count them again the next time. + */ + private function foldAndDelete(array $blocks) + { + $ids = array_map(fn ($block) => (int) $block->id, $blocks); + $lifted = $this->column($this->db->createQuery() + ->select($this->db->quoteName('block_id')) + ->from($this->db->quoteName(self::LiftTable)) + ->whereIn($this->db->quoteName('block_id'), $ids) + ->where($this->db->quoteName('source').' = '.self::LiftedByAdministrator)); + $lifted = array_flip(array_map('intval', $lifted)); + $offences = array(); + foreach ($blocks as $block) + { + if (isset($lifted[(int) $block->id])) + { + continue; + } + $address = (string) $block->ipaddress; + $offences[$address]['blocks'] = ($offences[$address]['blocks'] ?? 0) + 1; + $offences[$address]['last'] = max($offences[$address]['last'] ?? '', (string) $block->crdate); + } + + $this->inTransaction(function () use ($offences, $ids) + { + foreach ($offences as $address => $offence) + { + $this->addOffences((string) $address, $offence['blocks'], $offence['last']); + } + $this->execute($this->db->createQuery() + ->delete($this->db->quoteName(self::Table)) + ->whereIn($this->db->quoteName('id'), $ids)); + }); + } + + /** Adds $blocks to the offences of $address; the latest began at $last. */ + private function addOffences($address, $blocks, $last) + { + $known = $this->scalar($this->db->createQuery() + ->select($this->db->quoteName('ipaddress')) + ->from($this->db->quoteName(self::OffenceTable)) + ->where($this->db->quoteName('ipaddress').' = :ip'), array('ip' => (string) $address)); + if ($known === null || $known === false) + { + $this->insert(self::OffenceTable, array('ipaddress' => $address, 'blocks' => (int) $blocks, + 'last_block' => $last)); + return; + } + $this->execute($this->db->createQuery() + ->update($this->db->quoteName(self::OffenceTable)) + ->set($this->db->quoteName('blocks').' = '.$this->db->quoteName('blocks').' + :blocks') + ->set($this->db->quoteName('last_block').' = CASE WHEN '.$this->db->quoteName('last_block').' > :last1 THEN '. + $this->db->quoteName('last_block').' ELSE :last2 END') + ->where($this->db->quoteName('ipaddress').' = :ip'), + array('blocks' => (int) $blocks, 'last1' => (string) $last, 'last2' => (string) $last, 'ip' => (string) $address)); + } + + /** + * Forgets the addresses whose latest block began more than + * OffenceMemoryDays ago and, oldest first, as many more as needed to keep + * at most OffenceMaxRows. Fail-open: the next run does it. + */ + public function pruneOffences($memoryDays = null, $maxRows = null) + { + $memoryDays = $memoryDays ?? self::OffenceMemoryDays; + $maxRows = $maxRows ?? self::OffenceMaxRows; + $this->failOpen('pruneOffences', function () use ($memoryDays, $maxRows) + { + $this->deleteBefore(self::OffenceTable, 'last_block', self::daysAgo($memoryDays)); + $this->trimOldest(self::OffenceTable, 'ipaddress', 'last_block ASC', $maxRows, 1000, ParameterType::STRING); + }, null); + } + /** * Lifts the blocks $ids: whoever is blocked by them gets through again * (the blocks themselves stay, the next block's duration is based on diff --git a/library/src/Repository/Repository.php b/library/src/Repository/Repository.php index 5150cf1..225017f 100644 --- a/library/src/Repository/Repository.php +++ b/library/src/Repository/Repository.php @@ -57,6 +57,32 @@ protected function unknown($name, callable $operation) return FailurePolicy::guard($this->logger, static::class.'::'.$name, FailurePolicy::Unknown, $operation, null); } + /** + * Runs $work in a transaction: committed when it returns, rolled back when + * it throws. The exception goes on to the caller's failure policy (see + * failOpen()): this only makes sure the changes of $work are all or + * nothing. + */ + protected function inTransaction(callable $work) + { + $this->db->transactionStart(); + $committed = false; + try + { + $result = $work(); + $this->db->transactionCommit(); + $committed = true; + return $result; + } + finally + { + if (!$committed) + { + $this->db->transactionRollback(); + } + } + } + /** * Binds every value of $values as the parameter of its key (":key"). * The values are bound by reference, so $values must be a variable which diff --git a/library/src/Service/Maintenance.php b/library/src/Service/Maintenance.php index 13b867d..c114c2f 100644 --- a/library/src/Service/Maintenance.php +++ b/library/src/Service/Maintenance.php @@ -28,7 +28,10 @@ public function __construct(Repositories $repositories) /** * Deletes what is older than $purgeAgeWeeks weeks: failed logins, ended - * blocks (with the records of their lifting) and unblock tokens. + * blocks (with the records of their lifting) and unblock tokens. What the + * ended blocks add to the number of an address's offences is kept (see + * BlockRepository::purgeEndedBefore()), for the escalation of its next + * block. */ public function purgeOldEntries($purgeAgeWeeks) { @@ -57,5 +60,6 @@ public function keepWithinBounds() $this->repositories->knownIps()->prune(); $this->repositories->dnsCache()->prune(); $this->repositories->unblockTokens()->purgeExpired(); + $this->repositories->blocks()->pruneOffences(); } } diff --git a/plugin/sql/install.mysql.utf8.sql b/plugin/sql/install.mysql.utf8.sql index 64aecb3..2d3aaa8 100644 --- a/plugin/sql/install.mysql.utf8.sql +++ b/plugin/sql/install.mysql.utf8.sql @@ -47,6 +47,21 @@ CREATE TABLE IF NOT EXISTS #__bfstop_unblock ( ) DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci; +-- what the purge of old blocks keeps of them (issue #283, C14): the number of +-- blocks an address has had which were not lifted by an administrator, and +-- when the latest one began. Together with the blocks which are still there +-- this is what the duration of the next block is based on (maxBlocksBefore, +-- progressiveBlockDuration), so an attacker who returns every few weeks +-- still escalates; BlockRepository::pruneOffences() forgets the old ones. +CREATE TABLE IF NOT EXISTS #__bfstop_offence ( + ipaddress varchar(49) NOT NULL, + blocks int unsigned NOT NULL DEFAULT 0, + last_block datetime NOT NULL, + PRIMARY KEY (ipaddress), + KEY last_block (last_block) +) DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci; + + -- stores randomized tokens for unblocking an IP via an email -- to the blocked user -- username: the user the unblock link was sent to, to limit the links per user diff --git a/plugin/sql/install.postgresql.utf8.sql b/plugin/sql/install.postgresql.utf8.sql index ea4fdd3..cae30fa 100644 --- a/plugin/sql/install.postgresql.utf8.sql +++ b/plugin/sql/install.postgresql.utf8.sql @@ -45,6 +45,18 @@ CREATE TABLE IF NOT EXISTS "#__bfstop_unblock" ( ); +-- what the purge of old blocks keeps of them (issue #283, C14): the number of +-- blocks an address has had which were not lifted by an administrator, and +-- when the latest one began (see install.mysql.utf8.sql) +CREATE TABLE IF NOT EXISTS "#__bfstop_offence" ( + "ipaddress" varchar(49) NOT NULL, + "blocks" integer NOT NULL DEFAULT 0, + "last_block" timestamp without time zone NOT NULL, + PRIMARY KEY ("ipaddress") +); +CREATE INDEX IF NOT EXISTS "#__bfstop_offence_last_block" ON "#__bfstop_offence" ("last_block"); + + -- username: the user the unblock link was sent to, to limit the links per user -- username_lc: the same in lower case, for the lookups which must not tell -- "Bob" from "bob" - computed by the database diff --git a/plugin/sql/uninstall.mysql.utf8.sql b/plugin/sql/uninstall.mysql.utf8.sql index 1669a13..094f012 100644 --- a/plugin/sql/uninstall.mysql.utf8.sql +++ b/plugin/sql/uninstall.mysql.utf8.sql @@ -6,6 +6,8 @@ DROP TABLE IF EXISTS `#__bfstop_bannedip`; DROP TABLE IF EXISTS `#__bfstop_unblock`; +DROP TABLE IF EXISTS `#__bfstop_offence`; + DROP TABLE IF EXISTS `#__bfstop_unblock_token`; DROP TABLE IF EXISTS `#__bfstop_allowlist`; diff --git a/plugin/sql/uninstall.postgresql.utf8.sql b/plugin/sql/uninstall.postgresql.utf8.sql index c5d3bc3..e9d9bb9 100644 --- a/plugin/sql/uninstall.postgresql.utf8.sql +++ b/plugin/sql/uninstall.postgresql.utf8.sql @@ -6,6 +6,8 @@ DROP TABLE IF EXISTS "#__bfstop_bannedip"; DROP TABLE IF EXISTS "#__bfstop_unblock"; +DROP TABLE IF EXISTS "#__bfstop_offence"; + DROP TABLE IF EXISTS "#__bfstop_unblock_token"; DROP TABLE IF EXISTS "#__bfstop_allowlist"; diff --git a/plugin/sql/updates/2.0.0.sql b/plugin/sql/updates/2.0.0.sql index ae3a64e..f2625a2 100755 --- a/plugin/sql/updates/2.0.0.sql +++ b/plugin/sql/updates/2.0.0.sql @@ -88,6 +88,16 @@ ALTER TABLE `#__bfstop_failedlogin` ADD INDEX logtime (logtime) /** CAN FAIL **/ ALTER TABLE `#__bfstop_bannedip` ADD INDEX ipaddress (ipaddress) /** CAN FAIL **/; ALTER TABLE `#__bfstop_allowlist` ADD INDEX ipaddress (ipaddress) /** CAN FAIL **/; +-- what the purge of old blocks keeps of them (issue #283, C14), see +-- install.mysql.utf8.sql; blocks purged by earlier versions are gone +CREATE TABLE IF NOT EXISTS `#__bfstop_offence` ( + ipaddress varchar(49) NOT NULL, + blocks int unsigned NOT NULL DEFAULT 0, + last_block datetime NOT NULL, + PRIMARY KEY (ipaddress), + KEY last_block (last_block) +) DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci; + -- the plugin's own bookkeeping (name => value), apart from its settings: when -- the maintenance last ran. In the plugin's row of #__extensions, it was -- written by requests with the whole settings, and so raced with an diff --git a/tests/Integration/IntegrationTestCase.php b/tests/Integration/IntegrationTestCase.php index d4040a6..c6a0eef 100644 --- a/tests/Integration/IntegrationTestCase.php +++ b/tests/Integration/IntegrationTestCase.php @@ -66,7 +66,7 @@ public function log($msg, $priority) abstract class IntegrationTestCase extends TestCase { public const Tables = array('failedlogin', 'bannedip', 'unblock', - 'unblock_token', 'allowlist', 'knownip', 'dnscache', 'username_stats', 'state'); + 'offence', 'unblock_token', 'allowlist', 'knownip', 'dnscache', 'username_stats', 'state'); protected $db; protected $logger; diff --git a/tests/Integration/RepositoriesTest.php b/tests/Integration/RepositoriesTest.php index 9f38703..ef9e712 100644 --- a/tests/Integration/RepositoriesTest.php +++ b/tests/Integration/RepositoriesTest.php @@ -160,6 +160,67 @@ public function testNumberOfPreviousBlocks() $this->assertSame(1, $this->repos->blocks()->countPrevious('203.0.113.9')); } + public function testPurgedBlocksStillCountAsPreviousBlocks() + { + $old = 10 * 24 * 60; + $this->block('203.0.113.7', $old, 60); + $this->block('203.0.113.7', $old + 60, 60); + $this->block('203.0.113.7', 10, 60); // not ended-and-old: stays + $byAdministrator = $this->block('203.0.113.8', $old, 60); + $this->insert('#__bfstop_unblock', array('block_id' => $byAdministrator, 'source' => 0, 'crdate' => self::minutesAgo(0))); + $byMail = $this->block('203.0.113.9', $old, 60); + $this->insert('#__bfstop_unblock', array('block_id' => $byMail, 'source' => 1, 'crdate' => self::minutesAgo(0))); + $this->assertSame(3, $this->repos->blocks()->countPrevious('203.0.113.7')); + + $this->maintenance->purgeOldEntries(1); + + $this->assertSame(1, (int) $this->queryValue("SELECT COUNT(*) FROM #__bfstop_bannedip WHERE ipaddress = '203.0.113.7'")); + $this->assertSame(3, $this->repos->blocks()->countPrevious('203.0.113.7'), 'the purged ones are still counted'); + $this->assertSame(0, $this->repos->blocks()->countPrevious('203.0.113.8'), 'lifted by an administrator: not counted'); + $this->assertSame(1, $this->repos->blocks()->countPrevious('203.0.113.9'), 'lifted by the mail: counted'); + $this->assertSame(0, (int) $this->queryValue("SELECT COUNT(*) FROM #__bfstop_offence WHERE ipaddress = '203.0.113.8'")); + + // a second purge adds nothing: what was counted is deleted + $this->maintenance->purgeOldEntries(1); + $this->assertSame(3, $this->repos->blocks()->countPrevious('203.0.113.7')); + $this->assertSame(2, (int) $this->queryValue("SELECT blocks FROM #__bfstop_offence WHERE ipaddress = '203.0.113.7'")); + + // more ended blocks of the same address add to its row + $this->block('203.0.113.7', $old, 60); + $this->maintenance->purgeOldEntries(1); + $this->assertSame(3, (int) $this->queryValue("SELECT blocks FROM #__bfstop_offence WHERE ipaddress = '203.0.113.7'")); + $this->assertSame(1, (int) $this->queryValue("SELECT COUNT(*) FROM #__bfstop_offence WHERE ipaddress = '203.0.113.7'")); + } + + public function testPurgeOfManyEndedBlocksIsCountedOnce() + { + $old = 10 * 24 * 60; + for ($i = 0; $i < 1200; ++$i) + { + $this->block('203.0.113.'.(1 + $i % 3), $old, 60); + } + $this->maintenance->purgeOldEntries(1); + $this->assertSame(0, (int) $this->queryValue('SELECT COUNT(*) FROM #__bfstop_bannedip')); + $this->assertSame(1200, (int) $this->queryValue('SELECT SUM(blocks) FROM #__bfstop_offence')); + $this->assertSame(400, $this->repos->blocks()->countPrevious('203.0.113.2')); + } + + public function testOffencesAreForgottenAfterAYearAndBounded() + { + $row = fn ($ip, $daysAgo) => $this->insert('#__bfstop_offence', + array('ipaddress' => $ip, 'blocks' => 2, 'last_block' => self::minutesAgo($daysAgo * 24 * 60))); + $row('203.0.113.1', 400); // forgotten + $row('203.0.113.2', 30); + $row('203.0.113.3', 90); + $row('203.0.113.4', 10); + $addresses = fn () => $this->db->setQuery('SELECT ipaddress FROM #__bfstop_offence ORDER BY ipaddress')->loadColumn(); + $this->repos->blocks()->pruneOffences(); + $this->assertSame(array('203.0.113.2', '203.0.113.3', '203.0.113.4'), $addresses()); + $this->repos->blocks()->pruneOffences(null, 2); + $this->assertSame(array('203.0.113.2', '203.0.113.4'), $addresses(), 'the oldest go first'); + $this->assertSame(0, $this->repos->blocks()->countPrevious('203.0.113.3')); + } + public function testBlockIPAndRecordAttempts() { $this->failedLogin('203.0.113.50', 'bob', 0);