#!/usr/bin/env python3
"""Hook the shell VC's obfuscated helpers + detectFlags; dump retvals to find the active-codes source."""
import os, sys, time, json, threading

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


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)


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 objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const S = s => Memory.allocUtf8String(s);
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 bi = Process.getModuleByName('build-info');

function desc(o) {
    try {
        if (o.isNull()) return 'nil';
        const d = objc_msgSend(o, sel('description'));
        return d.readUtf8String().slice(0, 400);
    } catch (er) { return 'ptr:' + o.toString(); }
}

const targets = [
    [0x292edc, 'ocCZpmKIPHkHH'],
    [0x2924e4, 'ZSaUmgRvi'],
    [0x292ad8, 'oUtKjcZMfVx'],
    [0x292878, 'detectFlags'],
    [0x292e98, 'setDetectFlags'],
];
for (const [off, name] of targets) {
    try {
        Interceptor.attach(bi.base.add(off), {
            onEnter(args) {
                this.n = (counts[name] = (counts[name] || 0) + 1);
                this.a1 = desc(args[2]);
                this.from = modOf(this.returnAddress);
            },
            onLeave(v) {
                if (this.n <= 3) send({type: name, n: this.n, arg2: this.a1,
                                       from: this.from, ret: desc(v)});
            }
        });
        send({type: 'hooked', name: name});
    } catch (er) { send({type: 'hookerr', name: name, e: String(er)}); }
}
const counts = {};
"""


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)
            dev.kill(p.pid)
    time.sleep(2)
    pid = dev.spawn(['vn.gsm.md'])
    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(14)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
