#!/usr/bin/env python3
"""Dump the ORIGINAL vn.gsm.md 3.19.0 from the RootHide iPhone X.

The app does not crash - it opens Safari and may exit. So it is launched under
Frida spawn-gating and the guards go in BEFORE resuming.

The two script bodies share ONE preamble (PRELUDE) that is declared once here and
spliced into both, so a helper can never be orphaned when the scripts are split:

  phase 1 (process suspended)  GUARD_JS
      exit / _exit / abort   -> NATIVE self-branch (b .): the calling thread spins
                                in native code, the process stays alive, and no JS
                                is involved so the dump can still run
      kill / pthread_kill    -> native stub returning 0
      -[UIApplication openURL:...] -> stubs that do nothing; Safari never opens
  resume, let the shield reach its blocking state
  phase 2 (app running)        DUMP_JS
      every page of every app-bundle module is read first - that is what performs
      the FairPlay per-page decryption - then each image is fwrite'd into the app's
      own tmp directory (the process is sandboxed and cannot write to
      /var/mobile/Media); the root shell copies the files out afterwards.
"""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

# ---------------------------------------------------------------- single preamble
PRELUDE = r"""
const libSystem = Process.getModuleByName('libSystem.B.dylib');
const f = (n, r, a) => new NativeFunction(libSystem.getExportByName(n), r, a);
const fopen_ = f('fopen', 'pointer', ['pointer', 'pointer']);
const fwrite_ = f('fwrite', 'ulong', ['pointer', 'ulong', 'ulong', 'pointer']);
const fclose_ = f('fclose', 'int', ['pointer']);
const mkdir_ = f('mkdir', 'int', ['pointer', 'int']);
const S = s => Memory.allocUtf8String(s);
const KEEP = [];
const keepStr = s => { const p = S(s); KEEP.push(p); return p; };
const libobjc = Process.getModuleByName('libobjc.A.dylib');
const objc_getClass = new NativeFunction(libobjc.getExportByName('objc_getClass'), 'pointer', ['pointer']);
const sel_registerName = new NativeFunction(libobjc.getExportByName('sel_registerName'), 'pointer', ['pointer']);
const class_getInstanceMethod = new NativeFunction(libobjc.getExportByName('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(libobjc.getExportByName('method_getImplementation'), 'pointer', ['pointer']);
const msgSend = new NativeFunction(libobjc.getExportByName('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
"""

# ---------------------------------------------------------------- phase 1: guards
GUARD_BODY = r"""
const SPIN = Memory.alloc(Process.pageSize); KEEP.push(SPIN);
Memory.patchCode(SPIN, 4, p => p.writeByteArray([0x00, 0x00, 0x00, 0x14]));  // b .

const RET0 = Memory.alloc(Process.pageSize); KEEP.push(RET0);
Memory.patchCode(RET0, 8, p => p.writeByteArray([0x00, 0x00, 0x80, 0xd2,   // mov x0, #0
                                                 0xc0, 0x03, 0x5f, 0xd6])); // ret

function modExp(lib, name) {
    try { return Process.getModuleByName(lib).getExportByName(name); }
    catch (er) { send({type: 'guard_skip', what: lib + '!' + name, e: String(er)}); return null; }
}
function replaceSpin(lib, name) {
    const p = modExp(lib, name); if (!p) return;
    try { Interceptor.replace(p, SPIN); send({type: 'guard', what: lib + '!' + name + ' -> spin'}); }
    catch (er) { send({type: 'guard_fail', what: name, e: String(er)}); }
}
function replaceRet0(lib, name) {
    const p = modExp(lib, name); if (!p) return;
    try { Interceptor.replace(p, RET0); send({type: 'guard', what: lib + '!' + name + ' -> ret0'}); }
    catch (er) { send({type: 'guard_fail', what: name, e: String(er)}); }
}
function replaceObjcStub(clsName, selName, retType, argTypes) {
    try {
        const c = objc_getClass(S(clsName));
        if (c.isNull()) { send({type: 'guard_skip', what: clsName}); return; }
        const mm = class_getInstanceMethod(c, sel_registerName(S(selName)));
        if (mm.isNull()) { send({type: 'guard_skip', what: clsName + ' ' + selName}); return; }
        const cb = new NativeCallback(function () { return 0; }, retType, argTypes);
        KEEP.push(cb);
        Interceptor.replace(method_getImplementation(mm), cb);
        send({type: 'guard', what: clsName + ' ' + selName + ' -> ret0'});
    } catch (er) { send({type: 'guard_fail', what: clsName + ' ' + selName, e: String(er)}); }
}

replaceSpin('libsystem_c.dylib', 'exit');
replaceSpin('libsystem_c.dylib', 'abort');
replaceSpin('libsystem_kernel.dylib', '_exit');
replaceRet0('libsystem_kernel.dylib', 'kill');
replaceRet0('libsystem_pthread.dylib', 'pthread_kill');
replaceObjcStub('UIApplication', 'openURL:', 'int', ['pointer', 'pointer', 'pointer']);
replaceObjcStub('UIApplication', 'openURL:options:', 'int', ['pointer', 'pointer', 'pointer', 'pointer']);
replaceObjcStub('UIApplication', 'openURL:options:completionHandler:', 'void',
                ['pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
send({type: 'guards_done'});
"""

