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

namespace App\Http\Middleware;

5
use Cache;
Dominik Hebeler's avatar
Dominik Hebeler committed
6
use Closure;
7
use Cookie;
8
use Log;
Dominik Hebeler's avatar
Dominik Hebeler committed
9
use URL;
Dominik Hebeler's avatar
Dominik Hebeler committed
10
11
12
13
14
15
16
17
18
19

class HumanVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
20
    public function handle($request, Closure $next)
Dominik Hebeler's avatar
Dominik Hebeler committed
21
    {
22
23
24
25
        if ($request->filled("loadMore") && Cache::has($request->input("loadMore"))) {
            return $next($request);
        }

26
27
        // The specific user
        $user = null;
28
        $update = true;
29
        $prefix = "humanverification";
Dominik Hebeler's avatar
Dominik Hebeler committed
30
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
31
32
33
            $ip = $request->ip();
            $id = "";
            $uid = "";
34
35
36
37

            $spamID = \App\Http\Controllers\HumanVerification::couldBeSpammer($ip);
            if (!empty($spamID)) {
                $id = hash("sha1", $spamID);
38
                $uid = hash("sha1", $spamID . $ip . $_SERVER["AGENT"] . "uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
39
            } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
40
41
                $id = hash("sha1", $ip);
                $uid = hash("sha1", $ip . $_SERVER["AGENT"] . "uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
42
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
43
44
45
            unset($_SERVER["AGENT"]);

            /**
46
             * If the user sends a valid key or an appversion
Dominik Hebeler's avatar
Dominik Hebeler committed
47
48
49
50
             * We will not verificate the user.
             * If someone that uses a bot finds this out we
             * might have to change it at some point.
             */
51
52

            //use parameter for middleware to skip this when using associator
53
            if (!config("metager.metager.botprotection.enabled") || app('App\Models\Key')->getStatus()) {
54
55
                $update = false;
                return $next($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
56
            }
57

58
            # Get all Users of this IP
59
            $users = Cache::get($prefix . "." . $id, []);
60
            $users = $this->removeOldUsers($prefix, $users);
61
62

            $user = [];
63
64
            if (empty($users[$uid])) {
                $user = [
65
66
67
68
69
70
                    'uid' => $uid,
                    'id' => $id,
                    'unusedResultPages' => 0,
                    'whitelist' => false,
                    'locked' => false,
                    "lockedKey" => "",
71
                    "expiration" => now()->addWeeks(2),
72
                ];
73
74
75
76
77
78
79
80
            } 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;
81
            foreach ($users as $uidTmp => $userTmp) {
82
83
                if (!$userTmp["whitelist"]) {
                    $sum += $userTmp["unusedResultPages"];
84
                    if ($userTmp["uid"] !== $uid) {
85
86
87
                        $alone = false;
                    }
                }
Dominik Hebeler's avatar
Dominik Hebeler committed
88
            }
89

Dominik Hebeler's avatar
Dominik Hebeler committed
90
91
92
93
94
95
96
97
98
99
100
101
            # 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;
                }
            }
102

103
104
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
105
            }
106

Dominik Hebeler's avatar
Dominik Hebeler committed
107
            # If the user is locked we will force a Captcha validation
108
            if ($user["locked"]) {
109
                \App\Http\Controllers\HumanVerification::logCaptcha($request);
Dominik Hebeler's avatar
Dominik Hebeler committed
110
                return redirect()->route('captcha', ["id" => $id, "uid" => $uid, "url" => url()->full()]);
Dominik Hebeler's avatar
Dominik Hebeler committed
111
            }
112

113
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
114

115
            if ($alone || $user["whitelist"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
116
117
118
119
                # 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
120
                #   50 and then every 25 => Captcha validated Result Pages
Dominik Hebeler's avatar
Dominik Hebeler committed
121
                # If the user shows activity on our result page the counter will be deleted
122
                if ($user["unusedResultPages"] === 50 || ($user["unusedResultPages"] > 50 && $user["unusedResultPages"] % 25 === 0)) {
123
                    $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
124
125
                }
            }
126
            \App\PrometheusExporter::HumanVerificationSuccessfull();
127
128
        } catch (\Exception $e) {
            Log::error($e->getMessage());
129
            \App\PrometheusExporter::HumanVerificationError();
130
        } finally {
131
            if ($update && $user != null) {
132
                if ($user["whitelist"]) {
133
                    $user["expiration"] = now()->addWeeks(2);
134
                } else {
135
                    $user["expiration"] = now()->addHours(72);
136
                }
137
138
139
140
141
                try {
                    $this->setUser($prefix, $user);
                } catch (\Exception $e) {
                    Log::error($e->getMessage());
                }
142
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
143
        }
144

145
        $request->request->add(['verification_id' => $user["uid"], 'verification_count' => $user["unusedResultPages"]]);
Dominik Hebeler's avatar
Dominik Hebeler committed
146
147
        return $next($request);
    }
148
149
150
151
152

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

156
    public function removeOldUsers($prefix, $userList)
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    {
        $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) {
173
            Cache::put($prefix . "." . $user["id"], $newUserlist, 2 * 7 * 24 * 60 * 60);
174
175
176
177
        }

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