#!/usr/bin/env python3
"""Verify that pristine on-disk binaries differ from the memory dumps ONLY
inside the FairPlay crypt region [cryptoff, cryptoff+cryptsize).

If true, build 55 (crypt-region-only swap) is byte-exact vs a legit OS decrypt.
"""
import os, sys, struct, zipfile

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

PARTIAL_IPA = r'E:\ios\vn.gsm.md_3.19.0-PARTIAL.ipa'
APPTOOL_IPA = r'E:\ios\work319\gsm-driver-3.19.0.ipa'
DUMPDIR = r'E:\ios\work319\dump319'
PAGE = 4096


def find_enc(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x2C:
            return struct.unpack_from('<3I', d, off + 8)
        off += sz
    return None, None, None


def text_fs(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    for _ in range(ncmds):
        cmd, sz = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            nm = d[off + 8:off + 24].rstrip(b'\0').decode()
            if nm == '__TEXT':
                return struct.unpack_from('<Q', d, off + 48)[0]  # filesize at +48
        off += sz
    return None


def check(name, base, mem):
    co, cs, cid = find_enc(base)
    tfs = text_fs(base)
    n = min(tfs, len(mem))
    diffs = []
    for p in range(0, n, PAGE):
        e = min(p + PAGE, n)
        if base[p:e] != mem[p:e]:
            diffs.append((p, e))
    # classify
    inside = [r for r in diffs if r[0] >= co and r[1] <= co + cs]
    partial = [r for r in diffs if not (r[0] >= co and r[1] <= co + cs)]
    print('%-52s crypt=[0x%x,0x%x) textfs=0x%x  diffpages=%d  fullyInside=%d  OUTSIDE=%d'
          % (name, co, co + cs, tfs, len(diffs), len(inside), len(partial)))
    for r in partial[:4]:
        # show first differing offset in the page
        q = r[0]
        while q < r[1] and base[q] == mem[q]:
            q += 1
        print('    OUTSIDE-DIFF page 0x%x-0x%x first@0x%x' % (r[0], r[1], q))
    return len(partial) == 0


def main():
    partial = zipfile.ZipFile(PARTIAL_IPA)
    apptool = zipfile.ZipFile(APPTOOL_IPA)

    dumps = {}
    for fn in os.listdir(DUMPDIR):
        if fn.endswith('.bin'):
            dumps[fn[:-4]] = os.path.join(DUMPDIR, fn)
    print('dumps: %d' % len(dumps))

    app_prefix = None
    for n in partial.namelist():
        if n.endswith('/Driver.app/Info.plist'):
            app_prefix = n[:n.rfind('/')]
            break

    # Driver: ipatool pristine vs dump
    drv = apptool.read([n for n in apptool.namelist() if n.endswith('Driver.app/Driver')][0])
    drv_mem = open(dumps['Driver'], 'rb').read()
    ok_drv = check('Driver (ipatool)', drv, drv_mem)

    ok_fw = 0
    bad_fw = []
    nodump = []
    checked = 0
    for n in sorted(partial.namelist()):
        if not n.startswith(app_prefix + '/'):
            continue
        rel = n[len(app_prefix) + 1:]
        if not rel or rel.endswith('/'):
            continue
        try:
            head = partial.open(n).read(4)
        except Exception:
            continue
        if head != b'\xcf\xfa\xed\xfe':
            continue
        if rel == 'Driver':
            continue
        dp = dumps.get(os.path.basename(rel))
        if not dp:
            nodump.append(rel)
            continue
        base = partial.read(n)
        mem = open(dp, 'rb').read()
        if check(rel, base, mem):
            ok_fw += 1
        else:
            bad_fw.append(rel)
        checked += 1

    print()
    print('driver clean (only crypt region differs): %s' % ok_drv)
    print('frameworks checked: %d  clean: %d  DIRTY: %d' % (checked, ok_fw, len(bad_fw)))
    for b in bad_fw[:10]:
        print('   DIRTY:', b)
    print('frameworks without dump: %d' % len(nodump))
    for b in nodump[:10]:
        print('   NODUMP:', b)


if __name__ == '__main__':
    main()
