Files
hello_js_reverse_skill/tcaptcha/tests/test_xtea_key.py
T
yml2213 fbcf2d448a feat(反VM): 纯 Python 还原 XTEA 算法 + 从 tdc.js 运行时提取每构建密钥
做了什么
- 确认 collect 的加密算法就是教科书 XTEA (32 轮, delta=0x9E3779B9),
  并证明 crypto.py 原有的"带加盐"写法只是把两个密钥字折叠:
  K' = [k0, k1+salt1, k2+salt2, k3]
- tdc_worker.js 新增 captureKey 模式: 正则改写 VM 的 ADD/XOR opcode 为带日志版本,
  用反向引用自动识别栈变量名 (样本=g/雨云实时=j/1ms=M, 版本无关);
  匹配数不为 1 时显式报错, 不静默失败
- 密钥反推: (sum + K[j]) 是一次 ADD, 两操作数必有一个等于 r*DELTA,
  另一个就是密钥字; 再对 Top-N 候选做 4! 排列 + 明文内容特征验证
- 新增 recover_payload_template / generate_collect_from_template:
  运行时标定一次明文模板, 之后轨迹生成/组包/加密/编码全部在 Python
- 新增 tcaptcha/proxy.py 代理提取, client 支持 --proxy-api 遇 12 自动换 IP

为什么
- 服务端只认 collect 的解密结果, 而密钥是每构建随机的;
  把算法做成纯 Python 后, 只有"取密钥"依赖 Node, 抗发版能力最强

怎么验证的
- 纯 Python XTEA 加密结果与真实 tdc.js 产物前 48 字节逐字节一致
- 密钥按构建固定的证据: 同一脚本 3 次运行密文首块均为 f6a24e3e4fb5dd2b
- 三份脚本 (样本/雨云实时/1ms实时) 均成功复原密钥
- 雨云 aid 端到端: 纯 Python 出包 -> errorCode=0 + 真实 ticket
- 回归测试: tcaptcha/tests/test_xtea_key.py 11 项断言全过,
  文字点选求解 8/8; 新增 tcaptcha/selftest.py 一键复验

已知未解
- 1ms aid=195672344 在答案正确时仍返回 errorCode=12; 已排除密钥、
  遥测引擎、出口 IP (4 个住宅代理)、短时频控、静默窗口
2026-10-11 18:07:09 +08:00

129 lines
4.8 KiB
Python

