Files
iOSGuard/tools/llvm_obf/verify_macho_indirect_branches.py
T

129 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""Verify that every indirect-branch obfuscated function emits ARM64 `br xN` instructions in Mach-O."""
import argparse
from collections import Counter
from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import subprocess
from verify_macho_star_cfg import (
JUMP_TABLE_BR_RE,
_candidate_symbol_keys,
parse_dwarf_text_ranges,
)
def _count_br_insns(main_bin: Path, start_addr: int, end_addr: int) -> dict:
dis = subprocess.check_output(
[
'xcrun', 'llvm-objdump', '--disassemble',
f'--start-address={hex(start_addr)}',
f'--stop-address={hex(end_addr)}',
str(main_bin),
],
text=True,
)
br_count = sum(1 for line in dis.splitlines() if JUMP_TABLE_BR_RE.search(line))
return {
'start_addr': hex(start_addr),
'end_addr': hex(end_addr),
'indirect_br_count': br_count,
}
def verify_binary_indirect_branches(
main_bin: Path,
dwarf_bin: Path,
obf_audit: dict,
*,
fail_on_missing: bool = False,
required_sources: Iterable[str] = (),
) -> dict:
"""Disassemble every audited IBR function in main_bin and require >=1 `br xN`."""
ranges_map = parse_dwarf_text_ranges(dwarf_bin)
verified = []
failed = []
dead_stripped = []
to_check: list[tuple[str, str, list[tuple[int, int]]]] = []
for mod in obf_audit.get('module_audits') or []:
src_name = Path(mod.get('source_path') or 'unknown').name
for raw_name in mod.get('indirect_branches_functions') or []:
cand_ranges = []
for key in _candidate_symbol_keys(raw_name):
if key in ranges_map:
cand_ranges = ranges_map[key]
break
if not cand_ranges:
rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'}
dead_stripped.append(rec)
if fail_on_missing:
failed.append(rec)
continue
to_check.append((src_name, raw_name, cand_ranges))
unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist})
inspected_by_range: dict[tuple[int, int], dict] = {}
if unique_ranges:
with ThreadPoolExecutor(max_workers=8) as pool:
results = pool.map(lambda se: _count_br_insns(main_bin, se[0], se[1]), unique_ranges)
for se, res in zip(unique_ranges, results):
inspected_by_range[se] = res
for src_name, raw_name, cand_ranges in to_check:
range_results = [inspected_by_range[se] for se in cand_ranges]
bad = [r for r in range_results if r['indirect_br_count'] < 1]
if bad:
failed.append({
'source': src_name,
'name': raw_name,
'reason': 'missing_indirect_br_instruction',
'range_results': range_results,
})
else:
verified.append({
'source': src_name,
'name': raw_name,
**range_results[0],
})
verified_per_source = Counter(item['source'] for item in verified)
required_source_counts = {source: verified_per_source[source] for source in required_sources}
summary = {
'required_sources_verified': required_source_counts,
'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)),
'linked_checked_count': len(verified) + len(failed),
'verified_ibr_count': len(verified),
'dead_stripped_count': len(dead_stripped),
'failed_count': len(failed),
'failed': failed,
'sample_verified': verified[:12],
}
if failed:
preview = json.dumps(failed[:5], ensure_ascii=False, indent=2)
raise AssertionError(
f'[IndirectBranchGate] {len(failed)} function(s) failed br xN check:\n{preview}'
)
missing_sources = [source for source, count in required_source_counts.items() if not count]
if missing_sources:
raise AssertionError('[IndirectBranchGate] 缺少已链接的间接分支保护: ' + ', '.join(missing_sources))
return summary
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', type=Path, required=True)
parser.add_argument('--dwarf', type=Path, required=True)
parser.add_argument('--audit', type=Path, required=True)
args = parser.parse_args()
audit = json.loads(args.audit.read_text(encoding='utf-8'))
res = verify_binary_indirect_branches(args.binary, args.dwarf, audit)
print(json.dumps(res, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()