#!/usr/bin/env python3
"""Probe: is -[Function_UmcOPEDGyT application:configurationForConnectingSceneSession:options:]
called at all now? Also watch -[UIApplication _connectUISceneFromFBSScene:...] and
-[UIApplication setDelegate:] with backtraces."""
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 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 mCfg = class_getInstanceMethod(cls('Function_UmcOPEDGyT'),
    sel('application:configurationForConnectingSceneSession:options:'));
const cfgImp = method_getImplementation(mCfg);
send({type: 'cfg_imp', imp: modOf(cfgImp)});
try {
    Interceptor.attach(cfgImp, { onEnter(a) {
        send({type: 'CFG_CALLED', bt: Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 8).map(modOf)});
    }});
    send({type: 'hooked_cfg'});
} catch (er) { send({type: 'hookerr_cfg', e: String(er)}); }

const mDFL = class_getInstanceMethod(cls('Function_UmcOPEDGyT'),
    sel('application:didFinishLaunchingWithOptions:'));
try {
    Interceptor.attach(method_getImplementation(mDFL), { onEnter() { send({type: 'SHIELD_DFL'}); } });
    send({type: 'hooked_dfl'});
} catch (er) { send({type: 'hookerr_dfl', e: String(er)}); }

// UIKit scene connect
try {
    const p = Module.getExportByName('UIKitCore', '-[UIApplication _connectUISceneFromFBSScene:transitionContext:completion:]');
    Interceptor.attach(p, { onEnter() { send({type: 'CONNECT_SCENE'}); } });
    send({type: 'hooked_connect'});
} catch (er) { send({type: 'hookerr_connect', e: String(er)}); }

// where does the scene delegate class come from
try {
    const p2 = Module.getExportByName('UIKitCore', '-[UIApplication _createSceneDelegateForScene:withActivationParameters:]');
    Interceptor.attach(p2, { onLeave(v) { send({type: 'CREATE_SCENE_DELEGATE', ret: v.toString()}); } });
    send({type: 'hooked_createsd'});
} catch (er) { send({type: 'hookerr_createsd', e: String(er)}); }

const mSetDel = class_getInstanceMethod(cls('UIApplication'), sel('setDelegate:'));
try {
    Interceptor.attach(method_getImplementation(mSetDel), { onEnter(a) {
        send({type: 'SET_DELEGATE', cls: object_getClassName(a[2]).readCString()});
    }});
    send({type: 'hooked_setdel'});
} catch (er) { send({type: 'hookerr_setdel', e: String(er)}); }

setTimeout(function () {
    try {
        const m0 = new NativeFunction(e('objc_msgSend'), '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(),
              sceneDelegate: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString()});
    } catch (er) { send({type: 'state_err', e: String(er)}); }
}, 9000);
"""


class Watchdog:
    def __init__(self, secs=110):
        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(110)
    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(16)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
