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:
Executable
+319
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build portable standalone `opt` (with static IGObfuscator passes) from swiftlang/llvm-project."""
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
REPO_ROOT = SCRIPT_DIR.parents[1]
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from ig_toolchain_resolver import ( # noqa: E402
|
||||
DEFAULT_CACHE_ROOT,
|
||||
DEFAULT_GIT_REMOTE,
|
||||
_versioned_dir_name,
|
||||
_write_verified_marker,
|
||||
augmented_tool_env,
|
||||
compute_passes_hash,
|
||||
detect_sdk_info,
|
||||
detect_stock_tool,
|
||||
detect_swift_info,
|
||||
detect_xcode_info,
|
||||
file_sha256,
|
||||
find_cli_tool,
|
||||
host_arch,
|
||||
resolve_llvm_branch_for_swift,
|
||||
smoke_test_opt,
|
||||
verify_portability,
|
||||
)
|
||||
|
||||
LLVM_REMOTE = DEFAULT_GIT_REMOTE
|
||||
DEFAULT_BRANCH = 'auto'
|
||||
DEFAULT_BUILD_WORK = Path('/tmp/ig-llvm-build')
|
||||
|
||||
|
||||
def _emit(log_fn, msg, stream=None):
|
||||
if log_fn is not None:
|
||||
log_fn(msg)
|
||||
else:
|
||||
target = stream if stream is not None else sys.stdout
|
||||
target.write(f'{msg}\n')
|
||||
target.flush()
|
||||
|
||||
|
||||
def run(cmd, cwd=None, check=True, env=None, log_fn=None, log_stream=None):
|
||||
_emit(log_fn, '[build_igopt] ' + ' '.join(map(str, cmd)), stream=log_stream)
|
||||
target = log_stream if log_stream is not None else sys.stdout
|
||||
if log_fn is None:
|
||||
return subprocess.run(list(map(str, cmd)), cwd=cwd, env=env, check=check)
|
||||
proc = subprocess.Popen(
|
||||
list(map(str, cmd)),
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
errors='replace',
|
||||
)
|
||||
tail = []
|
||||
assert proc.stdout is not None
|
||||
for line in proc.stdout:
|
||||
s = line.rstrip('\r\n')
|
||||
if s:
|
||||
tail.append(s)
|
||||
if len(tail) > 60:
|
||||
tail.pop(0)
|
||||
_emit(log_fn, s, stream=target)
|
||||
rc = proc.wait()
|
||||
if check and rc != 0:
|
||||
raise RuntimeError(
|
||||
f'Command failed (rc={rc}): {" ".join(map(str, cmd))}\n' + '\n'.join(tail[-30:])
|
||||
)
|
||||
return subprocess.CompletedProcess(cmd, rc)
|
||||
|
||||
|
||||
def _prepare_llvm_source(src_dir, branch, remote, env, log_fn=None, log_stream=None):
|
||||
src_p = Path(src_dir)
|
||||
if (src_p / '.git').exists():
|
||||
run(['git', 'remote', 'set-url', 'origin', remote], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run(['git', 'fetch', '--depth', '1', 'origin', branch], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run(['git', 'checkout', '-f', 'FETCH_HEAD'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run(['git', 'sparse-checkout', 'set', 'llvm', 'cmake', 'third-party'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run(['git', 'clean', '-fdx'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
return
|
||||
|
||||
src_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
run([
|
||||
'git', 'clone', '--depth', '1', '--filter=blob:none', '--sparse',
|
||||
'--branch', branch, remote, str(src_p),
|
||||
], env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run(['git', 'sparse-checkout', 'set', 'llvm', 'cmake', 'third-party'], cwd=src_p, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
|
||||
|
||||
def build_opt(
|
||||
branch=DEFAULT_BRANCH,
|
||||
work_dir=DEFAULT_BUILD_WORK,
|
||||
keep_work=False,
|
||||
jobs=None,
|
||||
git_remote=None,
|
||||
cache_dir=None,
|
||||
mirror_dir=None,
|
||||
passes_dir=None,
|
||||
developer_dir=None,
|
||||
update_manifest=True,
|
||||
log_fn=None,
|
||||
log_stream=None,
|
||||
):
|
||||
env = augmented_tool_env()
|
||||
if developer_dir:
|
||||
env['DEVELOPER_DIR'] = str(developer_dir)
|
||||
|
||||
cmake_bin = find_cli_tool('cmake', env)
|
||||
if not cmake_bin:
|
||||
raise RuntimeError('cmake not found on PATH (/opt/homebrew/bin, /usr/local/bin)')
|
||||
ninja_bin = find_cli_tool('ninja', env)
|
||||
|
||||
xc = detect_xcode_info(developer_dir)
|
||||
sdk = detect_sdk_info(developer_dir=developer_dir)
|
||||
swift_info = detect_swift_info(developer_dir=developer_dir)
|
||||
arch = host_arch()
|
||||
swiftlang_ver = swift_info.get('raw', '')
|
||||
|
||||
remote = (git_remote or os.environ.get('IG_LLVM_GIT_MIRROR') or LLVM_REMOTE).strip()
|
||||
resolved_branch = (
|
||||
resolve_llvm_branch_for_swift(swift_info, xcode_info=xc, git_remote=remote)
|
||||
if not branch or branch == 'auto'
|
||||
else branch
|
||||
)
|
||||
|
||||
pdir = Path(passes_dir).resolve() if passes_dir is not None else (REPO_ROOT / 'llvm_passes')
|
||||
if not (pdir / 'CMakeLists.txt').is_file():
|
||||
raise FileNotFoundError(f'Missing llvm_passes/CMakeLists.txt at {pdir}')
|
||||
passes_hash = compute_passes_hash(pdir)
|
||||
|
||||
work = Path(work_dir).resolve()
|
||||
root_cache = Path(os.path.expanduser(str(cache_dir or os.environ.get('IG_TOOLCHAIN_CACHE_DIR') or DEFAULT_CACHE_ROOT)))
|
||||
root_cache.mkdir(parents=True, exist_ok=True)
|
||||
job_count = int(jobs or os.cpu_count() or 8)
|
||||
|
||||
use_persistent_mirror = mirror_dir is not None
|
||||
src_dir = Path(mirror_dir).resolve() if use_persistent_mirror else (work / 'llvm-project')
|
||||
temp_build_parent = None
|
||||
if use_persistent_mirror and not keep_work:
|
||||
build_dir = Path(tempfile.mkdtemp(prefix='ig-llvm-cmake-'))
|
||||
temp_build_parent = build_dir
|
||||
else:
|
||||
build_dir = work / 'build'
|
||||
|
||||
try:
|
||||
_prepare_llvm_source(src_dir, resolved_branch, remote, env, log_fn=log_fn, log_stream=log_stream)
|
||||
|
||||
generator_args = ['-G', 'Ninja', f'-DCMAKE_MAKE_PROGRAM={ninja_bin}'] if ninja_bin else ['-G', 'Unix Makefiles']
|
||||
cmake_args = [
|
||||
cmake_bin, *generator_args,
|
||||
'-S', str(src_dir / 'llvm'),
|
||||
'-B', str(build_dir),
|
||||
'-DCMAKE_BUILD_TYPE=Release',
|
||||
'-DCMAKE_OSX_ARCHITECTURES=arm64',
|
||||
'-DCMAKE_OSX_DEPLOYMENT_TARGET=13.0',
|
||||
'-DCMAKE_IGNORE_PREFIX_PATH=/opt/homebrew;/usr/local',
|
||||
'-DLLVM_TARGETS_TO_BUILD=AArch64',
|
||||
'-DLLVM_ENABLE_ZSTD=OFF',
|
||||
'-DLLVM_ENABLE_TERMINFO=OFF',
|
||||
'-DLLVM_ENABLE_LIBXML2=OFF',
|
||||
'-DLLVM_ENABLE_LIBEDIT=OFF',
|
||||
'-DLLVM_ENABLE_HTTPLIB=OFF',
|
||||
'-DLLVM_ENABLE_CURL=OFF',
|
||||
'-DLLVM_INCLUDE_TESTS=OFF',
|
||||
'-DLLVM_INCLUDE_BENCHMARKS=OFF',
|
||||
'-DLLVM_INCLUDE_EXAMPLES=OFF',
|
||||
'-DLLVM_INCLUDE_DOCS=OFF',
|
||||
'-DLLVM_INCLUDE_UTILS=OFF',
|
||||
'-DLLVM_BUILD_UTILS=OFF',
|
||||
'-DLLVM_EXTERNAL_PROJECTS=IGObfuscator',
|
||||
f'-DLLVM_EXTERNAL_IGOBFUSCATOR_SOURCE_DIR={pdir}',
|
||||
'-DLLVM_IGOBFUSCATOR_LINK_INTO_TOOLS=ON',
|
||||
]
|
||||
run(cmake_args, env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
run([cmake_bin, '--build', str(build_dir), '--target', 'opt', f'-j{job_count}'], env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
|
||||
built_opt = build_dir / 'bin' / 'opt'
|
||||
if not built_opt.is_file():
|
||||
raise FileNotFoundError(f'opt was not produced at {built_opt}')
|
||||
|
||||
llvm_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=src_dir, env=env, text=True).strip()
|
||||
cmake_ver_line = subprocess.check_output([cmake_bin, '--version'], env=env, text=True).splitlines()[0].strip()
|
||||
|
||||
target_name = _versioned_dir_name(xc['xcode_build'], arch, passes_hash)
|
||||
tc_dir = root_cache / target_name
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='.igopt-stage-', dir=root_cache) as td:
|
||||
stage = Path(td) / 'stage'
|
||||
dist_bin_dir = stage / 'bin'
|
||||
dist_bin_dir.mkdir(parents=True, exist_ok=True)
|
||||
stage_opt = dist_bin_dir / 'opt'
|
||||
|
||||
run(['strip', '-x', str(built_opt), '-o', str(stage_opt)], env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
stage_opt.chmod(0o755)
|
||||
run(['codesign', '--force', '--sign', '-', str(stage_opt)], env=env, log_fn=log_fn, log_stream=log_stream)
|
||||
|
||||
verify_portability(stage_opt)
|
||||
smoke_test_opt(stage_opt, developer_dir=developer_dir)
|
||||
|
||||
opt_sha = file_sha256(stage_opt)
|
||||
meta_out = {
|
||||
'schema_version': 1,
|
||||
'xcode_version': xc['xcode_version'],
|
||||
'xcode_build': xc['xcode_build'],
|
||||
'sdk_version': sdk['sdk_version'],
|
||||
'swift_version': swift_info.get('swift_version', ''),
|
||||
'swiftlang_version': swift_info.get('swiftlang_version', ''),
|
||||
'swift_major_minor': swift_info.get('swift_major_minor', ''),
|
||||
'arch': arch,
|
||||
'passes_hash': passes_hash,
|
||||
'opt_sha256': opt_sha,
|
||||
'source_mode': 'built',
|
||||
'llvm_branch': resolved_branch,
|
||||
'llvm_commit': llvm_commit,
|
||||
'cmake_version': cmake_ver_line,
|
||||
'smoke_passed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
}
|
||||
(stage / 'meta.json').write_text(json.dumps(meta_out, indent=2) + '\n', encoding='utf-8')
|
||||
_write_verified_marker(stage_opt, opt_sha)
|
||||
|
||||
if tc_dir.exists():
|
||||
shutil.rmtree(tc_dir)
|
||||
stage.rename(tc_dir)
|
||||
|
||||
dist_opt = tc_dir / 'bin' / 'opt'
|
||||
_emit(log_fn, f'[build_igopt] Installed opt ({opt_sha}) -> {dist_opt}', stream=log_stream)
|
||||
|
||||
if update_manifest:
|
||||
legacy_dir = root_cache / f"{xc['xcode_build']}-{arch}"
|
||||
if legacy_dir != tc_dir:
|
||||
(legacy_dir / 'bin').mkdir(parents=True, exist_ok=True)
|
||||
legacy_opt = legacy_dir / 'bin' / 'opt'
|
||||
shutil.copy2(dist_opt, legacy_opt)
|
||||
legacy_opt.chmod(0o755)
|
||||
_write_verified_marker(legacy_opt, opt_sha)
|
||||
|
||||
bundles_dir = root_cache.parent / 'bundles'
|
||||
bundles_dir.mkdir(parents=True, exist_ok=True)
|
||||
bundle_path = bundles_dir / f"igopt-{xc['xcode_build']}-{arch}.tar.gz"
|
||||
with tarfile.open(bundle_path, 'w:gz') as tf:
|
||||
tf.add(dist_opt, arcname='bin/opt')
|
||||
bundle_sha = file_sha256(bundle_path)
|
||||
|
||||
manifest_path = REPO_ROOT / 'config' / 'toolchain_manifest.json'
|
||||
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
manifest = {'schema_version': 2, 'toolchains': {}}
|
||||
if manifest_path.is_file():
|
||||
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
||||
manifest.setdefault('toolchains', {})[f"{xc['xcode_build']}:{arch}"] = {
|
||||
'xcode_version': xc['xcode_version'],
|
||||
'xcode_build': xc['xcode_build'],
|
||||
'sdk_version': sdk['sdk_version'],
|
||||
'host_arch': arch,
|
||||
'swiftlang_version': swiftlang_ver,
|
||||
'passes_hash': passes_hash,
|
||||
'llvm_branch': resolved_branch,
|
||||
'llvm_commit': llvm_commit,
|
||||
'cmake_version': cmake_ver_line,
|
||||
'opt_sha256': opt_sha,
|
||||
'bundle_path': f"~/.cache/iosguard/bundles/{bundle_path.name}",
|
||||
'bundle_sha256': bundle_sha,
|
||||
}
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
|
||||
_emit(log_fn, f'[build_igopt] Updated manifest: {manifest_path}', stream=log_stream)
|
||||
|
||||
return {
|
||||
'opt_path': str(dist_opt),
|
||||
'opt_sha256': opt_sha,
|
||||
'target_dir': str(tc_dir),
|
||||
'llvm_branch': resolved_branch,
|
||||
'llvm_commit': llvm_commit,
|
||||
'meta': meta_out,
|
||||
}
|
||||
finally:
|
||||
if not keep_work:
|
||||
if temp_build_parent is not None and temp_build_parent.exists():
|
||||
_emit(log_fn, f'[build_igopt] Cleaning temporary CMake build dir {temp_build_parent}...', stream=log_stream)
|
||||
shutil.rmtree(temp_build_parent, ignore_errors=True)
|
||||
elif not use_persistent_mirror and work.exists():
|
||||
_emit(log_fn, f'[build_igopt] Cleaning temporary LLVM build dir {work} to reclaim disk space...', stream=log_stream)
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--branch', default=DEFAULT_BRANCH)
|
||||
parser.add_argument('--work-dir', type=Path, default=DEFAULT_BUILD_WORK)
|
||||
parser.add_argument('--keep-work', action='store_true')
|
||||
parser.add_argument('--jobs', type=int, default=os.cpu_count() or 8)
|
||||
parser.add_argument('--git-remote', default=None)
|
||||
parser.add_argument('--cache-dir', type=Path, default=None)
|
||||
parser.add_argument('--mirror-dir', type=Path, default=None)
|
||||
parser.add_argument('--no-update-manifest', action='store_true')
|
||||
args = parser.parse_args()
|
||||
|
||||
build_opt(
|
||||
branch=args.branch,
|
||||
work_dir=args.work_dir,
|
||||
keep_work=args.keep_work,
|
||||
jobs=args.jobs,
|
||||
git_remote=args.git_remote,
|
||||
cache_dir=args.cache_dir,
|
||||
mirror_dir=args.mirror_dir,
|
||||
update_manifest=(not args.no_update_manifest),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
Executable
+1385
File diff suppressed because it is too large
Load Diff
Executable
+493
@@ -0,0 +1,493 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Execute Milestone 0 `readoor31` Release Archive verification & non-clean rollback matrix."""
|
||||
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'
|
||||
|
||||
sys.path.insert(0, str(TOOLS_CRASH))
|
||||
sys.path.insert(0, str(TOOLS_MACHO))
|
||||
|
||||
import restore_crash_report # noqa: E402
|
||||
from verify_baseline import scan # noqa: E402
|
||||
|
||||
DD_PATH = Path('/tmp/ig-m0-dd')
|
||||
ARCHIVE_DIR = Path('/tmp/ig-m0-archives')
|
||||
RESULTS_DIR = ROOT / 'test-results' / '20261119-m0-prototype-verification'
|
||||
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'
|
||||
ARCHIVE_PATH = ARCHIVE_DIR / 'readoor31.xcarchive'
|
||||
|
||||
|
||||
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 is_bitcode_wrapper(path):
|
||||
try:
|
||||
with Path(path).open('rb') as f:
|
||||
return f.read(4) in (b'\xde\xc0\x17\x0b', b'BC\xc0\xde')
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def reconstruct_step_from_artifacts(step_tag, log_name):
|
||||
bins_path = RESULTS_DIR / step_tag / 'route2' / f'{step_tag}-binaries.json'
|
||||
bins_data = json.loads(bins_path.read_text(encoding='utf-8'))
|
||||
main_info = bins_data['readoor31']
|
||||
sl = main_info['slices'][0]
|
||||
ig_ld_lines = []
|
||||
log_path = RESULTS_DIR / log_name
|
||||
if log_path.is_file():
|
||||
for line in log_path.read_text(encoding='utf-8', errors='replace').splitlines():
|
||||
if '[IGRoute2] ld OK' in line or '[IGRoute2] frameworks audit OK' in line:
|
||||
ig_ld_lines.append(line.strip())
|
||||
return {
|
||||
'reconstructed_from_artifacts': True,
|
||||
'main_binary_bytes': main_info['size'],
|
||||
'main_text_bytes': sl['segments']['__TEXT']['filesize'],
|
||||
'route2': {
|
||||
'binaries': len(bins_data),
|
||||
'direct_call_total': sum(
|
||||
int(s.get('total', 0))
|
||||
for b in bins_data.values()
|
||||
for s in b.get('slices', [])
|
||||
),
|
||||
'direct_call_counts': sl.get('counts', {}),
|
||||
},
|
||||
'linker_and_phase_log': ig_ld_lines,
|
||||
}
|
||||
|
||||
|
||||
def compact_large_logs(results_dir):
|
||||
prefixes = ('CompileC ', 'SwiftCompile ', 'Ld ', 'PhaseScriptExecution ', 'CreateBuildDirectory ')
|
||||
for p in sorted(results_dir.glob('m0_*.log')):
|
||||
if p.name.endswith('_excerpt.log'):
|
||||
continue
|
||||
if p.stat().st_size <= 1_000_000:
|
||||
continue
|
||||
lines = p.read_text(encoding='utf-8', errors='replace').splitlines()
|
||||
counts = {k.strip(): 0 for k in prefixes}
|
||||
ig_lines = []
|
||||
for ln in lines:
|
||||
for k in prefixes:
|
||||
if ln.startswith(k):
|
||||
counts[k.strip()] += 1
|
||||
break
|
||||
if '[IGRoute2]' in ln or '[IGObf]' in ln or 'IG_OBF' in ln or 'ARCHIVE SUCCEEDED' in ln:
|
||||
ig_lines.append(ln)
|
||||
tail = lines[-80:] if len(lines) > 80 else lines
|
||||
excerpt = [
|
||||
f'# Excerpt generated from {p.name} ({p.stat().st_size} bytes, {len(lines)} lines)',
|
||||
'step_counts: ' + json.dumps(counts),
|
||||
'',
|
||||
'## IG Lines',
|
||||
*ig_lines,
|
||||
'',
|
||||
'## Tail (last 80 lines)',
|
||||
*tail,
|
||||
'',
|
||||
]
|
||||
p.with_name(p.stem + '_excerpt.log').write_text('\n'.join(excerpt), encoding='utf-8')
|
||||
p.unlink()
|
||||
|
||||
|
||||
def text_section_size(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 find_symbol_range(dsym_dwarf_path, substring):
|
||||
"""Find (sym_name, start_vm, end_vm) from unstripped dSYM DWARF binary."""
|
||||
out = subprocess.check_output(['xcrun', 'nm', '-n', str(dsym_dwarf_path)], text=True).splitlines()
|
||||
entries = []
|
||||
for line in out:
|
||||
parts = line.strip().split(maxsplit=2)
|
||||
if len(parts) == 3 and parts[1].lower() == 't':
|
||||
try:
|
||||
entries.append((int(parts[0], 16), parts[2]))
|
||||
except ValueError:
|
||||
pass
|
||||
for idx, (addr, name) in enumerate(entries):
|
||||
if substring in name:
|
||||
end_addr = entries[idx + 1][0] if idx + 1 < len(entries) else (addr + 0x400)
|
||||
return name, addr, max(end_addr, addr + 16)
|
||||
return None, None, None
|
||||
|
||||
|
||||
def disassemble_range(bin_path, start_addr, end_addr):
|
||||
out = subprocess.check_output([
|
||||
'xcrun', 'llvm-objdump', '--disassemble',
|
||||
f'--start-address={hex(start_addr)}',
|
||||
f'--stop-address={hex(end_addr)}',
|
||||
str(bin_path),
|
||||
], text=True)
|
||||
lines = [l for l in out.splitlines() if re.match(r'^\s*[0-9a-f]+:\s', l)]
|
||||
return out, lines
|
||||
|
||||
|
||||
def text_vmaddr(bin_path):
|
||||
out = subprocess.check_output(['otool', '-l', str(bin_path)], 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
|
||||
|
||||
|
||||
def run_archive(step_name, extra_settings, log_path):
|
||||
free_gb = check_disk_budget()
|
||||
print(f'\n=== [{step_name}] disk_free={free_gb}GB args={extra_settings} ===', flush=True)
|
||||
if ARCHIVE_PATH.exists():
|
||||
shutil.rmtree(ARCHIVE_PATH)
|
||||
ARCHIVE_DIR.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)
|
||||
log_path.write_text(res.stdout + '\n' + res.stderr, encoding='utf-8')
|
||||
if res.returncode != 0:
|
||||
tail = '\n'.join((res.stdout + '\n' + res.stderr).splitlines()[-80:])
|
||||
raise RuntimeError(f'[{step_name}] xcodebuild archive failed (rc={res.returncode}):\n{tail}')
|
||||
return elapsed, res.stdout + '\n' + res.stderr
|
||||
|
||||
|
||||
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
|
||||
wl_path = app_dir / 'RDKnownImages.plist'
|
||||
wl = plistlib.loads(wl_path.read_bytes()) if wl_path.is_file() else {}
|
||||
known = [e['name'] if isinstance(e, dict) else str(e) for e in wl.get('known_images', [])]
|
||||
return {
|
||||
'binaries': len(binaries),
|
||||
'direct_call_total': total,
|
||||
'direct_call_counts': counts,
|
||||
'whitelist_count': len(known),
|
||||
'has_ig_archive_guard': ('RDCoreIO' in known) or ('IGArchiveGuard' in known),
|
||||
}
|
||||
|
||||
|
||||
def check_object_pair(swift_obj, oc_obj):
|
||||
def inspect_o(p):
|
||||
if not p or not p.is_file():
|
||||
return {'exists': False}
|
||||
data = p.read_bytes()
|
||||
nm_out = subprocess.check_output(['xcrun', 'nm', str(p)], text=True)
|
||||
dec_syms = [l.split()[-1] for l in nm_out.splitlines() if '__ig_dec_str_' in l]
|
||||
has_nul_plain = (b'\x00DYLD_INSERT_LIBRARIES\x00' in data) or data.startswith(b'DYLD_INSERT_LIBRARIES\x00')
|
||||
return {
|
||||
'exists': True,
|
||||
'path': str(p),
|
||||
'has_plaintext_dyld_cstr': has_nul_plain,
|
||||
'ig_dec_symbols': dec_syms,
|
||||
}
|
||||
|
||||
return {'swift': inspect_o(swift_obj), 'objc': inspect_o(oc_obj)}
|
||||
|
||||
|
||||
def find_target_objects():
|
||||
oc_obj = OBJ_BASE / 'STSJailbreakDetectTool.o'
|
||||
swift_machos = list((OBJ_BASE / 'ig-swift-macho').glob('*RDInjectionDetector*.o'))
|
||||
swift_macho = swift_machos[0] if swift_machos else (OBJ_BASE / 'RDInjectionDetector.o')
|
||||
return swift_macho, oc_obj
|
||||
|
||||
|
||||
def verify_readoor_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'
|
||||
sszip_bin = app_dir / 'Frameworks' / 'SSZipArchive.framework' / 'SSZipArchive'
|
||||
|
||||
main_uid = next(iter(uuids_of(main_bin)))
|
||||
if (dsyms_dir / 'RDCoreIO.framework.dSYM').is_dir() and guard_bin.is_file():
|
||||
fw_bin = guard_bin
|
||||
fw_dwarf = dsyms_dir / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO'
|
||||
fw_sym, fw_vm, _ = find_symbol_range(fw_dwarf, 'rd_io_chk')
|
||||
if not fw_sym:
|
||||
fw_sym, fw_vm, _ = find_symbol_range(fw_dwarf, 'rd_a')
|
||||
else:
|
||||
fw_bin = sszip_bin
|
||||
fw_sym, fw_vm, _ = find_symbol_range(fw_bin, 'unzip')
|
||||
fw_uid = next(iter(uuids_of(fw_bin)))
|
||||
|
||||
_, swift_vm, _ = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
_, oc_vm, _ = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
|
||||
main_base_static = text_vmaddr(main_bin)
|
||||
fw_base_static = text_vmaddr(fw_bin)
|
||||
main_load = 0x104000000
|
||||
fw_load = 0x109000000
|
||||
main_off = (swift_vm - main_base_static) + 4
|
||||
oc_off = (oc_vm - main_base_static) + 4
|
||||
fw_off = (fw_vm - fw_base_static) + 4
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td)
|
||||
ips_p = p / 'readoor_m0.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': fw_bin.name, 'arch': 'arm64', 'path': f'/private/var/readoor31.app/Frameworks/{fw_bin.name}.framework/{fw_bin.name}'},
|
||||
],
|
||||
'threads': [{
|
||||
'triggered': True,
|
||||
'frames': [
|
||||
{'imageIndex': 0, 'imageOffset': main_off},
|
||||
{'imageIndex': 0, 'imageOffset': oc_off},
|
||||
{'imageIndex': 1, 'imageOffset': fw_off},
|
||||
],
|
||||
}],
|
||||
}) + '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
crash_p = p / 'readoor_m0.crash'
|
||||
crash_p.write_text(
|
||||
'Thread 0 Crashed:\n'
|
||||
f'0 readoor31 {hex(main_load + main_off)} {hex(main_load)} + {main_off}\n'
|
||||
f'1 readoor31 {hex(main_load + oc_off)} {hex(main_load)} + {oc_off}\n'
|
||||
f'2 {fw_bin.name} {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)} {fw_bin.name} arm64 <{fw_uid}> /private/var/readoor31.app/Frameworks/{fw_bin.name}.framework/{fw_bin.name}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
res_ips = restore_crash_report.restore_report(ips_p, dsyms_dir)
|
||||
res_crash = restore_crash_report.restore_report(crash_p, dsyms_dir)
|
||||
return {'ips': res_ips, 'crash': res_crash}
|
||||
|
||||
|
||||
def main():
|
||||
resume_3a = '--resume-from-3a' in sys.argv
|
||||
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
if not resume_3a and DD_PATH.exists():
|
||||
shutil.rmtree(DD_PATH)
|
||||
|
||||
summary = {'steps': {}}
|
||||
app_dir = ARCHIVE_PATH / 'Products/Applications/readoor31.app'
|
||||
main_bin = app_dir / 'readoor31'
|
||||
dsyms_dir = ARCHIVE_PATH / 'dSYMs'
|
||||
main_dwarf = dsyms_dir / 'readoor31.app.dSYM/Contents/Resources/DWARF/readoor31'
|
||||
sw_insns_1 = None
|
||||
oc_insns_1 = None
|
||||
|
||||
if resume_3a:
|
||||
assert ARCHIVE_PATH.is_dir() and DD_PATH.is_dir(), 'Cannot resume from 3a without existing archive and DerivedData'
|
||||
summary['steps']['M0-1'] = reconstruct_step_from_artifacts('M0-1', 'm0_1.log')
|
||||
m0_2_rec = reconstruct_step_from_artifacts('M0-2', 'm0_2.log')
|
||||
m0_2_rec['text_delta_vs_m0_1'] = m0_2_rec['main_text_bytes'] - summary['steps']['M0-1']['main_text_bytes']
|
||||
m0_2_rec['binary_delta_vs_m0_1'] = m0_2_rec['main_binary_bytes'] - summary['steps']['M0-1']['main_binary_bytes']
|
||||
summary['steps']['M0-2'] = m0_2_rec
|
||||
t3a = 0.0
|
||||
else:
|
||||
# M0-1: Stock baseline + Route 2
|
||||
t1, log1 = run_archive('M0-1', ['IG_OBF_MODE=off', 'IG_SWIFT_LTO_BY_ALL_OFF_0=NO'], RESULTS_DIR / 'm0_1.log')
|
||||
sw_sym, sw_s1, sw_e1 = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
oc_sym, oc_s1, oc_e1 = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
assert sw_sym and oc_sym, f'Missing target symbols in dSYM: sw={sw_sym}, oc={oc_sym}'
|
||||
_, sw_insns_1 = disassemble_range(main_bin, sw_s1, sw_e1)
|
||||
_, oc_insns_1 = disassemble_range(main_bin, oc_s1, oc_e1)
|
||||
r2_1 = inspect_app_route2(app_dir, 'M0-1')
|
||||
assert r2_1['binaries'] == 40 and r2_1['direct_call_total'] == 0, f'M0-1 Route2 failed: {r2_1}'
|
||||
summary['steps']['M0-1'] = {
|
||||
'elapsed_s': t1,
|
||||
'main_text_bytes': text_section_size(main_bin),
|
||||
'route2': r2_1,
|
||||
'swift_symbol': sw_sym,
|
||||
'oc_symbol': oc_sym,
|
||||
'swift_insn_count': len(sw_insns_1),
|
||||
'oc_insn_count': len(oc_insns_1),
|
||||
'obf_audit': json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text()),
|
||||
}
|
||||
|
||||
# M0-2: Conversion-chain No-Op Control
|
||||
t2, log2 = run_archive('M0-2', ['IG_OBF_MODE=noop'], RESULTS_DIR / 'm0_2.log')
|
||||
r2_2 = inspect_app_route2(app_dir, 'M0-2')
|
||||
audit_2 = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text())
|
||||
assert audit_2['converted_swift_count'] > 0 and audit_2['objc_audited_count'] > 0
|
||||
assert audit_2['total_flattened'] == 0 and audit_2['total_strings_encrypted'] == 0
|
||||
assert r2_2['binaries'] == 40 and r2_2['direct_call_total'] == 0
|
||||
assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM')
|
||||
_, sw_s2, sw_e2 = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
_, oc_s2, oc_e2 = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
_, sw_insns_2 = disassemble_range(main_bin, sw_s2, sw_e2)
|
||||
_, oc_insns_2 = disassemble_range(main_bin, oc_s2, oc_e2)
|
||||
summary['steps']['M0-2'] = {
|
||||
'elapsed_s': t2,
|
||||
'main_text_bytes': text_section_size(main_bin),
|
||||
'text_delta_vs_m0_1': text_section_size(main_bin) - summary['steps']['M0-1']['main_text_bytes'],
|
||||
'swift_insn_count': len(sw_insns_2),
|
||||
'oc_insn_count': len(oc_insns_2),
|
||||
'route2': r2_2,
|
||||
'obf_audit': {k: audit_2[k] for k in ('mode', 'expected_swift_count', 'converted_swift_count', 'skipped_swift_count', 'objc_audited_count', 'total_flattened', 'total_strings_encrypted')},
|
||||
}
|
||||
|
||||
# M0-3a: Full single-target Swift + OC obfuscation (NO clean)
|
||||
t3a, log3a = run_archive('M0-3a', ['IG_OBF_MODE=full'], RESULTS_DIR / 'm0_3a.log')
|
||||
|
||||
r2_3a = inspect_app_route2(app_dir, 'M0-3a')
|
||||
audit_3a = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text())
|
||||
_, sw_s3a, sw_e3a = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
_, oc_s3a, oc_e3a = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
sw_dis_3a, sw_insns_3a = disassemble_range(main_bin, sw_s3a, sw_e3a)
|
||||
oc_dis_3a, oc_insns_3a = disassemble_range(main_bin, oc_s3a, oc_e3a)
|
||||
(RESULTS_DIR / 'm0_3a_swift_disasm.txt').write_text(sw_dis_3a, encoding='utf-8')
|
||||
(RESULTS_DIR / 'm0_3a_oc_disasm.txt').write_text(oc_dis_3a, encoding='utf-8')
|
||||
sw_o_3a, oc_o_3a = find_target_objects()
|
||||
objs_3a = check_object_pair(sw_o_3a, oc_o_3a)
|
||||
sym_3a = verify_readoor_symbolication(app_dir, dsyms_dir)
|
||||
assert r2_3a['binaries'] == 40 and r2_3a['direct_call_total'] == 0
|
||||
assert uuids_of(main_bin) == uuids_of(dsyms_dir / 'readoor31.app.dSYM')
|
||||
assert len(sw_insns_3a) > 0 and len(oc_insns_3a) > 0
|
||||
if sw_insns_1 is not None and oc_insns_1 is not None:
|
||||
assert len(sw_insns_3a) > len(sw_insns_1) and len(oc_insns_3a) > len(oc_insns_1)
|
||||
assert not objs_3a['swift']['has_plaintext_dyld_cstr'] and objs_3a['swift']['ig_dec_symbols']
|
||||
assert not objs_3a['objc']['has_plaintext_dyld_cstr'] and objs_3a['objc']['ig_dec_symbols']
|
||||
summary['steps']['M0-3a_full'] = {
|
||||
'elapsed_s': t3a,
|
||||
'resumed_from_3a_archive': resume_3a,
|
||||
'main_binary_bytes': main_bin.stat().st_size,
|
||||
'main_text_bytes': text_section_size(main_bin),
|
||||
'route2': r2_3a,
|
||||
'swift_insn_count': len(sw_insns_3a),
|
||||
'oc_insn_count': len(oc_insns_3a),
|
||||
'target_objects': objs_3a,
|
||||
'obf_audit': audit_3a,
|
||||
'symbolication': sym_3a,
|
||||
}
|
||||
|
||||
# M0-3b: str rollback (NO clean!)
|
||||
t3b, log3b = run_archive('M0-3b', ['IG_OBF_MODE=str'], RESULTS_DIR / 'm0_3b.log')
|
||||
r2_3b = inspect_app_route2(app_dir, 'M0-3b')
|
||||
audit_3b = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text())
|
||||
_, sw_s3b, sw_e3b = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
_, oc_s3b, oc_e3b = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
_, sw_insns_3b = disassemble_range(main_bin, sw_s3b, sw_e3b)
|
||||
_, oc_insns_3b = disassemble_range(main_bin, oc_s3b, oc_e3b)
|
||||
sw_o_3b, oc_o_3b = find_target_objects()
|
||||
objs_3b = check_object_pair(sw_o_3b, oc_o_3b)
|
||||
assert audit_3b['total_flattened'] == 0 and audit_3b['total_strings_encrypted'] >= 2
|
||||
assert len(sw_insns_3b) < len(sw_insns_3a) and len(oc_insns_3b) < len(oc_insns_3a)
|
||||
assert not objs_3b['swift']['has_plaintext_dyld_cstr'] and objs_3b['swift']['ig_dec_symbols']
|
||||
assert not objs_3b['objc']['has_plaintext_dyld_cstr'] and objs_3b['objc']['ig_dec_symbols']
|
||||
assert r2_3b['binaries'] == 40 and r2_3b['direct_call_total'] == 0
|
||||
summary['steps']['M0-3b_str'] = {
|
||||
'elapsed_s': t3b,
|
||||
'compile_c_ran': 'CompileC ' in log3b,
|
||||
'ld_ran': 'Ld ' in log3b,
|
||||
'swift_insn_count': len(sw_insns_3b),
|
||||
'oc_insn_count': len(oc_insns_3b),
|
||||
'target_objects': objs_3b,
|
||||
'obf_audit': {k: audit_3b[k] for k in ('mode', 'total_flattened', 'total_strings_encrypted', 'required_targets')},
|
||||
'route2': r2_3b,
|
||||
}
|
||||
|
||||
# M0-3c: off rollback (NO clean!)
|
||||
t3c, log3c = run_archive('M0-3c', ['IG_OBF_MODE=off'], RESULTS_DIR / 'm0_3c.log')
|
||||
r2_3c = inspect_app_route2(app_dir, 'M0-3c')
|
||||
audit_3c = json.loads((AUDIT_DIR / 'ig_obfuscation_audit.json').read_text())
|
||||
_, sw_s3c, sw_e3c = find_symbol_range(main_dwarf, '32hasSuspiciousDyldInsertLibraries')
|
||||
_, oc_s3c, oc_e3c = find_symbol_range(main_dwarf, '+[STSJailbreakDetectTool detectCurrentDeviceIsJailbroken]')
|
||||
_, sw_insns_3c = disassemble_range(main_bin, sw_s3c, sw_e3c)
|
||||
_, oc_insns_3c = disassemble_range(main_bin, oc_s3c, oc_e3c)
|
||||
sw_o_3c, oc_o_3c = find_target_objects()
|
||||
objs_3c = check_object_pair(sw_o_3c, oc_o_3c)
|
||||
assert audit_3c['total_flattened'] == 0 and audit_3c['total_strings_encrypted'] == 0
|
||||
assert len(sw_insns_3a) > len(sw_insns_3c) and len(oc_insns_3a) > len(oc_insns_3c)
|
||||
assert objs_3c['swift']['has_plaintext_dyld_cstr'] and not objs_3c['swift']['ig_dec_symbols']
|
||||
assert objs_3c['objc']['has_plaintext_dyld_cstr'] and not objs_3c['objc']['ig_dec_symbols']
|
||||
assert r2_3c['binaries'] == 40 and r2_3c['direct_call_total'] == 0
|
||||
summary['steps']['M0-3c_off'] = {
|
||||
'elapsed_s': t3c,
|
||||
'compile_c_ran': 'CompileC ' in log3c,
|
||||
'ld_ran': 'Ld ' in log3c,
|
||||
'swift_insn_count': len(sw_insns_3c),
|
||||
'oc_insn_count': len(oc_insns_3c),
|
||||
'target_objects': objs_3c,
|
||||
'obf_audit': {k: audit_3c[k] for k in ('mode', 'total_flattened', 'total_strings_encrypted')},
|
||||
'route2': r2_3c,
|
||||
}
|
||||
|
||||
# M0-3d: IG_ALL_GUARD_OFF=1 total circuit breaker (NO clean!)
|
||||
t3d, log3d = run_archive('M0-3d', ['IG_ALL_GUARD_OFF=1'], RESULTS_DIR / 'm0_3d.log')
|
||||
r2_3d = inspect_app_route2(app_dir, 'M0-3d')
|
||||
swift_native_o = OBJ_BASE / 'RDInjectionDetector.o'
|
||||
oc_native_o = OBJ_BASE / 'STSJailbreakDetectTool.o'
|
||||
linkfilelist_path = OBJ_BASE / 'readoor31.LinkFileList'
|
||||
linkfilelist_lines = [
|
||||
line.strip()
|
||||
for line in linkfilelist_path.read_text(encoding='utf-8').splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
linkfilelist_bc_count = sum(1 for line in linkfilelist_lines if line.endswith('.bc'))
|
||||
swift_native_is_bc = is_bitcode_wrapper(swift_native_o)
|
||||
objs_3d = check_object_pair(swift_native_o, oc_native_o)
|
||||
assert 'SwiftCompile ' in log3d
|
||||
assert swift_native_o.is_file() and not swift_native_is_bc
|
||||
assert linkfilelist_bc_count == 0
|
||||
assert r2_3d['binaries'] == 39 and not r2_3d['has_ig_archive_guard']
|
||||
assert r2_3d['direct_call_total'] > 0
|
||||
assert objs_3d['swift']['has_plaintext_dyld_cstr'] and not objs_3d['swift']['ig_dec_symbols']
|
||||
assert objs_3d['objc']['has_plaintext_dyld_cstr'] and not objs_3d['objc']['ig_dec_symbols']
|
||||
summary['steps']['M0-3d_all_off'] = {
|
||||
'elapsed_s': t3d,
|
||||
'swift_compile_ran': 'SwiftCompile ' in log3d,
|
||||
'swift_native_o_is_bitcode': swift_native_is_bc,
|
||||
'linkfilelist_bc_count': linkfilelist_bc_count,
|
||||
'route2': r2_3d,
|
||||
'target_objects': objs_3d,
|
||||
}
|
||||
|
||||
(RESULTS_DIR / 'm0_summary.json').write_text(
|
||||
json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8'
|
||||
)
|
||||
if ARCHIVE_DIR.exists():
|
||||
shutil.rmtree(ARCHIVE_DIR)
|
||||
if DD_PATH.exists():
|
||||
shutil.rmtree(DD_PATH)
|
||||
compact_large_logs(RESULTS_DIR)
|
||||
print('\n=== MILESTONE 0 MATRIX COMPLETE ===')
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,648 @@
|
||||
#!/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()
|
||||
Executable
+896
@@ -0,0 +1,896 @@
|
||||
#!/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()
|
||||
Executable
+543
@@ -0,0 +1,543 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Physical-device M0-2/M0-3 verification: cross-file Swift async throws + ObjC + embedded framework + .ips/.crash restore."""
|
||||
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
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TOOLS_ARCHIVE = ROOT / 'tools' / 'xcode_archive'
|
||||
TOOLS_LLVM = ROOT / 'tools' / 'llvm_obf'
|
||||
TOOLS_CRASH = ROOT / 'tools' / 'crash_restore'
|
||||
|
||||
sys.path.insert(0, str(TOOLS_LLVM))
|
||||
sys.path.insert(0, str(TOOLS_ARCHIVE))
|
||||
sys.path.insert(0, str(TOOLS_CRASH))
|
||||
|
||||
from ig_ld_wrapper import verify_macho_object_platform # noqa: E402
|
||||
from ig_toolchain_resolver import detect_sdk_info, detect_stock_tool # noqa: E402
|
||||
import restore_crash_report # noqa: E402
|
||||
|
||||
DEFAULT_PROFILE = Path.home() / 'Library/Developer/Xcode/UserData/Provisioning Profiles/e0f18495-668f-4fb1-87e1-4e048fb48d11.mobileprovision'
|
||||
DEFAULT_IDENTITY = '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8'
|
||||
DEFAULT_DEVICE = '00008140-000960811493001C'
|
||||
DEFAULT_BUNDLE_ID = 'cn.touchv.iosguard.hookpilot.m0async'
|
||||
|
||||
|
||||
def run(cmd, env=None, cwd=None):
|
||||
return subprocess.run(list(map(str, cmd)), env=env, cwd=cwd, capture_output=True, text=True)
|
||||
|
||||
|
||||
def write_sources(src_dir):
|
||||
src_dir.mkdir(parents=True, exist_ok=True)
|
||||
# 1. Embedded framework (ObjC + C flattened & string-encrypted + captures live stack return addr)
|
||||
fw_h = src_dir / 'IGM0ProbeKit.h'
|
||||
fw_m = src_dir / 'M0Kit.m'
|
||||
fw_h.write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'#include <stdint.h>\n'
|
||||
'FOUNDATION_EXPORT uintptr_t ig_m0_kit_probe_address(int selector);\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
fw_m.write_text(
|
||||
'#import "IGM0ProbeKit.h"\n'
|
||||
'#include <stdlib.h>\n'
|
||||
'#include <string.h>\n'
|
||||
'__attribute__((noinline)) static uintptr_t ig_m0_kit_leaf(void) {\n'
|
||||
' return (uintptr_t)__builtin_return_address(0) - 4;\n'
|
||||
'}\n'
|
||||
'__attribute__((noinline)) uintptr_t ig_m0_kit_probe_address(int selector) {\n'
|
||||
' const char *envv = getenv("IG_M0_NONEXISTENT_ENV_FLAG");\n'
|
||||
' int score = envv ? 99 : 0;\n'
|
||||
' if (selector == 1) score += 10;\n'
|
||||
' else if (selector == 2) score += 20;\n'
|
||||
' else score += 30;\n'
|
||||
' uintptr_t pc = ig_m0_kit_leaf();\n'
|
||||
' if (score == 10 || score == 20 || score == 30) {\n'
|
||||
' return pc;\n'
|
||||
' }\n'
|
||||
' return 0;\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 2. ObjC main object (concurrent string decryption + multi-branch flattening)
|
||||
objc_h = src_dir / 'ObjCBridge.h'
|
||||
objc_m = src_dir / 'ObjCBridge.m'
|
||||
objc_h.write_text(
|
||||
'#import <Foundation/Foundation.h>\n'
|
||||
'#import "IGM0ProbeKit.h"\n'
|
||||
'FOUNDATION_EXPORT int ig_m0_objc_concurrent_check(int thread_idx);\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
objc_m.write_text(
|
||||
'#import "ObjCBridge.h"\n'
|
||||
'#include <stdlib.h>\n'
|
||||
'#include <string.h>\n'
|
||||
'__attribute__((noinline)) static int ig_m0_branch_a(const char *s, int x) { return (int)s[x & 3] ^ x; }\n'
|
||||
'__attribute__((noinline)) static int ig_m0_branch_b(const char *s, int x) { return (int)s[(x + 1) & 3] + x; }\n'
|
||||
'__attribute__((noinline)) int ig_m0_objc_concurrent_check(int thread_idx) {\n'
|
||||
' const char *envv = getenv("M0_DEVICE_CONCURRENT_OBJC_SECRET");\n'
|
||||
' const char *secret = "M0_DEVICE_CONCURRENT_OBJC_SECRET";\n'
|
||||
' int base = envv ? 99 : 33;\n'
|
||||
' int r = 0;\n'
|
||||
' if (thread_idx == 0) { r = ig_m0_branch_a(secret, 1); }\n'
|
||||
' else if (thread_idx == 1) { r = ig_m0_branch_b(secret, 2); }\n'
|
||||
' else if (thread_idx == 2) { r = ig_m0_branch_a(secret, 3); }\n'
|
||||
' else { r = ig_m0_branch_b(secret, 4); }\n'
|
||||
' if (r == 0x7fffffff) return -1;\n'
|
||||
' return base + (thread_idx & 3);\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 3. Cross-file Swift 1: AsyncWorker.swift
|
||||
(src_dir / 'AsyncWorker.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'\n'
|
||||
'enum M0AsyncError: Error {\n'
|
||||
' case simulatedFailure(Int)\n'
|
||||
'}\n'
|
||||
'\n'
|
||||
'final class AsyncWorker {\n'
|
||||
' @inline(never)\n'
|
||||
' static func stepMix(_ tag: Int, _ val: UnsafePointer<Int8>?) -> Int {\n'
|
||||
' let extra = (val != nil) ? Int(strlen(val!)) : 0\n'
|
||||
' return tag + extra + Int(ProcessInfo.processInfo.processIdentifier & 0)\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' @inline(never)\n'
|
||||
' static func controlledEnvCheck(_ mode: Int) -> Int {\n'
|
||||
' let val = getenv("M0_DEVICE_SWIFT_CONTROLLED_VAR")\n'
|
||||
' var acc = 10\n'
|
||||
' if mode == 1 { acc += stepMix(7, val) }\n'
|
||||
' else if mode == 2 { acc += stepMix(14, val) }\n'
|
||||
' else { acc += stepMix(21, val) }\n'
|
||||
' if acc > 50 { acc += stepMix(1, val) }\n'
|
||||
' return acc\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func computeAsync(value: Int, shouldThrow: Bool) async throws -> Int {\n'
|
||||
' try await Task.sleep(nanoseconds: 5_000_000)\n'
|
||||
' try Task.checkCancellation()\n'
|
||||
' let base = controlledEnvCheck(value)\n'
|
||||
' try await Task.sleep(nanoseconds: 3_000_000)\n'
|
||||
' if shouldThrow {\n'
|
||||
' throw M0AsyncError.simulatedFailure(base + 1)\n'
|
||||
' }\n'
|
||||
' return base * 2\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func cancellableWork() async throws -> Int {\n'
|
||||
' while true {\n'
|
||||
' try Task.checkCancellation()\n'
|
||||
' try await Task.sleep(nanoseconds: 4_000_000)\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
# 4. Cross-file Swift 2: AsyncCaller.swift (async @main calling AsyncWorker + IGM0ProbeKit + ObjCBridge)
|
||||
(src_dir / 'AsyncCaller.swift').write_text(
|
||||
'import Foundation\n'
|
||||
'import MachO\n'
|
||||
'\n'
|
||||
'@main\n'
|
||||
'struct M0Entry {\n'
|
||||
' @inline(never)\n'
|
||||
' static func logLine(_ s: String) {\n'
|
||||
' NSLog("%@", s)\n'
|
||||
' fputs(s + "\\n", stderr)\n'
|
||||
' fflush(stderr)\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' @inline(never)\n'
|
||||
' static func captureMainCallerFrame() -> UInt {\n'
|
||||
' let stack = Thread.callStackReturnAddresses\n'
|
||||
' let ra = stack.first?.uintValue ?? 0\n'
|
||||
' return ra > 4 ? (ra - 4) : 0\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func imageInfoString(matching nameSuffix: String) -> String {\n'
|
||||
' for i in 0..<_dyld_image_count() {\n'
|
||||
' guard let cname = _dyld_get_image_name(i) else { continue }\n'
|
||||
' let path = String(cString: cname)\n'
|
||||
' if path.hasSuffix(nameSuffix), let hdr = _dyld_get_image_header(i) {\n'
|
||||
' let base = UInt(bitPattern: hdr)\n'
|
||||
' return "\\(nameSuffix)|0x\\(String(base, radix: 16))|\\(path)"\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
' return "\\(nameSuffix)|0x0|missing"\n'
|
||||
' }\n'
|
||||
'\n'
|
||||
' static func main() async {\n'
|
||||
' // 1. Cross-file async normal resume\n'
|
||||
' do {\n'
|
||||
' let v = try await AsyncWorker.computeAsync(value: 2, shouldThrow: false)\n'
|
||||
' logLine("M0_DEV_CASE async_normal_resume \\(v == 48 ? "PASS" : "FAIL(\\(v))")")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_normal_resume FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 2. Cross-file async throw/catch across suspension\n'
|
||||
' do {\n'
|
||||
' _ = try await AsyncWorker.computeAsync(value: 1, shouldThrow: true)\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch FAIL(no_throw)")\n'
|
||||
' } catch M0AsyncError.simulatedFailure(let code) {\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch \\(code == 18 ? "PASS" : "FAIL(\\(code))")")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_throw_catch FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 3. Cross-file async cancellation\n'
|
||||
' let t = Task { try await AsyncWorker.cancellableWork() }\n'
|
||||
' try? await Task.sleep(nanoseconds: 12_000_000)\n'
|
||||
' t.cancel()\n'
|
||||
' do {\n'
|
||||
' _ = try await t.value\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation FAIL(completed)")\n'
|
||||
' } catch is CancellationError {\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation PASS")\n'
|
||||
' } catch {\n'
|
||||
' logLine("M0_DEV_CASE async_cancellation FAIL(\\(error))")\n'
|
||||
' }\n'
|
||||
' // 4. 8-thread concurrent flattened ObjC + encrypted string\n'
|
||||
' let grp = DispatchGroup()\n'
|
||||
' let q = DispatchQueue.global(qos: .userInitiated)\n'
|
||||
' let lock = NSLock()\n'
|
||||
' var ok = true\n'
|
||||
' for idx in 0..<8 {\n'
|
||||
' grp.enter()\n'
|
||||
' q.async {\n'
|
||||
' let r = ig_m0_objc_concurrent_check(Int32(idx % 4))\n'
|
||||
' let expected = Int32(33 + (idx % 4))\n'
|
||||
' if r != expected {\n'
|
||||
' lock.lock(); ok = false; lock.unlock()\n'
|
||||
' }\n'
|
||||
' grp.leave()\n'
|
||||
' }\n'
|
||||
' }\n'
|
||||
' grp.wait()\n'
|
||||
' logLine("M0_DEV_CASE objc_concurrent_str_flatten \\(ok ? "PASS" : "FAIL")")\n'
|
||||
'\n'
|
||||
' // 5. Capture runtime addresses from main app & embedded framework\n'
|
||||
' let mainImg = imageInfoString(matching: "/IGM0AsyncPilot")\n'
|
||||
' let kitImg = imageInfoString(matching: "/IGM0ProbeKit")\n'
|
||||
' let kitAddr = ig_m0_kit_probe_address(2)\n'
|
||||
' let mainAddr = captureMainCallerFrame()\n'
|
||||
' logLine("M0_RUNTIME_IMG \\(mainImg)")\n'
|
||||
' logLine("M0_RUNTIME_IMG \\(kitImg)")\n'
|
||||
' logLine(String(format: "M0_RUNTIME_FRAME main=0x%lx kit=0x%lx", UInt(mainAddr), UInt(kitAddr)))\n'
|
||||
' }\n'
|
||||
'}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
|
||||
def verify_and_run(device, profile, identity, bundle_id, output_dir):
|
||||
output_dir = Path(output_dir).resolve()
|
||||
if output_dir.exists():
|
||||
shutil.rmtree(output_dir)
|
||||
output_dir.mkdir(parents=True)
|
||||
|
||||
r_prof = subprocess.run(['openssl', 'smime', '-inform', 'der', '-verify', '-noverify', '-in', str(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 identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in pdata['DeveloperCertificates']}:
|
||||
raise RuntimeError('Identity does not match provisioning profile')
|
||||
|
||||
src_dir = output_dir / 'src'
|
||||
write_sources(src_dir)
|
||||
|
||||
policy_path = output_dir / 'm0_device_policy.json'
|
||||
policy_path.write_text(json.dumps({
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [],
|
||||
'string_encrypt_targets': [
|
||||
{'path_contains': 'M0Kit.m'},
|
||||
{'path_contains': 'ObjCBridge.m'},
|
||||
{'path_contains': 'AsyncWorker.swift'},
|
||||
],
|
||||
'flatten_targets': [
|
||||
{'path_contains': 'M0Kit.m', 'function_contains': 'ig_m0_kit_probe_address'},
|
||||
{'path_contains': 'ObjCBridge.m', 'function_contains': 'ig_m0_objc_concurrent_check'},
|
||||
{'path_contains': 'AsyncWorker.swift', 'function_contains': '18controlledEnvCheck'},
|
||||
],
|
||||
'required_targets': [
|
||||
{'id': 'dev_objc', 'path_contains': 'ObjCBridge.m', 'symbol_contains': 'ig_m0_objc_concurrent_check', 'min_flattened': 1, 'min_strings_encrypted': 1},
|
||||
{'id': 'dev_swift', 'path_contains': 'AsyncWorker.swift', 'symbol_contains': '18controlledEnvCheck', 'min_flattened': 1, 'min_strings_encrypted': 1},
|
||||
],
|
||||
}, indent=2), encoding='utf-8')
|
||||
|
||||
sdk_info = detect_sdk_info()
|
||||
sdk = sdk_info['sdk_path']
|
||||
swiftc = detect_stock_tool('swiftc')
|
||||
cc_wrapper = str(TOOLS_ARCHIVE / 'ig_cc_wrapper.py')
|
||||
ld_wrapper = str(TOOLS_ARCHIVE / 'ig_ld_wrapper.py')
|
||||
|
||||
env = dict(os.environ)
|
||||
env['IG_LLVM_POLICY_PATH'] = str(policy_path)
|
||||
env['IG_OBF_MODE'] = 'full'
|
||||
env['IG_LLVM_PASS_FILTER'] = 'all'
|
||||
env['IG_ROUTE2_MODE'] = 'off'
|
||||
env['IG_ALL_GUARD_OFF'] = '0'
|
||||
env['IG_RELEASE_SEED'] = 'm0_device_seed_1'
|
||||
env['IG_REQUIRE_LLVM_OBF'] = '1'
|
||||
env['CONFIGURATION'] = 'Release'
|
||||
env['PLATFORM_NAME'] = 'iphoneos'
|
||||
env['SRCROOT'] = str(src_dir)
|
||||
env['TARGET_TEMP_DIR'] = str(output_dir / 'temp')
|
||||
|
||||
app_dir = output_dir / 'IGM0AsyncPilot.app'
|
||||
fw_dir = app_dir / 'Frameworks' / 'IGM0ProbeKit.framework'
|
||||
dsym_dir = output_dir / 'dSYMs'
|
||||
fw_dir.mkdir(parents=True)
|
||||
dsym_dir.mkdir(parents=True)
|
||||
|
||||
# Build embedded IGM0ProbeKit.framework via ig_cc_wrapper.py
|
||||
fw_obj = output_dir / 'M0Kit.o'
|
||||
p1 = run([
|
||||
cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
'-Os', '-g', '-fobjc-arc', '-fPIC', '-I', str(src_dir),
|
||||
'-c', str(src_dir / 'M0Kit.m'), '-o', str(fw_obj),
|
||||
], env=env)
|
||||
if p1.returncode != 0:
|
||||
raise RuntimeError(f'M0Kit.m failed:\n{p1.stdout}\n{p1.stderr}')
|
||||
|
||||
clang = detect_stock_tool('clang')
|
||||
fw_bin = fw_dir / 'IGM0ProbeKit'
|
||||
subprocess.run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk, '-dynamiclib',
|
||||
str(fw_obj), '-framework', 'Foundation',
|
||||
'-Wl,-install_name,@rpath/IGM0ProbeKit.framework/IGM0ProbeKit',
|
||||
'-o', str(fw_bin),
|
||||
], check=True)
|
||||
subprocess.run(['xcrun', 'dsymutil', str(fw_bin), '-o', str(dsym_dir / 'IGM0ProbeKit.framework.dSYM')], check=True)
|
||||
(fw_dir / 'Info.plist').write_bytes(plistlib.dumps({
|
||||
'CFBundleExecutable': 'IGM0ProbeKit',
|
||||
'CFBundleIdentifier': bundle_id + '.probekit',
|
||||
'CFBundleInfoDictionaryVersion': '6.0',
|
||||
'CFBundleName': 'IGM0ProbeKit',
|
||||
'CFBundlePackageType': 'FMWK',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'CFBundleSupportedPlatforms': ['iPhoneOS'],
|
||||
'CFBundleVersion': '1',
|
||||
'MinimumOSVersion': '15.0',
|
||||
}))
|
||||
|
||||
# Compile ObjCBridge.m via ig_cc_wrapper.py
|
||||
obj_dir = output_dir / 'objs'
|
||||
obj_dir.mkdir()
|
||||
objc_obj = obj_dir / 'ObjCBridge.o'
|
||||
p2 = run([
|
||||
cc_wrapper, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
'-Os', '-g', '-fobjc-arc', '-I', str(src_dir),
|
||||
'-c', str(src_dir / 'ObjCBridge.m'), '-o', str(objc_obj),
|
||||
], env=env)
|
||||
if p2.returncode != 0:
|
||||
raise RuntimeError(f'ObjCBridge.m failed:\n{p2.stdout}\n{p2.stderr}')
|
||||
|
||||
# Compile cross-file Swift via stock swiftc -O -g -lto=llvm-thin using OutputFileMap.json (matching Xcode SWIFT_LTO=YES_THIN)
|
||||
w_src = str(src_dir / 'AsyncWorker.swift')
|
||||
c_src = str(src_dir / 'AsyncCaller.swift')
|
||||
w_obj = obj_dir / 'AsyncWorker.o'
|
||||
c_obj = obj_dir / 'AsyncCaller.o'
|
||||
w_bc = obj_dir / 'AsyncWorker.bc'
|
||||
c_bc = obj_dir / 'AsyncCaller.bc'
|
||||
ofm_path = obj_dir / 'IGM0AsyncPilot-OutputFileMap.json'
|
||||
ofm_path.write_text(json.dumps({
|
||||
'': {'swift-dependencies': str(obj_dir / 'master.swiftdeps')},
|
||||
w_src: {'object': str(w_obj), 'llvm-bc': str(w_bc)},
|
||||
c_src: {'object': str(c_obj), 'llvm-bc': str(c_bc)},
|
||||
}, indent=2), encoding='utf-8')
|
||||
filelist_path = obj_dir / 'IGM0AsyncPilot.LinkFileList'
|
||||
filelist_path.write_text('\n'.join([str(objc_obj), str(w_bc), str(c_bc)]) + '\n', encoding='utf-8')
|
||||
|
||||
p_sw = run([
|
||||
swiftc, '-sdk', sdk, '-target', 'arm64-apple-ios15.0',
|
||||
'-module-name', 'IGM0AsyncPilot',
|
||||
'-O', '-g', '-lto=llvm-thin',
|
||||
'-import-objc-header', str(src_dir / 'ObjCBridge.h'),
|
||||
'-I', str(src_dir),
|
||||
'-output-file-map', str(ofm_path),
|
||||
'-c', w_src, c_src,
|
||||
], env=env)
|
||||
if p_sw.returncode != 0:
|
||||
raise RuntimeError(f'swiftc failed:\n{p_sw.stdout}\n{p_sw.stderr}')
|
||||
|
||||
# Link main executable through real ig_ld_wrapper.py (--ld-path)
|
||||
app_bin = app_dir / 'IGM0AsyncPilot'
|
||||
linkmap_p = output_dir / 'temp' / 'IGM0AsyncPilot-LinkMap.txt'
|
||||
linkmap_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p_ld = run([
|
||||
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk,
|
||||
f'--ld-path={ld_wrapper}',
|
||||
'-Wl,-ig_stamp,ctl_full__all__off__0__m0_device_seed_1__devstamp1',
|
||||
f'-Wl,-filelist,{filelist_path}',
|
||||
f'-Wl,-map,{linkmap_p}',
|
||||
'-Wl,-rpath,@executable_path/Frameworks',
|
||||
str(fw_bin),
|
||||
'-L', str(Path(swiftc).parents[1] / 'lib/swift/iphoneos'),
|
||||
'-L', str(Path(sdk) / 'usr/lib/swift'),
|
||||
'-framework', 'UIKit', '-framework', 'Foundation', '-lobjc',
|
||||
'-o', str(app_bin),
|
||||
], env=env)
|
||||
if p_ld.returncode != 0:
|
||||
raise RuntimeError(f'ig_ld_wrapper link failed:\n{p_ld.stdout}\n{p_ld.stderr}')
|
||||
|
||||
# Check converted Swift objects LC_BUILD_VERSION
|
||||
swift_machos = sorted((obj_dir / 'ig-swift-macho').glob('*.o'))
|
||||
assert len(swift_machos) == 2, f'Expected 2 converted Swift objects, got {swift_machos}'
|
||||
lc_versions = {m.name: verify_macho_object_platform(m) for m in swift_machos}
|
||||
|
||||
subprocess.run(['xcrun', 'dsymutil', str(app_bin), '-o', str(dsym_dir / 'IGM0AsyncPilot.app.dSYM')], check=True)
|
||||
(app_dir / 'Info.plist').write_bytes(plistlib.dumps({
|
||||
'CFBundleExecutable': 'IGM0AsyncPilot',
|
||||
'CFBundleIdentifier': bundle_id,
|
||||
'CFBundleName': 'IGM0AsyncPilot',
|
||||
'CFBundleDisplayName': 'IGM0AsyncPilot',
|
||||
'CFBundlePackageType': 'APPL',
|
||||
'CFBundleVersion': '1',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'MinimumOSVersion': '15.0',
|
||||
'LSRequiresIPhoneOS': True,
|
||||
'UIDeviceFamily': [1, 2],
|
||||
'UILaunchScreen': {},
|
||||
}))
|
||||
shutil.copy2(profile, app_dir / 'embedded.mobileprovision')
|
||||
ent_plist = dict(ent)
|
||||
ent_plist['application-identifier'] = f'{prefix}.{bundle_id}'
|
||||
ent_plist['keychain-access-groups'] = [f'{prefix}.{bundle_id}']
|
||||
(output_dir / 'ent.plist').write_bytes(plistlib.dumps(ent_plist))
|
||||
|
||||
subprocess.run(['codesign', '--force', '--sign', identity, str(fw_dir)], check=True)
|
||||
subprocess.run(['codesign', '--force', '--sign', identity, '--entitlements', str(output_dir / 'ent.plist'), str(app_dir)], check=True)
|
||||
|
||||
# Install and launch on physical device; guarantee uninstall afterwards
|
||||
installed = False
|
||||
try:
|
||||
subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'install', 'app',
|
||||
'--device', device, '--timeout', '60', str(app_dir),
|
||||
], check=True)
|
||||
installed = True
|
||||
launch = subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'process', 'launch',
|
||||
'--device', device, '--console', '--timeout', '25',
|
||||
'--terminate-existing', bundle_id,
|
||||
], capture_output=True, text=True)
|
||||
console_log = launch.stdout + '\n' + launch.stderr
|
||||
(output_dir / 'device-console.log').write_text(console_log, encoding='utf-8')
|
||||
finally:
|
||||
if installed:
|
||||
subprocess.run([
|
||||
'xcrun', 'devicectl', 'device', 'uninstall', 'app',
|
||||
'--device', device, '--timeout', '60', bundle_id,
|
||||
], check=False)
|
||||
|
||||
cases = {}
|
||||
for m in re.finditer(r'M0_DEV_CASE\s+(\S+)\s+(PASS|FAIL(?:\([^)]*\))?)', console_log):
|
||||
cases[m.group(1)] = m.group(2)
|
||||
|
||||
img_bases = {}
|
||||
for m in re.finditer(r'M0_RUNTIME_IMG\s+([^|\s]+)\|(0x[0-9a-fA-F]+)\|(\S+)', console_log):
|
||||
img_bases[m.group(1)] = {'base': int(m.group(2), 16), 'path': m.group(3)}
|
||||
|
||||
frame_m = re.search(r'M0_RUNTIME_FRAME\s+main=(0x[0-9a-fA-F]+)\s+kit=(0x[0-9a-fA-F]+)', console_log)
|
||||
if not frame_m:
|
||||
raise RuntimeError(f'Missing M0_RUNTIME_FRAME in device console:\n{console_log}')
|
||||
|
||||
main_pc = int(frame_m.group(1), 16)
|
||||
kit_pc = int(frame_m.group(2), 16)
|
||||
main_base = img_bases['/IGM0AsyncPilot']['base']
|
||||
kit_base = img_bases['/IGM0ProbeKit']['base']
|
||||
|
||||
def uuid_of(path):
|
||||
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(path)], text=True)
|
||||
return out.split()[1]
|
||||
|
||||
main_uid = uuid_of(app_bin)
|
||||
kit_uid = uuid_of(fw_bin)
|
||||
|
||||
# Symbolicate live device addresses in BOTH .ips JSON and .crash text formats!
|
||||
ips_p = output_dir / 'device_live.ips'
|
||||
ips_p.write_text(
|
||||
json.dumps({'app_name': 'IGM0AsyncPilot', 'bug_type': '309'}) + '\n' +
|
||||
json.dumps({
|
||||
'usedImages': [
|
||||
{'base': main_base, 'size': 0x40000, 'uuid': main_uid, 'name': 'IGM0AsyncPilot', 'arch': 'arm64', 'path': img_bases['/IGM0AsyncPilot']['path']},
|
||||
{'base': kit_base, 'size': 0x10000, 'uuid': kit_uid, 'name': 'IGM0ProbeKit', 'arch': 'arm64', 'path': img_bases['/IGM0ProbeKit']['path']},
|
||||
],
|
||||
'threads': [{
|
||||
'triggered': True,
|
||||
'frames': [
|
||||
{'imageIndex': 0, 'imageOffset': main_pc - main_base},
|
||||
{'imageIndex': 1, 'imageOffset': kit_pc - kit_base},
|
||||
],
|
||||
}],
|
||||
}) + '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
crash_p = output_dir / 'device_live.crash'
|
||||
crash_p.write_text(
|
||||
'Thread 0 Crashed:\n'
|
||||
f'0 IGM0AsyncPilot {hex(main_pc)} {hex(main_base)} + {main_pc - main_base}\n'
|
||||
f'1 IGM0ProbeKit {hex(kit_pc)} {hex(kit_base)} + {kit_pc - kit_base}\n\n'
|
||||
'Binary Images:\n'
|
||||
f' {hex(main_base)} - {hex(main_base + 0x40000)} IGM0AsyncPilot arm64 <{main_uid}> {img_bases["/IGM0AsyncPilot"]["path"]}\n'
|
||||
f' {hex(kit_base)} - {hex(kit_base + 0x10000)} IGM0ProbeKit arm64 <{kit_uid}> {img_bases["/IGM0ProbeKit"]["path"]}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
|
||||
sym_ips = restore_crash_report.restore_report(ips_p, dsym_dir)
|
||||
sym_crash = restore_crash_report.restore_report(crash_p, dsym_dir)
|
||||
|
||||
audit_file = output_dir / 'temp' / 'ig-route2-audit' / 'ig_obfuscation_audit.json'
|
||||
audit = json.loads(audit_file.read_text(encoding='utf-8'))
|
||||
|
||||
result = {
|
||||
'device': device,
|
||||
'lc_build_version': lc_versions,
|
||||
'cases': cases,
|
||||
'obf_audit': audit,
|
||||
'ips_restored': sym_ips,
|
||||
'crash_restored': sym_crash,
|
||||
}
|
||||
(output_dir / 'device-m0-verification.json').write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8'
|
||||
)
|
||||
|
||||
expected_cases = ('async_normal_resume', 'async_throw_catch', 'async_cancellation', 'objc_concurrent_str_flatten')
|
||||
for cname in expected_cases:
|
||||
if cases.get(cname) != 'PASS':
|
||||
raise AssertionError(f'Device case {cname} did not PASS: {cases}')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--device', default=DEFAULT_DEVICE)
|
||||
p.add_argument('--profile', type=Path, default=DEFAULT_PROFILE)
|
||||
p.add_argument('--identity', default=DEFAULT_IDENTITY)
|
||||
p.add_argument('--bundle-id', default=DEFAULT_BUNDLE_ID)
|
||||
p.add_argument('--output', type=Path, default=Path('/tmp/ig-m0-async-device'))
|
||||
a = p.parse_args()
|
||||
res = verify_and_run(a.device, a.profile, a.identity, a.bundle_id, a.output)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that every indirect-branch obfuscated function emits ARM64 `br xN` instructions in Mach-O."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
from verify_macho_star_cfg import (
|
||||
JUMP_TABLE_BR_RE,
|
||||
_candidate_symbol_keys,
|
||||
parse_dwarf_text_ranges,
|
||||
)
|
||||
|
||||
|
||||
def _count_br_insns(main_bin: Path, start_addr: int, end_addr: int) -> dict:
|
||||
dis = subprocess.check_output(
|
||||
[
|
||||
'xcrun', 'llvm-objdump', '--disassemble',
|
||||
f'--start-address={hex(start_addr)}',
|
||||
f'--stop-address={hex(end_addr)}',
|
||||
str(main_bin),
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
br_count = sum(1 for line in dis.splitlines() if JUMP_TABLE_BR_RE.search(line))
|
||||
return {
|
||||
'start_addr': hex(start_addr),
|
||||
'end_addr': hex(end_addr),
|
||||
'indirect_br_count': br_count,
|
||||
}
|
||||
|
||||
|
||||
def verify_binary_indirect_branches(
|
||||
main_bin: Path,
|
||||
dwarf_bin: Path,
|
||||
obf_audit: dict,
|
||||
*,
|
||||
fail_on_missing: bool = False,
|
||||
) -> dict:
|
||||
"""Disassemble every audited IBR function in main_bin and require >=1 `br xN`."""
|
||||
ranges_map = parse_dwarf_text_ranges(dwarf_bin)
|
||||
verified = []
|
||||
failed = []
|
||||
dead_stripped = []
|
||||
|
||||
to_check: list[tuple[str, str, list[tuple[int, int]]]] = []
|
||||
for mod in obf_audit.get('module_audits') or []:
|
||||
src_name = Path(mod.get('source_path') or 'unknown').name
|
||||
for raw_name in mod.get('indirect_branches_functions') or []:
|
||||
cand_ranges = []
|
||||
for key in _candidate_symbol_keys(raw_name):
|
||||
if key in ranges_map:
|
||||
cand_ranges = ranges_map[key]
|
||||
break
|
||||
if not cand_ranges:
|
||||
rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'}
|
||||
dead_stripped.append(rec)
|
||||
if fail_on_missing:
|
||||
failed.append(rec)
|
||||
continue
|
||||
to_check.append((src_name, raw_name, cand_ranges))
|
||||
|
||||
unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist})
|
||||
inspected_by_range: dict[tuple[int, int], dict] = {}
|
||||
if unique_ranges:
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = pool.map(lambda se: _count_br_insns(main_bin, se[0], se[1]), unique_ranges)
|
||||
for se, res in zip(unique_ranges, results):
|
||||
inspected_by_range[se] = res
|
||||
|
||||
for src_name, raw_name, cand_ranges in to_check:
|
||||
range_results = [inspected_by_range[se] for se in cand_ranges]
|
||||
bad = [r for r in range_results if r['indirect_br_count'] < 1]
|
||||
if bad:
|
||||
failed.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
'reason': 'missing_indirect_br_instruction',
|
||||
'range_results': range_results,
|
||||
})
|
||||
else:
|
||||
verified.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
**range_results[0],
|
||||
})
|
||||
|
||||
summary = {
|
||||
'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)),
|
||||
'linked_checked_count': len(verified) + len(failed),
|
||||
'verified_ibr_count': len(verified),
|
||||
'dead_stripped_count': len(dead_stripped),
|
||||
'failed_count': len(failed),
|
||||
'failed': failed,
|
||||
'sample_verified': verified[:12],
|
||||
}
|
||||
if failed:
|
||||
preview = json.dumps(failed[:5], ensure_ascii=False, indent=2)
|
||||
raise AssertionError(
|
||||
f'[IndirectBranchGate] {len(failed)} function(s) failed br xN check:\n{preview}'
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary', type=Path, required=True)
|
||||
parser.add_argument('--dwarf', type=Path, required=True)
|
||||
parser.add_argument('--audit', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
audit = json.loads(args.audit.read_text(encoding='utf-8'))
|
||||
res = verify_binary_indirect_branches(args.binary, args.dwarf, audit)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,470 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify ARM64 direct BL/tail-B vs indirect BLR call-graph metrics in a linked Mach-O binary."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from array import array
|
||||
import bisect
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
MH_MAGIC_64 = 0xFEEDFACF
|
||||
FAT_MAGIC = 0xCAFEBABE
|
||||
FAT_CIGAM = 0xBEBAFECA
|
||||
LC_SEGMENT_64 = 0x19
|
||||
CPU_TYPE_ARM64 = 0x0100000C
|
||||
|
||||
KEYBOX_AND_BRIDGE_C_SYMBOLS = [
|
||||
'_rd_epub_derive_book_key',
|
||||
'_rd_epub_derive_media_key',
|
||||
'_rd_epub_legacy_url_prefix',
|
||||
'_rd_epub_derive_book_key_ns',
|
||||
'_rd_epub_derive_media_key_ns',
|
||||
'_rd_epub_legacy_tag_prefix',
|
||||
'_rd_epub_media_pwd_ns',
|
||||
'_rd_epub_db_key_ns',
|
||||
'_rd_epub_device_token_key_ns',
|
||||
'_rd_epub_course_sign_prefix_ns',
|
||||
'_rd_epub_wx_pay_secret_ns',
|
||||
'_rd_content_decrypt_file',
|
||||
'_rd_epub_key_transform',
|
||||
'_rd_epub_poison_mark',
|
||||
'_rd_sd_derive_aes256_key',
|
||||
'_rd_sd_decrypt_bundled_asset',
|
||||
'_rd_sd_keychain_slot_name',
|
||||
'_rd_sd_bundle_asset_stem',
|
||||
'_rd_iap_keychain_account_name',
|
||||
'_rd_sd_media_decrypt_pwd',
|
||||
'_rd_sd_db_secret_key',
|
||||
'_rd_sd_device_token_key',
|
||||
'_rd_sd_course_sign_prefix',
|
||||
'_rd_sd_wx_pay_secret',
|
||||
'_rd_sd_derive_v31_seed',
|
||||
'_rd_sd_derive_v31_dt_pwd',
|
||||
'_rd_sd_seckey_create_with_data',
|
||||
'_rd_sd_seckey_create_signature',
|
||||
'_rd_sd_cc_crypt',
|
||||
'_rd_sd_cc_hmac',
|
||||
'_rd_sd_is_traced',
|
||||
'_rd_sd_sha256_init',
|
||||
'_rd_sd_sha256_update',
|
||||
'_rd_sd_sha256_final',
|
||||
'_rd_sd_sha256_raw',
|
||||
'_rd_sd_sha256_hex',
|
||||
'_rd_sd_md5_hex',
|
||||
'_rd_sec_bootstrap_launch',
|
||||
'_rd_sd_probe_env_artifacts',
|
||||
]
|
||||
|
||||
TRACKED_CORE_TYPES = [
|
||||
'RDEncryptedEpubResourceProvider',
|
||||
'EpubParser',
|
||||
'LoadEpub',
|
||||
'STSEpubWebResourceLoader',
|
||||
'RBCoreEpubLoadController',
|
||||
'STSRDFileManagerStorage',
|
||||
'RDPDFStsSimpleCryptBridge',
|
||||
'RDSDPrivateKeyManager',
|
||||
'RDSDAuthV32Signer',
|
||||
'RDBaseNetworkService',
|
||||
'RDKeyGenerator',
|
||||
'RDIAPHandler',
|
||||
'STSIAPVerifyHandler',
|
||||
]
|
||||
|
||||
|
||||
def _select_arm64_slice(data: bytes) -> memoryview:
|
||||
magic = struct.unpack_from('<I', data, 0)[0]
|
||||
if magic == MH_MAGIC_64:
|
||||
return memoryview(data)
|
||||
be_magic = struct.unpack_from('>I', data, 0)[0]
|
||||
if be_magic == FAT_MAGIC:
|
||||
nfat = struct.unpack_from('>I', data, 4)[0]
|
||||
for idx in range(nfat):
|
||||
cputype, _, offset, size, _ = struct.unpack_from('>IIIII', data, 8 + idx * 20)
|
||||
if cputype == CPU_TYPE_ARM64:
|
||||
return memoryview(data)[offset:offset + size]
|
||||
raise ValueError(f'Unsupported Mach-O magic: 0x{magic:08x}')
|
||||
|
||||
|
||||
def parse_macho_sections(binary_path: Path) -> dict[str, dict[str, int]]:
|
||||
"""Return mapping of 'SEGNAME,sectname' -> {'addr', 'size', 'offset'} for arm64 slice."""
|
||||
raw = binary_path.read_bytes()
|
||||
mv = _select_arm64_slice(raw)
|
||||
magic, _, _, _, ncmds, _, _, _ = struct.unpack_from('<IIIIIIII', mv, 0)
|
||||
if magic != MH_MAGIC_64:
|
||||
raise ValueError(f'Expected MH_MAGIC_64, got 0x{magic:08x}')
|
||||
sections: dict[str, dict[str, int]] = {}
|
||||
cmd_off = 32
|
||||
for _ in range(ncmds):
|
||||
cmd, cmdsize = struct.unpack_from('<II', mv, cmd_off)
|
||||
if cmd == LC_SEGMENT_64:
|
||||
segname_raw, vmaddr, vmsize, fileoff, filesize, _, _, nsects, _ = struct.unpack_from(
|
||||
'<16sQQQQIIII', mv, cmd_off + 8
|
||||
)
|
||||
segname = segname_raw.split(b'\x00', 1)[0].decode('latin1')
|
||||
sections[f'{segname},*'] = {
|
||||
'addr': vmaddr,
|
||||
'size': vmsize,
|
||||
'offset': fileoff,
|
||||
'filesize': filesize,
|
||||
}
|
||||
sect_off = cmd_off + 72
|
||||
for _ in range(nsects):
|
||||
sect_raw, seg_raw, addr, size, offset = struct.unpack_from(
|
||||
'<16s16sQQI', mv, sect_off
|
||||
)
|
||||
sname = sect_raw.split(b'\x00', 1)[0].decode('latin1')
|
||||
gname = seg_raw.split(b'\x00', 1)[0].decode('latin1')
|
||||
sections[f'{gname},{sname}'] = {
|
||||
'addr': addr,
|
||||
'size': size,
|
||||
'offset': offset,
|
||||
}
|
||||
sect_off += 80
|
||||
cmd_off += cmdsize
|
||||
return sections
|
||||
|
||||
|
||||
def parse_dwarf_symbols(dwarf_bin: Path) -> tuple[list[int], list[int], list[list[str]], dict[str, list[tuple[int, int]]]]:
|
||||
"""Return sorted unique text symbol ranges and name -> [(start, end)] lookup."""
|
||||
out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True)
|
||||
addr_to_names: dict[int, list[str]] = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.strip().split(maxsplit=2)
|
||||
if len(parts) == 3 and parts[1].lower() == 't':
|
||||
try:
|
||||
addr = int(parts[0], 16)
|
||||
except ValueError:
|
||||
continue
|
||||
addr_to_names.setdefault(addr, []).append(parts[2])
|
||||
|
||||
starts = sorted(addr_to_names.keys())
|
||||
ends: list[int] = []
|
||||
names_at_idx: list[list[str]] = []
|
||||
by_name: dict[str, list[tuple[int, int]]] = {}
|
||||
for idx, addr in enumerate(starts):
|
||||
end = starts[idx + 1] if idx + 1 < len(starts) else addr + 0x400
|
||||
ends.append(end)
|
||||
nlist = addr_to_names[addr]
|
||||
names_at_idx.append(nlist)
|
||||
for nm in nlist:
|
||||
by_name.setdefault(nm, []).append((addr, end))
|
||||
return starts, ends, names_at_idx, by_name
|
||||
|
||||
|
||||
def load_l1_type_map(symbol_map_path: Path | None) -> dict[str, str]:
|
||||
if not symbol_map_path or not symbol_map_path.is_file():
|
||||
return {}
|
||||
raw = json.loads(symbol_map_path.read_text(encoding='utf-8'))
|
||||
mappings = raw.get('mappings') if isinstance(raw.get('mappings'), dict) else raw
|
||||
out: dict[str, str] = {}
|
||||
if isinstance(mappings, dict):
|
||||
for orig, val in mappings.items():
|
||||
if isinstance(val, str):
|
||||
out[orig] = val
|
||||
elif isinstance(val, dict) and isinstance(val.get('obfuscated'), str):
|
||||
out[orig] = val['obfuscated']
|
||||
return out
|
||||
|
||||
|
||||
def analyze_macho_calls(
|
||||
binary_path: Path,
|
||||
dwarf_bin: Path,
|
||||
symbol_map_path: Path | None = None,
|
||||
require_zero_keybox_direct_bl: bool = False,
|
||||
) -> dict:
|
||||
raw = binary_path.read_bytes()
|
||||
mv = _select_arm64_slice(raw)
|
||||
sections = parse_macho_sections(binary_path)
|
||||
if '__TEXT,__text' not in sections:
|
||||
raise ValueError(f'Missing __TEXT,__text in {binary_path}')
|
||||
|
||||
text_sec = sections['__TEXT,__text']
|
||||
text_va = text_sec['addr']
|
||||
text_size = text_sec['size']
|
||||
text_off = text_sec['offset']
|
||||
text_end_va = text_va + text_size
|
||||
|
||||
stubs_va = sections.get('__TEXT,__stubs', {}).get('addr', 0)
|
||||
stubs_end_va = stubs_va + sections.get('__TEXT,__stubs', {}).get('size', 0)
|
||||
objc_stubs_va = sections.get('__TEXT,__objc_stubs', {}).get('addr', 0)
|
||||
objc_stubs_end_va = objc_stubs_va + sections.get('__TEXT,__objc_stubs', {}).get('size', 0)
|
||||
|
||||
starts, ends, names_at_idx, by_name = parse_dwarf_symbols(dwarf_bin)
|
||||
start_to_idx = {addr: idx for idx, addr in enumerate(starts)}
|
||||
l1_types = load_l1_type_map(symbol_map_path)
|
||||
|
||||
words = array('I')
|
||||
words.frombytes(mv[text_off:text_off + (text_size & ~3)])
|
||||
if sys.byteorder != 'little':
|
||||
words.byteswap()
|
||||
|
||||
total_bl = 0
|
||||
internal_text_bl = 0
|
||||
dylib_stub_bl = 0
|
||||
objc_stub_bl = 0
|
||||
other_bl = 0
|
||||
interproc_tail_b = 0
|
||||
blr_count = 0
|
||||
|
||||
# Track direct incoming calls (BL + inter-procedural tail B) keyed by target symbol index
|
||||
direct_in_bl_by_idx: dict[int, int] = {}
|
||||
direct_in_tail_b_by_idx: dict[int, int] = {}
|
||||
# Track caller symbol index -> list of (pc, target_idx, kind) for KeyBox targets
|
||||
keybox_indices: dict[str, list[int]] = {}
|
||||
keybox_idx_set: set[int] = set()
|
||||
for sym in KEYBOX_AND_BRIDGE_C_SYMBOLS:
|
||||
idxs = []
|
||||
for s_addr, _ in by_name.get(sym, []):
|
||||
if s_addr in start_to_idx:
|
||||
idxs.append(start_to_idx[s_addr])
|
||||
keybox_idx_set.add(start_to_idx[s_addr])
|
||||
keybox_indices[sym] = idxs
|
||||
|
||||
keybox_caller_samples: dict[int, list[dict]] = {}
|
||||
|
||||
# Pre-classify symbol indices belonging to tracked core types (using both original & L1 token)
|
||||
core_type_tokens: dict[str, tuple[str, ...]] = {}
|
||||
for orig_type in TRACKED_CORE_TYPES:
|
||||
obf_type = l1_types.get(orig_type)
|
||||
toks = [orig_type]
|
||||
if obf_type and obf_type != orig_type:
|
||||
toks.append(obf_type)
|
||||
core_type_tokens[orig_type] = tuple(toks)
|
||||
|
||||
idx_to_core_types: dict[int, list[str]] = {}
|
||||
for idx, nlist in enumerate(names_at_idx):
|
||||
matched_types = []
|
||||
for orig_type, toks in core_type_tokens.items():
|
||||
if any(tok in nm for nm in nlist for tok in toks):
|
||||
matched_types.append(orig_type)
|
||||
if matched_types:
|
||||
idx_to_core_types[idx] = matched_types
|
||||
|
||||
core_outgoing_internal_bl: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES}
|
||||
core_outgoing_blr: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES}
|
||||
core_incoming_direct: dict[str, int] = {t: 0 for t in TRACKED_CORE_TYPES}
|
||||
|
||||
# Walk linearly while maintaining current symbol cursor `cur_sym_idx` in O(1) amortized time!
|
||||
num_syms = len(starts)
|
||||
cur_sym_idx = 0
|
||||
|
||||
for i, insn in enumerate(words):
|
||||
pc = text_va + (i << 2)
|
||||
while cur_sym_idx + 1 < num_syms and pc >= ends[cur_sym_idx]:
|
||||
cur_sym_idx += 1
|
||||
caller_idx = cur_sym_idx if (num_syms > 0 and starts[cur_sym_idx] <= pc < ends[cur_sym_idx]) else -1
|
||||
|
||||
op6 = insn & 0xFC000000
|
||||
if op6 == 0x94000000: # BL imm26
|
||||
total_bl += 1
|
||||
imm26 = insn & 0x03FFFFFF
|
||||
if imm26 & 0x02000000:
|
||||
imm26 -= 0x04000000
|
||||
tgt = pc + (imm26 << 2)
|
||||
if stubs_va <= tgt < stubs_end_va:
|
||||
dylib_stub_bl += 1
|
||||
elif objc_stubs_va <= tgt < objc_stubs_end_va:
|
||||
objc_stub_bl += 1
|
||||
elif text_va <= tgt < text_end_va:
|
||||
internal_text_bl += 1
|
||||
if caller_idx in idx_to_core_types:
|
||||
for ct in idx_to_core_types[caller_idx]:
|
||||
core_outgoing_internal_bl[ct] += 1
|
||||
t_idx = start_to_idx.get(tgt)
|
||||
if t_idx is None:
|
||||
pos = bisect.bisect_right(starts, tgt) - 1
|
||||
if 0 <= pos < num_syms and starts[pos] <= tgt < ends[pos]:
|
||||
t_idx = pos
|
||||
if t_idx is not None:
|
||||
direct_in_bl_by_idx[t_idx] = direct_in_bl_by_idx.get(t_idx, 0) + 1
|
||||
if t_idx in idx_to_core_types:
|
||||
for ct in idx_to_core_types[t_idx]:
|
||||
core_incoming_direct[ct] += 1
|
||||
if t_idx in keybox_idx_set and len(keybox_caller_samples.get(t_idx, [])) < 8:
|
||||
caller_name = names_at_idx[caller_idx][0] if caller_idx >= 0 else hex(pc)
|
||||
keybox_caller_samples.setdefault(t_idx, []).append({
|
||||
'pc': hex(pc),
|
||||
'kind': 'bl',
|
||||
'caller': caller_name,
|
||||
})
|
||||
else:
|
||||
other_bl += 1
|
||||
elif op6 == 0x14000000: # B imm26 (check inter-procedural tail-call to symbol entry)
|
||||
imm26 = insn & 0x03FFFFFF
|
||||
if imm26 & 0x02000000:
|
||||
imm26 -= 0x04000000
|
||||
tgt = pc + (imm26 << 2)
|
||||
if text_va <= tgt < text_end_va:
|
||||
t_idx = start_to_idx.get(tgt)
|
||||
if t_idx is not None and t_idx != caller_idx:
|
||||
interproc_tail_b += 1
|
||||
direct_in_tail_b_by_idx[t_idx] = direct_in_tail_b_by_idx.get(t_idx, 0) + 1
|
||||
if caller_idx in idx_to_core_types:
|
||||
for ct in idx_to_core_types[caller_idx]:
|
||||
core_outgoing_internal_bl[ct] += 1
|
||||
if t_idx in idx_to_core_types:
|
||||
for ct in idx_to_core_types[t_idx]:
|
||||
core_incoming_direct[ct] += 1
|
||||
if t_idx in keybox_idx_set and len(keybox_caller_samples.get(t_idx, [])) < 8:
|
||||
caller_name = names_at_idx[caller_idx][0] if caller_idx >= 0 else hex(pc)
|
||||
keybox_caller_samples.setdefault(t_idx, []).append({
|
||||
'pc': hex(pc),
|
||||
'kind': 'tail_b',
|
||||
'caller': caller_name,
|
||||
})
|
||||
elif (insn & 0xFFFFFC1F) == 0xD63F0000 or (insn & 0xFEFFF800) == 0xD73F0800 or (
|
||||
(insn & 0xFFFFFC1F) in (0xD63F081F, 0xD63F0C1F)
|
||||
):
|
||||
# BLR Xn or BLRAA/BLRAB/BLRAAZ/BLRABZ
|
||||
blr_count += 1
|
||||
if caller_idx in idx_to_core_types:
|
||||
for ct in idx_to_core_types[caller_idx]:
|
||||
core_outgoing_blr[ct] += 1
|
||||
|
||||
keybox_report: dict[str, dict] = {}
|
||||
keybox_total_direct_xrefs = 0
|
||||
violations = []
|
||||
for sym in KEYBOX_AND_BRIDGE_C_SYMBOLS:
|
||||
idxs = keybox_indices[sym]
|
||||
bl_cnt = sum(direct_in_bl_by_idx.get(ix, 0) for ix in idxs)
|
||||
tb_cnt = sum(direct_in_tail_b_by_idx.get(ix, 0) for ix in idxs)
|
||||
samples = []
|
||||
for ix in idxs:
|
||||
samples.extend(keybox_caller_samples.get(ix, []))
|
||||
total_sym = bl_cnt + tb_cnt
|
||||
keybox_total_direct_xrefs += total_sym
|
||||
keybox_report[sym] = {
|
||||
'present_in_dwarf': len(idxs) > 0,
|
||||
'direct_bl': bl_cnt,
|
||||
'direct_tail_b': tb_cnt,
|
||||
'total_direct_call_xrefs': total_sym,
|
||||
'caller_samples': samples[:5],
|
||||
}
|
||||
if require_zero_keybox_direct_bl and total_sym > 0:
|
||||
violations.append(f'{sym}: {total_sym} direct call xrefs ({samples[:3]})')
|
||||
|
||||
core_types_report: dict[str, dict] = {}
|
||||
for orig_type in TRACKED_CORE_TYPES:
|
||||
core_types_report[orig_type] = {
|
||||
'l1_token': l1_types.get(orig_type, orig_type),
|
||||
'outgoing_internal_direct_calls': core_outgoing_internal_bl[orig_type],
|
||||
'outgoing_indirect_blr': core_outgoing_blr[orig_type],
|
||||
'incoming_direct_calls': core_incoming_direct[orig_type],
|
||||
}
|
||||
|
||||
data_const_bytes = sections.get('__DATA_CONST,__const', {}).get('size', 0)
|
||||
text_const_bytes = sections.get('__TEXT,__const', {}).get('size', 0)
|
||||
|
||||
result = {
|
||||
'binary_path': str(binary_path),
|
||||
'binary_bytes': binary_path.stat().st_size,
|
||||
'text_bytes': text_size,
|
||||
'text_const_bytes': text_const_bytes,
|
||||
'data_const_bytes': data_const_bytes,
|
||||
'text_call_summary': {
|
||||
'total_bl': total_bl,
|
||||
'internal_text_bl': internal_text_bl,
|
||||
'interproc_tail_b': interproc_tail_b,
|
||||
'internal_direct_calls_total': internal_text_bl + interproc_tail_b,
|
||||
'dylib_stub_bl': dylib_stub_bl,
|
||||
'objc_stub_bl': objc_stub_bl,
|
||||
'other_bl': other_bl,
|
||||
'indirect_blr_total': blr_count,
|
||||
},
|
||||
'keybox_and_bridge_15_symbols': {
|
||||
'total_direct_call_xrefs': keybox_total_direct_xrefs,
|
||||
'symbols': keybox_report,
|
||||
},
|
||||
'tracked_core_types': core_types_report,
|
||||
'gate_passed': len(violations) == 0,
|
||||
'violations': violations,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def analyze_ipa_directory(
|
||||
ipa_dir: Path,
|
||||
scheme: str = 'readoor31OtherPay',
|
||||
require_zero_keybox_direct_bl: bool = False,
|
||||
) -> dict:
|
||||
ipa_path = ipa_dir / f'{scheme}.ipa'
|
||||
dsyms_zip = ipa_dir / 'dSYMs.zip'
|
||||
maps_dir = ipa_dir / 'obfuscation_maps'
|
||||
symbol_map = next(maps_dir.glob('*symbol_map*.json'), None) if maps_dir.is_dir() else None
|
||||
if not ipa_path.is_file() or not dsyms_zip.is_file():
|
||||
raise FileNotFoundError(f'Missing {ipa_path} or {dsyms_zip}')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='ig-icall-verify-') as tmp:
|
||||
tmp_path = Path(tmp)
|
||||
app_extract = tmp_path / 'ipa'
|
||||
dsym_extract = tmp_path / 'dsyms'
|
||||
subprocess.run(['ditto', '-x', '-k', str(ipa_path), str(app_extract)], check=True)
|
||||
subprocess.run(['ditto', '-x', '-k', str(dsyms_zip), str(dsym_extract)], check=True)
|
||||
main_bin = app_extract / 'Payload' / f'{scheme}.app' / scheme
|
||||
dwarf_bin = dsym_extract / f'{scheme}.app.dSYM' / 'Contents' / 'Resources' / 'DWARF' / scheme
|
||||
res = analyze_macho_calls(
|
||||
main_bin,
|
||||
dwarf_bin,
|
||||
symbol_map_path=symbol_map,
|
||||
require_zero_keybox_direct_bl=require_zero_keybox_direct_bl,
|
||||
)
|
||||
res['ipa_dir'] = str(ipa_dir)
|
||||
res['ipa_bytes'] = ipa_path.stat().st_size
|
||||
return res
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--ipa-dir', type=Path, help='Directory containing <scheme>.ipa and dSYMs.zip')
|
||||
parser.add_argument('--scheme', default='readoor31OtherPay')
|
||||
parser.add_argument('--binary', type=Path, help='Path to linked Mach-O binary')
|
||||
parser.add_argument('--dwarf', type=Path, help='Path to DWARF binary inside .dSYM')
|
||||
parser.add_argument('--symbol-map', type=Path, help='Optional L1 symbol_map.json')
|
||||
parser.add_argument('--require-zero-keybox-bl', action='store_true')
|
||||
parser.add_argument('--out', type=Path, help='Optional output JSON path')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.ipa_dir:
|
||||
report = analyze_ipa_directory(
|
||||
args.ipa_dir,
|
||||
scheme=args.scheme,
|
||||
require_zero_keybox_direct_bl=args.require_zero_keybox_bl,
|
||||
)
|
||||
elif args.binary and args.dwarf:
|
||||
report = analyze_macho_calls(
|
||||
args.binary,
|
||||
args.dwarf,
|
||||
symbol_map_path=args.symbol_map,
|
||||
require_zero_keybox_direct_bl=args.require_zero_keybox_bl,
|
||||
)
|
||||
else:
|
||||
parser.error('Specify either --ipa-dir or both --binary and --dwarf')
|
||||
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2) + '\n'
|
||||
if args.out:
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out.write_text(text, encoding='utf-8')
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
'text_call_summary': report['text_call_summary'],
|
||||
'keybox_total_direct_call_xrefs': report['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'],
|
||||
'gate_passed': report['gate_passed'],
|
||||
'violations': report['violations'],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
return 0 if report['gate_passed'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that every flattened function in linked Mach-O binary has a single-center star-switch CFG."""
|
||||
import argparse
|
||||
import bisect
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
INSN_PC_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(.*)$')
|
||||
BRANCH_UNCOND_RE = re.compile(r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+b\s+(0x[0-9a-f]+)\b')
|
||||
BRANCH_ANY_RE = re.compile(
|
||||
r'^\s*([0-9a-f]+):\s+[0-9a-f]+\s+(b|b\.\w+|cbz|cbnz|tbz|tbnz)\s+.*?(0x[0-9a-f]+)\b'
|
||||
)
|
||||
JUMP_TABLE_BR_RE = re.compile(r'\bbr\s+x\d+\b')
|
||||
RET_INSN_RE = re.compile(r'^\s*ret(?:aa|ab)?\b')
|
||||
|
||||
|
||||
def parse_dwarf_text_ranges(dwarf_bin: Path) -> dict[str, list[tuple[int, int]]]:
|
||||
"""Return mapping of symbol name -> list of (start_addr, end_addr) ranges from DWARF nm."""
|
||||
out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True)
|
||||
syms: list[tuple[int, str]] = []
|
||||
for line in out.splitlines():
|
||||
parts = line.strip().split(maxsplit=2)
|
||||
if len(parts) == 3 and parts[1].lower() == 't':
|
||||
try:
|
||||
syms.append((int(parts[0], 16), parts[2]))
|
||||
except ValueError:
|
||||
continue
|
||||
syms.sort()
|
||||
unique_addrs = sorted({addr for addr, _ in syms})
|
||||
ranges: dict[str, list[tuple[int, int]]] = {}
|
||||
for addr, name in syms:
|
||||
pos = bisect.bisect_right(unique_addrs, addr)
|
||||
next_addr = unique_addrs[pos] if pos < len(unique_addrs) else addr + 0x400
|
||||
if next_addr > addr:
|
||||
ranges.setdefault(name, []).append((addr, next_addr))
|
||||
return ranges
|
||||
|
||||
|
||||
def _inspect_range(main_bin: Path, start_addr: int, end_addr: int) -> dict:
|
||||
dis = subprocess.check_output(
|
||||
[
|
||||
'xcrun', 'llvm-objdump', '--disassemble',
|
||||
f'--start-address={hex(start_addr)}',
|
||||
f'--stop-address={hex(end_addr)}',
|
||||
str(main_bin),
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
insns: list[tuple[int, str, str]] = []
|
||||
uncond_in: dict[int, int] = {}
|
||||
uncond_back_in: dict[int, int] = {}
|
||||
func_back_edges = 0
|
||||
has_jump_table_br = False
|
||||
indirect_br_count = 0
|
||||
|
||||
for line in dis.splitlines():
|
||||
mp = INSN_PC_RE.match(line)
|
||||
if not mp:
|
||||
continue
|
||||
pc = int(mp.group(1), 16)
|
||||
rest = mp.group(2).strip()
|
||||
insns.append((pc, rest, line))
|
||||
if JUMP_TABLE_BR_RE.search(rest):
|
||||
has_jump_table_br = True
|
||||
indirect_br_count += 1
|
||||
|
||||
mu = BRANCH_UNCOND_RE.match(line)
|
||||
if mu:
|
||||
tgt = int(mu.group(2), 16)
|
||||
if start_addr <= tgt < end_addr:
|
||||
uncond_in[tgt] = uncond_in.get(tgt, 0) + 1
|
||||
if tgt < pc:
|
||||
uncond_back_in[tgt] = uncond_back_in.get(tgt, 0) + 1
|
||||
ma = BRANCH_ANY_RE.match(line)
|
||||
if ma:
|
||||
tgt = int(ma.group(3), 16)
|
||||
if start_addr <= tgt < pc:
|
||||
func_back_edges += 1
|
||||
|
||||
# Single central dispatcher hub must have >=2 unconditional fan-in, continue dispatching
|
||||
# before returning (not a shared ret epilogue), and participate in a loop back-edge or jump table.
|
||||
best_hub = None
|
||||
best_uncond = 0
|
||||
best_back = 0
|
||||
best_valid = False
|
||||
has_cycle_or_jt = func_back_edges >= 1 or has_jump_table_br
|
||||
for tgt, u_cnt in uncond_in.items():
|
||||
if u_cnt < 2:
|
||||
continue
|
||||
hub_continues_in_func = False
|
||||
for pc, rest, raw_line in insns:
|
||||
if pc < tgt:
|
||||
continue
|
||||
if RET_INSN_RE.match(rest):
|
||||
break
|
||||
if JUMP_TABLE_BR_RE.search(rest):
|
||||
hub_continues_in_func = True
|
||||
break
|
||||
ma = BRANCH_ANY_RE.match(raw_line)
|
||||
if ma:
|
||||
b_tgt = int(ma.group(3), 16)
|
||||
if start_addr <= b_tgt < end_addr:
|
||||
hub_continues_in_func = True
|
||||
break
|
||||
|
||||
b_cnt = uncond_back_in.get(tgt, 0)
|
||||
is_valid = hub_continues_in_func and (b_cnt >= 1 or has_cycle_or_jt)
|
||||
score = (1 if is_valid else 0, b_cnt, u_cnt)
|
||||
best_score = (1 if best_valid else 0, best_back, best_uncond)
|
||||
if score > best_score:
|
||||
best_hub = tgt
|
||||
best_uncond = u_cnt
|
||||
best_back = b_cnt
|
||||
best_valid = is_valid
|
||||
|
||||
reported_back = max(best_back, 1 if best_valid and has_cycle_or_jt else 0)
|
||||
return {
|
||||
'start_addr': hex(start_addr),
|
||||
'end_addr': hex(end_addr),
|
||||
'insn_count': len(insns),
|
||||
'hub_addr': hex(best_hub) if best_hub is not None else None,
|
||||
'hub_uncond_fan_in': best_uncond,
|
||||
'hub_back_edges': reported_back,
|
||||
'indirect_br_count': indirect_br_count,
|
||||
'is_star_dispatcher': best_valid,
|
||||
}
|
||||
|
||||
|
||||
def _candidate_symbol_keys(raw_name: str) -> list[str]:
|
||||
clean = raw_name.lstrip('\x01')
|
||||
keys = []
|
||||
if clean.startswith('-') or clean.startswith('+'):
|
||||
keys.append(clean)
|
||||
else:
|
||||
keys.append('_' + clean)
|
||||
keys.append(clean)
|
||||
return keys
|
||||
|
||||
|
||||
def verify_binary_star_cfg(
|
||||
main_bin: Path,
|
||||
dwarf_bin: Path,
|
||||
obf_audit: dict,
|
||||
*,
|
||||
require_topology: str = 'sparse_switch',
|
||||
fail_on_missing: bool = False,
|
||||
) -> dict:
|
||||
"""Disassemble every audited flattened function in main_bin and enforce 100% star-hub CFG."""
|
||||
ranges_map = parse_dwarf_text_ranges(dwarf_bin)
|
||||
ibr_funcs = {
|
||||
fn
|
||||
for mod in (obf_audit.get('module_audits') or [])
|
||||
for fn in (mod.get('indirect_branches_functions') or [])
|
||||
}
|
||||
|
||||
verified = []
|
||||
failed = []
|
||||
dead_stripped = []
|
||||
|
||||
to_check: list[tuple[str, dict, list[tuple[int, int]]]] = []
|
||||
for mod in obf_audit.get('module_audits') or []:
|
||||
src_name = Path(mod.get('source_path') or 'unknown').name
|
||||
for det in mod.get('functions_flattened_details') or []:
|
||||
raw_name = det['name']
|
||||
topo = det.get('topology', '')
|
||||
if require_topology and topo != require_topology:
|
||||
failed.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
'reason': f'unexpected_topology:{topo}',
|
||||
})
|
||||
continue
|
||||
|
||||
cand_ranges = []
|
||||
for key in _candidate_symbol_keys(raw_name):
|
||||
if key in ranges_map:
|
||||
cand_ranges = ranges_map[key]
|
||||
break
|
||||
if not cand_ranges:
|
||||
rec = {'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'}
|
||||
dead_stripped.append(rec)
|
||||
if fail_on_missing:
|
||||
failed.append(rec)
|
||||
continue
|
||||
to_check.append((src_name, det, cand_ranges))
|
||||
|
||||
unique_ranges = sorted({se for _, _, rlist in to_check for se in rlist})
|
||||
inspected_by_range: dict[tuple[int, int], dict] = {}
|
||||
if unique_ranges:
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = pool.map(lambda se: _inspect_range(main_bin, se[0], se[1]), unique_ranges)
|
||||
for se, res in zip(unique_ranges, results):
|
||||
inspected_by_range[se] = res
|
||||
|
||||
for src_name, det, cand_ranges in to_check:
|
||||
raw_name = det['name']
|
||||
topo = det.get('topology', '')
|
||||
has_ibr = raw_name in ibr_funcs
|
||||
# If static C symbols have duplicates across TUs, require every linked copy to pass
|
||||
range_results = [inspected_by_range[se] for se in cand_ranges]
|
||||
bad = [
|
||||
r for r in range_results
|
||||
if not (r['is_star_dispatcher'] or (has_ibr and r.get('indirect_br_count', 0) >= 2))
|
||||
]
|
||||
if bad:
|
||||
failed.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
'topology': topo,
|
||||
'blocks': det.get('blocks'),
|
||||
'reason': 'missing_star_dispatcher_hub',
|
||||
'range_results': range_results,
|
||||
})
|
||||
else:
|
||||
verified.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
'topology': topo,
|
||||
'blocks': det.get('blocks'),
|
||||
'verified_via': (
|
||||
'star_dispatcher'
|
||||
if range_results[0]['is_star_dispatcher']
|
||||
else 'indirect_br'
|
||||
),
|
||||
**range_results[0],
|
||||
})
|
||||
|
||||
summary = {
|
||||
'total_audited': len(verified) + len(failed) + (0 if fail_on_missing else len(dead_stripped)),
|
||||
'linked_checked_count': len(verified) + len(failed),
|
||||
'verified_star_count': len(verified),
|
||||
'dead_stripped_count': len(dead_stripped),
|
||||
'failed_count': len(failed),
|
||||
'failed': failed,
|
||||
'sample_verified_hubs': verified[:12],
|
||||
}
|
||||
if failed:
|
||||
preview = json.dumps(failed[:5], ensure_ascii=False, indent=2)
|
||||
raise AssertionError(f'[StarCFGGate] {len(failed)} function(s) failed star-switch CFG check:\n{preview}')
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary', type=Path, required=True)
|
||||
parser.add_argument('--dwarf', type=Path, required=True)
|
||||
parser.add_argument('--audit', type=Path, required=True)
|
||||
parser.add_argument('--require-topology', default='sparse_switch')
|
||||
args = parser.parse_args()
|
||||
|
||||
audit = json.loads(args.audit.read_text(encoding='utf-8'))
|
||||
res = verify_binary_star_cfg(
|
||||
args.binary,
|
||||
args.dwarf,
|
||||
audit,
|
||||
require_topology=args.require_topology,
|
||||
)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user