#!/usr/bin/env python3
"""In-memory test: swap the shield's app delegate for a real Driver.AppDelegate
at -[UIApplication setDelegate:] time, and restore the Driver launch-path sites.
Goal: see whether the real app (Flutter) starts."""
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 m1 = new NativeFunction(e('objc_msgSend'), 'pointer', ['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; };

// restore Driver launch-path sites
const drv = Process.getModuleByName('Driver');
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});

// swap the shield's delegate for the real one
const shieldCls = cls('Function_UmcOPEDGyT');
const realCls = cls('Driver.AppDelegate');
let swapped = 0;
const mSetDel = class_getInstanceMethod(cls('UIApplication'), sel('setDelegate:'));
var swapCB = new NativeCallback(function (self, cmd, newDel) {
    const cname = newDel.isNull() ? 'nil' : object_getClassName(newDel).readCString();
    if (!newDel.isNull() && !object_getClassName(newDel).readCString().localeCompare('Function_UmcOPEDGyT')) {
        swapped++;
        const inst = m0(m0(realCls, sel('alloc')), sel('init'));
        send({type: 'SWAPPED', n: swapped, realCls: object_getClassName(inst).readCString()});
        newDel = inst;
    } else {
        send({type: 'setDelegate_passthru', cls: cname});
    }
    const orig = new NativeFunction(method_getImplementation(mSetDel), 'void', ['pointer', 'pointer', 'pointer']);
    orig(self, cmd, newDel);
}, 'void', ['pointer', 'pointer', 'pointer']);
method_setImplementation(mSetDel, swapCB);
send({type: 'swap_installed'});

// scene config -> let the real one through (patch to nil so Info.plist is used)
const bi = Process.getModuleByName('build-info');
Memory.patchCode(bi.base.add(0x292198), 8, p => p.writeByteArray(hb('000080d2c0035fd6')));
send({type: 'scene_cfg_nil'});

// watchers
try {
    const mSD = class_getInstanceMethod(cls('Driver.SceneDelegate'), sel('scene:willConnectToSession:options:'));
    Interceptor.attach(method_getImplementation(mSD), { onEnter() { send({type: 'REAL_SD_willConnect'}); } });
} catch (er) { send({type: 'hookerr_sd', e: String(er)}); }
try {
    Interceptor.attach(drv.base.add(0x3271c), { onEnter() { send({type: 'REAL_SCENE_FN'}); } });
} catch (er) { send({type: 'hookerr_scene_fn', e: String(er)}); }
try {
    const mDFL = class_getInstanceMethod(realCls, sel('application:didFinishLaunchingWithOptions:'));
    Interceptor.attach(method_getImplementation(mDFL), { onEnter() { send({type: 'REAL_DFL'}); } });
} catch (er) { send({type: 'hookerr_dfl', e: String(er)}); }

const hooked = {};
const tryHook = (cname, sname, label) => {
    const k = cname + '|' + sname;
    if (hooked[k]) return;
    const c = cls(cname); if (c.isNull()) return;
    const m = class_getInstanceMethod(c, sel(sname)); if (m.isNull()) return;
    hooked[k] = true;
    try {
        Interceptor.attach(method_getImplementation(m), { onEnter() { send({type: 'HIT', label: label}); } });
        send({type: 'hooked', label: label, imp: modOf(method_getImplementation(m))});
    } catch (er) { send({type: 'hookerr', label: label, e: String(er)}); }
};
const iv = setInterval(() => {
    tryHook('FlutterEngine', 'run', 'fe_run');
    tryHook('FlutterEngine', 'runWithEntrypoint:', 'fe_run1');
    tryHook('FlutterViewController', 'initWithEngine:nibName:bundle:', 'fvc_initEngine');
    tryHook('FlutterViewController', 'viewDidLoad', 'fvc_viewDidLoad');
}, 300);
setTimeout(() => clearInterval(iv), 25000);

setTimeout(function () {
    try {
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const dg = m0(app, sel('delegate'));
        const scenes = m0(app, sel('connectedScenes'));
        const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
        const sc = anyF(scenes, sel('anyObject'), 0);
        const sdg = sc.isNull() ? ptr(0) : m0(sc, sel('delegate'));
        let win = ptr(0), rvc = ptr(0);
        if (!sdg.isNull()) {
            win = m0(sdg, sel('window'));
            if (!win.isNull()) rvc = m0(win, sel('rootViewController'));
        }
        send({type: 'state',
              appDelegate: dg.isNull() ? 'nil' : object_getClassName(dg).readCString(),
              sceneDelegate: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString(),
              window: win.isNull() ? 'nil' : object_getClassName(win).readCString(),
              rootVC: rvc.isNull() ? 'nil' : object_getClassName(rvc).readCString()});
    } catch (er) { send({type: 'state_err', e: String(er)}); }
}, 10000);
"""


class Watchdog:
    def __init__(self, secs=150):
        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(150)
    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)[:600], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(24)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
