Symfony 中的自动 block/ban 暴力扫描器

Auto block/ban brute force scanners in Symfony

我是运行一个基于Symfony 2.7的网页。该页面使用 FOSUserBundle 进行用户管理和身份验证。

我可以在日志文件中观察到,该页面 "attacked" 经常被暴力扫描器攻击。

有两种类型的扫描:

  1. 正在搜索已知漏洞,例如导致 HTTP 404 响应
  2. 的 WordPress 文件等
  3. 使用默认用户凭据的登录尝试

我以前一直在使用 WordPress。有很多插件和工具可以自动识别和处理此类攻击:如果 404 请求或拒绝登录尝试达到一定阈值,user/ip 会自动被阻止一段时间。通常几分钟后 user/ip 会自动从阻止列表中删除。

我没能为 Symfony 找到这样的解决方案。有没有将这些功能集成到 Symfony 中的包?

当然我自己实现这个功能也不会太难。但是重新发明已经存在的东西是没有意义的。

如果你想阻止恶意 IP,你真的应该研究 fail2banThis blogs 完美解释:

创建身份验证失败处理程序

<?php

namespace Your\ExampleBundle\EventHandler;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;

class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler
{
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if (null !== $this->logger && null !== $request->getClientIp()) {
            $this->logger->error(sprintf('Authentication failure for IP: %s', $request->getClientIp()));
        }

        return parent::onAuthenticationFailure($request, $exception);
    }
}

将其添加到您的配置中:

services:
    your.examplebundle.authenticationfailurehandler:
        class: Your\ExampleBundle\EventHandler\AuthenticationFailureHandler
        arguments: ["@http_kernel", "@security.http_utils", {}, "@logger"]
        tags:
            - { name: 'monolog.logger', channel: 'security' }

# app/config/security.yml
    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_provider: form.csrf_provider
                failure_handler: your.examplebundle.authenticationfailurehandler
            logout:       true
            anonymous:    true

为 Symfony2 创建自定义 fail2ban 过滤器

要为 fail2ban 创建一个新过滤器,我们将在 /etc/fail2ban/filter.d/symfony.conf 中创建一个包含以下内容的文件:

[Definition]
failregex = Authentication\sfailure\sfor\sIP:\s<HOST>\s

这很简单,对吧?我们应该在 /etc/fail2ban/jail.local 中创建一个监狱,它使用我们的新过滤器。这个监狱的定义将取决于您的配置,但基本的定义可能如下所示:

[symfony]
enabled   = true
filter    = symfony
logpath   = /var/www/my-project/app/logs/prod.log
port      = http,https
bantime   = 600
banaction = iptables-multiport
maxretry  = 3