HumanVerification.php 6.44 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;
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');
28 29 30 31 32 33 34 35 36 37 38
        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.
             */
39
            if ($request->filled('password') || $request->filled('key') || Cookie::get('key') !== null || $request->filled('appversion') || !env('BOT_PROTECTION', false)) {
40
                $update = false;
41 42
                return $next($request);
            }
43

44
            # Get all Users of this IP
45 46
            $userList = $redis->smembers($prefix . "." . $id);
            $pipe = $redis->pipeline();
47

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

            $usersData = $pipe->execute();

            $user = [];
            $users = [];
56 57 58
            # Lock out everyone in a Bot network
            # Find out how many requests this IP has made
            $sum = 0;
59
            foreach ($usersData as $index => $userTmp) {
60
                if (empty($userTmp)) {
61 62
                    // This is a key that has been expired and should be deleted
                    $redis->srem($prefix . "." . $id, $userList[$index]);
63
                    continue;
64
                }
65 66 67 68 69 70 71 72 73 74 75 76 77
                $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;
                }
78
                if (!$userNew["whitelist"]) {
79
                    $sum += intval($userTmp["unusedResultPages"]);
80 81
                }

82
            }
83

84 85
            # If this user doesn't have an entry we will create one
            if (empty($user)) {
86
                $user =
87
                    [
88 89 90 91 92 93 94
                    'uid' => $uid,
                    'id' => $id,
                    'unusedResultPages' => 0,
                    'whitelist' => false,
                    'locked' => false,
                    "lockedKey" => "",
                ];
95
            }
96

97 98 99 100 101 102 103 104 105 106 107
            # 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
108

109
            }
110

111
            // Defines if this is the only user using that IP Adress
112
            $alone = true;
113
            foreach ($users as $userTmp) {
114
                if ($userTmp["uid"] != $uid && !$userTmp["whitelist"]) {
115
                    $alone = false;
116 117
                }

118 119 120
            }
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
121
            }
122

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

137
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
138

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

            }
151 152
        } catch (\Predis\Connection\ConnectionException $e) {
            $update = false;
153
        } finally {
154
            if ($update) {
155

Dominik Hebeler's avatar
Dominik Hebeler committed
156
                // Update the user in the database
157
                $pipeline = $redis->pipeline();
158 159 160 161

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

162 163 164 165
                // Expire in two weeks
                $expireLong = 60 * 60 * 24 * 14;
                // Expire in 72h
                $expireShort = 60 * 60 * 72;
166 167

                if ($user["whitelist"]) {
168
                    $pipeline->expire($prefix . "." . $user['uid'], $expireLong);
169
                } else {
170
                    $pipeline->expire($prefix . "." . $user['uid'], $expireShort);
171
                }
172

173
                $pipeline->expire($prefix . "." . $user["id"], $expireLong);
174 175

                $pipeline->execute();
176
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
177
        }
178

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

Dominik Hebeler's avatar
Dominik Hebeler committed
182 183
    }
}