@anonympins/fingerprint 0.5.2 → 0.5.4

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 (35) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/package.json +1 -1
  3. package/src/js/fingerprint.client.js +1271 -1191
  4. package/src/js/fingerprint.js +202 -108
  5. package/src/js/fingerprint.utils.js +213 -213
  6. package/src/js/library.js +24 -8
  7. package/src/js/mongodb-store.js +165 -79
  8. package/src/js/pow.solver.inline.js +500 -14
  9. package/src/js/pow.solver.js +323 -14
  10. package/src/js/problem-manager.js +1 -1
  11. package/src/js/redis-store.js +114 -42
  12. package/src/js/tests/dns-circuit-breaker.test.js +55 -0
  13. package/src/js/tests/fingerprint.client.init.test.js +143 -143
  14. package/src/js/tests/fingerprint.client.test.js +128 -128
  15. package/src/js/tests/fingerprint.test.js +32 -2
  16. package/src/js/tests/ip-reputation.test.js +1 -1
  17. package/src/js/tests/pow.solver.test.js +5 -2
  18. package/src/js/tests/usefulWorkSolver.test.js +162 -0
  19. package/src/php/Challenge/ChallengeUtils.php +21 -8
  20. package/src/php/FingerprintClient.php +22 -5
  21. package/src/php/FingerprintEngine.php +232 -56
  22. package/src/php/Optimization/Optimization.php +23 -16
  23. package/src/php/Optimization/OptimizationOperators.php +27 -0
  24. package/src/php/ProblemManager.php +1 -1
  25. package/src/php/Store/MongoDbStore.php +184 -104
  26. package/src/php/Store/RedisStore.php +91 -11
  27. package/src/php/Tests/ChallengeUtilsTest.php +285 -285
  28. package/src/php/Tests/DnsCircuitBreakerTest.php +106 -0
  29. package/src/php/Tests/IpReputationTest.php +1 -1
  30. package/src/php/Tests/PowTest.php +1 -1
  31. package/src/php/Tests/RequestUtilsTest.php +29 -0
  32. package/src/php/Tests/TLSClientHelloParserTest.php +177 -117
  33. package/src/php/Utils/BigInt.php +202 -202
  34. package/src/php/Utils/RequestUtils.php +74 -21
  35. package/src/php/Utils/TLSClientHelloParser.php +212 -116
@@ -0,0 +1,106 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Tests;
6
+
7
+ use Anonympins\Fingerprint\FingerprintEngine;
8
+ use PHPUnit\Framework\TestCase;
9
+ use ReflectionClass;
10
+
11
+ class DnsCircuitBreakerTest extends TestCase
12
+ {
13
+ private ReflectionClass $reflection;
14
+
15
+ protected function setUp(): void
16
+ {
17
+ parent::setUp();
18
+ $this->reflection = new ReflectionClass(FingerprintEngine::class);
19
+
20
+ // Réinitialise l'état statique du disjoncteur avant chaque test
21
+ $this->setCircuitBreakerState([
22
+ 'state' => 'CLOSED',
23
+ 'failureCount' => 0,
24
+ 'lastStateChange' => 0,
25
+ 'threshold' => 5,
26
+ 'cooldown' => 1, // 1 seconde de cooldown pour accélérer le test
27
+ ]);
28
+ }
29
+
30
+ private function getCircuitBreakerState(): array
31
+ {
32
+ $property = $this->reflection->getProperty('dnsCircuitBreaker');
33
+ if (PHP_VERSION_ID < 80100) {
34
+ $property->setAccessible(true);
35
+ }
36
+ return $property->getValue();
37
+ }
38
+
39
+ private function setCircuitBreakerState(array $state): void
40
+ {
41
+ $property = $this->reflection->getProperty('dnsCircuitBreaker');
42
+ if (PHP_VERSION_ID < 80100) {
43
+ $property->setAccessible(true);
44
+ }
45
+ $property->setValue(null, $state);
46
+ }
47
+
48
+ private function invokeMethod(string $methodName, array $args = [])
49
+ {
50
+ $method = $this->reflection->getMethod($methodName);
51
+ if (PHP_VERSION_ID < 80100) { // PHP 8.1.0
52
+ $method->setAccessible(true);
53
+ }
54
+ return $method->invokeArgs(null, $args);
55
+ }
56
+
57
+ public function testInitialStateIsClosed(): void
58
+ {
59
+ $this->assertTrue($this->invokeMethod('canAttemptDns'));
60
+ $state = $this->getCircuitBreakerState();
61
+ $this->assertSame('CLOSED', $state['state']);
62
+ }
63
+
64
+ public function testFailureThresholdTripsBreaker(): void
65
+ {
66
+ for ($i = 0; $i < 4; $i++) {
67
+ $this->invokeMethod('recordDnsFailure');
68
+ $this->assertTrue($this->invokeMethod('canAttemptDns'));
69
+ $state = $this->getCircuitBreakerState();
70
+ $this->assertSame('CLOSED', $state['state']);
71
+ }
72
+
73
+ $this->invokeMethod('recordDnsFailure');
74
+ $this->assertFalse($this->invokeMethod('canAttemptDns'));
75
+ $state = $this->getCircuitBreakerState();
76
+ $this->assertSame('OPEN', $state['state']);
77
+ }
78
+
79
+ public function testCooldownTransitionsToHalfOpen(): void
80
+ {
81
+ for ($i = 0; $i < 5; $i++) {
82
+ $this->invokeMethod('recordDnsFailure');
83
+ }
84
+ $this->assertFalse($this->invokeMethod('canAttemptDns'));
85
+
86
+ usleep(1100000); // 1.1s
87
+
88
+ $this->assertTrue($this->invokeMethod('canAttemptDns'));
89
+ $state = $this->getCircuitBreakerState();
90
+ $this->assertSame('HALF-OPEN', $state['state']);
91
+ }
92
+
93
+ public function testSuccessOnHalfOpenResetsBreaker(): void
94
+ {
95
+ for ($i = 0; $i < 5; $i++) {
96
+ $this->invokeMethod('recordDnsFailure');
97
+ }
98
+ usleep(1100000);
99
+ $this->assertTrue($this->invokeMethod('canAttemptDns'));
100
+
101
+ $this->invokeMethod('recordDnsSuccess');
102
+ $state = $this->getCircuitBreakerState();
103
+ $this->assertSame('CLOSED', $state['state']);
104
+ $this->assertSame(0, $state['failureCount']);
105
+ }
106
+ }
@@ -106,7 +106,7 @@ class IpReputationTest extends TestCase
106
106
  $this->assertEquals('192.168.1.0/24', $ipv4Subnet);
