#!/usr/bin/env python3
"""Root shell on the RootHide device.

- frida 17.x against the disguised frida-server (sysdiagd) on 127.0.0.1:7777
- system() is unusable on iOS (no fork, and RootHide hooks posix_spawn in launchd)
- posix_spawn lives in libSystem.B.dylib, not libsystem_c.dylib
- all tools addressed by absolute jbroot path

Usage:  python root_sh.py "cmd1" "cmd2" ...
        (output should be redirected by the caller to an absolute path under /var/mobile/Media)
"""
import frida, sys, time, json, socket

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

JB_DEFAULT = '/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'
];
const CMDS = CMDLIST;
for (const c of CMDS) {
    const r = spawn('/bin/sh', ['sh', '-c', c], ENV);
    send({ type: 'cmd', cmd: c, rc: r.rc, pid: r.pid });
}
send({ type: 'done' });
"""


def get_device(port=7777, retries=4):
    last = None
    for i in range(retries):
        try:
            s = socket.create_connection(('127.0.0.1', port), timeout=5)
            s.close()
            return frida.get_device_manager().add_remote_device('127.0.0.1:%d' % port)
        except Exception as e:
            last = e
            time.sleep(1.5)
    raise SystemExit('frida-server port %d unreachable: %r' % (port, last))


def run(cmds, target=None, jbroot=JB_DEFAULT, wait=4.0):
    dev = get_device()
    procs = {p.name: p.pid for p in dev.enumerate_processes()}
    candidates = [target] if target else ['sysdiagd', 'logd', 'launchd', 'securityd']
    pid = None
    for c in candidates:
        if c in procs:
            pid = procs[c]
            target = c
            break
    if pid is None:
        raise SystemExit('no attachable root target among %r' % candidates)
    session = dev.attach(pid)
    body = JS.replace('JBROOT', json.dumps(jbroot)).replace('CMDLIST', json.dumps(cmds))
    script = session.create_script(body)
    msgs = []
    script.on('message', lambda m, d: (msgs.append(m), print('[frida]', json.dumps(m)[:300])))
    script.load()
    time.sleep(wait)
    session.detach()
    return msgs


if __name__ == '__main__':
    cmds = sys.argv[1:]
    if not cmds:
        jb = JB_DEFAULT
        cmds = [
            'echo "=== id ===" > /var/mobile/Media/frout.txt 2>&1',
            'id >> /var/mobile/Media/frout.txt 2>&1',
            'echo "=== jbroot tools ===" >> /var/mobile/Media/frout.txt 2>&1',
            '%s/usr/bin/ls -la %s/usr/bin/id %s/usr/bin/uicache %s/usr/bin/tar %s/bin/sh >> /var/mobile/Media/frout.txt 2>&1' % (jb, jb, jb, jb, jb),
            'echo "=== bundle dir ===" >> /var/mobile/Media/frout.txt 2>&1',
            '/bin/ls -la /var/containers/Bundle/Application/ >> /var/mobile/Media/frout.txt 2>&1',
        ]
    run(cmds)
