diff --git a/CHANGELOG b/CHANGELOG
index 2df39b3..9e7fb26 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,5 +1,18 @@
2.0.0 (unreleased)
- Requires PHP 8.2 (was 8.1), the oldest version CI runs the tests on
+ - Issue #294: the administrators' mail about a block lists the failed
+ logins which led to it, not every failed login of the address still
+ stored (for a permanent block: of ten years, including those of earlier
+ blocks); an IPv4 client which the web server reports as IPv4-mapped IPv6
+ (::ffff:203.0.113.5, a server listening on "[::]") is handled as the IPv4
+ address, so the IPv4 entries of the block and allow list and the trusted
+ proxies match it (entries typed in that form are stored as IPv4, and the
+ update converts those of the lists); "Minimum Allowed Attempts" above
+ the block threshold no longer raises the threshold for every client
+ (the settings page refuses it, a stored value is capped); the IP
+ information page looks up a blocked network by its network address
+ instead of showing nothing; taking entries out of the .htaccess file
+ needs core.admin as well as core.delete, as adding one does
- 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
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 befc4c2..f8dce5a 100644
--- a/component/admin/language/ca-ES/ca-ES.com_bfstop.ini
+++ b/component/admin/language/ca-ES/ca-ES.com_bfstop.ini
@@ -206,6 +206,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Totes les entrades del registre s'eliminaran de maner
COM_BFSTOP_LOG_CLEAR_CONFIRM="Buida"
COM_BFSTOP_LOG_CLEARED="S'ha buidat el registre."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Els enllaços de desbloqueig només es poden enviar si l'adreça del lloc està definida ($live_site al configuration.php del lloc). Definiu-la allà, o desactiveu els enllaços de desbloqueig."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) no pot ser més alt que \"%3$s\" (%4$d): cada client tindria %2$d intents. Reduïu \"%1$s\", o augmenteu \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="L'adreça del lloc no està definida ($live_site al configuration.php). Llavors Joomla! construeix els enllaços dels correus de Brute Force Stop amb l'amfitrió indicat a cada petició, que un visitant pot triar lliurement - per això no s'envia cap enllaç de desbloqueig i les notificacions als administradors no indiquen cap adreça. Per definir l'adreça, afegiu aquesta línia a la classe del configuration.php del lloc, amb l'adreça amb què s'accedeix al lloc (proposada a partir d'aquesta petició, comproveu-la): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="S'han d'enviar enllaços de desbloqueig (configuració), però l'adreça del lloc no està definida ($live_site al configuration.php): no s'envia cap enllaç de desbloqueig."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recomanat)"
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 d4632d1..4b269b5 100644
--- a/component/admin/language/de-DE/de-DE.com_bfstop.ini
+++ b/component/admin/language/de-DE/de-DE.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Alle Logeinträge werden unwiderruflich gelöscht, au
COM_BFSTOP_LOG_CLEAR_CONFIRM="Leeren"
COM_BFSTOP_LOG_CLEARED="Das Log wurde geleert."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Entsperr-Links können nur gesendet werden, wenn die Adresse der Website gesetzt ist ($live_site in der configuration.php der Website). Setze sie dort, oder schalte die Entsperr-Links aus."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="„%1$s“ (%2$d) darf nicht höher sein als „%3$s“ (%4$d): Jeder Client bekäme %2$d Versuche. Verringere „%1$s“ oder erhöhe „%3$s“."
COM_BFSTOP_WARNING_NO_LIVE_SITE="Die Adresse der Website ist nicht gesetzt ($live_site in der configuration.php). Joomla! baut die Links in den Emails von Brute Force Stop dann mit dem Host, den die jeweilige Anfrage nennt und den ein Besucher frei wählen kann - deshalb werden keine Entsperr-Links gesendet, und die Benachrichtigungen an die Administratoren nennen keine Adresse. Um die Adresse zu setzen, füge diese Zeile in die Klasse in der configuration.php der Website ein, mit der Adresse, unter der die Website erreichbar ist (aus dieser Anfrage vorgeschlagen, bitte prüfen): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Entsperr-Links sollen gesendet werden (Einstellungen), aber die Adresse der Website ist nicht gesetzt ($live_site in der configuration.php): es werden keine Entsperr-Links gesendet."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (empfohlen)"
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 03a9285..158f30d 100644
--- a/component/admin/language/en-GB/en-GB.com_bfstop.ini
+++ b/component/admin/language/en-GB/en-GB.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="All log entries will be permanently deleted, includin
COM_BFSTOP_LOG_CLEAR_CONFIRM="Clear"
COM_BFSTOP_LOG_CLEARED="The log was cleared."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Unblock links can only be sent if the site's address is set ($live_site in the site's configuration.php). Set it there, or turn the unblock links off."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) must not be higher than \"%3$s\" (%4$d): every client would get %2$d attempts. Lower \"%1$s\", or raise \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="The site's address is not set ($live_site in configuration.php). Joomla! then builds the links in the emails of Brute Force Stop from the host named by each request, which a visitor can choose freely - so no unblock links are sent, and the notifications to the administrators name no address. To set the address, add this line to the class in the site's configuration.php, with the address under which the site is reached (proposed from this request, please check it): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Unblock links are to be sent (settings), but the site's address is not set ($live_site in configuration.php): no unblock links are sent."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recommended)"
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 355f265..7c380dd 100644
--- a/component/admin/language/es-ES/es-ES.com_bfstop.ini
+++ b/component/admin/language/es-ES/es-ES.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Todas las entradas del registro se eliminarán de for
COM_BFSTOP_LOG_CLEAR_CONFIRM="Vaciar"
COM_BFSTOP_LOG_CLEARED="Se ha vaciado el registro."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Los enlaces de desbloqueo solo se pueden enviar si la dirección del sitio está definida ($live_site en el configuration.php del sitio). Defínala allí, o desactive los enlaces de desbloqueo."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) no puede ser mayor que \"%3$s\" (%4$d): cada cliente tendría %2$d intentos. Reduzca \"%1$s\", o aumente \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="La dirección del sitio no está definida ($live_site en configuration.php). Entonces Joomla! construye los enlaces de los correos de Brute Force Stop con el host indicado en cada petición, que un visitante puede elegir libremente - por eso no se envían enlaces de desbloqueo y las notificaciones a los administradores no indican ninguna dirección. Para definir la dirección, añada esta línea a la clase del configuration.php del sitio, con la dirección en la que se accede al sitio (propuesta a partir de esta petición, compruébela): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Se deben enviar enlaces de desbloqueo (configuración), pero la dirección del sitio no está definida ($live_site en configuration.php): no se envían enlaces de desbloqueo."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recomendado)"
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 731ef3c..ff7ce66 100644
--- a/component/admin/language/fr-FR/fr-FR.com_bfstop.ini
+++ b/component/admin/language/fr-FR/fr-FR.com_bfstop.ini
@@ -212,6 +212,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Toutes les entrées du journal seront définitivement
COM_BFSTOP_LOG_CLEAR_CONFIRM="Vider"
COM_BFSTOP_LOG_CLEARED="Le journal a été vidé."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Les liens de déblocage ne peuvent être envoyés que si l'adresse du site est définie ($live_site dans le fichier configuration.php du site). Définissez-la, ou désactivez les liens de déblocage."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="« %1$s » (%2$d) ne doit pas être supérieur à « %3$s » (%4$d) : chaque client aurait %2$d tentatives. Diminuez « %1$s », ou augmentez « %3$s »."
COM_BFSTOP_WARNING_NO_LIVE_SITE="L'adresse du site n'est pas définie ($live_site dans configuration.php). Joomla! construit alors les liens des e-mails de Brute Force Stop à partir de l'hôte indiqué par chaque requête, qu'un visiteur peut choisir librement - c'est pourquoi aucun lien de déblocage n'est envoyé et les notifications aux administrateurs n'indiquent pas d'adresse. Pour définir l'adresse, ajoutez cette ligne à la classe du fichier configuration.php du site, avec l'adresse à laquelle le site est accessible (proposée d'après cette requête, veuillez la vérifier) : %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Des liens de déblocage doivent être envoyés (paramètres), mais l'adresse du site n'est pas définie ($live_site dans configuration.php) : aucun lien de déblocage n'est envoyé."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recommandé)"
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 d1f1f4c..87de659 100644
--- a/component/admin/language/it-IT/it-IT.com_bfstop.ini
+++ b/component/admin/language/it-IT/it-IT.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Tutte le voci del log verranno eliminate definitivame
COM_BFSTOP_LOG_CLEAR_CONFIRM="Svuota"
COM_BFSTOP_LOG_CLEARED="Il log è stato svuotato."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="I link di sblocco possono essere inviati solo se l'indirizzo del sito è impostato ($live_site nel configuration.php del sito). Impostalo lì, oppure disattiva i link di sblocco."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) non può essere superiore a \"%3$s\" (%4$d): ogni client avrebbe %2$d tentativi. Riduci \"%1$s\", oppure aumenta \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="L'indirizzo del sito non è impostato ($live_site in configuration.php). Joomla! costruisce allora i link nelle email di Brute Force Stop dall'host indicato in ogni richiesta, che un visitatore può scegliere liberamente - per questo non vengono inviati link di sblocco e le notifiche agli amministratori non indicano alcun indirizzo. Per impostare l'indirizzo, aggiungi questa riga alla classe nel configuration.php del sito, con l'indirizzo con cui si raggiunge il sito (proposto in base a questa richiesta, verificalo): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="I link di sblocco devono essere inviati (impostazioni), ma l'indirizzo del sito non è impostato ($live_site in configuration.php): non viene inviato alcun link di sblocco."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (consigliato)"
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 18b7969..7a74103 100644
--- a/component/admin/language/nl-NL/nl-NL.com_bfstop.ini
+++ b/component/admin/language/nl-NL/nl-NL.com_bfstop.ini
@@ -205,6 +205,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Alle logitems worden definitief verwijderd, inclusief
COM_BFSTOP_LOG_CLEAR_CONFIRM="Wissen"
COM_BFSTOP_LOG_CLEARED="Het log is gewist."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Deblokkeerlinks kunnen alleen worden verstuurd als het adres van de site is ingesteld ($live_site in de configuration.php van de site). Stel het daar in, of schakel de deblokkeerlinks uit."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) mag niet hoger zijn dan \"%3$s\" (%4$d): elke client zou %2$d pogingen krijgen. Verlaag \"%1$s\", of verhoog \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="Het adres van de site is niet ingesteld ($live_site in configuration.php). Joomla! bouwt de links in de e-mails van Brute Force Stop dan op uit de host die elk verzoek noemt, en die kan een bezoeker vrij kiezen - daarom worden geen deblokkeerlinks verstuurd en noemen de meldingen aan de beheerders geen adres. Om het adres in te stellen, voeg deze regel toe aan de klasse in de configuration.php van de site, met het adres waarop de site bereikbaar is (voorgesteld op basis van dit verzoek, controleer het): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Er moeten deblokkeerlinks worden verstuurd (instellingen), maar het adres van de site is niet ingesteld ($live_site in configuration.php): er worden geen deblokkeerlinks verstuurd."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (aanbevolen)"
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 ee4b785..c3a52e4 100644
--- a/component/admin/language/pt-BR/pt-BR.com_bfstop.ini
+++ b/component/admin/language/pt-BR/pt-BR.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Todas as entradas do log serão excluídas permanente
COM_BFSTOP_LOG_CLEAR_CONFIRM="Esvaziar"
COM_BFSTOP_LOG_CLEARED="O log foi esvaziado."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Links de desbloqueio só podem ser enviados se o endereço do site estiver definido ($live_site no configuration.php do site). Defina-o lá, ou desative os links de desbloqueio."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) não pode ser maior que \"%3$s\" (%4$d): todo cliente teria %2$d tentativas. Diminua \"%1$s\", ou aumente \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="O endereço do site não está definido ($live_site no configuration.php). O Joomla! então monta os links dos e-mails do Brute Force Stop com o host indicado em cada requisição, que um visitante pode escolher livremente - por isso nenhum link de desbloqueio é enviado e as notificações aos administradores não indicam nenhum endereço. Para definir o endereço, adicione esta linha à classe no configuration.php do site, com o endereço pelo qual o site é acessado (proposto a partir desta requisição, verifique-o): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Links de desbloqueio devem ser enviados (configurações), mas o endereço do site não está definido ($live_site no configuration.php): nenhum link de desbloqueio é enviado."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recomendado)"
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 acefe11..c4a8567 100644
--- a/component/admin/language/pt-PT/pt-PT.com_bfstop.ini
+++ b/component/admin/language/pt-PT/pt-PT.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Todas as entradas do registo serão eliminadas perman
COM_BFSTOP_LOG_CLEAR_CONFIRM="Esvaziar"
COM_BFSTOP_LOG_CLEARED="O registo foi esvaziado."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="As ligações de desbloqueio só podem ser enviadas se o endereço do site estiver definido ($live_site no configuration.php do site). Defina-o aí, ou desative as ligações de desbloqueio."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="\"%1$s\" (%2$d) não pode ser superior a \"%3$s\" (%4$d): cada cliente teria %2$d tentativas. Diminua \"%1$s\", ou aumente \"%3$s\"."
COM_BFSTOP_WARNING_NO_LIVE_SITE="O endereço do site não está definido ($live_site no configuration.php). O Joomla! constrói então as ligações dos e-mails do Brute Force Stop com o anfitrião indicado em cada pedido, que um visitante pode escolher livremente - por isso não é enviada nenhuma ligação de desbloqueio e as notificações aos administradores não indicam nenhum endereço. Para definir o endereço, adicione esta linha à classe no configuration.php do site, com o endereço pelo qual o site é acedido (proposto a partir deste pedido, verifique-o): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Devem ser enviadas ligações de desbloqueio (definições), mas o endereço do site não está definido ($live_site no configuration.php): não é enviada nenhuma ligação de desbloqueio."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (recomendado)"
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 f4a487f..eb811e7 100644
--- a/component/admin/language/ru-RU/ru-RU.com_bfstop.ini
+++ b/component/admin/language/ru-RU/ru-RU.com_bfstop.ini
@@ -204,6 +204,7 @@ COM_BFSTOP_LOG_CLEAR_DESC="Все записи журнала будут без
COM_BFSTOP_LOG_CLEAR_CONFIRM="Очистить"
COM_BFSTOP_LOG_CLEARED="Журнал очищен."
COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE="Ссылки разблокировки можно отправлять, только если задан адрес сайта ($live_site в configuration.php сайта). Задайте его там или отключите ссылки разблокировки."
+COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER="«%1$s» (%2$d) не может быть больше, чем «%3$s» (%4$d): каждый клиент получил бы %2$d попыток. Уменьшите «%1$s» или увеличьте «%3$s»."
COM_BFSTOP_WARNING_NO_LIVE_SITE="Адрес сайта не задан ($live_site в configuration.php). Тогда Joomla! строит ссылки в письмах Brute Force Stop с хостом, указанным в каждом запросе, который посетитель может выбрать произвольно, — поэтому ссылки разблокировки не отправляются, а уведомления администраторам не содержат адреса. Чтобы задать адрес, добавьте эту строку в класс в configuration.php сайта, указав адрес, по которому доступен сайт (предложен на основе этого запроса, проверьте его): %s"
COM_BFSTOP_WARNING_NOTIFY_ANY_WITHOUT_LIVE_SITE="Ссылки разблокировки должны отправляться (настройки), но адрес сайта не задан ($live_site в configuration.php): ссылки разблокировки не отправляются."
COM_BFSTOP_SETTINGS_IPV6_PREFIX_56="/56 (рекомендуется)"
diff --git a/component/admin/src/Controller/HtblocklistController.php b/component/admin/src/Controller/HtblocklistController.php
index be9a687..cbe4d56 100644
--- a/component/admin/src/Controller/HtblocklistController.php
+++ b/component/admin/src/Controller/HtblocklistController.php
@@ -22,6 +22,18 @@
*/
class HtblocklistController extends BaseController
{
+ /**
+ * Whether $user may take entries out of the .htaccess file: core.admin
+ * as well as core.delete, like adding one (see HtblockController::mayAdd()):
+ * the file is part of the web server's configuration, and an entry an
+ * administrator added by hand is taken out with the same task. The
+ * toolbar asks this too.
+ */
+ public static function mayRemove($user): bool
+ {
+ return $user && $user->authorise('core.delete', 'com_bfstop') && $user->authorise('core.admin', 'com_bfstop');
+ }
+
public function getModel($name = 'htblocklist', $prefix = '', $config = [])
{
$model = parent::getModel($name, $prefix, array('ignore_request' => true));
@@ -33,7 +45,7 @@ public function unblock()
$this->checkToken();
// custom action, not AdminModel's standard delete() flow, so it
// doesn't get the built-in core.delete check for free
- if (!$this->app->getIdentity()->authorise('core.delete', 'com_bfstop'))
+ if (!self::mayRemove($this->app->getIdentity()))
{
$this->setRedirect(Route::_('index.php?option=com_bfstop&view=htblocklist', false),
Text::_('COM_BFSTOP_NOT_AUTHORISED'), 'error');
diff --git a/component/admin/src/Model/SettingsModel.php b/component/admin/src/Model/SettingsModel.php
index e89e451..ad5bf98 100644
--- a/component/admin/src/Model/SettingsModel.php
+++ b/component/admin/src/Model/SettingsModel.php
@@ -22,6 +22,7 @@
use Joomla\CMS\MVC\Model\AdminModel;
use Joomla\CMS\Table\Asset;
use Joomla\CMS\Table\Extension;
+use Joomla\Registry\Registry;
/**
* The settings of BFStop, which are the params of the component's row of
@@ -119,6 +120,26 @@ public function validate($form, $data, $group = null)
$this->setError(Text::_('COM_BFSTOP_SETTINGS_NOTIFY_ANY_NEEDS_LIVE_SITE'));
return false;
}
+ if (is_array($valid))
+ {
+ // the floor of the risk scoring is a floor of the threshold for
+ // every client (see BlockPolicy::effectiveBlockNumber()): above the
+ // threshold it would raise it for everybody
+ $params = new Registry($valid['params'] ?? array());
+ $blockNumber = Settings::int($params, 'blockNumber');
+ $minBlockNumber = Settings::int($params, 'riskMinBlockNumber');
+ if ($minBlockNumber > $blockNumber)
+ {
+ // the label of the threshold is the plugin's, see the view
+ $language = Factory::getApplication()->getLanguage();
+ $language->load('plg_system_bfstop.sys', JPATH_ADMINISTRATOR)
+ || $language->load('plg_system_bfstop.sys', JPATH_PLUGINS.'/system/bfstop');
+ $this->setError(Text::sprintf('COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER',
+ Text::_('COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_LABEL'), $minBlockNumber,
+ Text::_('PLG_SYSTEM_BFSTOP_BLOCK_NUMBER_LABEL'), $blockNumber));
+ return false;
+ }
+ }
return $valid;
}
diff --git a/component/admin/src/View/Htblocklist/HtmlView.php b/component/admin/src/View/Htblocklist/HtmlView.php
index b361ef9..24d616d 100644
--- a/component/admin/src/View/Htblocklist/HtmlView.php
+++ b/component/admin/src/View/Htblocklist/HtmlView.php
@@ -11,6 +11,7 @@
defined('_JEXEC') or die;
use Codeling\Component\Bfstop\Administrator\Controller\HtblockController;
+use Codeling\Component\Bfstop\Administrator\Controller\HtblocklistController;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
@@ -42,7 +43,8 @@ protected function addToolBar()
$user = Factory::getApplication()->getIdentity();
ToolbarHelper::title(Text::_('COM_BFSTOP_HEADING_HTACCESS_BLOCKLIST'), 'bfstop');
ToolbarHelper::divider();
- if ($user->authorise('core.delete', 'com_bfstop'))
+ // the same rule as the task, see HtblocklistController::mayRemove()
+ if (HtblocklistController::mayRemove($user))
{
// batch unblock would require rewrite of unblock method to check
// for selected lines
diff --git a/library/src/Helper/GeoHelper.php b/library/src/Helper/GeoHelper.php
index 3be7167..871d359 100644
--- a/library/src/Helper/GeoHelper.php
+++ b/library/src/Helper/GeoHelper.php
@@ -41,7 +41,9 @@ public static function getCountryCode(LoggerHelper $logger, $dbPath, $ipaddress)
/**
* Needs a GeoLite2-City-tier database (region/city/postal/lat-long are
* not present in a Country-tier database). Used to restore the "click a
- * blocked IP" admin info view (#169).
+ * blocked IP" admin info view (#169). $ipaddress may also be a network
+ * (the block list has IPv6 clients by their network, see
+ * IpHelper::trackedAddress()): it is looked up by its network address.
*/
public static function getCityDetails(LoggerHelper $logger, $dbPath, $ipaddress)
{
@@ -81,12 +83,15 @@ private static function lookup(LoggerHelper $logger, $dbPath, $ipaddress)
$logger->log('GeoHelper: GeoIP database file not readable: '.$dbPath, Log::WARNING);
return null;
}
+ // the reader takes addresses only: a network by its network address
+ $canonical = IpHelper::canonicalEntry($ipaddress);
+ $address = $canonical === null ? (string) $ipaddress : explode('/', $canonical)[0];
try
{
$reader = new Reader($dbPath);
try
{
- $record = $reader->get($ipaddress);
+ $record = $reader->get($address);
}
finally
{
diff --git a/library/src/Helper/HtaccessHelper.php b/library/src/Helper/HtaccessHelper.php
index 732fae1..dbf0e04 100644
--- a/library/src/Helper/HtaccessHelper.php
+++ b/library/src/Helper/HtaccessHelper.php
@@ -312,11 +312,14 @@ public static function entryFor($tracked, $client)
/**
* Whether the entry $entry of the file is one a block of $address put
* there: $address itself, or the /64 of a client within it (see
- * entryFor()).
+ * entryFor()). An IPv4-mapped entry is the IPv4 address: earlier
+ * versions wrote the address of an IPv4 client in the form the web
+ * server reported it, the block list has it as IPv4 now (see
+ * IpHelper::unmapped()).
*/
public static function isEntryOf($entry, $address)
{
- $entry = (string) $entry;
+ $entry = IpHelper::unmapped((string) $entry);
$address = (string) $address;
if ($entry === $address)
{
diff --git a/library/src/Helper/IpHelper.php b/library/src/Helper/IpHelper.php
index f3fff46..2c454e8 100644
--- a/library/src/Helper/IpHelper.php
+++ b/library/src/Helper/IpHelper.php
@@ -38,9 +38,14 @@ class IpHelper
* that doesn't parse, IPv4 vs. IPv6 mismatch, or a prefix length that
* isn't a plain number within range for the address family - never
* matches, so a corrupted stored entry can't turn into a wildcard.
+ * IPv4-mapped IPv6 addresses and networks are compared as IPv4, see
+ * unmapped().
*/
public static function isInSubnet($ip, $subnet)
{
+ // an IPv4-mapped address is the IPv4 address, see unmapped()
+ $ip = self::unmapped($ip);
+ $subnet = self::unmapped($subnet);
$parts = explode('/', $subnet);
if (count($parts) !== 2 || !preg_match('/^[0-9]{1,3}\z/', $parts[1]))
{
@@ -106,18 +111,53 @@ public static function prefixMask($bits, $length = 16)
return str_pad($mask, $length, "\x00");
}
+ // the first 12 bytes of an IPv4-mapped IPv6 address, ::ffff:0:0/96
+ private const MappedPrefix = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff";
+
+ /**
+ * $value - an address, or a network in CIDR notation - with an
+ * IPv4-mapped IPv6 address (::ffff:203.0.113.5) as the IPv4 address it
+ * stands for, and a network within ::ffff:0:0/96 as that IPv4 network
+ * (::ffff:203.0.113.0/120 is 203.0.113.0/24). A web server listening on
+ * an IPv6 socket which takes IPv4 connections too ("[::]") may report an
+ * IPv4 client like that in REMOTE_ADDR: the client would match none of
+ * the IPv4 entries of the block or allow list otherwise. Anything else
+ * is returned as it is.
+ */
+ public static function unmapped($value)
+ {
+ $value = (string) $value;
+ $parts = explode('/', $value, 2);
+ $bin = @inet_pton($parts[0]);
+ if ($bin === false || strlen($bin) !== 16 || substr($bin, 0, 12) !== self::MappedPrefix)
+ {
+ return $value;
+ }
+ $ipv4 = inet_ntop(substr($bin, 12));
+ if (count($parts) === 1)
+ {
+ return $ipv4;
+ }
+ if (!preg_match('/^[0-9]{1,3}\z/', $parts[1]) || (int) $parts[1] < 96 || (int) $parts[1] > 128)
+ {
+ return $value;
+ }
+ return $ipv4.'/'.((int) $parts[1] - 96);
+ }
+
/**
* The one spelling in which addresses and networks are stored in the
* block and allow list: an address in the compressed lower-case form of
* inet_ntop(), a network as its masked network address and prefix length
- * ("2001:db8:1:2::/64", "203.0.113.0/24"). Lookups compare these strings
- * (see lookupCandidates()), so every writer has to use this form.
+ * ("2001:db8:1:2::/64", "203.0.113.0/24"); an IPv4-mapped IPv6 address
+ * or network as the IPv4 one (see unmapped()). Lookups compare these
+ * strings (see lookupCandidates()), so every writer has to use this form.
*
* @return string|null null if $value is neither an address nor a network
*/
public static function canonicalEntry($value)
{
- $value = trim((string) $value);
+ $value = self::unmapped(trim((string) $value));
if (!self::isValidIpOrSubnet($value))
{
return null;
@@ -140,11 +180,14 @@ public static function canonicalEntry($value)
* entries - how many there are depends on what visitors made the plugin
* block, and a request from any visitor has to look.
*
+ * An IPv4-mapped address is looked up as the IPv4 address (see
+ * unmapped()), which is how canonicalEntry() stores it.
+ *
* @return string[] empty if $ip is not an address
*/
public static function lookupCandidates($ip)
{
- $bin = @inet_pton(trim((string) $ip));
+ $bin = @inet_pton(self::unmapped(trim((string) $ip)));
if ($bin === false)
{
return array();
@@ -359,7 +402,8 @@ public static function overlapsTrustedProxy($entry, array $trustedProxies)
*/
public static function isTrustedProxy($ip, array $trustedProxies)
{
- $ipBin = @inet_pton((string) $ip);
+ // an IPv4-mapped address is the IPv4 address, see unmapped()
+ $ipBin = @inet_pton(self::unmapped($ip));
if ($ipBin === false)
{
return false;
@@ -373,7 +417,7 @@ public static function isTrustedProxy($ip, array $trustedProxies)
return true;
}
}
- elseif (@inet_pton($proxy) === $ipBin)
+ elseif (@inet_pton(self::unmapped($proxy)) === $ipBin)
{
return true;
}
@@ -456,7 +500,7 @@ public static function clientAddressFromHeader($headerName, $headerValue, array
}
if (!self::isTrustedProxy($addresses[$i], $trustedProxies))
{
- return $addresses[$i];
+ return self::unmapped($addresses[$i]);
}
}
return null;
@@ -474,7 +518,9 @@ public static function clientAddressFromHeader($headerName, $headerValue, array
*/
public static function getAddress(LoggerHelper $logger)
{
- $remoteAddr = array_key_exists('REMOTE_ADDR', $_SERVER) ? $_SERVER['REMOTE_ADDR'] : '';
+ // an IPv4 client of a server listening on an IPv6 socket may come
+ // as ::ffff:203.0.113.5: as the IPv4 address, see unmapped()
+ $remoteAddr = self::unmapped(array_key_exists('REMOTE_ADDR', $_SERVER) ? $_SERVER['REMOTE_ADDR'] : '');
$settings = self::proxySettings();
if (!$settings['useProxy'])
diff --git a/library/src/Helper/NotifierHelper.php b/library/src/Helper/NotifierHelper.php
index 17c9697..67c269e 100644
--- a/library/src/Helper/NotifierHelper.php
+++ b/library/src/Helper/NotifierHelper.php
@@ -129,12 +129,14 @@ public function isNotificationAllowed($logtime, $maxNumber, $blocks = false)
}
/**
- * The failed logins from $ipAddress in the $interval minutes up to
- * $curTime, as the table in the body of a mail.
+ * The failed logins $entries (see
+ * FailedLoginRepository::listUnhandledFromAddress()) as the table in the
+ * body of a mail.
+ *
+ * @param object[] $entries
*/
- public function failedLoginList($ipAddress, $curTime, $interval)
+ public function failedLoginList(array $entries)
{
- $entries = $this->repositories->failedLogins()->listFromAddress($ipAddress, $curTime, $interval);
$result = str_pad(Text::_('PLG_SYSTEM_BFSTOP_USERNAME'), 25)." ".
str_pad(Text::_('PLG_SYSTEM_BFSTOP_IPADDRESS'), 15)." ".
str_pad(Text::_('PLG_SYSTEM_BFSTOP_DATETIME'), 20)." ".
@@ -150,15 +152,18 @@ public function failedLoginList($ipAddress, $curTime, $interval)
return $result;
}
- public function getBlockedBody($logEntry, $interval)
+ /**
+ * The body of the administrators' mail about the block of the address of
+ * $logEntry, which the failed logins $failedLogins led to.
+ *
+ * @param object[] $failedLogins
+ */
+ public function getBlockedBody($logEntry, array $failedLogins)
{
return Text::sprintf('PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY',
$logEntry->ipaddress,
self::siteAddress(),
- $this->failedLoginList($logEntry->ipaddress,
- $logEntry->logtime,
- $interval
- )
+ $this->failedLoginList($failedLogins)
);
}
@@ -226,14 +231,33 @@ public function failedLogin($logEntry, $maxNumber)
$this->sendMail($subject, $body, $this->notifyAddresses);
}
- public function blockedNotifyAdmin($logEntry, $interval, $maxNumber)
+ /**
+ * Whether blocks may be mailed to the administrators at all, with at
+ * most $maxNumber of them a day (see isNotificationAllowed()): there is
+ * somebody to mail, and the limit isn't 0. For whoever has to collect
+ * what the mail lists before it knows whether one is sent.
+ */
+ public function mailsBlocks($maxNumber): bool
{
- if (count($this->notifyAddresses) === 0 ||
+ return count($this->notifyAddresses) > 0 && $maxNumber != 0;
+ }
+
+ /**
+ * Mails the block of the address of $logEntry to the administrators,
+ * with the failed logins $failedLogins it was for (those it marked
+ * handled - see BlockService::blockAsDecided() - not every failed login
+ * of the address still stored, which may have led to earlier blocks).
+ *
+ * @param object[] $failedLogins
+ */
+ public function blockedNotifyAdmin($logEntry, array $failedLogins, $maxNumber)
+ {
+ if (!$this->mailsBlocks($maxNumber) ||
!$this->isNotificationAllowed($logEntry->logtime, $maxNumber, true))
{
return;
}
- $body = $this->getBlockedBody($logEntry, $interval);
+ $body = $this->getBlockedBody($logEntry, $failedLogins);
$subject = Text::sprintf('PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT',
$this->getSiteName(),
$logEntry->ipaddress);
diff --git a/library/src/Repository/FailedLoginRepository.php b/library/src/Repository/FailedLoginRepository.php
index 6e3ccb7..c3793fc 100644
--- a/library/src/Repository/FailedLoginRepository.php
+++ b/library/src/Repository/FailedLoginRepository.php
@@ -112,23 +112,30 @@ public function countInLastHour()
}, 0);
}
+ // the most failed logins listUnhandledFromAddress() reads: those which
+ // count towards a block are about the block threshold (at most 25)
+ private const ListLimit = 100;
+
/**
- * The failed logins from $ipaddress in the $minutes up to $time.
- * Fail-open: none.
+ * The failed logins from $ipaddress in the $minutes up to $time which
+ * haven't been handled - those countUnhandledFromAddress() counts -
+ * oldest first, at most ListLimit (the latest). Fail-open: none.
*
* @return object[]
*/
- public function listFromAddress($ipaddress, $time, $minutes)
+ public function listUnhandledFromAddress($minutes, $ipaddress, $time)
{
- return $this->failOpen('listFromAddress', function () use ($ipaddress, $time, $minutes)
+ return $this->failOpen('listUnhandledFromAddress', function () use ($minutes, $ipaddress, $time)
{
$values = array();
$query = $this->windowQuery(self::Table, 'logtime', $time, $minutes, $values)
->clear('select')
- ->select('*')
- ->where($this->db->quoteName('ipaddress').' = :ip');
+ ->select($this->db->quoteName(array('id', 'ipaddress', 'logtime', 'username', 'origin')))
+ ->where($this->db->quoteName('ipaddress').' = :ip')
+ ->where($this->db->quoteName('handled').' = 0')
+ ->order($this->db->quoteName('logtime').' DESC, '.$this->db->quoteName('id').' DESC');
$values['ip'] = (string) $ipaddress;
- return $this->objects($query, $values);
+ return array_reverse($this->objects($query, $values, 0, self::ListLimit));
}, array());
}
diff --git a/library/src/Service/BlockPolicy.php b/library/src/Service/BlockPolicy.php
index 739a4fa..d388d6c 100644
--- a/library/src/Service/BlockPolicy.php
+++ b/library/src/Service/BlockPolicy.php
@@ -100,13 +100,16 @@ public function htaccessPath(): string
* trusted-looking attempt (negative score) gets a higher threshold, a
* suspicious-looking one (positive score) a lower one. Floored at
* riskMinBlockNumber so an extreme score can never reduce this to
- * 0-or-below and effectively instant-block a legitimate user.
+ * 0-or-below and effectively instant-block a legitimate user. The floor
+ * is at most blockNumber: it lowers how far the score may reduce the
+ * threshold, it never raises the threshold of every client (the settings
+ * page refuses such a floor, a value stored otherwise is capped here).
*/
public function effectiveBlockNumber($riskScore): int
{
$blockNumber = $this->intParam('blockNumber');
$reductionPerPoint = $this->intParam('riskBlockNumberReductionPerPoint');
- $minBlockNumber = $this->intParam('riskMinBlockNumber');
+ $minBlockNumber = min($this->intParam('riskMinBlockNumber'), $blockNumber);
$effective = (int) round($blockNumber - $riskScore * $reductionPerPoint);
return max($minBlockNumber, $effective);
}
diff --git a/library/src/Service/BlockService.php b/library/src/Service/BlockService.php
index d604f28..23d00bb 100644
--- a/library/src/Service/BlockService.php
+++ b/library/src/Service/BlockService.php
@@ -65,10 +65,14 @@ public function withLock($key, callable $decision)
*
* @param object $logEntry the failed login which led to the block
* @param string|null $clientAddress see BlockPolicy::decide()
+ * @param bool $listFailedLogins whether to return the failed
+ * logins the block is for (for the administrators'
+ * mail): read before the block marks them handled
* @return array|null id, duration and targetedOtherAccounts of the new
- * block; null if nothing was blocked
+ * block, and failedLogins (empty unless
+ * $listFailedLogins); null if nothing was blocked
*/
- public function blockAsDecided($logEntry, $clientAddress, BlockPolicy $policy)
+ public function blockAsDecided($logEntry, $clientAddress, BlockPolicy $policy, bool $listFailedLogins = false)
{
$logger = $this->repositories->logger();
$decision = $policy->decide($logEntry, $clientAddress);
@@ -81,6 +85,11 @@ public function blockAsDecided($logEntry, $clientAddress, BlockPolicy $policy)
// the file only holds what is still blocked
(new HtaccessHelper($decision['htaccessPath'], $logger))->removeLiftedBlocks($this->repositories->blocks());
}
+ // those the decision counted, see BlockPolicy::attemptsLeft()
+ $failedLogins = $listFailedLogins
+ ? $this->repositories->failedLogins()->listUnhandledFromAddress($policy->checkInterval(),
+ $logEntry->ipaddress, $logEntry->logtime)
+ : array();
$id = $this->block($logEntry, $decision['duration'], $decision['htaccess'], $decision['htaccessPath'],
$decision['htaccessEntry']);
if ($id < 1)
@@ -93,7 +102,7 @@ public function blockAsDecided($logEntry, $clientAddress, BlockPolicy $policy)
}
$logger->log('Inserted IP address '.$logEntry->ipaddress.' into block list', Log::INFO);
return array('id' => $id, 'duration' => $decision['duration'],
- 'targetedOtherAccounts' => $decision['targetedOtherAccounts']);
+ 'targetedOtherAccounts' => $decision['targetedOtherAccounts'], 'failedLogins' => $failedLogins);
}
/**
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 53fd4ea..6ea2d96 100644
--- a/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini
+++ b/plugin/language/ca-ES/ca-ES.plg_system_bfstop.ini
@@ -6,7 +6,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="Adreça IP"
PLG_SYSTEM_BFSTOP_ERROR="Error"
PLG_SYSTEM_BFSTOP_DATETIME="Dia i hora"
PLG_SYSTEM_BFSTOP_ORIGIN="Origen"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="S'ha bloquejat l'adreça IP %1$s perquè hi havia massa intents fallits d'inici de sessió en poc temps a %2$s. Aquests són tots els intents des d'aquesta adreça que s'han registrat:\n\n%3$s\n\nAvís: Aquesta llista pot contenir més entrades que les que han causat el bloqueig actual. Pot contenir intents anteriors que ja van causar un bloqueig temporal aleshores, o intents que estaven massa separats en el temps per causar un bloqueig directe."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="S'ha bloquejat l'adreça IP %1$s perquè hi havia massa intents fallits d'inici de sessió en poc temps a %2$s. Aquests són els intents des d'aquesta adreça que han provocat el bloqueig:\n\n%3$s\n\nNo s'hi inclouen els intents que ja van provocar un bloqueig anterior."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Adreça IP bloquejada %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="La teva adreça IP ha estat bloquejada perquè hi havia massa intents fallits d'ingressar en molt poc temps."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Et resten %d intent(s) d'ingressar abans que la teva adreça IP sigui bloquejada. Si no recordes el nom o contrasenya, pots demanar al sistema que te la torni a enviar"
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 1b396b8..3e15b80 100644
--- a/plugin/language/de-DE/de-DE.plg_system_bfstop.ini
+++ b/plugin/language/de-DE/de-DE.plg_system_bfstop.ini
@@ -4,7 +4,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="IP-Adresse"
PLG_SYSTEM_BFSTOP_ERROR="Fehler"
PLG_SYSTEM_BFSTOP_DATETIME="Zeitpunkt"
PLG_SYSTEM_BFSTOP_ORIGIN="Quelle"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Die IP Adresse %1$s wurde aufgrund zu vieler fehlgeschlagener Login-Versuche auf %2$s gesperrt! Login-Versuche, die von dieser IP-Adresse aufgezeichnet wurden:\n\n%3$s\n\nHinweis: Es könnten mehr Versuche angeführt sein als die, die zur Blockierung beitrugen, wenn es frühere Versuche gab, die z.B. bereits früher eine Blockade ausgelöst haben, oder zu weit auseinander lagen um eine Blockierung zu verursachen!"
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Die IP Adresse %1$s wurde aufgrund zu vieler fehlgeschlagener Login-Versuche auf %2$s gesperrt! Login-Versuche von dieser IP-Adresse, die zur Sperre geführt haben:\n\n%3$s\n\nVersuche, die bereits zu einer früheren Sperre geführt haben, sind nicht angeführt."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: IP-Adresse %s gesperrt"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Deine IP-Addresse wurde aufgrund zu vieler fehlgeschlagener Login-Versuche gesperrt."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Du hast noch %d Versuch(e) bevor deine IP-Adresse blockiert wird!"
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 d14c9b6..a539ac8 100644
--- a/plugin/language/en-GB/en-GB.plg_system_bfstop.ini
+++ b/plugin/language/en-GB/en-GB.plg_system_bfstop.ini
@@ -4,7 +4,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="IP-Address"
PLG_SYSTEM_BFSTOP_ERROR="Error"
PLG_SYSTEM_BFSTOP_DATETIME="Date and time"
PLG_SYSTEM_BFSTOP_ORIGIN="Origin"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Blocked IP Address %1$s because there were too many unsuccessful login attempts in a short time on %2$s. These are all the attempts from that address that were recorded:\n\n%3$s\n\nNotice: This list may hold more entries than the ones causing the current block. The list may contain attempts in the past which already caused a temporary block then, or attempts which were too far apart to cause a direct block."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Blocked IP Address %1$s because there were too many unsuccessful login attempts in a short time on %2$s. These are the attempts from that address which led to the block:\n\n%3$s\n\nAttempts which already led to an earlier block are not listed."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Blocked IP Address %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Your IP address has been blocked because there were too many unsuccessful login attempts in a short time."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="You have %d attempt(s) left before your IP address will be blocked"
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 f405979..cbf0d14 100644
--- a/plugin/language/es-ES/es-ES.plg_system_bfstop.ini
+++ b/plugin/language/es-ES/es-ES.plg_system_bfstop.ini
@@ -6,7 +6,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="IP-Dirección"
PLG_SYSTEM_BFSTOP_ERROR="Error"
PLG_SYSTEM_BFSTOP_DATETIME="Fecha y tiempo"
PLG_SYSTEM_BFSTOP_ORIGIN="Origen"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Se ha bloqueado la dirección IP %1$s porque hubo demasiados intentos fallidos de inicio de sesión en poco tiempo en %2$s. Estos son todos los intentos desde esa dirección que se han registrado:\n\n%3$s\n\nAviso: Esta lista puede contener más entradas que las que causan el bloqueo actual. Puede contener intentos pasados que ya provocaron entonces un bloqueo temporal, o intentos demasiado espaciados en el tiempo para provocar un bloqueo directo."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Se ha bloqueado la dirección IP %1$s porque hubo demasiados intentos fallidos de inicio de sesión en poco tiempo en %2$s. Estos son los intentos desde esa dirección que provocaron el bloqueo:\n\n%3$s\n\nNo se incluyen los intentos que ya provocaron un bloqueo anterior."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Dirección IP bloqueada %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Su dirección IP ha sido bloqueada por demasiadas tentativas fracasadas de entrada al sistema."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Puede intentar (s) %d antes de que su dirección IP sea bloqueada"
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 4115fa6..348ec4f 100644
--- a/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini
+++ b/plugin/language/fr-FR/fr-FR.plg_system_bfstop.ini
@@ -8,7 +8,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="Addresse IP"
PLG_SYSTEM_BFSTOP_ERROR="Erreur"
PLG_SYSTEM_BFSTOP_DATETIME="Date et heure"
PLG_SYSTEM_BFSTOP_ORIGIN="Origine"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="%2$s: Adresse IP %1$s bloquée pour cause de multiples tentatives de connexion sur un court laps de temps. Les tentatives enregistrées à cette adresse sont les suivantes:\n\n%3$s\n\nRemarque: D'autres tentatives de connexions, plus anciennes, ont néanmoins pu également concourir à ce blocage, telles des tentatives de connexion ayant conduit à des blocages temporaires..."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="%2$s: Adresse IP %1$s bloquée pour cause de multiples tentatives de connexion sur un court laps de temps. Voici les tentatives de cette adresse qui ont conduit au blocage :\n\n%3$s\n\nLes tentatives ayant déjà conduit à un blocage antérieur ne sont pas listées."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Addresse IP bloquée %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="En raison de multiples tentatives de connexion, rapprochées dans le temps, votre adresse IP a été bloquée."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Il vous reste %d tentative(s) avant que votre adresse IP ne soit bloquée."
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 1bb4af0..eaed15c 100644
--- a/plugin/language/it-IT/it-IT.plg_system_bfstop.ini
+++ b/plugin/language/it-IT/it-IT.plg_system_bfstop.ini
@@ -4,7 +4,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="Indirizzo-IP"
PLG_SYSTEM_BFSTOP_ERROR="Errore"
PLG_SYSTEM_BFSTOP_DATETIME="Data e ora"
PLG_SYSTEM_BFSTOP_ORIGIN="Origine"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Indirizzo IP Bloccato %1$s perché ci sono stati troppi tentativi di accesso non riusciti in breve tempo su %2$s. Questi sono i tentativi:\n\n%3$s\n\nNota: Questo elenco può contenere più voci rispetto a quelle che hanno causano il blocco attuale. L'elenco può contenere tentativi nel passato che hanno causato già un blocco temporaneo, o tentativi che erano troppo distanti per causare un blocco diretto."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="Indirizzo IP Bloccato %1$s perché ci sono stati troppi tentativi di accesso non riusciti in breve tempo su %2$s. Questi sono i tentativi da quell'indirizzo che hanno causato il blocco:\n\n%3$s\n\nI tentativi che hanno già causato un blocco precedente non sono elencati."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Indirizzo IP Bloccato %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Il tuo indirizzo IP è stato bloccato perché ci sono stati troppi tentativi di accesso non riusciti in breve tempo."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Hai ancora %d tentativo(i) prima che il tuo indirizzo IP venga bloccato"
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 3121d90..739cd74 100644
--- a/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini
+++ b/plugin/language/nl-NL/nl-NL.plg_system_bfstop.ini
@@ -4,7 +4,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="IP-Addres"
PLG_SYSTEM_BFSTOP_ERROR="Fout"
PLG_SYSTEM_BFSTOP_DATETIME="Datum en tijd"
PLG_SYSTEM_BFSTOP_ORIGIN="Oorsprong"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="%2$s: IP-adres %1$s geblokkeerd omdat er te veel mislukte inlogpogingen in een korte tijd zijn geweest. Dit zijn alle inlogpogingen die vanaf dit adres zijn geregistreerd:\n\n%3$s\n\nLet op: Dit overzicht kan uit meer pogingen bestaan dan die recent voor een blokkade hebben gezorgd. Er kunnen namelijk pogingen in het verleden geweest zijn die toen al tot een tijdelijke blokkade hebben geleid, of pogingen die toen qua tijd te ver uit elkaar lagen maar nu wel relevant zijn!"
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="%2$s: IP-adres %1$s geblokkeerd omdat er te veel mislukte inlogpogingen in een korte tijd zijn geweest. Dit zijn de inlogpogingen vanaf dit adres die tot de blokkade hebben geleid:\n\n%3$s\n\nPogingen die al tot een eerdere blokkade hebben geleid, worden niet vermeld."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Geblokkeerd IP adres %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Uw IP-adres is geblokkeerd omdat er te veel mislukte inlogpogingen in een korte tijd geweest zijn."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="U heeft %d poging(en) over voordat uw IP adres geblokkeerd wordt."
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 c33370b..e122138 100644
--- a/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini
+++ b/plugin/language/pt-BR/pt-BR.plg_system_bfstop.ini
@@ -8,7 +8,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="Endereço IP"
PLG_SYSTEM_BFSTOP_ERROR="Erro"
PLG_SYSTEM_BFSTOP_DATETIME="Data e hora"
PLG_SYSTEM_BFSTOP_ORIGIN="Origem"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="O endereço IP %1$s foi bloqueado porque houve muitas tentativas de login sem sucesso em um curto espaço de tempo em %2$s. Estas são todas as tentativas desse endereço que foram registradas:\n\n%3$s\n\nAviso: esta lista pode conter mais entradas do que as que causaram o bloqueio atual. Ela pode conter tentativas antigas que já causaram um bloqueio temporário na época, ou tentativas muito espaçadas no tempo para causar um bloqueio direto."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="O endereço IP %1$s foi bloqueado porque houve muitas tentativas de login sem sucesso em um curto espaço de tempo em %2$s. Estas são as tentativas desse endereço que levaram ao bloqueio:\n\n%3$s\n\nTentativas que já levaram a um bloqueio anterior não são listadas."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Bloqueado o endereço IP %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Seu endereço IP foi bloqueado porque houve muitas tentativas de login sem sucesso em um curto espaço de tempo."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Tem mais %d tentativas(s) antes do seu endereço IP ser bloqueado"
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 999cb84..b09d7a9 100644
--- a/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini
+++ b/plugin/language/pt-PT/pt-PT.plg_system_bfstop.ini
@@ -8,7 +8,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="Endereço IP"
PLG_SYSTEM_BFSTOP_ERROR="Erro"
PLG_SYSTEM_BFSTOP_DATETIME="Data e hora"
PLG_SYSTEM_BFSTOP_ORIGIN="Origem"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="O endereço IP %1$s foi bloqueado porque houve muitas tentativas de início de sessão sem sucesso num curto espaço de tempo em %2$s. Estas são todas as tentativas desse endereço que foram registadas:\n\n%3$s\n\nAviso: esta lista pode conter mais entradas do que as que causaram o bloqueio atual. Ela pode conter tentativas antigas que já causaram um bloqueio temporário na época, ou tentativas muito espaçadas no tempo para causar um bloqueio direto."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="O endereço IP %1$s foi bloqueado porque houve muitas tentativas de início de sessão sem sucesso num curto espaço de tempo em %2$s. Estas são as tentativas desse endereço que levaram ao bloqueio:\n\n%3$s\n\nAs tentativas que já levaram a um bloqueio anterior não são listadas."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: Bloqueado o endereço IP %s"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="O seu endereço IP foi bloqueado porque houve muitas tentativas de início de sessão sem sucesso num curto espaço de tempo."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="Tem mais %d tentativas(s) antes do seu endereço IP ser bloqueado"
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 0f73032..1c3a625 100644
--- a/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini
+++ b/plugin/language/ru-RU/ru-RU.plg_system_bfstop.ini
@@ -4,7 +4,7 @@ PLG_SYSTEM_BFSTOP_IPADDRESS="IP-адрес"
PLG_SYSTEM_BFSTOP_ERROR="Ошибка"
PLG_SYSTEM_BFSTOP_DATETIME="Дата и время"
PLG_SYSTEM_BFSTOP_ORIGIN="Источник"
-PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="IP-адрес %1$s заблокирован, так как с него было слишком много неудачных попыток входа за короткое время на сайте %2$s. Вот все зафиксированные попытки с этого адреса:\n\n%3$s\n\nПримечание: этот список может содержать больше записей, чем те, что вызвали текущую блокировку. В нём могут быть прошлые попытки, которые уже тогда привели к временной блокировке, или попытки, разделённые слишком большими промежутками времени, чтобы вызвать немедленную блокировку."
+PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_BODY="IP-адрес %1$s заблокирован, так как с него было слишком много неудачных попыток входа за короткое время на сайте %2$s. Вот попытки с этого адреса, которые привели к блокировке:\n\n%3$s\n\nПопытки, которые уже привели к более ранней блокировке, не указаны."
PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT="%s: IP адрес %s заблокирован"
PLG_SYSTEM_BFSTOP_BLOCKED_IP_MESSAGE="Ваш IP адрес будет заблокирован, потому что было слишком много неудачных попыток входа в течение короткого времени."
PLG_SYSTEM_BFSTOP_X_ATTEMPTS_LEFT="У Вас осталось %d попытки(а) до того как ваш IP адрес будет заблокирован"
diff --git a/plugin/src/Extension/Bfstop.php b/plugin/src/Extension/Bfstop.php
index 881e6d9..fe5cfea 100644
--- a/plugin/src/Extension/Bfstop.php
+++ b/plugin/src/Extension/Bfstop.php
@@ -278,16 +278,19 @@ public function onUserLoginFailure(LoginFailureEvent $event)
*/
private function block($logEntry)
{
- $block = $this->blocker->withLock($logEntry->ipaddress, function () use ($logEntry)
+ // the administrators' mail lists the failed logins the block is for,
+ // which the block marks handled: read before, if there may be a mail
+ $listFailedLogins = $this->notifier()->mailsBlocks($this->intParam('notifyBlockedNumber'));
+ $block = $this->blocker->withLock($logEntry->ipaddress, function () use ($logEntry, $listFailedLogins)
{
- return $this->blocker->blockAsDecided($logEntry, $this->clientAddress, $this->policy);
+ return $this->blocker->blockAsDecided($logEntry, $this->clientAddress, $this->policy, $listFailedLogins);
});
// the next login of this address sees the block (or the failed logins
// counted) now: it needn't wait for the mails, see LoginTurn
$this->loginTurn->end();
if ($block !== null)
{
- $this->notifyOfBlock($logEntry, $block['id'], $block['duration'], $block['targetedOtherAccounts']);
+ $this->notifyOfBlock($logEntry, $block['id'], $block['targetedOtherAccounts'], $block['failedLogins']);
}
}
@@ -295,10 +298,9 @@ private function block($logEntry)
* The mails about the new block $id (after the lock: sending may take a
* while).
*/
- private function notifyOfBlock($logEntry, $id, $duration, $targetedOtherAccounts)
+ private function notifyOfBlock($logEntry, $id, $targetedOtherAccounts, array $failedLogins)
{
- $this->notifier()->blockedNotifyAdmin($logEntry, BlockPolicy::realDuration($duration),
- $this->intParam('notifyBlockedNumber'));
+ $this->notifier()->blockedNotifyAdmin($logEntry, $failedLogins, $this->intParam('notifyBlockedNumber'));
if (!$this->policy->notifiesBlockedUser())
{
return;
diff --git a/plugin/updatescript.php b/plugin/updatescript.php
index 771ee52..1c22868 100644
--- a/plugin/updatescript.php
+++ b/plugin/updatescript.php
@@ -471,7 +471,7 @@ public static function seedMaintenanceState($db, $time)
*/
public static function canonicalAddress($value)
{
- $value = trim((string) $value);
+ $value = self::unmapped(trim((string) $value));
if (!self::isAddressOrNetwork($value))
{
return null;
@@ -491,6 +491,31 @@ public static function canonicalAddress($value)
return inet_ntop($bin & str_pad($mask, strlen($bin), "\x00")).'/'.$bits;
}
+ /**
+ * An IPv4-mapped IPv6 address or network (::ffff:203.0.113.5,
+ * ::ffff:203.0.113.0/120) as the IPv4 one: IpHelper::unmapped() of the
+ * plugin, see canonicalAddress().
+ */
+ private static function unmapped($value)
+ {
+ $parts = explode('/', $value, 2);
+ $bin = @inet_pton($parts[0]);
+ if ($bin === false || strlen($bin) !== 16 || substr($bin, 0, 12) !== str_repeat("\x00", 10)."\xff\xff")
+ {
+ return $value;
+ }
+ $ipv4 = inet_ntop(substr($bin, 12));
+ if (count($parts) === 1)
+ {
+ return $ipv4;
+ }
+ if (!preg_match('/^[0-9]{1,3}\z/', $parts[1]) || (int) $parts[1] < 96 || (int) $parts[1] > 128)
+ {
+ return $value;
+ }
+ return $ipv4.'/'.((int) $parts[1] - 96);
+ }
+
/**
* Brings the addresses in the block and allow list into canonical form
* (see canonicalAddress()): entries written by earlier versions, or by
diff --git a/tests/Integration/BlockPolicyTest.php b/tests/Integration/BlockPolicyTest.php
index 75bacd4..3f30c36 100644
--- a/tests/Integration/BlockPolicyTest.php
+++ b/tests/Integration/BlockPolicyTest.php
@@ -12,6 +12,7 @@
use Codeling\Library\Bfstop\Repository\BlockRepository;
use Codeling\Library\Bfstop\Repository\Repositories;
use Codeling\Library\Bfstop\Service\BlockPolicy;
+use Codeling\Library\Bfstop\Service\BlockService;
use Codeling\Library\Bfstop\Service\LoginService;
use Codeling\Library\Bfstop\Settings;
use Joomla\CMS\Factory;
@@ -177,6 +178,38 @@ public function testRiskMovesTheNumberOfAllowedAttemptsButNotBelowTheMinimum()
$this->assertSame(10, $this->policy()->effectiveBlockNumber(0), 'the default');
}
+ public function testABlockListsTheFailedLoginsItIsForNotThoseOfEarlierBlocks()
+ {
+ // the administrators' mail lists them: a permanent block isn't for
+ // every failed login of the address still stored
+ $this->failedLogins(4, 2 * 24 * 60, 'old', self::Ip, 1); // handled by an earlier block
+ $this->failedLogins(2, 30, 'eve');
+ $this->failedLogins(1, 10, 'other', '203.0.113.99');
+ $this->failedLogins(1, 2 * 60, 'outside'); // before the check interval
+ $this->failedLogins(1, 0, 'bob');
+ $policy = $this->policy(array('blockDuration' => 0, 'checkInterval' => 60));
+ $block = (new BlockService($this->repos))->blockAsDecided($this->entry(), null, $policy, true);
+ $this->assertNotNull($block);
+ $this->assertSame(array('eve', 'eve', 'bob'), array_column($block['failedLogins'], 'username'));
+ $this->assertSame(0, (int) $this->queryValue("SELECT COUNT(*) FROM #__bfstop_failedlogin WHERE handled=0 AND ipaddress='".
+ self::Ip."' AND username<>'outside'"), 'and the block marked them handled');
+
+ // not read unless asked for (no mail)
+ $this->failedLogins(3, 0, 'bob', '203.0.113.8');
+ $block = (new BlockService($this->repos))->blockAsDecided($this->entry('bob', '203.0.113.8'), null, $policy);
+ $this->assertSame(array(), $block['failedLogins']);
+ }
+
+ public function testTheMinimumNeverRaisesTheThreshold()
+ {
+ // a floor above blockNumber (stored without the settings page, which
+ // refuses it) is capped at blockNumber
+ $policy = $this->policy(array('blockNumber' => 5, 'riskBlockNumberReductionPerPoint' => 1, 'riskMinBlockNumber' => 10));
+ $this->assertSame(5, $policy->effectiveBlockNumber(0));
+ $this->assertSame(5, $policy->effectiveBlockNumber(3));
+ $this->assertSame(8, $policy->effectiveBlockNumber(-3), 'a trustworthy attempt still gets more');
+ }
+
public function testAttemptsLeftCountsTheFailedLoginsOfTheAddressWithinTheInterval()
{
$policy = $this->policy(array('blockNumber' => 5, 'checkInterval' => 60,
diff --git a/tests/Integration/ComponentTest.php b/tests/Integration/ComponentTest.php
index 2879466..687026c 100644
--- a/tests/Integration/ComponentTest.php
+++ b/tests/Integration/ComponentTest.php
@@ -1005,6 +1005,28 @@ public function testUnblockLinksNeedTheLiveSite()
$this->assertIsArray($valid, 'mode 0');
}
+ public function testTheRiskFloorMayNotBeAboveTheThreshold()
+ {
+ // a floor above the threshold would raise it for every client, see
+ // BlockPolicy::effectiveBlockNumber()
+ Factory::getLanguage()->load('com_bfstop', BFSTOP_COMPONENT_ROOT.'/admin');
+ $validate = function ($blockNumber, $minBlockNumber)
+ {
+ $model = $this->model(SettingsModel::class);
+ $valid = $model->validate($this->settingsForm(), array('params' => array('enabledForOrigin' => array('1'),
+ 'blockNumber' => (string) $blockNumber, 'riskMinBlockNumber' => (string) $minBlockNumber)));
+ return array($valid, implode(' ', array_map('strval', $model->getErrors())));
+ };
+ list($valid, $errors) = $validate(5, 10);
+ $this->assertFalse($valid);
+ $this->assertStringContainsString('10', $errors);
+ $this->assertStringNotContainsString('COM_BFSTOP_SETTINGS_RISK_MIN_BLOCK_NUMBER_ABOVE_BLOCK_NUMBER', $errors);
+ list($valid) = $validate(5, 5);
+ $this->assertIsArray($valid, 'the same number');
+ list($valid) = $validate(10, 2);
+ $this->assertIsArray($valid);
+ }
+
public function testSettingsPageProposesTheLiveSite()
{
Factory::getLanguage()->load('com_bfstop', BFSTOP_COMPONENT_ROOT.'/admin');
@@ -1280,6 +1302,75 @@ public function testHtaccessBlocksNeedTheAdminPermission()
}
}
+ /**
+ * Runs the task "unblock" of the .htaccess list for $entries as a user
+ * with $actions; the entries of the file in $dir afterwards.
+ */
+ private function removeHtaccessBlocks($dir, array $entries, array $actions)
+ {
+ $app = Factory::getApplication();
+ $original = $app->getIdentity();
+ $input = $app->getInput();
+ $input->post->set(\Joomla\CMS\Session\Session::getFormToken(), '1');
+ $input->post->set('cid', $entries);
+ try
+ {
+ $app->loadIdentity(self::userWith($actions));
+ // the tests run in the site application: the backend's controller
+ // would look for the site's models
+ $controller = new class(array('base_path' => JPATH_ADMINISTRATOR.'/components/com_bfstop', 'option' => 'com_bfstop'),
+ new MVCFactory('Codeling\\Component\\Bfstop'), $app, $input)
+ extends \Codeling\Component\Bfstop\Administrator\Controller\HtblocklistController
+ {
+ public function getModel($name = 'htblocklist', $prefix = '', $config = array())
+ {
+ return parent::getModel($name, $prefix ?: 'Administrator', $config);
+ }
+ };
+ $controller->unblock();
+ $app->getMessageQueue(true);
+ return (new HtaccessHelper($dir, null))->getDeniedIPs();
+ }
+ finally
+ {
+ $app->loadIdentity($original);
+ $input->post->set('cid', null);
+ }
+ }
+
+ public function testRemovingHtaccessBlocksNeedsTheAdminPermission()
+ {
+ // taking an entry out of the web server's configuration needs what
+ // adding one needs: core.admin, here as well as core.delete
+ $dir = sys_get_temp_dir().'/bfstop-htunblock-admin-'.getmypid();
+ mkdir($dir);
+ $original = $this->getSettings();
+ try
+ {
+ $this->setSettings(json_encode(array('blockMode' => 'htaccess', 'htaccessPath' => $dir)));
+ $this->assertTrue((new HtaccessHelper($dir, null))->denyIP('192.0.2.0/24'));
+ $this->assertSame(array('192.0.2.0/24'),
+ $this->removeHtaccessBlocks($dir, array('192.0.2.0/24'), array('core.manage', 'core.delete')));
+ $this->assertSame(array('192.0.2.0/24'),
+ $this->removeHtaccessBlocks($dir, array('192.0.2.0/24'), array('core.manage', 'core.admin')),
+ 'core.delete is still needed');
+ $this->assertSame(array(),
+ $this->removeHtaccessBlocks($dir, array('192.0.2.0/24'), array('core.manage', 'core.delete', 'core.admin')));
+ // the toolbar offers "Unblock" by the same rule
+ $mayRemove = \Codeling\Component\Bfstop\Administrator\Controller\HtblocklistController::class.'::mayRemove';
+ $this->assertFalse($mayRemove(self::userWith(array('core.manage', 'core.delete'))));
+ $this->assertFalse($mayRemove(self::userWith(array('core.manage', 'core.admin'))));
+ $this->assertTrue($mayRemove(self::userWith(array('core.manage', 'core.delete', 'core.admin'))));
+ $this->assertFalse($mayRemove(null));
+ }
+ finally
+ {
+ $this->setSettings($original);
+ @unlink($dir.'/.htaccess');
+ @rmdir($dir);
+ }
+ }
+
public function testWideNetworkBlocksNeedTheAdminPermission()
{
$controller = new \Codeling\Component\Bfstop\Administrator\Controller\BlockController(
diff --git a/tests/Integration/GeoHelperTest.php b/tests/Integration/GeoHelperTest.php
index ff24a82..4eaf96c 100644
--- a/tests/Integration/GeoHelperTest.php
+++ b/tests/Integration/GeoHelperTest.php
@@ -8,6 +8,7 @@
namespace Codeling\Bfstop\Tests\Integration;
+use Codeling\Bfstop\Tests\Support\MmdbBuilder;
use Codeling\Library\Bfstop\Helper\GeoHelper;
use Joomla\CMS\Log\Log;
@@ -44,6 +45,32 @@ public function testCorruptDbReturnsNullWithWarning()
}
}
+ public function testNetworksAreLookedUpByTheirNetworkAddress()
+ {
+ // the block list links a client tracked by its network (an IPv6
+ // /56, say) to the information page with the network
+ $file = tempnam(sys_get_temp_dir(), 'bfstop-geo');
+ file_put_contents($file, MmdbBuilder::build(array(
+ '203.0.113.0/24' => array('country' => array('iso_code' => 'DE', 'names' => array('en' => 'Germany')),
+ 'city' => array('names' => array('en' => 'Berlin'))),
+ )));
+ try
+ {
+ $details = GeoHelper::getCityDetails($this->logger, $file, '203.0.113.0/24');
+ $this->assertNotNull($details);
+ $this->assertSame('203.0.113.0/24', $details->ip, 'shown as given');
+ $this->assertSame('Berlin', $details->city);
+ $this->assertSame('DE', GeoHelper::getCountryCode($this->logger, $file, '203.0.113.77/25'), 'not masked yet');
+ $this->assertSame('DE', GeoHelper::getCountryCode($this->logger, $file, '::ffff:203.0.113.5'), 'IPv4-mapped');
+ $this->assertNull(GeoHelper::getCountryCode($this->logger, $file, '192.0.2.0/24'));
+ $this->assertFalse($this->logger->hasMessage(Log::WARNING, 'lookup failed'));
+ }
+ finally
+ {
+ unlink($file);
+ }
+ }
+
public function testStreamWrapperPathsAreRefused()
{
foreach (array('phar:///tmp/x.phar/GeoLite2.mmdb', 'file:///etc/GeoLite2.mmdb', 'ftp://example.org/GeoLite2.mmdb') as $path)
diff --git a/tests/Integration/HtaccessHelperTest.php b/tests/Integration/HtaccessHelperTest.php
index 7453e0f..0bb753b 100644
--- a/tests/Integration/HtaccessHelperTest.php
+++ b/tests/Integration/HtaccessHelperTest.php
@@ -501,6 +501,10 @@ public function testAnIpv6ClientsEntryIsItsSlash64()
$this->assertTrue(HtaccessHelper::isEntryOf('2001:db8:1::/56', '2001:db8:1::/56'));
$this->assertTrue(HtaccessHelper::isEntryOf('2001:db8:1:2a::/64', '2001:db8:1::/56'));
$this->assertTrue(HtaccessHelper::isEntryOf('203.0.113.5', '203.0.113.5'));
+ // written by an earlier version for a client the web server reported
+ // IPv4-mapped, whose block is IPv4 now
+ $this->assertTrue(HtaccessHelper::isEntryOf('::ffff:203.0.113.5', '203.0.113.5'));
+ $this->assertFalse(HtaccessHelper::isEntryOf('::ffff:203.0.113.6', '203.0.113.5'));
$this->assertFalse(HtaccessHelper::isEntryOf('2001:db8:2:2a::/64', '2001:db8:1::/56'), 'another network');
$this->assertFalse(HtaccessHelper::isEntryOf('2001:db8:1:2a::/80', '2001:db8:1::/56'), 'no /64: written by hand');
$this->assertFalse(HtaccessHelper::isEntryOf('2001:db8:1:2a::5', '2001:db8:1::/56'));
diff --git a/tests/Integration/InstallerScriptTest.php b/tests/Integration/InstallerScriptTest.php
index a35ec02..6727bf9 100644
--- a/tests/Integration/InstallerScriptTest.php
+++ b/tests/Integration/InstallerScriptTest.php
@@ -254,7 +254,8 @@ public function testTheInstallersSpellingOfAddressesIsThatOfTheLookups()
// loaded), so it has a copy of the canonical form: they must agree
$samples = array('203.0.113.5', '203.0.113.77/24', '203.0.113.0/24', '10.0.0.1/8', '0.0.0.0/0', '1.2.3.4/32',
'2001:DB8::ABCD', '2001:0DB8:0:0:0:0:0:5/64', '2001:db8:1:2::/64', '::1', '::/0', '2001:db8::1/128',
- '2001:db8::1/127', '::ffff:203.0.113.5', ' 203.0.113.5 ', '203.0.113.5/33', '2001:db8::/129',
+ '2001:db8::1/127', '::ffff:203.0.113.5', '::FFFF:CB00:7105', '::ffff:203.0.113.77/120', '::ffff:1.2.3.4/80',
+ '::ffff:1.2.3.4/abc', ' 203.0.113.5 ', '203.0.113.5/33', '2001:db8::/129',
'203.0.113.0/abc', '203.0.113.5/', 'nonsense', '', '1.2.3', '203.0.113.5/24/8', '203.0.113.5/-1');
foreach ($samples as $sample)
{
diff --git a/tests/Integration/IpHelperAddressTest.php b/tests/Integration/IpHelperAddressTest.php
index 856f289..cd56c20 100644
--- a/tests/Integration/IpHelperAddressTest.php
+++ b/tests/Integration/IpHelperAddressTest.php
@@ -75,6 +75,20 @@ public function testProxyDisabledIgnoresHeader()
$this->assertSame('198.51.100.7', IpHelper::getAddress($this->logger));
}
+ public function testIpv4MappedAddressesAreIpv4()
+ {
+ // a web server listening on an IPv6 socket which takes IPv4
+ // connections too reports an IPv4 client as ::ffff:a.b.c.d
+ $this->configure(array('useProxy' => 0));
+ $_SERVER['REMOTE_ADDR'] = '::ffff:203.0.113.5';
+ $this->assertSame('203.0.113.5', IpHelper::getAddress($this->logger));
+ // the proxy as well as the client behind it
+ $this->configure(array('useProxy' => 1, 'proxyIpAddress' => '198.51.100.7'));
+ $_SERVER['REMOTE_ADDR'] = '::ffff:198.51.100.7';
+ $_SERVER['HTTP_X_FORWARDED_FOR'] = '1.2.3.4, ::ffff:203.0.113.6';
+ $this->assertSame('203.0.113.6', IpHelper::getAddress($this->logger));
+ }
+
public function testProxyEnabledButRequestNotFromProxyIgnoresHeader()
{
$this->configure(array('useProxy' => 1, 'proxyIpAddress' => '192.0.2.1'));
diff --git a/tests/Integration/NotifierHelperTest.php b/tests/Integration/NotifierHelperTest.php
index 3e9748a..90572a5 100644
--- a/tests/Integration/NotifierHelperTest.php
+++ b/tests/Integration/NotifierHelperTest.php
@@ -44,7 +44,7 @@ private function mails()
'origin' => 0);
return array(
'failed login body' => $notifier->getFailedLoginBody($entry),
- 'blocked body' => $notifier->getBlockedBody($entry, 60),
+ 'blocked body' => $notifier->getBlockedBody($entry, array($entry)),
'site address' => NotifierHelper::siteAddress(),
);
}
diff --git a/tests/Integration/NotifierMailTest.php b/tests/Integration/NotifierMailTest.php
index 3220630..b77821e 100644
--- a/tests/Integration/NotifierMailTest.php
+++ b/tests/Integration/NotifierMailTest.php
@@ -184,7 +184,9 @@ public function testABlockIsMailedToTheAdministratorsWithTheFailedLoginsWhichCau
$this->blocks(1, 0);
$notifier = $this->notifier('admin@example.org');
$entry = $this->entry();
- $notifier->blockedNotifyAdmin($entry, 60, -1);
+ $failedLogins = (new Repositories($this->logger))->failedLogins()->listUnhandledFromAddress(60, self::Ip,
+ $entry->logtime);
+ $notifier->blockedNotifyAdmin($entry, $failedLogins, -1);
$this->assertCount(1, $notifier->mails);
$mail = $notifier->mails[0];
@@ -192,9 +194,9 @@ public function testABlockIsMailedToTheAdministratorsWithTheFailedLoginsWhichCau
$this->assertSame(Text::sprintf('PLG_SYSTEM_BFSTOP_BLOCKED_IP_ADDRESS_SUBJECT',
$notifier->getSiteName(), self::Ip), $mail['subject']);
$this->assertStringContainsString(self::Ip, $mail['subject']);
- $this->assertSame($notifier->getBlockedBody($entry, 60), $mail['body']);
+ $this->assertSame($notifier->getBlockedBody($entry, $failedLogins), $mail['body']);
// the table of the failed logins: 2 header lines and one line each
- $list = $notifier->failedLoginList(self::Ip, $entry->logtime, 60);
+ $list = $notifier->failedLoginList($failedLogins);
$this->assertSame(3 + 2, substr_count($list, "\n"), "2 header lines + 3 entries:\n".$list);
$this->assertStringContainsString($list, $mail['body'], 'the failed logins of the address are listed');
}
@@ -203,10 +205,10 @@ public function testBlockMailsAreLimited()
{
$this->blocks(3, 5);
$notifier = $this->notifier();
- $notifier->blockedNotifyAdmin($this->entry(), 60, 0);
- $notifier->blockedNotifyAdmin($this->entry(), 60, 2);
+ $notifier->blockedNotifyAdmin($this->entry(), array(), 0);
+ $notifier->blockedNotifyAdmin($this->entry(), array(), 2);
$this->assertSame(array(), $notifier->mails, 'off, and 3 blocks today where 2 are allowed');
- $notifier->blockedNotifyAdmin($this->entry(), 60, 3);
+ $notifier->blockedNotifyAdmin($this->entry(), array(), 3);
$this->assertCount(1, $notifier->mails);
}
@@ -229,7 +231,7 @@ public function testTheAddressOfAChosenUserIsNotified()
$id = $this->createUser('notifyuser');
$notifier = $this->notifier('admin@example.org', $id);
$this->assertSame(array('admin@example.org', 'notifyuser@example.org'), $notifier->getNotifyAddresses());
- $notifier->blockedNotifyAdmin($this->entry(), 60, -1);
+ $notifier->blockedNotifyAdmin($this->entry(), array(), -1);
$this->assertSame(array('admin@example.org', 'notifyuser@example.org'), $notifier->mails[0]['to']);
}
@@ -263,7 +265,7 @@ public function testWithoutAnAddressNothingIsCountedOrMailedOrLoggedAsAnError()
// notifications. Asking sendMail() to mail nobody logged an error with
// every block
$notifier = $this->notifier('');
- $notifier->blockedNotifyAdmin($this->entry(), 60, 5);
+ $notifier->blockedNotifyAdmin($this->entry(), array(), 5);
$notifier->failedLogin($this->entry(), -1);
$this->assertSame(array(), $notifier->mails);
$this->assertSame(array(), $this->logger->errors);
diff --git a/tests/Integration/RepositoriesTest.php b/tests/Integration/RepositoriesTest.php
index bc44907..c62580c 100644
--- a/tests/Integration/RepositoriesTest.php
+++ b/tests/Integration/RepositoriesTest.php
@@ -72,10 +72,16 @@ public function testFailedLoginCounting()
$this->assertSame(4, $this->repos->failedLogins()->countUnhandledFromAddress(180, '203.0.113.5', $now));
$this->assertSame(4, $this->repos->failedLogins()->countUnhandledForUsername(60, 'bob', $now));
$this->assertSame(4, (int) $this->repos->failedLogins()->countInLastHour());
- $list = $this->notifier->failedLoginList('203.0.113.5', $now, 60);
+ $entries = $this->repos->failedLogins()->listUnhandledFromAddress(60, '203.0.113.5', $now);
+ $this->assertCount(3, $entries);
+ $this->assertSame(array('bob', 'bob', 'bob'), array_column($entries, 'username'));
+ $this->assertLessThanOrEqual($entries[1]->logtime, $entries[0]->logtime, 'oldest first');
+ $list = $this->notifier->failedLoginList($entries);
$this->assertSame(3 + 2, substr_count($list, "\n"), "2 header lines + 3 entries:\n".$list);
$this->repos->failedLogins()->markHandled('203.0.113.5', 'bob');
+ $this->assertSame(array(), $this->repos->failedLogins()->listUnhandledFromAddress(60, '203.0.113.5', $now),
+ 'handled');
$this->assertSame(0, $this->repos->failedLogins()->countUnhandledFromAddress(60, '203.0.113.5', $now));
$this->assertSame(1, $this->repos->failedLogins()->countUnhandledForUsername(60, 'bob', $now), 'other IP not handled');
}
@@ -585,7 +591,8 @@ public function testTrimUsernameStatsKeepsTheMostAttackedAndMostRecent()
public function testLineBreaksInUsernamesDoNotForgeLinesInTheMailedList()
{
$this->failedLogin('203.0.113.5', "bob\n[forged] 203.0.113.99", 1);
- $list = $this->notifier->failedLoginList('203.0.113.5', self::minutesAgo(0), 60);
+ $list = $this->notifier->failedLoginList(
+ $this->repos->failedLogins()->listUnhandledFromAddress(60, '203.0.113.5', self::minutesAgo(0)));
// header, separator and the one entry
$this->assertCount(3, array_filter(explode("\n", $list), 'strlen'));
}
diff --git a/tests/Unit/IpHelperTest.php b/tests/Unit/IpHelperTest.php
index e4d5251..6b8e217 100644
--- a/tests/Unit/IpHelperTest.php
+++ b/tests/Unit/IpHelperTest.php
@@ -114,6 +114,47 @@ public function testIsTrustedProxy()
$this->assertFalse(IpHelper::isTrustedProxy('192.0.2.1', array()));
// a malformed entry never matches
$this->assertFalse(IpHelper::isTrustedProxy('192.0.2.1', array('foo', '192.0.2.0/abc')));
+ // IPv4-mapped is IPv4, on either side
+ $this->assertTrue(IpHelper::isTrustedProxy('::ffff:192.0.2.1', $proxies));
+ $this->assertTrue(IpHelper::isTrustedProxy('::ffff:198.51.100.77', $proxies));
+ $this->assertTrue(IpHelper::isTrustedProxy('192.0.2.5', array('::ffff:192.0.2.5')));
+ $this->assertTrue(IpHelper::isTrustedProxy('192.0.2.5', array('::ffff:192.0.2.0/120')));
+ $this->assertFalse(IpHelper::isTrustedProxy('::ffff:192.0.2.2', $proxies));
+ }
+
+ public static function unmappedProvider()
+ {
+ return array(
+ 'IPv4-mapped address' => array('::ffff:203.0.113.5', '203.0.113.5'),
+ 'hexadecimal spelling' => array('::FFFF:CB00:7105', '203.0.113.5'),
+ 'written out' => array('0:0:0:0:0:ffff:203.0.113.5', '203.0.113.5'),
+ 'network' => array('::ffff:203.0.113.0/120', '203.0.113.0/24'),
+ 'network /128' => array('::ffff:203.0.113.5/128', '203.0.113.5/32'),
+ 'network /96' => array('::ffff:0.0.0.0/96', '0.0.0.0/0'),
+ 'wider network stays' => array('::ffff:0.0.0.0/95', '::ffff:0.0.0.0/95'),
+ 'malformed prefix stays' => array('::ffff:203.0.113.0/abc', '::ffff:203.0.113.0/abc'),
+ 'prefix too long stays' => array('::ffff:203.0.113.0/129', '::ffff:203.0.113.0/129'),
+ 'IPv4 stays' => array('203.0.113.5', '203.0.113.5'),
+ 'IPv6 stays' => array('2001:db8::5', '2001:db8::5'),
+ 'IPv4-compatible (deprecated) stays' => array('::203.0.113.5', '::203.0.113.5'),
+ 'NAT64 stays' => array('64:ff9b::203.0.113.5', '64:ff9b::203.0.113.5'),
+ 'garbage stays' => array('not-an-ip', 'not-an-ip'),
+ 'empty' => array('', ''),
+ );
+ }
+
+ #[DataProvider('unmappedProvider')]
+ public function testUnmapped($value, $expected)
+ {
+ $this->assertSame($expected, IpHelper::unmapped($value));
+ }
+
+ public function testIsInSubnetComparesIpv4MappedAsIpv4()
+ {
+ $this->assertTrue(IpHelper::isInSubnet('::ffff:203.0.113.5', '203.0.113.0/24'));
+ $this->assertTrue(IpHelper::isInSubnet('203.0.113.5', '::ffff:203.0.113.0/120'));
+ $this->assertTrue(IpHelper::isInSubnet('::ffff:203.0.113.5', '::ffff:203.0.113.0/120'));
+ $this->assertFalse(IpHelper::isInSubnet('::ffff:203.0.114.5', '203.0.113.0/24'));
}
public static function forwardedHeaderProvider()
@@ -144,6 +185,8 @@ public static function forwardedHeaderProvider()
'Forwarded element without for' => array('HTTP_FORWARDED', 'for=203.0.113.5, proto=https', $proxy, null),
'only trusted proxies' => array('HTTP_X_FORWARDED_FOR', '198.51.100.7, 198.51.100.7', $proxy, null),
'empty header' => array('HTTP_X_FORWARDED_FOR', '', $proxy, null),
+ 'IPv4-mapped client is IPv4' => array('HTTP_X_FORWARDED_FOR', '1.2.3.4, ::ffff:203.0.113.5', $proxy, '203.0.113.5'),
+ 'IPv4-mapped trusted hop' => array('HTTP_X_FORWARDED_FOR', '203.0.113.5, ::ffff:198.51.100.7', $proxy, '203.0.113.5'),
);
}
@@ -201,7 +244,7 @@ public static function trackedAddressProvider()
'128 means per address' => array('2001:db8:1:2::1', 128, '2001:db8:1:2::1'),
'0 means per address' => array('2001:db8:1:2::1', 0, '2001:db8:1:2::1'),
'absurdly short prefix' => array('2001:db8:1:2::1', 16, '2001:db8:1:2::1'),
- 'IPv4-mapped stays' => array('::ffff:192.0.2.7', 64, '::ffff:192.0.2.7'),
+ 'IPv4-mapped is IPv4' => array('::ffff:192.0.2.7', 64, '192.0.2.7'),
'NAT64 stays (canonical form)' => array('64:ff9b::192.0.2.7', 64, '64:ff9b::c000:207'),
'6to4 stays' => array('2002:c000:207::1', 64, '2002:c000:207::1'),
'Teredo stays' => array('2001:0:4136:e378:8000:63bf:3fff:fdd2', 64, '2001:0:4136:e378:8000:63bf:3fff:fdd2'),
@@ -241,7 +284,10 @@ public static function canonicalEntryProvider()
'IPv6 written out' => array('2001:0db8:0000:0000:0000:0000:0000:0001', '2001:db8::1'),
'IPv6 network' => array('2001:DB8:AB:1:2:3:4:5/48', '2001:db8:ab::/48'),
'IPv6 not on a border' => array('2001:db8:1:ff7f::1/56', '2001:db8:1:ff00::/56'),
- 'IPv4-mapped' => array('::FFFF:1.2.3.4', '::ffff:1.2.3.4'),
+ 'IPv4-mapped is IPv4' => array('::FFFF:1.2.3.4', '1.2.3.4'),
+ 'IPv4-mapped network' => array('::ffff:203.0.113.77/120', '203.0.113.0/24'),
+ 'IPv4-mapped /96' => array('::ffff:1.2.3.4/96', '0.0.0.0/0'),
+ 'wider than ::ffff:0:0/96 stays IPv6' => array('::ffff:1.2.3.4/80', '::/80'),
'surrounding space' => array(' 203.0.113.5 ', '203.0.113.5'),
'prefix too long' => array('203.0.113.0/33', null),
'prefix too long (IPv6)' => array('2001:db8::/129', null),
@@ -274,6 +320,9 @@ public function testLookupCandidatesIPv4()
}
$this->assertContains('203.0.113.0/25', $candidates);
$this->assertNotContains('203.0.113.128/25', $candidates);
+ // the client of a server listening on an IPv6 socket: as IPv4
+ $this->assertSame($candidates, IpHelper::lookupCandidates('::ffff:203.0.113.77'));
+ $this->assertSame($candidates, IpHelper::lookupCandidates('::FFFF:CB00:714D'));
}
public function testLookupCandidatesIPv6()
@@ -316,12 +365,13 @@ public function testOverlapsTrustedProxy()
{
$proxies = array('192.0.2.10', '198.51.100.0/24', '2001:db8:aa::/48', 'nonsense');
foreach (array('192.0.2.10', '192.0.2.0/24', '0.0.0.0/0', '198.51.100.77', '198.51.100.0/25',
- '198.51.0.0/16', '2001:db8:aa:1::/64', '2001:db8:aa:1::5', '2001:db8::/32', '2001:DB8:AA::1') as $entry)
+ '198.51.0.0/16', '2001:db8:aa:1::/64', '2001:db8:aa:1::5', '2001:db8::/32', '2001:DB8:AA::1',
+ '::ffff:192.0.2.10', '::ffff:198.51.100.0/120') as $entry)
{
$this->assertTrue(IpHelper::overlapsTrustedProxy($entry, $proxies), $entry);
}
foreach (array('192.0.2.11', '192.0.2.12/31', '198.51.101.0/24', '203.0.113.5', '2001:db8:ab::/48',
- '::ffff:192.0.2.10', 'nonsense', '') as $entry)
+ '::ffff:192.0.2.11', 'nonsense', '') as $entry)
{
$this->assertFalse(IpHelper::overlapsTrustedProxy($entry, $proxies), $entry);
}