twitter-generator 1.0.0__tar.gz

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 (26) hide show
  1. twitter_generator-1.0.0/LEARN.md +1008 -0
  2. twitter_generator-1.0.0/LICENSE +21 -0
  3. twitter_generator-1.0.0/MANIFEST.in +9 -0
  4. twitter_generator-1.0.0/PKG-INFO +201 -0
  5. twitter_generator-1.0.0/README.md +165 -0
  6. twitter_generator-1.0.0/pyproject.toml +69 -0
  7. twitter_generator-1.0.0/requirements.txt +2 -0
  8. twitter_generator-1.0.0/setup.cfg +4 -0
  9. twitter_generator-1.0.0/setup.py +7 -0
  10. twitter_generator-1.0.0/tests/test_client_transaction.py +11 -0
  11. twitter_generator-1.0.0/tests/test_xp_forwarded_for.py +21 -0
  12. twitter_generator-1.0.0/twitter_generator/__init__.py +15 -0
  13. twitter_generator-1.0.0/twitter_generator/client_transaction/__init__.py +3 -0
  14. twitter_generator-1.0.0/twitter_generator/client_transaction/main.py +146 -0
  15. twitter_generator-1.0.0/twitter_generator/exceptions.py +11 -0
  16. twitter_generator-1.0.0/twitter_generator/helpers/__init__.py +4 -0
  17. twitter_generator-1.0.0/twitter_generator/helpers/cubic.py +72 -0
  18. twitter_generator-1.0.0/twitter_generator/helpers/math_utils.py +138 -0
  19. twitter_generator-1.0.0/twitter_generator/version.py +3 -0
  20. twitter_generator-1.0.0/twitter_generator/xp_forwarded_for/__init__.py +3 -0
  21. twitter_generator-1.0.0/twitter_generator/xp_forwarded_for/main.py +235 -0
  22. twitter_generator-1.0.0/twitter_generator.egg-info/PKG-INFO +201 -0
  23. twitter_generator-1.0.0/twitter_generator.egg-info/SOURCES.txt +24 -0
  24. twitter_generator-1.0.0/twitter_generator.egg-info/dependency_links.txt +1 -0
  25. twitter_generator-1.0.0/twitter_generator.egg-info/requires.txt +9 -0
  26. twitter_generator-1.0.0/twitter_generator.egg-info/top_level.txt +1 -0
