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

namespace App\Http\Controllers;

5
6
7
use Captcha;
use Carbon;
use Illuminate\Hashing\BcryptHasher as Hasher;
Dominik Hebeler's avatar
Dominik Hebeler committed
8
use Illuminate\Http\Request;
9
use Illuminate\Support\Facades\Redis;
Dominik Hebeler's avatar
Dominik Hebeler committed
10
11
12
13
use Input;

class HumanVerification extends Controller
{
14
    const PREFIX = "humanverification";
15
16
    const EXPIRELONG = 60 * 60 * 24 * 14;
    const EXPIRESHORT = 60 * 60 * 72;
17

18
19
    public static function captcha(Request $request, Hasher $hasher, $id, $url = null)
    {
20
        $redis = Redis::connection('redisCache');
21

22
23
24
25
26
        if ($url != null) {
            $url = base64_decode(str_replace("<<SLASH>>", "/", $url));
        } else {
            $url = $request->input('url');
        }
Dominik Hebeler's avatar
Dominik Hebeler committed
27

28
29
        if ($request->getMethod() == 'POST') {

30
            $user = $redis->hgetall(HumanVerification::PREFIX . "." . $id);
31
32
33
34
35
36
37
38
39
            $user = ['uid' => $user["uid"],
                'id' => $user["id"],
                'unusedResultPages' => intval($user["unusedResultPages"]),
                'whitelist' => filter_var($user["whitelist"], FILTER_VALIDATE_BOOLEAN),
                'locked' => filter_var($user["locked"], FILTER_VALIDATE_BOOLEAN),
                "lockedKey" => $user["lockedKey"],
            ];

            $lockedKey = $user["lockedKey"];
40
41
            $key = $request->input('captcha');
            $key = strtolower($key);
42

43
44
            if (!$hasher->check($key, $lockedKey)) {
                $captcha = Captcha::create("default", true);
45
46
47
48
                $pipeline = $redis->pipeline();
                $pipeline->hset(HumanVerification::PREFIX . "." . $id, 'lockedKey', $captcha["key"]);
                $pipeline->expire(HumanVerification::PREFIX . "." . $id, $user["whitelist"] ? HumanVerification::EXPIRELONG : HumanVerification::EXPIRESHORT);
                $pipeline->execute();
49
                return view('humanverification.captcha')->with('title', 'Bestätigung notwendig')
50
51
52
                    ->with('id', $id)
                    ->with('url', $url)
                    ->with('image', $captcha["img"])
Dominik Hebeler's avatar
Dominik Hebeler committed
53
                    ->with('errorMessage', 'Fehler: Falsches Captcha eingegeben!');
54
55
            } else {
                # If we can unlock the Account of this user we will redirect him to the result page
56
                if ($user !== null && $user["locked"]) {
Dominik Hebeler's avatar
Dominik Hebeler committed
57
                    # The Captcha was correct. We can remove the key from the user
58
59
60
61
62
63
64
                    # If the sum of all users with that ip is too high we need to whitelist the user or they will receive a captcha again on the next request
                    $sum = 0;
                    $users = [];
                    $pipeline = $redis->pipeline();
                    $pipeline->hmset(HumanVerification::PREFIX . "." . $id, ['locked' => "0", 'lockedKey' => "", 'whitelist' => '1']);
                    $pipeline->expire(HumanVerification::PREFIX . "." . $id, $user["whitelist"] ? HumanVerification::EXPIRELONG : HumanVerification::EXPIRESHORT);
                    $pipeline->execute();
Dominik Hebeler's avatar
Dominik Hebeler committed
65
                    return redirect($url);
66
                } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
67
68
69
70
                    return redirect('/');
                }
            }
        }
71
        $captcha = Captcha::create("default", true);
72
73
74
75
        $pipeline = $redis->pipeline();
        $pipeline->hset(HumanVerification::PREFIX . "." . $id, 'lockedKey', $captcha["key"]);
        $pipeline->expire(HumanVerification::PREFIX . "." . $id, $user["whitelist"] ? HumanVerification::EXPIRELONG : HumanVerification::EXPIRESHORT);
        $pipeline->execute();
76
        return view('humanverification.captcha')->with('title', 'Bestätigung notwendig')
77
78
79
            ->with('id', $id)
            ->with('url', $url)
            ->with('image', $captcha["img"]);
Dominik Hebeler's avatar
Dominik Hebeler committed
80

Dominik Hebeler's avatar
Dominik Hebeler committed
81
82
    }

83
84
85
    public static function remove(Request $request)
    {
        if (!$request->has('mm')) {
Dominik Hebeler's avatar
Dominik Hebeler committed
86
87
            abort(404, "Keine Katze gefunden.");
        }
88

89
        if (HumanVerification::checkId($request, $request->input('mm'))) {
90
            HumanVerification::removeUser($request, $request->input('mm'));
Dominik Hebeler's avatar
Dominik Hebeler committed
91
92
93
94
95
        }
        return response(hex2bin('89504e470d0a1a0a0000000d494844520000000100000001010300000025db56ca00000003504c5445000000a77a3dda0000000174524e530040e6d8660000000a4944415408d76360000000020001e221bc330000000049454e44ae426082'), 200)
            ->header('Content-Type', 'image/png');
    }

