- 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
600 lines
25 KiB
Python
Executable File
600 lines
25 KiB
Python
Executable File
#!/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())
|