#!/usr/bin/env python3
"""Build 50: the CLEANEST possible reconstruction.

Take the ORIGINAL App Store Driver binary - whose __LINKEDIT (bind stream,
symtab, export trie) and __DATA are exactly what Apple shipped and exactly what
dyld knows how to bind - and change only three things:

  1. __TEXT is swapped for the decrypted pages from the memory dump
     (FairPlay on-disk -> plaintext in memory).
  2. cryptid 1 -> 0 (the on-disk header says FairPlay-encrypted).
  3. the 6 detector-neuter patches are re-applied.

Everything else - __DATA, __DATA_CONST, __LINKEDIT, the load commands - is the
original, untouched. dyld will bind every import from the original bind stream,
exactly as it does for the App Store app.

The 11 launch-path sites are already pristine in the original (the inherited
neuters only ever existed in our patched copy).
"""
import struct, sys, zipfile, hashlib

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

IPA = r'E:\ios\work319\gsm-driver-3.19.0.ipa'
DUMP = r'E:\ios\work319\dump319\Driver.bin'
OUT = r'E:\ios\work319\patch_src\Payload\Driver.app\Driver'

TEXT_END = 0x1d98000          # __TEXT fileoff 0 + filesize

NEUTERS = [
    (0x22C740, 4, 'c0035fd6'),
    (0x1709780, 8, '00008052c0035fd6'),
    (0x170867C, 4, 'e0031faa'),
    (0x1708684, 4, 'e1031faa'),
    (0x17086BC, 4, 'e0031faa'),
    (0x17086C0, 4, 'e1031faa'),
]


def set_cryptid(d, val=0):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            old = struct.unpack_from('<I', d, off + 16)[0]
            struct.pack_into('<I', d, off + 16, val)
            return old
        off += sz
    return None


def main():
    with zipfile.ZipFile(IPA) as z:
        nm = [n for n in z.namelist() if n.endswith('Driver.app/Driver')][0]
        orig = bytearray(z.read(nm))
    print('original App Store Driver: %d bytes' % len(orig))

    dump = open(DUMP, 'rb').read()
    print('memory dump              : %d bytes' % len(dump))

    # 1. swap __TEXT for the decrypted pages
    orig[0:TEXT_END] = dump[0:TEXT_END]
    print('__TEXT swapped: %d bytes decrypted' % TEXT_END)

    # 2. cryptid
    old = set_cryptid(orig, 0)
    print('cryptid %s -> 0' % old)

    # 3. detector neuters
    for off, n, exp in NEUTERS:
        cur = bytes(orig[off:off + n]).hex()
        orig[off:off + n] = bytes.fromhex(exp)
        print('  neuter 0x%06x %s -> %s' % (off, cur[:len(exp)], exp))

    open(OUT, 'wb').write(bytes(orig))
    h = hashlib.sha256(bytes(orig)).hexdigest()
    print('\nwrote %s (%d bytes)\n  sha256 %s' % (OUT, len(orig), h))

    # verify the 11 launch-path sites are pristine
    PRISTINE = [(0x031FA8, '37316394'), (0x03281C, '3f2e6394'), (0x032BF8, 'a03b00b4'),
                (0x0333CC, '2e2c6394'), (0x035E4B4, '197f5694'), (0x03B8E0C, '9e155594'),
                (0x05DE9C8, '48774c94'), (0x18FE118, '902e00d0'), (0x18FE484, '902e00d0'),
                (0x18FC6E8, 'a03a00d0'), (0x190C47C, '702e00d0')]
    d = open(OUT, 'rb').read()
    bad = [hex(o) for o, w in PRISTINE if d[o:o + len(w) // 2].hex() != w]
    print('launch-path pristine sites: %d/%d ok%s' % (len(PRISTINE) - len(bad), len(PRISTINE),
                                                      ('  BAD: ' + ','.join(bad)) if bad else ''))

    # verify the bind stream survived (it is in __LINKEDIT, untouched)
    i = d.find(b'\x40_objc_msgSend\x00', 0x2044000)
    print('bind stream intact: %s (first entry at 0x%x)' % (i > 0, hex(i) if i > 0 else 'n/a'))


if __name__ == '__main__':
    main()
