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

namespace App\Http\Middleware;

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

class HumanVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
23
24
        // The specific user
        $user = null;
25
        $update = true;
26
        $prefix = "humanverification";
27
        $redis = Redis::connection('redisCache');
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
54
            $userList = $redis->smembers($prefix . "." . $id);
            $pipe = $redis->pipeline();
55

56
57
58
59
60
61
62
63
            foreach ($userList as $userid) {
                $pipe->hgetall($prefix . "." . $userid);
            }

            $usersData = $pipe->execute();

            $user = [];
            $users = [];
64
65
66
            # Lock out everyone in a Bot network
            # Find out how many requests this IP has made
            $sum = 0;
67
            foreach ($usersData as $index => $userTmp) {
68
                if (empty($userTmp)) {
69
70
                    // This is a key that has been expired and should be deleted
                    $redis->srem($prefix . "." . $id, $userList[$index]);
71
                    continue;
72
                }
73
74
75
76
77
78
79
80
81
82
83
84
85
                $userNew = ['uid' => $userTmp["uid"],
                    'id' => $userTmp["id"],
                    'unusedResultPages' => intval($userTmp["unusedResultPages"]),
                    'whitelist' => filter_var($userTmp["whitelist"], FILTER_VALIDATE_BOOLEAN),
                    'locked' => filter_var($userTmp["locked"], FILTER_VALIDATE_BOOLEAN),
                    "lockedKey" => $userTmp["lockedKey"],
                ];

                if ($uid === $userTmp["uid"]) {
                    $user = $userNew;
                } else {
                    $users[] = $userNew;
                }
86
                if (!$userNew["whitelist"]) {
87
                    $sum += intval($userTmp["unusedResultPages"]);
88
89
                }

90
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
91

92
93
            # If this user doesn't have an entry we will create one
            if (empty($user)) {
94
                $user =
Dominik Hebeler's avatar
Dominik Hebeler committed
95
                    [
96
97
98
99
100
101
102
                    'uid' => $uid,
                    'id' => $id,
                    'unusedResultPages' => 0,
                    'whitelist' => false,
                    'locked' => false,
                    "lockedKey" => "",
                ];
Dominik Hebeler's avatar
Dominik Hebeler committed
103
            }
104

Dominik Hebeler's avatar
Dominik Hebeler committed
105
106
107
108
109
110
111
112
113
114
115
            # 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
116

Dominik Hebeler's avatar
Dominik Hebeler committed
117
            }
118

Dominik Hebeler's avatar
Dominik Hebeler committed
119
            // Defines if this is the only user using that IP Adress
120
            $alone = true;
121
            foreach ($users as $userTmp) {
122
                if ($userTmp["uid"] != $uid && !$userTmp["whitelist"]) {
123
                    $alone = false;
124
125
                }

126
127
128
            }
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
129
            }
130

Dominik Hebeler's avatar
Dominik Hebeler committed
131
            # If the user is locked we will force a Captcha validation
132
            if ($user["locked"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
133
                $captcha = Captcha::create("default", true);
134
                $user["lockedKey"] = $captcha["key"];
Dominik Hebeler's avatar
Dominik Hebeler committed
135
136
137
138
139
140
141
142
143
                return
                new Response(
                    view('humanverification.captcha')
                        ->with('title', "Bestätigung erforderlich")
                        ->with('id', $uid)
                        ->with('url', url()->full())
                        ->with('image', $captcha["img"])
                );
            }
144

145
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
146

147
            if ($alone || $user["whitelist"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
148
149
150
151
                # 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
152
                #   50 and then every 25 => Captcha validated Result Pages
Dominik Hebeler's avatar
Dominik Hebeler committed
153
                # If the user shows activity on our result page the counter will be deleted
154
                if ($user["unusedResultPages"] === 50 || ($user["unusedResultPages"] > 50 && $user["unusedResultPages"] % 25 === 0)) {
155
                    $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
156
157
158
                }

            }
159
160
        } catch (\Predis\Connection\ConnectionException $e) {
            $update = false;
161
        } finally {
162
            if ($update) {
163

Dominik Hebeler's avatar
Dominik Hebeler committed
164
                // Update the user in the database
165
                $pipeline = $redis->pipeline();
166
167
168
169

                $pipeline->hmset($prefix . "." . $user['uid'], $user);
                $pipeline->sadd($prefix . "." . $user["id"], $user["uid"]);

170
171
172
173
                // Expire in two weeks
                $expireLong = 60 * 60 * 24 * 14;
                // Expire in 72h
                $expireShort = 60 * 60 * 72;
174
175

                if ($user["whitelist"]) {
176
                    $pipeline->expire($prefix . "." . $user['uid'], $expireLong);
177
                } else {
178
                    $pipeline->expire($prefix . "." . $user['uid'], $expireShort);
179
                }
180

181
                $pipeline->expire($prefix . "." . $user["id"], $expireLong);
182
183

                $pipeline->execute();
184
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
185
        }
186

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

Dominik Hebeler's avatar
Dominik Hebeler committed
190
191
    }
}