@anonympins/fingerprint 0.7.0 → 0.7.2

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 (66) hide show
  1. package/CHANGELOG.md +29 -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 +190 -16
  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 +124 -10
  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 +57 -11
  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 +44 -17
  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 +38 -0
  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/BlockList.php +99 -99
  54. package/src/php/Utils/Env.php +49 -49
  55. package/src/php/Utils/MaliciousPatterns.php +74 -74
  56. package/src/php/Utils/MetricsManager.php +209 -209
  57. package/src/php/Utils/RequestUtils.php +129 -7
  58. package/src/php/Utils/TLSClientHelloParser.php +369 -369
  59. package/src/php/WordPress/WpDbStore.php +155 -0
  60. package/src/php/WordPress/fingerprint-wordpress.php +554 -0
  61. package/src/php/WordPress/languages/fingerprint-wordpress-de_DE.mo +0 -0
  62. package/src/php/WordPress/languages/fingerprint-wordpress-de_DE.po +262 -0
  63. package/src/php/WordPress/languages/fingerprint-wordpress-fr_FR.mo +0 -0
  64. package/src/php/WordPress/languages/fingerprint-wordpress-fr_FR.po +268 -0
  65. package/src/php/WordPress/package.php +218 -0
  66. 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,100 +1,100 @@