# ---------------------------------------------------------------- phase 2: dump
DUMP_BODY = r"""
const mods = Process.enumerateModules();
let appdir = null;
for (const m of mods) {
    if (m.name === 'Driver') { appdir = m.path.substring(0, m.path.lastIndexOf('/')); break; }
}
send({type: 'appdir', path: appdir, modules: mods.length});

// the app process is sandboxed: dump into its own tmp directory
const fnd = Process.getModuleByName('Foundation');
const NSTmp = new NativeFunction(fnd.getExportByName('NSTemporaryDirectory'), 'pointer', []);
const tmpNs = NSTmp();
const tmpUtf = msgSend(tmpNs, sel_registerName(S('UTF8String')));
const APP_TMP = tmpUtf.readCString();
const OUTDIR_STR = APP_TMP.replace(new RegExp('/$'), '') + '/dump319';
mkdir_(S(OUTDIR_STR), 0x1ff);
send({type: 'outdir', path: OUTDIR_STR});

function forcePageIn(base, length) {
    let done = 0, n = 0;
    while (done < length) {
        try { base.add(done).readU8(); n++; } catch (er) {}
        done += 0x1000;
    }
    return n;
}

function mappedExtent(base) {
    // all segments are contiguous in VM for these images, so the first unreadable
    // page marks the end of the mapping. Frida's Module.size only reports part of
    // it, which is exactly why the first attempt lost __LINKEDIT.
    let end = 0;
    for (let o = 0; o < 0x8000000; o += 0x1000) {
        try { base.add(o).readU8(); end = o + 0x1000; }
        catch (er) { break; }
    }
    return end;
}

function dumpModule(m) {
    const base = m.base;
    if (base.readU32() !== 0xfeedfacf) { send({type: 'skip', name: m.name, why: 'bad magic'}); return; }
    const size = mappedExtent(base);
    const paged = forcePageIn(base, size);
    send({type: 'pagein', name: m.name, pages: paged, size: size});
    const fname = OUTDIR_STR + '/' + m.name.replace(/\//g, '_') + '.bin';
    const fp = fopen_(keepStr(fname), keepStr('wb'));
    if (fp.isNull()) { send({type: 'fail', name: m.name, why: 'fopen'}); return; }
    let done = 0;
    while (done < size) {
        const n = Math.min(0x100000, size - done);
        fwrite_(base.add(done), 1, n, fp);
        done += n;
    }
    fclose_(fp);
    send({type: 'dumped', name: m.name, size: size});
}

let count = 0;
for (const m of mods) {
    if (appdir && m.path.indexOf(appdir) === 0) { dumpModule(m); count++; }
}
send({type: 'done', dumped: count});
"""

GUARD_JS = PRELUDE + GUARD_BODY
DUMP_JS = PRELUDE + DUMP_BODY


class Watchdog:
    def __init__(self, secs=1200):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.5)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


def onmsg(m, d=None):
    print('[frida]', json.dumps(m)[:400], flush=True)


def main():
    Watchdog(1200)
    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 Driver', p.pid, flush=True)
            try:
                dev.kill(p.pid)
            except Exception:
                pass
    time.sleep(1.5)
    pid = dev.spawn([BID])
    print('spawned (suspended)', pid, flush=True)
    sess = dev.attach(pid)

    print('--- phase 1: guards ---', flush=True)
    s1 = sess.create_script(GUARD_JS)
    s1.on('message', onmsg)
    s1.load()
    dev.resume(pid)
    time.sleep(16)

    for pass_no in (1, 2):
        print('--- phase 2: dump (pass %d) ---' % pass_no, flush=True)
        s2 = sess.create_script(DUMP_JS)
        s2.on('message', onmsg)
        s2.load()
        time.sleep(25)

    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
