#!/usr/bin/env python3 """Execute Milestone 2 SD 3.2, IAP & Security Guard verification and physical-device 3-path test.""" import argparse import base64 import datetime import hashlib import json 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 restore_crash_report # noqa: E402 from verify_baseline import scan # noqa: E402 DD_PATH = Path('/tmp/ig-m2-dd') ARCHIVE_PATH = Path('/tmp/ig-m2-archives/readoor31.xcarchive') STAGE_DIR = Path('/tmp/ig-m2-stage') RESULTS_DIR = ROOT / 'test-results' / '20261119-m2-sd-iap-evaluation' TARGET_BUILD_INTERM = DD_PATH / 'Build/Intermediates.noindex/ArchiveIntermediates/readoor31/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/readoor31.build' OBJ_BASE = TARGET_BUILD_INTERM / 'Objects-normal/arm64' AUDIT_DIR = TARGET_BUILD_INTERM / 'ig-route2-audit' DEFAULT_DEVICE = '00008140-000960811493001C' DEFAULT_PROFILE = Path('/Users/shenlei/Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision') DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8' BENCH_BUNDLE_ID = 'cn.touchv.iosguard.m2seceval' M1_GROUP_A_MAIN_BYTES = 24_748_584 MAX_SIZE_DELTA_BYTES = 1_572_864 def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def check_disk_budget(min_gb=5.0): 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 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' copies = [ (ROOT / 'config/ig_llvm_policy.json', dst_root / 'config/ig_llvm_policy.json'), (ROOT / 'config/ig_diag_events.json', dst_root / 'config/ig_diag_events.json'), (ROOT / 'config/toolchain_manifest.json', dst_root / 'config/toolchain_manifest.json'), (ROOT / 'tools/xcode_archive/ig_cc_wrapper.py', dst_root / 'tools/xcode_archive/ig_cc_wrapper.py'), (ROOT / 'tools/xcode_archive/ig_cxx_wrapper.py', dst_root / 'tools/xcode_archive/ig_cxx_wrapper.py'), (ROOT / 'tools/xcode_archive/ig_ld_wrapper.py', dst_root / 'tools/xcode_archive/ig_ld_wrapper.py'), (ROOT / 'tools/xcode_archive/ig_guard_frameworks_phase.py', dst_root / 'tools/xcode_archive/ig_guard_frameworks_phase.py'), (ROOT / 'tools/llvm_obf/ig_toolchain_resolver.py', dst_root / 'tools/llvm_obf/ig_toolchain_resolver.py'), (ROOT / 'tools/crash_restore/restore_crash_report.py', dst_root / 'tools/crash_restore/restore_crash_report.py'), ] for src, dst in copies: if src.is_file(): dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) subprocess.run(['ruby', str(APP_REPO / 'scripts/integrate_route2_archive.rb')], cwd=APP_REPO, check=True) def run_archive(step_tag: str, extra_settings: list, log_path: Path) -> float: free_gb = check_disk_budget() print(f'\n=== [{step_tag}] disk_free={free_gb}GB args={extra_settings} ===', flush=True) if ARCHIVE_PATH.exists(): shutil.rmtree(ARCHIVE_PATH) ARCHIVE_PATH.parent.mkdir(parents=True, exist_ok=True) cmd = [ 'xcodebuild', '-workspace', str(APP_REPO / 'readoor.xcworkspace'), '-scheme', 'readoor31', '-configuration', 'Release', '-destination', 'generic/platform=iOS', '-derivedDataPath', str(DD_PATH), '-archivePath', str(ARCHIVE_PATH), 'CODE_SIGNING_ALLOWED=NO', *extra_settings, 'archive', ] t0 = time.monotonic() res = subprocess.run(cmd, cwd=APP_REPO, 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[-120:] + ['', '--- tail ---'] + text_log.splitlines()[-80:]) + '\n', encoding='utf-8') if res.returncode != 0: raise RuntimeError(f'[{step_tag}] xcodebuild failed (rc={res.returncode}):\n' + '\n'.join(text_log.splitlines()[-80:])) 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 find_m2_objects() -> dict: names = [ 'RDSDKeyBox', 'RDSDPrivateKeyManager', 'RDSDAuthV32Signer', 'RDJWTPayloadParser', 'RDBaseNetworkService', 'RDSecurityGuard', 'RDInjectionDetector', 'RDIAPPurchaseManager', 'RDIAPHandler', 'STSIAPVerifyHandler', 'STSIAPVerifyTask', 'STSIAPKeyChainHandler', ] swift_macho_dir = OBJ_BASE / 'ig-swift-macho' found = {} 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' found[n] = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None) return found 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_m2_static_clues(main_bin: Path) -> dict: objs = find_m2_objects() forbidden_clues = [ b'readoor_sd_v32', b'KSDPrivateKeyPEM', b'encrypted_private_key', b'cn.touchv.payment.models.keychain', b'[SDAuthV32]', b'[IAP]', b'[Security]', b'Exception: No product matched', ] 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_counts = { pat.decode('ascii', errors='replace'): main_raw.count(pat) for pat in forbidden_clues } main_strings = subprocess.run(['strings', str(main_bin)], capture_output=True).stdout.decode('utf-8', errors='replace').splitlines() protected_module_filenames = ( 'RDEpubKeyBox.c', 'RDEpubCryptBridge.m', 'RDEpubKeyGuard.c', 'RDEncryptedEpubResourceProvider.swift', 'RDEpubReaderLauncher.swift', 'RD30EpubCoordinator.swift', 'RD30EpubResourceService.swift', 'RD30EpubFileStore.swift', 'RD30EpubDownloadManager.swift', 'RDPDFStsSimpleCryptBridge.swift', 'STSEpubWebResourceLoader.m', 'EpubParser.m', 'EpubChapter.m', 'RBCoreEpubLoadController.m', 'RDSDKeyBox.c', 'RDSDPrivateKeyManager.swift', 'RDSDAuthV32Signer.swift', 'RDJWTPayloadParser.swift', 'RDBaseNetworkService.swift', 'RDRequestParamsFormat.swift', 'RDSecurityGuard.swift', 'RDInjectionDetector.swift', 'RDIAPPurchaseManager.swift', 'RDIAPHandler.swift', 'RDIAPHandler+RDVipExtension.swift', 'STSIAPVerifyHandler.m', 'STSIAPVerifyTask.m', 'STSIAPKeyChainHandler.m', ) host_path_lines = [l for l in main_strings if '/Users/shenlei/Work/ReadBook' in l] protected_host_path_lines = [ l for l in host_path_lines if any(l.endswith('/' + f) or f in l for f in protected_module_filenames) ] 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') if '7logDiag' in nm_u: logdiag_linked.append(n) main_diag_counts = { 'E_41_count': main_raw.count(b'E-41'), 'E_51_count': main_raw.count(b'E-51'), 'E_61_count': main_raw.count(b'E-61'), 'logDiag_symbol_linked_objects': logdiag_linked, 'logDiag_symbol_linked_objects_count': len(logdiag_linked), } return { 'object_paths': {k: (str(v) if v else None) for k, v in objs.items()}, 'object_clue_hits': obj_hits, 'main_binary_forbidden_counts': main_forbidden_counts, 'protected_module_host_path_hits': protected_host_path_lines, 'unscoped_snapkit_filepath_count': len(host_path_lines), 'main_binary_diag_counts': main_diag_counts, } def verify_m2_symbolication(app_dir: Path, dsyms_dir: Path) -> dict: main_bin = app_dir / 'readoor31' main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31' 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 kb_vm = find_sym(main_dwarf, 'rd_sd_derive_aes256_key') signer_vm = find_sym(main_dwarf, 'RDSDAuthV32Signer') iap_vm = find_sym(main_dwarf, 'STSIAPVerifyHandler') 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 / 'm2.ips' ips_p.write_text( json.dumps({'app_name': 'readoor31', 'bug_type': '309'}) + '\n' + json.dumps({ 'usedImages': [ {'base': main_load, 'size': 0x4000000, 'uuid': main_uid, 'name': 'readoor31', 'arch': 'arm64', 'path': '/private/var/readoor31.app/readoor31'}, {'base': fw_load, 'size': 0x400000, 'uuid': fw_uid, 'name': 'RDCoreIO', 'arch': 'arm64', 'path': '/private/var/readoor31.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 / 'm2.crash' crash_p.write_text( 'Thread 0 Crashed:\n' f'0 readoor31 {hex(main_load + kb_off)} {hex(main_load)} + {kb_off}\n' f'1 readoor31 {hex(main_load + signer_off)} {hex(main_load)} + {signer_off}\n' f'2 readoor31 {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)} readoor31 arm64 <{main_uid}> /private/var/readoor31.app/readoor31\n' f' {hex(fw_load)} - {hex(fw_load + 0x400000)} RDCoreIO arm64 <{fw_uid}> /private/var/readoor31.app/Frameworks/RDCoreIO.framework/RDCoreIO\n', encoding='utf-8', ) ips_res = restore_crash_report.restore_report(ips_p, dsyms_dir) crash_res = restore_crash_report.restore_report(crash_p, dsyms_dir) 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', [])) sym_frames = [' '.join(f.get('restored_frames') or []) for f in raw_frames] assert len(sym_frames) == 4, f'{label} expected 4 frames, got {raw_frames}' assert any('rd_sd_derive_aes256_key' in s for s in sym_frames), f'{label} missing RDSDKeyBox: {sym_frames}' assert any('RDSDAuthV32Signer' in s for s in sym_frames), f'{label} missing RDSDAuthV32Signer: {sym_frames}' assert any('STSIAPVerifyHandler' in s for s in sym_frames), f'{label} missing STSIAPVerifyHandler: {sym_frames}' assert any('rd_io_chk' in s for s in sym_frames), f'{label} missing RDCoreIO: {sym_frames}' return {'ips': ips_res, 'crash': crash_res} def prepare_signed_app(app_dir: Path, work_dir: Path) -> 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 / 'readoor31.app' 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'] = BENCH_BUNDLE_ID info['CFBundleDisplayName'] = 'M2SecEval' info.pop('CFBundleURLTypes', None) info_path.write_bytes(plistlib.dumps(info)) shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision') allowed = dict(ent) allowed['application-identifier'] = f'{prefix}.{BENCH_BUNDLE_ID}' allowed['keychain-access-groups'] = [f'{prefix}.{BENCH_BUNDLE_ID}'] ent_path = work_dir / 'entitlements.plist' ent_path.write_bytes(plistlib.dumps(allowed)) 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) 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, stage: str, do_install: bool) -> dict: if do_install: print(f'[device] installing {staged_app.name} ({BENCH_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 {BENCH_BUNDLE_ID} IG_M2_SEC_BENCH=1 IG_M2_STAGE={stage}...', flush=True) subprocess.run([ 'xcrun', 'devicectl', 'device', 'process', 'launch', '--device', DEFAULT_DEVICE, '--terminate-existing', '-e', json.dumps({'IG_M2_SEC_BENCH': '1', 'IG_M2_STAGE': stage}), BENCH_BUNDLE_ID, ], check=True) done_marker = work_dir / f'm2_sec_eval_{stage}.done' result_json = work_dir / f'm2_sec_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', BENCH_BUNDLE_ID, '--source', 'Documents/m2_sec_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/m2_sec_eval.done == {stage!r} from device') subprocess.run([ 'xcrun', 'devicectl', 'device', 'copy', 'from', '--device', DEFAULT_DEVICE, '--domain-type', 'appDataContainer', '--domain-identifier', BENCH_BUNDLE_ID, '--source', 'Documents/m2_sec_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 run_eval(clean_dd: bool = False): 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] if clean_dd and DD_PATH.exists(): shutil.rmtree(DD_PATH) base_args = [ 'IG_OBF_MODE=full', 'IG_POLICY_PROFILE=default', f'IG_POLICY_STAMP={policy_stamp}', 'IG_RELEASE_SEED=m2_seed_alpha', ] # Phase 1: Clean Production Archive t_clean = run_archive('m2_clean', [*base_args, 'IG_SWIFT_EXTRA_FLAGS='], RESULTS_DIR / 'm2_clean.log') app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app' main_bin = app_dir / 'readoor31' dsyms_dir = ARCHIVE_PATH / 'dSYMs' main_uuids = uuids_of(main_bin) dsym_uuids = uuids_of(dsyms_dir / 'readoor31.app.dSYM') assert main_uuids and main_uuids == dsym_uuids, f'UUID mismatch: bin={main_uuids} dsym={dsym_uuids}' r2 = inspect_app_route2(app_dir, 'm2_clean') assert r2['binaries'] == 40 and r2['direct_call_total'] == 0, f'Route2 check failed: {r2}' assert (app_dir / 'rd_glyph_lut_v2.dat').is_file(), 'rd_glyph_lut_v2.dat missing from app bundle' assert not (app_dir / 'encrypted_private_key.bin').exists(), 'Legacy encrypted_private_key.bin still in app bundle' obf_audit = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').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}' bin_bytes = main_bin.stat().st_size txt_bytes = text_section_bytes(main_bin) size_delta = bin_bytes - M1_GROUP_A_MAIN_BYTES assert size_delta <= MAX_SIZE_DELTA_BYTES, f'Main binary size delta {size_delta} exceeds {MAX_SIZE_DELTA_BYTES}' clues = audit_m2_static_clues(main_bin) for k, v in clues['main_binary_forbidden_counts'].items(): assert v == 0, f'Forbidden string {k!r} found {v}x in readoor31 main binary: {clues}' assert clues['protected_module_host_path_hits'] == [], f"Host path leaked for protected M1/M2 modules: {clues['protected_module_host_path_hits']}" for obj_name, obj_hits in clues['object_clue_hits'].items(): assert not obj_hits, f'Clue hits in object {obj_name}: {obj_hits}' assert clues['main_binary_diag_counts']['E_41_count'] >= 1, clues assert clues['main_binary_diag_counts']['E_51_count'] >= 1, clues assert clues['main_binary_diag_counts']['logDiag_symbol_linked_objects_count'] == 6, clues symbolication = verify_m2_symbolication(app_dir, dsyms_dir) # Phase 2: Bench Archive & Physical iPhone 16 Plus 3-Stage Verification t_bench = run_archive('m2_bench', [*base_args, 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M2_BENCH'], RESULTS_DIR / 'm2_bench.log') staged_app = prepare_signed_app(ARCHIVE_PATH / 'Products/Applications/readoor31.app', STAGE_DIR) # Start clean on device (uninstall prior test bundle if leftover) subprocess.run([ 'xcrun', 'devicectl', 'device', 'uninstall', 'app', '--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID, ], capture_output=True, check=False) stage_results = {} try: s1 = run_device_stage(staged_app, STAGE_DIR, 'fresh_seed_v1', do_install=True) assert s1['keychain_present_before'] is False assert s1['keychain_present_after'] is True assert s1['local_verify_ok'] is True assert s1['guard_baseline_count'] >= 2 assert s1['guard_eval_ok'] is True assert s1['iap_keychain_roundtrip_ok'] is True stage_results['fresh_seed_v1'] = s1 # Stage 2: over-install WITHOUT uninstalling first s2 = run_device_stage(staged_app, STAGE_DIR, 'upgrade_verify', do_install=True) assert s2['keychain_present_before'] is True, f'Over-install lost Keychain item: {s2}' assert s2['keychain_present_after'] is True assert s2['local_verify_ok'] is True assert s2['guard_baseline_count'] >= 2 assert s2['guard_eval_ok'] is True assert s2['iap_keychain_roundtrip_ok'] is True assert s2['pem_sha256'] == s1['pem_sha256'], 'Over-install changed PEM hash!' assert s2['x_sig'] == s1['x_sig'], 'Over-install changed X-SIG!' stage_results['upgrade_verify'] = s2 # Stage 3: clear Keychain item & verify recovery from rd_net_cfg_v1.dat s3 = run_device_stage(staged_app, STAGE_DIR, 'clear_recover', do_install=False) assert s3.get('had_before_clear') is True assert s3['keychain_present_before'] is False assert s3['keychain_present_after'] is True assert s3['local_verify_ok'] is True assert s3['guard_baseline_count'] >= 2 assert s3['guard_eval_ok'] is True assert s3['iap_keychain_roundtrip_ok'] is True assert s3['pem_sha256'] == s1['pem_sha256'], 'Recovered PEM hash mismatch!' assert s3['x_sig'] == s1['x_sig'], 'Recovered X-SIG mismatch!' stage_results['clear_recover'] = s3 finally: subprocess.run([ 'xcrun', 'devicectl', 'device', 'process', 'terminate', '--device', DEFAULT_DEVICE, BENCH_BUNDLE_ID, ], capture_output=True) subprocess.run([ 'xcrun', 'devicectl', 'device', 'uninstall', 'app', '--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID, ], capture_output=True, check=False) # Offline host cryptography RSA-SHA256 verification against repository PEM pem_path = APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem' pem_bytes = pem_path.read_bytes() expected_pem_sha256 = sha256_bytes(pem_bytes) assert stage_results['fresh_seed_v1']['pem_sha256'] == expected_pem_sha256, ( f"Device PEM sha256 {stage_results['fresh_seed_v1']['pem_sha256']} != {expected_pem_sha256}" ) priv_key = load_pem_private_key(pem_bytes, password=None) pub_key = priv_key.public_key() pub_key.verify( base64.b64decode(stage_results['fresh_seed_v1']['x_sig']), stage_results['fresh_seed_v1']['sign_string'].encode('utf-8'), padding.PKCS1v15(), hashes.SHA256(), ) summary = { 'milestone': 'M2', 'clean_archive': { 'elapsed_s': t_clean, 'main_binary_bytes': bin_bytes, 'main_text_bytes': txt_bytes, 'm1_group_a_main_bytes': M1_GROUP_A_MAIN_BYTES, 'size_delta_bytes': size_delta, 'main_uuids': sorted(main_uuids), 'bundle_has_rd_glyph_lut_v2_dat': True, 'bundle_has_legacy_encrypted_private_key_bin': False, 'route2': r2, 'obf_audit_summary': { 'expected_swift_count': obf_audit.get('expected_swift_count'), 'converted_swift_count': obf_audit.get('converted_swift_count'), 'total_flattened': obf_audit.get('total_flattened'), 'total_strings_encrypted': obf_audit.get('total_strings_encrypted'), 'required_targets': obf_audit.get('required_targets'), }, 'static_clues': clues, 'symbolication': symbolication, }, 'bench_archive': { 'elapsed_s': t_bench, }, 'device_verification': { 'device_udid': DEFAULT_DEVICE, 'bundle_id': BENCH_BUNDLE_ID, 'stages': stage_results, 'offline_host_rsa_verify_ok': True, 'expected_pem_sha256': expected_pem_sha256, }, } summary_path = RESULTS_DIR / 'm2_summary.json' summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') print(f'\n[M2] ALL CHECKS PASSED -> {summary_path}', flush=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--clean-dd', action='store_true', help='Remove DerivedData before archiving') args = parser.parse_args() run_eval(clean_dd=args.clean_dd) if __name__ == '__main__': main()