96
97
98
    public static function removeGet(Request $request, $mm, $password, $url)
    {
        $url = base64_decode(str_replace("<<SLASH>>", "/", $url));
Dominik Hebeler's avatar
Dominik Hebeler committed
99
100
101

        # If the user is correct and the password is we will delete any entry in the database
        $requiredPass = md5($mm . Carbon::NOW()->day . $url . env("PROXY_PASSWORD"));
102
        if (HumanVerification::checkId($request, $mm) && $requiredPass === $password) {
103
            HumanVerification::removeUser($request, $mm);
Dominik Hebeler's avatar
Dominik Hebeler committed
104
105
106
107
        }
        return redirect($url);
    }

108
109
    private static function removeUser($request, $uid)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
110
        $redis = Redis::connection('redisCache');
Dominik Hebeler's avatar
Dominik Hebeler committed
111
112
113
114
115
116
117
        $ip = $request->ip();
        $id = "";
        if (HumanVerification::isTor($ip)) {
            $id = hash("sha512", "999.999.999.999");
        } else {
            $id = hash("sha512", $ip);
        }
118

119
120
        $userList = $redis->smembers(HumanVerification::PREFIX . "." . $id);
        $pipe = $redis->pipeline();
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
        foreach ($userList as $userid) {
            $pipe->hgetall(HumanVerification::PREFIX . "." . $userid);
        }
        $usersData = $pipe->execute();

        $user = [];
        $users = [];
        $sum = 0;
        foreach ($usersData as $userTmp) {
            if (empty($userTmp)) {
                continue;
            }
            $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"]);
            }

        }
151

152
        if (empty($user)) {
153
154
155
            return;
        }

156
        $pipeline = $redis->pipeline();
157
        # Check if we have to whitelist the user or if we can simply delete the data
158
        if ($user["unusedResultPages"] < $sum && !$user["whitelist"]) {
159
            # Whitelist
160
161
            $pipeline->hset(HumanVerification::PREFIX . "." . $uid, 'whitelist', "1");
            $user["whitelist"] = true;
162
163
        }

164
165
        if ($user["whitelist"]) {
            $pipeline->hset(HumanVerification::PREFIX . "." . $uid, 'unusedResultPages', "0");
166
        } else {
167
            $pipeline->del(HumanVerification::PREFIX . "." . $uid);
168
            $pipeline->srem(HumanVerification::PREFIX . "." . $id, $uid);
169
        }
170
171
        $pipeline->expire(HumanVerification::PREFIX . "." . $uid, $user["whitelist"] ? HumanVerification::EXPIRELONG : HumanVerification::EXPIRESHORT);
        $pipeline->expire(HumanVerification::PREFIX . "." . $id, HumanVerification::EXPIRELONG);
172
        $pipeline->execute();
173
174
    }

175
176
    private static function checkId($request, $id)
    {
Dominik Hebeler's avatar
Dominik Hebeler committed
177
178
        $uid = "";
        $ip = $request->ip();
Dominik Hebeler's avatar
Dominik Hebeler committed
179
        if (HumanVerification::isTor($ip)) {
Dominik Hebeler's avatar
Dominik Hebeler committed
180
181
182
183
184
185
            $uid = hash("sha512", "999.999.999.999" . $ip . $_SERVER["AGENT"] . "uid");
        } else {
            $uid = hash("sha512", $ip . $_SERVER["AGENT"] . "uid");
        }

        if ($uid === $id) {
Dominik Hebeler's avatar
Dominik Hebeler committed
186
            return true;
187
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
188
189
190
            return false;
        }
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
191

Dominik Hebeler's avatar
Dominik Hebeler committed
192
    private static function isTor($ip)
Dominik Hebeler's avatar
Dominik Hebeler committed
193
194
195
196
197
198
199
200
201
202
203
204
    {
        $serverAddress = empty($_SERVER['SERVER_ADDR']) ? "144.76.88.77" : $_SERVER['SERVER_ADDR'];
        $queryUrl = "https://tor.metager.org?password=" . urlencode(env("TOR_PASSWORD")) . "&ra=" . urlencode($ip) . "&sa=" . urlencode($serverAddress) . "&sp=443";

        $ch = curl_init($queryUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpcode === 200) {
Dominik Hebeler's avatar
Dominik Hebeler committed
205
            return true;
Dominik Hebeler's avatar
Dominik Hebeler committed
206
        } else {
Dominik Hebeler's avatar
Dominik Hebeler committed
207
            return false;
Dominik Hebeler's avatar
Dominik Hebeler committed
208
209
        }
    }
Dominik Hebeler's avatar
Dominik Hebeler committed
210
}