#!/usr/bin/env python3
"""Localise the launch-path trap with Stalker block tracing.
Follows the thread only across the real Driver.AppDelegate
application:didFinishLaunchingWithOptions: call, then (deferred, so Stalker's
onReceive has time to deliver) reports the last Driver/build-info blocks executed
before the trap. Also hooks the few local functions called early in 0x3b8da4 as a
fallback localisation."""
import os, sys, time, json, threading

sys.stdout.reconfigure(encoding='utf-8')
import frida

BID = 'vn.gsm.md'

JS = r"""
const libobjc = Process.getModuleByName('libobjc.A.dylib');
const e = n => libobjc.getExportByName(n);
const objc_getClass = new NativeFunction(e('objc_getClass'), 'pointer', ['pointer']);
const sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const method_setImplementation = new NativeFunction(e('method_setImplementation'), 'pointer', ['pointer', 'pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };
const m0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const m2 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer', 'pointer']);
const hb = h => { const b = []; for (let i = 0; i < h.length; i += 2) b.push(parseInt(h.substr(i, 2), 16)); return b; };

const drv = Process.getModuleByName('Driver');
const drvLo = drv.base, drvHi = drv.base.add(drv.size);
const bi = Process.getModuleByName('build-info');
const biLo = bi.base, biHi = bi.base.add(bi.size);

// ---- restore Driver launch-path sites ----
const sites = [[0x031fa8, '37316394'], [0x03281c, '3f2e6394'], [0x032bf8, 'a03b00b4'],
               [0x0333cc, '2e2c6394'], [0x035e4b4, '197f5694'], [0x03b8e0c, '9e155594'],
               [0x05de9c8, '48774c94'], [0x18fe118, '902e00d0'], [0x18fe484, '902e00d0'],
               [0x18fc6e8, 'a03a00d0'], [0x190c47c, '702e00d0']];
for (const [off, h] of sites) { const a = drv.base.add(off); Memory.patchCode(a, 4, p => p.writeByteArray(hb(h))); }
send({type: 'driver_restored', n: sites.length});

// ---- fallback localisation: local functions called early inside 0x3b8da4 ----
const probeFns = [0x3bc904, 0x246c58, 0x2dc64, 0x3bcb70, 0x23a1e8, 0x19228a0, 0x19024f8];
for (const off of probeFns) {
    try {
        Interceptor.attach(drv.base.add(off), { onEnter() { send({type: 'REACH', fn: '0x' + off.toString(16)}); } });
        send({type: 'hooked_probe', fn: '0x' + off.toString(16)});
    } catch (er) { send({type: 'probe_fail', fn: '0x' + off.toString(16), e: String(er)}); }
}

// ---- Stalker trace across the trap ----
let chunks = [];
const realAD = cls('Driver.AppDelegate');
const shieldSD = cls('Function_JgvFbyFH');
const mWC = class_getInstanceMethod(shieldSD, sel('scene:willConnectToSession:options:'));

function parseTrace(trapped) {
    const toPtr = (x) => (typeof x === 'string' ? ptr(x) : x);
    const seq = [];
    let total = 0;
    for (const ch of chunks) {
        let parsed = null;
        try { parsed = Stalker.parse(ch, { annotate: false, stringify: false }); }
        catch (er) { continue; }
        if (!parsed) continue;
        total += parsed.length;
        for (const ev of parsed) {
            let a = null, b = null;
            try { a = toPtr(ev[0]); b = ev.length > 1 ? toPtr(ev[1]) : null; } catch (er) { continue; }
            if (!a || a.isNull()) continue;
            const inR = (x, lo, hi) => x && x.compare(lo) >= 0 && x.compare(hi) < 0;
            if (inR(a, drvLo, drvHi) || inR(a, biLo, biHi) ||
                inR(b, drvLo, drvHi) || inR(b, biLo, biHi)) {
                seq.push([modOf(a), b ? modOf(b) : '?']);
            }
        }
    }
    send({type: 'trace_len', total: total, n: seq.length, trapped: trapped});
    for (const t of seq.slice(-26)) send({type: 'blk', from: t[0], to: t[1]});
}

var cb = new NativeCallback(function (self, cmd, scene, session, options) {
    send({type: 'HANDOFF'});
    const tid = Process.getCurrentThreadId();
    chunks = [];
    let trapped = null;
    try { Stalker.follow(tid, { events: { block: true, call: false, ret: false, exec: false },
                                onReceive: function (ev) { chunks.push(ev); } }); }
    catch (er) { send({type: 'stalker_err', e: String(er)}); }
    try {
        const adInst = m0(m0(realAD, sel('alloc')), sel('init'));
        send({type: 'real_ad', cls: object_getClassName(adInst).readCString()});
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const r = m2(adInst, sel('application:didFinishLaunchingWithOptions:'), app, ptr(0));
        send({type: 'real_dfl_ok', r: r.toString()});
    } catch (er) { trapped = String(er); send({type: 'TRAP', e: trapped}); }
    try { Stalker.unfollow(tid); Stalker.flush(); } catch (er) { send({type: 'flush_err', e: String(er)}); }
    setTimeout(function () { parseTrace(trapped); }, 500);
}, 'void', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
method_setImplementation(mWC, cb);
send({type: 'handoff_installed'});
"""


class Watchdog:
    def __init__(self, secs=180):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.25)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


def main():
    Watchdog(180)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('kill stale', p.pid, flush=True)
            try:
                dev.kill(p.pid)
            except Exception:
                pass
    time.sleep(1.5)
    pid = dev.spawn([BID])
    print('spawned', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:900], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(26)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
