#!/usr/bin/env python3
"""Test: does the shield morph the delegate via object_setClass?"""
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 osc = e('object_setClass');
const object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
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 S = s => Memory.allocUtf8String(s);
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

send({type: 'osc', at: modOf(osc)});
Interceptor.attach(osc, {
    onEnter(a) {
        let from = '?', to = '?';
        try { from = object_getClassName(a[0]).readCString(); } catch (e) {}
        try { to = object_getClassName(a[1]).readCString(); } catch (e) {}
        send({type: 'object_setClass', from: from, to: to,
              bt: Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 10).map(modOf)});
    }
});

// also watch -[Driver.AppDelegate init]
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
for (const [cname, sname, label] of [
    ['Driver.AppDelegate', 'init', 'AppDelegate_init'],
    ['Driver.AppDelegate', 'allocWithZone:', 'AppDelegate_allocZone'],
    ['Function_UmcOPEDGyT', 'init', 'Shield_init'],
]) {
    try {
        const m = class_getInstanceMethod(cls(cname), sel(sname));
        if (m.isNull()) { send({type: 'no_method', label: label}); continue; }
        Interceptor.attach(method_getImplementation(m), {
            onEnter() { send({type: 'HIT', label: label, bt: Thread.backtrace(this.context, Backtracer.FUZZY).slice(0, 8).map(modOf)}); }
        });
        send({type: 'hooked', label: label, imp: modOf(method_getImplementation(m))});
    } catch (er) { send({type: 'hookerr', label: label, e: String(er)}); }
}
"""


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


if __name__ == '__main__':
    main()
