@anonympins/fingerprint 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,228 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint;
6
+
7
+ /**
8
+ * Classe de détection d'anomalies et d'usurpation TLS (JA3) en PHP.
9
+ */
10
+ class Ja3AnomalyDetector
11
+ {
12
+ // Liste décimale des valeurs GREASE (RFC 8701) utilisées par les moteurs Chromium/Safari récents
13
+ private const GREASE_VALUES = [
14
+ 2570, 6682, 10794, 14906, 19018, 23130, 27242, 31354,
15
+ 35466, 39578, 43690, 47802, 51914, 55926, 60038, 64150
16
+ ];
17
+
18
+ // Base de données locale de signatures JA3 MD5 connues pour la corroboration de base
19
+ private const TLS_FINGERPRINT_DB = [
20
+ 'e188a442b87f422c5a1e80b05399435b' => ['Chrome'],
21
+ 'd8e35855049321c6042a4325c697858f' => ['Chrome'],
22
+ 'a9f90958d44533748c139a5d1895b925' => ['Chrome'],
23
+ '3b5379916d2b3882253c42885956a350' => ['Chrome'],
24
+ '59822058c95c33d2d06e52f410855c8c' => ['Chrome'],
25
+ 'b386946a5a586163c7c533636b45c355' => ['Firefox'],
26
+ '66236495a523c1785f8f3a105b248b11' => ['Firefox'],
27
+ 'b73d470006575b5e35167a0b5a8540e2' => ['Firefox'],
28
+ '8443d7562933834333943465d52363cf' => ['Firefox'],
29
+ 'b633f21d532d35967c8753c38536b4d3' => ['Safari'],
30
+ '4d7a28d5f55b359b69100a311013f03e' => ['Safari', 'Chrome', 'Firefox'],
31
+ '8dd3d7532873575314df23c447543001' => ['Safari', 'Chrome', 'Firefox'],
32
+ // Bibliothèques et scrapers automatisés connus
33
+ '47344a349b75c4e82333475553b5f358' => ['Python'],
34
+ 'b29587b8a143c42546133ad7704b3310' => ['Go'],
35
+ 'd435b5223b2884c5a832b842637e245f' => ['Java'],
36
+ 'c72366b9551263d990b7fa574225332c' => ['curl'],
37
+ ];
38
+
39
+ /**
40
+ * Analyse une chaîne JA3 brute non hachée.
41
+ * Format attendu : "TLSVersion,Ciphers,Extensions,EllipticCurves,EllipticCurveFormats"
42
+ */
43
+ public static function parseJa3(string $ja3String): ?array
44
+ {
45
+ if (empty($ja3String)) {
46
+ return null;
47
+ }
48
+
49
+ $parts = explode(',', $ja3String);
50
+ if (count($parts) !== 5) {
51
+ return null;
52
+ }
53
+
54
+ return [
55
+ 'tlsVersion' => (int)$parts[0],
56
+ 'ciphers' => $parts[1] !== '' ? array_map('intval', explode('-', $parts[1])) : [],
57
+ 'extensions' => $parts[2] !== '' ? array_map('intval', explode('-', $parts[2])) : [],
58
+ 'curves' => $parts[3] !== '' ? array_map('intval', explode('-', $parts[3])) : [],
59
+ 'points' => $parts[4] !== '' ? array_map('intval', explode('-', $parts[4])) : []
60
+ ];
61
+ }
62
+
63
+ /**
64
+ * Vérifie si un tableau contient au moins une valeur GREASE.
65
+ */
66
+ public static function hasGrease(array $values): bool
67
+ {
68
+ foreach ($values as $val) {
69
+ if (in_array($val, self::GREASE_VALUES, true)) {
70
+ return true;
71
+ }
72
+ }
73
+ return false;
74
+ }
75
+
76
+ /**
77
+ * Parse sommairement le User-Agent pour en extraire la famille de navigateur.
78
+ */
79
+ public static function getBrowserFamily(string $userAgent): ?string
80
+ {
81
+ $ua = strtolower($userAgent);
82
+ if (strpos($ua, 'edg') !== false) {
83
+ return 'Edge';
84
+ }
85
+ if (strpos($ua, 'chrome') !== false) {
86
+ return 'Chrome';
87
+ }
88
+ if (strpos($ua, 'firefox') !== false) {
89
+ return 'Firefox';
90
+ }
91
+ if (strpos($ua, 'safari') !== false) {
92
+ return 'Safari';
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Calcule le score global d'anomalie et d'usurpation JA3.
99
+ *
100
+ * @param string|null $ja3Hash L'empreinte MD5 du JA3 (32 caractères)
101
+ * @param string|null $ja3Raw L'empreinte brute non hachée (si disponible)
102
+ * @param string $userAgent Le User-Agent de la requête
103
+ * @param string $httpVersion La version HTTP de la requête (ex: "HTTP/2", "HTTP/1.1", ou "2.0")
104
+ * @param object|null $cacheInstance Un driver de cache (ex: instance Redis) supportant get() et set() pour la détection de stagnation
105
+ * @return int Un score de suspicion compris entre 0 et 100
106
+ */
107
+ public static function getJa3AnomalyScore(
108
+ ?string $ja3Hash,
109
+ ?string $ja3Raw,
110
+ string $userAgent,
111
+ string $httpVersion,
112
+ ?object $cacheInstance = null
113
+ ): int {
114
+ $score = 0;
115
+ $claimedBrowser = self::getBrowserFamily($userAgent);
116
+ $isHumanBrowser = in_array($claimedBrowser, ['Chrome', 'Firefox', 'Safari', 'Edge'], true);
117
+
118
+ // --- ANALYSE 1 : CONTRÔLE SUR LE MD5 DU JA3 ---
119
+ if ($ja3Hash && strlen($ja3Hash) === 32) {
120
+ if (isset(self::TLS_FINGERPRINT_DB[$ja3Hash])) {
121
+ $expectedBrowsers = self::TLS_FINGERPRINT_DB[$ja3Hash];
122
+
123
+ // Cas A : L'empreinte correspond à un outil de scraping mais le UA prétend être humain
124
+ $isLibrary = array_intersect($expectedBrowsers, ['Python', 'Go', 'Java', 'curl']);
125
+ if (!empty($isLibrary) && $isHumanBrowser) {
126
+ $score = max($score, 90); // Suspicion maximale : usurpation évidente
127
+ }
128
+
129
+ // Cas B : Incohérence directe entre le UA prétendu et la stack TLS correspondante
130
+ if ($claimedBrowser !== null) {
131
+ $matched = false;
132
+ foreach ($expectedBrowsers as $expected) {
133
+ if (stripos($claimedBrowser, $expected) === 0) {
134
+ $matched = true;
135
+ break;
136
+ }
137
+ }
138
+ if (!$matched) {
139
+ $score = max($score, 80); // Le navigateur déclaré ne correspond pas au client TLS utilisé
140
+ }
141
+ }
142
+ }
143
+
144
+ // Cas C : Tracking de stagnation multi-UA (Stateful)
145
+ if ($cacheInstance && $claimedBrowser !== null && method_exists($cacheInstance, 'get') && method_exists($cacheInstance, 'set')) {
146
+ $cacheKey = "ja3-browsers:" . $ja3Hash;
147
+
148
+ try {
149
+ $rawCached = $cacheInstance->get($cacheKey);
150
+ $seenBrowsers = $rawCached ? json_decode((string)$rawCached, true) : [];
151
+ if (!is_array($seenBrowsers)) {
152
+ $seenBrowsers = [];
153
+ }
154
+
155
+ if (!in_array($claimedBrowser, $seenBrowsers, true)) {
156
+ $seenBrowsers[] = $claimedBrowser;
157
+ // Cache pendant 24 heures (86400 secondes)
158
+ if (method_exists($cacheInstance, 'setex')) {
159
+ $cacheInstance->setex($cacheKey, 86400, json_encode($seenBrowsers));
160
+ } else {
161
+ $cacheInstance->set($cacheKey, json_encode($seenBrowsers), 86400);
162
+ }
163
+ }
164
+
165
+ // Si une seule stack TLS génère des requêtes avec différents navigateurs, c'est un bot en rotation de UA
166
+ if (count($seenBrowsers) > 1) {
167
+ $score = max($score, 85);
168
+ }
169
+ } catch (\Throwable $e) {
170
+ // Tolérance aux pannes du cache
171
+ }
172
+ }
173
+ }
174
+
175
+ // --- ANALYSE 2 : CONTRÔLE PROFOND SUR L'EMPREINTE BRUTE (RAW JA3) ---
176
+ if ($ja3Raw) {
177
+ $parsed = self::parseJa3($ja3Raw);
178
+ if ($parsed) {
179
+ // Contrôle A : Mécanisme GREASE pour Chrome / Edge (obligatoire)
180
+ if ($claimedBrowser === 'Chrome' || $claimedBrowser === 'Edge') {
181
+ $hasCiphersGrease = self::hasGrease($parsed['ciphers']);
182
+ $hasExtensionsGrease = self::hasGrease($parsed['extensions']);
183
+
184
+ if (!$hasCiphersGrease && !$hasExtensionsGrease) {
185
+ // Chrome ou Edge moderne sans GREASE = spoofing de bas niveau (ex: python-requests déguisé)
186
+ $score = max($score, 75);
187
+ }
188
+ }
189
+
190
+ // Contrôle B : HTTP/2 ou HTTP/3 sans négociation ALPN (Extension 16)
191
+ $isH2OrHigher = (
192
+ strpos($httpVersion, '2.0') !== false ||
193
+ strpos($httpVersion, 'HTTP/2') !== false ||
194
+ strpos($httpVersion, 'HTTP/3') !== false
195
+ );
196
+ $hasAlpnExtension = in_array(16, $parsed['extensions'], true);
197
+
198
+ if ($isH2OrHigher && !$hasAlpnExtension) {
199
+ // Négociation HTTP/2 active au niveau serveur mais absente au niveau des extensions TLS du client
200
+ $score = max($score, 70);
201
+ }
202
+
203
+ // Contrôle C : Version TLS obsolète négociée par un navigateur moderne (ex: TLS < 1.2, id < 771)
204
+ if ($isHumanBrowser && $parsed['tlsVersion'] < 771) {
205
+ $score = max($score, 80);
206
+ }
207
+ }
208
+ }
209
+
210
+ return $score;
211
+ }
212
+ }
213
+
214
+ // --- EXEMPLE D'UTILISATION PRATIQUE ---
215
+ /*
216
+ $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
217
+ $httpVersion = $_SERVER['SERVER_PROTOCOL'] ?? '';
218
+
219
+ // Récupération des en-têtes injectés par votre Reverse-Proxy (Nginx, HAProxy, etc.)
220
+ $ja3Hash = $_SERVER['HTTP_X_JA3_HASH'] ?? null;
221
+ $ja3Raw = $_SERVER['HTTP_X_JA3_RAW'] ?? null;
222
+
223
+ // Redis facultatif pour la détection stateful de rotation UA
224
+ $redis = new \Redis();
225
+ $redis->connect('127.0.0.1', 6379);
226
+
227
+ $suspicionScore = Ja3AnomalyDetector::getJa3AnomalyScore($ja3Hash, $ja3Raw, $userAgent, $httpVersion, $redis);
228
+ */
@@ -34,6 +34,8 @@ class RequestContext
34
34
  // Propriétés spécifiques qui peuvent être fournies par un proxy inverse
35
35
  public ?string $ja3;
36
36
  public ?string $ja4;
37
+ public ?string $ja4s;
38
+ public ?string $ja4h;
37
39
  public ?string $http2Fingerprint;
38
40
  public ?string $tcpFingerprint;
39
41
 
@@ -70,6 +72,8 @@ class RequestContext
70
72
  // Extraire les empreintes TLS/HTTP2/TCP si elles sont fournies par les en-têtes
71
73
  $this->ja3 = $this->headers['x-ja3-hash'] ?? null;
72
74
  $this->ja4 = $this->headers['x-ja4-hash'] ?? null;
75
+ $this->ja4s = $this->headers['x-ja4s-hash'] ?? null;
76
+ $this->ja4h = $this->headers['x-ja4h-hash'] ?? null;
73
77
  $this->http2Fingerprint = $this->headers['x-http2-fingerprint'] ?? null;
74
78
  $this->tcpFingerprint = $this->headers['x-tcp-fingerprint'] ?? null;
75
79
  }
@@ -23,4 +23,14 @@ class StoreManager
23
23
  {
24
24
  self::$store = $externalStore;
25
25
  }
26
+
27
+ /**
28
+ * Définit l'instance active du store (utile pour l'injection de dépendances et les tests).
29
+ *
30
+ * @param mixed $store
31
+ */
32
+ public static function setStore($store): void
33
+ {
34
+ self::$store = $store;
35
+ }
26
36
  }