feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固

- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测
- llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言)
- tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化)
- tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+484
View File
@@ -0,0 +1,484 @@
#!/usr/bin/env python3
"""Audit exported IPA for Route 2 compliance, static hygiene, dSYM UUID consistency, and Mach-O hardening gates."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import plistlib
import re
import subprocess
import sys
from tempfile import TemporaryDirectory
SCRIPT_DIR = Path(__file__).resolve().parent
TOOLS_DIR = SCRIPT_DIR.parent
TOOLCHAIN_ROOT = TOOLS_DIR.parent
sys.path.insert(0, str(SCRIPT_DIR))
sys.path.insert(0, str(TOOLS_DIR / 'macho_guard'))
sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf'))
from route2_archive_common import ( # noqa: E402
EXTERNAL_SYMBOLS,
GUARD_FRAMEWORK_NAME,
SYSTEM_SYMBOLS,
collect_variant_stubs,
)
from verify_baseline import scan, validate_zip # noqa: E402
import verify_macho_indirect_branches # noqa: E402
import verify_macho_indirect_calls # noqa: E402
import verify_macho_star_cfg # noqa: E402
_ANTI_HOOK_OBJDUMP_RE = re.compile(r'^\s*([0-9a-fA-F]+):\s+([0-9a-fA-F]{8})\s+(.+?)\s*$')
_ANTI_HOOK_MOV_RE = re.compile(r'^(?:mov\s+(x1[67])\s*,\s*\1|orr\s+(x1[67])\s*,\s*xzr\s*,\s*\2)\b')
_ANTI_HOOK_OPCODES = {'aa1103f1': 'x17', 'aa1003f0': 'x16'}
_FORBIDDEN_DEFENDER_CLUES = (
b'IGDefender',
b'IGAntiHook',
b'IGAntiTamper',
b'IGArchiveGuard',
b'termination.jsonl',
b'"action":"terminate"',
)
_JAILBREAK_QUERY_SCHEMES = {'cydia', 'sileo', 'zebra', 'zbra', 'filza', 'undecimus'}
def _uuids_of(path):
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True)
return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')}
def _inspect_anti_hook_range(main_bin, start_addr, end_addr):
if end_addr - start_addr < 8:
return {
'start_addr': hex(start_addr),
'end_addr': hex(end_addr),
'ok': False,
'insns': [],
'reason': 'function_shorter_than_8_bytes',
}
dis = subprocess.check_output(
[
'xcrun', 'llvm-objdump', '--disassemble',
f'--start-address={hex(start_addr)}',
f'--stop-address={hex(start_addr + 8)}',
str(main_bin),
],
text=True,
)
insns = []
seen_regs = set()
for line in dis.splitlines():
m = _ANTI_HOOK_OBJDUMP_RE.match(line)
if not m:
continue
addr = int(m.group(1), 16)
ophex = m.group(2).lower()
text = ' '.join(m.group(3).split())
reg = _ANTI_HOOK_OPCODES.get(ophex)
if reg is None:
mm = _ANTI_HOOK_MOV_RE.match(text)
if mm:
reg = mm.group(1) or mm.group(2)
insns.append({'addr': hex(addr), 'opcode': ophex, 'asm': text, 'reg': reg})
if reg in ('x16', 'x17'):
seen_regs.add(reg)
ok = (
len(insns) >= 2
and insns[0]['addr'] == hex(start_addr)
and insns[1]['addr'] == hex(start_addr + 4)
and insns[0]['reg'] in ('x16', 'x17')
and insns[1]['reg'] in ('x16', 'x17')
and seen_regs == {'x16', 'x17'}
)
return {
'start_addr': hex(start_addr),
'end_addr': hex(end_addr),
'ok': ok,
'insns': insns[:2],
}
def _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit):
ranges_map = verify_macho_star_cfg.parse_dwarf_text_ranges(dwarf_bin)
verified = []
failed = []
dead_stripped = []
to_check = []
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('anti_hook_functions') or []:
cand_ranges = []
for key in verify_macho_star_cfg._candidate_symbol_keys(raw_name):
if key in ranges_map:
cand_ranges = ranges_map[key]
break
if not cand_ranges:
dead_stripped.append({'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'})
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 = {}
if unique_ranges:
with ThreadPoolExecutor(max_workers=8) as pool:
results = pool.map(lambda se: _inspect_anti_hook_range(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 not r['ok']]
if bad:
failed.append({
'source': src_name,
'name': raw_name,
'reason': 'missing_anti_hook_x16_x17_prologue',
'range_results': range_results,
})
else:
verified.append({'source': src_name, 'name': raw_name, **range_results[0]})
summary = {
'total_audited': len(verified) + len(failed) + len(dead_stripped),
'linked_checked_count': len(verified) + len(failed),
'verified_anti_hook_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 ValueError(f'[AntiHookGate] {len(failed)} function(s) failed x16/x17 prologue check:\n{preview}')
return summary
def _check_static_hygiene(app_dir, main_bin, info):
"""Run static-hygiene checks on unpacked .app payload (zero hardcoded host paths)."""
main_raw = main_bin.read_bytes()
fw_dir = app_dir / 'Frameworks'
rd_coreio_bin = fw_dir / f'{GUARD_FRAMEWORK_NAME}.framework' / GUARD_FRAMEWORK_NAME
rd_coreio_exists = rd_coreio_bin.is_file()
ig_archive_guard_absent = not (fw_dir / 'IGArchiveGuard.framework').exists()
rd_coreio_ig_exports = []
rd_coreio_ig_name_count = 0
if rd_coreio_exists:
core_raw = rd_coreio_bin.read_bytes()
rd_coreio_ig_name_count = core_raw.count(b'IGArchiveGuard')
nm_core = subprocess.check_output(['xcrun', 'nm', '-gU', str(rd_coreio_bin)], text=True, errors='replace')
rd_coreio_ig_exports = sorted(
sym for ln in nm_core.splitlines()
if ln.strip() and (sym := ln.split()[-1]).startswith('_ig_')
)
staticized_framework_leaks = [
name for name in ('RDEpubReaderView.framework', 'RDPDFReaderView.framework')
if (fw_dir / name).exists()
]
otool_l = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True, errors='replace').splitlines()
cryptokit_load_cmds = [ln.strip() for ln in otool_l if 'CryptoKit' in ln]
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(main_bin)], text=True, errors='replace').splitlines()
cryptokit_imports = sorted({
ln.strip() for ln in nm_u
if ln.strip() and ('CryptoKit' in ln or '9CryptoKit' in ln)
})
nm_gu = subprocess.check_output(['xcrun', 'nm', '-gU', str(main_bin)], text=True, errors='replace')
defined_exports = sorted({ln.split()[-1] for ln in nm_gu.splitlines() if ln.strip()})
allowed_exports = {'_main', '__mh_execute_header'}
main_exports_locked = set(defined_exports).issubset(allowed_exports)
forbidden_clue_counts = {
pat.decode('ascii', errors='replace'): main_raw.count(pat)
for pat in _FORBIDDEN_DEFENDER_CLUES
}
ats = info.get('NSAppTransportSecurity') or {}
ats_arbitrary_disabled = ats.get('NSAllowsArbitraryLoads') is not True
schemes = {str(s).lower() for s in (info.get('LSApplicationQueriesSchemes') or [])}
jb_schemes_found = sorted(schemes & _JAILBREAK_QUERY_SCHEMES)
checks = {
'guard_framework_present': rd_coreio_exists,
'ig_archive_guard_absent': ig_archive_guard_absent,
'guard_no_ig_exports': not rd_coreio_ig_exports,
'guard_no_ig_name_string': rd_coreio_ig_name_count == 0,
'self_frameworks_staticized': not staticized_framework_leaks,
'cryptokit_completely_absent': not cryptokit_load_cmds and not cryptokit_imports,
'main_exports_locked': main_exports_locked,
'defender_clues_absent': sum(forbidden_clue_counts.values()) == 0,
'ats_arbitrary_loads_disabled': ats_arbitrary_disabled,
'jailbreak_schemes_absent': not jb_schemes_found,
}
return {
'passed': all(checks.values()),
'checks': checks,
'rd_coreio_ig_exports': rd_coreio_ig_exports,
'rd_coreio_ig_name_count': rd_coreio_ig_name_count,
'staticized_framework_leaks': staticized_framework_leaks,
'cryptokit_load_cmds': cryptokit_load_cmds,
'cryptokit_imports': cryptokit_imports,
'main_defined_exports': defined_exports,
'forbidden_clue_counts': forbidden_clue_counts,
'jailbreak_schemes_found': jb_schemes_found,
}
def _check_obf_audit_counts(obf_audit, policy):
failures = []
checks = [
('flatten_targets', 'total_flattened'),
('opaque_const_targets', 'total_opaque_constants'),
('arithmetic_targets', 'total_arithmetic_rewrites'),
('indirect_branch_targets', 'total_indirect_branches'),
('string_encrypt_stack_targets', 'total_strings_stack_encrypted'),
('anti_hooking_targets', 'total_anti_hook_functions'),
('function_outline_targets', 'total_functions_outlined'),
('opaque_field_targets', 'total_opaque_field_access'),
('bb_split_targets', 'total_bb_split_count'),
]
for pol_key, audit_key in checks:
if policy.get(pol_key) and int(obf_audit.get(audit_key) or 0) <= 0:
failures.append(f'{audit_key} expected > 0')
has_str = any(
policy.get(k)
for k in ('string_encrypt_targets', 'string_encrypt_objc_targets', 'string_encrypt_swift_targets')
)
if has_str and int(obf_audit.get('total_strings_encrypted') or 0) <= 0:
failures.append('total_strings_encrypted expected > 0')
if policy.get('arithmetic_nonlinear_mba') or any(r.get('nonlinear_mba') for r in (policy.get('arithmetic_targets') or [])):
if int(obf_audit.get('total_nonlinear_mba') or 0) <= 0:
failures.append('total_nonlinear_mba expected > 0')
if policy.get('opaque_const_opaque_zero') or any(r.get('opaque_zero') for r in (policy.get('opaque_const_targets') or [])):
if int(obf_audit.get('total_opaque_zero') or 0) <= 0:
failures.append('total_opaque_zero expected > 0')
policy_reqs = {r['id']: r for r in (policy.get('required_targets') or []) if isinstance(r, dict) and r.get('id')}
if policy_reqs and isinstance(obf_audit.get('required_targets'), list):
got_map = {r['id']: r for r in obf_audit['required_targets'] if isinstance(r, dict) and r.get('id')}
for tid, req in policy_reqs.items():
got = got_map.get(tid)
if got is None:
failures.append(f'missing required_target: {tid}')
continue
if int(got.get('flattened_hits') or 0) < int(req.get('min_flattened', 0)):
failures.append(f'{tid} flattened_hits={got.get("flattened_hits")} < {req.get("min_flattened", 0)}')
if int(got.get('strings_encrypted_hits') or 0) < int(req.get('min_strings_encrypted', 0)):
failures.append(
f'{tid} strings_encrypted_hits={got.get("strings_encrypted_hits")} < {req.get("min_strings_encrypted", 0)}'
)
return failures
def _load_policy(policy_path=None):
cand = Path(policy_path) if policy_path else (TOOLCHAIN_ROOT / 'config' / 'ig_llvm_policy.json')
if cand.is_file():
return json.loads(cand.read_text(encoding='utf-8'))
return {}
def _find_dwarf_in_archive(archive_path, app_name, exec_name):
dsyms_dir = Path(archive_path) / 'dSYMs'
if not dsyms_dir.is_dir():
return None
for cand_name in (f'{app_name}.dSYM', f'{exec_name}.app.dSYM'):
dwarf_p = dsyms_dir / cand_name / 'Contents' / 'Resources' / 'DWARF' / exec_name
if dwarf_p.is_file():
return dwarf_p
for dsym in sorted(dsyms_dir.glob('*.app.dSYM')):
dwarf_p = dsym / 'Contents' / 'Resources' / 'DWARF' / dsym.name.removesuffix('.app.dSYM')
if dwarf_p.is_file():
return dwarf_p
return None
def audit_ipa(
ipa,
expected_bundle_id=None,
archive_path=None,
audit_json_path=None,
policy_path=None,
symbol_map_path=None,
skip_macho_gates=False,
report_out=None,
):
validate_zip(ipa)
report = {
'ipa': str(ipa),
'passed': False,
'errors': [],
}
try:
with TemporaryDirectory(prefix='ig-export-audit-') as temporary_dir:
unpacked = Path(temporary_dir)
subprocess.run(['ditto', '-x', '-k', str(ipa), str(unpacked)], check=True)
apps = sorted((unpacked / 'Payload').glob('*.app'))
if len(apps) != 1:
raise ValueError(f'IPA 应包含一个主 App,实际找到 {len(apps)} 个')
app = apps[0]
with (app / 'Info.plist').open('rb') as plist_file:
info = plistlib.load(plist_file)
bundle_id = info['CFBundleIdentifier']
if expected_bundle_id and bundle_id != expected_bundle_id:
raise ValueError(f'IPA Bundle ID 为 {bundle_id},预期为 {expected_bundle_id}')
exec_name = info['CFBundleExecutable']
main_bin = app / exec_name
binaries, callsites = scan(app, unpacked, 'exported')
if exec_name not in binaries:
raise ValueError('IPA 主可执行文件未纳入 Mach-O 扫描')
counts = dict.fromkeys(EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS, 0)
invalid_images = []
for relative_path, binary in binaries.items():
if any(section['cryptid'] for section in binary['slices']):
raise ValueError(f'无法静态检查已加密的 Mach-O:{relative_path}')
for section in binary['slices']:
for symbol, count in section['counts'].items():
counts[symbol] += count
variants = collect_variant_stubs(app / relative_path)
if variants:
invalid_images.append(f'{relative_path}: {", ".join(variants)}')
external = sum(counts[symbol] for symbol in EXTERNAL_SYMBOLS)
system = sum(counts[symbol] for symbol in SYSTEM_SYMBOLS)
report['bundle_id'] = bundle_id
report['route2'] = {
'binaries': len(binaries),
'external_calls': external,
'system_calls': system,
'callsites_total': callsites,
'variant_stubs': invalid_images,
}
if callsites or invalid_images:
raise ValueError(
f'IPA Route 2 审计失败:外部函数直接调用 {external},系统函数直接调用 {system},'
f'变体符号 {invalid_images}'
)
hygiene = _check_static_hygiene(app, main_bin, info)
report['static_hygiene'] = hygiene
if not hygiene['passed']:
failed_keys = [k for k, v in hygiene['checks'].items() if not v]
raise ValueError(f'IPA 静态卫生门禁失败: {failed_keys}')
policy = _load_policy(policy_path)
obf_audit = None
if audit_json_path and Path(audit_json_path).is_file():
obf_audit = json.loads(Path(audit_json_path).read_text(encoding='utf-8'))
audit_failures = _check_obf_audit_counts(obf_audit, policy)
report['obf_audit_summary'] = {
k: obf_audit.get(k)
for k in (
'total_flattened', 'total_strings_encrypted', 'total_strings_stack_encrypted',
'total_indirect_calls', 'total_opaque_constants', 'total_arithmetic_rewrites',
'total_nonlinear_mba', 'total_opaque_zero', 'total_indirect_branches',
'total_anti_hook_functions', 'total_functions_outlined',
'total_opaque_field_access', 'total_bb_split_count', 'static_frameworks_obfuscated',
)
}
if audit_failures:
raise ValueError(f'LLVM 混淆审计计数不满足策略: {"; ".join(audit_failures)}')
if archive_path and Path(archive_path).is_dir():
dwarf_bin = _find_dwarf_in_archive(archive_path, app.name, exec_name)
if dwarf_bin is None:
raise ValueError(f'xcarchive 缺少 DWARF 文件: {archive_path}')
ipa_uuids = _uuids_of(main_bin)
dwarf_uuids = _uuids_of(dwarf_bin)
report['dsym_uuid_match'] = {
'ipa_uuids': sorted(ipa_uuids),
'dwarf_uuids': sorted(dwarf_uuids),
'matched': bool(ipa_uuids) and ipa_uuids == dwarf_uuids,
}
if not report['dsym_uuid_match']['matched']:
raise ValueError(f'IPA 与 dSYM UUID 不一致: ipa={ipa_uuids}, dwarf={dwarf_uuids}')
if obf_audit is not None and not skip_macho_gates:
star_gate = verify_macho_star_cfg.verify_binary_star_cfg(
main_bin, dwarf_bin, obf_audit, require_topology='sparse_switch'
)
report['star_cfg_gate'] = star_gate
if policy.get('flatten_targets') and star_gate['verified_star_count'] <= 0:
raise ValueError('StarCFGGate verified_star_count 为 0')
ibr_gate = verify_macho_indirect_branches.verify_binary_indirect_branches(
main_bin, dwarf_bin, obf_audit
)
report['indirect_branch_gate'] = ibr_gate
if policy.get('indirect_branch_targets') and ibr_gate['verified_ibr_count'] <= 0:
raise ValueError('IndirectBranchGate verified_ibr_count 为 0')
icall_gate = verify_macho_indirect_calls.analyze_macho_calls(
main_bin,
dwarf_bin,
symbol_map_path=Path(symbol_map_path) if symbol_map_path else None,
require_zero_keybox_direct_bl=bool(policy.get('indirect_call_targets')),
)
report['indirect_call_gate'] = {
'text_call_summary': icall_gate['text_call_summary'],
'keybox_total_direct_call_xrefs': icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'],
'gate_passed': icall_gate['gate_passed'],
'violations': icall_gate['violations'],
}
if not icall_gate['gate_passed']:
raise ValueError(f"IndirectCallGate failed: {icall_gate['violations']}")
anti_hook_gate = _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit)
report['anti_hook_gate'] = anti_hook_gate
if policy.get('anti_hooking_targets') and anti_hook_gate['verified_anti_hook_count'] <= 0:
raise ValueError('AntiHookGate verified_anti_hook_count 为 0')
report['passed'] = True
print(
f'IPA 审计通过:{bundle_id},{len(binaries)} 个 Mach-O,'
f'外部函数直接调用 {external},系统函数直接调用 {system},'
f'StaticHygieneGate=PASS'
)
return report
except Exception as exc:
report['errors'].append(str(exc))
raise
finally:
if report_out:
out_p = Path(report_out)
out_p.parent.mkdir(parents=True, exist_ok=True)
out_p.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('ipa', type=Path)
parser.add_argument('--bundle-id')
parser.add_argument('--archive', type=Path, default=None)
parser.add_argument('--audit-json', type=Path, default=None)
parser.add_argument('--policy', type=Path, default=None)
parser.add_argument('--symbol-map', type=Path, default=None)
parser.add_argument('--report-out', type=Path, default=None)
parser.add_argument('--skip-macho-gates', action='store_true')
arguments = parser.parse_args()
try:
audit_ipa(
arguments.ipa,
expected_bundle_id=arguments.bundle_id,
archive_path=arguments.archive,
audit_json_path=arguments.audit_json,
policy_path=arguments.policy,
symbol_map_path=arguments.symbol_map,
skip_macho_gates=arguments.skip_macho_gates,
report_out=arguments.report_out,
)
except (OSError, ValueError, AssertionError, subprocess.CalledProcessError) as error:
parser.exit(1, f'{error}\n')