#!/usr/bin/env python3
"""Spawn the jbroot shell (not /bin/sh) as root and run a command."""
import frida, sys, time, json

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

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

JS = r"""
const libSystem = Process.getModuleByName('libSystem.B.dylib');
const posix_spawn = new NativeFunction(libSystem.getExportByName('posix_spawn'), 'int',
    ['pointer', 'pointer', 'pointer', 'pointer', 'pointer', 'pointer']);
const ps = Process.pointerSize;

function spawn(path, args, envs) {
    const argv = Memory.alloc((args.length + 1) * ps);
    for (let i = 0; i < args.length; i++)
        argv.add(i * ps).writePointer(Memory.allocUtf8String(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);
        for (let i = 0; i < envs.length; i++)
            envp.add(i * ps).writePointer(Memory.allocUtf8String(envs[i]));
        envp.add(envs.length * ps).writePointer(ptr(0));
    }
    const pidp = Memory.alloc(4);
    const rc = posix_spawn(pidp, Memory.allocUtf8String(path), ptr(0), ptr(0), argv, envp);
    return { rc: rc, pid: pidp.readS32() };
}

const JB = JBROOT;
const ENV = ['PATH=' + JB + '/usr/bin:' + JB + '/bin:/usr/bin:/bin:/usr/sbin:/sbin', 'HOME=/var/root'];

// what does /bin actually contain?
function listDir(p) {
    try { return new File(p, 'r').readdir().slice(0, 40); } catch (e) { return 'ERR ' + e; }
}
send({bin: listDir('/bin'), usrbin: listDir('/usr/bin'), jbbin: listDir(JB + '/bin')});

for (const c of CMDLIST) {
    const r = spawn(JB + '/bin/sh', ['sh', '-c', c], ENV);
    send({type: 'cmd', cmd: c, rc: r.rc, pid: r.pid});
}
send({type: 'done'});
"""

CMDS = [
    'id > /var/mobile/Media/frout.txt 2>&1',
    'echo "=== tools ===" >> /var/mobile/Media/frout.txt 2>&1',
    'ls -la ' + JB + '/usr/bin/id ' + JB + '/usr/bin/uicache ' + JB + '/usr/bin/tar ' + JB + '/bin/sh >> /var/mobile/Media/frout.txt 2>&1',
    'echo "=== bundles ===" >> /var/mobile/Media/frout.txt 2>&1',
    'ls -la /var/containers/Bundle/Application/ >> /var/mobile/Media/frout.txt 2>&1',
    'echo "=== media tar ===" >> /var/mobile/Media/frout.txt 2>&1',
    'ls -la /var/mobile/Media/*.tar >> /var/mobile/Media/frout.txt 2>&1',
]

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('CMDLIST', json.dumps(CMDS))
script = session.create_script(body)
script.on('message', lambda m, d: print('[frida]', json.dumps(m)[:700]))
script.load()
time.sleep(4)
session.detach()