# -*- coding: utf-8 -*-
"""
XTEA 算法还原 + tdc.js 密钥提取 回归测试 (AGENTS.md §5.9)
固化的性质:
1. 标准 XTEA 加解密往返
2. 与真实 tdc.js **逐字节一致** (算法还原正确的判据, §3.0)
3. 插桩能从 tdc.js 复原密钥, 且密钥按构建固定 (§5.5 受控环境逐字节一致)
4. 模板标定 + 纯 Python 回填 的产物可被同一把密钥解回预期结构
运行:
.venv/bin/python -m tcaptcha.tests.test_xtea_key
"""
from __future__ import annotations
import base64
import json
import struct
import subprocess
import sys
import urllib.parse
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from tcaptcha.crypto import ( # noqa: E402
DEFAULT_KEY,
generate_collect_from_template,
recover_payload_template,
xtea_decrypt_block,
xtea_decrypt_bytes,
xtea_encrypt_bytes,
extract_xtea_key,
)
ROOT = Path(__file__).resolve().parents[2]
SAMPLE = ROOT / "tcaptcha" / "tdc_sample.js"
SAMPLE_KEY = [1448563793, 1850559083, 1733513813, 1364613714] # 等价于 DEFAULT_KEY + 两个加盐
CD_PRE = b'{"cd":[[],"1920-1080-1055-24-*-*-|-*",0,0,"", ' # 旧版明文首段 (已补齐 48B)
_fails: list[str] = []
def check(name: str, cond: bool, detail: str = "") -> None:
print(f" [{'PASS' if cond else 'FAIL'}] {name}" + (f" {detail}" if detail else ""))
if not cond:
_fails.append(name)
def run_tdc(script: str, points, options) -> dict:
proc = subprocess.run(
["node", str(ROOT / "tcaptcha" / "tdc_worker.js"), "-", json.dumps(points),
json.dumps(options)],
input=script, capture_output=True, text=True, timeout=180)
return json.loads(proc.stdout.strip().splitlines()[-1])
def test_xtea_roundtrip() -> None:
print("1) 标准 XTEA 往返")
key = list(SAMPLE_KEY)
for chunk in (b"hello!!", bytes(range(32)), b"x" * 8):
enc = xtea_encrypt_bytes(chunk, key)
dec = xtea_decrypt_bytes(enc, key)
check(f"往返 {len(chunk)}B", dec.startswith(chunk), f"{chunk[:8]!r}")
# 已知明文 -> 与 tdc.js 密文逐字节一致
enc = xtea_encrypt_bytes(CD_PRE, key)
check("加密结果可被同密钥解回", xtea_decrypt_bytes(enc, key).rstrip(b"\x00") == CD_PRE.rstrip(b"\x00"))
def test_byte_exact_vs_tdcjs() -> None:
print("2) 纯 Python 密文 == 真实 tdc.js 密文 (逐字节)")
script = SAMPLE.read_text(encoding="utf-8", errors="replace")
job = run_tdc(script, [[100, 100], [200, 200], [300, 300]], {"aid": "195672344"})
real = base64.b64decode(urllib.parse.unquote(job["collect"]))
key = extract_xtea_key(script)
check("提取到的密钥 == 已知 K'", key == SAMPLE_KEY, str(key))
# 旧版首段是常量 cd_pre, 可逐字节对拍
check("前 48 字节逐字节一致",
xtea_encrypt_bytes(CD_PRE, key) == real[:48],
xtea_encrypt_bytes(CD_PRE, key)[:8].hex())
def test_key_fixed_per_build() -> None:
print("3) 密钥按构建固定 (同一脚本多次运行首块一致)")
script = SAMPLE.read_text(encoding="utf-8", errors="replace")
heads = set()
for _ in range(2):
job = run_tdc(script, [[10, 10], [20, 20], [30, 30]], {"aid": "195672344"})
heads.add(base64.b64decode(urllib.parse.unquote(job["collect"]))[:8])
check("两次运行首块相同", len(heads) == 1, heads.pop().hex())
def test_template_refill() -> None:
print("4) 模板标定 + 纯 Python 回填")
script = SAMPLE.read_text(encoding="utf-8", errors="replace")
template, key = recover_payload_template(script)
check("模板以 {\"cd\":[ 开头", template.startswith('{"cd":['), template[:24])
try:
json.loads(template)
check("模板是合法 JSON", True)
except Exception as exc: # noqa: BLE001
check("模板是合法 JSON", False, str(exc))
collect = generate_collect_from_template(template, [(449, 254), (48, 53), (148, 252)], key)
plain = xtea_decrypt_bytes(base64.b64decode(urllib.parse.unquote(collect)), key) \
.decode("latin1").rstrip(" ")
check("回填产物可解回 {\"cd\":[ 开头", plain.startswith('{"cd":['), plain[:24])
check("回填产物以 }} 结尾", plain.rstrip().endswith("}}"))
check("轨迹已换成 3 次点击的规模", len(plain) != len(template),
f"{len(template)} -> {len(plain)}")
def main() -> int:
if not SAMPLE.exists():
print(f"缺少样本 {SAMPLE}")
return 1
for fn in (test_xtea_roundtrip, test_byte_exact_vs_tdcjs,
test_key_fixed_per_build, test_template_refill):
fn()
print()
if _fails:
print(f"❌ XTEA/密钥 回归失败 {len(_fails)} 项: {_fails}")
return 1
print("✅ XTEA/密钥 回归全部通过")
return 0
if __name__ == "__main__":
raise SystemExit(main())