feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固

- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测
- llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言)
- tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化)
- tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+620
View File
@@ -0,0 +1,620 @@
#!/usr/bin/env python3
"""Execute Milestone 1 EPUB layered ablation, physical-device benchmark, static clue audit, and Round 2 seed polymorphism verification."""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import shutil
import subprocess
import sys
import tempfile
import time
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
from ig_toolchain_resolver import detect_sdk_info, detect_stock_tool, resolve_opt # noqa: E402
DD_PATH = Path('/tmp/ig-m1-dd')
ARCHIVE_PATH = Path('/tmp/ig-m1-archives/readoor31.xcarchive')
BLIND_DIR = Path('/tmp/ig-m1-blind-eval')
RESULTS_DIR = ROOT / 'test-results' / '20261119-m1-epub-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.m1epubbench'
def sha256_bytes(data):
return hashlib.sha256(data).hexdigest()
def file_sha256(path):
return sha256_bytes(Path(path).read_bytes())
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 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_llvm_policy_m1_group_b.json', dst_root / 'config/ig_llvm_policy_m1_group_b.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'),
]
if (ROOT / 'config/ig_diag_events.json').is_file():
copies.append((ROOT / 'config/ig_diag_events.json', dst_root / 'config/ig_diag_events.json'))
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, extra_settings, log_path):
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()[-60:]) + '\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 text_section_bytes(bin_path):
out = subprocess.check_output(['size', str(bin_path)], text=True).strip().splitlines()
return int(out[-1].split()[0])
def uuids_of(path):
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True)
return {line.split()[1] for line in out.splitlines() if line.startswith('UUID:')}
def inspect_app_route2(app_dir, step_tag):
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_epub_objects(include_keybox=False):
names = [
'RDEncryptedEpubResourceProvider',
'RDEpubReaderLauncher',
'RD30EpubCoordinator',
'RD30EpubResourceService',
'RD30EpubFileStore',
'RD30EpubDownloadManager',
'STSEpubWebResourceLoader',
'EpubParser',
'EpubChapter',
'RBCoreEpubLoadController',
]
if include_keybox:
names.extend(['RDEpubKeyBox', 'RDEpubCryptBridge', 'RDSDKeyBox'])
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'
p = cand_sw[0] if cand_sw else (cand_plain if cand_plain.is_file() else None)
found[n] = p
return found
def audit_static_clues(main_bin, include_keybox=False):
objs = find_epub_objects(include_keybox=include_keybox)
patterns = [
b'startiasoft',
b'[RD30Epub]',
b'com.readoor.rd30epub',
b'ERROR:epub',
]
obj_hits = {}
undef_xrefs = {}
for name, p in objs.items():
if not p or not p.is_file():
obj_hits[name] = {'missing': True}
continue
raw = p.read_bytes()
hits = {}
for pat in patterns:
cnt = raw.count(pat)
if cnt > 0:
hits[pat.decode('ascii', errors='replace')] = cnt
obj_hits[name] = hits
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(p)], text=True, errors='replace').splitlines()
tracked = [l.strip() for l in nm_u if any(k in l for k in ('_CC_MD5', 'MD5Hash', 'md5Encrypt', 'StsSimpleCrypt', 'rd_content_decrypt', 'rd_epub_derive'))]
if tracked:
undef_xrefs[name] = sorted(set(tracked))
main_raw = main_bin.read_bytes()
main_counts = {
'main_bin_startiasoft_count': main_raw.count(b'startiasoft'),
'main_bin_RD30Epub_log_count': main_raw.count(b'[RD30Epub]'),
'main_bin_rd30epub_queue_count': main_raw.count(b'com.readoor.rd30epub'),
'main_bin_RDDiag_E31_count': main_raw.count(b'[RDDiag] E-31'),
}
return {
'object_paths': {k: (str(v) if v else None) for k, v in objs.items()},
'object_clue_hits': obj_hits,
'object_xrefs': undef_xrefs,
'main_binary_counts': main_counts,
}
def sign_and_run_bench_on_device(app_dir, work_dir):
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'] = 'M1EpubBench'
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)
installed = False
bench_json = work_dir / 'm1_epub_bench.json'
done_marker = work_dir / 'm1_epub_bench.done'
try:
print(f'[device] installing {staged_app.name} ({BENCH_BUNDLE_ID}) on {DEFAULT_DEVICE}...', flush=True)
subprocess.run([
'xcrun', 'devicectl', 'device', 'install', 'app',
'--device', DEFAULT_DEVICE, '--timeout', '120', str(staged_app),
], check=True)
installed = True
print(f'[device] launching {BENCH_BUNDLE_ID} with IG_M1_EPUB_BENCH=1...', flush=True)
subprocess.run([
'xcrun', 'devicectl', 'device', 'process', 'launch',
'--device', DEFAULT_DEVICE, '--terminate-existing',
'-e', json.dumps({'IG_M1_EPUB_BENCH': '1'}),
BENCH_BUNDLE_ID,
], check=True)
print('[device] polling for Documents/m1_epub_bench.done...', flush=True)
deadline = time.monotonic() + 180.0
got_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/m1_epub_bench.done',
'--destination', str(done_marker),
], capture_output=True, text=True)
if r.returncode == 0 and done_marker.exists():
got_done = True
break
time.sleep(2.0)
if not got_done:
raise RuntimeError('Timed out waiting for Documents/m1_epub_bench.done from device')
subprocess.run([
'xcrun', 'devicectl', 'device', 'copy', 'from',
'--device', DEFAULT_DEVICE,
'--domain-type', 'appDataContainer',
'--domain-identifier', BENCH_BUNDLE_ID,
'--source', 'Documents/m1_epub_bench.json',
'--destination', str(bench_json),
], check=True)
finally:
subprocess.run([
'xcrun', 'devicectl', 'device', 'process', 'terminate',
'--device', DEFAULT_DEVICE, BENCH_BUNDLE_ID,
], capture_output=True)
if installed:
subprocess.run([
'xcrun', 'devicectl', 'device', 'uninstall', 'app',
'--device', DEFAULT_DEVICE, '--timeout', '60', BENCH_BUNDLE_ID,
], check=False)
return json.loads(bench_json.read_text(encoding='utf-8'))
def run_ablation_arm(arm_name, mode, policy_profile, policy_path, seed, blind_sample_name, include_keybox):
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
policy_stamp = hashlib.sha256(policy_path.read_bytes()).hexdigest()[:12]
base_args = [
f'IG_OBF_MODE={mode}',
f'IG_POLICY_PROFILE={policy_profile}',
f'IG_POLICY_STAMP={policy_stamp}',
f'IG_RELEASE_SEED={seed}',
]
# 1. Clean archive (no bench harness compiled in)
t_clean = run_archive(f'{arm_name}_clean', [*base_args, 'IG_SWIFT_EXTRA_FLAGS='], RESULTS_DIR / f'{arm_name}_clean.log')
app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app'
main_bin = app_dir / 'readoor31'
dsyms_dir = ARCHIVE_PATH / 'dSYMs'
assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM')
r2 = inspect_app_route2(app_dir, arm_name)
assert r2['binaries'] == 40 and r2['direct_call_total'] == 0, f'{arm_name} Route2 failed: {r2}'
obf_audit = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text(encoding='utf-8'))
clues = audit_static_clues(main_bin, include_keybox=include_keybox)
bin_bytes = main_bin.stat().st_size
txt_bytes = text_section_bytes(main_bin)
# Save stripped main binary for blind reverse-engineering evaluation
blind_target = BLIND_DIR / blind_sample_name / 'app.bin'
blind_target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(main_bin, blind_target)
arm_data = {
'arm': arm_name,
'mode': mode,
'policy_profile': policy_profile,
'seed': seed,
'clean_archive_elapsed_s': t_clean,
'main_binary_bytes': bin_bytes,
'main_text_bytes': txt_bytes,
'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'),
'module_audits': obf_audit.get('module_audits'),
},
'static_clues': clues,
}
if include_keybox:
# Preserve Round 2 bitcode & verify symbolication for Group C
r2_dir = RESULTS_DIR / 'round2_inputs'
r2_dir.mkdir(parents=True, exist_ok=True)
prov_bc = OBJ_BASE / 'RDEncryptedEpubResourceProvider.bc'
if prov_bc.is_file():
shutil.copy2(prov_bc, r2_dir / 'RDEncryptedEpubResourceProvider.bc')
arm_data['symbolication_c'] = verify_group_c_symbolication(app_dir, dsyms_dir)
if ARCHIVE_PATH.exists():
shutil.rmtree(ARCHIVE_PATH)
# 2. Bench archive (#if IG_ENABLE_M1_BENCH enabled) -> run on physical device
t_bench = run_archive(
f'{arm_name}_bench',
[*base_args, 'IG_SWIFT_EXTRA_FLAGS=-DIG_ENABLE_M1_BENCH'],
RESULTS_DIR / f'{arm_name}_bench.log',
)
bench_work = Path(f'/tmp/ig-m1-dev-{arm_name}')
bench_res = sign_and_run_bench_on_device(app_dir, bench_work)
if bench_work.exists():
shutil.rmtree(bench_work)
if ARCHIVE_PATH.exists():
shutil.rmtree(ARCHIVE_PATH)
if bench_res.get('status') != 'PASS':
raise AssertionError(f'[{arm_name}] Device EPUB bench failed: {bench_res}')
arm_data['bench_archive_elapsed_s'] = t_bench
arm_data['device_bench'] = bench_res
(RESULTS_DIR / f'{arm_name}.json').write_text(json.dumps(arm_data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
return arm_data
def verify_group_c_symbolication(app_dir, dsyms_dir):
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, sub):
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):
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_epub_derive_book_key')
try:
sw_vm = find_sym(main_dwarf, '31RDEncryptedEpubResourceProviderC12resourceData')
except RuntimeError:
sw_vm = find_sym(main_dwarf, '31RDEncryptedEpubResourceProviderC')
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
sw_off = (sw_vm - main_base) + 4
fw_off = (fw_vm - fw_base) + 4
with tempfile.TemporaryDirectory() as td:
p = Path(td)
ips_p = p / 'group_c.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': sw_off},
{'imageIndex': 1, 'imageOffset': fw_off},
],
}],
}) + '\n',
encoding='utf-8',
)
crash_p = p / 'group_c.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 + sw_off)} {hex(main_load)} + {sw_off}\n'
f'2 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',
)
return {
'ips': restore_crash_report.restore_report(ips_p, dsyms_dir),
'crash': restore_crash_report.restore_report(crash_p, dsyms_dir),
}
def run_seed_round2():
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
tc = resolve_opt(require_obf=True)
opt_path = tc['opt_path']
clang = detect_stock_tool('clang')
sdk = detect_sdk_info()['sdk_path']
policy_path = ROOT / 'config/ig_llvm_policy.json'
src_c = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.c'
defender_inc = APP_REPO / 'readoor/3.0/Base/Security/IGDefender'
prov_bc = RESULTS_DIR / 'round2_inputs/RDEncryptedEpubResourceProvider.bc'
assert src_c.is_file() and prov_bc.is_file(), 'Group C must run before seed-round2'
seeds = ['m1_seed_alpha', 'm1_seed_beta', 'm1_seed_gamma']
with tempfile.TemporaryDirectory(prefix='ig-m1-r2-') as td:
work = Path(td)
c_bc = work / 'RDEpubKeyBox.raw.bc'
subprocess.run([
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
'-Os', '-g', '-fvisibility=hidden',
'-I', str(defender_inc), '-I', str(defender_inc / 'include'),
'-emit-llvm', '-c', str(src_c), '-o', str(c_bc),
], check=True)
def text_sha(obj_path):
out = subprocess.check_output(['xcrun', 'otool', '-s', '__TEXT', '__text', '-v', str(obj_path)], text=True)
lines = [l for l in out.splitlines() if re.match(r'^[0-9a-f]+\s+', l)]
return sha256_bytes('\n'.join(lines).encode('utf-8'))
def compile_with_seed(tag, bc_in, pipeline, src_hint, seed, opt_level='-Os'):
obf_bc = work / f'{tag}.obf.bc'
obj_o = work / f'{tag}.o'
audit_p = work / f'{tag}.audit.json'
subprocess.run([
opt_path, f'-passes={pipeline}',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-pass-filter=all',
f'--ig-seed={seed}',
f'--ig-source-path={src_hint}',
f'--ig-audit-out={audit_p}',
str(bc_in), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
opt_level, '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
ll_txt = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True)
bb_names = []
# Extract IR block labels by running opt -S to check physical block permutation too
ir_ll = subprocess.check_output([
opt_path, f'-passes={pipeline}',
f'--ig-policy={policy_path}',
'--ig-mode=full', '--ig-pass-filter=all',
f'--ig-seed={seed}', f'--ig-source-path={src_hint}',
str(bc_in), '-S', '-o', '-',
], text=True)
for l in ir_ll.splitlines():
if l.endswith(':') and not l.startswith(';'):
bb_names.append(l)
return {
'obf_bc_sha256': file_sha256(obf_bc),
'obj_sha256': file_sha256(obj_o),
'text_disasm_sha256': sha256_bytes(ll_txt.encode('utf-8')),
'ir_block_layout_sha256': sha256_bytes('\n'.join(bb_names).encode('utf-8')),
'text_insn_count': len([l for l in ll_txt.splitlines() if re.match(r'^\s*[0-9a-f]+:\s', l)]),
'audit': json.loads(audit_p.read_text(encoding='utf-8')),
'ir_block_sample': bb_names[:30],
}
c_det_1 = compile_with_seed('c_det_1', c_bc, 'ig-obfuscate', str(src_c), 'm1_seed_alpha', '-Os')
c_det_2 = compile_with_seed('c_det_2', c_bc, 'ig-obfuscate', str(src_c), 'm1_seed_alpha', '-Os')
sw_det_1 = compile_with_seed('sw_det_1', prov_bc, 'default<O2>,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', 'm1_seed_alpha', '-O2')
sw_det_2 = compile_with_seed('sw_det_2', prov_bc, 'default<O2>,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', 'm1_seed_alpha', '-O2')
assert c_det_1['obf_bc_sha256'] == c_det_2['obf_bc_sha256'] and c_det_1['obj_sha256'] == c_det_2['obj_sha256']
assert sw_det_1['obf_bc_sha256'] == sw_det_2['obf_bc_sha256'] and sw_det_1['obj_sha256'] == sw_det_2['obj_sha256']
c_seeds = {s: compile_with_seed(f'c_{s}', c_bc, 'ig-obfuscate', str(src_c), s, '-Os') for s in seeds}
sw_seeds = {s: compile_with_seed(f'sw_{s}', prov_bc, 'default<O2>,ig-obfuscate', 'RDEncryptedEpubResourceProvider.swift', s, '-O2') for s in seeds}
assert len({c_seeds[s]['text_disasm_sha256'] for s in seeds}) == len(seeds)
assert len({sw_seeds[s]['text_disasm_sha256'] for s in seeds}) == len(seeds)
report = {
'determinism_same_seed': {
'RDEpubKeyBox_c_obf_bc_match': c_det_1['obf_bc_sha256'] == c_det_2['obf_bc_sha256'],
'RDEpubKeyBox_c_obj_match': c_det_1['obj_sha256'] == c_det_2['obj_sha256'],
'SwiftProvider_obf_bc_match': sw_det_1['obf_bc_sha256'] == sw_det_2['obf_bc_sha256'],
'SwiftProvider_obj_match': sw_det_1['obj_sha256'] == sw_det_2['obj_sha256'],
},
'c_cross_seed_variants': {
s: {k: v for k, v in c_seeds[s].items() if k != 'ir_block_sample'}
for s in seeds
},
'swift_cross_seed_variants': {
s: {k: v for k, v in sw_seeds[s].items() if k != 'ir_block_sample'}
for s in seeds
},
}
(RESULTS_DIR / 'round2_seed_polymorphism.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--phase', required=True, choices=['group-a', 'group-b', 'group-c', 'seed-round2'])
args = parser.parse_args()
if args.phase == 'group-a':
sync_toolchain_and_integrate()
if DD_PATH.exists():
shutil.rmtree(DD_PATH)
run_ablation_arm(
arm_name='group_a_noop',
mode='noop',
policy_profile='default',
policy_path=ROOT / 'config/ig_llvm_policy.json',
seed='m1_seed_alpha',
blind_sample_name='sample_2',
include_keybox=False,
)
elif args.phase == 'group-b':
sync_toolchain_and_integrate()
run_ablation_arm(
arm_name='group_b_flatten_only',
mode='full',
policy_profile='m1_group_b',
policy_path=ROOT / 'config/ig_llvm_policy_m1_group_b.json',
seed='m1_seed_alpha',
blind_sample_name='sample_1',
include_keybox=False,
)
elif args.phase == 'group-c':
sync_toolchain_and_integrate()
run_ablation_arm(
arm_name='group_c_flatten_and_cleanup',
mode='full',
policy_profile='default',
policy_path=ROOT / 'config/ig_llvm_policy.json',
seed='m1_seed_alpha',
blind_sample_name='sample_3',
include_keybox=True,
)
elif args.phase == 'seed-round2':
run_seed_round2()
if __name__ == '__main__':
main()