#!/usr/bin/env python3 """Execute Milestone 3 L1+L2+L3 dual-target regression, cold/warm cache timing, and iPhone 16 Plus over-install test.""" import argparse import base64 import datetime import hashlib import json import os from pathlib import Path import plistlib import shutil import subprocess import sys import tempfile import time from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_private_key ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard') APP_REPO = ROOT / 'readoor-test' TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' TOOLS_MACHO = ROOT / 'tools' / 'macho_guard' TOOLS_OBF = ROOT / 'tools' / 'llvm_obf' sys.path.insert(0, str(TOOLS_CRASH)) sys.path.insert(0, str(TOOLS_MACHO)) sys.path.insert(0, str(TOOLS_OBF)) import ig_toolchain_resolver # noqa: E402 import restore_crash_report # noqa: E402 from verify_baseline import scan # noqa: E402 WORK_ROOT = Path('/tmp/ig-m3-work') SNAPSHOT_SRC = WORK_ROOT / 'src' DD_PATH = WORK_ROOT / 'dd' ARCHIVE_DIR = WORK_ROOT / 'archives' STAGE_DIR = WORK_ROOT / 'stage' CACHE_ROOT = Path('/tmp/ig-m3-cache') RESULTS_DIR = ROOT / 'test-results' / '20261119-m3-production-regression' DEFAULT_DEVICE = '00008140-000960811493001C' DEFAULT_PROFILE = Path('/Users/shenlei/Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision') DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' BUNDLE_READOOR31 = 'cn.touchv.iosguard.m3eval' BUNDLE_OTHERPAY = 'cn.touchv.iosguard.m3otherpay' M2_MAIN_BYTES = 24_732_128 EXPECTED_NSCODING_CLASSES = ( 'STSPayOrderInfoObject', 'RBCorePenLineData', 'STSPaintModel', 'STSPaintLayerModel', 'STSPaintPageLayerModel', 'STSPaintStack', 'RDPlayerCacheMedia', 'RDPlayerCacheMediaConfiguration', ) def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def check_disk_budget(min_gb: float = 5.0) -> float: free_gb = shutil.disk_usage('/Users/shenlei').free / (1024 ** 3) if free_gb < min_gb: raise RuntimeError(f'Free disk space {free_gb:.2f} GB dropped below {min_gb:.1f} GB') return round(free_gb, 2) def cleanup_build_artifacts(): for path in (DD_PATH, ARCHIVE_DIR, STAGE_DIR): if path.exists(): shutil.rmtree(path) def text_section_bytes(bin_path: Path) -> int: out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines() return int(out[-1].split()[0]) def uuids_of(path: Path) -> set: 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 sync_toolchain_and_integrate(): dst_root = APP_REPO / 'iOSGuardIntegration' / 'toolchain' rels = [ 'config/ig_llvm_policy.json', 'config/ig_diag_events.json', 'config/xcode_llvm_map.json', 'config/toolchain_manifest.json', 'tools/xcode_archive/route2_archive_common.py', 'tools/xcode_archive/ig_cc_wrapper.py', 'tools/xcode_archive/ig_cxx_wrapper.py', 'tools/xcode_archive/ig_ld_wrapper.py', 'tools/xcode_archive/ig_guard_frameworks_phase.py', 'tools/xcode_archive/audit_exported_ipa.py', 'tools/macho_guard/verify_baseline.py', 'tools/macho_guard/redirect_framework_imports.py', 'tools/macho_guard/redirect_legacy_imports.py', 'tools/macho_guard/machox.py', 'tools/macho_guard/batch.py', 'defender/dispatch/IGArchiveGuard.h', 'defender/dispatch/IGArchiveGuard.c', 'defender/resolve/IGResolve.h', 'defender/resolve/IGResolve.c', 'tools/llvm_obf/ig_toolchain_resolver.py', 'tools/llvm_obf/build_igopt_local.py', 'tools/llvm_obf/verify_macho_star_cfg.py', 'tools/llvm_obf/verify_macho_indirect_branches.py', 'tools/llvm_obf/verify_macho_indirect_calls.py', 'tools/crash_restore/restore_crash_report.py', ] for rel in rels: src = ROOT / rel dst = dst_root / rel if src.is_file(): dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) passes_src = ROOT / 'llvm_passes' passes_dst = dst_root / 'llvm_passes' if passes_src.is_dir(): if passes_dst.exists(): shutil.rmtree(passes_dst) shutil.copytree( passes_src, passes_dst, ignore=shutil.ignore_patterns('__pycache__', '.DS_Store', 'build', '*.pyc'), ) subprocess.run(['ruby', str(APP_REPO / 'scripts/integrate_route2_archive.rb')], cwd=APP_REPO, check=True) def create_clean_snapshot_and_apply_l1() -> dict: check_disk_budget() if SNAPSHOT_SRC.exists(): shutil.rmtree(SNAPSHOT_SRC) SNAPSHOT_SRC.parent.mkdir(parents=True, exist_ok=True) print('\n=== [L1 Snapshot] rsync readoor-test -> /tmp/ig-m3-work/src ===', flush=True) subprocess.run([ 'rsync', '-a', '--delete', '--exclude', '/.git', '--exclude', '/build', '--exclude', '/DerivedData', '--exclude', '/build_output', '--exclude', '/obfuscation_maps', f'{APP_REPO}/', f'{SNAPSHOT_SRC}/', ], check=True) pre_check = subprocess.run( ['bash', str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')], cwd=SNAPSHOT_SRC, capture_output=True, text=True, ) if pre_check.returncode != 0: raise RuntimeError(f'Pre-L1 obfuscation_self_check failed:\n{pre_check.stdout}\n{pre_check.stderr}') ts = '20261119_m3' salt = 'm3_prod_seed_20261119' l1_res = subprocess.run([ 'python3', str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/obfuscate_symbols.py'), '--archive-mode', '--target-name', 'readoor31', '--timestamp', ts, '--salt', salt, ], cwd=SNAPSHOT_SRC, capture_output=True, text=True) l1_log = RESULTS_DIR / 'l1_apply.log' l1_log.write_text(l1_res.stdout + '\n' + l1_res.stderr, encoding='utf-8') if l1_res.returncode != 0: raise RuntimeError(f'obfuscate_symbols.py failed (rc={l1_res.returncode}):\n{l1_res.stdout[-4000:]}\n{l1_res.stderr[-2000:]}') sym_map_path = SNAPSHOT_SRC / f'obfuscation_maps/symbol_map_readoor31_{ts}.json' meth_map_path = SNAPSHOT_SRC / f'obfuscation_maps/method_map_readoor31_{ts}.json' assert sym_map_path.is_file(), f'Missing {sym_map_path}' assert meth_map_path.is_file(), f'Missing {meth_map_path}' sym_payload = json.loads(sym_map_path.read_text(encoding='utf-8')) meth_payload = json.loads(meth_map_path.read_text(encoding='utf-8')) assert sym_payload.get('schema_version') == 2, sym_payload.get('schema_version') assert meth_payload.get('schema_version') == 2, meth_payload.get('schema_version') sym_mappings = sym_payload.get('mappings') or {} meth_mappings = meth_payload.get('mappings') or {} for cls_name in EXPECTED_NSCODING_CLASSES: assert cls_name not in sym_mappings, f'NSCoding class {cls_name} leaked into obfuscation map' key_obf = {} for expected in ('RDLoginView', 'RDSDAuthV32Signer', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', 'RDInjectionDetector'): raw_entry = sym_mappings.get(expected) obf_val = raw_entry.get('obfuscated') if isinstance(raw_entry, dict) else raw_entry assert isinstance(obf_val, str) and obf_val and obf_val != expected, f'{expected} not obfuscated cleanly in L1 map: {raw_entry}' key_obf[expected] = obf_val post_check = subprocess.run( ['bash', str(SNAPSHOT_SRC / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')], cwd=SNAPSHOT_SRC, capture_output=True, text=True, ) assert post_check.returncode != 0, 'obfuscation_self_check.sh should fail (non-zero) after L1 apply' return { 'snapshot_src': str(SNAPSHOT_SRC), 'symbol_map_path': str(sym_map_path), 'method_map_path': str(meth_map_path), 'type_mappings_count': len(sym_mappings), 'method_mappings_count': len(meth_mappings), 'nscoding_exempt_verified': list(EXPECTED_NSCODING_CLASSES), 'sample_type_mappings': key_obf, 'pre_self_check_rc': pre_check.returncode, 'post_self_check_rc': post_check.returncode, } def target_interm_dir(scheme: str) -> Path: return DD_PATH / f'Build/Intermediates.noindex/ArchiveIntermediates/{scheme}/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/{scheme}.build' def run_archive( repo_dir: Path, scheme: str, step_tag: str, extra_settings: list, log_path: Path, clean_first: bool = True, use_cache: bool = True, require_llvm_obf: bool = True, ) -> float: free_gb = check_disk_budget() print(f'\n=== [{step_tag}] repo={repo_dir.name} scheme={scheme} disk_free={free_gb}GB ===', flush=True) archive_path = ARCHIVE_DIR / f'{scheme}.xcarchive' if archive_path.exists(): shutil.rmtree(archive_path) archive_path.parent.mkdir(parents=True, exist_ok=True) DD_PATH.mkdir(parents=True, exist_ok=True) env = os.environ.copy() if require_llvm_obf: env['IG_REQUIRE_LLVM_OBF'] = '1' else: env.pop('IG_REQUIRE_LLVM_OBF', None) if use_cache: obj_cache = CACHE_ROOT / 'obj_cache' sdk_cache = CACHE_ROOT / 'sdk_cache' obj_cache.mkdir(parents=True, exist_ok=True) sdk_cache.mkdir(parents=True, exist_ok=True) env['IG_OBF_OBJ_CACHE_DIR'] = str(obj_cache) env['IG_SDK_CACHE_DIR'] = str(sdk_cache) else: env.pop('IG_OBF_OBJ_CACHE_DIR', None) env.pop('IG_SDK_CACHE_DIR', None) base_cmd = [ 'xcodebuild', '-workspace', str(repo_dir / 'readoor.xcworkspace'), '-scheme', scheme, '-configuration', 'Release', '-destination', 'generic/platform=iOS', '-derivedDataPath', str(DD_PATH), 'CODE_SIGNING_ALLOWED=NO', *extra_settings, ] if clean_first: subprocess.run([*base_cmd, 'clean'], cwd=repo_dir, env=env, capture_output=True, text=True) cmd = [*base_cmd, '-archivePath', str(archive_path), 'archive'] t0 = time.monotonic() res = subprocess.run(cmd, cwd=repo_dir, env=env, capture_output=True, text=True) elapsed = round(time.monotonic() - t0, 2) text_log = res.stdout + '\n' + res.stderr ig_lines = [l for l in text_log.splitlines() if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l] log_path.write_text('\n'.join(ig_lines[-140:] + ['', '--- tail ---'] + text_log.splitlines()[-100:]) + '\n', encoding='utf-8') if res.returncode != 0: raise RuntimeError(f'[{step_tag}] xcodebuild failed (rc={res.returncode}):\n' + '\n'.join(text_log.splitlines()[-120:])) return elapsed def inspect_app_route2(app_dir: Path, step_tag: str) -> dict: out_dir = RESULTS_DIR / step_tag / 'route2' out_dir.mkdir(parents=True, exist_ok=True) binaries, total = scan(app_dir, out_dir, step_tag) counts = {} for info in binaries.values(): for sl in info['slices']: for k, v in sl['counts'].items(): counts[k] = counts.get(k, 0) + v return {'binaries': len(binaries), 'direct_call_total': total, 'direct_call_counts': counts} def verify_required_targets(audit_path: Path, policy: dict, expect_l1_translation: bool = True) -> dict: obf_audit = json.loads(audit_path.read_text(encoding='utf-8')) req_by_id = {r['id']: r for r in (obf_audit.get('required_targets') or [])} policy_reqs = policy.get('required_targets') or [] assert len(req_by_id) == len(policy_reqs), f'Expected {len(policy_reqs)} required_targets, got {list(req_by_id.keys())}' for req in policy_reqs: tid = req['id'] got = req_by_id.get(tid) assert got is not None, f'Missing required_target audit entry: {tid}' assert got['flattened_hits'] >= int(req.get('min_flattened', 0)), f'{tid} flattened_hits failed: {got} vs {req}' assert got['strings_encrypted_hits'] >= int(req.get('min_strings_encrypted', 0)), f'{tid} strings_encrypted_hits failed: {got} vs {req}' if expect_l1_translation: assert obf_audit.get('l1_translation_active') is True, f'Expected l1_translation_active=True in {audit_path}' return obf_audit def otool_cstring_bytes(obj_path: Path) -> bytes: out = subprocess.check_output(['xcrun', 'otool', '-s', '__TEXT', '__cstring', str(obj_path)], text=True, errors='replace') chunks = [] for line in out.splitlines(): parts = line.split('\t') if len(parts) == 2 and parts[0].strip().endswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')): hex_bytes = parts[1].strip().split() try: chunks.append(bytes(int(h, 16) for h in hex_bytes)) except ValueError: pass return b''.join(chunks) def audit_m3_static_clues(main_bin: Path, obj_base: Path, l1_repo: Path) -> dict: fwd_map, _ = ig_toolchain_resolver.load_l1_forward_symbol_map(l1_repo) logdiag_sym = fwd_map.get('logDiag', 'logDiag') logdiag_mangled_sub = f'{len(logdiag_sym)}{logdiag_sym}' names = [ 'RDSDKeyBox', 'RDSDPrivateKeyManager', 'RDSDAuthV32Signer', 'RDJWTPayloadParser', 'RDBaseNetworkService', 'RDSecurityGuard', 'RDInjectionDetector', 'RDIAPPurchaseManager', 'RDIAPHandler', 'STSIAPVerifyHandler', 'STSIAPVerifyTask', 'STSIAPKeyChainHandler', ] swift_macho_dir = obj_base / 'ig-swift-macho' objs = {} for n in names: cand_sw = sorted(swift_macho_dir.glob(f'*_{n}.o')) if swift_macho_dir.is_dir() else [] cand_plain = obj_base / f'{n}.o' objs[n] = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None) forbidden_clues = [ b'readoor_sd_v32', b'KSDPrivateKeyPEM', b'encrypted_private_key', b'rd_net_cfg_v1', b'rd_glyph_lut_v2', b'cn.touchv.payment.models.keychain', b'[SDAuthV32]', b'[IAP]', b'[Security]', b'Exception: No product matched', b'7ARrksiF7AoWXXBlmxfz9suSmTka7A', ] host_path_clue = b'/Users/shenlei/Work/ReadBook' obj_hits = {} for name, p in objs.items(): if not p or not p.is_file(): obj_hits[name] = {'missing': True} continue raw = p.read_bytes() cstring_raw = otool_cstring_bytes(p) hits = {} for pat in forbidden_clues: cnt = raw.count(pat) if cnt > 0: hits[pat.decode('ascii', errors='replace')] = cnt hp_cnt = cstring_raw.count(host_path_clue) if hp_cnt > 0: hits['__cstring_host_path'] = hp_cnt obj_hits[name] = hits main_raw = main_bin.read_bytes() main_forbidden = {p.decode('ascii', errors='replace'): main_raw.count(p) for p in forbidden_clues} logdiag_swift_objs = [ 'RDSDPrivateKeyManager', 'RDSDAuthV32Signer', 'RDSecurityGuard', 'RDInjectionDetector', 'RDIAPPurchaseManager', 'RDIAPHandler', ] logdiag_linked = [] for n in logdiag_swift_objs: p = objs.get(n) if p and p.is_file(): nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(p)], text=True, errors='replace') matched = logdiag_mangled_sub in nm_u or '7logDiag' in nm_u if not matched: swift_undef = [ tok for ln in nm_u.splitlines() if ln.strip() for tok in (ln.split()[-1],) if tok.startswith(('_$s', '$s')) ] if swift_undef: dm_res = subprocess.run( ['xcrun', 'swift-demangle', '--compact'], input='\n'.join(swift_undef) + '\n', capture_output=True, text=True, ) if dm_res.returncode == 0: matched = any(logdiag_sym in dm or 'logDiag' in dm for dm in dm_res.stdout.splitlines()) if matched: logdiag_linked.append(n) return { 'object_clue_hits': obj_hits, 'main_binary_forbidden_counts': main_forbidden, 'logDiag_translated_symbol': logdiag_mangled_sub, 'logDiag_symbol_linked_objects': logdiag_linked, 'logDiag_symbol_linked_objects_count': len(logdiag_linked), } def verify_m3_symbolication( app_dir: Path, bin_name: str, dsyms_dir: Path, symbol_map_path: Path, method_map_path: Path, l1_info: dict, ) -> dict: main_bin = app_dir / bin_name main_dwarf = dsyms_dir / f'{bin_name}.app.dSYM/Contents/Resources/DWARF/{bin_name}' guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO' guard_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO' def find_sym(dwarf_p: Path, sub: str) -> int: out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_p)], text=True).splitlines() for l in out: parts = l.strip().split(maxsplit=2) if len(parts) == 3 and parts[1].lower() == 't' and sub in parts[2]: return int(parts[0], 16) raise RuntimeError(f'Symbol matching {sub} not found in {dwarf_p}') def text_vm(bin_p: Path) -> int: out = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() for i, l in enumerate(out): if 'segname __TEXT' in l: for j in range(i + 1, min(i + 6, len(out))): if 'vmaddr' in out[j]: return int(out[j].split()[1], 16) return 0x100000000 obf_signer = l1_info['sample_type_mappings']['RDSDAuthV32Signer'] obf_iap = l1_info['sample_type_mappings']['STSIAPVerifyHandler'] kb_vm = find_sym(main_dwarf, 'rd_sd_derive_aes256_key') signer_vm = find_sym(main_dwarf, obf_signer) iap_vm = find_sym(main_dwarf, obf_iap) fw_vm = find_sym(guard_dwarf, 'rd_io_chk') main_uid = next(iter(uuids_of(main_bin))) fw_uid = next(iter(uuids_of(guard_bin))) main_base = text_vm(main_bin) fw_base = text_vm(guard_bin) main_load, fw_load = 0x104000000, 0x109000000 kb_off = (kb_vm - main_base) + 4 signer_off = (signer_vm - main_base) + 4 iap_off = (iap_vm - main_base) + 4 fw_off = (fw_vm - fw_base) + 4 with tempfile.TemporaryDirectory() as td: p = Path(td) ips_p = p / f'{bin_name}.ips' ips_p.write_text( json.dumps({'app_name': bin_name, 'bug_type': '309'}) + '\n' + json.dumps({ 'usedImages': [ {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': bin_name, 'arch': 'arm64', 'path': f'/private/var/{bin_name}.app/{bin_name}'}, {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': 'RDCoreIO', 'arch': 'arm64', 'path': f'/private/var/{bin_name}.app/Frameworks/RDCoreIO.framework/RDCoreIO'}, ], 'threads': [{ 'triggered': True, 'frames': [ {'imageIndex': 0, 'imageOffset': kb_off}, {'imageIndex': 0, 'imageOffset': signer_off}, {'imageIndex': 0, 'imageOffset': iap_off}, {'imageIndex': 1, 'imageOffset': fw_off}, ], }], }) + '\n', encoding='utf-8', ) crash_p = p / f'{bin_name}.crash' crash_p.write_text( 'Thread 0 Crashed:\n' f'0 {bin_name} {hex(main_load + kb_off)} {hex(main_load)} + {kb_off}\n' f'1 {bin_name} {hex(main_load + signer_off)} {hex(main_load)} + {signer_off}\n' f'2 {bin_name} {hex(main_load + iap_off)} {hex(main_load)} + {iap_off}\n' f'3 RDCoreIO {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' 'Binary Images:\n' f' {hex(main_load)} - {hex(main_load + 0x4000000)} {bin_name} arm64 <{main_uid}> /private/var/{bin_name}.app/{bin_name}\n' f' {hex(fw_load)} - {hex(fw_load + 0x400000)} RDCoreIO arm64 <{fw_uid}> /private/var/{bin_name}.app/Frameworks/RDCoreIO.framework/RDCoreIO\n', encoding='utf-8', ) ips_res = restore_crash_report.restore_report(ips_p, dsyms_dir, symbol_map=symbol_map_path, method_map=method_map_path) crash_res = restore_crash_report.restore_report(crash_p, dsyms_dir, symbol_map=symbol_map_path, method_map=method_map_path) for label, r in [('ips', ips_res), ('crash', crash_res)]: raw_frames = (r.get('threads', [{}])[0].get('frames', []) if label == 'ips' else r.get('frames', [])) raw_text = ' '.join(' '.join(f.get('raw_atos') or []) for f in raw_frames) restored_text = ' '.join(' '.join(f.get('restored_frames') or []) for f in raw_frames) assert obf_signer in raw_text, f'{label} raw_atos missing obfuscated signer {obf_signer}: {raw_frames}' assert obf_iap in raw_text, f'{label} raw_atos missing obfuscated handler {obf_iap}: {raw_frames}' assert 'RDSDAuthV32Signer' in restored_text, f'{label} failed to deobfuscate {obf_signer} -> RDSDAuthV32Signer: {restored_text}' assert 'STSIAPVerifyHandler' in restored_text, f'{label} failed to deobfuscate {obf_iap} -> STSIAPVerifyHandler: {restored_text}' assert 'rd_sd_derive_aes256_key' in restored_text, f'{label} missing rd_sd_derive_aes256_key: {restored_text}' assert 'ig_archive_check' in restored_text, f'{label} missing ig_archive_check: {restored_text}' return {'ips': ips_res, 'crash': crash_res} def prepare_signed_app(app_dir: Path, work_dir: Path, bundle_id: str, display_name: str) -> Path: r_prof = subprocess.run( ['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(DEFAULT_PROFILE)], capture_output=True, check=True, ) pdata = plistlib.loads(r_prof.stdout) ent = pdata['Entitlements'] prefix = pdata['ApplicationIdentifierPrefix'][0] if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'): raise RuntimeError('Provisioning profile must be wildcard development profile') if pdata['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None): raise RuntimeError('Provisioning profile expired') if DEFAULT_IDENTITY.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}: raise RuntimeError('Identity does not match provisioning profile') if work_dir.exists(): shutil.rmtree(work_dir) work_dir.mkdir(parents=True) staged_app = work_dir / app_dir.name subprocess.run(['ditto', str(app_dir), str(staged_app)], check=True) info_path = staged_app / 'Info.plist' info = plistlib.loads(info_path.read_bytes()) info['CFBundleIdentifier'] = bundle_id info['CFBundleDisplayName'] = display_name info.pop('CFBundleURLTypes', None) info_path.write_bytes(plistlib.dumps(info)) shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') # Handle any nested .appex plugins cleanly if present appex_dirs = sorted( {p for p in staged_app.rglob('*.appex') if not p.is_symlink()}, key=lambda p: (-len(p.parts), str(p)), ) for appex in appex_dirs: ext_info_p = appex / 'Info.plist' ext_info = plistlib.loads(ext_info_p.read_bytes()) ext_bid = f'{bundle_id}.{appex.stem}' ext_info['CFBundleIdentifier'] = ext_bid ext_info_p.write_bytes(plistlib.dumps(ext_info)) shutil.copy2(DEFAULT_PROFILE, appex / 'embedded.mobileprovision') ext_ent = dict(ent) ext_ent['application-identifier'] = f'{prefix}.{ext_bid}' ext_ent['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] ext_ent_p = work_dir / f'ent_{appex.stem}.plist' ext_ent_p.write_bytes(plistlib.dumps(ext_ent)) subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ext_ent_p), str(appex)], check=True) nested = sorted( {p for p in staged_app.rglob('*') if not p.is_symlink() and p.suffix in ('.framework', '.dylib')}, key=lambda p: (-len(p.parts), str(p)), ) for item in nested: subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(item)], check=True) allowed = dict(ent) allowed['application-identifier'] = f'{prefix}.{bundle_id}' allowed['keychain-access-groups'] = [f'{prefix}.{bundle_id}'] ent_path = work_dir / 'entitlements.plist' ent_path.write_bytes(plistlib.dumps(allowed)) subprocess.run( ['codesign', '--force', '--sign', DEFAULT_IDENTITY, '--entitlements', str(ent_path), str(staged_app)], check=True, ) subprocess.run(['codesign', '--verify', '--strict', str(staged_app)], check=True) return staged_app def run_device_stage(staged_app: Path, work_dir: Path, bundle_id: str, stage: str, do_install: bool = True) -> dict: if do_install: print(f'[device] installing {staged_app.name} ({bundle_id}) for stage={stage}...', flush=True) subprocess.run([ 'xcrun', 'devicectl', 'device', 'install', 'app', '--device', DEFAULT_DEVICE, '--timeout', '120', str(staged_app), ], check=True) print(f'[device] launching {bundle_id} IG_M3_BENCH=1 IG_M3_STAGE={stage}...', flush=True) subprocess.run([ 'xcrun', 'devicectl', 'device', 'process', 'launch', '--device', DEFAULT_DEVICE, '--terminate-existing', '-e', json.dumps({'IG_M3_BENCH': '1', 'IG_M3_STAGE': stage}), bundle_id, ], check=True) done_marker = work_dir / f'm3_eval_{stage}.done' result_json = work_dir / f'm3_eval_{stage}.json' deadline = time.monotonic() + 120.0 got_stage_done = False while time.monotonic() < deadline: if done_marker.is_file(): done_marker.unlink() elif done_marker.is_dir(): shutil.rmtree(done_marker) r = subprocess.run([ 'xcrun', 'devicectl', 'device', 'copy', 'from', '--device', DEFAULT_DEVICE, '--domain-type', 'appDataContainer', '--domain-identifier', bundle_id, '--source', 'Documents/m3_eval.done', '--destination', str(done_marker), ], capture_output=True, text=True) if r.returncode == 0 and done_marker.is_file(): if done_marker.read_text(encoding='utf-8', errors='replace').strip() == stage: got_stage_done = True break time.sleep(1.5) if not got_stage_done: raise RuntimeError(f'Timed out waiting for Documents/m3_eval.done == {stage!r} from {bundle_id}') subprocess.run([ 'xcrun', 'devicectl', 'device', 'copy', 'from', '--device', DEFAULT_DEVICE, '--domain-type', 'appDataContainer', '--domain-identifier', bundle_id, '--source', 'Documents/m3_eval.json', '--destination', str(result_json), ], check=True) payload = json.loads(result_json.read_text(encoding='utf-8')) assert payload.get('stage') == stage, f'Stage mismatch: expected {stage}, got {payload}' assert payload.get('status') == 'ok', f'Device stage {stage} failed: {payload}' return payload def verify_host_rsa(sig_b64: str, sign_string: str, pem_bytes: bytes): priv_key = load_pem_private_key(pem_bytes, password=None) pub_key = priv_key.public_key() pub_key.verify( base64.b64decode(sig_b64), sign_string.encode('utf-8'), padding.PKCS1v15(), hashes.SHA256(), ) def uninstall_app(bundle_id: str): subprocess.run([ 'xcrun', 'devicectl', 'device', 'process', 'terminate', '--device', DEFAULT_DEVICE, bundle_id, ], capture_output=True, check=False) subprocess.run([ 'xcrun', 'devicectl', 'device', 'uninstall', 'app', '--device', DEFAULT_DEVICE, '--timeout', '60', bundle_id, ], capture_output=True, check=False) def run_regression(): RESULTS_DIR.mkdir(parents=True, exist_ok=True) sync_toolchain_and_integrate() policy_path = ROOT / 'config/ig_llvm_policy.json' policy = json.loads(policy_path.read_text(encoding='utf-8')) policy_stamp = sha256_bytes(policy_path.read_bytes())[:12] # Clear persistent L2 cache before cold archive measurement if CACHE_ROOT.exists(): shutil.rmtree(CACHE_ROOT) CACHE_ROOT.mkdir(parents=True, exist_ok=True) cleanup_build_artifacts() l1_info = create_clean_snapshot_and_apply_l1() sym_map_path = Path(l1_info['symbol_map_path']) meth_map_path = Path(l1_info['method_map_path']) obf_args = [ 'IG_OBF_MODE=full', 'IG_POLICY_PROFILE=default', f'IG_POLICY_STAMP={policy_stamp}', 'IG_RELEASE_SEED=m3_prod_seed_20261119', 'IG_SWIFT_EXTRA_FLAGS=', 'IG_C_EXTRA_FLAGS=', ] # 1. Cold Cache Production Archive (readoor31, L1+L2+L3) t_cold = run_archive( SNAPSHOT_SRC, 'readoor31', 'm3_readoor31_cold', obf_args, RESULTS_DIR / 'm3_readoor31_cold.log', clean_first=True, use_cache=True, require_llvm_obf=True, ) app_31 = ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app' main_31 = app_31 / 'readoor31' dsyms_31 = ARCHIVE_DIR / 'readoor31.xcarchive/dSYMs' uuids_31_bin = uuids_of(main_31) uuids_31_dsym = uuids_of(dsyms_31 / 'readoor31.app.dSYM') assert uuids_31_bin and uuids_31_bin == uuids_31_dsym, (uuids_31_bin, uuids_31_dsym) assert (app_31 / 'rd_glyph_lut_v2.dat').is_file() r2_31 = inspect_app_route2(app_31, 'm3_readoor31_cold') assert r2_31['binaries'] == 40 and r2_31['direct_call_total'] == 0, r2_31 interm_31 = target_interm_dir('readoor31') audit_31 = verify_required_targets(interm_31 / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) clues_31 = audit_m3_static_clues(main_31, interm_31 / 'Objects-normal/arm64', SNAPSHOT_SRC) for k, v in clues_31['main_binary_forbidden_counts'].items(): assert v == 0, f'Forbidden string {k!r} found {v}x in L1+L2+L3 readoor31: {clues_31}' for obj_name, obj_hits in clues_31['object_clue_hits'].items(): assert not obj_hits, f'Clue hits in object {obj_name}: {obj_hits}' assert clues_31['logDiag_symbol_linked_objects_count'] == 6, clues_31 sym_restore_31 = verify_m3_symbolication(app_31, 'readoor31', dsyms_31, sym_map_path, meth_map_path, l1_info) size_31_bytes = main_31.stat().st_size txt_31_bytes = text_section_bytes(main_31) cold_cache_files = sum(1 for _ in CACHE_ROOT.rglob('*') if _.is_file()) cleanup_build_artifacts() # 2. Warm Cache Production Archive (readoor31, L1+L2+L3, clean DD reusing L2 cache) t_warm = run_archive( SNAPSHOT_SRC, 'readoor31', 'm3_readoor31_warm', obf_args, RESULTS_DIR / 'm3_readoor31_warm.log', clean_first=True, use_cache=True, require_llvm_obf=True, ) app_31_warm = ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app' r2_31_warm = inspect_app_route2(app_31_warm, 'm3_readoor31_warm') assert r2_31_warm['binaries'] == 40 and r2_31_warm['direct_call_total'] == 0, r2_31_warm verify_required_targets(target_interm_dir('readoor31') / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) warm_cache_files = sum(1 for _ in CACHE_ROOT.rglob('*') if _.is_file()) speedup = round(t_cold / t_warm, 2) if t_warm > 0 else 0.0 cleanup_build_artifacts() # 3. Dual-Target Production Archive (readoor31OtherPay, L1+L2+L3) t_otherpay = run_archive( SNAPSHOT_SRC, 'readoor31OtherPay', 'm3_otherpay', obf_args, RESULTS_DIR / 'm3_otherpay.log', clean_first=True, use_cache=True, require_llvm_obf=True, ) app_op = ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/Products/Applications/readoor31OtherPay.app' main_op = app_op / 'readoor31OtherPay' dsyms_op = ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/dSYMs' uuids_op_bin = uuids_of(main_op) uuids_op_dsym = uuids_of(dsyms_op / 'readoor31OtherPay.app.dSYM') assert uuids_op_bin and uuids_op_bin == uuids_op_dsym, (uuids_op_bin, uuids_op_dsym) assert (app_op / 'rd_glyph_lut_v2.dat').is_file() r2_op = inspect_app_route2(app_op, 'm3_otherpay') assert r2_op['binaries'] == 44 and r2_op['direct_call_total'] == 0, r2_op audit_op = verify_required_targets(target_interm_dir('readoor31OtherPay') / 'ig-route2-audit/ig_obfuscation_audit.json', policy, expect_l1_translation=True) sym_restore_op = verify_m3_symbolication(app_op, 'readoor31OtherPay', dsyms_op, sym_map_path, meth_map_path, l1_info) size_op_bytes = main_op.stat().st_size txt_op_bytes = text_section_bytes(main_op) cleanup_build_artifacts() # 4. Physical iPhone 16 Plus Over-Install (v1 clean -> v2 L1+L2+L3) + readoor31OtherPay (L1+L2+L3) pem_bytes = (APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem').read_bytes() expected_pem_sha256 = sha256_bytes(pem_bytes) bench_swift = 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M3_BENCH -Xcc -DIG_ENABLE_M3_BENCH=1' bench_c = 'IG_C_EXTRA_FLAGS=-DIG_ENABLE_M3_BENCH=1' device_stages = {} uninstall_app(BUNDLE_READOOR31) uninstall_app(BUNDLE_OTHERPAY) try: # Stage 1: Clean un-obfuscated v1 seed v1_args = [ 'IG_ALL_GUARD_OFF=1', 'IG_OBF_MODE=off', bench_swift, bench_c, ] t_bench_v1 = run_archive( APP_REPO, 'readoor31', 'm3_bench_v1', v1_args, RESULTS_DIR / 'm3_bench_v1.log', clean_first=True, use_cache=False, require_llvm_obf=False, ) staged_v1 = prepare_signed_app(ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app', STAGE_DIR, BUNDLE_READOOR31, 'M3Eval') s1 = run_device_stage(staged_v1, STAGE_DIR, BUNDLE_READOOR31, 'seed_legacy_v1', do_install=True) assert s1['keychain_present_before'] is False assert s1['pem_sha256'] == expected_pem_sha256 assert s1['login_view_class_obfuscated'] is False verify_host_rsa(s1['x_sig'], s1['sign_string'], pem_bytes) device_stages['seed_legacy_v1'] = s1 cleanup_build_artifacts() # Stage 2: L1+L2+L3 v2 over-install WITHOUT uninstalling v2_args = [ 'IG_OBF_MODE=full', 'IG_POLICY_PROFILE=default', f'IG_POLICY_STAMP={policy_stamp}', 'IG_RELEASE_SEED=m3_prod_seed_20261119', bench_swift, bench_c, ] t_bench_v2 = run_archive( SNAPSHOT_SRC, 'readoor31', 'm3_bench_v2', v2_args, RESULTS_DIR / 'm3_bench_v2.log', clean_first=True, use_cache=True, require_llvm_obf=True, ) staged_v2 = prepare_signed_app(ARCHIVE_DIR / 'readoor31.xcarchive/Products/Applications/readoor31.app', STAGE_DIR, BUNDLE_READOOR31, 'M3Eval') s2 = run_device_stage(staged_v2, STAGE_DIR, BUNDLE_READOOR31, 'verify_upgrade_l123', do_install=True) assert s2['keychain_present_before'] is True, f'Over-install lost Keychain key: {s2}' assert s2['pem_sha256'] == expected_pem_sha256 assert s2['x_sig'] == s1['x_sig'] assert s2['login_view_class_obfuscated'] is True assert s2['iap_handler_class_obfuscated'] is True assert s2['swift_media_cache_unarchive_ok'] is True assert s2['guard_baseline_count'] >= 2 assert s2['guard_eval_ok'] is True assert s2['epub_decrypt_ok'] is True verify_host_rsa(s2['x_sig'], s2['sign_string'], pem_bytes) device_stages['verify_upgrade_l123'] = s2 cleanup_build_artifacts() # Stage 3: L1+L2+L3 readoor31OtherPay device check t_bench_op = run_archive( SNAPSHOT_SRC, 'readoor31OtherPay', 'm3_bench_otherpay', v2_args, RESULTS_DIR / 'm3_bench_otherpay.log', clean_first=True, use_cache=True, require_llvm_obf=True, ) staged_op = prepare_signed_app(ARCHIVE_DIR / 'readoor31OtherPay.xcarchive/Products/Applications/readoor31OtherPay.app', STAGE_DIR, BUNDLE_OTHERPAY, 'M3OtherPay') s3 = run_device_stage(staged_op, STAGE_DIR, BUNDLE_OTHERPAY, 'verify_otherpay_l123', do_install=True) assert s3['pem_sha256'] == expected_pem_sha256 assert s3['login_view_class_obfuscated'] is True assert s3['iap_handler_class_obfuscated'] is True assert s3['swift_media_cache_roundtrip_ok'] is True assert s3['guard_baseline_count'] >= 2 assert s3['guard_eval_ok'] is True assert s3['epub_decrypt_ok'] is True verify_host_rsa(s3['x_sig'], s3['sign_string'], pem_bytes) device_stages['verify_otherpay_l123'] = s3 cleanup_build_artifacts() finally: uninstall_app(BUNDLE_READOOR31) uninstall_app(BUNDLE_OTHERPAY) cleanup_build_artifacts() if SNAPSHOT_SRC.exists(): shutil.rmtree(SNAPSHOT_SRC) if WORK_ROOT.exists(): shutil.rmtree(WORK_ROOT) if CACHE_ROOT.exists(): shutil.rmtree(CACHE_ROOT) summary = { 'milestone': 'M3', 'l1_obfuscation': l1_info, 'readoor31_production': { 'cold_archive_elapsed_s': t_cold, 'warm_archive_elapsed_s': t_warm, 'cache_speedup_ratio': speedup, 'cold_cache_files': cold_cache_files, 'warm_cache_files': warm_cache_files, 'main_binary_bytes': size_31_bytes, 'main_text_bytes': txt_31_bytes, 'size_delta_vs_m2_bytes': size_31_bytes - M2_MAIN_BYTES, 'main_uuids': sorted(uuids_31_bin), 'route2': r2_31, 'obf_audit': { 'l1_translation_active': audit_31.get('l1_translation_active'), 'expected_swift_count': audit_31.get('expected_swift_count'), 'converted_swift_count': audit_31.get('converted_swift_count'), 'total_flattened': audit_31.get('total_flattened'), 'total_strings_encrypted': audit_31.get('total_strings_encrypted'), 'required_targets': audit_31.get('required_targets'), }, 'static_clues': clues_31, 'symbolication_v2_restore': sym_restore_31, }, 'readoor31OtherPay_production': { 'archive_elapsed_s': t_otherpay, 'main_binary_bytes': size_op_bytes, 'main_text_bytes': txt_op_bytes, 'main_uuids': sorted(uuids_op_bin), 'route2': r2_op, 'obf_audit': { 'l1_translation_active': audit_op.get('l1_translation_active'), 'expected_swift_count': audit_op.get('expected_swift_count'), 'converted_swift_count': audit_op.get('converted_swift_count'), 'total_flattened': audit_op.get('total_flattened'), 'total_strings_encrypted': audit_op.get('total_strings_encrypted'), 'required_targets': audit_op.get('required_targets'), }, 'symbolication_v2_restore': sym_restore_op, }, 'device_verification': { 'device_udid': DEFAULT_DEVICE, 'bench_archive_timings_s': { 'v1_clean': t_bench_v1, 'v2_readoor31_l123': t_bench_v2, 'v2_otherpay_l123': t_bench_op, }, 'expected_pem_sha256': expected_pem_sha256, 'offline_host_rsa_verify_all_stages': True, 'stages': device_stages, }, } summary_path = RESULTS_DIR / 'm3_summary.json' summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') print(f'\n[M3] ALL CHECKS PASSED -> {summary_path}', flush=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.parse_args() run_regression() if __name__ == '__main__': main()