#!/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(' 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())