#!/usr/bin/env python3
"""Dump method list of the obfuscated app delegate class; hook UIScene.setDelegate: to catch
the scene delegate; trace UIWindow creation back to its creator module."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'


class Watchdog:
    def __init__(self, secs=120):
        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)


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_getName = new NativeFunction(e('class_getName'), 'pointer', ['pointer']);
const class_copyMethodList = new NativeFunction(e('class_copyMethodList'), 'pointer', ['pointer', 'pointer']);
const sel_getName = new NativeFunction(e('sel_getName'), 'pointer', ['pointer']);
const method_getName = new NativeFunction(e('method_getName'), 'pointer', ['pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const cname = o => o.isNull() ? '(nil)' : object_getClassName(o).readCString();
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

function methodList(clsName) {
    const c = cls(clsName);
    if (c.isNull()) return null;
    const cntP = Memory.alloc(Process.pointerSize);
    const list = class_copyMethodList(c, cntP);
    const n = cntP.readUInt();
    const out = [];
    for (let i = 0; i < n; i++) {
        const meth = list.add(i * Process.pointerSize).readPointer();
        out.push({sel: sel_getName(method_getName(meth)).readCString(),
                  imp: modOf(method_getImplementation(meth))});
    }
    return out;
}

const DL = 'Function_UmcOPEDGyT';
send({type: 'delegateMethods', list: methodList(DL)});

// what scene/delegate classes does the shield's configuration request?
for (const [s2, l2] of [['setDelegateClass:', 'cfgDelegateClass'], ['setSceneClass:', 'cfgSceneClass']]) {
    const m = class_getInstanceMethod(cls('UISceneConfiguration'), sel(s2));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        send({type: 'imp', label: l2, imp: modOf(imp)});
        Interceptor.attach(imp, {
            onEnter(args) {
                const c = args[2];
                send({type: 'cfg', what: l2, value: c.isNull() ? '(nil)' : class_getName(c).readCString(),
                      from: modOf(this.returnAddress)});
            }
        });
    } else { send({type: 'miss', label: l2}); }
}

// hook UIScene.setDelegate: to catch the scene delegate object
{
    const m = class_getInstanceMethod(cls('UIScene'), sel('setDelegate:'));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        send({type: 'imp', label: 'sceneSetDelegate', imp: modOf(imp)});
        Interceptor.attach(imp, {
            onEnter(args) {
                const dn = cname(args[2]);
                send({type: 'sceneDelegateSet', cls: dn});
                const ml = methodList(dn);
                send({type: 'sceneDelegateMethods', cls: dn, list: ml});
            }
        });
    } else { send({type: 'miss', label: 'sceneSetDelegate'}); }
}

// who creates the window?
{
    const m = class_getInstanceMethod(cls('UIWindow'), sel('initWithFrame:'));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        send({type: 'imp', label: 'winInit', imp: modOf(imp)});
        Interceptor.attach(imp, {
            onEnter() { this.from = modOf(this.returnAddress); },
            onLeave(v) { send({type: 'winCreated', ret: cname(v), from: this.from}); }
        });
    }
}
"""


def main():
    Watchdog(120)
    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)
            dev.kill(p.pid)
    time.sleep(2)
    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)[:1400], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(18)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
