#!/usr/bin/env python3
"""Determine whether the FairPlay envelope tail beyond __TEXT (inside __DATA_CONST)
is really encrypted in the pristine App Store Driver, and find plaintext sources."""
import os, sys, struct, zipfile

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

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


def segments_and_crypt(d):
    ncmds, = struct.unpack_from('<I', d, 16)
    off = 32
    segs, crypt = [], None
    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()
            vm, vs, fo, fs = struct.unpack_from('<QQQQ', d, off + 24)
            segs.append((nm, vm, vs, fo, fs))
        elif cmd == 0x2C:
            crypt = struct.unpack_from('<3I', d, off + 8)
        off += sz
    return segs, crypt


def entropy16(b):
    """rough entropy per 16-byte block: count distinct byte values"""
    from collections import Counter
    c = Counter(b)
    n = len(b)
    import math
    H = -sum((v / n) * math.log2(v / n) for v in c.values())
    return H


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

    drv = apptool.read([n for n in apptool.namelist() if n.endswith('Driver.app/Driver')][0])
    segs, crypt = segments_and_crypt(drv)
    co, cs, ci = crypt
    print('Driver segments:')
    for nm, vm, vs, fo, fs in segs:
        print('  %-16s vm=0x%09x vmsz=0x%09x fileoff=0x%09x filesz=0x%09x' % (nm, vm, vs, fo, fs))
    print('crypt: off=0x%x size=0x%x end=0x%x cryptid=%d' % (co, cs, co + cs, ci))

    mem = open(os.path.join(DUMPDIR, 'Driver.bin'), 'rb').read()

    # partial driver
    pprefix = None
    for n in partial.namelist():
        if n.endswith('/Driver.app/Info.plist'):
            pprefix = n[:n.rfind('/')]
            break
    pd = partial.read(pprefix + '/Driver')
    psegs, pcrypt = segments_and_crypt(pd)
    print('\nPARTIAL Driver crypt: off=0x%x size=0x%x cryptid=%d' % (pcrypt[0], pcrypt[1], pcrypt[2]))

    textfs = segs[1][4]  # __TEXT filesize
    tail_start, tail_end = textfs, min(co + cs, len(drv))
    print('\ntail region beyond __TEXT: [0x%x, 0x%x) = 0x%x bytes' % (tail_start, tail_end, tail_end - tail_start))

    # sample 3 blocks of 256 bytes from the tail in each source
    for name, buf in (('ipatool(disk)', drv), ('PARTIAL(disk)', pd), ('memory', mem)):
        print('\n%s:' % name)
        for s in (tail_start, tail_start + (tail_end - tail_start) // 2, tail_end - 512):
            blk = buf[s:s + 256]
            print('  @0x%09x entropy=%.2f  %s' % (s, entropy16(blk), blk[:32].hex()))

    # compare PARTIAL vs memory byte-for-byte in the whole crypt envelope
    n = min(co + cs, len(pd), len(mem))
    diffs = sum(1 for a, b in zip(pd[co:n], mem[co:n]) if a != b)
    print('\nPARTIAL vs memory in [0x%x,0x%x): %d/%d differing bytes' % (co, n, diffs, n - co))

    # compare ipatool vs PARTIAL over whole file head (is PARTIAL == ipatool outside crypt?)
    m = min(len(drv), len(pd))
    d1 = sum(1 for a, b in zip(drv[:co], pd[:co]) if a != b)
    print('ipatool vs PARTIAL in [0,0x%x): %d differing bytes' % (co, d1))
    d2 = sum(1 for a, b in zip(drv[tail_end:m], pd[tail_end:m]) if a != b)
    print('ipatool vs PARTIAL in [0x%x, 0x%x): %d differing bytes' % (tail_end, m, d2))

    # how big is each file
    print('\nipatool size=0x%x  PARTIAL size=0x%x  mem=0x%x' % (len(drv), len(pd), len(mem)))


if __name__ == '__main__':
    main()
