如果您想阻止恶意 IP,您应该真正研究fail2ban
. 这个博客完美地解释了它:
创建身份验证失败处理程序
<?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