-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCleanTalkAntiCrawler.php
More file actions
330 lines (274 loc) · 10.4 KB
/
CleanTalkAntiCrawler.php
File metadata and controls
330 lines (274 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<?php
declare(strict_types=1);
namespace Cleantalk\PHPAntiCrawler;
use Cleantalk\PHPAntiCrawler\RequestDto;
use Cleantalk\PHPAntiCrawler\ResultDto;
use Cleantalk\PHPAntiCrawler\Settings;
use Cleantalk\PHPAntiCrawler\KeyDBManager;
use Cleantalk\PHPAntiCrawler\SQLiteManager;
use Cleantalk\PHPAntiCrawler\SyncManager;
use Exception;
use PDO;
final class CleanTalkAntiCrawler
{
public const COOKIE = 'js_anticrawler_passed';
public const ONE_DAY = 60 * 60 * 24;
private PDO $pdo;
public function __construct(array $options = [])
{
Settings::configure($options);
$this->pdo = SQLiteManager::initDb(Settings::$dbPath);
}
public function badVisitor(): bool
{
if (self::isTestIp()) {
return true;
}
$request = RequestDto::fromArray([
'id' => bin2hex(random_bytes(16)),
'fingerprint' => self::fingerprint(),
'ip' => self::ip(),
'ua_name' => self::ua(),
'url' => self::url(),
'ua_id' => $this->getUaId(self::ua()),
'access_language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '',
'access_encoding' => $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '',
]);
// Unauthorized check
if ($this->apiKeyActive(Settings::$apiKey) === false) {
$checkResult = $this->checkByCookie($request);
return ($checkResult->goodRequest === false);
}
(new SyncManager($this->pdo))->manageSynchronization(Settings::$apiKey);
// Authorized check
$checkResult = $this->fullCheck($request);
$this->storeRequest($request, $checkResult);
return ($checkResult->goodRequest === false);
}
private function storeRequest(RequestDto $request, ResultDto $result): void
{
$stmt = $this->pdo->prepare("SELECT ua_id FROM user_agents WHERE ua_name LIKE :ua LIMIT 1");
$stmt->execute([':ua' => '%' . $request->uaName . '%']);
$ua = $stmt->fetch();
$request->uaId = !empty($ua) ? (int)$ua['ua_id'] : 0;
if (Settings::$requestsBackend === 'keydb') {
KeyDBManager::storeRequest($request, $result);
return;
}
$stmt = $this->pdo->prepare(<<<SQL
INSERT INTO requests
(id, fingerprint, ip, blocked, timestamp_unixtime, ua_name, ua_id, url, request_status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL);
$stmt->execute([
$request->id,
$request->fingerprint,
$request->ip,
$result->goodRequest ? 0 : 1,
time(),
$request->uaName,
$request->uaId,
$request->url,
$result->status,
]);
}
private function fullCheck(RequestDto $request): ResultDto
{
if (($firstCheck = $this->checkByLists($request))->status !== ResultDto::STATUS_UNDEFINED) {
return $firstCheck;
}
if (($secondCheck = $this->checkByUserAgents($request))->status !== ResultDto::STATUS_UNDEFINED) {
return $secondCheck;
}
return $thirdCheck = $this->checkByCookie($request);
}
private function checkByLists(RequestDto $request): ResultDto
{
$stmt = $this->pdo->prepare(<<<SQL
SELECT ip, is_personal_list, is_whitelist
FROM lists
WHERE ip = :ip
ORDER BY is_personal_list DESC, is_whitelist DESC
LIMIT 1
SQL);
$stmt->bindValue(':ip', inet_pton($request->ip), PDO::PARAM_LOB);
$stmt->execute();
$row = $stmt->fetch();
if (empty($row)) {
return ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_UNDEFINED]);
}
if ($row['is_whitelist'] == 1) {
return ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_PERSONAL_LIST_MATCH]);
}
if ($row['is_whitelist'] == 0) {
return ResultDto::fromArray(['good_request' => 0, 'status' => ResultDto::STATUS_DB_MATCH]);
}
throw new Exception('Unexpected data found in lists table: ' . json_encode($row));
}
private function checkByUserAgents(RequestDto $request): ResultDto
{
$stmt = $this->pdo->prepare(<<<SQL
SELECT is_whitelist FROM user_agents
WHERE ua_id = :id
ORDER BY is_whitelist DESC LIMIT 1
SQL);
$stmt->execute([':id' => $request->uaId]);
$row = $stmt->fetch();
if (empty($row)) {
return ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_UNDEFINED]);
}
if ($row['is_whitelist'] == 1) {
return ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_BOT_PROTECTION]);
}
if ($row['is_whitelist'] == 0) {
return ResultDto::fromArray(['good_request' => 0, 'status' => ResultDto::STATUS_BOT_PROTECTION]);
}
throw new Exception('Unexpected data found in user_agents table: ' . json_encode($row));
}
private function checkByCookie(RequestDto $request): ResultDto
{
$isFirstVisit = $this->saveVisitor($request); // returns `true` if INSERT happened and `false` otherwise
if ($isFirstVisit) {
return ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_DB_MATCH]);
}
$this->updateLastSeen($request);
return self::cookieFound()
? ResultDto::fromArray(['good_request' => 1, 'status' => ResultDto::STATUS_BOT_PROTECTION])
: ResultDto::fromArray(['good_request' => 0, 'status' => ResultDto::STATUS_BOT_PROTECTION]);
}
private function saveVisitor(RequestDto $request): bool
{
if (Settings::$requestsBackend === 'keydb') {
return KeyDBManager::saveVisitor($request);
}
$now = time();
$stmt = $this->pdo->prepare('
INSERT INTO visitors (fingerprint, ip, ua, created_at, last_seen)
VALUES (:fp, :ip, :ua, :c, :l)
ON CONFLICT(fingerprint) DO NOTHING
');
$stmt->execute([
':fp' => $request->fingerprint,
':ip' => $request->ip,
':ua' => $request->uaName,
':c' => $now,
':l' => $now,
]);
// rowCount() will be 1 if insert succeeded (first time), 0 if ignored (already existed)
return $stmt->rowCount() === 1;
}
private function updateLastSeen(RequestDto $request): void
{
if (Settings::$requestsBackend === 'keydb') {
KeyDBManager::updateLastSeen($request);
return;
}
$now = time();
$stmt = $this->pdo->prepare('UPDATE visitors SET last_seen = :l WHERE fingerprint = :fp');
$stmt->execute([
':fp' => $request->fingerprint,
':l' => $now,
]);
}
private static function cookieFound(): bool
{
return isset($_COOKIE[self::COOKIE]) && $_COOKIE[self::COOKIE] == 1;
}
public function showAccessDeniedScreen(int $status = 403): void
{
http_response_code($status);
header('content-type: text/html; charset=utf-8');
$html = file_get_contents(__DIR__ . '/cleantalk-anticrawler.html');
$html = str_replace(':IP:', htmlspecialchars(self::ip(), ENT_QUOTES, 'UTF-8'), $html);
echo $html;
exit;
}
private static function ip(): string
{
if (self::isTestIp()) {
return '10.10.10.10';
}
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
private static function ua(): string
{
return substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 1024);
}
private static function url(): string
{
$scheme = (
(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
|| (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
) ? 'https' : 'http';
$host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];
return "{$scheme}://{$host}{$uri}";
}
private static function isTestIp(): bool
{
return ($_REQUEST['sfw_test_ip'] ?? '') === '10.10.10.10';
}
private function getUaId(string $ua): int
{
$stmt = $this->pdo->prepare(<<<SQL
SELECT ua_id, ua_name, is_whitelist
FROM user_agents
ORDER BY is_whitelist DESC, ua_id ASC
SQL);
$stmt->execute();
$userAgents = $stmt->fetchAll();
foreach ($userAgents as $agent) {
$regex = $agent['ua_name'];
if (preg_match($regex, $ua, $matches) === 1) {
return (int)$agent['ua_id'];
}
}
return 0;
}
private static function fingerprint(): string
{
$userIp = self::ip();
$userAgent = self::ua();
$acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$acceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
return sha1(implode('|', [$userIp, $userAgent, $acceptLanguage, $acceptEncoding]));
}
private function apiKeyActive(string $apiKey = ''): bool
{
if (empty($apiKey)) {
return false;
}
$lastKeyCheckUnixTime = (int)(
$this->pdo
->query("SELECT v FROM kv WHERE k = 'last_key_check';")
->fetchColumn() ?? 0
);
$checkStillValid = (time() - $lastKeyCheckUnixTime < self::ONE_DAY);
if ($checkStillValid) {
return true;
}
$url = 'https://api.cleantalk.org/?method_name=notice_paid_till&auth_key=' . urlencode($apiKey);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_FOLLOWLOCATION => true,
]);
$response = curl_exec($ch);
if ($response === false) {
curl_close($ch);
return false;
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 200) {
return false;
}
$data = json_decode($response, true);
$keyActive = !empty($data['data']['moderate']);
if ($keyActive) {
$this->pdo->exec("UPDATE kv SET v = " . time() . " WHERE k = 'last_key_check';");
}
return $keyActive;
}
}