@@ -0,0 +1,1008 @@
1
+ # How did we get here?
2
+
3
+ ![How did we get here?](./images/hdwgh.png)
4
+
5
+ Let's break down each header's generation
6
+
7
+ <div align="center">
8
+ <img src="https://img.shields.io/badge/Status-Complete-brightgreen" alt="Status: Complete">
9
+ <img src="https://img.shields.io/badge/Type-Research-blue" alt="Type: Research">
10
+ <img src="https://img.shields.io/badge/License-MIT-yellow" alt="License: MIT">
11
+ <a href="https://www.npmjs.com/package/twitter_headers_generator"><img src="https://img.shields.io/npm/v/twitter_headers_generator.svg?style=flat-square&color=cb3837&logo=npm" alt="npm version"></a>
12
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator"><img src="https://img.shields.io/github/stars/GlizzyKingDreko/twitter_headers_generator?style=flat-square&logo=github" alt="GitHub stars"></a>
13
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator"><img src="https://img.shields.io/badge/GitHub-Repo-black?logo=github&style=flat-square" alt="GitHub repo"></a>
14
+ </div>
15
+
16
+ <br>
17
+
18
+ <div align="center">
19
+ <a href="https://github.com/GlizzyKingDreko/twitter_headers_generator-python"><img src="https://img.shields.io/badge/Check%20the%20Python%20version-purple?logo=python&style=flat-square" alt="Check the Python version"></a>
20
+ <a href="https://medium.com/@glizzykingdreko/breaking-down-datadome-captcha-waf-d7b68cef3e21"><img src="https://img.shields.io/badge/Read%20the%20full%20article%20on%20Medium-12100E?logo=medium&logoColor=white&style=flat-square" alt="Read the full article on Medium"></a>
21
+ <a href="https://buymeacoffee.com/glizzykingdreko"><img src="https://img.shields.io/badge/Support%20my%20researches%20by%20buying%20me%20a%20coffee-242424?style=flat-square&logo=buy-me-a-coffee&logoColor=yellow&labelColor=222&color=222" alt="Support my researches by buying me a coffee"></a>
22
+ </div>
23
+ <br>
24
+
25
+ ## Table of Contents
26
+
27
+ 1. [Before starting](#before-starting)
28
+ 2. [X-Client-Transaction-Id](#x-client-transaction-id)
29
+ 3. [X-Xp-Forwarded-For](#x-xp-forwarded-for)
30
+ - [Step 1: Extracting the WASM Binary](#step-1-extracting-the-wasm-binary)
31
+ - [Step 2: Converting WASM to WAT](#step-2-converting-wasm-to-wat)
32
+ - [Step 3: Analyzing WASM Structure](#step-3-analyzing-wasm-structure)
33
+ - [Step 4: Extracting Embedded Strings](#step-4-extracting-embedded-strings)
34
+ - [Step 5: Understanding the Go Runtime](#step-5-understanding-the-go-runtime)
35
+ - [Step 6: Identifying the Core Algorithm](#step-6-identifying-the-core-algorithm)
36
+ - [Step 7: Key Derivation Discovery (guest_id)](#step-7-key-derivation-discovery-guest_id)
37
+ - [Step 8: Recreating the JavaScript Implementation](#step-8-recreating-the-javascript-implementation)
38
+ - [Step 9: Validation](#step-9-validation)
39
+ - [Step 10: Multi-Language Implementations](#step-10-multi-language-implementations)
40
+ 4. [Author](#author)
41
+
42
+
43
+
44
+ ## Before starting
45
+ This is the first of a 3 episodes series about X (former Twitter) login flow protections.
46
+
47
+ Be sure to check the related [Medium Article](https://medium.com/@glizzykingdreko/breaking-down-datadome-captcha-waf-d7b68cef3e21) and subscribe to my newsletter (from Medium) in order to get notified when the next episode will be out (a follow on Github would make me happy too).
48
+
49
+ Next one is going to be about the first antibot challenge.
50
+
51
+ ## X-Client-Transaction-Id
52
+
53
+ The flow for the generation of it is:
54
+
55
+ 1. Fetch [x.com](https://x.com/home) home page and extract the value of the meta tag named `twitter-site-verification`
56
+
57
+ 2. Get *_on demand url_* via a regex like `["']ondemand\.s["']\s*:\s*["']([\w]+)["']` and load it
58
+
59
+ 3. Generation process
60
+
61
+ In few words is based on a hash that looks like
62
+ ```py
63
+ f"{method}!{path}!{time_now}obfiowerehiring{animation_key}"
64
+ ```
65
+
66
+ Where
67
+ | Key | Description |
68
+ |-----|-------------|
69
+ |method | Request method (POST/GET/...) |
70
+ |path | Endpoint where u sending the request (Ex. `https://api.x.com/1.1/onboarding/task.json` ) |
71
+ |time now | Current timestamp offset |
72
+ | animation_key | Generated based on the extracted key from the *_on demand url_* and the `twitter-site-verification` |
73
+
74
+ That is then XOR encoded and converted to b64
75
+
76
+ So, each time a request will be sent to X / Twitter a new token will be required since are based on the session (since we are extracting data from the loaded homepage and on demand url) as well as the current sending timestamp.
77
+
78
+ *Original code rewrote ina more uman-redable way*
79
+ ```js
80
+ // Calculate seconds elapsed since reference timestamp (April 2023)
81
+ var secondsSinceEpoch = Math.floor((Date.now() - 1682924400 * 1000) / 1000);
82
+
83
+ // Convert timestamp to bytes (Float64 → Uint8Array)
84
+ var timestampBytes = new Uint8Array(new Float64Array([secondsSinceEpoch]).buffer);
85
+
86
+ // Get fingerprint from DOM element
87
+ var fingerprint = new Uint8Array(atob(
88
+ document.querySelectorAll("[name^=tw]")[0].getAttribute("content")
89
+ )["split"]("")["map"](function (n) {
90
+ return n["charCodeAt"](0);
91
+ }));
92
+
93
+ var fingerprintHash = generateFingerprintHash(fingerprint);
94
+
95
+ // Random salt for the payload
96
+ var randomSalt = [Math.random() * 256];
97
+
98
+ // Convert fingerprint and timestamp to arrays
99
+ var fingerprintArray = Array.from(fingerprint);
100
+ var timestampArray = Array.from(timestampBytes);
101
+
102
+ // Build the hash input: "param2!param1!timestamp" + "obfiowerehiring" + fingerprintHash
103
+ var hashInput = [t, r, secondsSinceEpoch].join("!") + "obfiowerehiring" + fingerprintHash;
104
+
105
+ // Compute SHA-256 hash asynchronously
106
+ var hashResult = crypto.subtle.digest("sha-256", new TextEncoder().encode(hashInput));
107
+
108
+ // Build the final payload by concatenating:
109
+ // [randomSalt, fingerprintArray, timestampArray, transformed(slice16(arrayFrom(hashBytes).concat(HW))), 3]
110
+ var hashBytes = new Uint8Array(hashResult);
111
+ var hashArray = Array.from(hashBytes);
112
+ var transformed = hashArray.concat(HW)["slice"](0, Math.pow(2, 4)); // Take first 16 bytes
113
+
114
+ var payload = randomSalt.concat(fingerprintArray, timestampArray, transformed, [3]);
115
+
116
+ // Encode as base64 with optional XOR and return
117
+ var finalBytes = new Uint8Array(payload);
118
+
119
+ // base64 encode with optional XOR
120
+ MW = function (n, r, t) {
121
+ return r ? n ^ t[0] : n;
122
+ }
123
+ sW = function (n) {
124
+ return btoa(Array.from(n)["map"](function (n) {
125
+ return String["fromCharCode"](n);
126
+ })["join"](""))["replace"](/=/g, "");
127
+ }
128
+ var encoded = sW(finalBytes.map(MW));
129
+ ```
130
+ *([on demand url source](https://abs.twimg.com/responsive-web/client-web/ondemand.s.05fedcda.js) keep in mind tha the urls are dynamic)*
131
+
132
+ Check [out the full code of this implementation](./twitter_generator/client_transaction/main.py)
133
+
134
+
135
+ ## X-Xp-Forwarded-For
136
+
137
+ That's a bit harder.
138
+
139
+ So basically the javascript module `XPForwardedForSDK` [source](https://abs.twimg.com/responsive-web/client-web/loader.FwdForSdk.8ee16aca.js) (dynamic url/file)
140
+
141
+ After beeing initialized with some env details, is going to use a GO based WASM script in order to encrypt via `AES-256-GCM` a JSON payload by using a static key and the session cookie `guest_id` for **key derivation**.
142
+
143
+ Here it follows the full process that lead me to the understanding and debugging of it.
144
+
145
+
146
+ ### Step 1: Extracting the WASM Binary
147
+
148
+ #### Finding the WASM Bytes
149
+
150
+ The original [FwdForSdk](https://abs.twimg.com/responsive-web/client-web/loader.FwdForSdk.8ee16aca.js) file contains the WASM binary embedded as a byte array. Looking at the obfuscated code:
151
+
152
+ ```javascript
153
+ // Obfuscated structure
154
+ 864585: e => {
155
+ var t = new ArrayBuffer(372549);
156
+ new Uint8Array(t).set([0, 97, 115, 109, 1, 0, 0, 0, ...]);
157
+ // ... 372,549 bytes total
158
+ }
159
+ ```
160
+
161
+ #### Extraction Script
162
+
163
+ ```javascript
164
+ const fs = require('fs');
165
+ const code = fs.readFileSync('x_xp_forwarded_for.js', 'utf8');
166
+
167
+ // Find the WASM bytes array using regex
168
+ const match = code.match(
169
+ /864585:\s*e\s*=>\s*\{[^}]*var\s+t\s*=\s*new\s+ArrayBuffer\((\d+)\);\s*new\s+Uint8Array\(t\)\.set\(\[([^\]]+)\]/s
170
+ );
171
+
172
+ if (match) {
173
+ const size = parseInt(match[1]);
174
+ console.log('WASM size:', size, 'bytes');
175
+
176
+ // Parse the bytes
177
+ const allBytes = match[2].split(',').map(b => parseInt(b.trim()));
178
+ const buffer = Buffer.from(allBytes);
179
+
180
+ // Save to file
181
+ fs.writeFileSync('xpforwarded.wasm', buffer);
182
+ console.log('Saved to xpforwarded.wasm');
183
+ }
184
+ ```
185
+
186
+ #### Verifying the Magic Number
187
+
188
+ Every WASM file starts with the magic bytes `\0asm` (0x00 0x61 0x73 0x6d):
189
+
190
+ ```bash
191
+ $ xxd xpforwarded.wasm | head -1
192
+ 00000000: 0061 736d 0100 0000 0180 043c 6002 7f7f .asm.......<`.
193
+ ```
194
+
195
+ So it is valid.
196
+
197
+ ---
198
+
199
+ ### Step 2: Converting WASM to WAT
200
+
201
+ #### Using wasm2wat
202
+
203
+ `wasm2wat` is used to convert the WASM binary to readable text format
204
+
205
+ ```bash
206
+ $ wasm2wat xpforwarded.wasm -o xpforwarded.wat
207
+ ```
208
+
209
+ ---
210
+
211
+ ### Step 3: Analyzing WASM Structure
212
+
213
+ #### Examining Exports
214
+
215
+ ```wat
216
+ (export "memory" (memory 0))
217
+ (export "malloc" (func 429))
218
+ (export "free" (func 430))
219
+ (export "calloc" (func 431))
220
+ (export "realloc" (func 432))
221
+ (export "resume" (func 433))
222
+ (export "go_scheduler" (func 434))
223
+ (export "_start" (func 435))
224
+ (export "asyncify_start_unwind" (func 436))
225
+ (export "asyncify_stop_unwind" (func 437))
226
+ (export "asyncify_start_rewind" (func 438))
227
+ (export "asyncify_stop_rewind" (func 437))
228
+ (export "asyncify_get_state" (func 439))
229
+ ```
230
+
231
+ By just looking at those exports we can already understand that:
232
+ - `go_scheduler`: Go runtime's goroutine scheduler (so is a Go-based script)
233
+ - `malloc/free/calloc/realloc`: Memory management (standard C-style)
234
+ - `asyncify_*`: Binaryen asyncify transform for async JS interop
235
+
236
+ #### Examining Imports
237
+
238
+ ```wat
239
+ (import "gojs" "runtime.ticks" (func (;0;) (type 30)))
240
+ (import "wasi_snapshot_preview1" "fd_write" (func (;1;) (type 5)))
241
+ (import "gojs" "syscall/js.valueGet" (func (;2;) (type 31)))
242
+ (import "gojs" "syscall/js.valuePrepareString" (func (;3;) (type 12)))
243
+ (import "gojs" "syscall/js.valueLoadString" (func (;4;) (type 32)))
244
+ (import "gojs" "syscall/js.finalizeRef" (func (;5;) (type 33)))
245
+ (import "gojs" "syscall/js.stringVal" (func (;6;) (type 23)))
246
+ (import "gojs" "syscall/js.valueSet" (func (;7;) (type 34)))
247
+ (import "gojs" "syscall/js.valueNew" (func (;8;) (type 16)))
248
+ (import "gojs" "syscall/js.valueLength" (func (;9;) (type 20)))
249
+ (import "gojs" "syscall/js.valueInvoke" (func (;10;) (type 16)))
250
+ (import "gojs" "syscall/js.valueIndex" (func (;11;) (type 35)))
251
+ (import "gojs" "syscall/js.valueCall" (func (;12;) (type 17)))
252
+ (import "wasi_snapshot_preview1" "random_get" (func (;13;) (type 9)))
253
+ ```
254
+
255
+ Main things we can point out are:
256
+ - Uses `gojs` namespace a Go's JS interop layer (`syscall/js` package)
257
+ - `syscall/js.valueGet/valueSet`: Access JavaScript object properties
258
+ - `syscall/js.valueCall`: Call JavaScript functions
259
+
260
+ So yeah we can already be sure that is a go based script
261
+
262
+ ---
263
+
264
+ ### Step 4: Extracting Embedded Strings
265
+
266
+ #### Method 1: Using `strings` Command
267
+
268
+ ```bash
269
+ $ strings xpforwarded.wasm | grep -E "(forward|encrypt|sha|aes|guest|cookie)" | head -20
270
+ ```
271
+
272
+ **Results:**
273
+ ```
274
+ forwarded-for-sdk/javascript_fingerprint
275
+ crypto/aes
276
+ crypto/internal/fips140/aes
277
+ crypto/internal/fips140/aes/gcm
278
+ crypto/internal/fips140/sha256
279
+ documentcookie;=guest_id
280
+ navigatoruserActivationhasBeenActiveuserAgentwebdriverundefined
281
+ Error encrypting data:
282
+ getForwardedForStr
283
+ ```
284
+
285
+ #### Method 2: Analyzing WAT Data Segments
286
+
287
+ The WAT file contains data segments with embedded strings:
288
+
289
+ ```wat
290
+ (data (;0;) (i32.const 65536) "expand 32-byte k...")
291
+ (data (;1;) (i32.const 65842) "meta\00invalid syntax0123456789abcefz...")
292
+ ```
293
+
294
+ **Key String Discoveries:**
295
+
296
+ | String | Interpretation |
297
+ |--------|----------------|
298
+ | `forwarded-for-sdk/javascript_fingerprint` | Go package name |
299
+ | `crypto/aes`, `crypto/internal/fips140/aes` | AES encryption used |
300
+ | `crypto/internal/fips140/aes/gcm` | GCM mode specifically |
301
+ | `crypto/internal/fips140/sha256` | SHA-256 hashing |
302
+ | `documentcookie;=guest_id` | Guest ID cookie extraction (used for key derivation, NOT in payload) |
303
+ | `navigatoruserActivationhasBeenActive` | User interaction check |
304
+ | `userAgentwebdriverundefined` | Bot detection via webdriver |
305
+ | `getForwardedForStr` | Exported JS function name |
306
+ | `strexpiryTimeMillis` | Return object properties |
307
+ | `json:"navigator_properties"` | JSON field tag |
308
+ | `json:"created_at"` | JSON field tag |
309
+
310
+ #### Finding the Base AES Key
311
+
312
+ An important discovery was finding a hex string embedded near crypto error messages:
313
+
314
+ ```bash
315
+ # The key is embedded within a longer concatenated string
316
+ $ strings xpforwarded.wasm | grep "error creating AES"
317
+ \.+*?()|[]{}^$0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05error creating AES cipher:...
318
+
319
+ # Extract just 64-char hex sequences that contain letters (not pure numbers)
320
+ $ strings xpforwarded.wasm | grep -oE "[0-9a-f]{64}" | grep -E "[a-f]"
321
+ 0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05
322
+ ```
323
+
324
+ This is a 64-character hex string = 32 bytes = 256 bits, which is exactly the size for an AES-256 key. It appears immediately before the `error creating AES cipher:` confirming that it's used by the AES encryption code.
325
+
326
+ This is going to be the **base key**.
327
+
328
+ So at this point but just a first lookup on the strings we can already understand that we are facing an AES type of encryption based on an "original" GO file.
329
+
330
+ ---
331
+
332
+ ### Step 5: Understanding the Go Runtime
333
+
334
+ #### Go WASM Architecture
335
+
336
+ Go compiles to WASM using the `GOOS=js GOARCH=wasm` target. This requires:
337
+
338
+ 1. **JS Glue Code**: A JavaScript file that implements the `gojs` imports
339
+ 2. **Memory Management**: Go manages its own memory within WASM linear memory
340
+ 3. **JS Interop**: The `syscall/js` package provides bidirectional communication
341
+
342
+ #### Value Reference System
343
+
344
+ Go WASM uses a reference system to pass values between Go and JavaScript:
345
+
346
+ ```javascript
347
+ // Values are stored in an array, indexed by IDs
348
+ this._values = [
349
+ NaN, // 0: reserved
350
+ 0, // 1: zero
351
+ null, // 2: null
352
+ true, // 3: true
353
+ false, // 4: false
354
+ globalThis, // 5: global object
355
+ this // 6: Go instance
356
+ ];
357
+ ```
358
+
359
+ When Go calls `syscall/js.valueGet(obj, "property")`:
360
+ 1. Go passes the object reference ID
361
+ 2. The JS glue code looks up the object in `_values`
362
+ 3. Gets the property
363
+ 4. Stores the result in `_values` and returns the new ID
364
+
365
+ #### Asyncify Transform
366
+
367
+ The WASM module uses Binaryen's asyncify transform to handle async JavaScript operations:
368
+
369
+ ```wat
370
+ (export "asyncify_start_unwind" (func 436))
371
+ (export "asyncify_stop_unwind" (func 437))
372
+ (export "asyncify_start_rewind" (func 438))
373
+ ```
374
+
375
+ This allows the Go code to `await` JavaScript Promises, which is necessary for:
376
+ - `crypto.subtle.encrypt()`
377
+ - `crypto.subtle.digest()`
378
+
379
+ ---
380
+
381
+ ### Step 6: Identifying the Core Algorithm
382
+
383
+ #### The approach
384
+
385
+ So, at this point we could just "pack" the wasm file into a NodeJS file and call it a day, but I would not be satisfied without deeply understanding and recreating from scratch this situation.
386
+
387
+ So let's point out what we have at the moment in our hands, there's no need to further debug or whatever, just analyze our output file.
388
+
389
+ #### Evidence Source 1: Embedded Strings as "Breadcrumbs"
390
+
391
+ The most powerful technique is analyzing embedded strings. Go binaries contain:
392
+ - Package names
393
+ - Error messages
394
+ - JSON struct tags
395
+ - Type names
396
+
397
+ **Command used:**
398
+ ```bash
399
+ strings xpforwarded.wasm | grep -v "^.$" | sort -u > all_strings.txt
400
+ ```
401
+
402
+ **Key string discoveries and what they reveal:**
403
+
404
+ | String Found | What It Tells Us |
405
+ |--------------|------------------|
406
+ | `json:"navigator_properties"` | There's a Go struct with a field that serializes to `navigator_properties` |
407
+ | `json:"user_agent"` | Nested struct has `user_agent` field |
408
+ | `json:"has_been_active"` | Boolean field for user activation |
409
+ | `json:"webdriver"` | Boolean field for bot detection |
410
+ | `json:"created_at"` | Timestamp field |
411
+ | `navigatoruserActivationhasBeenActive` | Concatenated JS property access path |
412
+ | `userAgentwebdriverundefined` | More JS properties being accessed |
413
+ | `getForwardedForStr` | The exported function name |
414
+ | `strexpiryTimeMillis` | Return object has `str` and `expiryTimeMillis` keys |
415
+
416
+ **Reconstruction logic:**
417
+ ```
418
+ json:"navigator_properties" + json:"user_agent" + json:"has_been_active" + json:"webdriver"
419
+ ↓
420
+ NavigatorProperties struct with 3 fields
421
+
422
+ json:"navigator_properties" + json:"created_at"
423
+ ↓
424
+ ClientSignals struct wrapping NavigatorProperties
425
+ ```
426
+
427
+ #### Evidence Source 2: Package Paths
428
+
429
+ Go binaries embed full package paths:
430
+
431
+ ```bash
432
+ $ strings xpforwarded.wasm | grep "crypto/"
433
+ crypto/aes
434
+ crypto/cipher
435
+ crypto/internal/fips140/aes
436
+ crypto/internal/fips140/aes/gcm
437
+ crypto/internal/fips140/sha256
438
+ ```
439
+
440
+ What can we understand?
441
+ - `crypto/aes` → Uses AES encryption
442
+ - `crypto/cipher` → Uses cipher modes (block cipher interface)
443
+ - `crypto/internal/fips140/aes/gcm` → Specifically GCM mode
444
+ - NOT using CBC, CTR, or other modes
445
+
446
+ #### Evidence Source 3: Error Messages
447
+
448
+ Error messages reveal function behavior:
449
+
450
+ ```bash
451
+ $ strings xpforwarded.wasm | grep -i "error"
452
+ error creating AES cipher:
453
+ error creating GCM:
454
+ Error encrypting data:
455
+ ```
456
+
457
+ **Reconstruction:**
458
+ ```go
459
+ // Error message "error creating AES cipher:" implies:
460
+ block, err := aes.NewCipher(key)
461
+ if err != nil {
462
+ return nil, fmt.Errorf("error creating AES cipher: %w", err)
463
+ }
464
+
465
+ // Error message "error creating GCM:" implies:
466
+ gcm, err := cipher.NewGCM(block)
467
+ if err != nil {
468
+ return nil, fmt.Errorf("error creating GCM: %w", err)
469
+ }
470
+ ```
471
+
472
+ #### Evidence Source 4: WASM Imports Tell Us What JS APIs Are Used
473
+
474
+ ```wat
475
+ (import "gojs" "syscall/js.valueGet" ...) ; obj.property access
476
+ (import "gojs" "syscall/js.valueSet" ...) ; obj.property = value
477
+ (import "gojs" "syscall/js.valueCall" ...) ; obj.method()
478
+ (import "gojs" "syscall/js.valueNew" ...) ; new Constructor()
479
+ (import "wasi_snapshot_preview1" "random_get" ...) ; crypto random bytes
480
+ ```
481
+
482
+ This confirms:
483
+ - Code accesses JS object properties (navigator, document)
484
+ - Code calls JS methods
485
+ - Code needs random bytes (for IV/nonce generation)
486
+
487
+ #### Evidence Source 5: The 64-Character Hex String = AES-256 Key
488
+
489
+ The key is **not standalone**, it's embedded within a longer concatenated string. We find it by searching for hex patterns near crypto errors:
490
+
491
+ ```bash
492
+ $ strings xpforwarded.wasm | grep "error creating AES"
493
+ \.+*?()|[]{}^$0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05error creating AES cipher: error creating GCM: documentcookie;=guest_id
494
+ ```
495
+
496
+ **Extracting the key from the string:**
497
+ ```
498
+ \.+*?()|[]{}^$ ← regex special chars
499
+ 0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05 ← THE KEY (64 hex chars)
500
+ error creating AES cipher: error creating GCM: ← error messages
501
+ documentcookie;=guest_id ← other data
502
+ ```
503
+
504
+ How can we be sure that `0e6be1f1...` is the AES key?
505
+ - 64 hex chars = 32 bytes = 256 bits = **exact AES-256 key size**
506
+ - It appears **immediately before** `error creating AES cipher:` error message
507
+ - Go's `crypto/aes` package embeds error messages near key operations
508
+ - The regex chars before it (`\.+*?...^$`) are from a different Go package (regexp)
509
+ - Go linker concatenates nearby string literals from the data segment
510
+
511
+ or a more obv way is just to run
512
+ ```bash
513
+ # Extract 64-char sequences, filter to only those with letters (true hex, not just numbers)
514
+ $ strings xpforwarded.wasm | grep -oE "[0-9a-f]{64}" | grep -E "[a-f]"
515
+ 0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05
516
+ ```
517
+
518
+ And this is the **only** 64-char hex string with letters in the entire binary.
519
+
520
+ #### Evidence Source 6: JS Property Access Paths
521
+
522
+ The string `navigatoruserActivationhasBeenActiveuserAgentwebdriverundefined` is concatenated property names. Go's `syscall/js` package stores property names as strings:
523
+
524
+ ```go
525
+ // This Go code:
526
+ nav.Get("userAgent").String()
527
+ nav.Get("userActivation").Get("hasBeenActive").Bool()
528
+ nav.Get("webdriver").Bool()
529
+
530
+ // Results in these strings being embedded:
531
+ // "navigator", "userAgent", "userActivation", "hasBeenActive", "webdriver"
532
+ ```
533
+
534
+ #### Evidence Source 7: Return Value Structure
535
+
536
+ The string `strexpiryTimeMillis` reveals the return object keys:
537
+
538
+ ```go
539
+ // Concatenated: "str" + "expiryTimeMillis"
540
+ return map[string]interface{}{
541
+ "str": encoded, // ← "str"
542
+ "expiryTimeMillis": timestamp, // ← "expiryTimeMillis"
543
+ }
544
+ ```
545
+
546
+ #### Evidence Source 8: Type Names in WAT Data Segments
547
+
548
+ Looking at the WAT data segments:
549
+
550
+ ```wat
551
+ (data (;33;) ... "javascript_fingerprint.ClientSignals" ...)
552
+ (data (;33;) ... "json.MarshalerError" ...)
553
+ ```
554
+
555
+ This confirms:
556
+ - Package is named `javascript_fingerprint`
557
+ - Main type is `ClientSignals`
558
+ - Uses `encoding/json` for marshaling
559
+
560
+ #### Putting It All Together
561
+
562
+ **Step-by-step reconstruction:**
563
+
564
+ 1. **Find the function name** → `getForwardedForStr` (from strings)
565
+
566
+ 2. **Find what data is collected** → navigator properties (from JS property strings)
567
+
568
+ 3. **Find the data structure** → JSON tags reveal struct fields:
569
+ ```go
570
+ type ClientSignals struct {
571
+ NavigatorProperties NavigatorProperties `json:"navigator_properties"`
572
+ CreatedAt int64 `json:"created_at"`
573
+ }
574
+ ```
575
+
576
+ 4. **Find the encryption method** → AES-GCM (from package paths)
577
+
578
+ 5. **Find the encryption key** → 64-char hex string
579
+
580
+ 6. **Find the return format** → `{str, expiryTimeMillis}` from concatenated strings
581
+
582
+ 7. **Find error handling** → Error message strings reveal error paths
583
+
584
+ #### Reconstructing the Data Flow
585
+
586
+ From the strings and imports, we can reconstruct what the module does:
587
+
588
+ ##### 1. Entry Point Setup
589
+
590
+ **Evidence:** String `getForwardedForStr` + Go WASM always exports to `window`
591
+
592
+ When `_start` is called:
593
+ ```go
594
+ // Pseudocode from decompilation
595
+ func main() {
596
+ js.Global().Set("getForwardedForStr", js.FuncOf(getForwardedForStr))
597
+ }
598
+ ```
599
+
600
+ ##### 2. Data Collection Function
601
+
602
+ **Evidence chain:**
603
+ ```
604
+ String found: "json:\"user_agent\"" → Field name in struct
605
+ String found: "json:\"has_been_active\"" → Boolean field
606
+ String found: "json:\"webdriver\"" → Boolean field
607
+ String found: "json:\"navigator_properties\"" → Parent struct field
608
+ String found: "json:\"created_at\"" → Timestamp field
609
+ String found: "navigatoruserActivation..." → JS property access path
610
+ String found: "javascript_fingerprint.ClientSignals" → Type name
611
+ Import: "syscall/js.valueGet" → Confirms JS property access
612
+ ```
613
+
614
+ ```go
615
+ // Reconstructed from strings
616
+ type NavigatorProperties struct {
617
+ UserAgent string `json:"user_agent"` // ← from json:"user_agent"
618
+ HasBeenActive bool `json:"has_been_active"` // ← from json:"has_been_active"
619
+ Webdriver bool `json:"webdriver"` // ← from json:"webdriver"
620
+ }
621
+
622
+ type ClientSignals struct {
623
+ NavigatorProperties NavigatorProperties `json:"navigator_properties"` // ← from json:"navigator_properties"
624
+ CreatedAt int64 `json:"created_at"` // ← from json:"created_at"
625
+ }
626
+
627
+ func collectSignals() ClientSignals {
628
+ nav := js.Global().Get("navigator") // ← from "navigator" in property strings
629
+
630
+ return ClientSignals{
631
+ NavigatorProperties: NavigatorProperties{
632
+ UserAgent: nav.Get("userAgent").String(), // ← "userAgent"
633
+ HasBeenActive: nav.Get("userActivation").Get("hasBeenActive").Bool(), // ← "userActivation" + "hasBeenActive"
634
+ Webdriver: nav.Get("webdriver").Bool(), // ← "webdriver"
635
+ },
636
+ CreatedAt: time.Now().UnixMilli(), // ← "Datenow" string found
637
+ }
638
+ }
639
+
640
+ // Note: guest_id is extracted separately for key derivation, not included in ClientSignals
641
+ func extractGuestId(cookieStr string) string {
642
+ // Parse "guest_id=v1%3A..." from cookie string
643
+ // Return value used for: SHA256(baseKey + guestId)
644
+ }
645
+ ```
646
+
647
+ ##### 3. Encryption Function
648
+
649
+ **Evidence chain:**
650
+ ```
651
+ Package: "crypto/aes" → Uses AES algorithm
652
+ Package: "crypto/cipher" → Uses cipher modes
653
+ Package: "crypto/internal/fips140/aes/gcm" → Specifically GCM mode
654
+ String: "error creating AES cipher:" → Error message reveals aes.NewCipher() call
655
+ String: "error creating GCM:" → Error message reveals cipher.NewGCM() call
656
+ String: "0e6be1f1e21ffc33...c9571a05" → 32-byte (256-bit) AES key
657
+ Import: "wasi_snapshot_preview1.random_get" → Needs random bytes for nonce
658
+ String: "AES-GCM" → Confirms GCM mode
659
+ ```
660
+
661
+ **How we know it's AES-256-GCM:**
662
+ 1. Package path includes "gcm" → GCM mode
663
+ 2. Key is 32 bytes (256 bits) → AES-256
664
+ 3. `random_get` import → needs random IV/nonce
665
+ 4. GCM standard nonce is 12 bytes
666
+
667
+ ```go
668
+ // Reconstructed from crypto package usage
669
+ func encrypt(plaintext []byte, guestId string) ([]byte, error) {
670
+ // Base key from embedded 64-char hex string (32 bytes = AES-256)
671
+ baseKeyHex := "0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05"
672
+
673
+ // Derive per-user encryption key ← discovered from real token analysis
674
+ // Formula: SHA256(baseKey + guestId)
675
+ combined := baseKeyHex + guestId
676
+ hash := sha256.Sum256([]byte(combined))
677
+ key := hash[:] // 32 bytes
678
+
679
+ // Create AES cipher ← evidence: "error creating AES cipher:" error message
680
+ block, err := aes.NewCipher(key)
681
+ if err != nil {
682
+ return nil, fmt.Errorf("error creating AES cipher: %w", err) // ← exact string found
683
+ }
684
+
685
+ // Create GCM mode ← evidence: "error creating GCM:" + "crypto/.../gcm" package
686
+ gcm, err := cipher.NewGCM(block)
687
+ if err != nil {
688
+ return nil, fmt.Errorf("error creating GCM: %w", err) // ← exact string found
689
+ }
690
+
691
+ // Generate random nonce ← evidence: random_get import, GCM standard = 12 bytes
692
+ nonce := make([]byte, gcm.NonceSize()) // gcm.NonceSize() returns 12
693
+ io.ReadFull(rand.Reader, nonce)
694
+
695
+ // Encrypt and seal ← standard GCM operation
696
+ // Output format: nonce + ciphertext + auth_tag (GCM appends 16-byte tag)
697
+ ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
698
+ return ciphertext, nil
699
+ }
700
+ ```
701
+
702
+ **Key Derivation Discovery:**
703
+ - The base key alone does NOT work for decrypting real tokens
704
+ - Real tokens require: `SHA256(baseKey + guestId)` to derive the actual encryption key
705
+ - This was discovered by analyzing actual request headers and testing decryption
706
+ - The `guest_id` cookie value is extracted from `document.cookie` but NOT included in the payload
707
+
708
+ ##### 4. Main Function
709
+
710
+ **Evidence chain:**
711
+ ```
712
+ String: "getForwardedForStr" → Exported function name
713
+ String: "encoding/json" → Uses JSON marshaling
714
+ Package: "encoding/base64" → Uses base64 encoding
715
+ String: "strexpiryTimeMillis" → Return object keys (concatenated)
716
+ String: "Error encrypting data:" → Error handling path
717
+ Import: "syscall/js.valueSet" → Sets values on JS objects (return value)
718
+ String: "ObjectstrexpiryTimeMillis" → Confirms return is a JS object with these keys
719
+ ```
720
+
721
+ How we know the return format:
722
+ 1. `strexpiryTimeMillis` = `str` + `expiryTimeMillis` (concatenated keys)
723
+ 2. `Object` prefix suggests it's a JS object/map
724
+ 3. Standard Go WASM pattern returns `map[string]interface{}`
725
+
726
+ ```go
727
+ func getForwardedForStr(this js.Value, args []js.Value) interface{} {
728
+ // Extract guest_id from cookies ← evidence: "documentcookie;=guest_id" string
729
+ doc := js.Global().Get("document")
730
+ cookieStr := doc.Get("cookie").String()
731
+ guestId := extractGuestId(cookieStr) // e.g., "v1%3A176824413470818950"
732
+
733
+ // Collect signals ← uses collectSignals() we reconstructed
734
+ signals := collectSignals()
735
+
736
+ // Serialize to JSON ← evidence: "encoding/json" package
737
+ jsonData, _ := json.Marshal(signals)
738
+
739
+ // Encrypt with guest_id-derived key ← uses encrypt() with key derivation
740
+ encrypted, err := encrypt(jsonData, guestId)
741
+ if err != nil {
742
+ return map[string]interface{}{"error": err.Error()} // ← "Error encrypting data:"
743
+ }
744
+
745
+ // Encode as base64 ← evidence: "encoding/base64" package, standard pattern
746
+ encoded := base64.StdEncoding.EncodeToString(encrypted)
747
+
748
+ // Return result ← evidence: "strexpiryTimeMillis" = "str" + "expiryTimeMillis"
749
+ return map[string]interface{}{
750
+ "str": encoded, // ← "str"
751
+ "expiryTimeMillis": time.Now().Add(time.Hour).UnixMilli(), // ← "expiryTimeMillis"
752
+ }
753
+ }
754
+ ```
755
+
756
+ Why we know it's base64:
757
+ - Output in browser is clearly base64 (A-Za-z0-9+/=)
758
+ - Go's `encoding/base64` package is present
759
+ - Standard pattern for binary-to-string encoding
760
+
761
+ ---
762
+
763
+ ### Step 7: Key Derivation Discovery (guest_id)
764
+
765
+ #### The Problem
766
+
767
+ Initially, I thought the base AES key (`0e6be1f1...`) was used directly for encryption.
768
+
769
+ However, when I tried to decrypt real tokens from actual Twitter/X requests, decryption failed with authentication errors.
770
+
771
+ After running some tests based on every parameter provided from the request headers (almost a bruteforce, didn't wanted to spend more time debugging)
772
+ `SHA256(baseKey + guestId)` happeared to be the derivation way for the actual key.
773
+
774
+ #### Key Derivation Formula
775
+
776
+ ```javascript
777
+ // Base key (found in WASM)
778
+ const baseKey = "0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05";
779
+
780
+ // Guest ID from cookie (e.g., "v1%3A176824413470818950")
781
+ const guestId = extractGuestId(document.cookie);
782
+
783
+ // Derive per-user encryption key
784
+ const combined = baseKey + guestId;
785
+ const finalKey = SHA256(combined);
786
+ ```
787
+
788
+ ---
789
+
790
+ ### Step 8: Recreating the JavaScript Implementation
791
+
792
+ #### Utility Functions
793
+
794
+ ```javascript
795
+ // Convert hex string to bytes
796
+ function hexToBytes(hex) {
797
+ const bytes = new Uint8Array(hex.length / 2);
798
+ for (let i = 0; i < hex.length; i += 2) {
799
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
800
+ }
801
+ return bytes;
802
+ }
803
+
804
+ // Convert bytes to base64
805
+ function bytesToBase64(bytes) {
806
+ let binary = '';
807
+ for (let i = 0; i < bytes.length; i++) {
808
+ binary += String.fromCharCode(bytes[i]);
809
+ }
810
+ return btoa(binary);
811
+ }
812
+ ```
813
+
814
+ #### Fingerprint Collection
815
+
816
+ ```javascript
817
+ function collectClientSignals() {
818
+ const navigatorProps = {
819
+ user_agent: navigator.userAgent,
820
+ has_been_active: navigator.userActivation?.hasBeenActive || false,
821
+ webdriver: navigator.webdriver === true
822
+ };
823
+
824
+ return {
825
+ navigator_properties: navigatorProps,
826
+ created_at: Date.now()
827
+ };
828
+ }
829
+ ```
830
+
831
+ #### Key Derivation
832
+
833
+ ```javascript
834
+ const BASE_KEY_HEX = "0e6be1f1e21ffc33590b888fd4dc81b19713e570e805d4e5df80a493c9571a05";
835
+
836
+ /**
837
+ * Derive encryption key from guest_id
838
+ * Formula: SHA256(baseKey + guestId)
839
+ */
840
+ async function deriveKeyFromGuestId(guestId) {
841
+ const combined = BASE_KEY_HEX + guestId;
842
+ const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(combined));
843
+ return new Uint8Array(hash);
844
+ }
845
+ ```
846
+
847
+ #### AES-GCM Encryption
848
+
849
+ ```javascript
850
+ async function encryptAESGCM(plaintext, guestId) {
851
+ // Derive per-user encryption key
852
+ const key = await deriveKeyFromGuestId(guestId);
853
+
854
+ // Generate random 12-byte IV (standard for GCM)
855
+ const iv = crypto.getRandomValues(new Uint8Array(12));
856
+
857
+ // Import the derived key
858
+ const cryptoKey = await crypto.subtle.importKey(
859
+ 'raw',
860
+ key,
861
+ { name: 'AES-GCM' },
862
+ false,
863
+ ['encrypt']
864
+ );
865
+
866
+ // Encrypt
867
+ const encoder = new TextEncoder();
868
+ const plaintextBytes = encoder.encode(plaintext);
869
+
870
+ const ciphertext = await crypto.subtle.encrypt(
871
+ { name: 'AES-GCM', iv: iv, tagLength: 128 },
872
+ cryptoKey,
873
+ plaintextBytes
874
+ );
875
+
876
+ // Combine: IV + ciphertext (includes auth tag)
877
+ const result = new Uint8Array(iv.length + ciphertext.byteLength);
878
+ result.set(iv, 0);
879
+ result.set(new Uint8Array(ciphertext), iv.length);
880
+
881
+ return result;
882
+ }
883
+ ```
884
+
885
+ #### Main Implementation
886
+
887
+ ```javascript
888
+ class XPForwardedForSDK {
889
+ async getForwardedForStr() {
890
+ // 1. Extract guest_id from cookies
891
+ const guestId = this.getGuestId(); // e.g., "v1%3A176824413470818950"
892
+
893
+ // 2. Collect fingerprint data
894
+ const clientSignals = collectClientSignals();
895
+
896
+ // 3. Serialize to JSON
897
+ const jsonPayload = JSON.stringify(clientSignals);
898
+
899
+ // 4. Encrypt with AES-GCM using guest_id-derived key
900
+ const encryptedBytes = await encryptAESGCM(jsonPayload, guestId);
901
+
902
+ // 5. Encode as base64
903
+ const base64Token = bytesToBase64(encryptedBytes);
904
+
905
+ // 6. Return result with expiry
906
+ return {
907
+ str: base64Token,
908
+ expiryTimeMillis: Date.now() + (60 * 60 * 1000) // 1 hour
909
+ };
910
+ }
911
+
912
+ getGuestId() {
913
+ const cookies = document.cookie.split(';');
914
+ for (const cookie of cookies) {
915
+ const [name, value] = cookie.trim().split('=');
916
+ if (name === 'guest_id') {
917
+ return value;
918
+ }
919
+ }
920
+ return '';
921
+ }
922
+ }
923
+ ```
924
+
925
+ ---
926
+
927
+ ### Step 9: Validation
928
+
929
+ #### Testing Token Structure
930
+
931
+ ```javascript
932
+ // Generate a token
933
+ const sdk = new XPForwardedForSDK();
934
+ const result = await sdk.getForwardedForStr();
935
+
936
+ console.log("Token:", result.str);
937
+ console.log("Expiry:", new Date(result.expiryTimeMillis));
938
+
939
+ // Token format: base64(12-byte IV + encrypted JSON + 16-byte auth tag)
940
+ const decoded = atob(result.str);
941
+ console.log("Total bytes:", decoded.length);
942
+ console.log("IV (first 12):", [...decoded.slice(0,12)].map(c => c.charCodeAt(0)));
943
+ ```
944
+
945
+ #### Decryption Test
946
+
947
+ ```javascript
948
+ async function decryptToken(base64Token, guestId) {
949
+ const bytes = Uint8Array.from(atob(base64Token), c => c.charCodeAt(0));
950
+
951
+ const iv = bytes.slice(0, 12);
952
+ const ciphertext = bytes.slice(12);
953
+
954
+ // Derive the same key used for encryption
955
+ const key = await deriveKeyFromGuestId(guestId);
956
+
957
+ const cryptoKey = await crypto.subtle.importKey(
958
+ 'raw',
959
+ key,
960
+ { name: 'AES-GCM' },
961
+ false,
962
+ ['decrypt']
963
+ );
964
+
965
+ const decrypted = await crypto.subtle.decrypt(
966
+ { name: 'AES-GCM', iv: iv, tagLength: 128 },
967
+ cryptoKey,
968
+ ciphertext
969
+ );
970
+
971
+ return JSON.parse(new TextDecoder().decode(decrypted));
972
+ }
973
+
974
+ // Verify round-trip
975
+ const guestId = "v1%3A176824413470818950"; // From document.cookie as guest_id
976
+ const token = await sdk.getForwardedForStr();
977
+ const decrypted = await decryptToken(token.str, guestId);
978
+ console.log("Decrypted:", decrypted);
979
+ // Output: { navigator_properties: { userAgent: "...", hasBeenActive: "false", webdriver: "false" }, created_at: 1234567890 }
980
+ // Note: Real payload uses camelCase and string booleans
981
+ ```
982
+
983
+ ---
984
+
985
+ ### Step 10: Multi-Language Implementations
986
+
987
+
988
+ So now that we have the JS part fully working, it was just time to cleanup the code, convert into a NodeJS module that you can find in:
989
+
990
+ - [GO Version](./xp_forwarded_for/go/main.go)
991
+ - [NodeJS Version](./xp_forwarded_for/nodejs/index.js)
992
+ - [Python Version](./twitter_generator/xp_forwarded_for/main.py)
993
+
994
+ ---
995
+
996
+
997
+ ## Author
998
+
999
+ If you found this project helpful or interesting, consider starring the repo and following me for more security research and tools, or buy me a coffee to keep me up.
1000
+
1001
+ <p align="center">
1002
+ <a href="https://github.com/GlizzyKingDreko"><img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white" alt="GitHub"></a>
1003
+ <a href="https://twitter.com/GlizzyKingDreko"><img src="https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" alt="Twitter"></a>
1004
+ <a href="https://medium.com/@GlizzyKingDreko"><img src="https://img.shields.io/badge/Medium-12100E?style=for-the-badge&logo=medium&logoColor=white" alt="Medium"></a>
1005
+ <a href="https://discord.com/users/GlizzyKingDreko"><img src="https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>
1006
+ <a href="mailto:glizzykingdreko@protonmail.com"><img src="https://img.shields.io/badge/ProtonMail-8B89CC?style=for-the-badge&logo=protonmail&logoColor=white" alt="Email"></a>
1007
+ <a href="https://buymeacoffee.com/glizzykingdreko"><img src="https://img.shields.io/badge/Buy%20Me%20a%20Coffee-yellow?style=for-the-badge&logo=buy-me-a-coffee&logoColor=white" alt="Buy Me a Coffee"></a>
1008
+ </p>