﻿#!/usr/bin/env python3
"""Root exec on RootHide: posix_spawn + file_actions (capture stdout/stderr) + waitpid.

Note: every Memory.allocUtf8String must stay referenced in JS until after the spawn,
otherwise the GC frees the buffer and argv points at garbage.
"""
import frida, sys, time, json

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

JB = '/var/containers/Bundle/Application/.jbroot-B23459BE77770263'

JS = r"""
const libSystem = Process.getModuleByName('libSystem.B.dylib');
const f = function (n, r, a) { return new NativeFunction(libSystem.getExportByName(n), r, a); };
const posix_spawn = f('posix_spawn', 'int', ['pointer','pointer','pointer','pointer','pointer','pointer']);
const fa_init = f('posix_spawn_file_actions_init', 'int', ['pointer']);
const fa_addopen = f('posix_spawn_file_actions_addopen', 'int', ['pointer','int','pointer','int','int']);
const fa_adddup2 = f('posix_spawn_file_actions_adddup2', 'int', ['pointer','int','int']);
const fa_destroy = f('posix_spawn_file_actions_destroy', 'int', ['pointer']);
const waitpid = f('waitpid', 'int', ['int','pointer','int']);
const ps = Process.pointerSize;
const O_WRONLY = 1, O_CREAT = 0x200, O_TRUNC = 0x400;

const keep = [];   // keep every allocated string alive across the spawn
function keepStr(s) { const p = Memory.allocUtf8String(s); keep.push(p); return p; }

function run(path, args, envs, outfile) {
    const argv = Memory.alloc((args.length + 1) * ps);
    keep.push(argv);
    for (let i = 0; i < args.length; i++)
        argv.add(i * ps).writePointer(keepStr(args[i]));
    argv.add(args.length * ps).writePointer(ptr(0));

    let envp = ptr(0);
    if (envs && envs.length) {
        envp = Memory.alloc((envs.length + 1) * ps);
        keep.push(envp);
        for (let i = 0; i < envs.length; i++)
            envp.add(i * ps).writePointer(keepStr(envs[i]));
        envp.add(envs.length * ps).writePointer(ptr(0));
    }

    const fa = Memory.alloc(8);
    keep.push(fa);
    fa_init(fa);
    fa_addopen(fa, 1, keepStr(outfile), O_WRONLY | O_CREAT | O_TRUNC, 420);
    fa_adddup2(fa, 1, 2);

    const pidp = Memory.alloc(4);
    keep.push(pidp);
    const rc = posix_spawn(pidp, keepStr(path), fa, ptr(0), argv, envp);
    fa_destroy(fa);

    let status = -1;
    if (rc === 0) {
        const st = Memory.alloc(4);
        keep.push(st);
        waitpid(pidp.readS32(), st, 0);
        status = st.readS32();
    }
    return { rc: rc, pid: pidp.readS32(), status: status };
}

const JB = JBROOT;
const ENV = ['PATH=' + JB + '/usr/bin:' + JB + '/bin:/usr/bin:/bin:/usr/sbin:/sbin', 'HOME=/var/root'];
const OUT = OUTFILE;
const shScript = SHSCRIPT;
send({type: 'run', r: run(JB + '/bin/sh', ['sh', '-c', shScript], ENV, OUT)});
send({type: 'done'});
"""


def main():
    script_text = sys.argv[1] if len(sys.argv) > 1 else 'id; echo "---"; ls -la /var/mobile/Media | head -20'
    outfile = sys.argv[2] if len(sys.argv) > 2 else '/var/mobile/Media/frout.txt'
    timeout = float(sys.argv[3]) if len(sys.argv) > 3 else 120.0
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    procs = {p.name: p.pid for p in dev.enumerate_processes()}
    target = 'sysdiagd' if 'sysdiagd' in procs else 'launchd'
    session = dev.attach(procs[target])
    body = (JS.replace('JBROOT', json.dumps(JB))
              .replace('OUTFILE', json.dumps(outfile))
              .replace('SHSCRIPT', json.dumps(script_text)))
    state = {'done': False}

    def on_msg(m, d):
        print('[frida]', json.dumps(m)[:600])
        p = m.get('payload') or {}
        if isinstance(p, dict) and p.get('type') == 'done':
            state['done'] = True

    script = session.create_script(body)
    script.on('message', on_msg)
    script.load()
    t0 = time.time()
    while not state['done'] and time.time() - t0 < timeout:
        time.sleep(0.5)
    if not state['done']:
        print('WARN: no done message within %.0fs' % timeout)
    session.detach()


if __name__ == '__main__':
    main()

