#!/usr/bin/env python3
"""Experiment 3: make the shield's
   -[Function_UmcOPEDGyT application:configurationForConnectingSceneSession:options:]
return nil, so UIKit falls back to the Info.plist scene manifest
(UISceneDelegateClassName = Driver.SceneDelegate).

Watches: real SceneDelegate willConnect, Driver+0x3271c, FlutterEngine run,
FlutterViewController creation, and the live scene delegate.
"""
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 shield = cls('Function_UmcOPEDGyT');
const mCfg = class_getInstanceMethod(shield, sel('application:configurationForConnectingSceneSession:options:'));
send({type: 'cfg_imp', imp: mCfg.isNull() ? 'nil' : modOf(method_getImplementation(mCfg))});

let calls = 0;
const cb = new NativeCallback(function (self, cmd, app, session, options) {
    calls++;
    send({type: 'cfg_called', n: calls});
    return ptr(0);
}, 'pointer', ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
method_setImplementation(mCfg, cb);
send({type: 'cfg_swizzled'});

// real scene delegate method
try {
    const sd = cls('Driver.SceneDelegate');
    const mSD = class_getInstanceMethod(sd, sel('scene:willConnectToSession:options:'));
    send({type: 'sd_imp', imp: mSD.isNull() ? 'nil' : modOf(method_getImplementation(mSD))});
    if (!mSD.isNull()) {
        Interceptor.attach(method_getImplementation(mSD), {
            onEnter(a) { send({type: 'REAL_SD_willConnect', scene: a[2].toString()}); }
        });
        send({type: 'hooked_sd'});
    }
} catch (er) { send({type: 'hookerr_sd', e: String(er)}); }

try {
    Interceptor.attach(Process.getModuleByName('Driver').base.add(0x3271c),
        { onEnter(a) { send({type: 'REAL_SCENE_FN'}); } });
    send({type: 'hooked_scene_fn'});
} catch (er) { send({type: 'hookerr_scene_fn', e: String(er)}); }

// Flutter engine / VC
let 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 poll = () => {
    tryHook('FlutterEngine', 'run', 'fe_run');
    tryHook('FlutterEngine', 'runWithEntrypoint:', 'fe_run1');
    tryHook('FlutterViewController', 'initWithEngine:', 'fvc_initEngine');
    tryHook('FlutterViewController', 'initWithProject:', 'fvc_initProject');
    tryHook('FlutterViewController', 'viewDidLoad', 'fvc_viewDidLoad');
};
const iv = setInterval(poll, 300);
setTimeout(() => clearInterval(iv), 20000);
poll();

// live state at 10s
setTimeout(function () {
    try {
        const m0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
        const m1 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'pointer']);
        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'));
        send({type: 'state',
              appDelegate: dg.isNull() ? 'nil' : object_getClassName(dg).readCString(),
              scene: sc.isNull() ? 'nil' : object_getClassName(sc).readCString(),
              sceneDelegate: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString()});
        if (!sdg.isNull()) {
            const win = m0(sdg, sel('window'));
            const rvc = win.isNull() ? ptr(0) : m0(win, sel('rootViewController'));
            send({type: 'state2',
                  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(25)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
