# -*- coding: utf-8 -*-
"""
scan_config.py — tìm khối config nhúng trong Mach-O và giải mã thử.

Cấu trúc config (theo decompile ctor 0x33bb8 / 0x2e300 / 0x19c1c):
  +0x00  u32 rounds
  +0x04..+0x40  state words: x[i] = config[i+1] (i != 12); x[12] = counter
  +0x48  u64 pointer -> blob byte (sections)
  +0x68  u64 pointer -> u32 array offsets (biên section)
Section i = blob[offsets[i] : offsets[i+1]].
Keystream: biến thể ChaCha (rot 16/12/8/7, rot7 trì hoãn), counter = abs/0x40+1,
add-back state, serialize LE 64 byte, XOR tại (abs & 0x3f).
Nội dung section 1..6 và 8..26 phải là chuỗi chữ số thập phân.
"""
import struct, sys

M32 = 0xFFFFFFFF

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

def double_round(x):
    # col 0: (0,4,8,12)
    x[12] = (x[12] ^ ((x[0] + x[4]) & M32)) & M32
    u1 = rotl(x[12], 16)
    x[8] = (x[8] + u1) & M32
    t = rotl((x[4] ^ x[8]) & M32, 12)
    x[0] = (x[0] + x[4] + t) & M32
    u1 = (u1 ^ x[0]) & M32
    u2 = rotl(u1, 8)
    x[8] = (x[8] + u2) & M32
    u3 = rotl((t ^ x[8]) & M32, 7)
    # col 1: (1,5,9,13)
    x[13] = (x[13] ^ ((x[1] + x[5]) & M32)) & M32
    u1 = rotl(x[13], 16)
    x[9] = (x[9] + u1) & M32
    t = rotl((x[5] ^ x[9]) & M32, 12)
    x[1] = (x[1] + x[5] + t) & M32
    u1 = (u1 ^ x[1]) & M32
    u4 = rotl(u1, 8)
    x[9] = (x[9] + u4) & M32
    u5 = rotl((t ^ x[9]) & M32, 7)
    # col 2: (2,6,10,14)
    x[14] = (x[14] ^ ((x[2] + x[6]) & M32)) & M32
    u1 = rotl(x[14], 16)
    x[10] = (x[10] + u1) & M32
    t = rotl((x[6] ^ x[10]) & M32, 12)
    x[2] = (x[2] + x[6] + t) & M32
    u1 = (u1 ^ x[2]) & M32
    u6 = rotl(u1, 8)
    x[10] = (x[10] + u6) & M32
    u7 = rotl((t ^ x[10]) & M32, 7)
    # col 3: (3,7,11,15)
    x[15] = (x[15] ^ ((x[3] + x[7]) & M32)) & M32
    u1 = rotl(x[15], 16)
    x[11] = (x[11] + u1) & M32
    t = rotl((x[7] ^ x[11]) & M32, 12)
    x[3] = (x[3] + x[7] + t) & M32
    u1 = (u1 ^ x[3]) & M32
    u1 = rotl(u1, 8)
    x[11] = (x[11] + u1) & M32
    u8 = rotl((t ^ x[11]) & M32, 7)
    # diag 1
    x[0] = (x[0] + u5) & M32
    u1 = (u1 ^ x[0]) & M32
    u9 = rotl(u1, 16)
    x[10] = (x[10] + u9) & M32
    u5 = (u5 ^ x[10]) & M32
    u1 = rotl(u5, 12)
    x[0] = (x[0] + u1) & M32
    u9 = (u9 ^ x[0]) & M32
    x[15] = rotl(u9, 8)
    x[10] = (x[10] + x[15]) & M32
    u1 = (u1 ^ x[10]) & M32
    x[5] = rotl(u1, 7)
    # diag 2
    x[1] = (x[1] + u7) & M32
    u2 = (u2 ^ x[1]) & M32
    u9 = rotl(u2, 16)
    x[11] = (x[11] + u9) & M32
    u7 = (u7 ^ x[11]) & M32
    u1 = rotl(u7, 12)
    x[1] = (x[1] + u1) & M32
    u9 = (u9 ^ x[1]) & M32
    x[12] = rotl(u9, 8)
    x[11] = (x[11] + x[12]) & M32
    u1 = (u1 ^ x[11]) & M32
    x[6] = rotl(u1, 7)
    # diag 3
    x[2] = (x[2] + u8) & M32
    u4 = (u4 ^ x[2]) & M32
    u9 = rotl(u4, 16)
    x[8] = (x[8] + u9) & M32
    u8 = (u8 ^ x[8]) & M32
    u1 = rotl(u8, 12)
    x[2] = (x[2] + u1) & M32
    u9 = (u9 ^ x[2]) & M32
    x[13] = rotl(u9, 8)
    x[8] = (x[8] + x[13]) & M32
    u1 = (u1 ^ x[8]) & M32
    x[7] = rotl(u1, 7)
    # diag 4
    x[3] = (x[3] + u3) & M32
    u6 = (u6 ^ x[3]) & M32
    u9 = rotl(u6, 16)
    x[9] = (x[9] + u9) & M32
    u3 = (u3 ^ x[9]) & M32
    u1 = rotl(u3, 12)
    x[3] = (x[3] + u1) & M32
    u9 = (u9 ^ x[3]) & M32
    x[14] = rotl(u9, 8)
    x[9] = (x[9] + x[14]) & M32
    u1 = (u1 ^ x[9]) & M32
    x[4] = rotl(u1, 7)

