# -*- coding: utf-8 -*-
"""
scan_config2.py - tim khoi config nhung trong Mach-O, co giai ma chained fixup.

Layout config (theo decompile ctor 0x33bb8 / 0x2e300 / 0x19c1c / 0x28074c):
  +0x00  u32 rounds          (puVar12[0])
  +0x04  u32 state[16]       (puVar12[1..16])
  +0x48  ptr -> blob bytes   (puVar12+0x12)
  +0x68  ptr -> u32 offsets  (puVar12+0x1a)
Section i = blob[offsets[i] : offsets[i+1]]

Keystream: ChaCha bien the (16/12/8/7), counter = abs/0x40+1, add-back, LE.
Noi dung section sau giai ma la chuoi chu so thap phan.
Section quan trong: 1..6 (mask), 8..26 (registry key), 0x166 / 0x16b (khoa decrypt/encrypt).
"""
import struct, sys

M32 = 0xFFFFFFFF
MASK36 = 0xFFFFFFFFF

def rotl(x, n):
    x &= M32
    return ((x << n) | (x >> (32 - n))) & M32

def qr(x, a, b, c, d):
    x[a] = (x[a] + x[b]) & M32
    x[d] = rotl(x[d] ^ x[a], 16)
    x[c] = (x[c] + x[d]) & M32
    x[b] = rotl(x[b] ^ x[c], 12)
    x[a] = (x[a] + x[b]) & M32
    x[d] = rotl(x[d] ^ x[a], 8)
    x[c] = (x[c] + x[d]) & M32
    x[b] = rotl(x[b] ^ x[c], 7)

def block(state, rounds, counter):
    x = [0] * 16
    for i in range(16):
        x[i] = counter if i == 12 else state[i]
    orig = list(x)
    for _ in range(rounds):
        # column rounds
        qr(x, 0, 4, 8, 12)
        qr(x, 1, 5, 9, 13)
        qr(x, 2, 6, 10, 14)
        qr(x, 3, 7, 11, 15)
        # diagonal rounds
        qr(x, 0, 5, 10, 15)
        qr(x, 1, 6, 11, 12)
        qr(x, 2, 7, 8, 13)
        qr(x, 3, 4, 9, 14)
    for i in range(16):
        x[i] = (x[i] + orig[i]) & M32
    return b''.join(struct.pack('<I', v) for v in x)

def keystream(state, rounds, counter):
    # cache: counter khac nhau moi block
    return block(state, rounds, counter)

