HumanVerification.php 5.91 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
20
21

class HumanVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
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 = "";
Dominik Hebeler's avatar
Bugfix    
Dominik Hebeler committed
34
            if (\App\Http\Controllers\HumanVerification::couldBeSpammer($ip)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
35
                $id = hash("sha1", "999.999.999.999");
36
                $uid = hash("sha1", "999.999.999.999uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
37
            } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
38
39
                $id = hash("sha1", $ip);
                $uid = hash("sha1", $ip . $_SERVER["AGENT"] . "uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
40
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
41
42
43
            unset($_SERVER["AGENT"]);

            /**
44
             * If the user sends a valid key or an appversion
Dominik Hebeler's avatar
Dominik Hebeler committed
45
46
47
48
             * We will not verificate the user.
             * If someone that uses a bot finds this out we
             * might have to change it at some point.
             */
49
            if (!env('BOT_PROTECTION', false) || app('App\Models\Key')->getStatus()) {
50
                $update = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
51
52
                return $next($request);
            }
53

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
86
87
88
89
90
91
92
93
94
95
96
            # 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
97

Dominik Hebeler's avatar
Dominik Hebeler committed
98
            }
99

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

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

110
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
111

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
145
    }
146
147
148
149
150

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

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

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