JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

108 Views
No Comments

In JS reverse engineering, the most time-consuming tasks are often locating where encrypted parameters are generated and tracking dynamic code execution. Whether it’s Authorization in request headers, Tokens in Cookies, or encrypted data transmitted via WebSocket, Hook technique is the “sharp tool” to solve these problems. This article compiles practical scripts for 6 high-frequency Hook scenarios, combined with Chrome debugging tips, to help you locate core logic in 3 minutes and avoid reverse engineering pitfalls.

1. Hook Environment Setup: Tampermonkey Script Basic Framework

All practical scripts run on Tampermonkey, which ensures Hook code executes before page scripts load (a critical prerequisite). Remember this basic framework first—you only need to replace the core Hook logic later.


// ==UserScript==
// @name         JS Reverse Hook Toolkit
// @namespace    https://yourblog.com
// @match        https://target-website.com/*  // Replace with target website
// @grant        none
// @version      1.0.0
// @author       Your Name
// @description  JS Reverse Engineering High-Frequency Hook Script Collection
// @run-at       document-start  // Must execute in advance, otherwise Hook fails
// ==/UserScript==

(function() {
    'use strict';
    // Insert specific Hook code here
})();

Practical Detail: @match should be precise to the target domain (e.g., use https://blog.csdn.net/* for CSDN). @run-at must be set to document-start; otherwise, the page’s native functions will have already executed, and the Hook will fail.

2. JSON Hook: Capture Request/Response Serialization Core

90% of asynchronous requests use JSON.stringify to serialize parameters and JSON.parse to parse responses. Hooking these two methods allows you to directly capture raw parameters before encryption and response data after decryption.


// 1. Hook JSON.stringify (Request Parameter Serialization)
const originalStringify = JSON.stringify;
JSON.stringify = function(params) {console.log("[JSON Hook] Serialized Parameters:", params);
    // Detect key parameters (modify keywords like token/sign as needed)
    if (typeof params === 'object' && params !== null) {if ('sign' in params || 'token' in params || 'timestamp' in params) {debugger; // Trigger breakpoint to check call stack}
    }
    return originalStringify.apply(this, arguments);
};

// 2. Hook JSON.parse (Response Data Parsing)
const originalParse = JSON.parse;
JSON.parse = function(text) {console.log("[JSON Hook] Parsed Response:", text);
    // Breakpoint when response contains key data
    if (text.includes('userInfo') || text.includes('data')) {debugger;}
    return originalParse.apply(this, arguments);
};

Debugging Tip: After triggering the breakpoint, trace upward in the「Call Stack」panel of Chrome DevTools to find the parent function that calls JSON.stringify—that’s the core logic for parameter generation.

JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly
JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

3. WebSocket Hook: Track Encrypted Data in Real-Time Communication

WebSocket is commonly used in real-time interaction scenarios (e.g., live broadcasts, chat). Hooking its send method captures raw sent data without packet capture to analyze frame protocols.


// Save native WebSocket
window._originalWebSocket = window.WebSocket;

// Hook WebSocket constructor
window.WebSocket = function(url, protocols) {const ws = new window._originalWebSocket(url, protocols);
    // Hook send method
    const originalSend = ws.send;
    ws.send = function(data) {console.log("[WebSocket Hook] Sent Data:", data);
        // Breakpoint when data contains encryption keywords
        if (data.includes('encrypt') || data.includes('payload')) {debugger;}
        return originalSend.apply(this, arguments);
    };
    return ws;
};

Browser Compatibility: Firefox requires replacement with window.MozWebSocket. In practice, you can judge the environment via if ('MozWebSocket' in window).

4. Headers & Cookie Hook: Locate Authentication Information Source

Authentication information like Authorization and Token is often hidden in request headers or Cookies. Hooking these two scenarios quickly locates their generation logic.

4.1 Request Header Authorization Hook


// Inject script to avoid cross-domain restrictions
function injectHeaderHook() {
    const originalSetHeader = XMLHttpRequest.prototype.setRequestHeader;
    XMLHttpRequest.prototype.setRequestHeader = function(key, value) {if (key.toLowerCase() === 'authorization') {console.log("[Header Hook] Authorization:", value);
            debugger; // Capture Token/JWT generation
        }
        return originalSetHeader.apply(this, arguments);
    };
}

// Dynamically inject script
const script = document.createElement('script');
script.textContent = `(${injectHeaderHook.toString()})()`;
(document.head || document.documentElement).appendChild(script);
script.remove();

4.2 Cookie Hook: Track Token/Sign Generation

Rewrite the get/set methods of Cookie using Object.defineProperty to monitor all read/write operations, supporting keyword filtering.


const cookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') || {
    configurable: true,
    enumerable: true
};

Object.defineProperty(Document.prototype, 'cookie', {get() {const cookies = cookieDescriptor.get ? cookieDescriptor.get.call(this) : '';
        // Print when key Cookies are read
        if (/token|session|sign/i.test(cookies)) {console.log("[Cookie Get] Key Cookies Read:", cookies);
        }
        return cookies;
    },
    set(value) {console.log("[Cookie Set] Cookie Written:", value);
        // Breakpoint when specified keywords are written
        if (/token=|sign=/.test(value)) {console.trace('Key Cookie Setting Call Stack');
            debugger;
        }
        return cookieDescriptor.set ? cookieDescriptor.set.call(this, value) : value;
    }
});

Quickly Locate Cookie Generation Request: Right-click the target Cookie in Chrome「Application」→「Cookies」and select「Show requests with this cookie」. The Network panel will automatically filter relevant requests—the first request is the generation source.

JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly
JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

5. Dynamic Code Hook: eval & Function Interception

In reverse engineering, you often encounter encrypted code executed dynamically via eval or Function. Direct keyword search is ineffective, so you need to hook these two functions.

5.1 eval Hook: Capture Dynamically Executed Code


// Save and disguise native eval
const nativeEval = window.eval;
window.eval = function(code) {console.log("[eval Hook] Executed Code:", code.slice(0, 300) + "..."); // Truncate first 300 characters
    // Breakpoint when code contains encryption keywords
    if (/encrypt|signature|login/i.test(code)) {debugger;}
    return nativeEval.call(window, code);
};

// Avoid detection as non-native function
Object.defineProperty(window.eval, 'toString', {value: () => 'function eval() { [native code] }',
    writable: false
});
JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

5.2 Function Hook: Track Dynamically Created Functions

Function is the function constructor. Dynamically created encrypted functions are generated through it, and interception via Proxy is more stealthy.


function hookFunctionConstructor() {
    const nativeFunction = window.Function;
    window.Function = new Proxy(nativeFunction, {construct(target, args) {const funcCode = args[args.length - 1]; // Last parameter of Function is code
            console.log("[Function Hook] Dynamically Created Function:", funcCode.slice(0, 200) + "...");
            if (/encrypt|key/i.test(funcCode)) {debugger;}
            return Reflect.construct(target, args);
        }
    });
}
hookFunctionConstructor();
JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

6. Ajax Breakpoints: Locate Requests Without Code

No need to write Hook scripts for simple scenarios—Chrome has a built-in XHR breakpoint feature: Click「+」in「Sources」→「XHR/ Fetch Breakpoints」, enter a request URL keyword (e.g., /api/login), and the breakpoint will trigger automatically when the request is sent.

JS Reverse Engineering Hook Guide: Locate Encrypted Parameters & Key Code Quickly

7. Practical Summary: Core Principles of Hook Technique

  • Pre-execution: All Hook code must run before page scripts load (Tampermonkey document-start or injected scripts);
  • Precise keywords: Breakpoint conditions should use actual parameter names from the target website (e.g., sign, token) to reduce invalid breakpoints;
  • Stealth: Disguise native characteristics (e.g., toString method) after rewriting functions to avoid anti-crawling detection;
  • Call stack tracing: After triggering a breakpoint, trace upward in the Call Stack to find the function closest to business logic, not underlying methods.

These scripts have been verified in multiple reverse engineering projects and can solve 80% of parameter location problems. However, flexible adjustments are needed in practice—for example, when encountering obfuscated code, you can combine AST deobfuscation tools with Hook for location. Have you encountered any Hook challenges in your reverse engineering projects? Feel free to share in the comments.

END
 0
Fr2ed0m
Copyright Notice: Our original article was published by Fr2ed0m on 2025-11-25, total 7474 words.
Reproduction Note: Unless otherwise specified, all articles are published by cc-4.0 protocol. Please indicate the source of reprint.
Comment(No Comments)