#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
scan_verdiff.py - quet anchor (string plain + XOR-0x55) tren nhieu binary Mach-O
de so sanh su hien dien cua cac co che phat hien giua cac phien ban GSM Driver.

Dung: python scan_verdiff.py <out_report.txt> <ten1>=<duong_dan1> [ten2=duong_dan2 ...]
Moi anchor: in so hit + section (chi plain). Ghi file UTF-8.
"""
import struct, sys, re, os


def parse(p):
    d = open(p, 'rb').read()
    magic, cputype, cpusub, filetype, ncmds, sizeofcmds, flags = struct.unpack_from('<IiiIIII', d, 0)
    segs, sections = [], []
    off = 32
    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('utf-8', 'replace')
            vmaddr, vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off+24)
            segs.append((name, vmaddr, vmsize, fileoff, filesize))
            nsects, = struct.unpack_from('<I', d, off + 64)
            so = off + 72
            for _i in range(nsects):
                sname = d[so:so+16].rstrip(b'\x00').decode('utf-8', 'replace')
                segname = d[so+16:so+32].rstrip(b'\x00').decode('utf-8', 'replace')
                addr, sz = struct.unpack_from('<QQ', d, so+32)
                foff, = struct.unpack_from('<I', d, so+48)
                sections.append((segname, sname, addr, sz, foff))
                so += 80
        off += size
    return d, segs, sections


def sect_of(segs, sections, off):
    for segname, sname, addr, sz, foff in sections:
        if foff <= off < foff + sz:
            return '%s,%s' % (segname, sname)
    for name, vm, vs, fo, fs in segs:
        if fo <= off < fo + fs:
            return name
    return '?'


def xor55(b):
    return bytes(c ^ 0x55 for c in b)


ANCHORS_PLAIN = [
    # --- jailbreak paths / apps ---
    '/Applications/Cydia.app', 'TrollStore', '/var/jb', 'Dopamine', 'me.ra1n.dopamine',
    'com.opa334.Dopamine', 'ellekit', 'MobileSubstrate', 'SubstrateLoader', 'CydiaSubstrate',
    '/private/var/lib/apt', '/private/var/stash', 'xyz.willy.Zebra', 'sileo://', 'cydia://',
    'undecimus', 'trollstore', '/usr/sbin/sshd', '/bin/bash', '/var/mobile/Library/Preferences',
    'roothide', 'jbroot', 'systemhook', 'Bootstrap', 'Palera1n', 'checkra1n', 'TrollStoreHelper',
    # --- dylib / runtime hook ---
    'frida', 'libfrida', 'FridaGadget', 'frida-server', 'gadget', 'cynject', 'cycript',
    'libcycript', 'libhooker', 'TweakInject', 'substrate', 'libellekit', 'libsubstrate',
    'debugserver', 'SSLKillSwitch', 'PreferenceLoader', 'WeeLoader', 'Substitute',
    # --- swift eKYC_GSM fields / classes ---
    '_TtC8eKYC_GSM12ScreenShield', '_TtC8eKYC_GSM12SecurityInfo', '_TtC8eKYC_GSM18DetectionProcessor',
    'FEKYCCameraIntegritySession', 'isJailbroken', 'isJaibreak', 'isHooking', 'isDebug',
    'isSimulator', 'isScreeShield', 'isAddShield', 'isCanWrieSandbox', 'isAccessibility',
    '_securityReasons', '_securityPayload', 'hasRuntimeHook', 'runtimeHookDetector',
    'cachedRuntimeHookDetected', 'lastRuntimeHookCheckUptime', 'lastTopologyCheckUptime',
    'isDebuggerAttached', 'canWriteOutsideSandbox', 'hasSuspiciousProcess', 'hasSuspiciousImage',
    'isAccessibilityEnabled', 'cameraIntegrity', 'p_debugger',
    # --- receipt / profile ---
    'appStoreReceiptURL', 'sandboxReceipt', 'embedded.mobileprovision', 'get-task-allow',
    'ProvisionedDevices', 'aps-environment', 'application-identifier',
    # --- high risk config ---
    'high_ris', 'high_risk',
    # --- BShield surface ---
    'getDetectFlags', 'onOSProtectionStatusChanged', 'onBShieldOSProtectionStatusChanged',
    'loadShield:', 'ShieldLoader', 'getShieldCode', 'generateSignature', 'verifyChallenge',
    'build-info', 'bshield',
    # --- attestation / anti-abuse ---
    'DCAppAttest', 'RecaptchaEnterprise', 'attestKey', 'DeviceCheck',
    # --- env / debug misc ---
    'hw.machine', 'ptrace', 'csops', 'SecTask', 'MGCopyAnswer', 'sysctl',
]

ANCHORS_XOR55 = ['frida', 'Cydia', 'MobileSubstrate', 'roothide', 'jbroot', 'libhooker',
                 'TweakInject', 'substrate', 'frida-server', 'FridaGadget', 'cycript']


def main():
    out_path = sys.argv[1]
    specs = sys.argv[2:]
    lines = []
    bins = {}
    for spec in specs:
        name, path = spec.split('=', 1)
        d, segs, sections = parse(path)
        bins[name] = (path, d, segs, sections)
        lines.append('== %s = %s  (size %d)' % (name, path, len(d)))

    hdr = ['anchor'] + [n for n in bins]
    lines.append('')
    lines.append('## BANG ANCHOR PLAIN (so hit; -1 = anchor nam trong code-region ket qua am? khong ap dung)')
    lines.append(' | '.join(hdr))
    for a in ANCHORS_PLAIN:
        ab = a.encode()
        row = [a]
        for n, (path, d, segs, sections) in bins.items():
            row.append(str(d.count(ab)))
        lines.append(' | '.join(row))

    lines.append('')
    lines.append('## CHI TIET HIT PLAIN (offset + section, moi binary)')
    for a in ANCHORS_PLAIN:
        ab = a.encode()
        any_hit = False
        for n, (path, d, segs, sections) in bins.items():
            offs = [m.start() for m in re.finditer(re.escape(ab), d)]
            if offs:
                any_hit = True
                shown = offs[:6]
                more = '' if len(offs) <= 6 else ' (+%d)' % (len(offs) - 6)
                lines.append('%s | %s | %s%s' % (
                    a, n,
                    ', '.join('0x%x[%s]' % (o, sect_of(segs, sections, o)) for o in shown),
                    more))
        if any_hit:
            lines.append('')

    lines.append('## BANG ANCHOR XOR-0x55 (so hit)')
    lines.append(' | '.join(hdr))
    for a in ANCHORS_XOR55:
        ab = xor55(a.encode())
        row = [a + ' ^55']
        for n, (path, d, segs, sections) in bins.items():
            row.append(str(d.count(ab)))
        lines.append(' | '.join(row))

    lines.append('')
    lines.append('## CHI TIET HIT XOR-0x55')
    for a in ANCHORS_XOR55:
        ab = xor55(a.encode())
        any_hit = False
        for n, (path, d, segs, sections) in bins.items():
            offs = [m.start() for m in re.finditer(re.escape(ab), d)]
            if offs:
                any_hit = True
                shown = offs[:6]
                more = '' if len(offs) <= 6 else ' (+%d)' % (len(offs) - 6)
                lines.append('%s^55 | %s | %s%s' % (
                    a, n,
                    ', '.join('0x%x[%s]' % (o, sect_of(segs, sections, o)) for o in shown),
                    more))
        if any_hit:
            lines.append('')

    txt = '\n'.join(lines)
    with open(out_path, 'w', encoding='utf-8') as f:
        f.write(txt)
    # stdout short: chi phan bang
    for ln in lines:
        if ln.startswith(('==', '##', ' | '.join(hdr)[:0]) ) or ' | ' in ln:
            try:
                print(ln)
            except Exception:
                pass


if __name__ == '__main__':
    main()
