@anonympins/fingerprint 0.7.0 → 0.7.1

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/composer.json +8 -1
  4. package/package.json +1 -1
  5. package/public/fingerprint-wordpress.zip +0 -0
  6. package/src/js/build-client.js +8 -10
  7. package/src/js/fingerprint.builder.js +37 -38
  8. package/src/js/fingerprint.client.js +1531 -1463
  9. package/src/js/fingerprint.client.obfuscated.js +1 -0
  10. package/src/js/fingerprint.js +152 -10
  11. package/src/js/fingerprint.utils.js +213 -213
  12. package/src/js/library.js +340 -376
  13. package/src/js/mongodb-store.js +1 -1
  14. package/src/js/optimization.worker.js +27 -27
  15. package/src/js/pow.solver.inline.js +154 -56
  16. package/src/js/pow.solver.js +180 -92
  17. package/src/js/pow.worker.js +48 -48
  18. package/src/js/redis-store.js +1 -1
  19. package/src/js/tests/fingerprint.client.init.test.js +146 -143
  20. package/src/js/tests/fingerprint.test.js +34 -7
  21. package/src/js/tests/ip-reputation.test.js +1 -0
  22. package/src/js/upow-model-task.js +14 -15
  23. package/src/php/AutoTuner.php +34 -34
  24. package/src/php/Challenge/ChallengeUtils.php +56 -10
  25. package/src/php/Config/SecurityProfiles.php +20 -0
  26. package/src/php/DirectFingerprint.php +190 -145
  27. package/src/php/FingerprintBuilder.php +29 -30
  28. package/src/php/FingerprintClient.php +147 -148
  29. package/src/php/FingerprintEngine.php +7 -5
  30. package/src/php/Ja3AnomalyDetector.php +33 -32
  31. package/src/php/Optimization/FunctionRegistry.php +7 -7
  32. package/src/php/Optimization/Optimization.php +24 -24
  33. package/src/php/Optimization/OptimizationOperators.php +26 -25
  34. package/src/php/Optimization/ProblemInitializers.php +52 -52
  35. package/src/php/ProblemManager.php +31 -34
  36. package/src/php/RequestContext.php +8 -1
  37. package/src/php/Store/IStore.php +7 -8
  38. package/src/php/Store/InMemoryStore.php +66 -66
  39. package/src/php/Store/MongoDbStore.php +5 -5
  40. package/src/php/Store/RedisStore.php +5 -5
  41. package/src/php/Store/StoreManager.php +35 -35
  42. package/src/php/Tests/ChallengeUtilsTest.php +453 -453
  43. package/src/php/Tests/DnsCircuitBreakerTest.php +105 -105
  44. package/src/php/Tests/FingerprintEngineTest.php +662 -662
  45. package/src/php/Tests/IpReputationTest.php +10 -0
  46. package/src/php/Tests/MaliciousPatternsTest.php +103 -103
  47. package/src/php/Tests/MetricsTest.php +97 -97
  48. package/src/php/Tests/ProblemManagerTest.php +376 -376
  49. package/src/php/Tests/QuicFingerprintTest.php +53 -53
  50. package/src/php/Tests/RequestUtilsTest.php +471 -471
  51. package/src/php/Tests/TLSClientHelloParserTest.php +177 -177
  52. package/src/php/Tests/config/ed25519_key.json +3 -3
  53. package/src/php/Utils/Env.php +49 -49
  54. package/src/php/Utils/MaliciousPatterns.php +74 -74
  55. package/src/php/Utils/MetricsManager.php +209 -209
  56. package/src/php/Utils/RequestUtils.php +129 -7
  57. package/src/php/Utils/TLSClientHelloParser.php +369 -369
  58. package/src/php/WordPress/WpDbStore.php +155 -0
  59. package/src/php/WordPress/fingerprint-wordpress.php +217 -0
  60. package/src/php/WordPress/package.php +123 -0
  61. package/src/php/bin/auto-tune.php +118 -118
