You are here

public function PerimeterSubscriber::handleBannedUrls in Drupal Perimeter Defence 8

Same name and namespace in other branches
  1. 2.0.x src/EventSubscriber/PerimeterSubscriber.php \Drupal\perimeter\EventSubscriber\PerimeterSubscriber::handleBannedUrls()

On page not found events, ban the IP if the request is suspicious.

File

src/EventSubscriber/PerimeterSubscriber.php, line 42

Class

PerimeterSubscriber
On page not found events, ban the IP if the request is suspicious.

Namespace

Drupal\perimeter\EventSubscriber

Code

public function handleBannedUrls(Event $event) {
  $exception = $event
    ->getException();
  if ($exception instanceof NotFoundHttpException) {
    $request_path = $event
      ->getRequest()
      ->getPathInfo();
    $bannedPatterns = $this->configFactory
      ->get('perimeter.settings')
      ->get('not_found_exception_patterns');
    foreach ($bannedPatterns as $pattern) {
      $pattern = trim($pattern);
      if (preg_match($pattern, $request_path)) {
        $connection = Database::getConnection();
        $banManager = new BanIpManager($connection);
        $banManager
          ->banIp($event
          ->getRequest()
          ->getClientIp());
        $this->loggerFactory
          ->get('Perimeter')
          ->notice('Banned: %ip for requesting %pattern <br />Source: %source <br /> User Agent: %browser', [
          '%ip' => $event
            ->getRequest()
            ->getClientIp(),
          '%pattern' => Xss::filter($request_path),
          '%source' => isset($_SERVER['HTTP_REFERER']) ? Xss::filter($_SERVER['HTTP_REFERER']) : '',
          '%browser' => isset($_SERVER['HTTP_USER_AGENT']) ? Xss::filter($_SERVER['HTTP_USER_AGENT']) : '',
        ]);
        break;
      }
    }
  }
}