diff --git a/README.en.md b/README.en.md index 8ff86f0..44d14f5 100644 --- a/README.en.md +++ b/README.en.md @@ -118,7 +118,9 @@ adb pull /data/data/com.example.app/trace.log ~/captures/login.trace.log # e.g. "Use algokiller ciphertext mode on ~/captures/login.trace.log to recover the X-Sign cipher a3b2c1..." ``` -For detailed hook scripts, see GumTrace's [example.js](https://github.com/lidongyooo/GumTrace/blob/main/example.js) / [example_ios.js](https://github.com/lidongyooo/GumTrace/blob/main/example_ios.js). +For detailed hook scripts, see GumTrace's [example.js](https://github.com/lidongyooo/GumTrace/blob/main/example.js) / [example_ios.js](https://github.com/lidongyooo/GumTrace/blob/main/example_ios.js), plus this repo's three production templates under [`examples/frida-gumtrace/`](examples/frida-gumtrace/) (including an anti-jailbreak-bypass spawn pattern). + +> **Full iOS jailbreak deployment guide** (iproxy + scp + ldid + anti-jailbreak / anti-frida bypass) is in **[docs/setup-ios.md](docs/setup-ios.md)** — covers Dopamine, known_hosts collisions, TweakInject injection failures, the Dopamine "Hide Jailbreak" ↔ GumTrace loading conflict, and resilient transfer for multi-GB traces over USB. > Frida's native trace formats (`frida-trace` / Stalker default emit) are NOT compatible — GumTrace's custom emitter is required. diff --git a/README.md b/README.md index c8897f7..a476654 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,9 @@ adb pull /data/data/com.example.app/trace.log ~/captures/login.trace.log # 例如:"用 algokiller ciphertext 模式分析 ~/captures/login.trace.log,还原 X-Sign 密文 a3b2c1..." ``` -详细 hook 写法见 GumTrace 的 [example.js](https://github.com/lidongyooo/GumTrace/blob/main/example.js) / [example_ios.js](https://github.com/lidongyooo/GumTrace/blob/main/example_ios.js)。 +详细 hook 写法见 GumTrace 的 [example.js](https://github.com/lidongyooo/GumTrace/blob/main/example.js) / [example_ios.js](https://github.com/lidongyooo/GumTrace/blob/main/example_ios.js),以及本仓库 [`examples/frida-gumtrace/`](examples/frida-gumtrace/) 的三个实战模板(含 anti-jailbreak bypass + spawn 范式)。 + +> **iOS 越狱设备部署完整步骤**(iproxy + scp + ldid + 反越狱 / 反 frida 检测处理)详见 **[docs/setup-ios.md](docs/setup-ios.md)** —— Dopamine 越狱、known_hosts 冲突、TweakInject 注入失败、Dopamine 隐藏越狱与 GumTrace 加载冲突、大 trace 文件 USB 续传等坑都有命令级处置方案。 > Frida 原生 trace(`frida-trace` / Stalker 默认 emit)格式不兼容本 plugin —— 必须用 GumTrace 的自定义 emitter。 diff --git a/docs/setup-ios.md b/docs/setup-ios.md new file mode 100644 index 0000000..6f1ffc5 --- /dev/null +++ b/docs/setup-ios.md @@ -0,0 +1,233 @@ +# iOS 越狱设备 GumTrace 部署指南 + +从 USB 连接到 dylib 注入验证的完整流程。所有命令在 macOS 端执行(除非另外说明)。 + +## 0. 前置准备 + +- **iOS 设备**:用 **Dopamine** 越狱(rootless,`/var/jb` 前缀),或 **palera1n** + (`/private/preboot/...`)。下面以 Dopamine 为主,palera1n 路径不同但流程一样。 +- **macOS 端工具**: + ```bash + brew install libimobiledevice frida # iproxy + frida-cli + pip3 install frida-tools + ``` +- **设备端**:已装 OpenSSH,`frida-server` 已运行。 +- **GumTrace** 已交叉编译出 `build_ios/libGumTrace.dylib` + (见 [GumTrace 仓库](https://github.com/lidongyooo/GumTrace))。 + +## 1. iproxy 打通 USB → SSH 通道 + +iOS 越狱设备 SSH 走 USB(不走 WiFi)。`iproxy` 把设备 22 端口转发到本地 2222: + +```bash +iproxy 2222 22 & +``` + +启动一次即可,整个工作流期间别 kill。验证: + +```bash +ssh -p 2222 root@localhost "uname -a" +# 首次连接要确认指纹,输 yes +# 默认密码 alpine(建议尽快改) +``` + +## 2. SSH known_hosts 冲突(换设备 / 重装 OpenSSH 必踩) + +之前用 `localhost:2222` 连过别的设备,或者本设备重装过 OpenSSH,就会看到: + +``` +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ +... +Offending ED25519 key in ~/.ssh/known_hosts:NN +Host key verification failed. +``` + +一行解决——只删 `[localhost]:2222` 这一条 entry,不动其他: + +```bash +ssh-keygen -R "[localhost]:2222" +``` + +再次连接会问 `Are you sure you want to continue connecting (yes/no)?`,输 `yes` +新 key 自动入库。 + +**安全提醒**:换设备 / 刷机场景下这个 warning 是误报;如果你**没换过设备** +却突然冒这个错,先停下排查是不是中间人,再清 known_hosts。 + +## 3. 推 GumTrace 到设备 + +```bash +# 1) 推 dylib 到 Dopamine TweakInject 目录 +scp -P 2222 build_ios/libGumTrace.dylib \ + root@localhost:/var/jb/usr/lib/TweakInject/GumTrace.dylib + +# 2) ldid 签空 entitlements(dylib 不需要权限,签一下让 amfid 放行) +ssh -p 2222 root@localhost \ + "ldid -S /var/jb/usr/lib/TweakInject/GumTrace.dylib" + +# 3) 让 TweakInject 重扫注入清单 +ssh -p 2222 root@localhost "killall -9 SpringBoard" +``` + +SpringBoard 重启 = 锁屏黑 3-5 秒后回来。**禁忌**:永远不要给目标 App 主二进制 +重签名或加 entitlements,会破坏 Apple Distribution 证书链,FBS 直接拒 launch。 + +## 4. 验证 dylib 是否注入到目标进程 + +冷启动一次目标 App(强杀再点开,保证 TweakInject 有干净注入窗口),用 frida +检查已加载模块: + +```bash +frida -U -n <目标 App 进程名> -e \ + "console.log(JSON.stringify(Process.enumerateModules().filter(m => /GumTrace/i.test(m.path)), null, 2))" +``` + +进程名不知道先 `frida-ps -Uai | grep -i <关键词>` 查。 + +期待输出: + +```json +[ + { + "name": "GumTrace.dylib", + "base": "0x10xxxxxxxx", + "size": 7356416, + "path": "/var/jb/usr/lib/TweakInject/GumTrace.dylib" + } +] +``` + +**输出是 `[]` = TweakInject 没把 dylib 装进这个 App**。最常见原因: + +- Choicy 把目标 App 的 tweak 注入全屏蔽了(越狱党防检测的常见配置) +- ellekit 处于 opt-in 模式,目标 App 没加白名单 +- 目标 App 自带反 tweak 检测 + +进一步诊断——在 frida REPL 里看注入框架本身在不在: + +```javascript +Process.enumerateModules() + .filter(m => /(ellekit|substitute|substrate|TweakInject|libhooker|choicy)/i.test(m.path)) + .forEach(m => console.log(m.path)) +``` + +- 有输出 → 框架进来了但 GumTrace 被过滤 → 改 Choicy / ellekit 白名单。 +- 完全空 → 整个 tweak 链都被屏蔽 → 用第 5 节的"兜底方案"。 + +## 5. 兜底方案:frida 直接 `Module.load`(100% 绕过 ellekit) + +把 dylib 用 `Module.load` 拉进去,不依赖 TweakInject。在 frida REPL 或 hook +脚本里执行: + +```javascript +const m = Module.load('/var/jb/usr/lib/TweakInject/GumTrace.dylib') +console.log('loaded:', m.name, '@', m.base, '| size:', m.size) +``` + +期待输出: + +``` +loaded: GumTrace.dylib @ 0x13c3ac000 | size: 7356416 +``` + +反 tweak 检测拦不到这条路径(dylib 不在进程启动时的初始模块列表里,是 +**动态**加载的)。本目录三个示例脚本都自带这个兜底逻辑。 + +## 6. JS 侧反越狱 bypass(目标 App 主动检测 `/var/jb` 时) + +一些重度加固 App 会主动扫描越狱痕迹(`/var/jb/`、`Cydia.app`、`TweakInject`、 +`MobileSubstrate` 等)并在 main() 早期自杀。两种处理方式: + +| 方案 | 代价 | +|---|---| +| **Dopamine 自带"隐藏越狱"开关** | 系统级隐藏 `/var/jb` 对**所有进程**。副作用:TweakInject 也看不到 jb 路径,**GumTrace 也加载不了** | +| **JS 侧 anti-jb hook**(见 [`examples/frida-gumtrace/targetapp-anti-jb-spawn.js`](../examples/frida-gumtrace/targetapp-anti-jb-spawn.js)) | 在 frida 注入的脚本里逐个 hook `stat / access / open / dlopen / getenv / ptrace / sysctl / _dyld_get_image_name`。dlopen **特殊处理**:放过 GumTrace.dylib,其他 jb 路径返回 NULL。这样 frida 还能加载 GumTrace,但目标 App 看到的是干净系统 | + +**推荐**:**关掉 Dopamine 的全局隐藏越狱开关**,改用脚本级 anti-jb hook。 +这样 frida 还能正常 `Module.load` GumTrace,目标 App 也看不到越狱痕迹。 + +## 7. 故障排查速查表 + +| 现象 | 原因 | 处理 | +|---|---|---| +| `iproxy: bind failed` | 2222 已被占用 | `lsof -ti:2222 \| xargs kill -9` 或换端口 | +| `Host key verification failed` | known_hosts 冲突 | `ssh-keygen -R "[localhost]:2222"` | +| `scp: Permission denied` | 目标目录权限不够 | 先 `ssh ... "mkdir -p /var/jb/usr/lib/TweakInject"` | +| `ldid: command not found` | 设备上没装 ldid | `ssh ... "apt install ldid"`(Dopamine 包管理) | +| `frida -U -n` 找不到设备 | USB 未授权 | 解锁设备、信任此电脑、`idevice_id -l` 确认设备能识别 | +| `frida-ps -Uai` 进程列表空 | frida-server 没跑 | `ssh ... "frida-server &"`(后台) | +| dylib 加载成功但 trace 0 字节 | `init()` 在错误线程调用 | hook ObjC 业务方法在 `onEnter` 里 init/run,`threadId=0` 必须 | +| `Module.load` 抛 `ENOENT` | dylib 不在设备上 | 重做第 3 步,`ls -la /var/jb/usr/lib/TweakInject/GumTrace.dylib` 确认 | +| spawn 立刻 `connection is closed` | 反越狱检测干掉进程 | 用第 6 节的 JS 侧 anti-jb hook | + +## 8. 一次性命令包(环境就绪后快速复用) + +```bash +# 推 + 签 + 重启 SpringBoard(dylib 重编后跑这一条) +scp -P 2222 build_ios/libGumTrace.dylib \ + root@localhost:/var/jb/usr/lib/TweakInject/GumTrace.dylib && \ +ssh -p 2222 root@localhost \ + "ldid -S /var/jb/usr/lib/TweakInject/GumTrace.dylib && killall -9 SpringBoard" + +# 强杀目标 App(让下次启动是真冷启动) +ssh -p 2222 root@localhost "killall -9 <进程名>" + +# 验证注入(替换 <进程名>) +frida -U -n <进程名> -e \ + "console.log(Process.enumerateModules().filter(m => /GumTrace/i.test(m.path)).length)" +# 输出 1 = 已注入;0 = 用第 5 节 Module.load 兜底 +``` + +## 9. 大 trace 文件拉回 macOS(USB SSH 单次撑不住几个 GB 时) + +1.5–10 GB trace 通过 USB SSH 直传容易中途断。**三种方案从简到难**: + +### 方案 A:`scp -C` 内置 gzip 压缩(最快试) + +```bash +scp -P 2222 -C \ + root@localhost:'/var/mobile/Containers/Data/Application//Documents/.log' \ + ./ +``` + +`-C` 让 SSH 双端自动协商 gzip 压缩。trace 是文本,重复指令多,压缩率 5-10x。 + +### 方案 B:`rsync --partial` 续传(如果设备有 rsync) + +```bash +ssh -p 2222 root@localhost "which rsync" # 先确认有 +rsync -avP --partial -e 'ssh -p 2222' \ + root@localhost:'<远端路径>' \ + ./ +``` + +断了直接重跑命令,从断点续传。 + +### 方案 C:dd 100 MB 分块(万能最稳) + +```bash +mkdir -p /tmp/chunks && cd /tmp/chunks +SRC='/var/mobile/Containers/Data/Application//Documents/.log' +for i in $(seq 0 19); do # 20 块 = 2 GB(按实际文件大小调整) + CHUNK=$(printf "chunk_%03d.bin" $i) + [ -s "$CHUNK" ] && continue # 已拉过且非空就跳过 + echo "拉块 $i" + ssh -p 2222 root@localhost "dd if='$SRC' bs=1M count=100 skip=$((i*100)) 2>/dev/null" > "$CHUNK" +done +cat chunk_*.bin > <本地输出.log> +rm -rf /tmp/chunks +``` + +每块短连接,断一块只丢一块的重传成本。 + +## 相关文档 + +- [`examples/frida-gumtrace/README.md`](../examples/frida-gumtrace/README.md) + —— GumTrace 实战教程总览 + 三个示例脚本 +- [`examples/frida-gumtrace/targetapp-correct.js`](../examples/frida-gumtrace/targetapp-correct.js) + —— 最小验证版(单 hook 点) +- [`examples/frida-gumtrace/targetapp-startup-trace.js`](../examples/frida-gumtrace/targetapp-startup-trace.js) + —— 启动期完整 trace 模板 +- [`examples/frida-gumtrace/targetapp-anti-jb-spawn.js`](../examples/frida-gumtrace/targetapp-anti-jb-spawn.js) + —— **反越狱 bypass + spawn 模式 trace** 模板(目标 App 检测越狱时用) diff --git a/examples/frida-gumtrace/README.md b/examples/frida-gumtrace/README.md index 3483733..9465651 100644 --- a/examples/frida-gumtrace/README.md +++ b/examples/frida-gumtrace/README.md @@ -2,14 +2,17 @@ 把 [GumTrace](https://github.com/lidongyooo/GumTrace)(@lidongyooo 基于 frida-gum Stalker 写的 ARM64 trace 工具)部署到越狱 iOS 设备,对**任意目标 App** 做指令级动态追踪,产物可直接喂给 AlgoKiller plugin 做密文 / 流程分析。 -本目录两个示例脚本: +本目录三个示例脚本: | 脚本 | 用途 | hook 入口 | |---|---|---| | `targetapp-correct.js` | 最小可用版(单 hook 点 + 简单验证) | `-[UIView layoutSubviews]` 首次触发 | | `targetapp-startup-trace.js` | 启动期完整 trace(推荐用作生产模板) | `-[ applicationDidBecomeActive:]` + autotrigger | +| `targetapp-anti-jb-spawn.js` | **带反越狱 bypass 的 spawn 模式 trace**(目标 App 检测越狱时用) | `arc4random_buf` 深度调用栈 + `-[NSURLSession dataTaskWithRequest:]` 业务 URL 首次触发 | -> **重要**:这两个脚本顶部都有 `TARGET_APP_NAME` / `TARGET_APP_DELEGATE_CLASS` 占位符。**用之前必须改成你目标 App 的实际 module 名 + AppDelegate 类名**。脚本本身是算法/品牌无关的模板。 +> **重要**:这三个脚本顶部都有 `TARGET_APP_NAME` / `TARGET_MODULE` / 业务 URL regex 等占位符。**用之前必须改成你目标 App 的实际 module 名 / AppDelegate 类名 / URL 模式**。脚本本身是算法/品牌无关的模板。 +> +> **iOS 越狱设备部署**(iproxy / scp / ldid / 反越狱处理)详见 [`docs/setup-ios.md`](../../docs/setup-ios.md)。 --- diff --git a/examples/frida-gumtrace/targetapp-anti-jb-spawn.js b/examples/frida-gumtrace/targetapp-anti-jb-spawn.js new file mode 100644 index 0000000..ada06cd --- /dev/null +++ b/examples/frida-gumtrace/targetapp-anti-jb-spawn.js @@ -0,0 +1,457 @@ +// targetapp-anti-jb-spawn.js +// ───────────────────────────────────────────────────────────────────────── +// 带"反越狱 bypass + 字符串混淆"的 spawn 模式 GumTrace 范式(Dopamine 兼容) +// +// 适用场景: +// 目标 App 主动检测越狱(扫 /var/jb / TweakInject / Cydia 等),在 main() 早期 +// 自杀;Dopamine 自带的"隐藏越狱"开关又会让 GumTrace 也加载不进去。需要 JS +// 脚本里自己做反越狱 hook,让目标 App 看不到越狱,但 frida 还能 Module.load +// GumTrace.dylib。 +// +// 脚本结构: +// 1. 最早 IIFE:JS 侧反越狱 hook +// - 文件检测 syscall:stat / lstat / access / open / fopen / opendir / +// readlink / statfs(jb 路径返回 -1 或 NULL) +// - dlopen 特殊处理:放过 GumTrace.dylib,其他 jb 路径返回 NULL +// - getenv 隐藏 DYLD_INSERT_LIBRARIES +// - ptrace 改 NOOP(PT_DENY_ATTACH 无效化) +// - sysctl 清 kinfo_proc.kp_proc.p_flag 的 P_TRACED 位 +// - _dyld_get_image_name 把 jb 路径替换成系统 dylib +// 2. arc4random_buf hook + 15 层调用栈(找算法入口候选) +// 3. setTimeout 500ms 装 ObjC hooks:setValue:forHTTPHeaderField: + +// NSURLSession dataTaskWithRequest: +// 4. 业务 URL 首次命中 dataTask → Module.load GumTrace → stalker 启动 +// 5. 文件大小达 TARGET_TRACE_GB 自动 stop(双路 unrun 解决跨线程 unfollow) +// +// 越狱关键字(/var/jb / TweakInject / GumTrace 等)都通过 hex 字面量在运行时 +// 解码,**不在 V8 constant pool 留字面量**。有些 App 会扫自己的 heap 找越狱 +// 特征字符串,碰到立即 abort——这套做法能避开。 +// +// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +// 用之前必须改的占位符: +// TARGET_MODULE —— 主可执行模块名(Process.findModuleByName 用) +// TARGET_URL_RE —— 业务 URL 正则(用来过滤掉 CDN / 图片等噪音) +// TARGET_HEADERS_RE —— 要关注的签名 header 正则 +// (可选)想抓 Curve25519 / 服务器公钥等,自己加 scan + hook +// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +// +// 跑法: +// frida -U -f -l targetapp-anti-jb-spawn.js 2>&1 | tee spawn.log + +var TAG = '[TR]'; + +// ───────────────────────────────────────────────────────────────────────── +// 占位符 —— 改成你目标 App 的实际值 +// ───────────────────────────────────────────────────────────────────────── + +// 主可执行模块名 +var TARGET_MODULE = 'TargetApp'; + +// 业务 URL 正则(CDN / 静态资源 URL 会被过滤掉) +var TARGET_URL_RE = /(api|gateway|auth)\.example\.com/i; + +// 要关注的签名 header 正则 +var TARGET_HEADERS_RE = /^x-(sign|nonce|trace|client)/i; + +// stalker 文件大小阈值 +var TARGET_TRACE_GB = 1.5; // 软目标(达到自动 stop) +var MAX_TRACE_GB = 5; // 硬上限(强制 stop) + +// trace 输出文件名(落到 App sandbox Documents) +var TRACE_NAME = 'targetapp-spawn.trace.log'; + +// ───────────────────────────────────────────────────────────────────────── +// hex 字符串解码 —— 把越狱关键字从 V8 constant pool 里剥离 +// ───────────────────────────────────────────────────────────────────────── + +function dec(hex) { + var s = ''; + for (var i = 0; i < hex.length; i += 2) + s += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + return s; +} + +// '/var/jb' +var P_JB = dec('2f7661722f6a62'); +// '/Library/MobileSubstrate' +var P_MS = dec('2f4c6962726172792f4d6f62696c655375627374726174'); +// '/Library/LaunchDaemons/jb.' +var P_JB_DAEMON = dec('2f4c6962726172792f4c61756e636844616d6f6e732f6a622e'); +// '/Applications/Cydia.app' +var P_CYDIA = dec('2f4170706c69636174696f6e732f4379646961'); +// '/Applications/Sileo.app' +var P_SILEO = dec('2f4170706c69636174696f6e732f53696c656f'); +// '/usr/sbin/sshd' +var P_SSHD = dec('2f7573722f7362696e2f73736864'); +// 'TweakInject' +var TW = dec('547765616b496e6a656374'); +// 'GumTrace' +var GT = dec('47756d5472616365'); +// 'substrate' +var SUBSTRATE = dec('737562737472617465'); +// 'frida' +var FRIDA = dec('6672696461'); +// 'cydia' +var CYDIA_S = dec('6379646961'); + +// '/var/jb/usr/lib/TweakInject/GumTrace.dylib' —— 运行时拼接 +var DYLIB_PATH = P_JB + dec('2f7573722f6c69622f') + TW + '/' + GT + dec('2e64796c6962'); + +function isJBPath(path) { + if (!path) return false; + if (path.indexOf(P_JB) === 0) return true; + if (path.indexOf(P_MS) === 0) return true; + if (path.indexOf(P_JB_DAEMON) === 0) return true; + if (path.indexOf(P_CYDIA) === 0) return true; + if (path.indexOf(P_SILEO) === 0) return true; + if (path === P_SSHD) return true; + var low = path.toLowerCase(); + if (low.indexOf(TW.toLowerCase()) >= 0) return true; + if (low.indexOf(SUBSTRATE) >= 0) return true; + if (low.indexOf(FRIDA) >= 0) return true; + if (low.indexOf(CYDIA_S) >= 0) return true; + return false; +} + +// GumTrace 自己的路径要放过 —— frida 后面要 Module.load 它 +function isGumTracePath(path) { return path && path.indexOf(GT) >= 0; } + +// ───────────────────────────────────────────────────────────────────────── +// IIFE 1:反越狱 syscall hook(main() 之前生效) +// ───────────────────────────────────────────────────────────────────────── + +(function antiJB() { + var fileFns = [ + ['stat', false], ['lstat', false], ['access', false], + ['readlink', false], ['statfs', false], + ['open', false], ['fopen', true], ['opendir', true] + ]; + fileFns.forEach(function (cfg) { + try { + var fn = cfg[0], retIsPtr = cfg[1]; + var addr = Module.findGlobalExportByName(fn); + if (!addr) return; + Interceptor.attach(addr, { + onEnter: function (args) { + try { + var path = args[0].readUtf8String(); + if (isJBPath(path)) this.block = true; + } catch (e) {} + }, + onLeave: function (retval) { + // fopen / opendir 返回 NULL,其他返回 -1(即 ENOENT 风格) + if (this.block) retval.replace(retIsPtr ? ptr(0) : ptr(-1)); + } + }); + } catch (e) {} + }); + + // dlopen —— 关键:放过 GumTrace.dylib,让 frida 后面能加载 + try { + var dlopenAddr = Module.findGlobalExportByName('dlopen'); + if (dlopenAddr) { + Interceptor.attach(dlopenAddr, { + onEnter: function (args) { + try { + if (args[0].isNull()) return; + var path = args[0].readUtf8String(); + if (isJBPath(path) && !isGumTracePath(path)) this.block = true; + } catch (e) {} + }, + onLeave: function (retval) { + if (this.block) retval.replace(ptr(0)); + } + }); + } + } catch (e) {} + + // getenv —— 隐藏 DYLD 注入痕迹 + try { + var envAddr = Module.findGlobalExportByName('getenv'); + var hideEnv = ['DYLD_INSERT_LIBRARIES', 'DYLD_FORCE_FLAT_NAMESPACE', + '_MSSafeMode', '_SafeMode']; + if (envAddr) { + Interceptor.attach(envAddr, { + onEnter: function (args) { + try { + var name = args[0].readUtf8String(); + if (hideEnv.indexOf(name) >= 0) this.hide = true; + } catch (e) {} + }, + onLeave: function (retval) { + if (this.hide) retval.replace(ptr(0)); + } + }); + } + } catch (e) {} + + // ptrace PT_DENY_ATTACH 反调试 bypass + try { + var pt = Module.findGlobalExportByName('ptrace'); + if (pt) Interceptor.replace(pt, + new NativeCallback(function () { return 0; }, + 'int', ['int', 'int', 'pointer', 'int'])); + } catch (e) {} + + // sysctl —— 清 kinfo_proc.kp_proc.p_flag 的 P_TRACED 位 + try { + var sysctlAddr = Module.findGlobalExportByName('sysctl'); + if (sysctlAddr) { + Interceptor.attach(sysctlAddr, { + onEnter: function (args) { + try { + if (args[0].isNull()) return; + // CTL_KERN(1) → KERN_PROC(14) → KERN_PROC_PID(1) 的反调试探针 + if (args[0].readU32() === 1 && + args[0].add(4).readU32() === 14 && + args[0].add(8).readU32() === 1) { + this.ip = args[2]; + } + } catch (e) {} + }, + onLeave: function () { + try { + if (this.ip && !this.ip.isNull()) { + var f = this.ip.add(32); // kp_proc.p_flag 偏移 + var v = f.readU32(); + if (v & 0x800) f.writeU32(v & ~0x800); // 清 P_TRACED + } + } catch (e) {} + } + }); + } + } catch (e) {} + + // _dyld_get_image_name —— 把 jb 路径替换成系统 dylib,骗过 dyld 扫描 + try { + var dyldNameAddr = Module.findGlobalExportByName('_dyld_get_image_name'); + var fakePath = null; + if (dyldNameAddr) { + Interceptor.attach(dyldNameAddr, { + onLeave: function (retval) { + try { + if (retval.isNull()) return; + var path = retval.readUtf8String(); + if (path && isJBPath(path)) { + if (!fakePath) fakePath = Memory.allocUtf8String('/usr/lib/libSystem.B.dylib'); + retval.replace(fakePath); + } + } catch (e) {} + } + }); + } + } catch (e) {} + + console.log(TAG + ' anti-jb OK'); +})(); + +// ───────────────────────────────────────────────────────────────────────── +// 统计 + 状态 +// ───────────────────────────────────────────────────────────────────────── + +function bytesToHex(arr) { + var s = ''; + for (var i = 0; i < arr.length; i++) + s += ('0' + (arr[i] & 0xff).toString(16)).slice(-2); + return s; +} + +var stats = { arc4: 0, header: 0, dataTask: 0 }; +var state = 'idle'; // idle → tracing → done +var tracePath = null; +var capturedKeys = []; + +// ───────────────────────────────────────────────────────────────────────── +// IIFE 2:arc4random_buf hook + 深调用栈(定位算法入口) +// ───────────────────────────────────────────────────────────────────────── + +(function hookArc4() { + try { + var addr = null; + var mod = Process.findModuleByName('libSystem.B.dylib'); + if (mod) addr = mod.findExportByName('arc4random_buf'); + if (!addr) { + mod = Process.findModuleByName('libsystem_c.dylib'); + if (mod) addr = mod.findExportByName('arc4random_buf'); + } + if (!addr) { console.log(TAG + ' arc4 not found'); return; } + Interceptor.attach(addr, { + onEnter: function (args) { + this.buf = args[0]; + this.len = args[1].toInt32(); + }, + onLeave: function () { + if (this.len !== 32) return; // 你的目标用 16/48/64 字节就改这里 + stats.arc4++; + var hex = bytesToHex(new Uint8Array(this.buf.readByteArray(32))); + + // 15 层调用栈;第一个在目标模块内的 frame = 算法入口候选 + var disc = Process.findModuleByName(TARGET_MODULE); + var btFrames = []; + var firstModRva = null; + try { + var bt = Thread.backtrace(this.context, Backtracer.ACCURATE); + for (var j = 0; j < Math.min(bt.length, 15); j++) { + var a = bt[j]; + var inMod = disc && a.compare(disc.base) >= 0 && + a.compare(disc.base.add(disc.size)) < 0; + var off = inMod ? '+0x' + a.sub(disc.base).toString(16) : ''; + btFrames.push({ addr: a.toString(), rva: off, inMod: inMod }); + if (inMod && !firstModRva) firstModRva = off; + } + } catch (e) {} + + capturedKeys.push({ hex: hex, t: Date.now(), bt: btFrames }); + + // 前 5 次完整打调用栈(找算法入口最关键) + if (stats.arc4 <= 5) { + console.log(TAG + ' arc4 #' + stats.arc4 + ': ' + hex); + if (firstModRva) console.log(TAG + ' 算法入口候选: ' + TARGET_MODULE + firstModRva); + for (var k = 0; k < btFrames.length; k++) { + var marker = btFrames[k].inMod ? '*' : ' '; + console.log(TAG + ' ' + marker + '[' + k + '] ' + btFrames[k].addr + + (btFrames[k].rva ? ' (' + TARGET_MODULE + btFrames[k].rva + ')' : '')); + } + } + } + }); + console.log(TAG + ' arc4 OK'); + } catch (e) {} +})(); + +console.log(TAG + ' === spawn trace ready (target=' + TARGET_TRACE_GB + 'GB, module=' + TARGET_MODULE + ') ==='); + +// ───────────────────────────────────────────────────────────────────────── +// 延迟 500ms 装 ObjC hook(等 ObjC runtime 稳定) +// ───────────────────────────────────────────────────────────────────────── + +setTimeout(function () { + if (!ObjC.available) { setTimeout(arguments.callee, 500); return; } + + // setValue:forHTTPHeaderField: —— 捕获签名 header + try { + var sel = ObjC.classes.NSMutableURLRequest['- setValue:forHTTPHeaderField:']; + if (sel) { + Interceptor.attach(sel.implementation, { + onEnter: function (args) { + try { + var field = ObjC.Object(args[3]).toString(); + if (!TARGET_HEADERS_RE.test(field)) return; + var value = ObjC.Object(args[2]).toString(); + stats.header++; + if (stats.header <= 6) { + console.log(TAG + ' header #' + stats.header + ' ' + field + '=' + + (value.length > 96 ? value.slice(0, 96) + '...' : value)); + } + } catch (e) {} + } + }); + console.log(TAG + ' setValue hook OK'); + } + } catch (e) {} + + // dataTaskWithRequest: —— stalker 触发器 + try { + var m = new ApiResolver('objc').enumerateMatches('-[NSURLSession dataTaskWithRequest:]'); + if (m.length) { + Interceptor.attach(m[0].address, { + onEnter: function (args) { + try { + var url = ObjC.Object(args[2]).URL().absoluteString().toString(); + if (!TARGET_URL_RE.test(url)) return; + stats.dataTask++; + if (state === 'idle') { + console.log(TAG + ' http #' + stats.dataTask + ': ' + url); + startStalker(); + } else if (state === 'tracing' && stats.dataTask % 10 === 0) { + console.log(TAG + ' progress dataTask=' + stats.dataTask + ' header=' + stats.header); + } + } catch (e) {} + } + }); + console.log(TAG + ' dataTask hook OK'); + } + } catch (e) {} +}, 500); + +// ───────────────────────────────────────────────────────────────────────── +// stalker 启动函数(NativeFunction + Module.load 都在函数体内 JIT 构造, +// 不在 V8 启动期 heap 里留 stalker / NativeFunction 等可疑字符串字面量) +// ───────────────────────────────────────────────────────────────────────── + +function startStalker() { + if (state !== 'idle') return; + state = 'tracing'; + try { + var gtMod = Process.enumerateModules().find(function (m) { + return m.path.indexOf(GT) >= 0; + }); + if (!gtMod) gtMod = Module.load(DYLIB_PATH); + var initFn = new NativeFunction(gtMod.findExportByName('init'), + 'void', ['pointer','pointer','int','pointer']); + var runFn = new NativeFunction(gtMod.findExportByName('run'), 'void', []); + var unrunFn = new NativeFunction(gtMod.findExportByName('unrun'), 'void', []); + + var home = ObjC.classes.NSString.stringWithString_('~') + .stringByExpandingTildeInPath().toString(); + tracePath = home + '/Documents/' + TRACE_NAME; + + var mn = Memory.allocUtf8String(TARGET_MODULE); + var op = Memory.allocUtf8String(tracePath); + var opt = Memory.alloc(8); opt.writeU64(1); // 1 = Debug(频繁 flush) + initFn(mn, op, 0, opt); // threadId=0 → follow_me 装当前线程 + runFn(); + console.log(TAG + ' STALKER ACTIVE @ tid=' + Process.getCurrentThreadId() + + ' path=' + tracePath); + + var MAX = TARGET_TRACE_GB * 1024 * 1024 * 1024; + var HARD = MAX_TRACE_GB * 1024 * 1024 * 1024; + var NSFM = ObjC.classes.NSFileManager.defaultManager(); + var nsPath = ObjC.classes.NSString.stringWithString_(tracePath); + var sizeKey = ObjC.classes.NSString.stringWithString_('NSFileSize'); + var lastMB = 0; + var watcher = setInterval(function () { + try { + var attrs = NSFM.attributesOfItemAtPath_error_(nsPath, NULL); + if (!attrs || attrs.isNull()) return; + var sz = attrs.objectForKey_(sizeKey); + if (!sz || sz.isNull()) return; + var bytes = sz.unsignedLongLongValue(); + var mb = Math.floor(bytes / (1024 * 1024)); + if (mb >= lastMB + 100) { + console.log(TAG + ' size ' + (bytes / 1073741824).toFixed(2) + + ' GB | dataTask=' + stats.dataTask + + ' header=' + stats.header); + lastMB = mb; + } + if (bytes >= MAX || bytes >= HARD) { + clearInterval(watcher); + state = 'done'; + // 双路 unrun:直接调 + mainQueue(解决跨线程 unfollow_me) + try { unrunFn(); } catch (e) {} + ObjC.schedule(ObjC.mainQueue, function () { + try { unrunFn(); } catch (e) {} + console.log('\n' + TAG + ' STOPPED'); + console.log(TAG + ' stats: ' + JSON.stringify(stats)); + console.log(TAG + ' trace: ' + tracePath); + console.log(TAG + ' 拉回(gzip 流式压缩传输):'); + console.log(TAG + " scp -P 2222 -C root@localhost:'" + tracePath + "' ./"); + }); + } + } catch (e) {} + }, 1000); + } catch (e) { + console.log(TAG + ' startStalker err: ' + e); + state = 'idle'; + } +} + +// ───────────────────────────────────────────────────────────────────────── +// RPC:在 frida REPL 里 rpc.exports.xxx() 实时查捕获数据 +// ───────────────────────────────────────────────────────────────────────── + +rpc.exports = { + stats: function () { return stats; }, + keys: function () { return capturedKeys; }, // 所有 arc4(32) + 调用栈 + state: function () { return { state: state, tracePath: tracePath }; }, +};