HumanVerification.php 6.29 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
1
2
3
4
<?php

namespace App\Http\Middleware;

5
use Cache;
6
use Captcha;
Dominik Hebeler's avatar
Dominik Hebeler committed
7
use Closure;
8
use Cookie;
9
use Illuminate\Http\Response;
10
use Log;
Dominik Hebeler's avatar
Dominik Hebeler committed
11
use URL;
Dominik Hebeler's avatar
Dominik Hebeler committed
12
13
14
15
16
17
18
19
20
21
22
23

class HumanVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
24
25
        // The specific user
        $user = null;
26
        $update = true;
27
        $prefix = "humanverification";
Dominik Hebeler's avatar
Dominik Hebeler committed
28
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
29
30
31
            $ip = $request->ip();
            $id = "";
            $uid = "";
Dominik Hebeler's avatar
Bugfix    
Dominik Hebeler committed
32
            if (\App\Http\Controllers\HumanVerification::couldBeSpammer($ip)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
33
34
35
36
37
38
                $id = hash("sha512", "999.999.999.999");
                $uid = hash("sha512", "999.999.999.999" . $ip . $_SERVER["AGENT"] . "uid");
            } else {
                $id = hash("sha512", $ip);
                $uid = hash("sha512", $ip . $_SERVER["AGENT"] . "uid");
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
39
40
41
42
43
44
45
46
            unset($_SERVER["AGENT"]);

            /**
             * If the user sends a Password or a key
             * We will not verificate the user.
             * If someone that uses a bot finds this out we
             * might have to change it at some point.
             */
47
            if ($request->filled('password') || $request->filled('key') || Cookie::get('key') !== null || $request->filled('appversion') || !env('BOT_PROTECTION', false)) {
48
                $update = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
49
50
                return $next($request);
            }
51

52
            # Get all Users of this IP
53
            $users = Cache::get($prefix . "." . $id, []);
54
            $users = $this->removeOldUsers($prefix, $users);
55
56

            $user = [];
57
58
            if (empty($users[$uid])) {
                $user = [
59
60
61
62
63
64
                    'uid' => $uid,
                    'id' => $id,
                    'unusedResultPages' => 0,
                    'whitelist' => false,
                    'locked' => false,
                    "lockedKey" => "",
65
                    "expiration" => now()->addWeeks(2),
66
                ];
67
68
69
70
71
72
73
74
            } else {
                $user = $users[$uid];
            }
            # Lock out everyone in a Bot network
            # Find out how many requests this IP has made
            $sum = 0;
            // Defines if this is the only user using that IP Adress
            $alone = true;
75
            foreach ($users as $uidTmp => $userTmp) {
76
77
                if (!$userTmp["whitelist"]) {
                    $sum += $userTmp["unusedResultPages"];
78
                    if ($userTmp["uid"] !== $uid) {
79
80
81
                        $alone = false;
                    }
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
82
            }
83

Dominik Hebeler's avatar
Dominik Hebeler committed
84
85
86
87
88
89
90
91
92
93
94
            # A lot of automated requests are from websites that redirect users to our result page.
            # We will detect those requests and put a captcha
            $referer = URL::previous();
            # Just the URL-Parameter
            $refererLock = false;
            if (stripos($referer, "?") !== false) {
                $referer = substr($referer, stripos($referer, "?") + 1);
                $referer = urldecode($referer);
                if (preg_match("/http[s]{0,1}:\/\/metager\.de\/meta\/meta.ger3\?.*?eingabe=([\w\d]+\.){1,2}[\w\d]+/si", $referer) === 1) {
                    $refererLock = true;
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
95

Dominik Hebeler's avatar
Dominik Hebeler committed
96
            }
97

98
99
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
100
            }
101

Dominik Hebeler's avatar
Dominik Hebeler committed
102
            # If the user is locked we will force a Captcha validation
103
            if ($user["locked"]) {
104
                sleep(\random_int(1, 8));
Dominik Hebeler's avatar
Dominik Hebeler committed
105
                $captcha = Captcha::create("default", true);
106
                $user["lockedKey"] = $captcha["key"];
107
                \App\PrometheusExporter::CaptchaShown();
Dominik Hebeler's avatar
Dominik Hebeler committed
108
109
110
111
                return
                new Response(
                    view('humanverification.captcha')
                        ->with('title', "Bestätigung erforderlich")
112
113
                        ->with('uid', $uid)
                        ->with('id', $id)
Dominik Hebeler's avatar
Dominik Hebeler committed
114
115
116
117
                        ->with('url', url()->full())
                        ->with('image', $captcha["img"])
                );
            }
118

119
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
120

121
            if ($alone || $user["whitelist"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
122
123
124
125
                # This IP doesn't need verification yet
                # The user currently isn't locked

                # We have different security gates:
Dominik Hebeler's avatar
Dominik Hebeler committed
126
                #   50 and then every 25 => Captcha validated Result Pages
Dominik Hebeler's avatar
Dominik Hebeler committed
127
                # If the user shows activity on our result page the counter will be deleted
128
                if ($user["unusedResultPages"] === 50 || ($user["unusedResultPages"] > 50 && $user["unusedResultPages"] % 25 === 0)) {
129
                    $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
130
131
132
                }

            }
133
134
        } catch (\Exception $e) {
            Log::error($e->getMessage());
135
        } finally {
136
            if ($update && $user != null) {
137
                if ($user["whitelist"]) {
138
                    $user["expiration"] = now()->addWeeks(2);
139
                } else {
140
                    $user["expiration"] = now()->addHours(72);
141
                }
142
143
144
145
146
147
                try {
                    $this->setUser($prefix, $user);
                    \App\PrometheusExporter::HumanVerificationSuccessfull();
                } catch (\Exception $e) {
                    Log::error($e->getMessage());
                }
148
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
149
        }
150

151
        $request->request->add(['verification_id' => $user["uid"], 'verification_count' => $user["unusedResultPages"]]);
Dominik Hebeler's avatar
Dominik Hebeler committed
152
        return $next($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
153

Dominik Hebeler's avatar
Dominik Hebeler committed
154
    }
155
156
157
158
159

    public function setUser($prefix, $user)
    {
        $userList = Cache::get($prefix . "." . $user["id"], []);
        $userList[$user["uid"]] = $user;
160
        Cache::put($prefix . "." . $user["id"], $userList, 2 * 7 * 24 * 60 * 60);
161
162
    }

163
    public function removeOldUsers($prefix, $userList)
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    {
        $newUserlist = [];
        $now = now();

        $id = "";
        $changed = false;
        foreach ($userList as $uid => $user) {
            $id = $user["id"];
            if ($now < $user["expiration"]) {
                $newUserlist[$user["uid"]] = $user;
            } else {
                $changed = true;
            }
        }

        if ($changed) {
180
            Cache::put($prefix . "." . $user["id"], $newUserlist, 2 * 7 * 24 * 60 * 60);
181
182
183
184
        }

        return $newUserlist;
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
185
}