def decrypt(state, rounds, blob, off0, off1):
    out = bytearray(blob[off0:off1])
    ks = b''
    for i in range(off0, off1):
        if (i & 0x3f) == 0:
            ks = keystream(state, rounds, i // 0x40 + 1)
        out[i - off0] ^= ks[i & 0x3f]
    return bytes(out)

def is_digits(b):
    return len(b) > 0 and all(0x30 <= c <= 0x39 for c in b)

def parse_macho(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    off = 32
    segs = []
    fixups = {}   # file offset -> target vmaddr (da giai ma)
    for _ in range(ncmds):
        cmd, size = struct.unpack_from('<II', d, off)
        if cmd == 0x19:
            name = d[off+8:off+24].rstrip(b'\x00').decode()
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((name, vmaddr, vmsize, fileoff, filesize))
        elif cmd == 0x80000034:  # LC_DYLD_CHAINED_FIXUPS
            dataoff, datasize = struct.unpack_from('<II', d, off+8)
            fixups = parse_chained(d, dataoff, segs)
        off += size
    return d, segs, fixups

def parse_chained(d, base, segs):
    """Tra ve dict: file_offset -> vmaddr dich (giai ma chained pointer)."""
    out = {}
    starts_off, = struct.unpack_from('<I', d, base)
    seg_count, = struct.unpack_from('<I', d, base + 4)
    imp_off, = struct.unpack_from('<I', d, base + 8)
    sym_off, = struct.unpack_from('<I', d, base + 12)
    p = base + starts_off
    for i in range(seg_count):
        seg_info_off, = struct.unpack_from('<I', d, p + i * 4)
        if seg_info_off == 0:
            continue
        q = base + seg_info_off
        seg_offset, = struct.unpack_from('<Q', d, q)          # vmaddr cua segment
        page_size, = struct.unpack_from('<H', d, q + 8)
        page_count, = struct.unpack_from('<H', d, q + 10)
        fmt, = struct.unpack_from('<H', d, q + 12)
        r = q + 22
        # tim segment tuong ung
        seg = next((s for s in segs if s[1] == seg_offset), None)
        if seg is None:
            continue
        _, vm, vs, fo, fs = seg
        for pg in range(page_count):
            page_start, = struct.unpack_from('<H', d, r + pg * 2)
            if page_start == 0xFFFF:
                continue
            page_fo = fo + pg * page_size
            o = page_fo + page_start
            while o < page_fo + page_size and o + 8 <= len(d):
                raw, = struct.unpack_from('<Q', d, o)
                nxt = raw >> 51
                if fmt == 2:      # DYLD_CHAINED_PTR_64
                    target = raw & MASK36
                elif fmt == 6:    # DYLD_CHAINED_PTR_64_OFFSET
                    target = raw & MASK36
                else:
                    target = raw & MASK36
                out[o] = target
                if nxt == 0:
                    break
                o += nxt * 4
    return out

def vm2file(segs, va):
    for name, vm, vs, fo, fs in segs:
        if vm <= va < vm + vs:
            return fo + (va - vm)
    return None

def main():
    p = sys.argv[1]
    d, segs, fixups = parse_macho(p)
    print('file:', p)
    print('segments:', [(s[0], hex(s[1]), hex(s[2]), hex(s[3])) for s in segs])
    print('chained fixups decoded:', len(fixups))

    def resolve(q):
        """Gia tri pointer tai file offset q -> file offset dich (hoac None)."""
        if q in fixups:
            t = fixups[q]
        else:
            t, = struct.unpack_from('<Q', d, q)
            if not (0 <= t < (1 << 40)):
                return None
            t &= MASK36
        if t == 0:
            return None
        return vm2file(segs, t)

    # vung ung vien: __DATA
    cands = []
    for name, vm, vs, fo, fs in segs:
        if name not in ('__DATA', '__DATA_CONST', '__DATA_DIRTY'):
            continue
        for q in range(fo, fo + fs - 0x70, 4):
            rounds, = struct.unpack_from('<I', d, q)
            if not (1 <= rounds <= 64):
                continue
            fo_blob = resolve(q + 0x48)
            fo_offs = resolve(q + 0x68)
            if fo_blob is None or fo_offs is None:
                continue
            cands.append((q, rounds, fo_blob, fo_offs))
    print('struct candidates:', len(cands))

    hits = 0
    for q, rounds, fo_blob, fo_offs in cands:
        try:
            offs = list(struct.unpack_from('<%dI' % 0x16d, d, fo_offs))
        except Exception:
            continue
        if offs[0] != 0:
            continue
        if any(offs[i] >= offs[i+1] for i in range(len(offs) - 1)):
            continue
        if offs[-1] > 0x800000:
            continue
        if fo_blob + offs[-1] > len(d):
            continue
        state = list(struct.unpack_from('<16I', d, q + 4))
        blob = d[fo_blob:fo_blob + offs[-1]]
        tested = list(range(1, 7)) + list(range(8, 27)) + [0x166, 0x16b]
        ok = 0
        for sec in tested:
            b = decrypt(state, rounds, blob, offs[sec], offs[sec + 1])
            if is_digits(b):
                ok += 1
        print('CAND q=0x%x rounds=%d blob=0x%x offs=0x%x last=0x%x digits_ok=%d/%d'
              % (q, rounds, fo_blob, fo_offs, offs[-1], ok, len(tested)))
        if ok >= 20:
            hits += 1
            for sec in tested:
                b = decrypt(state, rounds, blob, offs[sec], offs[sec + 1])
                print('   sec %-5d len=%-5d %s' % (sec, len(b), b[:48]))
    print('hits:', hits)

if __name__ == '__main__':
    main()
