#!/usr/bin/env python3
"""Hook the flag setter (0x18e58) + its two check functions (0xed88, 0x42408) + success/fail
continuations. Logs arguments, retvals, return addresses, and samples the flag byte."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

JS = r"""
const bi = Process.getModuleByName('build-info');
const st = {setter: 0, ed88: 0, chk: 0, flag_samples: [], sites: {}, last: null};

function site(addr) { return addr.sub(bi.base).toString(16); }

// setter
Interceptor.attach(bi.base.add(0x18e58), {
    onEnter(args) {
        st.setter++;
        const s = site(this.returnAddress);
        st.sites[s] = (st.sites[s] || 0) + 1;
        if (st.setter <= 6) {
            send({type: 'setter', n: st.setter, obj: args[0].toString(),
                  a1: args[1].toString(), w2: args[2].toInt32(), from: s});
        }
        this.obj = args[0];
    },
    onLeave(v) {
        if (this.obj) {
            const b = this.obj.add(0x80).readU8();
            if (st.flag_samples.length < 10) st.flag_samples.push(b);
        }
        st.last = {ret: v.toInt32()};
    }
});

// the two checks
for (const [off, name] of [[0xed88, 'ed88'], [0x42408, 'chk42408']]) {
    try {
        Interceptor.attach(bi.base.add(off), {
            onEnter(args) {
                this.n = st[name] = (st[name] || 0) + 1;
                this.from = site(this.returnAddress);
            },
            onLeave(v) {
                if (this.n <= 6) send({type: name, n: this.n, ret: v.toInt32(), from: this.from});
            }
        });
    } catch (e) { send({type: 'err', off: off.toString(16), e: String(e)}); }
}

// success continuation (0x18f44) and fail continuation (0x19288) as instruction hooks
for (const off of [0x18f44, 0x19288]) {
    try {
        Interceptor.attach(bi.base.add(off), {
            onEnter() { send({type: 'path', off: off.toString(16)}); }
        });
    } catch (e) { send({type: 'err2', off: off.toString(16), e: String(e)}); }
}

setInterval(function () {
    send({type: 'tick', st: {setter: st.setter, ed88: st.ed88, chk: st.chk,
                             sites: st.sites, flags: st.flag_samples, last: st.last}});
}, 4000);
"""


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)
            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)[:800], flush=True))
    s.load()
    dev.resume(pid)
    time.sleep(25)
    print('observation done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
