feat(VM): 运行时反证通过 —— 静态导出的 cd 槽位序与真机 require 序逐位一致

做法: 真机 iframe 里包 Function.prototype.apply, 模块工厂调用形状实测为
4 参 [object,object,object,function](require 是最后一个), 按工厂实例分组记账;
再用新增 tools/cdp_script_source.js(Debugger.scriptParsed + getScriptSource)
取运行时真正执行的那份 tdc.js(不能用重新 fetch —— 同 URL 每次返回不同构建)。

结果: 静态 == 运行时 =
[8,9,10,13,14,15,16,17,18,19,20,21,23,24,25,30,31,32,34,36,37,1,38,39,40,41,42,43,44,47,48,49,50,51,56,57,58]
37 项逐位相同 -> 槽位序=require序 这条链闭合; 之前语义对不上是标注启发式的问题。

附带: window.TDC(含 getData) 只在验证码 iframe, 可直接调用取证; cdp_eval 新增 --init-script。
账本新增已知 #35。
This commit is contained in:
yml2213
2026-10-12 00:24:13 +08:00
parent 50c0ca33c6
commit d2b3889132
5 changed files with 283 additions and 1 deletions
+1
View File
@@ -65,6 +65,7 @@
| 32 | **仓库在用的 collect 模板 = `签到成功-1.har` 那一次的槽位序** | 模板指纹与 `签到成功-1#0` **逐槽一致**;与晚些时候的真机会话 29 个槽不同。→ `generate_collect_success()` 虽然回填了新轨迹/时间戳,但**槽位序是那一次的** | 确证 |
| 33 | **VM 程序结构层已吃透:顶层就是 62 个模块工厂的注册表** | 顶层 `@0` 做 `registry[id] = function(module, exports, require){...}`(`DUP; PUSH_IMM [id]; REVERSE_TOP2; JUMP -> CREATE_CLOSURE; SET_PROP`)。`tools/tdc_program.py --modules` 直接导出。修了两个真 bug:① 反汇编器漏了 `RET_TRUE`/`THROW` 是终结符(控制流穿过函数结尾 → 子程序归属全错);② 提升器终结符判定写死 opcode 数值 | 确证 |
| 34 | **`cd` 槽位序的来源已定位并可静态导出** | 装配链:清单模块 `arr[arr.length] = require(N)`(**追加,所以 require 顺序就是数组顺序**,已核)→ 分发模块按 `.on`/`.reset`/`.get` 分三数组 → 装配模块 `r3='{"cd":['` + `for(...) r3 += arr[i].get()`。线上构建实测 **37 个 require + 1 个字面量槽 = 38**,与真机 `cd` 槽数完全吻合;两份构建的 require 串不同(与 #31 一致)。工具:`tools/tdc_layout.py` | 确证(顺序)/ 语义标签部分 |
| 35 | **运行时反证通过:静态导出的 require 序 == 运行时真实 require 序(逐项一致)** | 在真机 iframe(`tdc.js` 实际执行的上下文,`window.TDC.getData` 就在这里)里包一层 `Function.prototype.apply`,模块工厂调用形状 = **4 参 `[object,object,object,function]`**(require 是最后一个),按工厂实例分组记账。触发一次刷新后取运行时串,用 `tools/cdp_script_source.js`(Debugger.scriptParsed + getScriptSource)取到**运行时真正执行的那份 tdc.js**(exactly-once,不能用重新 fetch 代替——#29 每次返回不同构建),两边串:<br>静态 = 运行时 = `[8,9,10,13,14,15,16,17,18,19,20,21,23,24,25,30,31,32,34,36,37,1,38,39,40,41,42,43,44,47,48,49,50,51,56,57,58]`(37 项,逐位相同)<br>→ 由此可判定:之前"部分槽语义对不上"是**标注启发式**的问题,**顺序本身正确**。工具:`scripts/experiment_require_order.py` | 确证 |
---
+158
View File
@@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
"""
实验 B —— 运行时反证「静态导出的 cd 槽位序」。
要回答的问题(har/1ms_dianxuan/PROGRESS.md §五 1(b) 残留点②):
`tools/tdc_layout.py` 从字节码静态推出的 require 顺序, 真的是**运行时**清单模块
请求模块的顺序吗? 如果一致, 槽位序=require 序 这条链就闭合了; 不一致则还有一层重排。
做法(只做观测, 不伪造环境):
1. 在真机页面里包一层 `Function.prototype.apply`。VM 的 `CALL_FUNC` 走 apply,
而模块工厂的调用形参固定是 (module, exports, require) —— 我们借这次调用的机会
把**该工厂专属的 require** 换成记账版本(每个工厂一个 group)。
2. 触发一次真实答题(走既有桥接), 让模块系统真正跑起来(清单模块在组装 collect 时被 require)。
3. 取回日志: 找出"distinct id 数最多"的那个 group = 清单模块;
与同一次会话抓到的 tdc.js 的静态导出串对比。
用法:
.venv/bin/python scripts/experiment_require_order.py
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import subprocess
import sys
import time
from pathlib import Path
from typing import List
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
if str(ROOT / "tools") not in sys.path:
sys.path.insert(0, str(ROOT / "tools"))
import tdc_layout # noqa: E402
import tdc_program as tp # noqa: E402
TRAP_JS = r"""(() => {
if (window.__reqTrapInstalled) return {already: true};
window.__reqTrapInstalled = true;
window.__reqLog = [];
window.__reqGroup = 0;
const origApply = Function.prototype.apply;
Function.prototype.apply = function (thisArg, args) {
try {
// 模块工厂调用形参固定 (module, exports, require): 3 个实参, 第 3 个是函数
if (args && args.length === 3 && typeof args[2] === 'function' && args[1] && typeof args[1] === 'object') {
const req = args[2];
if (!req.__logged) {
const g = ++window.__reqGroup;
const wrapped = function (id) {
window.__reqLog.push([g, typeof id === 'number' ? id : String(id)]);
return req.apply(this, arguments);
};
wrapped.__logged = true;
return origApply.call(this, thisArg, [args[0], args[1], wrapped]);
}
}
} catch (e) { /* 观测器绝不影响原流程 */ }
return origApply.call(this, thisArg, args);
};
return {installed: true};
})()"""
READ_LOG = "(() => ({installed: !!window.__reqTrapInstalled, n: (window.__reqLog||[]).length, log: window.__reqLog||[]}))()"
def _bridge():
spec = importlib.util.spec_from_file_location("bridge_1ms", ROOT / "scripts" / "bridge_1ms_captcha.py")
mod = importlib.util.module_from_spec(spec)
sys.argv = ["experiment"]
spec.loader.exec_module(mod)
return mod
def main() -> int:
ap = argparse.ArgumentParser(description="运行时 require 顺序 vs 静态导出")
ap.add_argument("--rounds", type=int, default=8)
args = ap.parse_args()
b = _bridge()
cap_path = Path("/tmp/1ms_bridge/req_cap.json")
print("[1] 唤起 widget 并装 require 记账器 ...")
print(" ", b.cdp_eval(b.EXPR_ENSURE, b.PAGE)["result"])
time.sleep(2.0)
for ctx in (b.PAGE, b.IFRAME):
try:
print(f" {ctx}: {b.cdp_eval(TRAP_JS, ctx)['result']}")
except Exception as exc:
print(f" {ctx}: 装失败 {exc}")
print("[2] 同时抓包(取本会话的 tdc.js) + 答题触发模块系统 ...")
cap = subprocess.Popen(["node", str(ROOT / "tools" / "cdp_capture.js"),
"--seconds", "70", "--url-substr", "tdc.js,cap_union",
"--out", str(cap_path)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(3)
p = subprocess.run([sys.executable, str(ROOT / "scripts" / "bridge_1ms_captcha.py"),
"--rounds", str(args.rounds), "--solves", "1"],
cwd=str(ROOT), capture_output=True, text=True, timeout=600)
tail = [ln for ln in p.stdout.splitlines() if ln.strip()][-4:]
print(" " + "\n ".join(tail))
cap.wait(timeout=120)
print("[3] 取运行时 require 日志 ...")
logs: List[list] = []
for ctx in (b.IFRAME, b.PAGE):
try:
r = b.cdp_eval(READ_LOG, ctx)["result"]
print(f" {ctx}: installed={r.get('installed')} 条数={r.get('n')}")
if r.get("log"):
logs += r["log"]
except Exception as exc:
print(f" {ctx}: 读失败 {exc}")
if not logs:
print("❌ 没拿到 require 日志(模块系统可能没跑到)")
return 1
groups: dict = {}
for g, mid in logs:
groups.setdefault(g, []).append(mid)
# 清单模块 = distinct id 最多的那个 group
best_g, best_seq = max(groups.items(), key=lambda kv: len(set(kv[1])))
runtime_seq = list(dict.fromkeys(best_seq))
print(f"[4] group 数={len(groups)} 清单候选 group={best_g} "
f"调用 {len(best_seq)} 次 / distinct {len(runtime_seq)}")
print(f" 运行时序列: {runtime_seq}")
print("[5] 静态导出(同一份构建)...")
if not cap_path.exists():
print("❌ 没抓到本会话的 tdc.js, 无法比对")
return 1
recs = json.load(open(cap_path, encoding="utf-8"))["records"]
tdcs = [r for r in recs if "tdc.js" in r["url"] and r.get("body")]
if not tdcs:
print("❌ 抓包里没有 tdc.js 响应体")
return 1
js_path = Path("/tmp/1ms_bridge/req_build.js")
js_path.write_text(tdcs[-1]["body"], encoding="utf-8")
prog = tp.load(str(js_path))
reg = dict(prog.module_registry(0))
_mid, _entry, static_seq = tdc_layout.find_manifest_module(prog)
print(f" 静态序列: {static_seq}")
ok = runtime_seq == static_seq
print(f"\n>>> 运行时 == 静态 ? {ok}")
if not ok:
print(f" 只在运行时有的 id: {sorted(set(runtime_seq) - set(static_seq))}")
print(f" 只在静态有的 id : {sorted(set(static_seq) - set(runtime_seq))}")
print(" (若只是顺序不同 -> 分发阶段有重排; 若集合都不同 -> 静态提取取错了模块)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+27
View File
@@ -330,3 +330,30 @@ E.push(function g() {
> 因此纯算路线必须**按本次构建**导出槽位表(`tools/tdc_layout.py`),
> 并用**本次 prehandle 的 sid** 去取那份 tdc.js(真机 URL 还多带 `appid=<aid>`)。
### 9.5 运行时反证(2026-10-11,已通过)
静态导出不能自证,所以做了对拍:在真机 iframe 里包一层 `Function.prototype.apply`,
模块工厂的调用形状实测是 **4 参 `[object, object, object, function]`**(require 是最后一个),
按工厂实例分组记账;再用 `tools/cdp_script_source.js`(`Debugger.scriptParsed` +
`getScriptSource`)取到**运行时真正执行的那份 tdc.js**。
> ⚠️ 不能用"重新 fetch 一次 tdc.js"来对比 —— 同一个 URL **每次返回不同构建**(§9.6/#29),
> 必须用 Debugger 取**已解析的源码**。
结果:静态导出的 37 个 id 与运行时逐位相同
```
[8,9,10,13,14,15,16,17,18,19,20,21,23,24,25,30,31,32,34,36,37,1,38,39,40,41,42,43,44,47,48,49,50,51,56,57,58]
```
→ **槽位序 = 清单模块 require 序** 这条链闭合。脚本:`scripts/experiment_require_order.py`。
### 9.6 附带发现
- `window.TDC`(含 `getData`/`getInfo`/`setData`/`clearTc`)**只存在于验证码 iframe**,可以直接
`TDC.getData(true)` 触发取证(不必真的答一次题),返回值就是 collect 明文。
- iframe 里还有 `__TENCENT_CHAOS_STACK` 全局。
- `Page.reload` 对 OOPIF iframe 无效("Command can only be executed on top-level targets");
想在脚本执行前挂钩子要用 `Page.addScriptToEvaluateOnNewDocument`(已加到 `tools/cdp_eval.js`
的 `--init-script`)。
+11 -1
View File
@@ -79,10 +79,20 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
const cdp = await Cdp.connect(target.webSocketDebuggerUrl);
await cdp.send('Runtime.enable');
// --init-script FILE: 在**该文档的任何脚本之前**注入 (配合 --reload 使用)。
// 用途: 挂钩子必须在 tdc.js 之类的目标脚本执行前就位, 否则模块系统已经初始化完/被缓存。
const initFile = arg('init-script', null);
if (initFile && initFile !== true) {
await cdp.send('Page.enable');
const src = fs.readFileSync(initFile, 'utf8');
const added = await cdp.send('Page.addScriptToEvaluateOnNewDocument', { source: src });
console.error(`[init-script] installed ${initFile} (${added.identifier})`);
}
if (arg('reload', false)) {
await cdp.send('Page.enable');
await cdp.send('Page.reload', { ignoreCache: true });
await sleep(2500);
await sleep(parseInt(arg('settle', '2500'), 10));
}
let expr;
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env node
/**
* cdp_script_source.js —— 用 CDP Debugger 取某个标签页里**已解析脚本**的原文。
*
* 为什么需要它(而不是再 fetch 一次):
* `tdc.js?app_data=..&t=..` **每次请求返回不同构建**, 所以"再抓一次"拿不到当前会话
* 正在跑的那一份。只有 Debugger.scriptParsed + Debugger.getScriptSource 能拿到**运行时
* 真正执行的那份源码**(缓存命中也不影响)。
*
* 零依赖 (Node >= 22 内置 WebSocket/fetch)。
*
* 用法:
* node tools/cdp_script_source.js --match drag_ele --url-substr tdc.js --out /tmp/build.js
* node tools/cdp_script_source.js --match drag_ele --list
*/
const fs = require('fs');
function arg(name, def) {
const i = process.argv.indexOf('--' + name);
if (i < 0) return def;
const v = process.argv[i + 1];
return (v === undefined || v.startsWith('--')) ? true : v;
}
class Cdp {
constructor(ws) { this.ws = ws; this.id = 0; this.waits = new Map(); this.handlers = []; }
static async connect(url) {
const ws = new WebSocket(url);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
const c = new Cdp(ws);
ws.onmessage = ev => {
const m = JSON.parse(ev.data);
if (m.id && c.waits.has(m.id)) {
const { res, rej } = c.waits.get(m.id);
c.waits.delete(m.id);
m.error ? rej(new Error(JSON.stringify(m.error))) : res(m.result);
} else if (m.method) {
for (const h of c.handlers) h(m);
}
};
return c;
}
send(method, params = {}) {
const id = ++this.id;
this.ws.send(JSON.stringify({ id, method, params }));
return new Promise((res, rej) => this.waits.set(id, { res, rej }));
}
on(fn) { this.handlers.push(fn); }
close() { try { this.ws.close(); } catch (e) {} }
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
(async () => {
const port = parseInt(arg('port', '9222'), 10);
const match = arg('match', null);
const substr = arg('url-substr', null);
const wait = parseInt(arg('wait', '1500'), 10);
const targets = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json())
.filter(t => t.type === 'page' || t.type === 'iframe');
let target = match ? targets.find(t => (t.url || '').includes(match)) : targets[0];
if (!target) throw new Error('没有可用标签页');
const cdp = await Cdp.connect(target.webSocketDebuggerUrl);
const scripts = [];
cdp.on(m => { if (m.method === 'Debugger.scriptParsed') scripts.push(m.params); });
await cdp.send('Debugger.enable');
await sleep(wait); // 等已经跑过的脚本被重新上报
await cdp.send('Runtime.enable');
await cdp.send('Runtime.evaluate', { expression: '1' }); // 触发一次上下文
if (arg('list', false)) {
for (const s of scripts) console.log(`${String(s.url || '').slice(0, 120)}\t${s.length}B`);
cdp.close();
return;
}
const hits = scripts.filter(s => substr ? String(s.url || '').includes(substr) : true);
if (!hits.length) throw new Error(`没找到匹配 ${substr} 的已解析脚本 (共 ${scripts.length} 个)`);
const pick = hits[hits.length - 1];
const r = await cdp.send('Debugger.getScriptSource', { scriptId: pick.scriptId });
const out = arg('out', '/tmp/cdp_script.js');
fs.writeFileSync(out, r.scriptSource, 'utf8');
console.log(JSON.stringify({ ok: true, url: pick.url, length: r.scriptSource.length, out,
candidates: hits.map(h => String(h.url).slice(0, 90)) }, null, 1));
cdp.close();
})().catch(e => { console.error('CDP_ERROR: ' + e.message); process.exit(1); });