#!/usr/bin/env python3 """完整链路验证: 正常启动App → attach + SSL_write hook → 存活观察 + 抓dfpReport. 基于最新发现: attach 不再必然被杀 (E0-E7 状态依赖)。 流程: 1. monkey 正常启动 App (无 frida) 2. 等 8s (App 完全起来) 3. attach 主进程 + SSL_write/SSL_read hook (零 bypass) 4. 用 /proc 精确监控主进程存活; logcat crash 同步 5. 观察到 dfpReport + actionV 即停 用法: python3 emu_attach_capture_v2.py [--waits N] [--observe S] """ 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" 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 main(): ap = argparse.ArgumentParser() ap.add_argument("--wait", type=float, default=8.0) ap.add_argument("--observe", type=int, default=40) ap.add_argument("--out", default="/Users/yml/codes/douyu_login_py/evidence/emu_attach_capture_v2.json") args = ap.parse_args() d = frida.get_device_manager().add_remote_device(REMOTE) adb("shell", "am", "force-stop", PACKAGE) time.sleep(1.5) adb("shell", "logcat", "-c") adb("shell", "monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1") time.sleep(args.wait) pid = main_pid() print(f"[*] App 启动 {args.wait}s, 主进程 pid={pid}", flush=True) if pid is None: print("[!] 无主进程, 退出"); return t0 = time.time() try: session = d.attach(pid) print(f"[*] attach ok at +{(time.time()-t0)*1000:.0f}ms", flush=True) except Exception as e: print(f"[!] attach err {e}", flush=True); return events = [] got_dfp = [False] actionVs = [] def on_main(m, dta): if m.get('type') == 'error': print(" [JS-ERR]", str(m)[:120], flush=True) return p = m.get('payload') or {} t = p.get('type') if t == 'hooked': print("[*] SSL_write hooked", flush=True) elif 'cls' in p: print(f"[*] {p['cls']} len={p['len']}", flush=True) 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()) if av: print(f"[*] RESP actionV {av.group(1).decode()}", flush=True) events.append(p) def on_detach(reason, detail): print(f"[*] DETACHED reason={reason} detail={str(detail)[:100]}", flush=True) session.on('detached', on_detach) try: sc = session.create_script(MAIN_JS) sc.on('message', on_main) sc.load() except Exception as e: print(f"[!] script err {e}", flush=True) # 监控: 每2s 主进程存活 died_at = None while time.time() - t0 < args.observe: time.sleep(2) mp = main_pid() if mp is None: died_at = time.time() - t0 print(f"[*] 主进程死 at +{died_at:.0f}s", flush=True) break if mp != pid: print(f"[*] pid变化 {pid}->{mp} (KeepAlive?) at +{time.time()-t0:.0f}s", flush=True) died_at = time.time() - t0 break cr = adb("shell", "logcat", "-d", "-b", "crash", "-t", "10").stdout print(f"[*] 结果: 存活={died_at is None} 存活时长={died_at or args.observe}s EGL崩={'EGL' in cr} 事件={len(events)} actionV={actionVs[:2]}", flush=True) Path(args.out).write_text(json.dumps(events, ensure_ascii=False, indent=1)) try: session.detach() except Exception: pass print(f"[*] done -> {args.out}", flush=True) if __name__ == "__main__": main()