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')
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Xcode Release arm64 C/ObjC compiler wrapper (3-stage LLVM bitcode -> opt -> native Mach-O)."""
import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile
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 / 'llvm_obf'))
from ig_toolchain_resolver import ( # noqa: E402
detect_sdk_info,
detect_stock_tool,
detect_xcode_info,
discover_active_app_repo,
file_sha256,
resolve_effective_policy,
resolve_opt,
)
SOURCE_EXTENSIONS = {'.c', '.m', '.mm', '.cc', '.cpp', '.cxx', '.c++'}
def resolve_default_policy(profile='default'):
names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else []
names.append('ig_llvm_policy.json')
for name in names:
for cand in (
TOOLCHAIN_ROOT / 'config' / name,
TOOLCHAIN_ROOT / 'llvm_obf' / name,
):
if cand.is_file():
return str(cand)
return ''
def expand_response_files(args):
expanded = []
for arg in args:
if arg.startswith('@') and len(arg) > 1:
resp = Path(arg[1:])
if resp.is_file():
text = resp.read_text(encoding='utf-8', errors='replace')
expanded.extend(shlex.split(text))
continue
expanded.append(arg)
return expanded
def parse_control_token(expanded_args):
"""Extract control tuple from `-DIG_OBF_CTL_<mode>__<filter>__<route2>__<all_off>__<seed>__<stamp>[__<profile>]=1`."""
ctl = {
'mode': 'full',
'filter': 'all',
'route2': 'on',
'all_off': '0',
'seed': 'm0_seed_20261119_v1',
'stamp': 'default',
'policy_profile': 'default',
}
prefix = '-DIG_OBF_CTL_'
for arg in expanded_args:
if arg.startswith(prefix):
body = arg[len(prefix):]
if '=' in body:
body = body.split('=', 1)[0]
parts = body.split('__')
if len(parts) >= 7:
ctl['mode'] = parts[0] or ctl['mode']
ctl['filter'] = parts[1] or ctl['filter']
ctl['route2'] = parts[2] or ctl['route2']
ctl['all_off'] = parts[3] or ctl['all_off']
ctl['seed'] = parts[4] or ctl['seed']
ctl['stamp'] = parts[5] or ctl['stamp']
ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile']
elif len(parts) >= 6:
ctl['mode'] = parts[0] or ctl['mode']
ctl['filter'] = parts[1] or ctl['filter']
ctl['route2'] = parts[2] or ctl['route2']
ctl['all_off'] = parts[3] or ctl['all_off']
ctl['seed'] = parts[4] or ctl['seed']
ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp']
elif len(parts) >= 1 and parts[0]:
ctl['mode'] = parts[0]
# Env overrides take precedence if explicitly set
if os.environ.get('IG_DISABLE_LLVM_OBF') == '1':
ctl['mode'] = 'off'
if os.environ.get('IG_ALL_GUARD_OFF') == '1':
ctl['all_off'] = '1'
ctl['mode'] = 'off'
if os.environ.get('IG_OBF_MODE'):
ctl['mode'] = os.environ['IG_OBF_MODE']
if os.environ.get('IG_LLVM_PASS_FILTER'):
ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER']
if os.environ.get('IG_RELEASE_SEED'):
ctl['seed'] = os.environ['IG_RELEASE_SEED']
if os.environ.get('IG_POLICY_PROFILE'):
ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE']
if ctl['all_off'] == '1':
ctl['mode'] = 'off'
return ctl
def parse_compile_metadata(raw_args, expanded_args):
has_c = '-c' in expanded_args
out_path = None
top_out_idx = None
for idx, arg in enumerate(raw_args):
if arg == '-o' and idx + 1 < len(raw_args):
top_out_idx = idx + 1
out_path = raw_args[idx + 1]
if out_path is None:
for idx, arg in enumerate(expanded_args):
if arg == '-o' and idx + 1 < len(expanded_args):
out_path = expanded_args[idx + 1]
lang = None
isysroot = None
target = None
arch = None
min_ver_flag = None
opt_flag = None
debug_flags = []
extra_codegen = []
source_path = None
i = 0
skip_next_flags = {
'-o', '-I', '-isystem', '-iquote', '-F', '-iframework', '-include',
'-include-pch', '-MT', '-MF', '-MQ', '-D', '-U', '-x', '-target',
'-arch', '-isysroot', '-ivfsoverlay', '-index-store-path',
'-index-unit-output-path', '--serialize-diagnostics', '-dependency-info',
'-pch-output-dir', '-fmodule-map-file', '-Xclang', '-Xpreprocessor',
'-idirafter', '-iprefix', '-iwithprefix', '-iwithprefixbefore', '-B',
}
while i < len(expanded_args):
a = expanded_args[i]
nxt = expanded_args[i + 1] if i + 1 < len(expanded_args) else None
if a == '-x' and nxt is not None:
lang = nxt
i += 2
continue
if a == '-target' and nxt is not None:
target = nxt
i += 2
continue
if a.startswith('--target='):
target = a.split('=', 1)[1]
i += 1
continue
if a == '-arch' and nxt is not None:
arch = nxt
i += 2
continue
if a == '-isysroot' and nxt is not None:
isysroot = nxt
i += 2
continue
if a.startswith('-miphoneos-version-min=') or a.startswith('-mllvm'):
if a.startswith('-miphoneos-version-min='):
min_ver_flag = a
elif nxt is not None:
i += 2
continue
i += 1
continue
if a in ('-O0', '-O1', '-O2', '-O3', '-Os', '-Oz', '-Ofast'):
opt_flag = a
i += 1
continue
if a.startswith('-g') and not a.startswith('-gmodules') and a != '-g0':
debug_flags.append(a)
i += 1
continue
if a in ('-fPIC', '-fpic', '-fno-common', '-fstrict-aliasing', '-fno-strict-aliasing') or (
a.startswith('-fvisibility=')
or a.startswith('-fstack-protector')
or a.startswith('-ffile-prefix-map=')
or a.startswith('-fdebug-prefix-map=')
or a.startswith('-fembed-bitcode')
):
extra_codegen.append(a)
i += 1
continue
if a in skip_next_flags and nxt is not None:
i += 2
continue
if not a.startswith('-'):
if Path(a).suffix.lower() in SOURCE_EXTENSIONS:
source_path = a
i += 1
return {
'has_c': has_c,
'out_path': out_path,
'top_out_idx': top_out_idx,
'lang': lang,
'isysroot': isysroot,
'target': target,
'arch': arch,
'min_ver_flag': min_ver_flag,
'opt_flag': opt_flag or '-Os',
'debug_flags': debug_flags,
'extra_codegen': extra_codegen,
'source_path': source_path,
}
def should_passthrough(meta, expanded_args, ctl, policy):
if ctl['all_off'] == '1' or ctl['mode'] == 'off':
return True, f"mode={ctl['mode']} all_off={ctl['all_off']}"
if os.environ.get('PLATFORM_NAME') and os.environ.get('PLATFORM_NAME') != 'iphoneos':
return True, f"platform={os.environ.get('PLATFORM_NAME')}"
if os.environ.get('CONFIGURATION') and os.environ.get('CONFIGURATION') != 'Release':
return True, f"config={os.environ.get('CONFIGURATION')}"
if not meta['has_c'] or not meta['out_path']:
return True, 'not single -c object compile'
if any(f in expanded_args for f in ('-E', '-M', '-MM', '-fsyntax-only', '--analyze', '-emit-llvm', '-S')):
return True, 'preprocess/syntax/emit-llvm/asm mode'
if meta['lang'] and (meta['lang'].endswith('-header') or meta['lang'] in ('ir', 'assembler', 'assembler-with-cpp')):
return True, f"lang={meta['lang']}"
out_suf = Path(meta['out_path']).suffix.lower()
if out_suf in ('.pch', '.gch', '.pcm'):
return True, f'precompiled header output {out_suf}'
if meta['arch'] and meta['arch'] != 'arm64':
return True, f"non-arm64 arch {meta['arch']}"
if meta['target'] and 'arm64' not in meta['target']:
return True, f"non-arm64 target {meta['target']}"
if meta['isysroot'] and 'iPhoneSimulator' in meta['isysroot']:
return True, 'simulator sdk'
src = meta['source_path'] or ''
if not src:
return True, 'no C/ObjC/C++ source path'
for ex in policy.get('exempt_path_substrings', []):
if ex in src:
return True, f'exempt path ({ex})'
return False, ''
def build_stage3_flags(meta):
flags = []
if meta['target']:
flags.extend(['-target', meta['target']])
else:
flags.extend(['-arch', meta['arch'] or 'arm64'])
if meta['min_ver_flag']:
flags.append(meta['min_ver_flag'])
if meta['isysroot']:
flags.extend(['-isysroot', meta['isysroot']])
if meta['target'] and meta['min_ver_flag'] and 'ios' not in meta['target']:
flags.append(meta['min_ver_flag'])
flags.append(meta['opt_flag'])
flags.extend(meta['debug_flags'])
flags.extend(meta['extra_codegen'])
flags.extend(['-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c'])
return flags
def infer_obj_cache_dir(out_path):
env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR')
if env_dir:
return Path(env_dir)
for parent in out_path.parents:
if parent.name in ('Intermediates.noindex', 'Build'):
return parent / 'ig-obf-obj-cache'
return out_path.parent / '.ig-obf-obj-cache'
def run_wrapper(argv=None, cxx=False):
raw_args = list(sys.argv[1:] if argv is None else argv)
tool_name = 'clang++' if cxx else 'clang'
real_cc = detect_stock_tool(tool_name)
expanded_args = expand_response_files(raw_args)
ctl = parse_control_token(expanded_args)
policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default'))
policy = {}
if policy_path and Path(policy_path).is_file():
policy = json.loads(Path(policy_path).read_text(encoding='utf-8'))
meta = parse_compile_metadata(raw_args, expanded_args)
passthrough, _ = should_passthrough(meta, expanded_args, ctl, policy)
if passthrough:
if meta.get('out_path'):
stale_audit = Path(str(meta['out_path']) + '.ig-audit.json')
if stale_audit.exists():
try:
stale_audit.unlink()
except OSError:
pass
os.execv(real_cc, [real_cc, *raw_args])
return 0
require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop')
tc = resolve_opt(require_obf=require_obf)
opt_path = tc.get('opt_path')
if not opt_path:
sys.stderr.write(f"[IGCC] WARNING: {tc.get('warning', 'opt unavailable')}; falling back to stock {tool_name}\n")
os.execv(real_cc, [real_cc, *raw_args])
return 0
out_path = Path(meta['out_path'])
out_path.parent.mkdir(parents=True, exist_ok=True)
audit_sidecar = Path(str(out_path) + '.ig-audit.json')
app_repo = discover_active_app_repo([meta.get('source_path') or ''])
eff_policy_path, _eff_policy = resolve_effective_policy(policy_path, app_repo, infer_obj_cache_dir(out_path))
stage3_prefix = build_stage3_flags(meta)
xc_build = tc['xcode']['xcode_build']
sdk_info = detect_sdk_info(meta['isysroot']) if meta['isysroot'] else {'sdk_version': ''}
wrapper_sha = file_sha256(__file__)
policy_sha = file_sha256(eff_policy_path) if eff_policy_path and Path(eff_policy_path).is_file() else 'none'
with tempfile.TemporaryDirectory(prefix='.ig-cc-', dir=out_path.parent) as td:
work = Path(td)
bc_path = work / 'stage1.bc'
obf_bc_path = work / 'stage2.obf.bc'
# Stage 1: stock clang -> bitcode (preserving .pch, .d, .dia generation!)
s1_args = list(raw_args)
if meta['top_out_idx'] is not None:
s1_args[meta['top_out_idx']] = str(bc_path)
else:
s1_args.extend(['-o', str(bc_path)])
s1_args.append('-emit-llvm')
p1 = subprocess.run([real_cc, *s1_args])
if p1.returncode != 0:
return p1.returncode
bc_sha = file_sha256(bc_path)
key_hash = hashlib.sha256(
json.dumps(
{
'kind': 'cc_v1',
'bc_sha256': bc_sha,
'xcode_build': xc_build,
'sdk_version': sdk_info.get('sdk_version', ''),
'opt_sha256': tc['opt_sha256'],
'wrapper_sha256': wrapper_sha,
'policy_sha256': policy_sha,
'mode': ctl['mode'],
'filter': ctl['filter'],
'seed': ctl['seed'],
'stamp': ctl['stamp'],
'stage3': stage3_prefix,
},
sort_keys=True,
).encode('utf-8')
).hexdigest()[:24]
cache_dir = infer_obj_cache_dir(out_path) / key_hash[:2]
cached_obj = cache_dir / f'{key_hash}.o'
cached_audit = cache_dir / f'{key_hash}.audit.json'
if cached_obj.is_file() and cached_audit.is_file():
shutil.copy2(cached_obj, out_path)
shutil.copy2(cached_audit, audit_sidecar)
return 0
# Stage 2: standalone opt
opt_cmd = [
opt_path,
'-passes=ig-obfuscate',
f'--ig-policy={eff_policy_path}',
f"--ig-mode={ctl['mode']}",
f"--ig-pass-filter={ctl['filter']}",
f"--ig-seed={ctl['seed']}",
f"--ig-source-path={meta['source_path'] or ''}",
f'--ig-audit-out={audit_sidecar}',
str(bc_path),
'-o',
str(obf_bc_path),
]
p2 = subprocess.run(opt_cmd)
if p2.returncode != 0:
return p2.returncode
# Stage 3: stock clang pure backend lowering (no duplicate middle-end IR passes)
s3_cmd = [real_cc, *stage3_prefix, str(obf_bc_path), '-o', str(out_path)]
p3 = subprocess.run(s3_cmd)
if p3.returncode != 0:
return p3.returncode
# Atomic cache save (.o + .audit.json sidecar)
try:
cache_dir.mkdir(parents=True, exist_ok=True)
tmp_o = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.o'
tmp_a = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json'
shutil.copy2(out_path, tmp_o)
shutil.copy2(audit_sidecar, tmp_a)
tmp_o.replace(cached_obj)
tmp_a.replace(cached_audit)
except OSError:
pass
return 0
if __name__ == '__main__':
raise SystemExit(run_wrapper(cxx=False))
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Xcode Release arm64 C++/ObjC++ compiler wrapper."""
from pathlib import Path
import sys
SCRIPT_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))
from ig_cc_wrapper import run_wrapper # noqa: E402
if __name__ == '__main__':
raise SystemExit(run_wrapper(cxx=True))
+599
View File
@@ -0,0 +1,599 @@
#!/usr/bin/env python3
"""Xcode Release arm64 Run Script phase for IGArchiveGuard, dynamic framework rebinding, and whole-app audit."""
import hashlib
import json
import os
from pathlib import Path
import plistlib
import shutil
import struct
import subprocess
import sys
import tempfile
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 batch import arm64_slices, iter_macho_files # noqa: E402
from machox import Macho, LC_DYLD_CHAINED_FIXUPS # noqa: E402
from redirect_framework_imports import ( # noqa: E402
DEPENDENCY,
detect_chained_target_mapping,
rewrite as rewrite_chained,
)
from redirect_legacy_imports import ( # noqa: E402
detect_legacy_target_mapping,
rewrite as rewrite_legacy,
)
from route2_archive_common import ( # noqa: E402
EXPECTED_ARCHIVE_EXPORTS,
EXTERNAL_SYMBOLS,
FORBIDDEN_SYMBOLS,
GUARD_BUNDLE_ID,
GUARD_FRAMEWORK_NAME,
SYSTEM_SYMBOLS,
collect_variant_stubs,
file_sha256,
resolve_app_repo,
resolve_defender_dir,
)
from verify_baseline import inspect_binary, scan # noqa: E402
import ig_toolchain_resolver # noqa: E402
APPSTORE_PLIST_KEYS = (
'DTCompiler', 'DTPlatformBuild', 'DTPlatformName', 'DTPlatformVersion',
'DTSDKBuild', 'DTSDKName', 'DTXcode', 'DTXcodeBuild', 'UIDeviceFamily',
)
DYLIB_LOAD_CMDS = {0x0c, 0x18, 0x1f, 0x80000018, 0x8000001f}
def run_cmd(*args, env=None, cwd=None):
return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True)
def macho_load_dylibs(raw):
m = Macho(raw)
libs = []
for cmd, cmdsize, off in m.cmds:
if cmd in DYLIB_LOAD_CMDS and cmdsize >= 24:
name_off, = struct.unpack_from('<I', m.d, off + 8)
if 0 < name_off < cmdsize:
libs.append(m.d[off + name_off:off + cmdsize].split(b'\0', 1)[0].decode(errors='replace'))
return libs
def thin_if_fat(binary_path):
raw = binary_path.read_bytes()
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
with tempfile.NamedTemporaryFile(dir=binary_path.parent, delete=False) as tf:
tmp = Path(tf.name)
try:
subprocess.run(['xcrun', 'lipo', str(binary_path), '-thin', 'arm64', '-output', str(tmp)], check=True)
shutil.copymode(binary_path, tmp)
tmp.replace(binary_path)
return True
finally:
if tmp.exists():
tmp.unlink()
return False
def codesign_framework(fw_dir, preserve_metadata=False):
if os.environ.get('CODE_SIGNING_ALLOWED') == 'NO' or os.environ.get('CODE_SIGNING_REQUIRED') == 'NO':
return 'skipped_disabled'
identity = os.environ.get('EXPANDED_CODE_SIGN_IDENTITY', '').strip()
if not identity:
if os.environ.get('AD_HOC_CODE_SIGNING_ALLOWED') == 'YES':
identity = '-'
else:
return 'skipped_no_identity'
cmd = ['codesign', '--force', '--sign', identity]
if preserve_metadata:
cmd.append('--preserve-metadata=identifier,entitlements')
if identity == '-':
cmd.append('--timestamp=none')
cmd.append(str(fw_dir))
subprocess.run(cmd, check=True)
return f'signed:{identity}'
def build_archive_guard(defender_dir, fw_dir, app_plist_path=None, dsym_folder=None, debug_info_format='', app_repo=None):
if fw_dir.exists():
shutil.rmtree(fw_dir)
fw_dir.mkdir(parents=True)
binary = fw_dir / GUARD_FRAMEWORK_NAME
sources = [
defender_dir / 'dispatch/IGArchiveGuard.c',
defender_dir / 'resolve/IGResolve.c',
defender_dir / 'anti_hook/IGAntiHook.c',
]
dsym_generated = None
obf_mode = os.environ.get('IG_OBF_MODE', 'full')
all_off = os.environ.get('IG_ALL_GUARD_OFF', '0') == '1'
require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1'
opt_path = None
if not all_off and obf_mode != 'off':
try:
tc = ig_toolchain_resolver.resolve_opt(require_obf=require_obf)
opt_path = tc.get('opt_path')
except Exception:
if require_obf:
raise
opt_path = None
real_clang = ig_toolchain_resolver.detect_stock_tool('clang')
sdk_path = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
def_roots = list(dict.fromkeys([str(defender_dir), str(defender_dir.resolve())]))
prefix_flags = []
for root in def_roots:
prefix_flags.extend([f'-ffile-prefix-map={root}=.', f'-fmacro-prefix-map={root}=.', f'-fdebug-prefix-map={root}=.'])
common_cflags = [
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path,
'-O2', '-Wall', '-Wextra', '-Werror', '-fvisibility=hidden',
'-DIG_ARCHIVE_INTERNAL_RESOLVE=1',
*prefix_flags,
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
]
opt_used = False
with tempfile.TemporaryDirectory(prefix='ig-guard-objs-') as tmp_obj_dir:
obj_dir = Path(tmp_obj_dir)
policy_path = obj_dir / 'guard_policy.json'
if opt_path:
guard_policy = {
'schema_version': 3,
'flatten_topology': 'sparse_switch',
'flatten_bogus_blocks': 2,
'flatten_split_linear_blocks': True,
'opaque_const_max_per_fn': 48,
'arithmetic_rounds': 1,
'arithmetic_max_per_fn': 96,
'string_encrypt_stack_max_len': 128,
'indirect_call_dual_table': True,
'exempt_path_substrings': [],
'exempt_function_prefixes': [
'__ig_', 'ig_archive_warmup', 'ig_anti_hook_warmup',
'rd_a0', 'rd_f', 'rd_a1', 'rd_a2', 'rd_a3', 'rd_a4',
'rd_u00', 'rd_o', 'rdo', 'rd_r', 'rdr', 'rd_w0', 'rd_w',
'rd_c0', 'rd_c', 'rd_p00', 'rd_p0', 'rd_e', 'rd_k',
'rd_l00', 'rd_s0', 'rd_s', 'llvm.',
],
'scrub_path_substrings': list(dict.fromkeys([
*def_roots,
'/tmp/ig-',
f'{Path.home()}/',
*([str(app_repo)] if app_repo else []),
])),
'string_encrypt_targets': [
{'id': 'rdcoreio_guard_str', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_str', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_str', 'path_contains': 'IGAntiHook.c'},
],
'indirect_call_same_image_prefixes': [
'ig_', 'rd_io_', 'checked', 'prepare', 'validate',
'initialize', 'locate_bindings', 'check_bindings',
],
'indirect_call_targets': [
{'id': 'rdcoreio_guard_icall', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_icall', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_icall', 'path_contains': 'IGAntiHook.c'},
],
'flatten_targets': [
{'id': 'rdcoreio_guard_flat', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_flat', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_flat', 'path_contains': 'IGAntiHook.c'},
],
'opaque_const_targets': [
{'id': 'rdcoreio_guard_const', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_const', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_const', 'path_contains': 'IGAntiHook.c'},
],
'arithmetic_targets': [
{'id': 'rdcoreio_guard_arith', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_arith', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_arith', 'path_contains': 'IGAntiHook.c'},
],
'indirect_branch_targets': [
{'id': 'rdcoreio_guard_ibr', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_ibr', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_ibr', 'path_contains': 'IGAntiHook.c'},
],
'string_encrypt_stack_targets': [
{'id': 'rdcoreio_guard_sstr', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_sstr', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_sstr', 'path_contains': 'IGAntiHook.c'},
],
'anti_hooking_targets': [
{'id': 'rdcoreio_guard_antihook', 'path_contains': 'IGArchiveGuard.c'},
{'id': 'rdcoreio_resolve_antihook', 'path_contains': 'IGResolve.c'},
{'id': 'rdcoreio_antihook_antihook', 'path_contains': 'IGAntiHook.c'},
],
}
policy_path.write_text(json.dumps(guard_policy, indent=2) + '\n', encoding='utf-8')
objects = []
seed = os.environ.get('IG_RELEASE_SEED', 'rdcoreio_seed_v1')
for src in sources:
obj = obj_dir / f'{src.stem}.o'
if opt_path:
bc_path = obj_dir / f'{src.stem}.bc'
obf_bc = obj_dir / f'{src.stem}.obf.bc'
audit_p = obj_dir / f'{src.stem}.audit.json'
subprocess.run([real_clang, '-g', *common_cflags, '-emit-llvm', '-c', str(src), '-o', str(bc_path)], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
f'--ig-mode={obf_mode}',
'--ig-pass-filter=all',
f'--ig-seed={seed}',
f'--ig-source-path={src}',
f'--ig-audit-out={audit_p}',
str(bc_path), '-o', str(obf_bc),
], check=True)
subprocess.run([
real_clang, '-g', '-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path,
'-O2', '-fvisibility=hidden', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj),
], check=True)
opt_used = True
else:
subprocess.run([real_clang, '-g', *common_cflags, '-c', str(src), '-o', str(obj)], check=True)
objects.append(str(obj))
subprocess.run([
real_clang,
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path, '-dynamiclib',
*objects,
'-Wl,-install_name,' + DEPENDENCY,
'-o', str(binary),
], check=True)
if dsym_folder and debug_info_format == 'dwarf-with-dsym':
dsym_dir = Path(dsym_folder)
dsym_dir.mkdir(parents=True, exist_ok=True)
dsym_out = dsym_dir / f'{GUARD_FRAMEWORK_NAME}.framework.dSYM'
if dsym_out.exists():
shutil.rmtree(dsym_out)
subprocess.run(['xcrun', 'dsymutil', str(binary), '-o', str(dsym_out)], check=True)
dsym_generated = str(dsym_out)
subprocess.run(['xcrun', 'strip', '-x', str(binary)], check=True)
plist = {
'CFBundleExecutable': GUARD_FRAMEWORK_NAME,
'CFBundleIdentifier': GUARD_BUNDLE_ID,
'CFBundleInfoDictionaryVersion': '6.0',
'CFBundleName': GUARD_FRAMEWORK_NAME,
'CFBundlePackageType': 'FMWK',
'CFBundleShortVersionString': '1.0',
'CFBundleSupportedPlatforms': ['iPhoneOS'],
'CFBundleVersion': '1',
'MinimumOSVersion': '15.0',
}
if app_plist_path and Path(app_plist_path).is_file():
app_plist = plistlib.loads(Path(app_plist_path).read_bytes())
for key in APPSTORE_PLIST_KEYS:
if key in app_plist:
plist[key] = app_plist[key]
if 'MinimumOSVersion' in app_plist:
plist['MinimumOSVersion'] = app_plist['MinimumOSVersion']
with (fw_dir / 'Info.plist').open('wb') as stream:
plistlib.dump(plist, stream)
exports_out = run_cmd('xcrun', 'nm', '-gU', binary)
exported = {line.split()[-1] for line in exports_out.splitlines() if line.split()}
missing = EXPECTED_ARCHIVE_EXPORTS - exported
if missing:
raise ValueError(f'{GUARD_FRAMEWORK_NAME} missing expected exports: {sorted(missing)}')
leaked_ig = sorted(s for s in exported if s.startswith('_ig_'))
if leaked_ig:
raise ValueError(f'{GUARD_FRAMEWORK_NAME} leaked _ig_* exports: {leaked_ig}')
undef_out = run_cmd('xcrun', 'nm', '-u', binary)
undef = {line.split()[-1] for line in undef_out.splitlines() if line.split()}
forbidden_undef = undef & FORBIDDEN_SYMBOLS
if forbidden_undef:
raise ValueError(f'{GUARD_FRAMEWORK_NAME} has forbidden undefined imports: {sorted(forbidden_undef)}')
info, sites = inspect_binary(binary)
if sites:
raise ValueError(f'{GUARD_FRAMEWORK_NAME} has direct target calls: {sites}')
sign_status = codesign_framework(fw_dir, preserve_metadata=False)
return dict(
sha256=file_sha256(binary),
exported_count=len(exported),
obfuscated=opt_used,
dsym=dsym_generated,
sign_status=sign_status,
inspect=info,
)
def process_framework(fw_dir, orig_backup_dir=None):
name = fw_dir.stem
binary = fw_dir / name
if not binary.is_file():
raise FileNotFoundError(binary)
raw_initial = binary.read_bytes()
slices_initial = arm64_slices(raw_initial)
initial_load_dylibs = macho_load_dylibs(raw_initial) if (len(slices_initial) == 1 and slices_initial[0][0] == 0) else []
if DEPENDENCY not in initial_load_dylibs and orig_backup_dir is not None:
orig_backup_dir.mkdir(parents=True, exist_ok=True)
backup_path = orig_backup_dir / f'{name}.orig'
shutil.copy2(binary, backup_path)
if len(slices_initial) == 1 and slices_initial[0][0] == 0:
if DEPENDENCY in initial_load_dylibs:
info, sites = inspect_binary(binary)
variants = collect_variant_stubs(binary)
if not sites and not variants:
return dict(
framework=name,
mode='already_guarded',
modified=False,
thinned=False,
before_total=0,
after_total=0,
symbols_redirected=0,
sign_status='preserved',
)
thinned = thin_if_fat(binary)
raw = binary.read_bytes()
slices = arm64_slices(raw)
if len(slices) != 1 or slices[0][0] != 0:
raise ValueError(f'{name}: expected single thin arm64 Mach-O')
m = Macho(raw)
has_chained = any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds)
has_dyld_info = any(c in (0x22, 0x80000022) for c, _, _ in m.cmds)
include_stdio_rw = (name == 'SSZipArchive')
if has_chained:
mapping = detect_chained_target_mapping(raw, include_stdio_rw=include_stdio_rw)
mode = 'chained'
elif has_dyld_info:
mapping = detect_legacy_target_mapping(raw)
mode = 'legacy_dyld_info'
else:
mapping = {}
mode = 'none'
before_info, _ = inspect_binary(binary)
before_total = sum(s['total'] for s in before_info['slices'])
if mapping:
in_sha = hashlib.sha256(raw).hexdigest()
if mode == 'chained':
out_bytes, report = rewrite_chained(raw, in_sha, mapping)
else:
out_bytes, report = rewrite_legacy(raw, in_sha, mapping)
binary.write_bytes(out_bytes)
after_info, after_sites = inspect_binary(binary)
if after_sites:
raise ValueError(f'{name}: remaining direct calls after rewrite: {after_sites}')
variants = collect_variant_stubs(binary)
if variants:
raise ValueError(f'{name}: remaining Darwin-variant stubs after rewrite: {variants}')
codesig = fw_dir / '_CodeSignature'
if codesig.exists():
shutil.rmtree(codesig)
sign_status = codesign_framework(fw_dir, preserve_metadata=True)
return dict(
framework=name,
mode=mode,
modified=True,
thinned=thinned,
before_total=before_total,
after_total=sum(s['total'] for s in after_info['slices']),
symbols_redirected=len(mapping),
mapping=mapping,
output_sha256=report['output_sha256'],
sign_status=sign_status,
)
if before_total > 0:
raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}')
sign_status = 'preserved'
if thinned:
codesig = fw_dir / '_CodeSignature'
if codesig.exists():
shutil.rmtree(codesig)
sign_status = codesign_framework(fw_dir, preserve_metadata=True)
return dict(
framework=name,
mode='clean_no_change' if not thinned else 'thinned_clean',
modified=thinned,
thinned=thinned,
before_total=0,
after_total=0,
symbols_redirected=0,
sign_status=sign_status,
)
def run_phase(app_dir, main_bin, audit_dir, app_repo, defender_dir, dsym_folder=None, debug_info_format=''):
frameworks_dir = app_dir / 'Frameworks'
frameworks_dir.mkdir(parents=True, exist_ok=True)
guard_report = build_archive_guard(
defender_dir,
frameworks_dir / f'{GUARD_FRAMEWORK_NAME}.framework',
app_plist_path=app_dir / 'Info.plist',
dsym_folder=dsym_folder,
debug_info_format=debug_info_format,
app_repo=app_repo,
)
orig_backup_dir = audit_dir / 'orig_frameworks'
fw_reports = []
for fw_dir in sorted(frameworks_dir.glob('*.framework')):
if fw_dir.name == f'{GUARD_FRAMEWORK_NAME}.framework':
continue
fw_reports.append(process_framework(fw_dir, orig_backup_dir=orig_backup_dir))
# Incremental builds may already have a stale RDKnownImages.plist before Generate Image Whitelist runs.
whitelist_plist = app_dir / 'RDKnownImages.plist'
if whitelist_plist.exists():
wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
if wl_script.is_file():
env = dict(os.environ)
env['TARGET_BUILD_DIR'] = str(app_dir.parent)
env['WRAPPER_NAME'] = app_dir.name
env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent)))
subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True)
audit_dir.mkdir(parents=True, exist_ok=True)
(audit_dir / 'route2-frameworks.json').write_text(json.dumps(fw_reports, indent=2) + '\n')
binaries, callsite_total = scan(app_dir, audit_dir, 'route2')
combined_counts = {}
for info in binaries.values():
for sl in info['slices']:
for sym, cnt in sl['counts'].items():
combined_counts[sym] = combined_counts.get(sym, 0) + cnt
external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS)
system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS)
if external_call_total != 0 or system_call_total != 0 or callsite_total != 0:
raise RuntimeError(
f'[IGRoute2] Non-zero residual callsites across {app_dir.name}: '
f'external={external_call_total}, system={system_call_total}, total={callsite_total}, counts={combined_counts}'
)
variant_stubs = []
for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))):
found = collect_variant_stubs(mpath)
if found:
variant_stubs.append((str(mpath.relative_to(app_dir)), found))
if variant_stubs:
raise RuntimeError(f'[IGRoute2] Found Darwin-variant stubs in {app_dir.name}: {variant_stubs}')
main_undef_out = run_cmd('xcrun', 'nm', '-u', main_bin)
main_undef = {line.split()[-1] for line in main_undef_out.splitlines() if line.split()}
forbidden_main_undef = sorted(main_undef & FORBIDDEN_SYMBOLS)
forbidden_variant_undef = sorted(u for u in main_undef if any(u.startswith(f + '$') for f in FORBIDDEN_SYMBOLS))
if forbidden_variant_undef:
raise RuntimeError(
f'[IGRoute2] Main binary {main_bin.name} still has Darwin-variant undefined imports: '
f'{forbidden_variant_undef}'
)
summary = dict(
app=app_dir.name,
binaries=len(binaries),
external_call_total=external_call_total,
system_call_total=system_call_total,
direct_calls=combined_counts,
main_binary_forbidden_undef=forbidden_main_undef,
ig_archive_guard=guard_report,
frameworks_total=len(fw_reports),
frameworks_rewritten=sum(1 for r in fw_reports if r['symbols_redirected'] > 0),
frameworks_already_guarded=sum(1 for r in fw_reports if r['mode'] == 'already_guarded'),
frameworks_thinned=sum(1 for r in fw_reports if r['thinned']),
)
(audit_dir / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
return summary
def restore_route2_off(app_dir, main_bin, audit_dir, app_repo, dsym_folder=None):
"""Remove RDCoreIO.framework (and legacy IGArchiveGuard.framework) & restore pre-Route2 backups."""
frameworks_dir = app_dir / 'Frameworks'
removed_guard = False
for fw_name in (GUARD_FRAMEWORK_NAME, 'IGArchiveGuard'):
guard_fw = frameworks_dir / f'{fw_name}.framework'
if guard_fw.exists():
shutil.rmtree(guard_fw)
removed_guard = True
if dsym_folder:
guard_dsym = Path(dsym_folder) / f'{fw_name}.framework.dSYM'
if guard_dsym.exists():
shutil.rmtree(guard_dsym)
restored = []
orig_backup_dir = audit_dir / 'orig_frameworks'
if frameworks_dir.is_dir() and orig_backup_dir.is_dir():
for fw_dir in sorted(frameworks_dir.glob('*.framework')):
name = fw_dir.stem
binary = fw_dir / name
backup = orig_backup_dir / f'{name}.orig'
if binary.is_file() and backup.is_file():
if DEPENDENCY in macho_load_dylibs(binary.read_bytes()):
shutil.copy2(backup, binary)
codesig = fw_dir / '_CodeSignature'
if codesig.exists():
shutil.rmtree(codesig)
codesign_framework(fw_dir, preserve_metadata=True)
restored.append(name)
whitelist_plist = app_dir / 'RDKnownImages.plist'
if (removed_guard or restored) and whitelist_plist.exists():
wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
if wl_script.is_file():
env = dict(os.environ)
env['TARGET_BUILD_DIR'] = str(app_dir.parent)
env['WRAPPER_NAME'] = app_dir.name
env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent)))
subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True)
return removed_guard, restored
def main():
off_reason = None
if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1':
off_reason = 'IG_DISABLE_ROUTE2_ARCHIVE=1'
elif os.environ.get('IG_ALL_GUARD_OFF') == '1':
off_reason = 'IG_ALL_GUARD_OFF=1'
elif os.environ.get('IG_ROUTE2_MODE') == 'off':
off_reason = 'IG_ROUTE2_MODE=off'
config = os.environ.get('CONFIGURATION', '')
platform = os.environ.get('PLATFORM_NAME', '')
if config != 'Release' or platform != 'iphoneos':
print(f'[IGRoute2] frameworks phase skipped: CONFIGURATION={config} PLATFORM_NAME={platform}')
return 0
target_build_dir = Path(os.environ['TARGET_BUILD_DIR'])
wrapper_name = os.environ['WRAPPER_NAME']
app_dir = target_build_dir / wrapper_name
exec_rel = os.environ.get('EXECUTABLE_PATH') or f'{wrapper_name}/{Path(wrapper_name).stem}'
main_bin = target_build_dir / exec_rel
target_temp_dir = Path(os.environ.get('TARGET_TEMP_DIR') or str(target_build_dir))
audit_dir = target_temp_dir / 'ig-route2-audit'
app_repo = resolve_app_repo(TOOLCHAIN_ROOT)
if off_reason:
removed_guard, restored = restore_route2_off(
app_dir, main_bin, audit_dir, app_repo, dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH')
)
print(
f'[IGRoute2] frameworks phase off ({off_reason}): '
f'removed_guard={removed_guard}, restored={len(restored)}'
)
return 0
defender_dir = resolve_defender_dir(TOOLCHAIN_ROOT, app_repo)
summary = run_phase(
app_dir=app_dir,
main_bin=main_bin,
audit_dir=audit_dir,
app_repo=app_repo,
defender_dir=defender_dir,
dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH'),
debug_info_format=os.environ.get('DEBUG_INFORMATION_FORMAT', ''),
)
print(
f'[IGRoute2] frameworks audit OK for {app_dir.name}: '
f'binaries={summary["binaries"]}, rewritten={summary["frameworks_rewritten"]}, '
f'already_guarded={summary["frameworks_already_guarded"]}, external=0, system=0'
)
return 0
if __name__ == '__main__':
raise SystemExit(main())
+1452
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,83 @@
"""Shared constants and Mach-O helpers for Route 2 Xcode Archive integration."""
import hashlib
import os
from pathlib import Path
import struct
from batch import arm64_slices, Slice
EXTERNAL_SYMBOLS = {'_fopen', '_dlopen', '_dlsym'}
SYSTEM_SYMBOLS = {'_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid'}
FORBIDDEN_SYMBOLS = EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS
EXPECTED_DISPATCH_SYMBOLS = {
'_IG_dispatch_fopen', '_IG_dispatch_dlopen', '_IG_dispatch_dlsym',
'_IG_dispatch_write', '_IG_dispatch_read', '_IG_dispatch_open',
'_IG_dispatch_close', '_IG_dispatch_exit', '_IG_dispatch_fork',
'_IG_dispatch_unlink', '_IG_dispatch_getpid',
}
GUARD_FRAMEWORK_NAME = 'RDCoreIO'
GUARD_BUNDLE_ID = 'cn.touchv.readoor.coreio'
EXPECTED_ARCHIVE_EXPORTS = {
'_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4',
'_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w',
'_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k',
'_rd_l00', '_rd_s0', '_rd_s',
'_rd_io_cfg', '_rd_io_chk', '_rd_io_ev',
}
def file_sha256(path):
h = hashlib.sha256()
with Path(path).open('rb') as stream:
for chunk in iter(lambda: stream.read(1 << 20), b''):
h.update(chunk)
return h.hexdigest()
def resolve_app_repo(toolchain_root):
"""Resolve active readoor repository root, preferring SRCROOT for isolated build snapshots."""
candidates = []
srcroot = os.environ.get('SRCROOT')
if srcroot:
candidates.append(Path(srcroot).resolve())
candidates.extend([
(toolchain_root / 'readoor-test').resolve(),
toolchain_root.parent / 'readoor-test',
])
for candidate in candidates:
if (candidate / 'readoor.xcodeproj').exists():
return candidate
raise FileNotFoundError(f'Unable to resolve readoor-test repository root from {toolchain_root}')
def resolve_defender_dir(toolchain_root, app_repo):
in_toolchain = (toolchain_root / 'defender').resolve()
if (in_toolchain / 'dispatch/IGArchiveGuard.c').is_file():
return in_toolchain
in_repo = app_repo / 'readoor/3.0/Base/Security/IGDefender'
if (in_repo / 'dispatch/IGArchiveGuard.c').is_file():
return in_repo
raise FileNotFoundError(f'Unable to resolve IGDefender directory under {toolchain_root} or {app_repo}')
def collect_variant_stubs(binary_path):
"""Return any Darwin-suffixed stub imports (e.g. _fopen$DARWIN_EXTSN) for forbidden targets."""
data = Path(binary_path).read_bytes()
found = set()
for off, _ in arm64_slices(data):
sl = Slice(data, off)
if not (sl.stubs and sl.symtab and sl.dysym):
continue
symoff, _, stroff, _ = sl.symtab
indoff = sl.dysym[12]
_, ssize, _, sr1, sr2 = sl.stubs
for idx_pos in range(ssize // sr2):
symi, = struct.unpack_from('<I', data, off + indoff + (sr1 + idx_pos) * 4)
strx, = struct.unpack_from('<I', data, off + symoff + symi * 16)
sname = data[off + stroff + strx:data.index(b'\0', off + stroff + strx)].decode(errors='replace')
if sname == '_fopen$DARWIN_EXTSN' or any(sname.startswith(f + '$') for f in FORBIDDEN_SYMBOLS):
found.add(sname)
return sorted(found)