From d9f48a19fbbd69003ddc098b611beaa13c6f0d81 Mon Sep 17 00:00:00 2001
From: Dominik Hebeler <dominik@suma-ev.de>
Date: Wed, 20 Jan 2021 16:30:55 +0100
Subject: [PATCH] loggin failed authentication attempts to redis

---
 .../LogFailedAuthenticationAttempt.php        | 54 +++++++++++++++++++
 app/Providers/EventServiceProvider.php        |  4 +-
 2 files changed, 56 insertions(+), 2 deletions(-)
 create mode 100644 app/Listeners/LogFailedAuthenticationAttempt.php

diff --git a/app/Listeners/LogFailedAuthenticationAttempt.php b/app/Listeners/LogFailedAuthenticationAttempt.php
new file mode 100644
index 000000000..5caa848d5
--- /dev/null
+++ b/app/Listeners/LogFailedAuthenticationAttempt.php
@@ -0,0 +1,54 @@
+<?php
+
+namespace App\Listeners;
+
+use Illuminate\Auth\Events\Failed;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Support\Facades\Redis;
+use Illuminate\Support\Facades\Request;
+
+class LogFailedAuthenticationAttempt
+{
+    /**
+     * Create the event listener.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        //
+    }
+
+    /**
+     * Handle the event.
+     *
+     * @param  Failed  $event
+     * @return void
+     */
+    public function handle(Failed $event)
+    {
+        // Authentication failed Let's log the user
+
+        $fail2banEnabled = config("metager.metager.fail2ban_enabled");
+        if(empty($fail2banEnabled) || !$fail2banEnabled || !env("fail2banurl", false) || !env("fail2banuser") || !env("fail2banpassword")){
+            return;
+        }
+
+        // Submit fetch job to worker
+        $mission = [
+                "resulthash" => "captcha",
+                "url" => env("fail2banurl") . "/mgadmin/",
+                "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
+                "username" => env("fail2banuser"),
+                "password" => env("fail2banpassword"),
+                "headers" => [
+                    "ip" => Request::ip()
+                ],
+                "cacheDuration" => 0,
+                "name" => "Captcha",
+            ];
+        $mission = json_encode($mission);
+        Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
+    }
+}
diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php
index a182657e6..040fa827c 100644
--- a/app/Providers/EventServiceProvider.php
+++ b/app/Providers/EventServiceProvider.php
@@ -13,8 +13,8 @@ class EventServiceProvider extends ServiceProvider
      * @var array
      */
     protected $listen = [
-        'App\Events\SomeEvent' => [
-            'App\Listeners\EventListener',
+        'Illuminate\Auth\Events\Failed' => [
+            'App\Listeners\LogFailedAuthenticationAttempt',
         ],
     ];
 
-- 
GitLab