diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9ca0c9..ad526bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,7 +87,8 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.1', '8.4', '8.5'] + # the oldest PHP BFStop runs on, and the newest + php: ['8.2', '8.4', '8.5'] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 @@ -99,8 +100,6 @@ jobs: - name: Check PHP syntax run: find . -name '*.php' -not -path './.git/*' -print0 | xargs -0 -n1 php -l - name: Unit tests - # PHPUnit 11 needs PHP >= 8.2 - if: matrix.php != '8.1' run: phpunit -c tests/phpunit.xml.dist --testsuite unit apache: @@ -200,7 +199,8 @@ jobs: - name: Start database (${{ matrix.db }}) env: - DB_IMAGE: ${{ matrix.db }} + # pinned by its digest, see tests/ci/matrix.json + DB_IMAGE: ${{ matrix.db }}@${{ matrix.digest }} run: tests/ci/start-database.sh # the release packages the tests install (Joomla; for the update, the @@ -256,7 +256,8 @@ jobs: ini-values: error_reporting=E_ALL - name: Start database (${{ matrix.db }}) env: - DB_IMAGE: ${{ matrix.db }} + # pinned by its digest, see tests/ci/matrix.json + DB_IMAGE: ${{ matrix.db }}@${{ matrix.digest }} run: tests/ci/start-database.sh # the release packages the tests install (Joomla; for the update, the # previous BFStop release) are kept between runs instead of being diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index d96bedc..539acc6 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -11,30 +11,56 @@ on: permissions: contents: read - issues: write jobs: + # runs composer (and with it whatever the packages bring) without any + # permission to write: the issue is opened by the job below geoip-reader: name: maxmind-db/reader is current and free of advisories runs-on: ubuntu-latest + outputs: + # what failed: only a finding of a check opens an issue, not a + # download that didn't work + finding: ${{ steps.vendored.outcome == 'failure' || steps.audit.outcome == 'failure' || steps.outdated.outcome == 'failure' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 with: php-version: '8.4' coverage: none - run: composer install --no-interaction --no-progress - name: Vendored copy is the locked version + id: vendored + continue-on-error: true run: composer check-geoip - name: Security advisories + id: audit + continue-on-error: true run: composer audit - name: Newer release available? + id: outdated + continue-on-error: true + run: composer outdated --direct --strict maxmind-db/reader + - name: Result + if: steps.vendored.outcome == 'failure' || steps.audit.outcome == 'failure' || steps.outdated.outcome == 'failure' run: | - composer outdated --direct --strict maxmind-db/reader - - name: Open an issue - if: failure() + echo "::error::vendored copy: ${{ steps.vendored.outcome }}, advisories: ${{ steps.audit.outcome }}, newer release: ${{ steps.outdated.outcome }}" + exit 1 + + issue: + name: Open an issue + needs: geoip-reader + if: always() && needs.geoip-reader.outputs.finding == 'true' + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: Open an issue unless there is one env: GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} run: | title="Update the vendored GeoIP reader (maxmind-db/reader)" if [ -z "$(gh issue list --state open --search "in:title $title" --json number --jq '.[0].number')" ]; then diff --git a/CHANGELOG b/CHANGELOG index e545da5..2df39b3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,30 @@ 2.0.0 (unreleased) + - Requires PHP 8.2 (was 8.1), the oldest version CI runs the tests on + - Review fixes: an unblock mail is no longer sent with an empty token when + the token can't be stored; failed logins typed with the email address or + in another case get the account's unblock mail (none for a disabled + account) and are cleared by its successful login; "All" in the list of + the .htaccess file shows all entries instead of none; without a + notification address, blocks no longer log an error; group + notifications skip disabled accounts; a block's duration of less than 0 + minutes counts as unlimited everywhere (and the block form takes 0 or + more, and a valid start); a broken manifest cache no longer breaks the + settings page; the list controllers no longer offer Joomla's publish, + delete, ... tasks, which ended in an error page; "Save" in the .htaccess + form is offered by the same permissions the save needs, and the form + validates with its own fields and stores the entry in canonical form; + an update that can't migrate the settings says so; known addresses of + two logins at the same time are one row; the log sorts by severity + - Hand-written blocks in the .htaccess block section are kept intact + by every change and by the uninstallation + - Code clean-up: every setting's default is in Settings::Defaults (and + read with Settings::get()), lock files are named by LockHelper::file(), + form rules return their error instead of posting it, unused code removed + (the token unblock without confirmation, the 403 message of .htaccess, + DateRule, UnblockTokenRepository::exists()), duplicates of the library's + origin names and network masks removed + - CI: database images pinned by digest, PostgreSQL 15 instead of 12; the + weekly dependency check runs composer without write permissions - Code clean-up (issue #283): unblock tokens are 40 hex digits of random_bytes() without the weaker fallback generator; the notifier's "one day" is a constant; the log page of the component shows the newest diff --git a/README.md b/README.md index 7fa5584..47d2277 100644 --- a/README.md +++ b/README.md @@ -37,12 +37,28 @@ of another, only those of the library. [releases](https://github.com/codeling/bfstop/releases). It contains the plugin and the component and installs both. Don't install them separately: they are released together, and need to have the same version. -- Requirements: Joomla! 5.4 or 6, PHP 8.1 or newer, and MySQL, MariaDB or +- Requirements: Joomla! 5.4 or 6, PHP 8.2 or newer, and MySQL, MariaDB or PostgreSQL. Sites still on Joomla! 4 stay with BFStop 1.5. - The plugin is enabled when it is installed. Configure BFStop under *Components → Brute Force Stop → Settings*. - Joomla! offers updates through its update manager. +### What the delays can and can't do + +Blocking is what protects the login: an address (an IPv6 client: its +network) gets only so many failed logins. The delays - the delay of the +response to a failed login, the adaptive delay, the account throttle and the +delay per point of the risk score - only slow down a client which waits for +one answer before it sends the next attempt. Each delayed response holds a +PHP worker for as long as it is delayed, so at most "delayMaxConcurrent" +responses are delayed at the same time (and none longer than 60 seconds); +any further failed login is answered at once. An attacker who sends many +attempts in parallel, from many addresses, therefore gets most answers +without delay: the account throttle in particular doesn't stop a distributed +attack on one account, it only makes it a little slower. Holding many +connections open cheaply is something only the web server or a proxy in +front of it can do (e.g. nginx's `limit_req`). + ## Resources - Documentation: [the bfstop wiki](https://github.com/codeling/bfstop/wiki) diff --git a/component/admin/language/ca-ES/ca-ES.com_bfstop.ini b/component/admin/language/ca-ES/ca-ES.com_bfstop.ini index 7ab01e5..befc4c2 100644 --- a/component/admin/language/ca-ES/ca-ES.com_bfstop.ini +++ b/component/admin/language/ca-ES/ca-ES.com_bfstop.ini @@ -71,6 +71,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 hores" COM_BFSTOP_BLOCK_8HOURS="8 hores" COM_BFSTOP_BLOCK_24HOURS="1 dia" COM_BFSTOP_BLOCK_N_MINUTES="%d minuts" +COM_BFSTOP_BLOCK_DURATION_INVALID="La durada d'un bloqueig és un nombre de minuts: 0 (il·limitat) o més." +COM_BFSTOP_BLOCK_START_INVALID="L'inici d'un bloqueig és una data (i hora) com 2026-01-31 o 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d hores" COM_BFSTOP_BLOCK_N_DAYS="%d dies" COM_BFSTOP_NO_IPINFO_AVAILABLE="No hi ha informació disponible per a aquesta adreça IP" diff --git a/component/admin/language/de-DE/de-DE.com_bfstop.ini b/component/admin/language/de-DE/de-DE.com_bfstop.ini index b097e5a..d4632d1 100644 --- a/component/admin/language/de-DE/de-DE.com_bfstop.ini +++ b/component/admin/language/de-DE/de-DE.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 Stunden" COM_BFSTOP_BLOCK_8HOURS="8 Stunden" COM_BFSTOP_BLOCK_24HOURS="1 Tag" COM_BFSTOP_BLOCK_N_MINUTES="%d Minuten" +COM_BFSTOP_BLOCK_DURATION_INVALID="Die Dauer einer Sperre ist eine Anzahl von Minuten: 0 (unbegrenzt) oder mehr." +COM_BFSTOP_BLOCK_START_INVALID="Der Beginn einer Sperre ist ein Datum (mit Uhrzeit) wie 2026-01-31 oder 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d Stunden" COM_BFSTOP_BLOCK_N_DAYS="%d Tage" COM_BFSTOP_NO_IPINFO_AVAILABLE="Keine Informationen zu dieser IP-Adresse verfügbar" diff --git a/component/admin/language/en-GB/en-GB.com_bfstop.ini b/component/admin/language/en-GB/en-GB.com_bfstop.ini index 4439e48..03a9285 100644 --- a/component/admin/language/en-GB/en-GB.com_bfstop.ini +++ b/component/admin/language/en-GB/en-GB.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 hours" COM_BFSTOP_BLOCK_8HOURS="8 hours" COM_BFSTOP_BLOCK_24HOURS="1 day" COM_BFSTOP_BLOCK_N_MINUTES="%d minutes" +COM_BFSTOP_BLOCK_DURATION_INVALID="The duration of a block is a number of minutes: 0 (unlimited) or more." +COM_BFSTOP_BLOCK_START_INVALID="The start of a block is a date (and time) like 2026-01-31 or 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d hours" COM_BFSTOP_BLOCK_N_DAYS="%d days" COM_BFSTOP_NO_IPINFO_AVAILABLE="No information available for that IP address" diff --git a/component/admin/language/es-ES/es-ES.com_bfstop.ini b/component/admin/language/es-ES/es-ES.com_bfstop.ini index 84b1029..355f265 100644 --- a/component/admin/language/es-ES/es-ES.com_bfstop.ini +++ b/component/admin/language/es-ES/es-ES.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 horas" COM_BFSTOP_BLOCK_8HOURS="8 horas" COM_BFSTOP_BLOCK_24HOURS="1 día" COM_BFSTOP_BLOCK_N_MINUTES="%d minutos" +COM_BFSTOP_BLOCK_DURATION_INVALID="La duración de un bloqueo es un número de minutos: 0 (ilimitado) o más." +COM_BFSTOP_BLOCK_START_INVALID="El inicio de un bloqueo es una fecha (y hora) como 2026-01-31 o 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d horas" COM_BFSTOP_BLOCK_N_DAYS="%d días" COM_BFSTOP_NO_IPINFO_AVAILABLE="No hay información disponible para esa dirección IP" diff --git a/component/admin/language/fr-FR/fr-FR.com_bfstop.ini b/component/admin/language/fr-FR/fr-FR.com_bfstop.ini index 3b91de0..731ef3c 100644 --- a/component/admin/language/fr-FR/fr-FR.com_bfstop.ini +++ b/component/admin/language/fr-FR/fr-FR.com_bfstop.ini @@ -72,6 +72,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 heures" COM_BFSTOP_BLOCK_8HOURS="8 heures" COM_BFSTOP_BLOCK_24HOURS="1 jour" COM_BFSTOP_BLOCK_N_MINUTES="%d minutes" +COM_BFSTOP_BLOCK_DURATION_INVALID="La durée d'un blocage est un nombre de minutes : 0 (illimité) ou plus." +COM_BFSTOP_BLOCK_START_INVALID="Le début d'un blocage est une date (et une heure) comme 2026-01-31 ou 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d heures" COM_BFSTOP_BLOCK_N_DAYS="%d jours" COM_BFSTOP_NO_IPINFO_AVAILABLE="Aucune information disponible pour cette adresse IP" diff --git a/component/admin/language/it-IT/it-IT.com_bfstop.ini b/component/admin/language/it-IT/it-IT.com_bfstop.ini index 1d98430..d1f1f4c 100644 --- a/component/admin/language/it-IT/it-IT.com_bfstop.ini +++ b/component/admin/language/it-IT/it-IT.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 ore" COM_BFSTOP_BLOCK_8HOURS="8 ore" COM_BFSTOP_BLOCK_24HOURS="1 giorno" COM_BFSTOP_BLOCK_N_MINUTES="%d minuti" +COM_BFSTOP_BLOCK_DURATION_INVALID="La durata di un blocco è un numero di minuti: 0 (illimitato) o più." +COM_BFSTOP_BLOCK_START_INVALID="L'inizio di un blocco è una data (e ora) come 2026-01-31 o 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d ore" COM_BFSTOP_BLOCK_N_DAYS="%d giorni" COM_BFSTOP_NO_IPINFO_AVAILABLE="Nessuna informazione disponibile per questo indirizzo IP" diff --git a/component/admin/language/nl-NL/nl-NL.com_bfstop.ini b/component/admin/language/nl-NL/nl-NL.com_bfstop.ini index 3fd5dbf..18b7969 100644 --- a/component/admin/language/nl-NL/nl-NL.com_bfstop.ini +++ b/component/admin/language/nl-NL/nl-NL.com_bfstop.ini @@ -70,6 +70,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 uur" COM_BFSTOP_BLOCK_8HOURS="8 uur" COM_BFSTOP_BLOCK_24HOURS="1 dag" COM_BFSTOP_BLOCK_N_MINUTES="%d minuten" +COM_BFSTOP_BLOCK_DURATION_INVALID="De duur van een blokkering is een aantal minuten: 0 (onbeperkt) of meer." +COM_BFSTOP_BLOCK_START_INVALID="Het begin van een blokkering is een datum (en tijd) zoals 2026-01-31 of 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d uur" COM_BFSTOP_BLOCK_N_DAYS="%d dagen" COM_BFSTOP_NO_IPINFO_AVAILABLE="Geen informatie beschikbaar voor dit IP-adres" diff --git a/component/admin/language/pt-BR/pt-BR.com_bfstop.ini b/component/admin/language/pt-BR/pt-BR.com_bfstop.ini index eacfd14..ee4b785 100644 --- a/component/admin/language/pt-BR/pt-BR.com_bfstop.ini +++ b/component/admin/language/pt-BR/pt-BR.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 horas" COM_BFSTOP_BLOCK_8HOURS="8 horas" COM_BFSTOP_BLOCK_24HOURS="1 dia" COM_BFSTOP_BLOCK_N_MINUTES="%d minutos" +COM_BFSTOP_BLOCK_DURATION_INVALID="A duração de um bloqueio é um número de minutos: 0 (ilimitado) ou mais." +COM_BFSTOP_BLOCK_START_INVALID="O início de um bloqueio é uma data (e hora) como 2026-01-31 ou 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d horas" COM_BFSTOP_BLOCK_N_DAYS="%d dias" COM_BFSTOP_NO_IPINFO_AVAILABLE="Nenhuma informação disponível para esse endereço IP" diff --git a/component/admin/language/pt-PT/pt-PT.com_bfstop.ini b/component/admin/language/pt-PT/pt-PT.com_bfstop.ini index 7228557..acefe11 100644 --- a/component/admin/language/pt-PT/pt-PT.com_bfstop.ini +++ b/component/admin/language/pt-PT/pt-PT.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 horas" COM_BFSTOP_BLOCK_8HOURS="8 horas" COM_BFSTOP_BLOCK_24HOURS="1 dia" COM_BFSTOP_BLOCK_N_MINUTES="%d minutos" +COM_BFSTOP_BLOCK_DURATION_INVALID="A duração de um bloqueio é um número de minutos: 0 (ilimitado) ou mais." +COM_BFSTOP_BLOCK_START_INVALID="O início de um bloqueio é uma data (e hora) como 2026-01-31 ou 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d horas" COM_BFSTOP_BLOCK_N_DAYS="%d dias" COM_BFSTOP_NO_IPINFO_AVAILABLE="Nenhuma informação disponível para esse endereço IP" diff --git a/component/admin/language/ru-RU/ru-RU.com_bfstop.ini b/component/admin/language/ru-RU/ru-RU.com_bfstop.ini index 23a0a41..f4a487f 100644 --- a/component/admin/language/ru-RU/ru-RU.com_bfstop.ini +++ b/component/admin/language/ru-RU/ru-RU.com_bfstop.ini @@ -69,6 +69,8 @@ COM_BFSTOP_BLOCK_4HOURS="4 часа" COM_BFSTOP_BLOCK_8HOURS="8 часов" COM_BFSTOP_BLOCK_24HOURS="1 день" COM_BFSTOP_BLOCK_N_MINUTES="%d мин." +COM_BFSTOP_BLOCK_DURATION_INVALID="Длительность блокировки — это число минут: 0 (без ограничения) или больше." +COM_BFSTOP_BLOCK_START_INVALID="Начало блокировки — это дата (и время), например 2026-01-31 или 2026-01-31 14:30:00." COM_BFSTOP_BLOCK_N_HOURS="%d ч." COM_BFSTOP_BLOCK_N_DAYS="%d дн." COM_BFSTOP_NO_IPINFO_AVAILABLE="Для этого IP-адреса нет информации" diff --git a/component/admin/src/Controller/AllowlistController.php b/component/admin/src/Controller/AllowlistController.php index 0466669..14f3b1e 100644 --- a/component/admin/src/Controller/AllowlistController.php +++ b/component/admin/src/Controller/AllowlistController.php @@ -12,11 +12,16 @@ use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; use Joomla\CMS\Language\Text; -use Joomla\CMS\MVC\Controller\AdminController; +use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\Router\Route; use Joomla\Utilities\ArrayHelper; -class AllowlistController extends AdminController +/** + * The tasks of the list (see the toolbar of its view): a BaseController, not + * an AdminController, whose tasks (publish, delete, checkin, ...) call + * methods a list model hasn't got - an error page instead of an answer. + */ +class AllowlistController extends BaseController { public function getModel($name = 'allowlist', $prefix = '', $config = []) { diff --git a/component/admin/src/Controller/BlocklistController.php b/component/admin/src/Controller/BlocklistController.php index e9d039f..8e7506e 100644 --- a/component/admin/src/Controller/BlocklistController.php +++ b/component/admin/src/Controller/BlocklistController.php @@ -12,10 +12,15 @@ use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; use Joomla\CMS\Language\Text; -use Joomla\CMS\MVC\Controller\AdminController; +use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\Router\Route; -class BlocklistController extends AdminController +/** + * The tasks of the list (see the toolbar of its view): a BaseController, not + * an AdminController, whose tasks (publish, delete, checkin, ...) call + * methods a list model hasn't got - an error page instead of an answer. + */ +class BlocklistController extends BaseController { public function getModel($name = 'blocklist', $prefix = '', $config = []) { diff --git a/component/admin/src/Controller/DisplayController.php b/component/admin/src/Controller/DisplayController.php index 98e6b0f..6929761 100644 --- a/component/admin/src/Controller/DisplayController.php +++ b/component/admin/src/Controller/DisplayController.php @@ -93,7 +93,7 @@ public function warnIfHtAccessNotWorking() */ public function warnIfUnblockLinksNeedLiveSite() { - $setting = (int) ParamHelper::get('notifyBlockedUser', 0); + $setting = (int) ParamHelper::get('notifyBlockedUser'); if (BlockPolicy::effectiveNotifyBlockedUser($setting, BlockPolicy::hasLiveSite()) !== $setting) { $this->app->enqueueMessage(Text::sprintf('COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE', @@ -103,7 +103,7 @@ public function warnIfUnblockLinksNeedLiveSite() public function checkWhetherProxyConfigured() { - $useProxy = (bool) ParamHelper::get('useProxy', false); + $useProxy = (bool) ParamHelper::get('useProxy'); if ($useProxy) { return; diff --git a/component/admin/src/Controller/FailedloginlistController.php b/component/admin/src/Controller/FailedloginlistController.php index 39368aa..b267bba 100644 --- a/component/admin/src/Controller/FailedloginlistController.php +++ b/component/admin/src/Controller/FailedloginlistController.php @@ -13,10 +13,15 @@ use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; -use Joomla\CMS\MVC\Controller\AdminController; +use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\Router\Route; -class FailedloginlistController extends AdminController +/** + * The tasks of the list (see the toolbar of its view): a BaseController, not + * an AdminController, whose tasks (publish, delete, checkin, ...) call + * methods a list model hasn't got - an error page instead of an answer. + */ +class FailedloginlistController extends BaseController { public function getModel($name = 'failedloginlist', $prefix = '', $config = []) { diff --git a/component/admin/src/Controller/HtblockController.php b/component/admin/src/Controller/HtblockController.php index 47028a9..da73d88 100644 --- a/component/admin/src/Controller/HtblockController.php +++ b/component/admin/src/Controller/HtblockController.php @@ -11,7 +11,6 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; -use Codeling\Component\Bfstop\Administrator\Helper\ParamHelper; use Codeling\Component\Bfstop\Administrator\Helper\UnblockHelper; use Codeling\Library\Bfstop\Repository\Repositories; use Codeling\Library\Bfstop\Helper\HtaccessHelper; @@ -23,6 +22,18 @@ class HtblockController extends FormController { + /** + * Whether $user may add an entry to the .htaccess file: it is part of the + * web server's configuration, which turns addresses away before Joomla + * runs, so nobody in it can lift it from within the site - core.admin as + * well as core.create, like the settings (which choose the file) and the + * allow list. The toolbars ask this too. + */ + public static function mayAdd($user): bool + { + return $user && $user->authorise('core.create', 'com_bfstop') && $user->authorise('core.admin', 'com_bfstop'); + } + public function add() { $this->setRedirect( @@ -46,13 +57,8 @@ public function save($key = null, $urlVar = null) { $this->checkToken(); // this fully overrides FormController::save(), so it doesn't - // inherit the base class's automatic allowSave()/core.create check. - // An entry is part of the web server's configuration: it turns - // addresses away before Joomla runs, so nobody can lift it from - // within the site who is in it - core.admin as well, like the - // settings (which choose the file) and the allow list - $user = $this->app->getIdentity(); - if (!$user || !$user->authorise('core.create', 'com_bfstop') || !$user->authorise('core.admin', 'com_bfstop')) + // inherit the base class's automatic allowSave()/core.create check + if (!self::mayAdd($this->app->getIdentity())) { $this->returnToFormWithMessage('', Text::_('COM_BFSTOP_NOT_AUTHORISED')); return false; @@ -60,8 +66,9 @@ public function save($key = null, $urlVar = null) $logger = LogHelper::getLogger(); $htaccessPath = UnblockHelper::getHtaccessPath(); $htaccess = new HtaccessHelper($htaccessPath, null); - $model = $this->getModel('block'); - $form = $model->getForm(null, false); + // the form of the view, see HtblockModel + $model = $this->getModel('htblock'); + $form = $model->getForm(array(), false); $input = $this->input; $data = $input->post->get('jform', array(), 'array'); $validData = $model->validate($form, $data); @@ -78,7 +85,9 @@ public function save($key = null, $urlVar = null) $this->returnToFormWithMessage(is_string($data['ipaddress'] ?? null) ? $data['ipaddress'] : '', $msg); return false; } - $ipaddress = $validData['ipaddress']; + // in the spelling the block list has it, which the file's entries + // are compared with (see HtaccessHelper::isEntryOf()) + $ipaddress = IpHelper::canonicalEntry($validData['ipaddress']) ?? (string) $validData['ipaddress']; $repositories = new Repositories($logger); // the web server knows nothing of the allow list: a network in the // file would also turn away the allowed addresses in it (and an diff --git a/component/admin/src/Controller/HtblocklistController.php b/component/admin/src/Controller/HtblocklistController.php index 5b9d86b..be9a687 100644 --- a/component/admin/src/Controller/HtblocklistController.php +++ b/component/admin/src/Controller/HtblocklistController.php @@ -12,10 +12,15 @@ use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; use Joomla\CMS\Language\Text; -use Joomla\CMS\MVC\Controller\AdminController; +use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\Router\Route; -class HtblocklistController extends AdminController +/** + * The tasks of the list (see the toolbar of its view): a BaseController, not + * an AdminController, whose tasks (publish, delete, checkin, ...) call + * methods a list model hasn't got - an error page instead of an answer. + */ +class HtblocklistController extends BaseController { public function getModel($name = 'htblocklist', $prefix = '', $config = []) { diff --git a/component/admin/src/Controller/LogController.php b/component/admin/src/Controller/LogController.php index 0f4aa4b..23e1fd1 100644 --- a/component/admin/src/Controller/LogController.php +++ b/component/admin/src/Controller/LogController.php @@ -51,14 +51,14 @@ public function prune() { return; } - $keepDays = (int) ParamHelper::get('logKeepDays', LoggerHelper::DefaultKeepDays); + $keepDays = (int) ParamHelper::get('logKeepDays'); if ($keepDays < 1) { $this->setRedirect($listUrl, Text::sprintf('COM_BFSTOP_LOG_PRUNE_DISABLED', Route::_('index.php?option=com_bfstop&view=settings', false)), 'warning'); return; } - $maxMB = (int) ParamHelper::get('logMaxSize', LoggerHelper::DefaultMaxSizeMB); + $maxMB = (int) ParamHelper::get('logMaxSize'); LoggerHelper::rotateIfTooBig(LoggerHelper::maxBytesFromMegabytes($maxMB)); $deleted = LoggerHelper::pruneByAge($keepDays); LogHelper::getLogger()->log("Manually pruned $deleted log entries older than $keepDays days", Log::INFO); diff --git a/component/admin/src/Controller/SettingsController.php b/component/admin/src/Controller/SettingsController.php index 9d989f4..1359570 100644 --- a/component/admin/src/Controller/SettingsController.php +++ b/component/admin/src/Controller/SettingsController.php @@ -111,10 +111,10 @@ public function testNotify() Text::_('COM_BFSTOP_NOT_AUTHORISED'), 'error'); return; } - $emailAddress = ParamHelper::get('emailaddress', ''); - $userID = (int) ParamHelper::get('userID', -1); - $userGroup = (int) ParamHelper::get('userGroup', -1); - $groupNotifEnabled = (bool) ParamHelper::get('groupNotificationEnabled', false); + $emailAddress = ParamHelper::get('emailaddress'); + $userID = (int) ParamHelper::get('userID'); + $userGroup = (int) ParamHelper::get('userGroup'); + $groupNotifEnabled = (bool) ParamHelper::get('groupNotificationEnabled'); $logger = LogHelper::getLogger(); $notifier = new NotifierHelper($logger, new Repositories($logger), $emailAddress, diff --git a/component/admin/src/Controller/UsernamestatsController.php b/component/admin/src/Controller/UsernamestatsController.php index 9b21f5a..6e39f66 100644 --- a/component/admin/src/Controller/UsernamestatsController.php +++ b/component/admin/src/Controller/UsernamestatsController.php @@ -13,10 +13,15 @@ use Codeling\Component\Bfstop\Administrator\Helper\LogHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; -use Joomla\CMS\MVC\Controller\AdminController; +use Joomla\CMS\MVC\Controller\BaseController; use Joomla\CMS\Router\Route; -class UsernamestatsController extends AdminController +/** + * The tasks of the list (see the toolbar of its view): a BaseController, not + * an AdminController, whose tasks (publish, delete, checkin, ...) call + * methods a list model hasn't got - an error page instead of an answer. + */ +class UsernamestatsController extends BaseController { public function getModel($name = 'usernamestats', $prefix = '', $config = []) { diff --git a/component/admin/src/Helper/DurationHelper.php b/component/admin/src/Helper/DurationHelper.php index e9cc6b4..9cff2f4 100644 --- a/component/admin/src/Helper/DurationHelper.php +++ b/component/admin/src/Helper/DurationHelper.php @@ -36,7 +36,8 @@ class DurationHelper */ public static function toReadable($duration) { - $duration = (int) $duration; + // 0 or less: for ever, see BlockPolicy::realDuration() + $duration = max(0, (int) $duration); if (array_key_exists($duration, self::Named)) { return Text::_(self::Named[$duration]); diff --git a/component/admin/src/Helper/IpRangeHelper.php b/component/admin/src/Helper/IpRangeHelper.php index 074a5fd..48e45ad 100644 --- a/component/admin/src/Helper/IpRangeHelper.php +++ b/component/admin/src/Helper/IpRangeHelper.php @@ -10,6 +10,8 @@ defined('_JEXEC') or die; +use Codeling\Library\Bfstop\Helper\IpHelper; + class IpRangeHelper { public static function isIPv6($ip) @@ -32,49 +34,23 @@ public static function formatCount($count) return is_float($count) ? sprintf('%.0f', $count) : (string) $count; } - // builds a $bits-long run of 1-bits (from the most significant bit), - // packed into a 16-byte binary string, for use as an IPv6 netmask - public static function ipv6Mask($bits) - { - $fullBytes = intdiv($bits, 8); - $mask = str_repeat("\xff", $fullBytes); - $remainderBits = $bits % 8; - if ($remainderBits > 0) - { - $mask .= chr((0xff << (8 - $remainderBits)) & 0xff); - } - return str_pad($mask, 16, "\x00"); - } - - private static function cidrToRangeIPv6($cidrParts) - { - $startBin = inet_pton($cidrParts[0]); - $mask = self::ipv6Mask((int) $cidrParts[1]); - $invertedMask = $mask ^ str_repeat("\xff", 16); - $startBin &= $mask; - $endBin = $startBin | $invertedMask; - return array(inet_ntop($startBin), inet_ntop($endBin)); - } - - private static function cidrToRangeIPv4($cidrParts) - { - $range = array(); - $startIP = ip2long($cidrParts[0]); - $mask = -1 << (32 - (int) $cidrParts[1]); - $range[0] = long2ip($startIP & $mask); - $newStartIP = ip2long($range[0]); - $range[1] = long2ip($newStartIP + pow(2, 32 - (int) $cidrParts[1]) - 1); - return $range; - } - - // adapted from https://stackoverflow.com/a/5858676 + /** + * The first and the last address of the network $cidr ("192.0.2.77/24" + * gives 192.0.2.0 and 192.0.2.255), for IPv4 and IPv6 alike. + * + * @return string[] array(first, last) + */ public static function cidrToRange($cidr) { $cidrParts = explode('/', $cidr); - if (self::isIPv6($cidrParts[0])) + $bin = @inet_pton($cidrParts[0]); + if ($bin === false || count($cidrParts) !== 2) { - return self::cidrToRangeIPv6($cidrParts); + // an entry which is no network (typed by hand into the table) + return array('', ''); } - return self::cidrToRangeIPv4($cidrParts); + $mask = IpHelper::prefixMask((int) $cidrParts[1], strlen($bin)); + $first = $bin & $mask; + return array(inet_ntop($first), inet_ntop($first | ($mask ^ str_repeat("\xff", strlen($bin))))); } } diff --git a/component/admin/src/Helper/IpValidateHelper.php b/component/admin/src/Helper/IpValidateHelper.php index f5d7666..f0917d0 100644 --- a/component/admin/src/Helper/IpValidateHelper.php +++ b/component/admin/src/Helper/IpValidateHelper.php @@ -11,7 +11,6 @@ defined('_JEXEC') or die; use Codeling\Library\Bfstop\Helper\IpHelper; -use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; class IpValidateHelper @@ -35,58 +34,65 @@ private static function e($text) return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8'); } - public static function validIPRange($address) + /** + * What is wrong with $address as an entry of the block or allow list (an + * address, or a network in CIDR notation), as a message to show (escaped: + * it contains what was typed in); null if nothing is. The form rules + * return it as their error, which Joomla shows instead of its own. + */ + public static function rangeError($address): ?string { + $address = (string) $address; $ip = $address; - $isSubNet = str_contains($address, "/"); - if ($isSubNet) + if (str_contains($address, '/')) { - $parts = explode("/", $ip, 2); - $subnet = $parts[1]; - $ip = $parts[0]; + list($ip, $subnet) = explode('/', $address, 2); $maxBits = IpRangeHelper::isIPv6($ip) ? 128 : 32; // digits only: is_numeric() would also accept "1e1", "0x8" or " 8", // which don't mean what they look like in the places the range ends // up (e.g. the web server's configuration) if (preg_match('/^[0-9]{1,3}\z/', $subnet) !== 1 || (int) $subnet > $maxBits) { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_BFSTOP_IP_INVALID_SUBNET', self::e($subnet)), 'warning'); - return false; + return Text::sprintf('COM_BFSTOP_IP_INVALID_SUBNET', self::e($subnet)); } $minBits = IpRangeHelper::isIPv6($ip) ? self::MinPrefixIPv6 : self::MinPrefixIPv4; if ((int) $subnet < $minBits) { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_BFSTOP_IP_NETWORK_TOO_LARGE', - self::e($address), self::MinPrefixIPv4, self::MinPrefixIPv6), 'warning'); - return false; + return Text::sprintf('COM_BFSTOP_IP_NETWORK_TOO_LARGE', self::e($address), + self::MinPrefixIPv4, self::MinPrefixIPv6); } } if (!filter_var($ip, FILTER_VALIDATE_IP)) { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_BFSTOP_IP_INVALID_ADDRESS', self::e($ip)), 'warning'); - return false; - } - if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) - { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_BFSTOP_IP_PRIVATE_OR_RESERVED', self::e($ip)), 'warning'); + return Text::sprintf('COM_BFSTOP_IP_INVALID_ADDRESS', self::e($ip)); } - return true; + return null; } /** - * Whether the current client's address is in $range (an address, or a - * network in CIDR notation), with a warning if it is: a block of it would - * shut out whoever is entering it. Matched by the library's IpHelper, - * like the block and allow list themselves. + * The note that $address (a valid entry, see rangeError()) is of a + * private or reserved range - which can be meant, so it is no error - or + * null if it isn't. */ - public static function matchesCurrentIP($range) + public static function privateRangeNote($address): ?string + { + $ip = explode('/', (string) $address, 2)[0]; + return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) + ? null + : Text::sprintf('COM_BFSTOP_IP_PRIVATE_OR_RESERVED', self::e($ip)); + } + + /** + * The error that $range (an address, or a network in CIDR notation) + * holds the address of the current client - a block of it would shut out + * whoever is entering it - or null if it doesn't. Matched by the + * library's IpHelper, like the block and allow list themselves. + */ + public static function currentIpError($range): ?string { $curIP = IpHelper::getAddress(LogHelper::getLogger()); - $result = IpHelper::contains($range, $curIP); - if ($result) - { - Factory::getApplication()->enqueueMessage(Text::sprintf('COM_BFSTOP_IP_BLOCKS_USER', self::e($range), self::e($curIP)), 'warning'); - } - return $result; + return IpHelper::contains($range, $curIP) + ? Text::sprintf('COM_BFSTOP_IP_BLOCKS_USER', self::e($range), self::e($curIP)) + : null; } } diff --git a/component/admin/src/Helper/LinkHelper.php b/component/admin/src/Helper/LinkHelper.php index 7f5a30a..e8d90e1 100644 --- a/component/admin/src/Helper/LinkHelper.php +++ b/component/admin/src/Helper/LinkHelper.php @@ -10,15 +10,11 @@ defined('_JEXEC') or die; -use Joomla\CMS\Factory; - class LinkHelper { public static function getIpInfoLink($ipaddress) { - $input = Factory::getApplication()->getInput(); - $menuId = $input->get('Itemid', 0, 'INTEGER'); - $link = 'index.php?option=com_bfstop&Itemid='.$menuId.'&view=ipinfo&ipaddress='.rawurlencode($ipaddress); - return $link; + // a page of the backend, which has no menu items + return 'index.php?option=com_bfstop&view=ipinfo&ipaddress='.rawurlencode((string) $ipaddress); } } diff --git a/component/admin/src/Helper/ParamHelper.php b/component/admin/src/Helper/ParamHelper.php index 058febd..fc7014f 100644 --- a/component/admin/src/Helper/ParamHelper.php +++ b/component/admin/src/Helper/ParamHelper.php @@ -15,15 +15,14 @@ class ParamHelper { /** - * A setting as it is stored now (see the library's Settings, and - * Settings::Defaults for the defaults). Costs no query: Joomla has the - * params of the components loaded. + * A setting as it is stored now, or its default (see the library's + * Settings::get()). Costs no query: Joomla has the params of the + * components loaded. * - * @param string $name the name of the setting - * @param mixed $defaultValue what is returned if the setting isn't stored + * @param string $name the name of the setting */ - public static function get($name, $defaultValue) + public static function get($name) { - return Settings::stored()->get($name, $defaultValue); + return Settings::get(Settings::stored(), $name); } } diff --git a/component/admin/src/Helper/UnblockHelper.php b/component/admin/src/Helper/UnblockHelper.php index a463331..ab785bc 100644 --- a/component/admin/src/Helper/UnblockHelper.php +++ b/component/admin/src/Helper/UnblockHelper.php @@ -18,7 +18,7 @@ class UnblockHelper { public static function getHtaccessPath() { - return HtaccessHelper::resolvePath(ParamHelper::get('htaccessPath', '')); + return HtaccessHelper::resolvePath(ParamHelper::get('htaccessPath')); } /** @@ -34,7 +34,7 @@ public static function removeLiftedHtaccessBlocks($logger) { $htaccess = new HtaccessHelper(self::getHtaccessPath(), $logger); $htaccess->removeStaleBlocks((new Repositories($logger))->blocks(), - ParamHelper::get('blockMode', 'full') === 'htaccess'); + ParamHelper::get('blockMode') === 'htaccess'); } public static function unblockHtaccess($ips, $logger) diff --git a/component/admin/src/Helper/VersionHelper.php b/component/admin/src/Helper/VersionHelper.php index 106f354..7ea2c87 100644 --- a/component/admin/src/Helper/VersionHelper.php +++ b/component/admin/src/Helper/VersionHelper.php @@ -15,10 +15,16 @@ class VersionHelper { + /** + * The version in the manifest cache $manifest_cache (JSON) of an + * extension, '' if it has none - also if the cache is empty or no JSON + * object (json_decode() gives null then, which property_exists() throws + * a TypeError for). + */ public static function getVersion($manifest_cache) { - $json = json_decode($manifest_cache); - return (property_exists($json, "version")) ? $json->version : ''; + $json = json_decode((string) $manifest_cache); + return (is_object($json) && isset($json->version) && is_scalar($json->version)) ? (string) $json->version : ''; } public static function checkSameMajorMinor($version1, $version2) @@ -33,15 +39,18 @@ public static function checkSameMajorMinor($version1, $version2) public static function getInstalledVersions() { $db = Factory::getContainer()->get(DatabaseInterface::class); - - $query = "SELECT manifest_cache FROM #__extensions WHERE name='plg_system_bfstop'"; - $db->setQuery($query); - $plugin = $db->loadResult(); - - $query = "SELECT manifest_cache FROM #__extensions WHERE name='com_bfstop'"; - $db->setQuery($query); - $component = $db->loadResult(); - + $manifest = function ($name) use ($db) + { + $query = $db->createQuery() + ->select($db->quoteName('manifest_cache')) + ->from($db->quoteName('#__extensions')) + ->where($db->quoteName('name').' = :name') + ->bind(':name', $name); + $db->setQuery($query); + return $db->loadResult(); + }; + $plugin = $manifest('plg_system_bfstop'); + $component = $manifest('com_bfstop'); return array( 'plugin' => $plugin === null ? null : self::getVersion($plugin), 'component' => $component === null ? null : self::getVersion($component), diff --git a/component/admin/src/Model/BlockModel.php b/component/admin/src/Model/BlockModel.php index 9f7a42f..1ff1459 100644 --- a/component/admin/src/Model/BlockModel.php +++ b/component/admin/src/Model/BlockModel.php @@ -66,7 +66,7 @@ public function save($data) */ private function blockThroughHtaccess($id, $former = null) { - if ($id < 1 || ParamHelper::get('blockMode', 'full') !== 'htaccess') + if ($id < 1 || ParamHelper::get('blockMode') !== 'htaccess') { return; } diff --git a/component/admin/src/Model/HtblocklistModel.php b/component/admin/src/Model/HtblocklistModel.php index e8ac42b..908f970 100644 --- a/component/admin/src/Model/HtblocklistModel.php +++ b/component/admin/src/Model/HtblocklistModel.php @@ -10,7 +10,6 @@ defined('_JEXEC') or die; -use Codeling\Component\Bfstop\Administrator\Helper\ParamHelper; use Codeling\Component\Bfstop\Administrator\Helper\UnblockHelper; use Codeling\Library\Bfstop\Helper\HtaccessHelper; use Joomla\CMS\Language\Text; @@ -45,11 +44,14 @@ private function getHtAccessLines() return $this->cachedHtAccessLines; } + /** + * The entries of the page starting at $start, $count of them - all from + * $start on if $count is 0, which is what the list's "All" sets. + */ private function getPaginatedHtAccessLines($start, $count) { - $direction = $this->getState('list.direction'); $items = $this->getHtAccessLines(); - if (strtolower($direction) === 'asc') + if (strtolower((string) $this->getState('list.direction')) === 'asc') { sort($items); } @@ -57,29 +59,12 @@ private function getPaginatedHtAccessLines($start, $count) { rsort($items); } - $current = 0; - $result = array(); - foreach ($items as $entry) - { - if ($current >= $start) - { - if (($current - $start) >= $count) - { - break; - } - $result[] = $entry; - } - $current++; - } - return $result; + return array_slice($items, max(0, (int) $start), (int) $count > 0 ? (int) $count : null); } public function getItems() { - $start = $this->getStart(); - $count = $this->getState('list.limit'); - $result = $this->getPaginatedHtAccessLines($start, $count); - return $result; + return $this->getPaginatedHtAccessLines($this->getStart(), $this->getState('list.limit')); } protected function populateState($ordering = null, $direction = null) diff --git a/component/admin/src/Model/LogModel.php b/component/admin/src/Model/LogModel.php index 011eb6b..d74169d 100644 --- a/component/admin/src/Model/LogModel.php +++ b/component/admin/src/Model/LogModel.php @@ -12,6 +12,7 @@ use Codeling\Library\Bfstop\Helper\LoggerHelper; use Joomla\CMS\Factory; +use Joomla\CMS\Log\Log; use Joomla\CMS\MVC\Model\ListModel; /** @@ -89,12 +90,12 @@ public function getItems() { // the order needs every entry $entries = array_filter(array_map(array($this, 'parseLine'), $lines)); - // the sort is stable: entries of the same priority stay in the order of the file - usort($entries, fn ($a, $b) => strcmp($a->priority, $b->priority)); - if ($descending) - { - $entries = array_reverse($entries); - } + // by severity, the most severe first in ascending order (as Joomla + // numbers the priorities: EMERGENCY 1 ... DEBUG 128), not by the + // name; the sort is stable: entries of the same priority stay in + // the order of the file - also descending + $direction = $descending ? -1 : 1; + usort($entries, fn ($a, $b) => $direction * (self::severity($a->priority) <=> self::severity($b->priority))); return array_slice($entries, $start, $count > 0 ? $count : null); } // by date, which is the order of the file @@ -106,6 +107,18 @@ public function getItems() return array_values(array_filter(array_map(array($this, 'parseLine'), $page))); } + /** + * The value of a priority as the log file names it (Log::ERROR for + * "ERROR"); a name which is none sorts after DEBUG. + */ + public static function severity($priority): int + { + $names = array('EMERGENCY' => Log::EMERGENCY, 'ALERT' => Log::ALERT, 'CRITICAL' => Log::CRITICAL, + 'ERROR' => Log::ERROR, 'WARNING' => Log::WARNING, 'NOTICE' => Log::NOTICE, 'INFO' => Log::INFO, + 'DEBUG' => Log::DEBUG); + return $names[strtoupper(trim((string) $priority))] ?? PHP_INT_MAX; + } + protected function populateState($ordering = null, $direction = null) { parent::populateState('date', 'DESC'); diff --git a/component/admin/src/Rule/DateRule.php b/component/admin/src/Rule/DateRule.php deleted file mode 100644 index c611330..0000000 --- a/component/admin/src/Rule/DateRule.php +++ /dev/null @@ -1,38 +0,0 @@ -format($format) === $value); - } -} diff --git a/component/admin/src/Rule/IprangeRule.php b/component/admin/src/Rule/IprangeRule.php index 39b457c..a7c054e 100644 --- a/component/admin/src/Rule/IprangeRule.php +++ b/component/admin/src/Rule/IprangeRule.php @@ -11,14 +11,29 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\IpValidateHelper; +use Joomla\CMS\Factory; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormRule; use Joomla\Registry\Registry; +/** + * An entry of the allow list: an address or a network. The error is returned, for Joomla to show + * instead of its own; a private or reserved range is no error, only noted. + */ class IprangeRule extends FormRule { public function test(\SimpleXMLElement $element, $value, $group = null, ?Registry $input = null, ?Form $form = null) { - return IpValidateHelper::validIPRange($value); + $error = IpValidateHelper::rangeError($value); + if ($error !== null) + { + return new \UnexpectedValueException($error); + } + $note = IpValidateHelper::privateRangeNote($value); + if ($note !== null) + { + Factory::getApplication()->enqueueMessage($note, 'warning'); + } + return true; } } diff --git a/component/admin/src/Rule/IprangeblockRule.php b/component/admin/src/Rule/IprangeblockRule.php index 8528ba2..222879e 100644 --- a/component/admin/src/Rule/IprangeblockRule.php +++ b/component/admin/src/Rule/IprangeblockRule.php @@ -11,14 +11,30 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\IpValidateHelper; +use Joomla\CMS\Factory; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormRule; use Joomla\Registry\Registry; +/** + * A block: an address or a network, which must not + * hold the address of whoever enters it. The error is returned, for Joomla to show + * instead of its own; a private or reserved range is no error, only noted. + */ class IprangeblockRule extends FormRule { public function test(\SimpleXMLElement $element, $value, $group = null, ?Registry $input = null, ?Form $form = null) { - return (IpValidateHelper::validIPRange($value) && !IpValidateHelper::matchesCurrentIP($value)); + $error = IpValidateHelper::rangeError($value) ?? IpValidateHelper::currentIpError($value); + if ($error !== null) + { + return new \UnexpectedValueException($error); + } + $note = IpValidateHelper::privateRangeNote($value); + if ($note !== null) + { + Factory::getApplication()->enqueueMessage($note, 'warning'); + } + return true; } } diff --git a/component/admin/src/Table/BlockTable.php b/component/admin/src/Table/BlockTable.php index f51401c..25860de 100644 --- a/component/admin/src/Table/BlockTable.php +++ b/component/admin/src/Table/BlockTable.php @@ -39,7 +39,21 @@ public function check() { $this->ipaddress = $canonical; } + // minutes, 0 for ever: the list names some, but a block may last any + // number of them (see BlockModel::addDurationOption()) - just not fewer + // than none + if (!is_numeric($this->duration) || (int) $this->duration < 0 || (string) (int) $this->duration !== trim((string) $this->duration)) + { + $this->setError(\Joomla\CMS\Language\Text::_('COM_BFSTOP_BLOCK_DURATION_INVALID')); + return false; + } + $this->duration = (int) $this->duration; $this->crdate = self::startTime((string) $this->crdate, $this->storedStartTime(), date('Y-m-d H:i:s')); + if (\DateTime::createFromFormat('!Y-m-d H:i:s', $this->crdate) === false) + { + $this->setError(\Joomla\CMS\Language\Text::_('COM_BFSTOP_BLOCK_START_INVALID')); + return false; + } return parent::check(); } diff --git a/component/admin/src/View/Blocklist/HtmlView.php b/component/admin/src/View/Blocklist/HtmlView.php index c83f3d4..a89b3c5 100644 --- a/component/admin/src/View/Blocklist/HtmlView.php +++ b/component/admin/src/View/Blocklist/HtmlView.php @@ -12,7 +12,6 @@ use Codeling\Component\Bfstop\Administrator\Helper\DurationHelper; use Codeling\Component\Bfstop\Administrator\Helper\ParamHelper; -use Codeling\Library\Bfstop\Settings; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; @@ -37,8 +36,8 @@ public function display($tpl = null) $this->sortDirection = (string) $state->get('list.direction'); // with .htaccess blocking, blocked requests never reach Joomla, // so attempts can't be counted - $this->attemptsTracked = ParamHelper::get('blockMode', 'full') !== 'htaccess'; - $this->autoPurgeWeeks = (int) ParamHelper::get('deleteOld', Settings::Defaults['deleteOld']); + $this->attemptsTracked = ParamHelper::get('blockMode') !== 'htaccess'; + $this->autoPurgeWeeks = (int) ParamHelper::get('deleteOld'); // selecting a range of rows with shift-click, see grid.checkall in the head $this->getDocument()->getWebAssetManager()->useScript('multiselect'); $this->addToolBar(); @@ -53,7 +52,7 @@ public function getBlockedState($item) } else { - if ($item->duration == 0) + if ($item->duration <= 0) { return Text::_('COM_BFSTOP_BLOCKED_PERMANENTLY'); } diff --git a/component/admin/src/View/Failedloginlist/HtmlView.php b/component/admin/src/View/Failedloginlist/HtmlView.php index 79f14d1..f4882d2 100644 --- a/component/admin/src/View/Failedloginlist/HtmlView.php +++ b/component/admin/src/View/Failedloginlist/HtmlView.php @@ -11,7 +11,6 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\ParamHelper; -use Codeling\Library\Bfstop\Settings; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; @@ -36,7 +35,7 @@ public function display($tpl = null) $this->sortColumn = (string) $state->get('list.ordering'); $this->sortDirection = (string) $state->get('list.direction'); $this->filterUsername = (string) $state->get('filter.username', ''); - $this->autoPurgeWeeks = (int) ParamHelper::get('deleteOld', Settings::Defaults['deleteOld']); + $this->autoPurgeWeeks = (int) ParamHelper::get('deleteOld'); $this->canPurge = (bool) Factory::getApplication()->getIdentity()->authorise('core.delete', 'com_bfstop'); if ($this->canPurge) { @@ -46,20 +45,6 @@ public function display($tpl = null) parent::display($tpl); } - public function getOriginName($origin) - { - // the client id of the application: site 0, administrator 1, api 3 - switch ((int) $origin) - { - case 0: - return 'Frontend'; - case 3: - return 'API'; - default: - return 'Backend'; - } - } - protected function addToolBar() { ToolbarHelper::title(Text::_('COM_BFSTOP_HEADING_FAILEDLOGINLIST'), 'bfstop'); diff --git a/component/admin/src/View/Htblock/HtmlView.php b/component/admin/src/View/Htblock/HtmlView.php index 8661fe3..de55bfc 100644 --- a/component/admin/src/View/Htblock/HtmlView.php +++ b/component/admin/src/View/Htblock/HtmlView.php @@ -10,6 +10,7 @@ defined('_JEXEC') or die; +use Codeling\Component\Bfstop\Administrator\Controller\HtblockController; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; @@ -27,8 +28,7 @@ public function display($tpl = null) $this->form = $this->getModel()->getForm(); $this->item = $this->getModel()->getItem(); - $user = Factory::getApplication()->getIdentity(); - $this->canSave = (bool) ($user && $user->authorise('core.create', 'com_bfstop')); + $this->canSave = HtblockController::mayAdd(Factory::getApplication()->getIdentity()); $this->addToolbar(); // the stylesheet is in the component's template folder, not in media/: a diff --git a/component/admin/src/View/Htblocklist/HtmlView.php b/component/admin/src/View/Htblocklist/HtmlView.php index 34b8384..b361ef9 100644 --- a/component/admin/src/View/Htblocklist/HtmlView.php +++ b/component/admin/src/View/Htblocklist/HtmlView.php @@ -10,7 +10,7 @@ defined('_JEXEC') or die; -use Codeling\Component\Bfstop\Administrator\Helper\DurationHelper; +use Codeling\Component\Bfstop\Administrator\Controller\HtblockController; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView; @@ -37,35 +37,6 @@ public function display($tpl = null) parent::display($tpl); } - public function getBlockedState($item) - { - if ($item->unblocked != null) - { - return Text::sprintf('COM_BFSTOP_UNBLOCKED_STATE', $item->unblocked); - } - else - { - if ($item->duration == 0) - { - return Text::_('COM_BFSTOP_BLOCKED_PERMANENTLY'); - } - else - { - $blockedUntil = strtotime($item->crdate); - $blockedUntil += $item->duration * 60; - $strDate = date('Y-m-d H:i:s', $blockedUntil); - return ($blockedUntil < time()) - ? Text::sprintf('COM_BFSTOP_BLOCK_EXPIRED_AT', $strDate) - : Text::sprintf('COM_BFSTOP_BLOCKED_UNTIL', $strDate); - } - } - } - - public function convertDurationToReadable($duration) - { - return DurationHelper::toReadable($duration); - } - protected function addToolBar() { $user = Factory::getApplication()->getIdentity(); @@ -79,7 +50,7 @@ protected function addToolBar() } // an entry is part of the web server's configuration, see // HtblockController::save() - if ($user->authorise('core.create', 'com_bfstop') && $user->authorise('core.admin', 'com_bfstop')) + if (HtblockController::mayAdd($user)) { ToolbarHelper::addNew('htblock.add'); } diff --git a/component/admin/src/View/Ipinfo/HtmlView.php b/component/admin/src/View/Ipinfo/HtmlView.php index 6d37d94..7fe3442 100644 --- a/component/admin/src/View/Ipinfo/HtmlView.php +++ b/component/admin/src/View/Ipinfo/HtmlView.php @@ -32,7 +32,7 @@ public function display($tpl = null) // this used to call the free freegeoip.net API, which was shut down // in 2018 (see issue #169); a local lookup also avoids sending every // blocked visitor's IP address to a third party. - $geoDbPath = ParamHelper::get('geoDbPath', ''); + $geoDbPath = ParamHelper::get('geoDbPath'); $details = GeoHelper::getCityDetails(LogHelper::getLogger(), $geoDbPath, $this->ipAddress); if ($details === null) diff --git a/component/admin/src/View/Log/HtmlView.php b/component/admin/src/View/Log/HtmlView.php index c229a79..8d595f0 100644 --- a/component/admin/src/View/Log/HtmlView.php +++ b/component/admin/src/View/Log/HtmlView.php @@ -11,7 +11,6 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\ParamHelper; -use Codeling\Library\Bfstop\Helper\LoggerHelper; use Joomla\CMS\Access\Exception\NotAllowed; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; @@ -42,8 +41,8 @@ public function display($tpl = null) $state = $this->getModel()->getState(); $this->sortColumn = (string) $state->get('list.ordering'); $this->sortDirection = (string) $state->get('list.direction'); - $this->keepDays = (int) ParamHelper::get('logKeepDays', LoggerHelper::DefaultKeepDays); - $this->maxSizeMB = max(1, (int) ParamHelper::get('logMaxSize', LoggerHelper::DefaultMaxSizeMB)); + $this->keepDays = (int) ParamHelper::get('logKeepDays'); + $this->maxSizeMB = max(1, (int) ParamHelper::get('logMaxSize')); $this->canDelete = (bool) Factory::getApplication()->getIdentity()->authorise('core.delete', 'com_bfstop'); if ($this->canDelete) { diff --git a/component/admin/tmpl/failedloginlist/default_body.php b/component/admin/tmpl/failedloginlist/default_body.php index eacc92c..40c33af 100644 --- a/component/admin/tmpl/failedloginlist/default_body.php +++ b/component/admin/tmpl/failedloginlist/default_body.php @@ -8,6 +8,7 @@ defined('_JEXEC') or die; use Codeling\Component\Bfstop\Administrator\Helper\LinkHelper; +use Codeling\Library\Bfstop\Origin; foreach ($this->items as $i => $item): ?> @@ -15,6 +16,6 @@ escape($item->ipaddress); ?> escape($item->logtime); ?> escape($item->username); ?> - getOriginName($item->origin); ?> + escape(Origin::name($item->origin)); ?> lift($repositories, $token, $issued['blockId'], $logger); } - /** - * Unblocks with $token, from wherever (see process() for what a request - * of the page has to show first). - */ - public function unblock($token, $logger) - { - $repositories = $this->repositories($logger); - $issued = $this->issuedFor($repositories, $token); - if ($issued === null) - { - $logger->log("com_bfstop-tokenunblock: Token not found.", Log::ERROR); - return false; - } - return $this->lift($repositories, $token, $issued['blockId'], $logger) === self::ResultUnblocked; - } - /** * The block $token was issued for, see UnblockTokenRepository::issuedFor(). * The expired tokens are deleted first: a request of this page is where diff --git a/component/site/src/View/Tokenunblock/HtmlView.php b/component/site/src/View/Tokenunblock/HtmlView.php index 2eb1630..026c0cc 100644 --- a/component/site/src/View/Tokenunblock/HtmlView.php +++ b/component/site/src/View/Tokenunblock/HtmlView.php @@ -77,7 +77,7 @@ public function display($tpl = null) // The status is only set if the plugin's "Use HTTP Error" setting is // on: a web server or CDN replacing error pages with its own would // otherwise hide the message from the user. - if ((bool) ParamHelper::get('useHttpError', true)) + if ((bool) ParamHelper::get('useHttpError')) { $status = TokenunblockModel::httpStatus($result); if ($status !== 200) diff --git a/composer.json b/composer.json index bc0cdd3..0ff6d95 100644 --- a/composer.json +++ b/composer.json @@ -4,13 +4,13 @@ "type": "project", "license": "GPL-3.0-or-later", "require": { - "php": ">=8.1", + "php": ">=8.2", "maxmind-db/reader": "^1.14.0" }, "config": { "sort-packages": true, "platform": { - "php": "8.1.0" + "php": "8.2.0" } }, "scripts": { diff --git a/composer.lock b/composer.lock index 9e14e3e..18545e1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "beba2166aa5e7c6d104e346faf146ef3", + "content-hash": "c4cbfb4f4dd535d8298724f95b8b13dc", "packages": [ { "name": "maxmind-db/reader", @@ -144,11 +144,11 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=8.1" + "php": ">=8.2" }, "platform-dev": {}, "platform-overrides": { - "php": "8.1.0" + "php": "8.2.0" }, "plugin-api-version": "2.6.0" } diff --git a/library/src/Helper/HtaccessHelper.php b/library/src/Helper/HtaccessHelper.php index 02b12e9..732fae1 100644 --- a/library/src/Helper/HtaccessHelper.php +++ b/library/src/Helper/HtaccessHelper.php @@ -11,7 +11,6 @@ defined('_JEXEC') or die; use Codeling\Library\Bfstop\Repository\BlockRepository; -use Joomla\CMS\Factory; use Joomla\CMS\Log\Log; use Joomla\CMS\Uri\Uri; @@ -53,6 +52,8 @@ class HtaccessHelper private const DenyLine = 'Require all denied'; private const EndIfLine = ''; private const ErrorDocumentPrefix = 'ErrorDocument 403 '; + // the start of an section (not of , , ...) + private const IfStart = '/^]/i'; /** * The query of the link of an unblock email (see TokenHelper::unblockLink()): @@ -116,20 +117,54 @@ public function checkRequirements() * which somebody wrote into it by hand. Read from both the current and * the earlier form (see LegacyLines). * + * Only the blocks the plugin writes count as its own: an whose + * condition is nothing but addresses (and, since the unblock page is let + * through, the condition of that page - see renderSection()), followed by + * "Require all denied" and "". Any other was written by hand + * and is kept as it is, with all of its lines up to its own . + * * @param string[] $lines the lines of the section (see load()) * @return array{addresses: string[], errorDocument: string|null, other: string[], legacy: bool} */ private static function parseSection(array $lines) { $section = array('addresses' => array(), 'errorDocument' => null, 'other' => array(), 'legacy' => false); - foreach ($lines as $line) + $lines = array_values($lines); + $count = count($lines); + for ($i = 0; $i < $count; ++$i) { + $line = $lines[$i]; $trimmed = trim($line); - if ($trimmed === '' || $trimmed === self::DenyLine || $trimmed === self::EndIfLine) + if ($trimmed === '') { continue; } - if (in_array($trimmed, self::LegacyLines, true)) + $addresses = self::blockConditionAddresses($trimmed); + if ($addresses !== null && + trim($lines[$i + 1] ?? '') === self::DenyLine && trim($lines[$i + 2] ?? '') === self::EndIfLine) + { + foreach ($addresses as $address) + { + $section['addresses'][] = $address; + } + $i += 2; + } + elseif (preg_match(self::IfStart, $trimmed)) + { + // written by hand: kept, up to the which closes it + $depth = 0; + for (; $i < $count; ++$i) + { + $inner = trim($lines[$i]); + $depth += (preg_match(self::IfStart, $inner) ? 1 : 0) - (strcasecmp($inner, self::EndIfLine) === 0 ? 1 : 0); + $section['other'][] = $lines[$i]; + if ($depth <= 0) + { + break; + } + } + } + elseif (in_array($trimmed, self::LegacyLines, true)) { $section['legacy'] = true; } @@ -138,14 +173,6 @@ private static function parseSection(array $lines) $section['legacy'] = true; $section['addresses'][] = substr($trimmed, strlen(self::BlockPrefix)); } - elseif (strpos($trimmed, ' line the plugin writes (see + * renderSection()) - "-R 'address'" terms joined by "||", in parentheses + * and followed by the exception of the unblock page if it has one - or + * null if $line is no such line. + * + * @return string[]|null + */ + private static function blockConditionAddresses($line) + { + $terms = "-R '[^']*'(?: \\|\\| -R '[^']*')*"; + $unblockPage = " && !\\(%\\{REQUEST_URI\\} == '[^']*' && %\\{QUERY_STRING\\} =~ /[^/]*/\\)"; + if (!preg_match('#^$#', $line)) + { + return null; + } + preg_match_all("/-R '([^']*)'/", $line, $matches); + return $matches[1]; + } + /** * The lines of the block section for $section (see parseSection()). Only * addresses and networks get into a condition: what is written there is @@ -544,59 +591,6 @@ function ($entry) use ($stillBlocked) }); } - /** - * Edit ErrorDocument 403 line in .htaccess. - * - * @param string $message - * @return boolean - */ - public function edit403Message($message) - { - if (empty($message)) - { - return $this->remove403Message(); - } - // a line break would start a new directive - if (preg_match('/[\x00-\x1f\x7f]/', $message)) - { - if (!is_null($this->logger)) - { - $this->logger->log("Refusing to write a 403 message containing control characters to .htaccess!", Log::ERROR); - } - return false; - } - - $line = self::ErrorDocumentPrefix.'"'.addcslashes($message, '"\\').'"'; - - return $this->locked(function () use ($line) - { - $file = $this->load(); - $section = self::parseSection($file['section']); - $section['errorDocument'] = $line; - return $this->store($file, self::renderSection($section)); - }); - } - - /** - * Remove ErrorDocument 403 line from .htaccess. - * - * @return boolean - */ - public function remove403Message() - { - return $this->locked(function () - { - $file = $this->load(); - $section = self::parseSection($file['section']); - if ($section['errorDocument'] === null && !$section['legacy']) - { - return true; - } - $section['errorDocument'] = null; - return $this->store($file, self::renderSection($section)); - }); - } - /** * Runs a read-modify-write cycle of the .htaccess file while holding an * exclusive lock, so that concurrent requests (several clients getting @@ -612,7 +606,8 @@ public function remove403Message() */ private function locked(callable $change) { - $lockFile = self::lockDirectory().'/bfstop-htaccess-'.md5($this->path).'.lock'; + // by the file, not the site: sites which share a file share its lock + $lockFile = LockHelper::directory().'/bfstop-htaccess-'.md5($this->path).'.lock'; $handle = LockHelper::acquire($lockFile, self::LockWaitSeconds); if (!$handle) { @@ -651,29 +646,6 @@ public static function resolvePath($configured): string // is not going to let go of it public const LockWaitSeconds = 10; - /** - * Where lock files go (also those of the plugin, see Bfstop): Joomla's own - * temporary directory if there is one we can use, not the system's: that - * one is shared with other users of the machine on many hosts, who could - * then hold the lock (or plant a link under its name). - */ - public static function lockDirectory() - { - try - { - $tmp = (string) Factory::getApplication()->get('tmp_path'); - if ($tmp !== '' && is_dir($tmp) && is_writable($tmp)) - { - return rtrim($tmp, '/\\'); - } - } - catch (\Throwable $e) - { - // no application (e.g. in a script): use the system's - } - return sys_get_temp_dir(); - } - /** * Replaces the file as a whole: the new content is written next to it and * renamed over it. Writing into the file itself would truncate it first, diff --git a/library/src/Helper/IpHelper.php b/library/src/Helper/IpHelper.php index f9f8eda..f3fff46 100644 --- a/library/src/Helper/IpHelper.php +++ b/library/src/Helper/IpHelper.php @@ -92,7 +92,11 @@ public static function isValidIpOrSubnet($value) (int) $parts[1] <= (strpos($parts[0], ':') !== false ? 128 : 32); } - private static function prefixMask($bits, $length = 16) + /** + * The network mask of a prefix length of $bits, as a binary string of + * $length bytes (16 for IPv6, 4 for IPv4). + */ + public static function prefixMask($bits, $length = 16) { $mask = str_repeat("\xff", intdiv($bits, 8)); if ($bits % 8 > 0) @@ -244,9 +248,9 @@ private static function proxySettings() } $settings = array('useProxy' => false, 'proxyIpAddress' => '', 'header' => 'HTTP_X_FORWARDED_FOR', 'trustedProxies' => array()); - $settings['useProxy'] = (bool) $params->get('useProxy', false); - $settings['proxyIpAddress'] = (string) $params->get('proxyIpAddress', ''); - $settings['header'] = (string) $params->get('proxyHeaderSource', 'HTTP_X_FORWARDED_FOR'); + $settings['useProxy'] = Settings::bool($params, 'useProxy'); + $settings['proxyIpAddress'] = Settings::string($params, 'proxyIpAddress'); + $settings['header'] = Settings::string($params, 'proxyHeaderSource'); if ($settings['useProxy']) { $settings['trustedProxies'] = self::parseTrustedProxies($settings['proxyIpAddress']); diff --git a/library/src/Helper/LockHelper.php b/library/src/Helper/LockHelper.php index b69f59d..c568074 100644 --- a/library/src/Helper/LockHelper.php +++ b/library/src/Helper/LockHelper.php @@ -34,6 +34,60 @@ public static function siteHash(): string return md5((string) $app->get('db').(string) $app->get('dbprefix')); } + /** + * Where lock files go: Joomla's own temporary directory if there is one + * we can use, not the system's: that one is shared with other users of + * the machine on many hosts, who could then hold the lock (or plant a + * link under its name). + */ + public static function directory(): string + { + try + { + $tmp = (string) \Joomla\CMS\Factory::getApplication()->get('tmp_path'); + if ($tmp !== '' && is_dir($tmp) && is_writable($tmp)) + { + return rtrim($tmp, '/\\'); + } + } + catch (\Throwable $e) + { + // no application (e.g. in a script): use the system's + } + return sys_get_temp_dir(); + } + + /** + * The file of a lock (or a stamp) of this site: what it is for + * ($purpose: "block", "login", ...), and which of them ($part: a slot, + * see slot(); null if there is only one). One place for the names, so + * that two kinds of lock never share a file by accident. + */ + public static function file(string $purpose, $part = null, string $extension = 'lock'): string + { + return self::directory().'/bfstop-'.$purpose.'-'.self::siteHash(). + ($part !== null ? '-'.$part : '').'.'.$extension; + } + + /** + * Which of $count slots (lock files) the key $key gets: always the same + * one, and - as it depends on the site's secret - none somebody could + * choose keys for to share the slot of somebody else's. + */ + public static function slot($key, int $count): int + { + $secret = ''; + try + { + $secret = (string) \Joomla\CMS\Factory::getApplication()->get('secret', ''); + } + catch (\Throwable $e) + { + // no application: no secret + } + return hexdec(substr(hash_hmac('sha256', (string) $key, $secret), 0, 7)) % max(1, $count); + } + /** * Takes the exclusive lock on $file, creating the file if need be. * diff --git a/library/src/Helper/LoggerHelper.php b/library/src/Helper/LoggerHelper.php index 39e15e4..d61d3d1 100644 --- a/library/src/Helper/LoggerHelper.php +++ b/library/src/Helper/LoggerHelper.php @@ -53,8 +53,8 @@ public function __construct($log_level, $maxBytes = self::MaxLogFileBytes) public static function fromSettings(\Joomla\Registry\Registry $params) { return new self( - (int) $params->get('logLevel', Settings::Defaults['logLevel']), - self::maxBytesFromMegabytes($params->get('logMaxSize', self::DefaultMaxSizeMB))); + Settings::int($params, 'logLevel'), + self::maxBytesFromMegabytes(Settings::get($params, 'logMaxSize'))); } /** diff --git a/library/src/Helper/NotifierHelper.php b/library/src/Helper/NotifierHelper.php index b65f9a4..17c9697 100644 --- a/library/src/Helper/NotifierHelper.php +++ b/library/src/Helper/NotifierHelper.php @@ -213,7 +213,9 @@ public function sendMail($subject, $body, $emailAddresses) public function failedLogin($logEntry, $maxNumber) { - if (!$this->isNotificationAllowed($logEntry->logtime, $maxNumber)) + // nobody to notify (the default): neither count nor mail + if (count($this->notifyAddresses) === 0 || + !$this->isNotificationAllowed($logEntry->logtime, $maxNumber)) { return; } @@ -226,7 +228,8 @@ public function failedLogin($logEntry, $maxNumber) public function blockedNotifyAdmin($logEntry, $interval, $maxNumber) { - if (!$this->isNotificationAllowed($logEntry->logtime, $maxNumber, true)) + if (count($this->notifyAddresses) === 0 || + !$this->isNotificationAllowed($logEntry->logtime, $maxNumber, true)) { return; } diff --git a/library/src/Helper/RiskHelper.php b/library/src/Helper/RiskHelper.php index b37662a..01725b4 100644 --- a/library/src/Helper/RiskHelper.php +++ b/library/src/Helper/RiskHelper.php @@ -24,27 +24,17 @@ */ class RiskHelper { - private static function getBoolParam(Registry $params, $paramName, $default) - { - return (bool) $params->get($paramName, $default); - } - - private static function getIntParam(Registry $params, $paramName, $default) - { - return (int) $params->get($paramName, $default); - } - private static function knownIpScore(Repositories $repositories, LoggerHelper $logger, Registry $params, $ipaddress, $username) { - if (!self::getBoolParam($params, 'riskKnownIpEnabled', true)) + if (!Settings::bool($params, 'riskKnownIpEnabled')) { return 0; } try { - if ($repositories->knownIps()->hasLoggedInFrom($ipaddress, $username, self::getIntParam($params, 'ipv6PrefixLength', Settings::Defaults['ipv6PrefixLength']))) + if ($repositories->knownIps()->hasLoggedInFrom($ipaddress, $username, Settings::int($params, 'ipv6PrefixLength'))) { - return -self::getIntParam($params, 'riskKnownIpPoints', 5); + return -Settings::int($params, 'riskKnownIpPoints'); } } catch (\Throwable $e) @@ -60,7 +50,7 @@ private static function knownIpScore(Repositories $repositories, LoggerHelper $l */ public static function isCommonUsername(Registry $params, $username) { - $list = (string) $params->get('riskCommonUsernames', Settings::Defaults['riskCommonUsernames']); + $list = Settings::string($params, 'riskCommonUsernames'); $candidates = array_filter(array_map('trim', explode("\n", str_replace("\r", '', $list)))); foreach ($candidates as $candidate) { @@ -74,25 +64,25 @@ public static function isCommonUsername(Registry $params, $username) private static function commonUsernameScore(Registry $params, $username) { - if (!self::getBoolParam($params, 'riskCommonUsernameEnabled', true)) + if (!Settings::bool($params, 'riskCommonUsernameEnabled')) { return 0; } return self::isCommonUsername($params, $username) - ? self::getIntParam($params, 'riskCommonUsernamePoints', 2) + ? Settings::int($params, 'riskCommonUsernamePoints') : 0; } private static function userAgentScore(Registry $params) { - if (!self::getBoolParam($params, 'riskUserAgentEnabled', true)) + if (!Settings::bool($params, 'riskUserAgentEnabled')) { return 0; } $userAgent = array_key_exists('HTTP_USER_AGENT', $_SERVER) ? trim($_SERVER['HTTP_USER_AGENT']) : ''; if ($userAgent === '') { - return self::getIntParam($params, 'riskUserAgentPoints', 2); + return Settings::int($params, 'riskUserAgentPoints'); } return 0; } @@ -105,23 +95,23 @@ private static function userAgentScore(Registry $params) */ private static function geoScore(LoggerHelper $logger, Registry $params, $ipaddress) { - if (!self::getBoolParam($params, 'riskGeoEnabled', false)) + if (!Settings::bool($params, 'riskGeoEnabled')) { return 0; } - $dbPath = (string) $params->get('geoDbPath', ''); + $dbPath = Settings::string($params, 'geoDbPath'); $countryCode = GeoHelper::getCountryCode($logger, $dbPath, $ipaddress); if ($countryCode === null) { return 0; } - $homeCountries = (string) $params->get('riskGeoHomeCountries', ''); + $homeCountries = Settings::string($params, 'riskGeoHomeCountries'); $homeList = array_filter(array_map('trim', explode(',', strtoupper($homeCountries)))); if (empty($homeList) || in_array(strtoupper($countryCode), $homeList, true)) { return 0; } - return self::getIntParam($params, 'riskGeoPoints', 3); + return Settings::int($params, 'riskGeoPoints'); } /** @@ -135,7 +125,7 @@ private static function geoScore(LoggerHelper $logger, Registry $params, $ipaddr */ private static function reverseDnsScore(Repositories $repositories, LoggerHelper $logger, Registry $params, $ipaddress, $cacheKey) { - if (!self::getBoolParam($params, 'riskReverseDnsEnabled', false)) + if (!Settings::bool($params, 'riskReverseDnsEnabled')) { return 0; } @@ -155,7 +145,7 @@ private static function reverseDnsScore(Repositories $repositories, LoggerHelper } if ($hostname === null) { - return self::getIntParam($params, 'riskReverseDnsPoints', 2); + return Settings::int($params, 'riskReverseDnsPoints'); } } catch (\Throwable $e) diff --git a/library/src/Repository/BlockRepository.php b/library/src/Repository/BlockRepository.php index 2404eb4..52b9a8a 100644 --- a/library/src/Repository/BlockRepository.php +++ b/library/src/Repository/BlockRepository.php @@ -16,7 +16,8 @@ /** * The blocks (#__bfstop_bannedip) and their lifting (#__bfstop_unblock). - * A block is active while its duration (in minutes, 0 for ever) hasn't run + * A block is active while its duration (in minutes, 0 - or less, see + * BlockPolicy::realDuration() - for ever) hasn't run * out and it hasn't been lifted. */ class BlockRepository extends AddressTableRepository @@ -50,7 +51,7 @@ class BlockRepository extends AddressTableRepository // SQL for "the block t is active at :now"; names of columns and tables only private function activeCondition($block, $lifted) { - return '('.$block.'.duration = 0 OR '. + return '('.$block.'.duration <= 0 OR '. $this->addMinutesSql($block.'.crdate', $block.'.duration').' >= :now)'. ' AND NOT EXISTS (SELECT 1 FROM #__bfstop_unblock '.$lifted.' WHERE '.$block.'.id = '.$lifted.'.block_id)'; } @@ -230,7 +231,7 @@ public function purgeEndedBefore($date) $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->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); diff --git a/library/src/Repository/FailedLoginRepository.php b/library/src/Repository/FailedLoginRepository.php index 05c406e..6e3ccb7 100644 --- a/library/src/Repository/FailedLoginRepository.php +++ b/library/src/Repository/FailedLoginRepository.php @@ -156,12 +156,15 @@ public function unhandledUsernamesFromAddress($minutes, $ipaddress, $time) /** * Marks the unhandled failed logins from $ipaddress - and, with - * $username, only those against it - as handled. Fail-open: they go on - * counting. + * $usernames (a username, or several: an account's username and email + * address), only those against them, whatever their case, as Joomla + * matches a login - as handled. Fail-open: they go on counting. + * + * @param string|string[]|null $usernames */ - public function markHandled($ipaddress, $username = null) + public function markHandled($ipaddress, $usernames = null) { - $this->failOpen('markHandled', function () use ($ipaddress, $username) + $this->failOpen('markHandled', function () use ($ipaddress, $usernames) { $query = $this->db->createQuery() ->update($this->db->quoteName(self::Table)) @@ -169,10 +172,26 @@ public function markHandled($ipaddress, $username = null) ->where($this->db->quoteName('ipaddress').' = :ip') ->where($this->db->quoteName('handled').' = 0'); $values = array('ip' => (string) $ipaddress); - if ($username !== null) + if ($usernames !== null) { - $query->where($this->db->quoteName('username').' = :username'); - $values['username'] = (string) $username; + $names = array_values(array_unique(array_filter(array_map('strval', (array) $usernames), + fn ($name) => $name !== ''))); + if (count($names) === 0) + { + return; + } + // MySQL and MariaDB compare the column case-insensitively + // themselves (its collation); PostgreSQL exactly. The rows are + // found by the address, so LOWER() reads no more of them + $lower = $this->db->getServerType() === 'postgresql'; + $column = $this->db->quoteName('username'); + $placeholders = array(); + foreach ($names as $i => $name) + { + $values['username'.$i] = $name; + $placeholders[] = $lower ? 'LOWER(:username'.$i.')' : ':username'.$i; + } + $query->where(($lower ? 'LOWER('.$column.')' : $column).' IN ('.implode(', ', $placeholders).')'); } $this->execute($query, $values); }, null); diff --git a/library/src/Repository/KnownIpRepository.php b/library/src/Repository/KnownIpRepository.php index f8303df..86e6cef 100644 --- a/library/src/Repository/KnownIpRepository.php +++ b/library/src/Repository/KnownIpRepository.php @@ -57,8 +57,19 @@ public function remember($key, $username) } else { - $this->insert(self::Table, array('ipaddress' => $key, 'username' => $username, - 'first_success' => $now, 'last_success' => $now)); + // two logins at the same time may both have found none: the + // second one updates the row of the first (the unique key is + // the address and the username as it is spelt) + $sql = 'INSERT INTO '.$this->db->quoteName(self::Table). + ' (ipaddress, username, first_success, last_success) VALUES (:ip, :username, :first, :last)'; + $sql .= $this->db->getServerType() === 'postgresql' + ? ' ON CONFLICT (ipaddress, username) DO UPDATE SET last_success = :last2' + : ' ON DUPLICATE KEY UPDATE last_success = :last2'; + $insert = $this->db->createQuery(); + $insert->setQuery($sql); + $insertValues = array('ip' => (string) $key, 'username' => (string) $username, 'first' => $now, + 'last' => $now, 'last2' => $now); + $this->execute($insert, $insertValues); } }, null); } diff --git a/library/src/Repository/Repository.php b/library/src/Repository/Repository.php index 225017f..aab6374 100644 --- a/library/src/Repository/Repository.php +++ b/library/src/Repository/Repository.php @@ -134,9 +134,9 @@ protected function column(QueryInterface $query, array $values = array(), $offse return $this->db->loadColumn(); } - protected function row(QueryInterface $query, array $values = array()) + protected function row(QueryInterface $query, array $values = array(), $offset = 0, $limit = 0) { - $this->prepare($query, $values); + $this->prepare($query, $values, $offset, $limit); return $this->db->loadAssoc(); } diff --git a/library/src/Repository/UnblockTokenRepository.php b/library/src/Repository/UnblockTokenRepository.php index b1ce895..536acef 100644 --- a/library/src/Repository/UnblockTokenRepository.php +++ b/library/src/Repository/UnblockTokenRepository.php @@ -109,24 +109,6 @@ public function hasCurrentFor($username) }, true); } - /** - * Whether the token (any, expired or not) is stored. - * - * Fail-closed: no. - */ - public function exists($token) - { - return $this->failClosed('exists', function () use ($token) - { - $query = $this->db->createQuery() - ->select($this->db->quoteName('token')) - ->from($this->db->quoteName(self::Table)) - ->where($this->db->quoteName('token').' = :token'); - $values = array('token' => self::hash($token)); - return $this->scalar($query, $values) != null; - }, false); - } - /** * The block an unexpired token was issued for: its id, and the address * (or network) it blocks, which is the only one the token may unblock diff --git a/library/src/Repository/UserRepository.php b/library/src/Repository/UserRepository.php index 8153bd2..aef09a4 100644 --- a/library/src/Repository/UserRepository.php +++ b/library/src/Repository/UserRepository.php @@ -34,24 +34,46 @@ public function emailById($id) } /** - * The email address of the account with the username $username, null if - * there is none. Fail-open: null (no mail is sent). + * The enabled account whose username or email address is $login - what a + * failed login was typed with, see accountExists(), so matched the same + * way: whatever the case, and also by the email address. Null if there is + * no such account, or it is disabled (it can't log in, so an unblock link + * is of no use to it). If $login is the username of one account and the + * email address of another, the one whose username it is wins. + * + * Fail-open: null (so no mail is sent). + * + * @return array{username: string, email: string}|null */ - public function emailByUsername($username) + public function accountByLogin($login) { - return $this->failOpen('emailByUsername', function () use ($username) + $login = (string) $login; + if ($login === '') + { + return null; + } + return $this->failOpen('accountByLogin', function () use ($login) { + $values = array('u0' => $login, 'e0' => $login, 'o0' => $login); $query = $this->db->createQuery() - ->select($this->db->quoteName('email')) + ->select($this->db->quoteName(array('username', 'email'))) ->from($this->db->quoteName('#__users')) - ->where($this->db->quoteName('username').' = :username'); - $values = array('username' => (string) $username); - return $this->scalar($query, $values, 0, 1); + ->where('('.$this->loginCondition(array('u0'), array('e0')).')') + ->where($this->db->quoteName('block').' = 0') + ->order('CASE WHEN '.$this->loginCondition(array('o0'), array()).' THEN 0 ELSE 1 END') + ->order($this->db->quoteName('id')); + $row = $this->row($query, $values, 0, 1); + if (!is_array($row) || (string) $row['email'] === '') + { + return null; + } + return array('username' => (string) $row['username'], 'email' => (string) $row['email']); }, null); } /** - * The email addresses of the members of the user group $groupId. + * The email addresses of the enabled members of the user group $groupId + * (not those of its sub-groups): a disabled account gets no mails. * Fail-open: none. * * @return string[] @@ -63,9 +85,10 @@ public function emailsOfGroup($groupId) $query = $this->db->createQuery() ->select($this->db->quoteName('u.email')) ->from($this->db->quoteName('#__users', 'u')) - ->join('LEFT', $this->db->quoteName('#__user_usergroup_map', 'g'). + ->innerJoin($this->db->quoteName('#__user_usergroup_map', 'g'). ' ON '.$this->db->quoteName('u.id').' = '.$this->db->quoteName('g.user_id')) - ->where($this->db->quoteName('g.group_id').' = :group'); + ->where($this->db->quoteName('g.group_id').' = :group') + ->where($this->db->quoteName('u.block').' = 0'); $values = array('group' => (int) $groupId); return $this->column($query, $values); }, array()); @@ -116,18 +139,11 @@ public function anyAccountExists(array $logins) /** * Whether one of $logins (at most LookupChunk) is the username or email - * address of an account, by the indexes of both columns. - * - * Joomla looks an account up case-insensitively on login. MySQL and - * MariaDB compare the columns that way themselves (their collation, - * utf8mb4_unicode_ci, is the one Joomla creates them with), and, unlike - * LOWER(), by index: with LOWER() every failed login read the whole table - * of accounts. PostgreSQL compares exactly, so there both sides are lowered - * (Joomla has no index on the lowered columns there). + * address of an account, by the indexes of both columns (see + * loginCondition()). */ private function accountAmong(array $logins): bool { - $lower = $this->db->getServerType() === 'postgresql'; $values = array(); $usernames = array(); $emails = array(); @@ -135,18 +151,43 @@ private function accountAmong(array $logins): bool { $values['u'.$i] = $login; $values['e'.$i] = $login; - $usernames[] = $lower ? 'LOWER(:u'.$i.')' : ':u'.$i; - $emails[] = $lower ? 'LOWER(:e'.$i.')' : ':e'.$i; + $usernames[] = 'u'.$i; + $emails[] = 'e'.$i; } - $username = $this->db->quoteName('username'); - $email = $this->db->quoteName('email'); - $condition = $lower - ? 'LOWER('.$username.') IN ('.implode(', ', $usernames).') OR LOWER('.$email.') IN ('.implode(', ', $emails).')' - : $username.' IN ('.implode(', ', $usernames).') OR '.$email.' IN ('.implode(', ', $emails).')'; $query = $this->db->createQuery() ->select('1') ->from($this->db->quoteName('#__users')) - ->where('('.$condition.')'); + ->where('('.$this->loginCondition($usernames, $emails).')'); return $this->scalar($query, $values, 0, 1) !== null; } + + /** + * SQL for "the username is one of the parameters $usernames, or the email + * address one of $emails" (names of parameters, without the colon), as + * Joomla looks an account up on login: case-insensitively. MySQL and + * MariaDB compare the columns that way themselves (their collation, + * utf8mb4_unicode_ci, is the one Joomla creates them with), and, unlike + * LOWER(), by index: with LOWER() every failed login read the whole table + * of accounts. PostgreSQL compares exactly, so there both sides are lowered + * (Joomla has no index on the lowered columns there). + */ + private function loginCondition(array $usernames, array $emails): string + { + $lower = $this->db->getServerType() === 'postgresql'; + $parts = array(); + foreach (array('username' => $usernames, 'email' => $emails) as $column => $parameters) + { + if (count($parameters) === 0) + { + continue; + } + $placeholders = array_map(function ($name) use ($lower) + { + return $lower ? 'LOWER(:'.$name.')' : ':'.$name; + }, $parameters); + $quoted = $this->db->quoteName($column); + $parts[] = ($lower ? 'LOWER('.$quoted.')' : $quoted).' IN ('.implode(', ', $placeholders).')'; + } + return implode(' OR ', $parts); + } } diff --git a/library/src/Service/BlockPolicy.php b/library/src/Service/BlockPolicy.php index b178b84..739a4fa 100644 --- a/library/src/Service/BlockPolicy.php +++ b/library/src/Service/BlockPolicy.php @@ -13,7 +13,6 @@ use Codeling\Library\Bfstop\Helper\HtaccessHelper; use Codeling\Library\Bfstop\Helper\IpHelper; use Codeling\Library\Bfstop\Helper\LoggerHelper; -use Codeling\Library\Bfstop\Helper\NotifierHelper; use Codeling\Library\Bfstop\Repository\BlockRepository; use Codeling\Library\Bfstop\Repository\Repositories; use Codeling\Library\Bfstop\Settings; @@ -49,20 +48,20 @@ public function __construct(Registry $params, Repositories $repositories, LoginS $this->logger = $logger; } - private function intParam($name, $default): int + private function intParam($name): int { - return (int) $this->params->get($name, $default); + return Settings::int($this->params, $name); } - private function boolParam($name, $default): bool + private function boolParam($name): bool { - return (bool) $this->params->get($name, $default); + return Settings::bool($this->params, $name); } /** "blockMode": full, loginonly, htaccess or off */ public function mode(): string { - return (string) $this->params->get('blockMode', 'full'); + return Settings::string($this->params, 'blockMode'); } public function isOff(): bool @@ -81,18 +80,18 @@ public static function realDuration($duration) /** The minutes within which the failed logins of an address count. */ public function checkInterval() { - return self::realDuration($this->intParam('checkInterval', Settings::Defaults['checkInterval'])); + return self::realDuration($this->intParam('checkInterval')); } /** The duration of a first block, in minutes (0: permanent). */ public function blockDuration(): int { - return $this->intParam('blockDuration', NotifierHelper::OneDay); + return $this->intParam('blockDuration'); } public function htaccessPath(): string { - return HtaccessHelper::resolvePath((string) $this->params->get('htaccessPath', '')); + return HtaccessHelper::resolvePath(Settings::string($this->params, 'htaccessPath')); } /** @@ -105,9 +104,9 @@ public function htaccessPath(): string */ public function effectiveBlockNumber($riskScore): int { - $blockNumber = $this->intParam('blockNumber', Settings::Defaults['blockNumber']); - $reductionPerPoint = $this->intParam('riskBlockNumberReductionPerPoint', 1); - $minBlockNumber = $this->intParam('riskMinBlockNumber', 2); + $blockNumber = $this->intParam('blockNumber'); + $reductionPerPoint = $this->intParam('riskBlockNumberReductionPerPoint'); + $minBlockNumber = $this->intParam('riskMinBlockNumber'); $effective = (int) round($blockNumber - $riskScore * $reductionPerPoint); return max($minBlockNumber, $effective); } @@ -170,7 +169,7 @@ public function decide($logEntry, $clientAddress = null): ?array 'htaccessPath' => $this->htaccessPath(), // has to be found out before blocking, which marks these failed // logins as handled - 'targetedOtherAccounts' => $this->boolParam('notifyBlockedUser', false) && + 'targetedOtherAccounts' => $this->boolParam('notifyBlockedUser') && $this->logins->hasFailedLoginsForOtherAccounts($this->checkInterval(), $logEntry->ipaddress, $logEntry->username, $logEntry->logtime), ); @@ -183,8 +182,8 @@ public function decide($logEntry, $clientAddress = null): ?array */ public function escalatedDuration($address, $duration) { - $maxBlocksBefore = $this->intParam('maxBlocksBefore', Settings::Defaults['maxBlocksBefore']); - $progressiveEnabled = $this->boolParam('progressiveBlockDuration', false); + $maxBlocksBefore = $this->intParam('maxBlocksBefore'); + $progressiveEnabled = $this->boolParam('progressiveBlockDuration'); if ($maxBlocksBefore <= 0 && !$progressiveEnabled) { return $duration; @@ -245,7 +244,7 @@ public function htaccessAllowed($address): bool /** Whether blocked users may be sent an unblock link at all. */ public function notifiesBlockedUser(): bool { - return $this->boolParam('notifyBlockedUser', false); + return $this->boolParam('notifyBlockedUser'); } /** @@ -269,15 +268,20 @@ public function notifiesBlockedUser(): bool * @param object $logEntry the failed login which led to the block * @param string|null $clientAddress see decide() * @param bool $targetedOtherAccounts see decide() + * @param string|null $username the username of the account the + * failed login was against, if not + * what it was typed with (an email + * address, another case) * @return string|null why no email is sent, null if it may be */ - public function whyNoUnblockMail($logEntry, $clientAddress, $targetedOtherAccounts): ?string + public function whyNoUnblockMail($logEntry, $clientAddress, $targetedOtherAccounts, $username = null): ?string { + $username = $username ?? $logEntry->username; if ($targetedOtherAccounts) { return 'the failed logins from this address also targeted other accounts'; } - $mode = self::effectiveNotifyBlockedUser($this->intParam('notifyBlockedUser', 0), self::hasLiveSite()); + $mode = self::effectiveNotifyBlockedUser($this->intParam('notifyBlockedUser'), self::hasLiveSite()); if ($mode === 0) { $this->logger->log('Unblock links need the site\'s address ($live_site in configuration.php): '. @@ -286,12 +290,12 @@ public function whyNoUnblockMail($logEntry, $clientAddress, $targetedOtherAccoun } if ($mode === self::NotifyBlockedAnyAddress) { - return $this->repositories->unblockTokens()->hasCurrentFor($logEntry->username) + return $this->repositories->unblockTokens()->hasCurrentFor($username) ? 'there already is an unblock link for this user which can be used' : null; } return $this->repositories->knownIps()->hasLoggedInFrom($clientAddress ?? $logEntry->ipaddress, - $logEntry->username, $this->intParam('ipv6PrefixLength', Settings::Defaults['ipv6PrefixLength'])) + $username, $this->intParam('ipv6PrefixLength')) ? null : 'the user has never logged in from this IP address'; } @@ -354,19 +358,19 @@ public function delaySeconds($logEntry, $riskScore) */ private function accountThrottleDelay($logEntry): int { - if (!$this->boolParam('accountThrottleEnabled', true)) + if (!$this->boolParam('accountThrottleEnabled')) { return 0; } - $checkInterval = $this->intParam('accountCheckInterval', 60); - $accountBlockNumber = $this->intParam('accountBlockNumber', 20); + $checkInterval = $this->intParam('accountCheckInterval'); + $accountBlockNumber = $this->intParam('accountBlockNumber'); $numberOfFailedLogins = $this->repositories->failedLogins()->countUnhandledForUsername( $checkInterval, $logEntry->username, $logEntry->logtime); if ($numberOfFailedLogins < $accountBlockNumber) { return 0; } - $throttleDelay = max(0, $this->intParam('accountThrottleDelay', 5)); + $throttleDelay = max(0, $this->intParam('accountThrottleDelay')); if ($throttleDelay > 0) { $this->logger->log('Account-level throttle triggered for username \''. @@ -385,21 +389,20 @@ private function accountThrottleDelay($logEntry): int */ private function determineDelayDuration($riskScore) { - $riskDelaySecondsPerPoint = $this->intParam('riskDelaySecondsPerPoint', - Settings::Defaults['riskDelaySecondsPerPoint']); + $riskDelaySecondsPerPoint = $this->intParam('riskDelaySecondsPerPoint'); return $this->determineBaseDelayDuration() + max(0, $riskScore) * $riskDelaySecondsPerPoint; } private function determineBaseDelayDuration() { - $delayDuration = $this->intParam('delayDuration', 0); - if (!$this->boolParam('adaptiveDelay', false)) + $delayDuration = $this->intParam('delayDuration'); + if (!$this->boolParam('adaptiveDelay')) { return $delayDuration; } - $maxDelay = $this->intParam('adaptiveDelayMax', Settings::Defaults['adaptiveDelayMax']); - $lowThreshold = $this->intParam('adaptiveDelayThresholdMin', Settings::Defaults['adaptiveDelayThresholdMin']); - $highThreshold = $this->intParam('adaptiveDelayThresholdMax', Settings::Defaults['adaptiveDelayThresholdMax']); + $maxDelay = $this->intParam('adaptiveDelayMax'); + $lowThreshold = $this->intParam('adaptiveDelayThresholdMin'); + $highThreshold = $this->intParam('adaptiveDelayThresholdMax'); if ($lowThreshold > $highThreshold) { $tmp = $lowThreshold; diff --git a/library/src/Service/BlockService.php b/library/src/Service/BlockService.php index 297a092..d604f28 100644 --- a/library/src/Service/BlockService.php +++ b/library/src/Service/BlockService.php @@ -39,8 +39,7 @@ public function __construct(Repositories $repositories) */ public function withLock($key, callable $decision) { - $stripe = hexdec(substr(md5((string) $key), 0, 4)) % self::LockStripes; - $lockFile = HtaccessHelper::lockDirectory().'/bfstop-block-'.LockHelper::siteHash().'-'.$stripe.'.lock'; + $lockFile = LockHelper::file('block', LockHelper::slot($key, self::LockStripes)); // not for ever: see LockHelper $handle = LockHelper::acquire($lockFile, HtaccessHelper::LockWaitSeconds); if (!$handle) diff --git a/library/src/Service/DailyMaintenance.php b/library/src/Service/DailyMaintenance.php index 38b646b..69d62b8 100644 --- a/library/src/Service/DailyMaintenance.php +++ b/library/src/Service/DailyMaintenance.php @@ -43,7 +43,7 @@ public function __construct(Repositories $repositories, Registry $settings) private static function lockFile(): string { - return HtaccessHelper::lockDirectory().'/bfstop-maintenance-'.LockHelper::siteHash().'.lock'; + return LockHelper::file('maintenance'); } /** @@ -107,14 +107,14 @@ private function run(): void // added by hand $this->tidyHtaccess(); $maintenance = new Maintenance($this->repositories); - $purgeAge = (int) $this->settings->get('deleteOld', Settings::Defaults['deleteOld']); + $purgeAge = Settings::int($this->settings, 'deleteOld'); if ($purgeAge > 0) { $maintenance->purgeOldEntries($purgeAge); } // regardless of the purge age setting: these are not deleted by age $maintenance->keepWithinBounds(); - LoggerHelper::pruneByAge((int) $this->settings->get('logKeepDays', LoggerHelper::DefaultKeepDays)); + LoggerHelper::pruneByAge(Settings::int($this->settings, 'logKeepDays')); $this->schedule->recordRun(); } @@ -136,7 +136,7 @@ private function tidyHtaccess(): void { $logger = $this->repositories->logger(); $htaccess = new HtaccessHelper( - HtaccessHelper::resolvePath((string) $this->settings->get('htaccessPath', '')), $logger); + HtaccessHelper::resolvePath(Settings::string($this->settings, 'htaccessPath')), $logger); if (!is_file($htaccess->getFileName())) { return; @@ -148,7 +148,7 @@ private function tidyHtaccess(): void 'access controls of the directory, and without the current form, the links of unblock emails can\'t be '. 'followed', Log::ERROR); } - $throughFile = (string) $this->settings->get('blockMode', 'full') === 'htaccess'; + $throughFile = Settings::string($this->settings, 'blockMode') === 'htaccess'; if ($htaccess->removeStaleBlocks($this->repositories->blocks(), $throughFile) === false) { $logger->log('Could not take the addresses the plugin blocked out of '.$htaccess->getFileName(). diff --git a/library/src/Service/LoginService.php b/library/src/Service/LoginService.php index d081bed..5bfda40 100644 --- a/library/src/Service/LoginService.php +++ b/library/src/Service/LoginService.php @@ -40,7 +40,9 @@ public function recordFailedLogin($logEntry) * were counted against the user stop counting, and the address is one * the user has logged in from. * - * @param object $info ipaddress (the client's address) and username + * @param object $info ipaddress (the client's address), username + * and, if known, email (failed logins + * typed with it are the user's too) * @param string|null $trackedAddress the key this client is tracked by (see * IpHelper::trackedAddress(): for IPv6 its * network), if not its address. Failed @@ -54,7 +56,8 @@ public function recordFailedLogin($logEntry) public function recordSuccessfulLogin($info, $trackedAddress = null, $trustedAddress = null) { $key = $trackedAddress ?? $info->ipaddress; - $this->repositories->failedLogins()->markHandled($key, $info->username); + $this->repositories->failedLogins()->markHandled($key, + array_filter(array((string) $info->username, (string) ($info->email ?? '')))); $this->repositories->knownIps()->remember($trustedAddress ?? $key, $info->username); } diff --git a/library/src/Service/MaintenanceSchedule.php b/library/src/Service/MaintenanceSchedule.php index 15f5fe4..ea13e92 100644 --- a/library/src/Service/MaintenanceSchedule.php +++ b/library/src/Service/MaintenanceSchedule.php @@ -10,7 +10,6 @@ defined('_JEXEC') or die; -use Codeling\Library\Bfstop\Helper\HtaccessHelper; use Codeling\Library\Bfstop\Helper\LockHelper; use Codeling\Library\Bfstop\Repository\StateRepository; @@ -44,7 +43,7 @@ public function __construct(StateRepository $state) public static function stampFile(): string { - return HtaccessHelper::lockDirectory().'/bfstop-maintenance-'.LockHelper::siteHash().'.stamp'; + return LockHelper::file('maintenance', null, 'stamp'); } /** diff --git a/library/src/Settings.php b/library/src/Settings.php index 7a22f78..ed00a6d 100644 --- a/library/src/Settings.php +++ b/library/src/Settings.php @@ -49,38 +49,125 @@ public static function held(): Registry return ComponentHelper::getParams(self::Extension); } + /** + * A setting of $params (the settings, see stored() and held()): what is + * stored, or its default (Defaults) if nothing - or an empty string - is. + * Every setting is read this way, so that its default is in one place. + * + * @throws \InvalidArgumentException for a name which is no setting + */ + public static function get(Registry $params, string $name) + { + if (!array_key_exists($name, self::Defaults)) + { + throw new \InvalidArgumentException("There is no setting '$name'"); + } + return $params->get($name, self::Defaults[$name]); + } + + /** A setting as a number, see get(). */ + public static function int(Registry $params, string $name): int + { + return (int) self::get($params, $name); + } + + /** A setting which is switched on or off, see get(). */ + public static function bool(Registry $params, string $name): bool + { + return (bool) self::get($params, $name); + } + + /** A setting as a string, see get(). */ + public static function string(Registry $params, string $name): string + { + return (string) self::get($params, $name); + } + /** * What the settings are while they have not been saved: the same as the - * settings page shows for them. The plugin is enabled by the - * installation, so it runs with these until an administrator opens the - * settings. + * settings page shows for them (forms/settings.xml, which a test compares + * with this, both ways). The plugin is enabled by the installation, so it + * runs with these until an administrator opens the settings. */ public const Defaults = array( + // basic + 'blockMode' => 'full', 'blockNumber' => 10, - 'checkInterval' => 10080, + 'blockDuration' => 1440, + // notifications + 'emailaddress' => '', + // no user or group chosen + 'userID' => '', + 'groupNotificationEnabled' => 0, + 'userGroup' => '', + 'notifyBlockedUser' => 0, + 'notifyBlockedNumber' => 5, + 'notifyFailedNumber' => 0, + 'notifyFailedOnlyExisting' => 0, + // proxy + 'useProxy' => 0, + 'proxyHeaderSource' => 'HTTP_X_FORWARDED_FOR', + 'proxyIpAddress' => '', + // advanced + // frontend, backend and the Web Services API + 'enabledForOrigin' => Origin::Frontend | Origin::Backend | Origin::Api, + 'progressiveBlockDuration' => 0, 'maxBlocksBefore' => 3, + 'checkInterval' => 10080, + 'notifyRemainingAttempts' => 0, 'notifyUsePasswordReminder' => 1, - 'adaptiveDelayMax' => 0, - 'adaptiveDelayThresholdMin' => 50, - 'adaptiveDelayThresholdMax' => 200, + // empty: the message of the language file + 'blockedMessage' => '', + 'blockedMsgShowIP' => 0, + 'logLevel' => 8, // Log::ERROR + 'logMaxSize' => 5, + 'logKeepDays' => 28, + 'unknownUsernameMode' => 'hash', + // what an IPv6 client is tracked by, see IpHelper::trackedAddress(): + // a connection usually gets a /56 (or more), not just a /64, so a /64 + // would let a client start over 256 times + 'ipv6PrefixLength' => 56, + 'useHttpError' => 1, // failed logins are purged after this many weeks unless the // administrator chose another time (0 = never). Keeping them for ever // is not needed to protect anything, and they are personal data // (addresses, usernames) 'deleteOld' => 4, - 'logLevel' => 8, // Log::ERROR + // empty: the root of the site + 'htaccessPath' => '', + // delay + 'delayDuration' => 0, + 'adaptiveDelay' => 0, + 'adaptiveDelayMax' => 0, + 'adaptiveDelayThresholdMin' => 50, + 'adaptiveDelayThresholdMax' => 200, + // at most this many responses are delayed at the same time + 'delayMaxConcurrent' => 5, + // account throttle + 'accountThrottleEnabled' => 1, + 'accountBlockNumber' => 20, + 'accountCheckInterval' => 60, + 'accountThrottleDelay' => 5, + // GeoIP + 'geoDbPath' => '', + // risk score + 'riskGeoEnabled' => 0, + 'riskGeoHomeCountries' => '', + 'riskGeoPoints' => 3, + 'riskReverseDnsEnabled' => 0, + 'riskReverseDnsPoints' => 2, + 'riskKnownIpEnabled' => 1, + 'riskKnownIpPoints' => 5, + 'riskCommonUsernameEnabled' => 1, 'riskCommonUsernames' => "admin\nadministrator\nroot\ntest\nwebmaster", - // frontend, backend and the Web Services API - 'enabledForOrigin' => Origin::Frontend | Origin::Backend | Origin::Api, + 'riskCommonUsernamePoints' => 2, + 'riskUserAgentEnabled' => 1, + 'riskUserAgentPoints' => 2, // a delay ties up a PHP worker for its whole length, see the // plugin's Responder::delay(): the risk score adds none unless the // administrator asks for it 'riskDelaySecondsPerPoint' => 0, - // what an IPv6 client is tracked by, see IpHelper::trackedAddress(): - // a connection usually gets a /56 (or more), not just a /64, so a /64 - // would let a client start over 256 times - 'ipv6PrefixLength' => 56, - // at most this many responses are delayed at the same time - 'delayMaxConcurrent' => 5, + 'riskBlockNumberReductionPerPoint' => 1, + 'riskMinBlockNumber' => 2, ); } diff --git a/package/README.md b/package/README.md index 0f1b334..a62bb28 100644 --- a/package/README.md +++ b/package/README.md @@ -11,7 +11,7 @@ repository (with its history) for 2.0.0. - `pkg_bfstop.xml`: the package manifest. - `script.php`: the package's installer script; refuses Joomla! < 5.4 and - PHP < 8.1 before anything is installed (sites on Joomla! 4 stay with 1.5). + PHP < 8.2 before anything is installed (sites on Joomla! 4 stay with 1.5). - `update-server.php`: writes the files of the update server (`update.xml` and `update-pkg.xml` at `https://bfstop.de`, which installed sites ask) from the GitHub releases, see "The update server". diff --git a/package/script.php b/package/script.php index 2abaabe..585645b 100644 --- a/package/script.php +++ b/package/script.php @@ -23,7 +23,7 @@ class pkg_bfstopInstallerScript extends InstallerScript implements InstallerScriptInterface { protected $minimumJoomla = '5.4.0'; - protected $minimumPhp = '8.1.0'; + protected $minimumPhp = '8.2.0'; // InstallerScript's checks, with the return type InstallerScriptInterface // has (InstallerScript's own preflight() has none) diff --git a/package/update-server.php b/package/update-server.php index 3fb8948..6a5ce24 100644 --- a/package/update-server.php +++ b/package/update-server.php @@ -50,8 +50,8 @@ function updateServerLines() // requirements of 2.x) 1 => array('targetplatform' => '(4|5\.[0-3])\..*', 'php_minimum' => null), // 2.x: package/script.php refuses anything older than Joomla! 5.4 - // and PHP 8.1 - 2 => array('targetplatform' => '(5\.[4-9]|6)\..*', 'php_minimum' => '8.1'), + // and PHP 8.2 + 2 => array('targetplatform' => '(5\.[4-9]|6)\..*', 'php_minimum' => '8.2'), ); } diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index bb285d2..a437dae 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -90,30 +90,6 @@ parameters: count: 1 path: component/admin/src/Model/SettingsModel.php - - - message: '#^Method Codeling\\Component\\Bfstop\\Administrator\\Rule\\EmaillistRule\:\:test\(\) should return bool but returns UnexpectedValueException\.$#' - identifier: return.type - count: 1 - path: component/admin/src/Rule/EmaillistRule.php - - - - message: '#^Method Codeling\\Component\\Bfstop\\Administrator\\Rule\\GeodbpathRule\:\:test\(\) should return bool but returns UnexpectedValueException\.$#' - identifier: return.type - count: 1 - path: component/admin/src/Rule/GeodbpathRule.php - - - - message: '#^Method Codeling\\Component\\Bfstop\\Administrator\\Rule\\HtaccesspathRule\:\:test\(\) should return bool but returns UnexpectedValueException\.$#' - identifier: return.type - count: 1 - path: component/admin/src/Rule/HtaccesspathRule.php - - - - message: '#^Method Codeling\\Component\\Bfstop\\Administrator\\Rule\\ProxylistRule\:\:test\(\) should return bool but returns UnexpectedValueException\.$#' - identifier: return.type - count: 1 - path: component/admin/src/Rule/ProxylistRule.php - - message: '#^Call to an undefined method Joomla\\CMS\\MVC\\Model\\BaseDatabaseModel\:\:getForm\(\)\.$#' identifier: method.notFound diff --git a/phpstan.neon b/phpstan.neon index f7b6443..22d26b3 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -11,7 +11,7 @@ includes: parameters: level: 5 # the oldest PHP the extensions support (composer.json) - phpVersion: 80100 + phpVersion: 80200 paths: - library/src - plugin/src @@ -27,3 +27,11 @@ parameters: scanDirectories: - %env.JOOMLA_ROOT%/libraries treatPhpDocTypesAsCertain: false + ignoreErrors: + # a form rule returns true, false - or the error to show, as an + # exception: Joomla's Form::validateField() takes that ("if ($valid + # instanceof \Exception)"), though FormRule::test() says it returns bool + - + identifier: return.type + message: '#^Method Codeling\\Component\\Bfstop\\Administrator\\Rule\\\w+Rule::test\(\) should return bool but returns UnexpectedValueException\.$#' + path: component/admin/src/Rule/* diff --git a/plugin/deploy.sh b/plugin/deploy.sh index 70a09b2..9523f95 100755 --- a/plugin/deploy.sh +++ b/plugin/deploy.sh @@ -22,7 +22,6 @@ langfiles="language" # the documentation of the repository, put at the top of the zip docs="CHANGELOG LICENSE.txt README.md" plgtype="system" -langs="de-DE en-GB" version="$(sed -n 's:.*\(.*\).*:\1:p' "$extname.xml" | head -n 1)" if [ "$1" == "zip" ] @@ -46,7 +45,10 @@ fi cp -r $srcfiles $dstdir/plugins/$plgtype/$extname/ -for lang in $langs +# every language the plugin has (the folders of language/) +for dir in language/*/ do - cp language/$lang/* $dstdir/administrator/language/$lang/ + lang="$(basename "$dir")" + mkdir -p "$dstdir/administrator/language/$lang" + cp "$dir"*.ini "$dstdir/administrator/language/$lang/" done diff --git a/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini b/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini index a5ffc16..53fd4ea 100644 --- a/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini +++ b/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini @@ -17,6 +17,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="La vostra adreça IP és: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Aquesta actualització a la versió 2.0.0 comporta canvis importants de configuració. La configuració ha passat del Gestor de connectors al component BFStop: aneu a la vista de Configuració del component i reviseu els vostres paràmetres, en particular la secció «Proxy / Balancejador de càrrega» si el vostre lloc es troba darrere d'un proxy invers o d'un balancejador de càrrega." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop ara també protegeix els inicis de sessió a través de l'API de serveis web de Joomla! (api/index.php, amb testimonis d'API o autenticació HTTP Basic), i aquesta actualització ho ha activat: els inicis de sessió fallits hi compten per al bloqueig i les adreces bloquejades també són rebutjades per l'API. Si alguna de les teves integracions fa servir l'API des d'una adreça els inicis de sessió de la qual poden fallar, revisa l'opció 'Activa per a' a la vista de configuració del component." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop no ha pogut reescriure la seva secció de bloquejos a %s. La secció escrita per versions anteriors permet a qualsevol que no estigui bloquejat saltar-se els altres controls d'accés d'aquest directori (protecció amb contrasenya, restriccions d'IP). Feu que el fitxer es pugui escriure i torneu a executar l'actualització, o elimineu a mà les línies entre '# BEGIN BFStop Blocks' i '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop no ha pogut migrar la seva configuració i les seves dades durant l'actualització (%s). Fins que no es resolgui, el connector funciona amb la configuració per defecte: reviseu la configuració i torneu a executar l'actualització." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(adreça del lloc no configurada)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Ara mateix no és possible iniciar la sessió. Torneu-ho a provar d'aquí a uns minuts." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop no ha pogut treure la seva secció de bloquejos de %s: el servidor web continua rebutjant les adreces que conté. Feu que el fitxer es pugui escriure i traieu a mà les línies entre '# BEGIN BFStop Blocks' i '# END BFStop Blocks'." diff --git a/plugin/language/de-DE/de-DE.plg_system_bfstop.ini b/plugin/language/de-DE/de-DE.plg_system_bfstop.ini index 559e584..1b396b8 100644 --- a/plugin/language/de-DE/de-DE.plg_system_bfstop.ini +++ b/plugin/language/de-DE/de-DE.plg_system_bfstop.ini @@ -15,6 +15,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Deine IP-Adresse ist: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Dieses Update auf Version 2.0.0 bringt umfangreiche Änderungen an der Konfiguration mit. Die Konfiguration wurde aus der Plugin-Verwaltung in die BFStop-Komponente verlegt - bitte öffne die Ansicht „Einstellungen“ der Komponente und überprüfe deine Einstellungen - insbesondere den Abschnitt „Proxy / Load-Balancer“, falls deine Website hinter einem Reverse-Proxy oder Load-Balancer läuft." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop schützt jetzt auch Logins über die Web-Services-API von Joomla! (api/index.php, mit API-Token oder HTTP-Basic-Authentifizierung), und dieses Update hat das eingeschaltet: fehlgeschlagene Logins dort zählen für die Sperre, und gesperrte Adressen werden auch von der API abgewiesen. Falls eine Ihrer Anbindungen die API von einer Adresse aus nutzt, deren Logins fehlschlagen können, prüfen Sie die Einstellung 'Aktiv für' in der Einstellungsansicht der Komponente." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop konnte seinen Sperrabschnitt in %s nicht neu schreiben. Der von früheren Versionen geschriebene Abschnitt lässt alle, die nicht gesperrt sind, an den anderen Zugriffsbeschränkungen dieses Verzeichnisses vorbei (Passwortschutz, IP-Beschränkungen). Machen Sie die Datei beschreibbar und führen Sie das Update erneut aus, oder entfernen Sie die Zeilen zwischen '# BEGIN BFStop Blocks' und '# END BFStop Blocks' von Hand." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop konnte seine Einstellungen und Daten beim Update nicht übernehmen (%s). Bis das behoben ist, arbeitet das Plugin mit seinen Standardeinstellungen: Prüfen Sie die Einstellungen und führen Sie das Update erneut aus." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(Adresse der Website nicht eingestellt)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Anmelden ist gerade nicht möglich. Bitte versuchen Sie es in ein paar Minuten erneut." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop konnte seinen Sperr-Abschnitt nicht aus %s entfernen: der Webserver weist die Adressen darin weiter ab. Machen Sie die Datei beschreibbar und entfernen Sie die Zeilen zwischen '# BEGIN BFStop Blocks' und '# END BFStop Blocks' von Hand." diff --git a/plugin/language/en-GB/en-GB.plg_system_bfstop.ini b/plugin/language/en-GB/en-GB.plg_system_bfstop.ini index 4c6ac65..d14c9b6 100644 --- a/plugin/language/en-GB/en-GB.plg_system_bfstop.ini +++ b/plugin/language/en-GB/en-GB.plg_system_bfstop.ini @@ -15,6 +15,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Your IP address is: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="This update to version 2.0.0 comes with major configuration changes. Configuration has moved out of the Plugin Manager into the BFStop component - please go to the component's Settings view and review your settings - in particular the 'Proxy / Load Balancer' section if your site sits behind a reverse proxy or load balancer." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop now also protects logins through Joomla's Web Services API (api/index.php, with API tokens or HTTP Basic authentication), and this update has switched that on: failed logins there count towards blocking, and blocked addresses are rejected by the API too. If an integration of yours uses the API from an address whose logins may fail, check the 'Active for' setting in the component's Settings view." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop could not rewrite its block section in %s. The section written by earlier versions lets everybody who isn't blocked past the other access controls of that directory (password protection, IP restrictions). Make the file writable and run the update again, or remove the lines between '# BEGIN BFStop Blocks' and '# END BFStop Blocks' by hand." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop could not migrate its settings and data during the update (%s). The plugin works with its default settings until this is fixed: check the settings, and run the update again." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(site address not configured)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Logging in is not possible right now. Please try again in a few minutes." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop could not remove its block section from %s: the web server goes on refusing the addresses in it. Make the file writable and remove the lines between '# BEGIN BFStop Blocks' and '# END BFStop Blocks' by hand." diff --git a/plugin/language/es-ES/es-ES.plg_system_bfstop.ini b/plugin/language/es-ES/es-ES.plg_system_bfstop.ini index b275b44..f405979 100644 --- a/plugin/language/es-ES/es-ES.plg_system_bfstop.ini +++ b/plugin/language/es-ES/es-ES.plg_system_bfstop.ini @@ -17,6 +17,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Su dirección IP es: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Esta actualización a la versión 2.0.0 incluye cambios importantes en la configuración. La configuración se ha trasladado del Gestor de plugins al componente BFStop: vaya a la vista Ajustes del componente y revise sus ajustes, en particular la sección «Proxy / Balanceador de carga» si su sitio está detrás de un proxy inverso o de un balanceador de carga." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop ahora también protege los inicios de sesión a través de la API de servicios web de Joomla! (api/index.php, con tokens de API o autenticación HTTP Basic), y esta actualización lo ha activado: los inicios de sesión fallidos allí cuentan para el bloqueo y las direcciones bloqueadas también son rechazadas por la API. Si alguna de tus integraciones usa la API desde una dirección cuyos inicios de sesión pueden fallar, revisa el ajuste 'Activo para' en la vista de configuración del componente." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop no pudo reescribir su sección de bloqueos en %s. La sección escrita por versiones anteriores permite a cualquiera que no esté bloqueado saltarse los demás controles de acceso de ese directorio (protección por contraseña, restricciones de IP). Haz que el archivo se pueda escribir y vuelve a ejecutar la actualización, o elimina a mano las líneas entre '# BEGIN BFStop Blocks' y '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop no pudo migrar su configuración y sus datos durante la actualización (%s). Hasta que se resuelva, el plugin funciona con su configuración predeterminada: revisa la configuración y vuelve a ejecutar la actualización." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(dirección del sitio no configurada)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="No es posible iniciar sesión en este momento. Inténtalo de nuevo dentro de unos minutos." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop no pudo quitar su sección de bloqueos de %s: el servidor web sigue rechazando las direcciones que contiene. Haga el archivo escribible y quite a mano las líneas entre '# BEGIN BFStop Blocks' y '# END BFStop Blocks'." diff --git a/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini b/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini index 6fd4529..4115fa6 100644 --- a/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini +++ b/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini @@ -19,6 +19,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Votre address IP est: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Cette mise à jour vers la version 2.0.0 apporte des changements importants de configuration. La configuration a quitté le Gestionnaire de plugins pour le composant BFStop : veuillez ouvrir la vue Configuration du composant et vérifier vos paramètres, en particulier la section « Proxy / Répartiteur de charge » si votre site se trouve derrière un proxy inverse ou un répartiteur de charge." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop protège désormais aussi les connexions via l'API des services web de Joomla! (api/index.php, avec des jetons d'API ou l'authentification HTTP Basic), et cette mise à jour l'a activé : les échecs de connexion y comptent pour le blocage, et les adresses bloquées sont aussi refusées par l'API. Si l'une de vos intégrations utilise l'API depuis une adresse dont les connexions peuvent échouer, vérifiez le paramètre 'Activé pour' dans la vue Paramètres du composant." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop n'a pas pu réécrire sa section de blocage dans %s. La section écrite par les versions précédentes laisse passer toute personne non bloquée au-delà des autres contrôles d'accès de ce répertoire (protection par mot de passe, restrictions IP). Rendez le fichier accessible en écriture et relancez la mise à jour, ou supprimez à la main les lignes entre '# BEGIN BFStop Blocks' et '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop n'a pas pu migrer ses paramètres et ses données lors de la mise à jour (%s). Tant que ce n'est pas corrigé, le plugin fonctionne avec ses paramètres par défaut : vérifiez les paramètres et relancez la mise à jour." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(adresse du site non configurée)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="La connexion n'est pas possible pour le moment. Veuillez réessayer dans quelques minutes." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop n'a pas pu retirer sa section de blocage de %s : le serveur web continue de refuser les adresses qu'elle contient. Rendez le fichier accessible en écriture et retirez à la main les lignes entre '# BEGIN BFStop Blocks' et '# END BFStop Blocks'." diff --git a/plugin/language/it-IT/it-IT.plg_system_bfstop.ini b/plugin/language/it-IT/it-IT.plg_system_bfstop.ini index 83c7a05..1bb4af0 100644 --- a/plugin/language/it-IT/it-IT.plg_system_bfstop.ini +++ b/plugin/language/it-IT/it-IT.plg_system_bfstop.ini @@ -15,6 +15,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Il tuo indirizzo IP è: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Questo aggiornamento alla versione 2.0.0 comporta importanti modifiche alla configurazione. La configurazione è stata spostata dal Gestore dei plugin al componente BFStop: apri la vista Configurazione del componente e controlla le tue impostazioni, in particolare la sezione «Proxy / Bilanciatore di carico» se il tuo sito si trova dietro un reverse proxy o un bilanciatore di carico." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop ora protegge anche gli accessi tramite la API dei servizi web di Joomla! (api/index.php, con token API o autenticazione HTTP Basic), e questo aggiornamento lo ha attivato: gli accessi falliti lì contano per il blocco e gli indirizzi bloccati vengono respinti anche dalla API. Se una tua integrazione usa la API da un indirizzo i cui accessi possono fallire, controlla l'impostazione 'Attivo per' nella vista Impostazioni del componente." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop non è riuscito a riscrivere la sua sezione di blocco in %s. La sezione scritta dalle versioni precedenti permette a chiunque non sia bloccato di superare gli altri controlli di accesso di quella directory (protezione con password, restrizioni IP). Rendi il file scrivibile ed esegui di nuovo l'aggiornamento, oppure rimuovi a mano le righe tra '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop non è riuscito a migrare le sue impostazioni e i suoi dati durante l'aggiornamento (%s). Finché non viene risolto, il plugin funziona con le impostazioni predefinite: controlla le impostazioni ed esegui di nuovo l'aggiornamento." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(indirizzo del sito non configurato)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Al momento non è possibile accedere. Riprova tra qualche minuto." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop non è riuscito a togliere la sua sezione dei blocchi da %s: il server web continua a rifiutare gli indirizzi che contiene. Rendi il file scrivibile e togli a mano le righe tra '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." diff --git a/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini b/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini index 9b75903..3121d90 100644 --- a/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini +++ b/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini @@ -15,6 +15,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Uw IP-adres is: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Deze update naar versie 2.0.0 brengt ingrijpende wijzigingen in de configuratie met zich mee. De configuratie is verhuisd van de Pluginbeheerder naar de BFStop-component - ga naar de weergave Instellingen van de component en controleer je instellingen, met name het onderdeel 'Proxy / Load balancer' als je site achter een reverse proxy of load balancer staat." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop beschermt nu ook aanmeldingen via de webservices-API van Joomla! (api/index.php, met API-tokens of HTTP Basic-authenticatie), en deze update heeft dat ingeschakeld: mislukte aanmeldingen daar tellen mee voor blokkering en geblokkeerde adressen worden ook door de API geweigerd. Als een van uw koppelingen de API gebruikt vanaf een adres waarvan aanmeldingen kunnen mislukken, controleer dan de instelling 'Activeer detectie voor' in de instellingenweergave van de component." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop kon zijn blokkeersectie in %s niet herschrijven. De sectie die eerdere versies schreven laat iedereen die niet geblokkeerd is langs de andere toegangscontroles van die map (wachtwoordbeveiliging, IP-beperkingen). Maak het bestand schrijfbaar en voer de update opnieuw uit, of verwijder de regels tussen '# BEGIN BFStop Blocks' en '# END BFStop Blocks' met de hand." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop kon zijn instellingen en gegevens bij de update niet overzetten (%s). Tot dit is opgelost werkt de plugin met zijn standaardinstellingen: controleer de instellingen en voer de update opnieuw uit." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(adres van de site niet ingesteld)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Inloggen is op dit moment niet mogelijk. Probeer het over een paar minuten opnieuw." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop kon zijn blokkadesectie niet uit %s verwijderen: de webserver blijft de adressen erin weigeren. Maak het bestand schrijfbaar en verwijder de regels tussen '# BEGIN BFStop Blocks' en '# END BFStop Blocks' met de hand." diff --git a/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini b/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini index f013e1f..c33370b 100644 --- a/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini +++ b/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini @@ -19,6 +19,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Seu endereço IP é: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Esta atualização para a versão 2.0.0 traz grandes mudanças na configuração. A configuração saiu do Gerenciador de plugins e foi para o componente BFStop - acesse a visualização Configurações do componente e revise suas configurações, em especial a seção 'Proxy / Balanceador de carga' se o seu site estiver atrás de um proxy reverso ou de um balanceador de carga." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="O Brute Force Stop agora também protege os logins pela API de serviços web do Joomla! (api/index.php, com tokens de API ou autenticação HTTP Basic), e esta atualização ativou isso: logins com falha ali contam para o bloqueio, e endereços bloqueados também são recusados pela API. Se alguma integração sua usa a API a partir de um endereço cujos logins podem falhar, verifique a configuração 'Ativo para' na tela de configurações do componente." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="O Brute Force Stop não conseguiu reescrever sua seção de bloqueios em %s. A seção escrita por versões anteriores deixa qualquer pessoa que não esteja bloqueada passar pelos outros controles de acesso desse diretório (proteção por senha, restrições de IP). Torne o arquivo gravável e execute a atualização novamente, ou remova manualmente as linhas entre '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="O Brute Force Stop não conseguiu migrar suas configurações e dados durante a atualização (%s). Até que isso seja corrigido, o plugin funciona com as configurações padrão: verifique as configurações e execute a atualização novamente." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(endereço do site não configurado)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Não é possível fazer login agora. Tente novamente em alguns minutos." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="O Brute Force Stop não conseguiu remover sua seção de bloqueios de %s: o servidor web continua recusando os endereços nela. Torne o arquivo gravável e remova manualmente as linhas entre '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." diff --git a/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini b/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini index 4308a64..999cb84 100644 --- a/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini +++ b/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini @@ -19,6 +19,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="O seu endereço IP é: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Esta atualização para a versão 2.0.0 traz grandes alterações à configuração. A configuração saiu do Gestor de plugins e foi para o componente BFStop - aceda à vista Definições do componente e reveja as suas definições, em especial a secção 'Proxy / Balanceador de carga' se o seu site estiver atrás de um proxy inverso ou de um balanceador de carga." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="O Brute Force Stop agora também protege os inícios de sessão através da API de serviços web do Joomla! (api/index.php, com tokens de API ou autenticação HTTP Basic), e esta atualização ativou-o: os inícios de sessão falhados aí contam para o bloqueio e os endereços bloqueados também são recusados pela API. Se alguma integração sua usa a API a partir de um endereço cujos inícios de sessão podem falhar, verifique a definição 'Ativo para' na vista de definições do componente." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="O Brute Force Stop não conseguiu reescrever a sua secção de bloqueios em %s. A secção escrita por versões anteriores deixa qualquer pessoa que não esteja bloqueada passar pelos outros controlos de acesso desse diretório (proteção por palavra-passe, restrições de IP). Torne o ficheiro gravável e execute a atualização novamente, ou remova manualmente as linhas entre '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="O Brute Force Stop não conseguiu migrar as suas definições e dados durante a atualização (%s). Até que isso seja corrigido, o plugin funciona com as definições predefinidas: verifique as definições e execute a atualização novamente." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(endereço do site não configurado)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Não é possível iniciar sessão neste momento. Tente novamente dentro de alguns minutos." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="O Brute Force Stop não conseguiu remover a sua secção de bloqueios de %s: o servidor web continua a recusar os endereços nela. Torne o ficheiro gravável e remova manualmente as linhas entre '# BEGIN BFStop Blocks' e '# END BFStop Blocks'." diff --git a/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini b/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini index 6e8d76d..0f73032 100644 --- a/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini +++ b/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini @@ -15,6 +15,7 @@ PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP="Ваш IP-адрес: %s." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT="Это обновление до версии 2.0.0 содержит серьёзные изменения в настройках. Настройки перенесены из менеджера плагинов в компонент BFStop - откройте раздел «Настройки» компонента и проверьте свои параметры, особенно секцию «Прокси / Балансировщик нагрузки», если ваш сайт работает за обратным прокси или балансировщиком нагрузки." PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT="Brute Force Stop теперь защищает и входы через API веб-сервисов Joomla! (api/index.php, с API-токенами или HTTP Basic-аутентификацией), и это обновление включило эту защиту: неудачные входы там учитываются для блокировки, а заблокированные адреса отклоняются и API. Если какая-либо ваша интеграция использует API с адреса, входы с которого могут быть неудачными, проверьте настройку 'Активно для' в настройках компонента." PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN="Brute Force Stop не смог переписать свой раздел блокировок в %s. Раздел, записанный предыдущими версиями, позволяет всем, кто не заблокирован, обходить другие ограничения доступа этого каталога (защиту паролем, ограничения по IP). Сделайте файл доступным для записи и запустите обновление снова или удалите вручную строки между '# BEGIN BFStop Blocks' и '# END BFStop Blocks'." +PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED="Brute Force Stop не смог перенести свои настройки и данные при обновлении (%s). Пока это не исправлено, плагин работает с настройками по умолчанию: проверьте настройки и запустите обновление снова." PLG_SYSTEM_BFSTOP_SITE_ADDRESS_NOT_SET="(адрес сайта не настроен)" PLG_SYSTEM_BFSTOP_LOGIN_UNAVAILABLE="Вход сейчас невозможен. Пожалуйста, попробуйте снова через несколько минут." PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED="Brute Force Stop не удалось удалить свой раздел блокировок из %s: веб-сервер продолжает отклонять адреса из него. Сделайте файл доступным для записи и удалите вручную строки между '# BEGIN BFStop Blocks' и '# END BFStop Blocks'." diff --git a/plugin/src/Extension/Bfstop.php b/plugin/src/Extension/Bfstop.php index 69009d4..881e6d9 100644 --- a/plugin/src/Extension/Bfstop.php +++ b/plugin/src/Extension/Bfstop.php @@ -89,9 +89,9 @@ public static function getSubscribedEvents(): array ); } - private function intParam($paramName, $default) + private function intParam($paramName): int { - return (int) $this->params->get($paramName, $default); + return Settings::int($this->params, $paramName); } private function init() @@ -128,23 +128,23 @@ private function notifier(): NotifierHelper if ($this->notifier === null) { $this->notifier = new NotifierHelper($this->logger, $this->repositories, - $this->params->get('emailaddress', ''), - $this->intParam('userID', -1), - $this->intParam('userGroup', -1), - (bool) $this->params->get('groupNotificationEnabled', false)); + Settings::get($this->params, 'emailaddress'), + $this->intParam('userID'), + $this->intParam('userGroup'), + Settings::bool($this->params, 'groupNotificationEnabled')); } return $this->notifier; } private function isEnabledForCurrentOrigin() { - return Origin::isEnabled($this->params->get('enabledForOrigin', Settings::Defaults['enabledForOrigin']), + return Origin::isEnabled(Settings::get($this->params, 'enabledForOrigin'), $this->getApplication()); } private function trackedAddress($ipAddress) { - return IpHelper::trackedAddress($ipAddress, $this->intParam('ipv6PrefixLength', Settings::Defaults['ipv6PrefixLength'])); + return IpHelper::trackedAddress($ipAddress, $this->intParam('ipv6PrefixLength')); } /** @@ -153,7 +153,7 @@ private function trackedAddress($ipAddress) */ private function usernameForStorage($username) { - $mode = (string) $this->params->get('unknownUsernameMode', UsernameHelper::ModeHash); + $mode = Settings::string($this->params, 'unknownUsernameMode'); $isReadable = ($mode !== UsernameHelper::ModePlain) && ($this->isAccount($username) || RiskHelper::isCommonUsername($this->params, $username)); @@ -243,14 +243,14 @@ public function onUserLoginFailure(LoginFailureEvent $event) // $username is what was typed; the entry only holds a hash of it if // it isn't an account (see usernameForStorage()) - if ((bool) $this->params->get('notifyFailedOnlyExisting', false) && + if (Settings::bool($this->params, 'notifyFailedOnlyExisting') && !$this->isAccount($username)) { $this->logger->log('Not notifying of failed login: the username does not belong to an account', Log::DEBUG); } else { - $this->notifier()->failedLogin($logEntry, $this->intParam('notifyFailedNumber', 0)); + $this->notifier()->failedLogin($logEntry, $this->intParam('notifyFailedNumber')); } $delay = $this->policy->delaySeconds($logEntry, $riskScore); @@ -298,26 +298,46 @@ private function block($logEntry) private function notifyOfBlock($logEntry, $id, $duration, $targetedOtherAccounts) { $this->notifier()->blockedNotifyAdmin($logEntry, BlockPolicy::realDuration($duration), - $this->intParam('notifyBlockedNumber', 5)); + $this->intParam('notifyBlockedNumber')); if (!$this->policy->notifiesBlockedUser()) { return; } - $userEmail = $this->repositories->users()->emailByUsername($logEntry->username); - if ($userEmail == null) + // the failed login may have been typed with the email address, or in + // another case: matched as Joomla matches a login (and accountExists()) + $account = $this->repositories->users()->accountByLogin($logEntry->username); + if ($account === null) { $this->logger->log('Unknown user ('.$logEntry->username.') blocked, not sending any notifications', Log::DEBUG); return; } - $withheld = $this->policy->whyNoUnblockMail($logEntry, $this->clientAddress, $targetedOtherAccounts); + $userEmail = $account['email']; + $withheld = $this->policy->whyNoUnblockMail($logEntry, $this->clientAddress, $targetedOtherAccounts, + $account['username']); if ($withheld !== null) { $this->logger->log("Existing user '".$logEntry->username."' was blocked, but ".$withheld. ' - not sending unblock instructions', Log::INFO); return; } + try + { + $token = TokenHelper::getToken(); + } + catch (\Throwable $e) + { + // no source of randomness: no link rather than a weak one + $this->logger->log('Could not make an unblock token: '.$e->getMessage(), Log::ERROR); + return; + } + if ($this->repositories->unblockTokens()->add($id, $token, $account['username']) === null) + { + // a link whose token isn't stored would lead nowhere + $this->logger->log("Existing user '".$logEntry->username."' was blocked, but the unblock token ". + 'could not be stored - not sending unblock instructions', Log::ERROR); + return; + } $this->logger->log("Existing user '".$logEntry->username."' was blocked, sending unblock instructions", Log::INFO); - $token = $this->repositories->unblockTokens()->add($id, TokenHelper::getToken(), $logEntry->username); $this->notifier()->sendUnblockMail($userEmail, TokenHelper::unblockLink($token)); } @@ -342,11 +362,13 @@ public function onUserLogin(LoginEvent $event) $info = new \stdClass(); $info->ipaddress = $ipAddress; $info->username = (string) ($user['username'] ?? ''); + // failed logins may have been typed with the email address + $info->email = (string) ($user['email'] ?? ''); $this->logger->log('Successful login by '.$info->username. ' from IP address '.$info->ipaddress, Log::DEBUG); $this->logins->recordSuccessfulLogin($info, $this->trackedAddress($info->ipaddress), IpHelper::trackedAddress($info->ipaddress, IpHelper::trustPrefixLength( - $this->intParam('ipv6PrefixLength', Settings::Defaults['ipv6PrefixLength'])))); + $this->intParam('ipv6PrefixLength')))); } public function onAfterInitialise($event) diff --git a/plugin/src/Service/LoginTurn.php b/plugin/src/Service/LoginTurn.php index c2a85e6..8eb743d 100644 --- a/plugin/src/Service/LoginTurn.php +++ b/plugin/src/Service/LoginTurn.php @@ -10,10 +10,8 @@ defined('_JEXEC') or die; -use Codeling\Library\Bfstop\Helper\HtaccessHelper; use Codeling\Library\Bfstop\Helper\LockHelper; use Codeling\Library\Bfstop\Helper\LoggerHelper; -use Joomla\CMS\Factory; use Joomla\CMS\Log\Log; /** @@ -54,17 +52,15 @@ class LoginTurn /** * The lock file for the logins of a client, by the key it is tracked * under (IpHelper::trackedAddress()), one set of files per site (see - * Responder::delaySlotFiles()). A fixed number of files, not one per - * address: a visitor with many addresses must not be able to fill the - * directory. Which one an address gets depends on the site's secret, so - * nobody can pick addresses which share the file of somebody else's. + * LockHelper::file()). A fixed number of files, not one per address: a + * visitor with many addresses must not be able to fill the directory. + * Which one an address gets depends on the site's secret (see + * LockHelper::slot()), so nobody can pick addresses which share the file + * of somebody else's. */ public static function file($trackedAddress) { - $app = Factory::getApplication(); - $slot = hexdec(substr(hash_hmac('sha256', (string) $trackedAddress, (string) $app->get('secret', '')), 0, 7)) - % self::Slots; - return HtaccessHelper::lockDirectory().'/bfstop-login-'.LockHelper::siteHash().'-'.$slot.'.lock'; + return LockHelper::file('login', LockHelper::slot($trackedAddress, self::Slots)); } /** diff --git a/plugin/src/Service/Responder.php b/plugin/src/Service/Responder.php index 2e02ac8..5c73c78 100644 --- a/plugin/src/Service/Responder.php +++ b/plugin/src/Service/Responder.php @@ -10,7 +10,6 @@ defined('_JEXEC') or die; -use Codeling\Library\Bfstop\Helper\HtaccessHelper; use Codeling\Library\Bfstop\Helper\LockHelper; use Codeling\Library\Bfstop\Helper\LoggerHelper; use Codeling\Library\Bfstop\Settings; @@ -57,10 +56,9 @@ private function isApi(): bool */ public function showsRemainingAttempts(): bool { - $passwordReminder = (int) $this->params->get('notifyUsePasswordReminder', - Settings::Defaults['notifyUsePasswordReminder']); + $passwordReminder = Settings::int($this->params, 'notifyUsePasswordReminder'); return !$this->isApi() && - ((bool) $this->params->get('notifyRemainingAttempts', false) || + (Settings::bool($this->params, 'notifyRemainingAttempts') || $passwordReminder == -1 || $passwordReminder > 0); } @@ -75,9 +73,8 @@ public function showRemainingAttempts($attemptsLeft) $this->logger->log('Remaining attempts below zero ('.$attemptsLeft.'), that should not happen. ', Log::ERROR); return; } - $passwordReminder = (int) $this->params->get('notifyUsePasswordReminder', - Settings::Defaults['notifyUsePasswordReminder']); - if ((bool) $this->params->get('notifyRemainingAttempts', false) && $attemptsLeft > 0) + $passwordReminder = Settings::int($this->params, 'notifyUsePasswordReminder'); + if (Settings::bool($this->params, 'notifyRemainingAttempts') && $attemptsLeft > 0) { $this->app->enqueueMessage(Text::sprintf('PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT', $attemptsLeft), 'warning'); } @@ -94,7 +91,7 @@ public function showRemainingAttempts($attemptsLeft) */ public function refuseBlocked($ipaddress) { - $status = self::blockedResponseCode((bool) $this->params->get('useHttpError', true)); + $status = self::blockedResponseCode(Settings::bool($this->params, 'useHttpError')); if ($status !== null) { http_response_code($status); @@ -103,8 +100,8 @@ public function refuseBlocked($ipaddress) { header($header); } - $message = $this->params->get('blockedMessage', Text::_('PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE')); - if ((bool) $this->params->get('blockedMsgShowIP', false)) + $message = Settings::string($this->params, 'blockedMessage') ?: Text::_('PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE'); + if (Settings::bool($this->params, 'blockedMsgShowIP')) { $message .= ' '.Text::sprintf('PLG_SYSTEM_BFSTOP_BLOCKED_CLIENT_IP', $ipaddress); } @@ -197,11 +194,10 @@ public static function cappedDelay($seconds) */ public static function delaySlotFiles($count) { - $site = LockHelper::siteHash(); $files = array(); for ($i = 0; $i < max(1, (int) $count); ++$i) { - $files[] = HtaccessHelper::lockDirectory().'/bfstop-delay-'.$site.'-'.$i.'.lock'; + $files[] = LockHelper::file('delay', $i); } return $files; } @@ -240,8 +236,7 @@ public function delay($seconds) { return false; } - $maxConcurrent = max(1, (int) $this->params->get('delayMaxConcurrent', - Settings::Defaults['delayMaxConcurrent'])); + $maxConcurrent = max(1, Settings::int($this->params, 'delayMaxConcurrent')); $opened = false; foreach (self::delaySlotFiles($maxConcurrent) as $file) { @@ -271,7 +266,7 @@ public function delay($seconds) // not delaying is what keeps the server available $this->logger->log($opened ? 'Not delaying the response: '.$maxConcurrent.' response(s) are being delayed already' - : 'Not delaying the response: could not create the lock files in '.HtaccessHelper::lockDirectory(), + : 'Not delaying the response: could not create the lock files in '.LockHelper::directory(), $opened ? Log::INFO : Log::WARNING); return false; } diff --git a/plugin/updatescript.php b/plugin/updatescript.php index a51546a..771ee52 100644 --- a/plugin/updatescript.php +++ b/plugin/updatescript.php @@ -13,6 +13,7 @@ use Joomla\CMS\Installer\InstallerScript; use Joomla\CMS\Installer\InstallerScriptInterface; use Joomla\CMS\Language\Text; +use Joomla\CMS\Log\Log; use Joomla\CMS\Router\Route; use Joomla\Database\DatabaseInterface; @@ -26,7 +27,7 @@ class PlgsystembfstopInstallerScript extends InstallerScript implements Installe // InstallerScript::preflight() refuses to install on anything older (and // to replace a newer version of the plugin with an older one) protected $minimumJoomla = '5.4.0'; - protected $minimumPhp = '8.1.0'; + protected $minimumPhp = '8.2.0'; // the version this update replaces, null for an installation private $previousVersion = null; @@ -35,6 +36,9 @@ class PlgsystembfstopInstallerScript extends InstallerScript implements Installe // be replaced, see replaceLegacyHtaccessSection() private $htaccessNotRewritten = null; + // why update() could not migrate the settings and data, if it couldn't + private $updateFailure = null; + // the bit of the "enabledForOrigin" setting for the Web Services API // (Origin::Api - the class of the version being replaced may be the // one loaded while this runs) @@ -263,6 +267,15 @@ private function renameWhitelistTable() public function postflight(string $type, InstallerAdapter $adapter): bool { + if ($this->updateFailure !== null) + { + Factory::getApplication()->getLanguage()->load('plg_system_bfstop', JPATH_ADMINISTRATOR); + Factory::getApplication()->enqueueMessage( + Text::sprintf('PLG_SYSTEM_BFSTOP_UPDATE_MIGRATION_FAILED', htmlspecialchars($this->updateFailure, ENT_QUOTES, 'UTF-8'), + Route::_('index.php?option=com_bfstop&view=settings', false)), + 'error' + ); + } if ($this->htaccessNotRewritten !== null) { Factory::getApplication()->getLanguage()->load('plg_system_bfstop', JPATH_ADMINISTRATOR); @@ -415,8 +428,13 @@ public function update(InstallerAdapter $adapter): bool } catch (\Throwable $e) { - // if the extension row can't be found/updated, there's nothing we can do -// Log::add("Update ERROR: ".$e->getMessage(), Log::ERROR, 'Update'); + // the update itself goes on (the files are new, the plugin works + // with its defaults), but the administrator has to know: the + // settings may not have been moved or converted. Logged, and + // told by postflight() + $this->updateFailure = $e->getMessage(); + Log::add('Brute Force Stop: the update could not migrate the settings and data: '.$e->getMessage(), + Log::ERROR, 'jerror'); } return true; } @@ -626,6 +644,18 @@ public static function replaceLegacyHtaccessSection($file) return self::writeFile($file, implode("\n", $lines)); } + /** + * Whether $line is the of a block the plugin writes: a condition of + * nothing but addresses, with the exception of the unblock page or + * without (a copy of HtaccessHelper's, see htaccessFile() for why). + */ + private static function isBlockCondition($line) + { + $terms = "-R '[^']*'(?: \\|\\| -R '[^']*')*"; + $unblockPage = " && !\\(%\\{REQUEST_URI\\} == '[^']*' && %\\{QUERY_STRING\\} =~ /[^/]*/\\)"; + return preg_match('#^$#', $line) === 1; + } + /** * The first and the last line of the block section of the .htaccess file * with the lines $lines (its markers), or two nulls if it has none. @@ -700,9 +730,30 @@ public static function removeHtaccessSection($file) for ($i = $begin + 1; $i < $end; ++$i) { $line = trim($lines[$i]); - if ($line === '' || strpos($line, '', '', 'Require all granted', ''), true)) + if (self::isBlockCondition($line) && trim($lines[$i + 1] ?? '') === 'Require all denied' && + trim($lines[$i + 2] ?? '') === '' && $i + 2 < $end) + { + // a block the plugin wrote + $i += 2; + continue; + } + if (preg_match('/^]/i', $line)) + { + // one somebody wrote by hand: kept, up to the which closes it + for ($depth = 0; $i < $end; ++$i) + { + $inner = trim($lines[$i]); + $depth += (preg_match('/^]/i', $inner) ? 1 : 0) - (strcasecmp($inner, '') === 0 ? 1 : 0); + $other[] = rtrim($lines[$i], "\r"); + if ($depth <= 0) + { + break; + } + } + continue; + } + if ($line === '' || strpos($line, 'Require not ip ') === 0 || strpos($line, 'ErrorDocument 403 ') === 0 || + in_array($line, array('', 'Require all granted', ''), true)) { continue; } diff --git a/task/script.php b/task/script.php index b8f928c..1ae6eb2 100644 --- a/task/script.php +++ b/task/script.php @@ -29,7 +29,7 @@ class PlgtaskbfstopInstallerScript extends InstallerScript implements InstallerScriptInterface { protected $minimumJoomla = '5.4.0'; - protected $minimumPhp = '8.1.0'; + protected $minimumPhp = '8.2.0'; /** the routine of the plugin, see Codeling\Plugin\Task\Bfstop\Extension\Bfstop */ public const Routine = 'bfstop.maintenance'; diff --git a/tests/Integration/BlockPolicyTest.php b/tests/Integration/BlockPolicyTest.php index 832edbd..75bacd4 100644 --- a/tests/Integration/BlockPolicyTest.php +++ b/tests/Integration/BlockPolicyTest.php @@ -130,6 +130,17 @@ public function testDefaults() $this->assertFalse($policy->notifiesBlockedUser()); } + public function testSettingsAreReadWithTheirDefaults() + { + $params = new \Joomla\Registry\Registry(array('blockNumber' => '7', 'emailaddress' => '')); + $this->assertSame(7, Settings::int($params, 'blockNumber')); + $this->assertSame(Settings::Defaults['maxBlocksBefore'], Settings::int($params, 'maxBlocksBefore'), 'not stored'); + $this->assertSame('', Settings::string($params, 'emailaddress')); + $this->assertTrue(Settings::bool($params, 'useHttpError')); + $this->expectException(\InvalidArgumentException::class); + Settings::get($params, 'blockNumbr'); + } + public function testModeAndConfiguredValues() { $policy = $this->policy(array('blockMode' => 'off', 'blockDuration' => '90', 'checkInterval' => '30', diff --git a/tests/Integration/ComponentTest.php b/tests/Integration/ComponentTest.php index b69dede..2879466 100644 --- a/tests/Integration/ComponentTest.php +++ b/tests/Integration/ComponentTest.php @@ -108,9 +108,10 @@ public function testUnblockViaEmailToken() $this->assertTrue($helper->blocks()->isBlocked('203.0.113.5')); $model = $this->model(TokenunblockModel::class); - $this->assertFalse((bool) $model->unblock('expired', $this->logger), 'expired token must not unblock'); - $this->logger->errors = array(); // expected: "token not found" error - $this->assertTrue((bool) $model->unblock('valid', $this->logger)); + $this->assertSame(TokenunblockModel::ResultNotFound, $model->process('expired', true, '203.0.113.5', $this->logger), + 'expired token must not unblock'); + $this->logger->errors = array(); // expected: "no block found" error + $this->assertSame(TokenunblockModel::ResultUnblocked, $model->process('valid', true, '203.0.113.5', $this->logger)); $this->assertFalse($helper->blocks()->isBlocked('203.0.113.5')); $this->assertSame(1, (int) $this->queryValue('SELECT source FROM #__bfstop_unblock WHERE block_id='.$blockId)); @@ -279,14 +280,8 @@ public function testMessagesEscapeWhatWasTypedIn() Factory::getLanguage()->load('com_bfstop', BFSTOP_COMPONENT_ROOT.'/admin'); $app->getMessageQueue(true); $evil = ''; - $this->assertFalse(IpValidateHelper::validIPRange($evil)); - $this->assertFalse(IpValidateHelper::validIPRange('203.0.113.0/'.$evil)); - IpValidateHelper::validIPRange('10.0.0.1'); // private: a warning with the address - $messages = ''; - foreach ($app->getMessageQueue(true) as $message) - { - $messages .= $message['message']; - } + $messages = IpValidateHelper::rangeError($evil).IpValidateHelper::rangeError('203.0.113.0/'.$evil). + IpValidateHelper::currentIpError($evil); $this->assertStringNotContainsString('