HumanVerification.php 5.81 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
        // The specific user
        $user = null;
24
        $update = true;
25
        $prefix = "humanverification";
Dominik Hebeler's avatar
Dominik Hebeler committed
26
        try {
Dominik Hebeler's avatar
Dominik Hebeler committed
27 28 29
            $ip = $request->ip();
            $id = "";
            $uid = "";
Dominik Hebeler's avatar
Bugfix  
Dominik Hebeler committed
30
            if (\App\Http\Controllers\HumanVerification::couldBeSpammer($ip)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
31 32
                $id = hash("sha1", "999.999.999.999");
                $uid = hash("sha1", "999.999.999.999" . $ip . $_SERVER["AGENT"] . "uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
33
            } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
34 35
                $id = hash("sha1", $ip);
                $uid = hash("sha1", $ip . $_SERVER["AGENT"] . "uid");
Dominik Hebeler's avatar
Dominik Hebeler committed
36
            }
Dominik Hebeler's avatar
Dominik Hebeler committed
37 38 39 40 41 42 43 44
            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.
             */
45
            if ($request->filled('password') || $request->filled('key') || Cookie::get('key') !== null || $request->filled('appversion') || !env('BOT_PROTECTION', false)) {
46
                $update = false;
Dominik Hebeler's avatar
Dominik Hebeler committed
47 48
                return $next($request);
            }
49

50
            # Get all Users of this IP
51
            $users = Cache::get($prefix . "." . $id, []);
52
            $users = $this->removeOldUsers($prefix, $users);
53 54

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

Dominik Hebeler's avatar
Dominik Hebeler committed
82 83 84 85 86 87 88 89 90 91 92
            # 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
93

Dominik Hebeler's avatar
Dominik Hebeler committed
94
            }
95

96 97
            if ((!$alone && $sum >= 50 && !$user["whitelist"]) || $refererLock) {
                $user["locked"] = true;
Dominik Hebeler's avatar
Dominik Hebeler committed
98
            }
99

Dominik Hebeler's avatar
Dominik Hebeler committed
100
            # If the user is locked we will force a Captcha validation
101
            if ($user["locked"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
102
                return redirect()->route('captcha', ["id" => $id, "uid" => $uid, "url" => url()->full()]);
Dominik Hebeler's avatar
Dominik Hebeler committed
103
            }
104

105
            $user["unusedResultPages"]++;
Dominik Hebeler's avatar
Dominik Hebeler committed
106

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

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

Dominik Hebeler's avatar
Dominik Hebeler committed
140
    }
141 142 143 144 145

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

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

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