@@ -1,178 +1,178 @@
1
- <?php
2
-
3
- declare(strict_types=1);
4
-
5
- namespace Anonympins\Fingerprint\Tests;
6
-
7
- use Anonympins\Fingerprint\Utils\TLSClientHelloParser;
8
- use PHPUnit\Framework\TestCase;
9
-
10
- /**
11
- * Tests unitaires pour le décodeur binaire TLS Client Hello.
12
- */
13
- class TLSClientHelloParserTest extends TestCase
14
- {
15
- /**
16
- * Helper pour construire un paquet TLS Client Hello binaire valide et réaliste.
17
- *
18
- * @param int $sslVersion Version TLS (ex: 0x0303 pour TLS 1.2)
19
- * @param array<int> $ciphers Liste des Cipher Suites
20
- * @param array<array{type: int, data: string}> $extensions Liste des extensions
21
- * @return string Paquet binaire brut
22
- */
23
- private function buildMockClientHello(int $sslVersion = 0x0303, array $ciphers = [4865, 2570], array $extensions = []): string
24
- {
25
- $recordType = pack('C', 0x16); // Handshake Record (22)
26
- $recordVersion = pack('n', 0x0301); // TLS 1.0 record layer version
27
- $recordLength = pack('n', 120); // Dummy length
28
-
29
- $handshakeType = pack('C', 0x01); // Client Hello (1)
30
- $handshakeLength = pack('C3', 0, 0, 110); // Dummy length
31
-
32
- $clientVersion = pack('n', $sslVersion);
33
- $random = str_repeat("\x00", 32); // Random de 32 octets
34
- $sessionId = pack('C', 0x00); // Session ID vide (longueur 0)
35
-
36
- // Construction des Cipher Suites
37
- $ciphersBinary = '';
38
- foreach ($ciphers as $cipher) {
39
- $ciphersBinary .= pack('n', $cipher);
40
- }
41
- $ciphersPayload = pack('n', strlen($ciphersBinary)) . $ciphersBinary;
42
-
43
- // Compression Methods (Standard: 1 méthode, valeur 0x00 = null)
44
- $compression = pack('C2', 1, 0);
45
-
46
- // Construction des Extensions
47
- $extensionsBinary = '';
48
- foreach ($extensions as $ext) {
49
- $extensionsBinary .= pack('n', $ext['type']) . pack('n', strlen($ext['data'])) . $ext['data'];
50
- }
51
- $extensionsPayload = pack('n', strlen($extensionsBinary)) . $extensionsBinary;
52
-
53
- return $recordType . $recordVersion . $recordLength . $handshakeType . $handshakeLength . $clientVersion . $random . $sessionId . $ciphersPayload . $compression . $extensionsPayload;
54
- }
55
-
56
- public function testParseValidClientHelloWithGreaseAndExtensions(): void
57
- {
58
- // On injecte l'extension 10 (Supported Groups / Curves)
59
- // Data: 4 octets de longueur de liste + 29 (X25519) + 2570 (GREASE)
60
- $extCurves = [
61
- 'type' => 10,
62
- 'data' => pack('n', 4) . pack('n2', 29, 2570)
63
- ];
64
-
65
- // On injecte l'extension 11 (EC Point Formats)
66
- // Data: 1 octet de longueur de liste + 0 (uncompressed)
67
- $extPoints = [
68
- 'type' => 11,
69
- 'data' => pack('C2', 1, 0)
70
- ];
71
-
72
- // On build le paquet binaire de test
73
- $binary = $this->buildMockClientHello(
74
- 0x0303, // SSL Version: 771 (TLS 1.2)
75
- [4865, 2570], // Ciphers (2570 est une valeur GREASE)
76
- [$extCurves, $extPoints]
77
- );
78
-
79
- $result = TLSClientHelloParser::parse($binary);
80
-
81
- $this->assertNotNull($result);
82
-
83
- // Vérifications des filtrages GREASE et de la construction de la chaîne JA3
84
- // Chaîne JA3 attendue: "Version,Ciphers,Extensions,Curves,Points"
85
- // - Version: 771
86
- // - Ciphers: 4865 (2570 a été nettoyé car GREASE)
87
- // - Extensions: 10-11
88
- // - Curves: 29 (2570 a été nettoyé car GREASE)
89
- // - Points: 0
90
- $expectedJa3String = '771,4865,10-11,29,0';
91
- $this->assertSame($expectedJa3String, $result['ja3_string']);
92
- $this->assertSame(md5($expectedJa3String), $result['ja3_hash']);
93
- }
94
-
95
- public function testParseValidClientHelloWithJa4(): void
96
- {
97
- // On injecte l'extension 0 (SNI) avec données vides
98
- $extSni = [
99
- 'type' => 0,
100
- 'data' => pack('n', 0)
101
- ];
102
-
103
- // On injecte l'extension 16 (ALPN)
104
- // Data: list len (3) + str len (2) + "h2"
105
- $extAlpn = [
106
- 'type' => 16,
107
- 'data' => pack('n', 3) . pack('C', 2) . 'h2'
108
- ];
109
-
110
- // On injecte l'extension 13 (Signature Algorithms)
111
- // Data: list len (4) + 2 sig algs (0x0401, 0x0804)
112
- $extSigAlgs = [
113
- 'type' => 13,
114
- 'data' => pack('n', 4) . pack('n2', 0x0401, 0x0804)
115
- ];
116
-
117
- // On injecte l'extension 43 (Supported Versions) pour forcer la version TLS 1.3 (0x0304)
118
- // Data: list len (4) + 2 versions (0x0304, 0x0303)
119
- $extSupportedVersions = [
120
- 'type' => 43,
121
- 'data' => pack('C', 4) . pack('n2', 0x0304, 0x0303)
122
- ];
123
-
124
- // On build le paquet binaire de test
125
- $binary = $this->buildMockClientHello(
126
- 0x0303, // Version de base
127
- [4865, 2570], // Ciphers (2570 est GREASE, sera ignoré dans les comptes)
128
- [$extSni, $extAlpn, $extSigAlgs, $extSupportedVersions]
129
- );
130
-
131
- $result = TLSClientHelloParser::parse($binary);
132
-
133
- $this->assertNotNull($result);
134
- $this->assertArrayHasKey('ja4_raw', $result);
135
-
136
- // Version la plus haute: 0x0304 -> "13"
137
- // SNI présent: "d"
138
- // Nombre de ciphers (hors GREASE): 4865 (0x1301) -> 1 -> "01"
139
- // Nombre d'extensions (hors GREASE): 0, 13, 16, 43 -> 4 -> "04"
140
- // ALPN: "h2"
141
- // Partie A attendue: "t13d0104h2"
142
- $this->assertStringStartsWith('t13d0104h2', $result['ja4_raw']);
143
-
144
- // Partie B: hash sha256 de "1301" haché en hexadécimal et tronqué à 12 caractères
145
- $expectedJa4b = substr(hash('sha256', '1301'), 0, 12);
146
- $this->assertStringContainsString($expectedJa4b, $result['ja4_raw']);
147
-
148
- // Partie C: extensions triées et hachées: "0000,000d,0010,002b_0401,0804"
149
- $extensionsString = '0000,000d,0010,002b';
150
- $sigAlgsString = '0401,0804';
151
- $expectedJa4c = substr(hash('sha256', $extensionsString . '_' . $sigAlgsString), 0, 12);
152
- $this->assertStringEndsWith($expectedJa4c, $result['ja4_raw']);
153
- }
154
-
155
- public function testParseReturnsNullWhenPacketTooShort(): void
156
- {
157
- $shortBinary = str_repeat("\x16", 40);
158
- $this->assertNull(TLSClientHelloParser::parse($shortBinary));
159
- }
160
-
161
- public function testParseReturnsNullOnInvalidRecordType(): void
162
- {
163
- // 0x17 au lieu de 0x16 (Application data au lieu de Handshake)
164
- $invalidRecord = $this->buildMockClientHello();
165
- $invalidRecord[0] = chr(0x17);
166
-
167
- $this->assertNull(TLSClientHelloParser::parse($invalidRecord));
168
- }
169
-
170
- public function testParseReturnsNullOnInvalidHandshakeType(): void
171
- {
172
- // 0x02 au lieu de 0x01 (Server Hello au lieu de Client Hello)
173
- $invalidHandshake = $this->buildMockClientHello();
174
- $invalidHandshake[5] = chr(0x02);
175
-
176
- $this->assertNull(TLSClientHelloParser::parse($invalidHandshake));
177
- }
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Tests;
6
+
7
+ use Anonympins\Fingerprint\Utils\TLSClientHelloParser;
8
+ use PHPUnit\Framework\TestCase;
9
+
10
+ /**
11
+ * Tests unitaires pour le décodeur binaire TLS Client Hello.
12
+ */
13
+ class TLSClientHelloParserTest extends TestCase
14
+ {
15
+ /**
16
+ * Helper pour construire un paquet TLS Client Hello binaire valide et réaliste.
17
+ *
18
+ * @param int $sslVersion Version TLS (ex: 0x0303 pour TLS 1.2)
19
+ * @param array<int> $ciphers Liste des Cipher Suites
20
+ * @param array<array{type: int, data: string}> $extensions Liste des extensions
21
+ * @return string Paquet binaire brut
22
+ */
23
+ private function buildMockClientHello(int $sslVersion = 0x0303, array $ciphers = [4865, 2570], array $extensions = []): string
24
+ {
25
+ $recordType = pack('C', 0x16); // Handshake Record (22)
26
+ $recordVersion = pack('n', 0x0301); // TLS 1.0 record layer version
27
+ $recordLength = pack('n', 120); // Dummy length
28
+
29
+ $handshakeType = pack('C', 0x01); // Client Hello (1)
30
+ $handshakeLength = pack('C3', 0, 0, 110); // Dummy length
31
+
32
+ $clientVersion = pack('n', $sslVersion);
33
+ $random = str_repeat("\x00", 32); // Random de 32 octets
34
+ $sessionId = pack('C', 0x00); // Session ID vide (longueur 0)
35
+
36
+ // Construction des Cipher Suites
37
+ $ciphersBinary = '';
38
+ foreach ($ciphers as $cipher) {
39
+ $ciphersBinary .= pack('n', $cipher);
40
+ }
41
+ $ciphersPayload = pack('n', strlen($ciphersBinary)) . $ciphersBinary;
42
+
43
+ // Compression Methods (Standard: 1 méthode, valeur 0x00 = null)
44
+ $compression = pack('C2', 1, 0);
45
+
46
+ // Construction des Extensions
47
+ $extensionsBinary = '';
48
+ foreach ($extensions as $ext) {
49
+ $extensionsBinary .= pack('n', $ext['type']) . pack('n', strlen($ext['data'])) . $ext['data'];
50
+ }
51
+ $extensionsPayload = pack('n', strlen($extensionsBinary)) . $extensionsBinary;
52
+
53
+ return $recordType . $recordVersion . $recordLength . $handshakeType . $handshakeLength . $clientVersion . $random . $sessionId . $ciphersPayload . $compression . $extensionsPayload;
54
+ }
55
+
56
+ public function testParseValidClientHelloWithGreaseAndExtensions(): void
57
+ {
58
+ // On injecte l'extension 10 (Supported Groups / Curves)
59
+ // Data: 4 octets de longueur de liste + 29 (X25519) + 2570 (GREASE)
60
+ $extCurves = [
61
+ 'type' => 10,
62
+ 'data' => pack('n', 4) . pack('n2', 29, 2570)
63
+ ];
64
+
65
+ // On injecte l'extension 11 (EC Point Formats)
66
+ // Data: 1 octet de longueur de liste + 0 (uncompressed)
67
+ $extPoints = [
68
+ 'type' => 11,
69
+ 'data' => pack('C2', 1, 0)
70
+ ];
71
+
72
+ // On build le paquet binaire de test
73
+ $binary = $this->buildMockClientHello(
74
+ 0x0303, // SSL Version: 771 (TLS 1.2)
75
+ [4865, 2570], // Ciphers (2570 est une valeur GREASE)
76
+ [$extCurves, $extPoints]
77
+ );
78
+
79
+ $result = TLSClientHelloParser::parse($binary);
80
+
81
+ $this->assertNotNull($result);
82
+
83
+ // Vérifications des filtrages GREASE et de la construction de la chaîne JA3
84
+ // Chaîne JA3 attendue: "Version,Ciphers,Extensions,Curves,Points"
85
+ // - Version: 771
86
+ // - Ciphers: 4865 (2570 a été nettoyé car GREASE)
87
+ // - Extensions: 10-11
88
+ // - Curves: 29 (2570 a été nettoyé car GREASE)
89
+ // - Points: 0
90
+ $expectedJa3String = '771,4865,10-11,29,0';
91
+ $this->assertSame($expectedJa3String, $result['ja3_string']);
92
+ $this->assertSame(md5($expectedJa3String), $result['ja3_hash']);
93
+ }
94
+
95
+ public function testParseValidClientHelloWithJa4(): void
96
+ {
97
+ // On injecte l'extension 0 (SNI) avec données vides
98
+ $extSni = [
99
+ 'type' => 0,
100
+ 'data' => pack('n', 0)
101
+ ];
102
+
103
+ // On injecte l'extension 16 (ALPN)
104
+ // Data: list len (3) + str len (2) + "h2"
105
+ $extAlpn = [
106
+ 'type' => 16,
107
+ 'data' => pack('n', 3) . pack('C', 2) . 'h2'
108
+ ];
109
+
110
+ // On injecte l'extension 13 (Signature Algorithms)
111
+ // Data: list len (4) + 2 sig algs (0x0401, 0x0804)
112
+ $extSigAlgs = [
113
+ 'type' => 13,
114
+ 'data' => pack('n', 4) . pack('n2', 0x0401, 0x0804)
115
+ ];
116
+
117
+ // On injecte l'extension 43 (Supported Versions) pour forcer la version TLS 1.3 (0x0304)
118
+ // Data: list len (4) + 2 versions (0x0304, 0x0303)
119
+ $extSupportedVersions = [
120
+ 'type' => 43,
121
+ 'data' => pack('C', 4) . pack('n2', 0x0304, 0x0303)
122
+ ];
123
+
124
+ // On build le paquet binaire de test
125
+ $binary = $this->buildMockClientHello(
126
+ 0x0303, // Version de base
127
+ [4865, 2570], // Ciphers (2570 est GREASE, sera ignoré dans les comptes)
128
+ [$extSni, $extAlpn, $extSigAlgs, $extSupportedVersions]
129
+ );
130
+
131
+ $result = TLSClientHelloParser::parse($binary);
132
+
133
+ $this->assertNotNull($result);
134
+ $this->assertArrayHasKey('ja4_raw', $result);
135
+
136
+ // Version la plus haute: 0x0304 -> "13"
137
+ // SNI présent: "d"
138
+ // Nombre de ciphers (hors GREASE): 4865 (0x1301) -> 1 -> "01"
139
+ // Nombre d'extensions (hors GREASE): 0, 13, 16, 43 -> 4 -> "04"
140
+ // ALPN: "h2"
141
+ // Partie A attendue: "t13d0104h2"
142
+ $this->assertStringStartsWith('t13d0104h2', $result['ja4_raw']);
143
+
144
+ // Partie B: hash sha256 de "1301" haché en hexadécimal et tronqué à 12 caractères
145
+ $expectedJa4b = substr(hash('sha256', '1301'), 0, 12);
146
+ $this->assertStringContainsString($expectedJa4b, $result['ja4_raw']);
147
+
148
+ // Partie C: extensions triées et hachées: "0000,000d,0010,002b_0401,0804"
149
+ $extensionsString = '0000,000d,0010,002b';
150
+ $sigAlgsString = '0401,0804';
151
+ $expectedJa4c = substr(hash('sha256', $extensionsString . '_' . $sigAlgsString), 0, 12);
152
+ $this->assertStringEndsWith($expectedJa4c, $result['ja4_raw']);
153
+ }
154
+
155
+ public function testParseReturnsNullWhenPacketTooShort(): void
156
+ {
157
+ $shortBinary = str_repeat("\x16", 40);
158
+ $this->assertNull(TLSClientHelloParser::parse($shortBinary));
159
+ }
160
+
161
+ public function testParseReturnsNullOnInvalidRecordType(): void
162
+ {
163
+ // 0x17 au lieu de 0x16 (Application data au lieu de Handshake)
164
+ $invalidRecord = $this->buildMockClientHello();
165
+ $invalidRecord[0] = chr(0x17);
166
+
167
+ $this->assertNull(TLSClientHelloParser::parse($invalidRecord));
168
+ }
169
+
170
+ public function testParseReturnsNullOnInvalidHandshakeType(): void
171
+ {
172
+ // 0x02 au lieu de 0x01 (Server Hello au lieu de Client Hello)
173
+ $invalidHandshake = $this->buildMockClientHello();
174
+ $invalidHandshake[5] = chr(0x02);
175
+
176
+ $this->assertNull(TLSClientHelloParser::parse($invalidHandshake));
177
+ }
178
178
  }
@@ -1,4 +1,4 @@
1
- {
2
- "privateKey": "-----BEGIN PRIVATE KEY-----\\ndummy-php-private\\n-----END PRIVATE KEY-----",
3
- "publicKey": "-----BEGIN PUBLIC KEY-----\\ndummy-php-public\\n-----END PUBLIC KEY-----"
1
+ {
2
+ "privateKey": "-----BEGIN PRIVATE KEY-----\\ndummy-php-private\\n-----END PRIVATE KEY-----",
3
+ "publicKey": "-----BEGIN PUBLIC KEY-----\\ndummy-php-public\\n-----END PUBLIC KEY-----"
4
4
  }
@@ -1,50 +1,50 @@
1
- <?php
2
-
3
- declare(strict_types=1);
4
-
5
- namespace Anonympins\Fingerprint\Utils;
6
-
7
- class Env
8
- {
9
- /** @var array<string, mixed> */
10
- private static array $localCache = [];
11
-
12
- /**
13
- * @param string $key
14
- * @param mixed $default
15
- * @return mixed
16
- */
17
- public static function get(string $key, $default = null)
18
- {
19
- if (array_key_exists($key, self::$localCache)) {
20
- return self::$localCache[$key];
21
- }
22
- if (isset($_ENV[$key]) && $_ENV[$key] !== '') {
23
- return $_ENV[$key];
24
- }
25
- if (isset($_SERVER[$key]) && $_SERVER[$key] !== '') {
26
- return $_SERVER[$key];
27
- }
28
- $val = getenv($key);
29
- if ($val !== false && $val !== '') {
30
- return $val;
31
- }
32
- return $default;
33
- }
34
-
35
- public static function set(string $key, $value): void
36
- {
37
- self::$localCache[$key] = $value;
38
- $_ENV[$key] = $value;
39
- $_SERVER[$key] = $value;
40
- @putenv("{$key}={$value}");
41
- }
42
-
43
- public static function clear(string $key): void
44
- {
45
- unset(self::$localCache[$key]);
46
- unset($_ENV[$key]);
47
- unset($_SERVER[$key]);
48
- @putenv($key);
49
- }
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Utils;
6
+
7
+ class Env
8
+ {
9
+ /** @var array<string, mixed> */
10
+ private static array $localCache = [];
11
+
12
+ /**
13
+ * @param string $key
14
+ * @param mixed $default
15
+ * @return mixed
16
+ */
17
+ public static function get(string $key, $default = null)
18
+ {
19
+ if (array_key_exists($key, self::$localCache)) {
20
+ return self::$localCache[$key];
21
+ }
22
+ if (isset($_ENV[$key]) && $_ENV[$key] !== '') {
23
+ return $_ENV[$key];
24
+ }
25
+ if (isset($_SERVER[$key]) && $_SERVER[$key] !== '') {
26
+ return $_SERVER[$key];
27
+ }
28
+ $val = getenv($key);
29
+ if ($val !== false && $val !== '') {
30
+ return $val;
31
+ }
32
+ return $default;
33
+ }
34
+
35
+ public static function set(string $key, $value): void
36
+ {
37
+ self::$localCache[$key] = $value;
38
+ $_ENV[$key] = $value;
39
+ $_SERVER[$key] = $value;
40
+ @putenv("{$key}={$value}");
41
+ }
42
+
43
+ public static function clear(string $key): void
44
+ {
45
+ unset(self::$localCache[$key]);
46
+ unset($_ENV[$key]);
47
+ unset($_SERVER[$key]);
48
+ @putenv($key);
49
+ }
50
50
  }
@@ -1,75 +1,75 @@
1
- <?php
2
-
3
- declare(strict_types=1);
4
-
5
- namespace Anonympins\Fingerprint\Utils;
6
-
7
- /**
8
- * Fournit des fonctions pour détecter les patterns d'injection malveillants.
9
- */
10
- class MaliciousPatterns
11
- {
12
- /**
13
- * @var array<string, string> Map des patterns malveillants regroupés par type.
14
- */
15
- private const INJECTION_PATTERNS = [
16
- // SQL/NoSQL injections, including time-based attacks
17
- 'sql' => '/(\$ne|\' *OR *\'1\'=\'1|[\'";]\s*--|; ?(DROP|TRUNCATE|DELETE)|UNION SELECT|(?:SLEEP|BENCHMARK)\s*\(|WAITFOR DELAY)/i',
18
- // Log4Shell (JNDI injection)
19
- 'log4shell' => '/\$\{jndi:(ldap|rmi|dns):/i',
20
- // Server-Side Template Injection (SSTI) for engines like Jinja2, Twig, etc.
21
- 'ssti' => '/\{\{.*\}\}|\{%.*%\}/',
22
- // XML External Entity (XXE) injection
23
- 'xxe' => '/<!ENTITY\s+.*SYSTEM/i',
24
- // Path Traversal
25
- 'traversal' => '/(\.\.\/|\.\.)/',
26
- // Remote Command Execution (RCE)
27
- // The original regex had an issue with `|cmd` being interpreted as a modifier in some PCRE versions.
28
- // Using a non-capturing group (?:...) makes it more robust and fixes the compilation error.
29
- 'rce' => '/`.*`|(?:^|[\n;&|]\s*)(?:ping|ls|whoami|cat|rm|ncat|nc|bash|sh|powershell|cmd)\b/i',
30
- // Server-Side Request Forgery (SSRF)
31
- 'ssrf' => '/(?:https?:\/\/)?(?:127\.\d+\.\d+\.\d+|169\.254\.169\.254|10\.\d+\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+|192\.168\.\d+\.\d+|localhost|0\.0\.0\.0|\[[0:]+1\])\b/i',
32
- // Carriage Return Line Feed (CRLF) Injection
33
- 'crlf' => '/[\r\n]|%0[ad]/i',
34
- // Cross-Site Scripting (XSS)
35
- 'xss' => '/(<script|javascript:|on\w+\s*=|alert\s*\(|confirm\s*\(|prompt\s*\(|<img\s+src[^>]+onerror|<iframe)/i',
36
- // Open Redirect
37
- 'openRedirect' => '/^(https?:)?\/\/(?![^\/]*?(localhost|127\.0\.0\.1))[^\s\/]+/i',
38
- // Local/Remote File Inclusion (LFI/RFI)
39
- 'lfi' => '/(?:etc\/passwd|win\.ini|boot\.ini|php:\/\/filter|data:\/\/|zip:\/\/)/i',
40
- // Shellshock (CVE-2014-6271)
41
- 'shellshock' => '/\(\)\s*\{\s*:\s*;\s*\}\s*/i',
42
- // NoSQL Injection (MongoDB query operators)
43
- 'nosql' => '/\$(?:eq|ne|gt|gte|lt|lte|in|nin|and|or|nor|not|expr|jsonSchema|mod|regex|text|where|elemMatch)/i',
44
- ];
45
-
46
- /**
47
- * Vérifie si une chaîne de caractères contient des patterns d'injection connus.
48
- * @param string $str La chaîne à vérifier.
49
- * @param array<string> $typesToDetect Les types d'injections à détecter (par défaut, tous).
50
- * @return bool True si un pattern malveillant est détecté, false sinon.
51
- */
52
- public static function isMalicious(string $str, array $typesToDetect = []): bool
53
- {
54
- if (empty($typesToDetect)) {
55
- $typesToDetect = array_filter(array_keys(self::INJECTION_PATTERNS), function ($key) {
56
- return $key !== 'openRedirect';
57
- });
58
- }
59
-
60
- foreach ($typesToDetect as $type) {
61
- if (isset(self::INJECTION_PATTERNS[$type])) {
62
- try {
63
- if (preg_match(self::INJECTION_PATTERNS[$type], $str)) {
64
- return true;
65
- }
66
- }catch (\Exception $e){
67
- error_log($type);
68
- error_log($e->getMessage());
69
- }
70
- }
71
- }
72
-
73
- return false;
74
- }
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Utils;
6
+
7
+ /**
8
+ * Fournit des fonctions pour détecter les patterns d'injection malveillants.
9
+ */
10
+ class MaliciousPatterns
11
+ {
12
+ /**
13
+ * @var array<string, string> Map des patterns malveillants regroupés par type.
14
+ */
15
+ private const INJECTION_PATTERNS = [
16
+ // SQL/NoSQL injections, including time-based attacks
17
+ 'sql' => '/(\$ne|\' *OR *\'1\'=\'1|[\'";]\s*--|; ?(DROP|TRUNCATE|DELETE)|UNION SELECT|(?:SLEEP|BENCHMARK)\s*\(|WAITFOR DELAY)/i',
18
+ // Log4Shell (JNDI injection)
19
+ 'log4shell' => '/\$\{jndi:(ldap|rmi|dns):/i',
20
+ // Server-Side Template Injection (SSTI) for engines like Jinja2, Twig, etc.
21
+ 'ssti' => '/\{\{.*\}\}|\{%.*%\}/',
22
+ // XML External Entity (XXE) injection
23
+ 'xxe' => '/<!ENTITY\s+.*SYSTEM/i',
24
+ // Path Traversal
25
+ 'traversal' => '/(\.\.\/|\.\.)/',
26
+ // Remote Command Execution (RCE)
27
+ // The original regex had an issue with `|cmd` being interpreted as a modifier in some PCRE versions.
28
+ // Using a non-capturing group (?:...) makes it more robust and fixes the compilation error.
29
+ 'rce' => '/`.*`|(?:^|[\n;&|]\s*)(?:ping|ls|whoami|cat|rm|ncat|nc|bash|sh|powershell|cmd)\b/i',
30
+ // Server-Side Request Forgery (SSRF)
31
+ 'ssrf' => '/(?:https?:\/\/)?(?:127\.\d+\.\d+\.\d+|169\.254\.169\.254|10\.\d+\.\d+\.\d+|172\.(?:1[6-9]|2\d|3[01])\.\d+\.\d+|192\.168\.\d+\.\d+|localhost|0\.0\.0\.0|\[[0:]+1\])\b/i',
32
+ // Carriage Return Line Feed (CRLF) Injection
33
+ 'crlf' => '/[\r\n]|%0[ad]/i',
34
+ // Cross-Site Scripting (XSS)
35
+ 'xss' => '/(<script|javascript:|on\w+\s*=|alert\s*\(|confirm\s*\(|prompt\s*\(|<img\s+src[^>]+onerror|<iframe)/i',
36
+ // Open Redirect
37
+ 'openRedirect' => '/^(https?:)?\/\/(?![^\/]*?(localhost|127\.0\.0\.1))[^\s\/]+/i',
38
+ // Local/Remote File Inclusion (LFI/RFI)
39
+ 'lfi' => '/(?:etc\/passwd|win\.ini|boot\.ini|php:\/\/filter|data:\/\/|zip:\/\/)/i',
40
+ // Shellshock (CVE-2014-6271)
41
+ 'shellshock' => '/\(\)\s*\{\s*:\s*;\s*\}\s*/i',
42
+ // NoSQL Injection (MongoDB query operators)
43
+ 'nosql' => '/\$(?:eq|ne|gt|gte|lt|lte|in|nin|and|or|nor|not|expr|jsonSchema|mod|regex|text|where|elemMatch)/i',
44
+ ];
45
+
46
+ /**
47
+ * Vérifie si une chaîne de caractères contient des patterns d'injection connus.
48
+ * @param string $str La chaîne à vérifier.
49
+ * @param array<string> $typesToDetect Les types d'injections à détecter (par défaut, tous).
50
+ * @return bool True si un pattern malveillant est détecté, false sinon.
51
+ */
52
+ public static function isMalicious(string $str, array $typesToDetect = []): bool
53
+ {
54
+ if (empty($typesToDetect)) {
55
+ $typesToDetect = array_filter(array_keys(self::INJECTION_PATTERNS), function ($key) {
56
+ return $key !== 'openRedirect';
57
+ });
58
+ }
59
+
60
+ foreach ($typesToDetect as $type) {
61
+ if (isset(self::INJECTION_PATTERNS[$type])) {
62
+ try {
63
+ if (preg_match(self::INJECTION_PATTERNS[$type], $str)) {
64
+ return true;
65
+ }
66
+ }catch (\Exception $e){
67
+ error_log($type);
68
+ error_log($e->getMessage());
69
+ }
70
+ }
71
+ }
72
+
73
+ return false;
74
+ }
75
75
  }