#!/usr/bin/env python3
"""Extract embedded entitlements + bundle id from a signed Mach-O app binary."""
import sys, struct, plistlib

path = sys.argv[1]
d = open(path, 'rb').read()
ncmds = struct.unpack_from('<I', d, 16)[0]
o = 32
cs = None
for _ in range(ncmds):
    cmd, sz = struct.unpack_from('<II', d, o)
    if cmd == 0x1d:  # LC_CODE_SIGNATURE
        dataoff, datasize = struct.unpack_from('<II', d, o+8)
        cs = (dataoff, datasize)
    o += sz
if not cs:
    print('no LC_CODE_SIGNATURE'); sys.exit(1)
base = cs[0]
magic, length, count = struct.unpack_from('>III', d, base)
print('superblob magic=%08x len=%d count=%d' % (magic, length, count))
for i in range(count):
    t, off = struct.unpack_from('>II', d, base+12+i*8)
    p = base + off
    bmagic = struct.unpack_from('>I', d, p)[0]
    blen = struct.unpack_from('>I', d, p+4)[0]
    if t == 5:
        xml = d[p+8:p+blen]
        try:
            pl = plistlib.loads(xml)
            print('--- entitlements (type 5) ---')
            for k, v in pl.items():
                print('  %s = %r' % (k, v))
        except Exception as e:
            print('ent parse err', e, xml[:80])
    elif t == 7:
        print('--- DER entitlements (type 7), %d bytes ---' % blen)
    else:
        print('blob type %d magic=%08x len=%d' % (t, bmagic, blen))
