#!/usr/bin/env python3
"""Scan Driver __text for tripwire pattern: sentinel check -> b.ne -> block with bl into __stubs."""
import struct, sys
import capstone, lief

sys.stdout.reconfigure(encoding='utf-8')
P = r'patch_src\Payload\Driver.app\Driver'
b = lief.MachO.parse(P).at(0)
base = b.imagebase
d = open(P, 'rb').read()
text = b.get_section('__text')
lo, hi = text.virtual_address, text.virtual_address + text.size
STUB_LO, STUB_HI = 0x1018fcedc, 0x10190cd10  # __stubs range

md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
md.skipdata = True

# First: index every bl into __stubs
stub_bl = {}
insns = list(md.disasm(d[lo - base:hi - base], lo))
print('insns:', len(insns))
for idx, ins in enumerate(insns):
    if ins.mnemonic == 'bl' and ins.operands and ins.operands[0].type == capstone.arm64.ARM64_OP_IMM:
        t = ins.operands[0].imm
        if STUB_LO <= t < STUB_HI:
            stub_bl[idx] = t

# Known confirmed-abort stubs
known = {0x1018fc6e8, 0x10190c47c, 0x1018fe118, 0x1018fe484}

# Tripwire fingerprint: within a 6-instruction window before a stub_bl, there is
# 'cmn xN, #1' or 'cmp x0, xN'-style check feeding a b.ne/b.eq that lands near the bl.
sites = []
for idx, stub in stub_bl.items():
    window = insns[max(0, idx - 8):idx]
    has_cmn1 = any(i.mnemonic == 'cmn' and len(i.operands) == 2 and
                   i.operands[1].type == capstone.arm64.ARM64_OP_IMM and
                   i.operands[1].imm == 1 for i in window)
    sites.append((insns[idx].address, stub, has_cmn1))

print('total bl-into-stubs sites:', len(sites))
cmn_sites = [s for s in sites if s[2]]
print('sites with cmn #1 fingerprint:', len(cmn_sites))
for a, s, _ in cmn_sites:
    mark = ' <-- KNOWN' if s in known else ''
    print('  %#x stub %#x%s' % (a - base, s, mark))
# Also list all distinct stubs called, sorted by site count, to spot the abort family
from collections import Counter
cnt = Counter(s for _, s, _ in sites)
print('--- stub call counts (top 25) ---')
for s, c in cnt.most_common(25):
    print('  stub %#x x%d %s' % (s, c, 'KNOWN-ABORT' if s in known else ''))
