HumanVerification.php 6.31 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 Illuminate\Http\Response;
8
use Illuminate\Support\Facades\Redis;
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
        // The specific user
        $user = null;
24
        $update = true;
25
        $prefix = "humanverification";
Dominik Hebeler's avatar
Dominik Hebeler committed
26
27
28
29
30
31
32
33
34
35
36
        try {
            $id = hash("sha512", $request->ip());
            $uid = hash("sha512", $request->ip() . $_SERVER["AGENT"]);
            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.
             */
Dominik Hebeler's avatar
Dominik Hebeler committed
37
            if ($request->filled('password') || $request->filled('key') || $request->filled('appversion') || !env('BOT_PROTECTION', false)) {
38
                $update = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
39
40
                return $next($request);
            }
41

42
43
44
            # Get all Users of this IP
            $userList = Redis::smembers($prefix . "." . $id);
            $pipe = Redis::pipeline();
45

46
47
48
49
50
51
52
53
            foreach ($userList as $userid) {
                $pipe->hgetall($prefix . "." . $userid);
            }

            $usersData = $pipe->execute();

            $user = [];
            $users = [];
54
55
56
            # Lock out everyone in a Bot network
            # Find out how many requests this IP has made
            $sum = 0;
57
58
59
            foreach ($usersData as $userTmp) {
                if (empty($userTmp)) {
                    continue;
60
                }
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
                $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;
                }
                if ($userNew["whitelist"]) {
                    $sum += intval($userTmp["unusedResultPages"]);
76
77
                }

78
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
79

80
81
            # If this user doesn't have an entry we will create one
            if (empty($user)) {
82
                $user =
Dominik Hebeler's avatar
Dominik Hebeler committed
83
                    [
84
85
86
87
88
89
90
                    'uid' => $uid,
                    'id' => $id,
                    'unusedResultPages' => 0,
                    'whitelist' => false,
                    'locked' => false,
                    "lockedKey" => "",
                ];
Dominik Hebeler's avatar
Dominik Hebeler committed
91
            }
92

Dominik Hebeler's avatar
Dominik Hebeler committed
93
94
95
96
97
98
99
100
101
102
103
            # 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
104

Dominik Hebeler's avatar
Dominik Hebeler committed
105
            }
106

Dominik Hebeler's avatar
Dominik Hebeler committed
107
            // Defines if this is the only user using that IP Adress
108
            $alone = true;
109
            foreach ($users as $userTmp) {
110
                if ($userTmp["uid"] != $uid && !$userTmp["whitelist"]) {
111
                    $alone = false;
112
113
                }

114
115
116
            }
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
117
            }
118

Dominik Hebeler's avatar
Dominik Hebeler committed
119
            # If the user is locked we will force a Captcha validation
120
            if ($user["locked"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
121
                $captcha = Captcha::create("default", true);
122
                $user["lockedKey"] = $captcha["key"];
Dominik Hebeler's avatar
Dominik Hebeler committed
123
124
125
126
127
128
129
130
131
                return
                new Response(
                    view('humanverification.captcha')
                        ->with('title', "Bestätigung erforderlich")
                        ->with('id', $uid)
                        ->with('url', url()->full())
                        ->with('image', $captcha["img"])
                );
            }
132

133
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
134

135
            if ($alone || $user["whitelist"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
136
137
138
139
                # 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
140
                #   50 and then every 25 => Captcha validated Result Pages
Dominik Hebeler's avatar
Dominik Hebeler committed
141
                # If the user shows activity on our result page the counter will be deleted
142
                if ($user["unusedResultPages"] === 50 || ($user["unusedResultPages"] > 50 && $user["unusedResultPages"] % 25 === 0)) {
143
                    $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
144
145
146
                }

            }
147
148
        } catch (\Predis\Connection\ConnectionException $e) {
            $update = false;
149
        } finally {
150
            if ($update) {
151

Dominik Hebeler's avatar
Dominik Hebeler committed
152
                // Update the user in the database
153
154
155
156
157
158
159
160
161
162
163
                $pipeline = Redis::pipeline();

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

                $expireDate = now();
                $expireDateLong = date_add($expireDate, date_interval_create_from_date_string('2 weeks'))->timestamp;
                $expireDateShort = date_add($expireDate, date_interval_create_from_date_string('2 weeks'))->timestamp;

                if ($user["whitelist"]) {
                    $pipeline->expireat($prefix . "." . $user['uid'], $expireDateLong);
164
                } else {
165
                    $pipeline->expireat($prefix . "." . $user['uid'], $expireDateShort);
166
                }
167
168
169
170

                $pipeline->expireat($prefix . "." . $user["id"], $expireDateLong);

                $pipeline->execute();
171
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
172
        }
173

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

Dominik Hebeler's avatar
Dominik Hebeler committed
177
178
    }
}