107
107
 
108
108
  $ipv6Subnet = RequestUtils::getIpSubnet('2001:db8:abcd:0012::1', 24, 48);
109
- $this->assertEquals('2001:db8:abcd::/48', $ipv6Subnet);
109
+ $this->assertEquals('2001:0db8:abcd:0000:0000:0000:0000:0000/48', $ipv6Subnet);
110
110
  }
111
111
 
112
112
  public function testGetClientHintsInconsistencyScoreMismatch(): void
@@ -23,7 +23,7 @@ class PowTest extends TestCase
23
23
 
24
24
  // 2. Initialiser le ProblemManager avec une configuration et un store valides.
25
25
  // C'est l'étape cruciale qui manquait.
26
- $configPath = dirname(__FILE__) . '/problems.config.json';
26
+ $configPath = dirname(__FILE__) . '/config/problems.config.json';
27
27
  ProblemManager::getInstance($configPath, $store);
28
28
 
29
29
  // 3. Créer l'instance du moteur.
@@ -141,6 +141,35 @@ class RequestUtilsTest extends TestCase
141
141
  $this->assertLessThanOrEqual(3, count($attackerLogs));
142
142
  }
143
143
 
144
+ public function testSanitizeTrafficDataFiltersHardwareClusters(): void
145
+ {
146
+ $trafficData = [];
147
+ // Simulated attacker rotating deviceId and IP, but keeping identical hardware fingerprint
148
+ for ($i = 0; $i < 100; $i++) {
149
+ $trafficData[] = [
150
+ 'deviceId' => "attacker_device_{$i}",
151
+ 'clientIp' => "192.168.1.{$i}",
152
+ 'type' => 'trap_triggered',
153
+ 'fingerprint' => 'gpu:heavy_nvidia_hash|cvs:canvas_hash_1'
154
+ ];
155
+ }
156
+ // Legit users with unique hardware fingerprints
157
+ for ($i = 0; $i < 10; $i++) {
158
+ $trafficData[] = [
159
+ 'deviceId' => "legit_device_{$i}",
160
+ 'clientIp' => "10.0.0.{$i}",
161
+ 'type' => 'challenge_solved',
162
+ 'fingerprint' => "gpu:legit_gpu_{$i}|cvs:legit_cvs_{$i}"
163
+ ];
164
+ }
165
+
166
+ $sanitized = RequestUtils::sanitizeTrafficData($trafficData);
167
+ $attackerLogs = array_filter($sanitized, fn($log) => str_starts_with($log['deviceId'], 'attacker_device_'));
168
+
169
+ // Max limit of 2% of 110 total = 2.2 -> max(3, 2) = 3 logs allowed for this hardware cluster
170
+ $this->assertLessThanOrEqual(3, count($attackerLogs));
171
+ }
172
+
144
173
  public function testChallengePayloadSigningAndVerification(): void
145
174
  {
146
175
  $secret = 'test-fallback-dev-secret-32-chars-minimum';
@@ -1,118 +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 testParseReturnsNullWhenPacketTooShort(): void
96
- {
97
- $shortBinary = str_repeat("\x16", 40);
98
- $this->assertNull(TLSClientHelloParser::parse($shortBinary));
99
- }
100
-
101
- public function testParseReturnsNullOnInvalidRecordType(): void
102
- {
103
- // 0x17 au lieu de 0x16 (Application data au lieu de Handshake)
104
- $invalidRecord = $this->buildMockClientHello();
105
- $invalidRecord[0] = chr(0x17);
106
-
107
- $this->assertNull(TLSClientHelloParser::parse($invalidRecord));
108
- }
109
-
110
- public function testParseReturnsNullOnInvalidHandshakeType(): void
111
- {
112
- // 0x02 au lieu de 0x01 (Server Hello au lieu de Client Hello)
113
- $invalidHandshake = $this->buildMockClientHello();
114
- $invalidHandshake[5] = chr(0x02);
115
-
116
- $this->assertNull(TLSClientHelloParser::parse($invalidHandshake));
117
- }
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
+ }
118
178
  }