1
- <?php
2
-
3
- declare(strict_types=1);
4
-
5
- namespace Anonympins\Fingerprint\Utils;
6
-
7
- /**
8
- * Implémentation PHP d'une liste de blocage IP/CIDR, similaire à Node.js `net.BlockList`.
9
- */
10
- class BlockList
11
- {
12
- /**
13
- * @var array<string> Liste des IPs ou CIDR à bloquer.
14
- */
15
- private array $entries = [];
16
-
17
- /**
18
- * Ajoute une adresse IP ou une plage CIDR à la liste.
19
- * @param string $entry Une adresse IP (ex: '192.168.1.1') ou une plage CIDR (ex: '192.168.1.0/24').
20
- * @return void
21
- */
22
- public function add(string $entry): void
23
- {
24
- $this->entries[] = $entry;
25
- }
26
-
27
- /**
28
- * Vérifie si une adresse IP est présente dans la liste de blocage.
29
- * @param string $ip L'adresse IP à vérifier.
30
- * @return bool True si l'IP est bloquée, false sinon.
31
- */
32
- public function check(string $ip): bool
33
- {
34
- foreach ($this->entries as $entry) {
35
- if (str_contains($entry, '/')) {
36
- // C'est une plage CIDR
37
- if ($this->ipInCidr($ip, $entry)) {
38
- return true;
39
- }
40
- } else {
41
- // C'est une IP directe
42
- if ($ip === $entry) {
43
- return true;
44
- }
45
- }
46
- }
47
- return false;
48
- }
49
-
50
- /**
51
- * Vérifie si une adresse IP se trouve dans une plage CIDR donnée.
52
- * @param string $ip L'adresse IP à vérifier.
53
- * @param string $cidr La plage CIDR (ex: '192.168.1.0/24').
54
- * @return bool True si l'IP est dans la plage, false sinon.
55
- */
56
- private function ipInCidr(string $ip, string $cidr): bool
57
- {
58
- [$network, $mask] = explode('/', $cidr);
59
- $mask = (int)$mask;
60
-
61
- if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
62
- // IPv6
63
- $ipBinary = inet_pton($ip);
64
- $networkBinary = inet_pton($network);
65
-
66
- if ($ipBinary === false || $networkBinary === false) {
67
- return false;
68
- }
69
-
70
- $ipHex = bin2hex($ipBinary);
71
- $networkHex = bin2hex($networkBinary);
72
-
73
- $numBytes = (int)ceil($mask / 8);
74
- $compareLength = $numBytes * 2;
75
-
76
- if (substr($ipHex, 0, $compareLength) !== substr($networkHex, 0, $compareLength)) {
77
- return false;
78
- }
79
-
80
- if ($mask % 8 !== 0) {
81
- $bitMask = (0xFF << (8 - ($mask % 8))) & 0xFF;
82
- $ipByte = hexdec(substr($ipHex, $numBytes * 2 - 2, 2));
83
- $networkByte = hexdec(substr($networkHex, $numBytes * 2 - 2, 2));
84
- return ($ipByte & $bitMask) === ($networkByte & $bitMask);
85
- }
86
-
87
- return true;
88
-
89
- } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
90
- // IPv4
91
- $ipLong = ip2long($ip);
92
- $networkLong = ip2long($network);
93
- $wildcard = pow(2, (32 - $mask)) - 1;
94
- $netmask = ~$wildcard;
95
- return (($ipLong & $netmask) === ($networkLong & $netmask));
96
- }
97
-
98
- return false;
99
- }
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Utils;
6
+
7
+ /**
8
+ * Implémentation PHP d'une liste de blocage IP/CIDR, similaire à Node.js `net.BlockList`.
9
+ */
10
+ class BlockList
11
+ {
12
+ /**
13
+ * @var array<string> Liste des IPs ou CIDR à bloquer.
14
+ */
15
+ private array $entries = [];
16
+
17
+ /**
18
+ * Ajoute une adresse IP ou une plage CIDR à la liste.
19
+ * @param string $entry Une adresse IP (ex: '192.168.1.1') ou une plage CIDR (ex: '192.168.1.0/24').
20
+ * @return void
21
+ */
22
+ public function add(string $entry): void
23
+ {
24
+ $this->entries[] = $entry;
25
+ }
26
+
27
+ /**
28
+ * Vérifie si une adresse IP est présente dans la liste de blocage.
29
+ * @param string $ip L'adresse IP à vérifier.
30
+ * @return bool True si l'IP est bloquée, false sinon.
31
+ */
32
+ public function check(string $ip): bool
33
+ {
34
+ foreach ($this->entries as $entry) {
35
+ if (str_contains($entry, '/')) {
36
+ // C'est une plage CIDR
37
+ if ($this->ipInCidr($ip, $entry)) {
38
+ return true;
39
+ }
40
+ } else {
41
+ // C'est une IP directe
42
+ if ($ip === $entry) {
43
+ return true;
44
+ }
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+
50
+ /**
51
+ * Vérifie si une adresse IP se trouve dans une plage CIDR donnée.
52
+ * @param string $ip L'adresse IP à vérifier.
53
+ * @param string $cidr La plage CIDR (ex: '192.168.1.0/24').
54
+ * @return bool True si l'IP est dans la plage, false sinon.
55
+ */
56
+ private function ipInCidr(string $ip, string $cidr): bool
57
+ {
58
+ // Handle IPv4-mapped IPv6 addresses by converting them to IPv4
59
+ if (str_starts_with(strtolower($ip), '::ffff:') && filter_var(substr($ip, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
60
+ $ip = substr($ip, 7);
61
+ }
62
+
63
+ [$network, $mask] = explode('/', $cidr, 2);
64
+ $mask = (int)$mask;
65
+
66
+ // Now, both $ip and $network should be in the same family for a valid comparison
67
+ if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
68
+ if ($mask < 0 || $mask > 32) { return false; }
69
+ $ipLong = ip2long($ip);
70
+ $networkLong = ip2long($network);
71
+ if ($ipLong === false || $networkLong === false) return false;
72
+ $netmask = -1 << (32 - $mask);
73
+ return ($ipLong & $netmask) === ($networkLong & $netmask);
74
+ } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
75
+ // IPv6 vs IPv6 CIDR
76
+ if ($mask < 0 || $mask > 128) { return false; }
77
+ $ipBinary = inet_pton($ip);
78
+ $networkBinary = inet_pton($network);
79
+ if ($ipBinary === false || $networkBinary === false) return false;
80
+
81
+ $bytesToCompare = (int)floor($mask / 8);
82
+ if (strncmp($ipBinary, $networkBinary, $bytesToCompare) !== 0) {
83
+ return false;
84
+ }
85
+
86
+ $bitsToCompare = $mask % 8;
87
+ if ($bitsToCompare > 0) {
88
+ $byteIndex = $bytesToCompare;
89
+ $bitmask = (0xFF << (8 - $bitsToCompare)) & 0xFF;
90
+ if ((ord($ipBinary[$byteIndex]) & $bitmask) !== (ord($networkBinary[$byteIndex]) & $bitmask)) {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ return true;
96
+ }
97
+
98
+ return false;
99
+ }
100
100
  }