def keystream(cfg_words, counter):
    rounds = cfg_words[0]
    x = [0] * 16
    for i in range(16):
        x[i] = counter if i == 12 else cfg_words[i + 1]
    for _ in range(rounds):
        double_round(x)
    for i in range(16):
        x[i] = (x[i] + (counter if i == 12 else cfg_words[i + 1])) & M32
    return b''.join(struct.pack('<I', v) for v in x)

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

def load(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    off = 32
    segs = []
    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))
        off += size
    return d, segs

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

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

def main():
    p = sys.argv[1]
    d, segs = load(p)
    print('segments:', [(s[0], hex(s[1]), hex(s[2]), hex(s[3])) for s in segs])
    # đếm pointer "trơn" trong __DATA để biết chained-fixup
    for name, vm, vs, fo, fs in segs:
        if name == '__DATA':
            cnt = 0
            for o in range(fo, fo + fs - 8, 8):
                v = struct.unpack_from('<Q', d, o)[0]
                if 0x1000 <= v < 0x7d0000:
                    cnt += 1
            print('plain-looking pointers in __DATA:', cnt, '/', fs // 8)

    hits = 0
    for q in range(0, len(d) - 0x80, 8):
        rounds = struct.unpack_from('<I', d, q)[0]
        if not (1 <= rounds <= 64):
            continue
        p_off = struct.unpack_from('<Q', d, q + 0x68)[0]
        p_blob = struct.unpack_from('<Q', d, q + 0x48)[0]
        if not (0x1000 <= p_off < len(d)) or not (0x1000 <= p_blob < len(d)):
            continue
        # offsets phải nằm trong vùng đọc được
        try:
            offs = list(struct.unpack_from('<%dI' % (0x198 + 3), d, p_off))
        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] > 0x400000:
            continue
        blob_size = len(d) - p_blob
        if offs[-1] > blob_size:
            continue
        cfg_words = list(struct.unpack_from('<17I', d, q))
        blob = d[p_blob:p_blob + offs[-1]]
        ok = 0
        for sec in list(range(1, 7)) + list(range(8, 27)):
            b = decrypt(cfg_words, blob, offs[sec], offs[sec+1])
            if is_digits(b):
                ok += 1
        print('\nCANDIDATE q=0x%x rounds=%d p_off=0x%x p_blob=0x%x last_off=0x%x digits_ok=%d/%d'
              % (q, rounds, p_off, p_blob, offs[-1], ok, 6 + 19))
        if ok >= 20:
            hits += 1
            for sec in list(range(1, 7)) + list(range(8, 27)):
                b = decrypt(cfg_words, blob, offs[sec], offs[sec+1])
                print('  sec %-4d len=%-4d %s' % (sec, len(b), b[:60]))
    print('\nhits:', hits)

if __name__ == '__main__':
    main()
