#!/usr/bin/env python3 """模拟器抓包 v11: B组优先三策略 (基于 diag E0-E7 实验结论). 结论回顾 (GC3VE/Android12/frida15.2.2): - 纯 spawn→resume (不attach) = 存活, 但无 hook 能力 (B组/E3, 多次3/3存活) - 任何 attach (挂起中/延迟, 有无脚本) = 被杀: 空attach静默_exit / attach+bypass=EGL崩 - 历史上 spawn+挂起attach+bypass 曾抓到 dfpReport+actionV, 但 App 随后必崩 (抢窗口) 本脚本提供三种模式: zero (默认) 纯B组: spawn→立即resume→存活观察 (无hook, 验证App真能活/验证码可用) race B组+延迟attach: resume后2s attach+bypass+SSLhook, 抢dfp窗口 (接受闪退) stale 旧法对照: 挂起中加载 art_callsite+mask 再resume (复现历史成功路径) 用法: python3 emu_hook_zero_suspend.py [--mode zero|race|stale] [--rounds N] [--out path] """ from pathlib import Path import frida, time, json, re, subprocess, sys, argparse REMOTE = "127.0.0.1:31878" ADB = ["adb", "-s", "127.0.0.1:5555"] PACKAGE = "com.duowan.kiwi" RE = Path("/Users/yml/codes/Reverse-Engineering-Agent-Universal-v3.0") MAIN_JS = r""" 'use strict'; send({type:'armed', t:Date.now()}); function hexb(p,n){try{return Array.from(new Uint8Array(p.readByteArray(n))).map(b=>('0'+b.toString(16)).slice(-2)).join('');}catch(e){return '';}} function head(p,n){try{return p.readCString(n);}catch(e){return '';}} var n=0; try{ var r=new ApiResolver('module'); r.enumerateMatchesSync('exports:*!SSL_write').forEach(function(m){ Interceptor.attach(m.address,{onEnter:function(a){ var len=a[2].toInt32(); if(len<50||len>50000)return; var h=head(a[1],Math.min(len,1500)); if(h.indexOf('dfpReport')>=0||h.indexOf('dckey')>=0){ n++; send({cls:h.indexOf('dfpReport')>=0?'dfpReport':'dckey',n:n,len:len,t:Date.now(),hex:hexb(a[1],len)}); } }}); }); send({type:'hooked', t:Date.now()}); }catch(e){send({type:'err',e:String(e)});} try{ var r2=new ApiResolver('module'); r2.enumerateMatchesSync('exports:*!SSL_read').forEach(function(m){ Interceptor.attach(m.address,{onEnter:function(a){this.buf=a[1];}, onLeave:function(ret){ var nn=ret.toInt32(); if(nn<=0||nn>4000)return; send({type:'resp',len:nn,hex:hexb(this.buf,nn),t:Date.now()}); }}); }); send({type:'readhooked'}); }catch(e){send({type:'readerr',e:String(e)});} """ def sh(*a): return subprocess.run(a, capture_output=True, text=True) def adb(*a): return sh(*ADB, *a) def main_pid(): r = adb("shell", "pidof", PACKAGE) for p in r.stdout.strip().split(): rr = adb("shell", "cat", f"/proc/{p}/cmdline") if rr.stdout.strip("\x00").strip() == PACKAGE: return int(p) return None def detach_cb(reason, detail, tag=""): print(f" [detached:{tag}] reason={reason} detail={str(detail)[:120]}", flush=True) def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", default="zero", choices=["zero", "race", "stale"]) ap.add_argument("--out", default="/Users/yml/codes/douyu_login_py/evidence/emu_hook_v11.json") ap.add_argument("--rounds", type=int, default=2) args = ap.parse_args() out_path = Path(args.out) d = frida.get_device_manager().add_remote_device(REMOTE) print(f"[*] mode={args.mode} rounds={args.rounds} OUT={out_path}", flush=True) all_events = [] for rnd in range(1, args.rounds + 1): adb("shell", "am", "force-stop", PACKAGE) time.sleep(1.2) adb("shell", "logcat", "-c") pid = None session = None try: pid = d.spawn([PACKAGE]) t_spawn = time.time() if args.mode == "stale": # 旧法: 挂起中加载2个脚本再resume session = d.attach(pid) session.on('detached', lambda r, dd, t=f"[r{rnd}]": detach_cb(r, dd, t)) for name in ("bypass_msaoaid_maps_art_callsite.js", "mask_frida_maps_only.js"): sc = session.create_script((RE/"evidence/scripts"/name).read_text()); sc.load() suspend_ms = (time.time() - t_spawn) * 1000 d.resume(pid) print(f"[r{rnd}] stale: spawn pid={pid} 挂起{suspend_ms:.0f}ms(2脚本) resumed", flush=True) time.sleep(0.5) else: # zero/race: 先立即 resume (B组存活) d.resume(pid) print(f"[r{rnd}] spawn pid={pid} 立即resumed (B组存活)", flush=True) if args.mode == "race": time.sleep(2.0) t_att = time.time() session = d.attach(pid) session.on('detached', lambda r, dd, t=f"[r{rnd}]": detach_cb(r, dd, t)) for name in ("bypass_msaoaid_maps_art_callsite.js", "mask_frida_maps_only.js"): sc = session.create_script((RE/"evidence/scripts"/name).read_text()); sc.load() print(f"[r{rnd}] race: attach at +{(time.time()-t_spawn)*1000:.0f}ms +2脚本 +{(time.time()-t_att)*1000:.0f}ms", flush=True) events = [] got_dfp = [False] actionVs = [] def on_main(m, dta): if m.get('type') == 'error': return p = m.get('payload') or {} t = p.get('type') if t == 'hooked': print(f"[r{rnd}] SSL_write hooked", flush=True) elif 'cls' in p: print(f"[r{rnd}] {p['cls']} len={p['len']}", flush=True) events.append(p); all_events.append(p) if p['cls'] == 'dfpReport': got_dfp[0] = True elif t == 'resp': av = re.search(rb'actionV\(([0-9a-f]{40})', bytes.fromhex(p.get('hex') or '')) mark = f" actionV={av.group(1).decode()}" if av else "" if av: actionVs.append(av.group(1).decode()) print(f"[r{rnd}] RESP len={p['len']}{mark}", flush=True) events.append(p); all_events.append(p) if session: sc = session.create_script(MAIN_JS) sc.on('message', on_main) sc.load() # 存活监控 (死因判定: crash buffer 有记录=EGL崩, 无=静默_exit) t0 = time.time() died_at = None while time.time() - t0 < 30: time.sleep(2) mp = main_pid() if mp is None: died_at = time.time() - t0 break if mp != pid: print(f"[r{rnd}] pid变化 {pid}->{mp} (KeepAlive重启)", flush=True) died_at = time.time() - t0 break if got_dfp[0] and time.time() - t0 > 15: break cr = adb("shell", "logcat", "-d", "-b", "crash", "-t", "20").stdout crashed = bool(re.search(r"Fatal|Abort message|signal \d", cr)) print(f"[r{rnd}] 结束: 存活={died_at is None} 死后至+{round(died_at,1) if died_at else '-'} 崩={crashed} 事件={len(events)} actionV={actionVs[:2]}", flush=True) try: if session: session.detach() except Exception: pass try: d.kill(pid) except Exception: pass except Exception as e: print(f"[r{rnd}] ERR {repr(e)[:140]}", flush=True) try: if session: session.detach() except Exception: pass try: d.kill(pid) except Exception: pass time.sleep(1.5) out_path.write_text(json.dumps(all_events, ensure_ascii=False, indent=1)) print(f"[*] 结束 事件={len(all_events)} -> {out_path}", flush=True) if __name__ == "__main__": main()