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:
@@ -21,24 +21,25 @@ ARCHIVE_SHA='485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
|
||||
def prepare_archive(guarded,output,command,baseline):
|
||||
sdk=guarded/'Frameworks/SSZipArchive.framework/SSZipArchive'
|
||||
if sha(sdk)!=ARCHIVE_SHA:raise ValueError('SSZipArchive 版本变化,须重新审核绑定规则')
|
||||
folder=guarded/'Frameworks/IGArchiveGuard.framework'
|
||||
folder=guarded/'Frameworks/RDCoreIO.framework'
|
||||
if folder.exists():raise ValueError('保护 Framework 已存在')
|
||||
folder.mkdir()
|
||||
(folder/'Info.plist').write_bytes(plistlib.dumps(dict(
|
||||
CFBundleExecutable='IGArchiveGuard',CFBundleIdentifier='cn.touchv.iosguard.archiveguard',
|
||||
CFBundleName='IGArchiveGuard',CFBundlePackageType='FMWK',CFBundleVersion='1',
|
||||
CFBundleExecutable='RDCoreIO',CFBundleIdentifier='cn.touchv.readoor.coreio',
|
||||
CFBundleName='RDCoreIO',CFBundlePackageType='FMWK',CFBundleVersion='1',
|
||||
CFBundleShortVersionString='1.0',MinimumOSVersion='15.0',CFBundleSupportedPlatforms=['iPhoneOS'])))
|
||||
sources=['dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
|
||||
command(['xcrun','--sdk','iphoneos','clang','-arch','arm64','-miphoneos-version-min=15.0',
|
||||
'-O2','-Wall','-Wextra','-Werror','-fvisibility=hidden','-DIG_OBSERVATION',
|
||||
'-DIG_ARCHIVE_INTERNAL_RESOLVE=1',
|
||||
'-I',ROOT/'defender','-I',ROOT/'defender/include','-dynamiclib',
|
||||
*(ROOT/'defender'/p for p in sources),
|
||||
'-Wl,-install_name,@rpath/IGArchiveGuard.framework/IGArchiveGuard',
|
||||
'-Wl,-install_name,@rpath/RDCoreIO.framework/RDCoreIO',
|
||||
'-Wl,-map,'+str(output/'archive-guard-link.map'),
|
||||
*(f'-Wl,-exported_symbol,_{n}' for n in
|
||||
['ig_a0','ig_a1','ig_a2','ig_a3','ig_archive_check','ig_archive_counter']),
|
||||
'-o',folder/'IGArchiveGuard'])
|
||||
symbols=command(['xcrun','nm','-g',folder/'IGArchiveGuard'])
|
||||
['rd_a0','rd_a1','rd_a2','rd_a3','rd_io_chk','ig_archive_counter']),
|
||||
'-o',folder/'RDCoreIO'])
|
||||
symbols=command(['xcrun','nm','-g',folder/'RDCoreIO'])
|
||||
if 'ig_archive_test_' in symbols:raise ValueError('业务保护 Framework 含测试接口')
|
||||
# 基线仍执行完整格式审核,但不保留 SDK 改写;两包主程序完全相同。
|
||||
temp=output/'ssziparchive-rewritten'
|
||||
|
||||
Executable
+280
@@ -0,0 +1,280 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Symbolicate modern JSON (.ips) and classic text (.crash) Apple crash reports with UUID enforcement."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FRAME_LINE_RE = re.compile(
|
||||
r'^(\d+)\s+(\S+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)(?:\s*\+\s*(\d+))?(.*)$'
|
||||
)
|
||||
BIN_IMAGE_RE = re.compile(
|
||||
r'^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+(\S+)\s+(\S+)\s+<([0-9a-fA-F-]+)>\s+(.+)$'
|
||||
)
|
||||
|
||||
|
||||
def norm_uuid(u):
|
||||
return str(u).replace('-', '').upper()
|
||||
|
||||
|
||||
def index_dsyms(dsym_root):
|
||||
"""Map normalized UUID -> {'arch': ..., 'dwarf': Path, 'dsym': Path}."""
|
||||
mapping = {}
|
||||
root = Path(dsym_root)
|
||||
candidates = []
|
||||
if root.is_dir() and root.suffix == '.dSYM':
|
||||
candidates.append(root)
|
||||
elif root.is_dir():
|
||||
candidates.extend(sorted(root.glob('*.dSYM')))
|
||||
else:
|
||||
raise FileNotFoundError(f'dSYM path not found: {root}')
|
||||
|
||||
for dsym in candidates:
|
||||
dwarf_dir = dsym / 'Contents' / 'Resources' / 'DWARF'
|
||||
if not dwarf_dir.is_dir():
|
||||
continue
|
||||
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dsym)], text=True)
|
||||
for line in out.splitlines():
|
||||
m = re.match(r'^UUID:\s*([0-9A-Fa-f-]+)\s+\(([^)]+)\)\s+(.+)$', line.strip())
|
||||
if m:
|
||||
uid = norm_uuid(m.group(1))
|
||||
arch = m.group(2)
|
||||
dwarf_path = Path(m.group(3).strip())
|
||||
mapping[uid] = {'arch': arch, 'dwarf': dwarf_path, 'dsym': dsym}
|
||||
return mapping
|
||||
|
||||
|
||||
def _unwrap_v2_mappings(raw) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
if isinstance(raw.get('mappings'), dict) and (
|
||||
'schema_version' in raw or raw.get('kind') in ('symbol_map', 'method_map')
|
||||
):
|
||||
return raw['mappings']
|
||||
return raw
|
||||
|
||||
|
||||
def load_reverse_maps(symbol_map_path=None, method_map_path=None):
|
||||
cls_rev = {}
|
||||
sel_rev = {}
|
||||
if symbol_map_path and Path(symbol_map_path).is_file():
|
||||
raw = _unwrap_v2_mappings(json.loads(Path(symbol_map_path).read_text(encoding='utf-8')))
|
||||
for orig, obf in raw.items():
|
||||
if isinstance(obf, str):
|
||||
cls_rev[obf] = orig
|
||||
elif isinstance(obf, dict) and isinstance(obf.get('obfuscated'), str):
|
||||
cls_rev[obf['obfuscated']] = orig
|
||||
if method_map_path and Path(method_map_path).is_file():
|
||||
raw = _unwrap_v2_mappings(json.loads(Path(method_map_path).read_text(encoding='utf-8')))
|
||||
for orig, obf in raw.items():
|
||||
if isinstance(obf, str):
|
||||
sel_rev[obf] = orig
|
||||
if ':' in orig:
|
||||
orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig)
|
||||
for idx, orig_part in enumerate(orig_parts, start=1):
|
||||
sel_rev.setdefault(f'{obf}_{idx}:', orig_part)
|
||||
if orig_parts:
|
||||
sel_rev.setdefault(f'{obf}_1', orig_parts[0][:-1])
|
||||
elif isinstance(obf, list):
|
||||
for item in obf:
|
||||
if isinstance(item, str):
|
||||
sel_rev[item] = orig
|
||||
elif isinstance(obf, dict):
|
||||
full_obf = obf.get('obfuscated')
|
||||
tok = obf.get('token')
|
||||
parts = obf.get('parts')
|
||||
if isinstance(full_obf, str) and full_obf:
|
||||
sel_rev[full_obf] = orig
|
||||
if obf.get('kind') == 'objc_selector' and isinstance(parts, list) and ':' in orig:
|
||||
orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig)
|
||||
if len(orig_parts) == len(parts):
|
||||
for obf_part, orig_part in zip(parts, orig_parts):
|
||||
norm_obf = obf_part if obf_part.endswith(':') else f'{obf_part}:'
|
||||
sel_rev.setdefault(norm_obf, orig_part)
|
||||
if isinstance(tok, str) and tok and orig_parts:
|
||||
sel_rev.setdefault(tok, orig_parts[0][:-1])
|
||||
elif isinstance(tok, str) and tok:
|
||||
sel_rev[tok] = orig
|
||||
return cls_rev, sel_rev
|
||||
|
||||
|
||||
def deobfuscate_symbol_text(text, cls_rev, sel_rev):
|
||||
out = text
|
||||
combined = {}
|
||||
combined.update(cls_rev)
|
||||
combined.update(sel_rev)
|
||||
for obf, orig in sorted(combined.items(), key=lambda kv: -len(kv[0])):
|
||||
if not obf or obf not in out:
|
||||
continue
|
||||
if ':' in obf:
|
||||
out = out.replace(obf, orig)
|
||||
else:
|
||||
out = re.sub(r'(?<![A-Za-z0-9_])' + re.escape(obf) + r'(?![A-Za-z0-9_])', orig, out)
|
||||
return out
|
||||
|
||||
|
||||
def atos_lookup(dwarf_path, load_addr_hex, addr_hex, arch='arm64'):
|
||||
out = subprocess.check_output(
|
||||
['xcrun', 'atos', '-arch', arch, '-o', str(dwarf_path), '-l', load_addr_hex, '-inlineFrames', addr_hex],
|
||||
text=True,
|
||||
).strip()
|
||||
return [line.strip() for line in out.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def parse_ips(text):
|
||||
lines = [l for l in text.splitlines() if l.strip()]
|
||||
if not lines:
|
||||
raise ValueError('Empty .ips report')
|
||||
header = json.loads(lines[0])
|
||||
body = json.loads('\n'.join(lines[1:])) if len(lines) > 1 else header
|
||||
return header, body
|
||||
|
||||
|
||||
def symbolicate_ips(text, dsym_index, cls_rev, sel_rev):
|
||||
_, body = parse_ips(text)
|
||||
used_images = body.get('usedImages') or []
|
||||
results = []
|
||||
for t_idx, thread in enumerate(body.get('threads') or []):
|
||||
if not thread.get('triggered') and len(body.get('threads') or []) > 1 and t_idx != 0:
|
||||
continue
|
||||
frames_out = []
|
||||
for f_idx, frame in enumerate(thread.get('frames') or []):
|
||||
img_idx = frame.get('imageIndex')
|
||||
img_off = frame.get('imageOffset')
|
||||
if img_idx is None or img_off is None or img_idx >= len(used_images):
|
||||
continue
|
||||
img = used_images[img_idx]
|
||||
uid = norm_uuid(img.get('uuid', ''))
|
||||
base = img.get('base', 0)
|
||||
name = img.get('name', img.get('path', f'img_{img_idx}'))
|
||||
addr_hex = hex(base + img_off)
|
||||
base_hex = hex(base)
|
||||
dsym_entry = dsym_index.get(uid)
|
||||
if not dsym_entry:
|
||||
# Require UUID match for app/embedded bundle binaries
|
||||
img_path = img.get('path', '')
|
||||
if '.app/' in img_path:
|
||||
raise RuntimeError(
|
||||
f'UUID mismatch or missing dSYM for bundle image {name} (uuid={img.get("uuid")})'
|
||||
)
|
||||
frames_out.append({
|
||||
'frame_index': f_idx,
|
||||
'image': name,
|
||||
'uuid': img.get('uuid'),
|
||||
'address': addr_hex,
|
||||
'status': 'system_or_unindexed',
|
||||
'inline_frames': [],
|
||||
})
|
||||
continue
|
||||
raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img.get('arch', 'arm64'))
|
||||
restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms]
|
||||
frames_out.append({
|
||||
'frame_index': f_idx,
|
||||
'image': name,
|
||||
'uuid': img.get('uuid'),
|
||||
'dsym': str(dsym_entry['dsym']),
|
||||
'load_address': base_hex,
|
||||
'address': addr_hex,
|
||||
'status': 'symbolicated',
|
||||
'raw_atos': raw_syms,
|
||||
'restored_frames': restored,
|
||||
})
|
||||
results.append({'thread_index': t_idx, 'triggered': bool(thread.get('triggered')), 'frames': frames_out})
|
||||
return {'format': 'ips_json', 'threads': results}
|
||||
|
||||
|
||||
def symbolicate_crash(text, dsym_index, cls_rev, sel_rev):
|
||||
images_by_name = {}
|
||||
in_bin_images = False
|
||||
for line in text.splitlines():
|
||||
if line.strip().startswith('Binary Images:'):
|
||||
in_bin_images = True
|
||||
continue
|
||||
if in_bin_images:
|
||||
m = BIN_IMAGE_RE.match(line)
|
||||
if m:
|
||||
start_hex, _, name, arch, uid_str, path = m.groups()
|
||||
images_by_name[name] = {
|
||||
'base_hex': start_hex,
|
||||
'name': name,
|
||||
'arch': arch,
|
||||
'uuid': uid_str,
|
||||
'uuid_norm': norm_uuid(uid_str),
|
||||
'path': path.strip(),
|
||||
}
|
||||
|
||||
frames_out = []
|
||||
for line in text.splitlines():
|
||||
m = FRAME_LINE_RE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
f_idx, img_name, addr_hex, base_or_sym, _, _ = m.groups()
|
||||
img = images_by_name.get(img_name)
|
||||
if not img:
|
||||
continue
|
||||
uid = img['uuid_norm']
|
||||
base_hex = img['base_hex']
|
||||
dsym_entry = dsym_index.get(uid)
|
||||
if not dsym_entry:
|
||||
if '.app/' in img['path']:
|
||||
raise RuntimeError(
|
||||
f'UUID mismatch or missing dSYM for bundle image {img_name} (uuid={img["uuid"]})'
|
||||
)
|
||||
frames_out.append({
|
||||
'frame_index': int(f_idx),
|
||||
'image': img_name,
|
||||
'uuid': img['uuid'],
|
||||
'address': addr_hex,
|
||||
'status': 'system_or_unindexed',
|
||||
'restored_frames': [],
|
||||
})
|
||||
continue
|
||||
raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img['arch'])
|
||||
restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms]
|
||||
frames_out.append({
|
||||
'frame_index': int(f_idx),
|
||||
'image': img_name,
|
||||
'uuid': img['uuid'],
|
||||
'dsym': str(dsym_entry['dsym']),
|
||||
'load_address': base_hex,
|
||||
'address': addr_hex,
|
||||
'status': 'symbolicated',
|
||||
'raw_atos': raw_syms,
|
||||
'restored_frames': restored,
|
||||
})
|
||||
return {'format': 'crash_text', 'images_parsed': len(images_by_name), 'frames': frames_out}
|
||||
|
||||
|
||||
def restore_report(report_path, dsym_dir, symbol_map=None, method_map=None):
|
||||
text = Path(report_path).read_text(encoding='utf-8', errors='replace')
|
||||
dsym_index = index_dsyms(dsym_dir)
|
||||
cls_rev, sel_rev = load_reverse_maps(symbol_map, method_map)
|
||||
|
||||
first_nonempty = next((l.strip() for l in text.splitlines() if l.strip()), '')
|
||||
if first_nonempty.startswith('{'):
|
||||
return symbolicate_ips(text, dsym_index, cls_rev, sel_rev)
|
||||
return symbolicate_crash(text, dsym_index, cls_rev, sel_rev)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--report', required=True, type=Path)
|
||||
p.add_argument('--dsym-dir', required=True, type=Path)
|
||||
p.add_argument('--symbol-map', type=Path)
|
||||
p.add_argument('--method-map', type=Path)
|
||||
p.add_argument('--out', type=Path)
|
||||
args = p.parse_args()
|
||||
|
||||
res = restore_report(args.report, args.dsym_dir, args.symbol_map, args.method_map)
|
||||
text = json.dumps(res, ensure_ascii=False, indent=2) + '\n'
|
||||
if args.out:
|
||||
args.out.write_text(text, encoding='utf-8')
|
||||
else:
|
||||
sys.stdout.write(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
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()
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attribute direct calls in a Mach-O to objects in its same-build Link Map."""
|
||||
|
||||
import argparse
|
||||
from bisect import bisect_right
|
||||
import csv
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from machox import Macho
|
||||
from redirect_to_runtime import defined_symbols
|
||||
from verify_baseline import inspect_binary
|
||||
|
||||
|
||||
def load_link_map(path):
|
||||
objects, symbols = {}, []
|
||||
section = ''
|
||||
for line in path.read_text(errors='replace').splitlines():
|
||||
if line in ('# Object files:', '# Sections:', '# Symbols:', '# Dead Stripped Symbols:'):
|
||||
section = line
|
||||
elif line.startswith('# '):
|
||||
continue
|
||||
elif section == '# Object files:':
|
||||
match = re.fullmatch(r'\[\s*(\d+)\]\s+(.+)', line)
|
||||
if match:
|
||||
objects[int(match[1])] = match[2]
|
||||
elif section == '# Symbols:':
|
||||
match = re.fullmatch(r'(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+\[\s*(\d+)\]\s+(.+)', line)
|
||||
if match and int(match[2], 16):
|
||||
symbols.append((int(match[1], 16), int(match[2], 16), int(match[3]), match[4]))
|
||||
if not objects or not symbols:
|
||||
raise ValueError(f'Incomplete Link Map: {path}')
|
||||
return objects, sorted(symbols)
|
||||
|
||||
|
||||
def attribute(binary, link_map):
|
||||
objects, entries = load_link_map(link_map)
|
||||
defined = defined_symbols(Macho(binary.read_bytes()))
|
||||
# Require matching named functions before trusting the object addresses.
|
||||
common = [(address, defined[name]) for address, _, _, name in entries if name in defined]
|
||||
if not common or any(mapped != actual for mapped, actual in common):
|
||||
raise ValueError('Link Map symbols do not match executable')
|
||||
_, calls = inspect_binary(binary)
|
||||
starts = [entry[0] for entry in entries]
|
||||
for call in calls:
|
||||
site = int(call['site'], 16)
|
||||
index = bisect_right(starts, site) - 1
|
||||
if index >= 0:
|
||||
address, size, obj, name = entries[index]
|
||||
if site < address + size and (index == 0 or starts[index - 1] != address):
|
||||
call.update(caller=name, object=objects.get(obj, ''))
|
||||
yield call
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('binary', type=Path)
|
||||
parser.add_argument('link_map', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
args = parser.parse_args()
|
||||
rows = list(attribute(args.binary, args.link_map))
|
||||
with args.output.open('x', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=['slice_offset', 'site', 'target', 'branch', 'symbol', 'caller', 'object'])
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
@@ -73,7 +73,7 @@ def build(profile, identity, bundle, output):
|
||||
(app / 'Info.plist').write_bytes(plistlib.dumps(info))
|
||||
|
||||
common = ['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
||||
'-miphoneos-version-min=15.0', '-O2',
|
||||
'-miphoneos-version-min=15.0', '-O2', '-DIG_OBSERVATION=1',
|
||||
'-I', source / 'defender', '-I', source / 'defender/include']
|
||||
modules = ['IGDefender.c', 'dispatch/IGDispatch.c', 'resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c',
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Relink one captured release command with hash-verified SDK candidate inputs."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
from redirect_to_runtime import patch
|
||||
|
||||
|
||||
def sha(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def relink(log, manifest_path, output, working_directory):
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
root = manifest_path.parent
|
||||
verified = set()
|
||||
for record in manifest['files']:
|
||||
path = (root / record['path']).resolve()
|
||||
verified.add(path)
|
||||
if sha(path) != record['sha256']:
|
||||
raise ValueError(f'SDK candidate changed: {path}')
|
||||
required = [(root / item).resolve() for item in manifest['objects']]
|
||||
required += [(root / rule['file']).resolve() for rule in manifest['replacements']]
|
||||
required.append((root / manifest['patch_profile']).resolve())
|
||||
if not set(required) <= verified:
|
||||
raise ValueError('Candidate file missing from hash manifest')
|
||||
commands = []
|
||||
for line in log.read_text(errors='replace').splitlines():
|
||||
if '/bin/clang++ ' in line:
|
||||
argv = shlex.split(line)
|
||||
if '-o' in argv and argv[argv.index('-o') + 1].endswith(
|
||||
'.app/' + manifest['executable']):
|
||||
commands.append(argv)
|
||||
if len(commands) != 1:
|
||||
raise ValueError('Need exactly one matching release link command')
|
||||
argv = commands[0]
|
||||
if any(arg.startswith(('-fprofile', '-fcoverage')) for arg in argv):
|
||||
raise ValueError('Release link still enables coverage')
|
||||
for rule in manifest['replacements']:
|
||||
needle = rule['arguments']
|
||||
positions = [i for i in range(len(argv) - len(needle) + 1)
|
||||
if argv[i:i + len(needle)] == needle]
|
||||
if len(positions) != 1:
|
||||
raise ValueError(f'Link input missing or duplicated: {needle}')
|
||||
i = positions[0]
|
||||
argv[i:i + len(needle)] = [str((root / rule['file']).resolve())]
|
||||
prepend = [str((root / item).resolve()) for item in manifest['objects']]
|
||||
prepend += ['-F' + str((root / item).resolve()) for item in manifest['framework_search']]
|
||||
argv[1:1] = prepend
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
output.mkdir()
|
||||
for key, name in [('-map', 'LinkMap.txt'), ('-object_path_lto', 'lto.o'),
|
||||
('-dependency_info', 'dependency_info.dat')]:
|
||||
if key not in argv and key == '-map':
|
||||
argv[1:1] = ['-Xlinker', '-map', '-Xlinker', str(output / name)]
|
||||
continue
|
||||
i = argv.index(key)
|
||||
if argv[i + 1] != '-Xlinker':
|
||||
raise ValueError(f'Unexpected linker argument layout: {key}')
|
||||
argv[i + 2] = str(output / name)
|
||||
binary = output / manifest['executable']
|
||||
argv[argv.index('-o') + 1] = str(output / 'unpatched')
|
||||
(output / 'link-argv.json').write_text(json.dumps(argv, indent=2) + '\n')
|
||||
with (output / 'link.log').open('w') as stream:
|
||||
subprocess.run(argv, cwd=working_directory, stdout=stream,
|
||||
stderr=subprocess.STDOUT, check=True)
|
||||
profile = json.loads((root / manifest['patch_profile']).read_text())
|
||||
report = patch(output / 'unpatched', binary, output / 'LinkMap.txt', profile)
|
||||
(output / 'patch.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
(output / 'inputs.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
return binary
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('build_log', 'manifest', 'output', 'working_directory'):
|
||||
parser.add_argument(name, type=Path)
|
||||
args = parser.parse_args()
|
||||
print(relink(args.build_log.resolve(), args.manifest.resolve(),
|
||||
args.output.resolve(), args.working_directory.resolve()))
|
||||
@@ -0,0 +1,326 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package Route 2 hardened app bundle, build IGArchiveGuard, redirect all embedded frameworks, audit & sign."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from batch import arm64_slices, iter_macho_files, Slice
|
||||
from machox import Macho, LC_DYLD_CHAINED_FIXUPS
|
||||
from redirect_framework_imports import (
|
||||
DEPENDENCY,
|
||||
detect_chained_target_mapping,
|
||||
rewrite as rewrite_chained,
|
||||
)
|
||||
from redirect_legacy_imports import (
|
||||
detect_legacy_target_mapping,
|
||||
rewrite as rewrite_legacy,
|
||||
)
|
||||
from verify_baseline import inspect_binary, scan
|
||||
|
||||
EXTERNAL_SYMBOLS = ('_fopen', '_dlopen', '_dlsym')
|
||||
SYSTEM_SYMBOLS = ('_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid')
|
||||
FORBIDDEN_SYMBOLS = set(EXTERNAL_SYMBOLS) | set(SYSTEM_SYMBOLS)
|
||||
|
||||
EXPECTED_ARCHIVE_EXPORTS = {
|
||||
'_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4',
|
||||
'_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w',
|
||||
'_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k',
|
||||
'_rd_l00', '_rd_s0', '_rd_s',
|
||||
'_rd_io_cfg', '_rd_io_chk', '_rd_io_ev',
|
||||
}
|
||||
|
||||
|
||||
def sha256(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def run_cmd(*args, env=None, cwd=None):
|
||||
return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True)
|
||||
|
||||
|
||||
def build_archive_guard(defender_dir, framework_dir):
|
||||
if framework_dir.exists():
|
||||
shutil.rmtree(framework_dir)
|
||||
framework_dir.mkdir(parents=True)
|
||||
binary = framework_dir / 'RDCoreIO'
|
||||
sources = [
|
||||
defender_dir / 'dispatch/IGArchiveGuard.c',
|
||||
defender_dir / 'resolve/IGResolve.c',
|
||||
defender_dir / 'anti_hook/IGAntiHook.c',
|
||||
]
|
||||
subprocess.run([
|
||||
'xcrun', '--sdk', 'iphoneos', 'clang',
|
||||
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-O2',
|
||||
'-Wall', '-Wextra', '-Werror', '-fvisibility=hidden', '-dynamiclib',
|
||||
'-DIG_ARCHIVE_INTERNAL_RESOLVE=1',
|
||||
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
|
||||
*map(str, sources),
|
||||
'-Wl,-install_name,' + DEPENDENCY,
|
||||
'-o', str(binary),
|
||||
], check=True)
|
||||
|
||||
plist = {
|
||||
'CFBundleExecutable': 'RDCoreIO',
|
||||
'CFBundleIdentifier': 'cn.touchv.readoor.coreio',
|
||||
'CFBundleName': 'RDCoreIO',
|
||||
'CFBundlePackageType': 'FMWK',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'CFBundleSupportedPlatforms': ['iPhoneOS'],
|
||||
'CFBundleVersion': '1',
|
||||
'MinimumOSVersion': '15.0',
|
||||
}
|
||||
with (framework_dir / 'Info.plist').open('wb') as stream:
|
||||
plistlib.dump(plist, stream)
|
||||
|
||||
exports_out = run_cmd('xcrun', 'nm', '-gU', binary)
|
||||
exported = {line.split()[-1] for line in exports_out.splitlines() if line.split()}
|
||||
missing = EXPECTED_ARCHIVE_EXPORTS - exported
|
||||
if missing:
|
||||
raise ValueError(f'RDCoreIO missing expected exports: {sorted(missing)}')
|
||||
leaked_ig = sorted(s for s in exported if s.startswith('_ig_'))
|
||||
if leaked_ig:
|
||||
raise ValueError(f'RDCoreIO leaked _ig_* exports: {leaked_ig}')
|
||||
|
||||
undef_out = run_cmd('xcrun', 'nm', '-u', binary)
|
||||
undef = {line.split()[-1] for line in undef_out.splitlines() if line.split()}
|
||||
forbidden_undef = undef & FORBIDDEN_SYMBOLS
|
||||
if forbidden_undef:
|
||||
raise ValueError(f'RDCoreIO has forbidden undefined imports: {sorted(forbidden_undef)}')
|
||||
|
||||
info, sites = inspect_binary(binary)
|
||||
if sites:
|
||||
raise ValueError(f'RDCoreIO has direct target calls: {sites}')
|
||||
return dict(sha256=sha256(binary), exported_count=len(exported), inspect=info)
|
||||
|
||||
|
||||
def thin_if_fat(binary_path):
|
||||
raw = binary_path.read_bytes()
|
||||
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
|
||||
with tempfile.NamedTemporaryFile(dir=binary_path.parent, delete=False) as tf:
|
||||
tmp = Path(tf.name)
|
||||
try:
|
||||
subprocess.run(['xcrun', 'lipo', str(binary_path), '-thin', 'arm64', '-output', str(tmp)], check=True)
|
||||
shutil.copymode(binary_path, tmp)
|
||||
tmp.replace(binary_path)
|
||||
return True
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
return False
|
||||
|
||||
|
||||
def process_framework(fw_dir):
|
||||
name = fw_dir.stem
|
||||
codesig = fw_dir / '_CodeSignature'
|
||||
if codesig.exists():
|
||||
shutil.rmtree(codesig)
|
||||
binary = fw_dir / name
|
||||
if not binary.is_file():
|
||||
raise FileNotFoundError(binary)
|
||||
|
||||
thinned = thin_if_fat(binary)
|
||||
raw = binary.read_bytes()
|
||||
slices = arm64_slices(raw)
|
||||
if len(slices) != 1 or slices[0][0] != 0:
|
||||
raise ValueError(f'{name}: expected single thin arm64 Mach-O')
|
||||
m = Macho(raw)
|
||||
has_chained = any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds)
|
||||
has_dyld_info = any(c in (0x22, 0x80000022) for c, _, _ in m.cmds)
|
||||
|
||||
include_stdio_rw = (name == 'SSZipArchive')
|
||||
if has_chained:
|
||||
mapping = detect_chained_target_mapping(raw, include_stdio_rw=include_stdio_rw)
|
||||
mode = 'chained'
|
||||
elif has_dyld_info:
|
||||
mapping = detect_legacy_target_mapping(raw)
|
||||
mode = 'legacy_dyld_info'
|
||||
else:
|
||||
mapping = {}
|
||||
mode = 'none'
|
||||
|
||||
before_info, _ = inspect_binary(binary)
|
||||
if mapping:
|
||||
in_sha = hashlib.sha256(raw).hexdigest()
|
||||
if mode == 'chained':
|
||||
out_bytes, report = rewrite_chained(raw, in_sha, mapping)
|
||||
else:
|
||||
out_bytes, report = rewrite_legacy(raw, in_sha, mapping)
|
||||
binary.write_bytes(out_bytes)
|
||||
after_info, after_sites = inspect_binary(binary)
|
||||
if after_sites:
|
||||
raise ValueError(f'{name}: remaining direct calls after rewrite: {after_sites}')
|
||||
return dict(
|
||||
framework=name,
|
||||
mode=mode,
|
||||
thinned=thinned,
|
||||
before_total=sum(s['total'] for s in before_info['slices']),
|
||||
after_total=sum(s['total'] for s in after_info['slices']),
|
||||
symbols_redirected=len(mapping),
|
||||
mapping=mapping,
|
||||
output_sha256=report['output_sha256'],
|
||||
)
|
||||
|
||||
if sum(s['total'] for s in before_info['slices']) > 0:
|
||||
raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}')
|
||||
return dict(
|
||||
framework=name,
|
||||
mode='clean_no_change' if not thinned else 'thinned_clean',
|
||||
thinned=thinned,
|
||||
before_total=0,
|
||||
after_total=0,
|
||||
symbols_redirected=0,
|
||||
)
|
||||
|
||||
|
||||
def regenerate_whitelist(app_repo, payload_dir, app_name):
|
||||
script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
|
||||
env = dict(os.environ)
|
||||
env['TARGET_BUILD_DIR'] = str(payload_dir)
|
||||
env['WRAPPER_NAME'] = app_name
|
||||
env['EXECUTABLE_PATH'] = Path(app_name).stem
|
||||
out = run_cmd(sys.executable, script, env=env, cwd=app_repo)
|
||||
plist_path = payload_dir / app_name / 'RDKnownImages.plist'
|
||||
data = plistlib.loads(plist_path.read_bytes())
|
||||
return dict(stdout=out.strip(), entry_count=len(data['known_images']), digest=data['digest'])
|
||||
|
||||
|
||||
def adhoc_sign_and_verify(app_dir):
|
||||
frameworks = sorted((app_dir / 'Frameworks').glob('*.framework'))
|
||||
for fw in frameworks:
|
||||
subprocess.run(['codesign', '--force', '--sign', '-', str(fw)], check=True)
|
||||
subprocess.run(['codesign', '--force', '--sign', '-', str(app_dir)], check=True)
|
||||
|
||||
verified = []
|
||||
for target in [*frameworks, app_dir]:
|
||||
subprocess.run(['codesign', '--verify', '--strict', str(target)], check=True)
|
||||
verified.append(str(target.relative_to(app_dir.parent)))
|
||||
return verified
|
||||
|
||||
|
||||
def package(source_app, relinked_main, app_repo, output):
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
output.mkdir(parents=True)
|
||||
payload_dir = output / 'Payload'
|
||||
payload_dir.mkdir()
|
||||
app_dir = payload_dir / source_app.name
|
||||
shutil.copytree(source_app, app_dir, symlinks=True)
|
||||
|
||||
app_sig = app_dir / '_CodeSignature'
|
||||
if app_sig.exists():
|
||||
shutil.rmtree(app_sig)
|
||||
|
||||
main_bin = app_dir / relinked_main.name
|
||||
shutil.copy2(relinked_main, main_bin)
|
||||
main_bin.chmod(0o755)
|
||||
|
||||
defender_dir = app_repo / 'readoor/3.0/Base/Security/IGDefender'
|
||||
guard_report = build_archive_guard(defender_dir, app_dir / 'Frameworks/RDCoreIO.framework')
|
||||
|
||||
fw_reports = []
|
||||
for fw_dir in sorted((app_dir / 'Frameworks').glob('*.framework')):
|
||||
if fw_dir.name == 'RDCoreIO.framework':
|
||||
continue
|
||||
fw_reports.append(process_framework(fw_dir))
|
||||
(output / 'framework-rewrites.json').write_text(json.dumps(fw_reports, indent=2) + '\n')
|
||||
|
||||
whitelist_report = regenerate_whitelist(app_repo, payload_dir, source_app.name)
|
||||
|
||||
binaries, callsite_total = scan(app_dir, output, 'route2')
|
||||
combined_counts = {}
|
||||
for rel, info in binaries.items():
|
||||
for sl in info['slices']:
|
||||
for sym, cnt in sl['counts'].items():
|
||||
combined_counts[sym] = combined_counts.get(sym, 0) + cnt
|
||||
|
||||
external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS)
|
||||
system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS)
|
||||
|
||||
if len(binaries) != 44:
|
||||
raise ValueError(f'Expected 44 Mach-O binaries, got {len(binaries)}')
|
||||
if external_call_total != 0 or system_call_total != 0 or callsite_total != 0:
|
||||
raise ValueError(
|
||||
f'Non-zero residual callsites: external={external_call_total}, '
|
||||
f'system={system_call_total}, total={callsite_total}, counts={combined_counts}'
|
||||
)
|
||||
|
||||
variant_stubs = []
|
||||
for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))):
|
||||
mdata = mpath.read_bytes()
|
||||
for off, _ in arm64_slices(mdata):
|
||||
sl = Slice(mdata, off)
|
||||
if not (sl.stubs and sl.symtab and sl.dysym):
|
||||
continue
|
||||
import struct
|
||||
symoff, _, stroff, _ = sl.symtab
|
||||
indoff = sl.dysym[12]
|
||||
_, ssize, _, sr1, sr2 = sl.stubs
|
||||
for idx_pos in range(ssize // sr2):
|
||||
symi, = struct.unpack_from('<I', mdata, off + indoff + (sr1 + idx_pos) * 4)
|
||||
strx, = struct.unpack_from('<I', mdata, off + symoff + symi * 16)
|
||||
sname = mdata[off + stroff + strx:mdata.index(b'\0', off + stroff + strx)].decode(errors='replace')
|
||||
if sname == '_fopen$DARWIN_EXTSN' or any(sname.startswith(f + '$') for f in FORBIDDEN_SYMBOLS):
|
||||
variant_stubs.append((str(mpath.relative_to(app_dir)), sname))
|
||||
if variant_stubs:
|
||||
raise ValueError(f'Found Darwin variant stubs of target symbols: {variant_stubs}')
|
||||
|
||||
main_undef_out = run_cmd('xcrun', 'nm', '-u', main_bin)
|
||||
main_undef = {line.split()[-1] for line in main_undef_out.splitlines() if line.split()}
|
||||
if '_fopen$DARWIN_EXTSN' in main_undef or any(any(u.startswith(f + '$') for f in FORBIDDEN_SYMBOLS) for u in main_undef):
|
||||
raise ValueError(f'Main binary still imports Darwin variant of target symbol: {sorted(main_undef)}')
|
||||
main_defined_out = run_cmd('xcrun', 'nm', '-U', main_bin)
|
||||
main_defined = {line.split()[-1] for line in main_defined_out.splitlines() if line.split()}
|
||||
expected_dispatch_exports = {
|
||||
'_IG_dispatch_fopen', '_IG_dispatch_dlopen', '_IG_dispatch_dlsym',
|
||||
'_IG_dispatch_write', '_IG_dispatch_read', '_IG_dispatch_open',
|
||||
'_IG_dispatch_close', '_IG_dispatch_exit', '_IG_dispatch_fork',
|
||||
'_IG_dispatch_unlink', '_IG_dispatch_getpid',
|
||||
}
|
||||
missing_dispatch = expected_dispatch_exports - main_defined
|
||||
if missing_dispatch:
|
||||
raise ValueError(f'Main binary missing IG_dispatch symbols: {sorted(missing_dispatch)}')
|
||||
|
||||
verified_bundles = adhoc_sign_and_verify(app_dir)
|
||||
ipa_path = output / 'route2-adhoc.ipa'
|
||||
subprocess.run(['ditto', '-c', '-k', '--keepParent', str(payload_dir), str(ipa_path)], check=True)
|
||||
|
||||
summary = dict(
|
||||
binaries=len(binaries),
|
||||
external_call_total=external_call_total,
|
||||
system_call_total=system_call_total,
|
||||
direct_calls=combined_counts,
|
||||
main_binary_forbidden_undef=sorted(main_undef & FORBIDDEN_SYMBOLS),
|
||||
ig_archive_guard=guard_report,
|
||||
frameworks_rewritten=sum(1 for r in fw_reports if r['symbols_redirected'] > 0),
|
||||
frameworks_thinned=sum(1 for r in fw_reports if r['thinned']),
|
||||
whitelist=whitelist_report,
|
||||
codesign_verified_count=len(verified_bundles),
|
||||
ipa=str(ipa_path),
|
||||
ipa_sha256=sha256(ipa_path),
|
||||
)
|
||||
(output / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
|
||||
return summary
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source-app', type=Path, required=True)
|
||||
parser.add_argument('--relinked-main', type=Path, required=True)
|
||||
parser.add_argument('--app-repo', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
result = package(
|
||||
args.source_app.resolve(),
|
||||
args.relinked_main.resolve(),
|
||||
args.app_repo.resolve(),
|
||||
args.output.resolve(),
|
||||
)
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"caller": "__isJailbreak",
|
||||
"symbol": "_fopen",
|
||||
"destination": "_IG_dispatch_fopen",
|
||||
"expected_count": 6
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"caller": "__isJailbreak",
|
||||
"symbol": "_fopen",
|
||||
"destination": "_IG_dispatch_fopen",
|
||||
"expected_count": 6
|
||||
},
|
||||
{
|
||||
"caller": "_SignalHandler",
|
||||
"symbol": "_getpid",
|
||||
"destination": "_IG_dispatch_getpid",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "+[UMInternalUtil Value2]",
|
||||
"symbol": "_getpid",
|
||||
"destination": "_IG_dispatch_getpid",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__initializeAvailabilityCheck",
|
||||
"symbol": "_fopen",
|
||||
"destination": "_IG_dispatch_fopen",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__initializeAvailabilityCheck",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 10
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZL25swift_voucher_needs_adoptP9voucher_sENKUlvE_clEvENUlPvE_8__invokeES2_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZN5swift19_swift_tsan_acquireEPvENK3$_0clEvENUlS0_E_8__invokeES0_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZN5swift19_swift_tsan_releaseEPvENK3$_0clEvENUlS0_E_8__invokeES0_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZN5swift31swift_task_escalateBackdeploy56EPNS_9AsyncTaskENS_11JobPriorityEENK3$_0clEvENUlPvE_8__invokeES4_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZN5swift45swift_task_exitThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
},
|
||||
{
|
||||
"caller": "__ZZZN5swift46swift_task_enterThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_",
|
||||
"symbol": "_dlsym",
|
||||
"destination": "_IG_dispatch_dlsym",
|
||||
"expected_count": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -8,8 +8,29 @@ import struct
|
||||
|
||||
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
DEPENDENCY = '@rpath/IGArchiveGuard.framework/IGArchiveGuard'
|
||||
MAPPING = {'_fopen': '_ig_a0', '_fread': '_ig_a1', '_fwrite': '_ig_a2', '_fclose': '_ig_a3'}
|
||||
GUARD_FRAMEWORK_NAME = 'RDCoreIO'
|
||||
DEPENDENCY = '@rpath/RDCoreIO.framework/RDCoreIO'
|
||||
MAPPING = {'_fopen': '_rd_a0', '_fread': '_rd_a1', '_fwrite': '_rd_a2', '_fclose': '_rd_a3'}
|
||||
ALLOWED_MAPPING = {
|
||||
'_fopen': '_rd_a0',
|
||||
'_fread': '_rd_a1',
|
||||
'_fwrite': '_rd_a2',
|
||||
'_fclose': '_rd_a3',
|
||||
'_unlink': '_rd_a4',
|
||||
'_open': '_rd_o',
|
||||
'_read': '_rd_r',
|
||||
'_write': '_rd_w0',
|
||||
'_close': '_rd_c0',
|
||||
'_getpid': '_rd_p00',
|
||||
'_exit': '_rd_e',
|
||||
'_fork': '_rd_k',
|
||||
'_dlopen': '_rd_l00',
|
||||
'_dlsym': '_rd_s0',
|
||||
}
|
||||
REPORT_TARGET_SYMBOLS = {
|
||||
'_fopen', '_dlopen', '_dlsym', '_write', '_read', '_open',
|
||||
'_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid',
|
||||
}
|
||||
LOADS = (0xc, 0x80000018, 0x8000001f, 0x80000023, 0x20)
|
||||
|
||||
|
||||
@@ -18,7 +39,45 @@ def require(value, message):
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def rewrite(data, expected_sha256):
|
||||
def detect_chained_target_mapping(data, include_stdio_rw=False):
|
||||
m = Macho(data)
|
||||
deps = []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
n = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= n < size, '依赖名偏移无效')
|
||||
end = m.d.index(0, off + n, off + size)
|
||||
deps.append(bytes(m.d[off + n:end]).decode())
|
||||
if '/usr/lib/libSystem.B.dylib' not in deps:
|
||||
return {}
|
||||
old_ordinal = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
commands = [o for c, _, o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS]
|
||||
require(len(commands) == 1, '需要唯一 chained fixups')
|
||||
fixoff, fixsize = struct.unpack_from('<II', m.d, commands[0] + 8)
|
||||
version, starts, imports, symbols, count, fmt, compression = struct.unpack_from('<7I', m.d, fixoff)
|
||||
require(version == 0 and fmt == 1 and compression == 0, '仅支持无压缩 DYLD_CHAINED_IMPORT')
|
||||
wanted = set(REPORT_TARGET_SYMBOLS)
|
||||
if include_stdio_rw:
|
||||
wanted.update({'_fread', '_fwrite', '_fclose'})
|
||||
found = {}
|
||||
pool_start, pool_end = fixoff + symbols, fixoff + fixsize
|
||||
for i in range(count):
|
||||
word = struct.unpack_from('<I', m.d, fixoff + imports + 4 * i)[0]
|
||||
if (word & 255) != old_ordinal:
|
||||
continue
|
||||
start = pool_start + (word >> 9)
|
||||
end = m.d.index(0, start, pool_end)
|
||||
name = bytes(m.d[start:end]).decode('utf-8')
|
||||
if name in wanted:
|
||||
require(name in ALLOWED_MAPPING, f'缺少框架保护映射: {name}')
|
||||
found[name] = ALLOWED_MAPPING[name]
|
||||
return found
|
||||
|
||||
|
||||
def rewrite(data, expected_sha256, mapping=None):
|
||||
mapping = MAPPING if mapping is None else mapping
|
||||
require(bool(mapping) and all(k in ALLOWED_MAPPING and ALLOWED_MAPPING[k] == v for k, v in mapping.items()),
|
||||
'映射必须是已实现的保护入口子集')
|
||||
require(hashlib.sha256(data).hexdigest() == expected_sha256, 'SDK 哈希不匹配,须重新审核版本')
|
||||
m = Macho(data)
|
||||
require(m.filetype == 6 and m.flags & 0x80, '需要 two-level MH_DYLIB')
|
||||
@@ -66,17 +125,17 @@ def rewrite(data, expected_sha256):
|
||||
require(pool_start <= start < pool_end, '字符串索引越界')
|
||||
end = m.d.index(0, start, pool_end)
|
||||
name = bytes(m.d[start:end]).decode('utf-8')
|
||||
require(name not in MAPPING.values(), '已改写或目标冲突')
|
||||
require(name not in mapping.values(), '已改写或目标冲突')
|
||||
intervals.append((start, end + 1, name))
|
||||
if name in MAPPING:
|
||||
if name in mapping:
|
||||
require(name not in selected and ordinal_value == old_ordinal,
|
||||
'重复导入或提供方不匹配')
|
||||
selected[name] = (entry, start, end)
|
||||
require(set(selected) == set(MAPPING), '缺少预期四个文件函数')
|
||||
require(set(selected) == set(mapping), '缺少配置的文件函数')
|
||||
for name, (entry, start, end) in selected.items():
|
||||
require(all(other == name or finish <= start or begin >= end + 1
|
||||
for begin, finish, other in intervals), '共享后缀字符串,拒绝原地改名')
|
||||
encoded = MAPPING[name].encode()
|
||||
encoded = mapping[name].encode()
|
||||
require(len(encoded) <= end - start, '新名称超出原字符串空间')
|
||||
write(start, encoded + bytes(end - start + 1 - len(encoded)))
|
||||
if kind == 'chained':
|
||||
@@ -87,7 +146,7 @@ def rewrite(data, expected_sha256):
|
||||
desc = struct.unpack_from('<H', m.d, entry + 6)[0]
|
||||
require(not desc & 0x40, '不支持 weak 符号')
|
||||
write(entry + 6, struct.pack('<H', (desc & 255) | (ordinal << 8)))
|
||||
changes.append({'table': kind, 'source': name, 'destination': MAPPING[name],
|
||||
changes.append({'table': kind, 'source': name, 'destination': mapping[name],
|
||||
'old_ordinal': old_ordinal, 'ordinal': ordinal})
|
||||
entries = []
|
||||
for i in range(count):
|
||||
@@ -119,13 +178,13 @@ def rewrite(data, expected_sha256):
|
||||
Macho(result)
|
||||
return result, {'input_sha256': hashlib.sha256(data).hexdigest(),
|
||||
'output_sha256': hashlib.sha256(result).hexdigest(), 'dependency': DEPENDENCY,
|
||||
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': 4}
|
||||
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': len(mapping)}
|
||||
|
||||
|
||||
def patch(source, destination, expected_sha256):
|
||||
def patch(source, destination, expected_sha256, mapping=None):
|
||||
source, destination = Path(source), Path(destination)
|
||||
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
|
||||
output, report = rewrite(source.read_bytes(), expected_sha256)
|
||||
output, report = rewrite(source.read_bytes(), expected_sha256, mapping)
|
||||
destination.write_bytes(output)
|
||||
destination.chmod(source.stat().st_mode)
|
||||
return report
|
||||
@@ -137,5 +196,6 @@ if __name__ == '__main__':
|
||||
p.add_argument('destination', type=Path)
|
||||
p.add_argument('--expected-sha256', required=True)
|
||||
p.add_argument('--report', type=Path, required=True)
|
||||
p.add_argument('--mapping', type=Path, help='现有四入口中的显式子集 JSON')
|
||||
a = p.parse_args()
|
||||
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256), indent=2) + '\n')
|
||||
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256, json.loads(a.mapping.read_text()) if a.mapping else None), indent=2) + '\n')
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Redirect a reviewed lazy fopen import without changing lazy-record offsets."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from machox import Macho
|
||||
from redirect_framework_imports import DEPENDENCY, LOADS, require
|
||||
|
||||
SOURCE = b'_fopen'
|
||||
DESTINATION = b'_rd_a0'
|
||||
|
||||
|
||||
def uleb(data, pos, end):
|
||||
start, value, shift = pos, 0, 0
|
||||
while pos < end and shift < 64:
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
value |= (byte & 127) << shift
|
||||
if not byte & 128:
|
||||
return value, pos, start
|
||||
shift += 7
|
||||
raise ValueError('Invalid LEB128')
|
||||
|
||||
|
||||
def encode(value):
|
||||
result = bytearray()
|
||||
while value >= 128:
|
||||
result.append((value & 127) | 128)
|
||||
value >>= 7
|
||||
result.append(value)
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def rewrite(data, expected_sha):
|
||||
require(hashlib.sha256(data).hexdigest() == expected_sha, 'Input hash changed')
|
||||
m = Macho(data)
|
||||
require(m.filetype == 6 and m.flags & 0x80, 'Expected two-level dylib')
|
||||
deps, dyld, symtab, sections = [], [], [], []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= nameoff < size, 'Invalid dependency')
|
||||
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
|
||||
if cmd in (0x22, 0x80000022):
|
||||
dyld.append(off)
|
||||
if cmd == 2:
|
||||
symtab.append(off)
|
||||
if cmd == 0x80000034:
|
||||
raise ValueError('Chained imports require the chained rewriter')
|
||||
if cmd == 0x19:
|
||||
for i in range(struct.unpack_from('<I', m.d, off + 64)[0]):
|
||||
section = off + 72 + i * 80
|
||||
length, fileoff = struct.unpack_from('<QI', m.d, section + 40)
|
||||
flags = struct.unpack_from('<I', m.d, section + 64)[0] & 255
|
||||
if length and flags not in (1, 0xc, 0x12):
|
||||
require(fileoff > 0 and fileoff + length <= len(data), 'Invalid section')
|
||||
sections.append((fileoff, length))
|
||||
require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables')
|
||||
require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict')
|
||||
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
new = len(deps) + 1
|
||||
fields = struct.unpack_from('<10I', m.d, dyld[0] + 8)
|
||||
for i in (1, 2):
|
||||
offset, size = fields[i * 2:i * 2 + 2]
|
||||
require(SOURCE + b'\0' not in data[offset:offset + size],
|
||||
'fopen also appears in regular or weak binding')
|
||||
offset, size = fields[6:8]
|
||||
require(offset + size <= len(data), 'Lazy stream outside file')
|
||||
pos, end, records = offset, offset + size, []
|
||||
record = {'symbols': [], 'ordinals': [], 'binds': 0}
|
||||
while pos < end:
|
||||
at = pos
|
||||
opcode = data[pos] & 0xf0
|
||||
imm = data[pos] & 15
|
||||
pos += 1
|
||||
if opcode == 0:
|
||||
require(imm == 0, 'Invalid DONE opcode')
|
||||
if record['symbols']:
|
||||
records.append(record)
|
||||
record = {'symbols': [], 'ordinals': [], 'binds': 0}
|
||||
elif opcode == 0x10:
|
||||
record['ordinals'].append((at, pos, imm, False))
|
||||
elif opcode == 0x20:
|
||||
value, pos, start = uleb(data, pos, end)
|
||||
record['ordinals'].append((start, pos, value, True))
|
||||
elif opcode == 0x40:
|
||||
finish = data.index(0, pos, end)
|
||||
record['symbols'].append((pos, finish, data[pos:finish], imm))
|
||||
pos = finish + 1
|
||||
elif opcode in (0x60, 0x70, 0x80):
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
elif opcode == 0x50:
|
||||
pass
|
||||
elif opcode == 0x90:
|
||||
record['binds'] += 1
|
||||
else:
|
||||
raise ValueError(f'Unsupported lazy opcode {opcode:#x}')
|
||||
require(not record['symbols'] and not record['ordinals'] and not record['binds'], 'Unterminated lazy record')
|
||||
selected = [r for r in records if any(s[2] == SOURCE for s in r['symbols'])]
|
||||
require(len(selected) == 1, 'Need exactly one fopen lazy record')
|
||||
r = selected[0]
|
||||
require(len(r['symbols']) == len(r['ordinals']) == r['binds'] == 1,
|
||||
'Shared or multi-bind lazy record')
|
||||
start, finish, name, flags = r['symbols'][0]
|
||||
require(flags == 0 and len(DESTINATION) == finish - start, 'Unsupported symbol flags/length')
|
||||
at, stop, ordinal, extended = r['ordinals'][0]
|
||||
require(ordinal == old, 'Unexpected provider')
|
||||
encoded = encode(new) if extended else bytes([0x10 | new]) if new < 16 else b''
|
||||
require(len(encoded) == stop - at, 'Ordinal size would move lazy records')
|
||||
allowed = set()
|
||||
def write(at, content):
|
||||
m.d[at:at + len(content)] = content
|
||||
allowed.update(range(at, at + len(content)))
|
||||
write(start, DESTINATION)
|
||||
write(at, encoded)
|
||||
|
||||
so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8)
|
||||
require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table')
|
||||
matched = 0
|
||||
intervals = []
|
||||
for i in range(count):
|
||||
entry = so + i * 16
|
||||
index, typ, _, desc, _ = struct.unpack_from('<IBBHQ', data, entry)
|
||||
if index >= stringsize:
|
||||
raise ValueError('Symbol name outside pool')
|
||||
nameend = data.index(0, strings + index, strings + stringsize)
|
||||
intervals.append((strings + index, nameend + 1))
|
||||
if data[strings + index:nameend] != SOURCE:
|
||||
continue
|
||||
require(typ == 1 and desc >> 8 == old, 'Unexpected nlist provider')
|
||||
symbol_span = (strings + index, nameend + 1)
|
||||
write(strings + index, DESTINATION)
|
||||
write(entry + 6, struct.pack('<H', (desc & 255) | (new << 8)))
|
||||
matched += 1
|
||||
require(matched == 1, 'Need one undefined fopen symbol')
|
||||
require(all(span == symbol_span or span[1] <= symbol_span[0] or span[0] >= symbol_span[1]
|
||||
for span in intervals), 'Shared symbol-name suffix')
|
||||
name = DEPENDENCY.encode() + b'\0'
|
||||
length = (24 + len(name) + 7) & ~7
|
||||
at = 32 + m.sizeofcmds
|
||||
require(at + length <= min(s[0] for s in sections), 'Insufficient header padding')
|
||||
require(not any(data[at:at + length]), 'Nonzero header padding')
|
||||
command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name
|
||||
write(at, command + bytes(length - len(command)))
|
||||
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + length))
|
||||
result = bytes(m.d)
|
||||
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), 'Unexpected mutation')
|
||||
require(all(data[o:o+n] == result[o:o+n] for o,n in sections), 'Section bytes changed')
|
||||
return result, dict(input_sha256=expected_sha, output_sha256=hashlib.sha256(result).hexdigest(),
|
||||
source=SOURCE.decode(), destination=DESTINATION.decode(),
|
||||
old_ordinal=old, new_ordinal=new, lazy_offsets_preserved=True,
|
||||
section_bytes_unchanged=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--sha256', required=True)
|
||||
p.add_argument('--report', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
result, report = rewrite(a.source.read_bytes(), a.sha256)
|
||||
with a.output.open('xb') as stream:
|
||||
stream.write(result)
|
||||
a.report.write_text(json.dumps(report, indent=2) + '\n')
|
||||
@@ -0,0 +1,327 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Redirect reviewed lazy imports in thin arm64 DYLD_INFO_ONLY frameworks without shifting lazy offsets."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
|
||||
from redirect_framework_imports import DEPENDENCY, LOADS, REPORT_TARGET_SYMBOLS, require
|
||||
|
||||
EQUAL_LEN_MAPPING = {
|
||||
'_fopen': '_rd_a0',
|
||||
'_open': '_rd_o',
|
||||
'_read': '_rd_r',
|
||||
'_write': '_rd_w0',
|
||||
'_close': '_rd_c0',
|
||||
'_unlink': '_rd_u00',
|
||||
'_getpid': '_rd_p00',
|
||||
'_exit': '_rd_e',
|
||||
'_fork': '_rd_k',
|
||||
'_dlopen': '_rd_l00',
|
||||
'_dlsym': '_rd_s0',
|
||||
}
|
||||
|
||||
SHRINK1_MAPPING = {
|
||||
'_fopen': '_rd_f',
|
||||
'_open': '_rdo',
|
||||
'_read': '_rdr',
|
||||
'_write': '_rd_w',
|
||||
'_close': '_rd_c',
|
||||
'_unlink': '_rd_a4',
|
||||
'_getpid': '_rd_p0',
|
||||
'_dlsym': '_rd_s',
|
||||
}
|
||||
|
||||
|
||||
def uleb(data, pos, end):
|
||||
start, value, shift = pos, 0, 0
|
||||
while pos < end and shift < 64:
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
value |= (byte & 127) << shift
|
||||
if not byte & 128:
|
||||
return value, pos, start
|
||||
shift += 7
|
||||
raise ValueError('Invalid LEB128')
|
||||
|
||||
|
||||
def sleb_skip(data, pos, end):
|
||||
while pos < end:
|
||||
byte = data[pos]
|
||||
pos += 1
|
||||
if not byte & 128:
|
||||
return pos
|
||||
raise ValueError('Invalid SLEB128')
|
||||
|
||||
|
||||
def encode_uleb(value):
|
||||
result = bytearray()
|
||||
while value >= 128:
|
||||
result.append((value & 127) | 128)
|
||||
value >>= 7
|
||||
result.append(value)
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def parse_bind_symbols(data, offset, size):
|
||||
if not size:
|
||||
return set()
|
||||
require(offset + size <= len(data), 'Bind stream outside file')
|
||||
pos, end, symbols = offset, offset + size, set()
|
||||
while pos < end:
|
||||
opcode = data[pos] & 0xf0
|
||||
pos += 1
|
||||
if opcode in (0x00, 0x10, 0x30, 0x50, 0x90, 0xb0):
|
||||
pass
|
||||
elif opcode in (0x20, 0x70, 0x80, 0xa0):
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
elif opcode == 0x60:
|
||||
pos = sleb_skip(data, pos, end)
|
||||
elif opcode == 0xc0:
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
elif opcode == 0x40:
|
||||
finish = data.index(0, pos, end)
|
||||
symbols.add(data[pos:finish])
|
||||
pos = finish + 1
|
||||
else:
|
||||
raise ValueError(f'Unsupported bind opcode {opcode:#x}')
|
||||
return symbols
|
||||
|
||||
|
||||
def parse_lazy_records(data, offset, size):
|
||||
require(offset + size <= len(data), 'Lazy stream outside file')
|
||||
pos, end, records = offset, offset + size, []
|
||||
record = {'symbols': [], 'ordinals': [], 'binds': 0}
|
||||
while pos < end:
|
||||
at = pos
|
||||
opcode = data[pos] & 0xf0
|
||||
imm = data[pos] & 15
|
||||
pos += 1
|
||||
if opcode == 0:
|
||||
require(imm == 0, 'Invalid DONE opcode')
|
||||
if record['symbols']:
|
||||
records.append(record)
|
||||
record = {'symbols': [], 'ordinals': [], 'binds': 0}
|
||||
elif opcode == 0x10:
|
||||
record['ordinals'].append((at, pos, imm, False))
|
||||
elif opcode == 0x20:
|
||||
value, pos, _ = uleb(data, pos, end)
|
||||
record['ordinals'].append((at, pos, value, True))
|
||||
elif opcode == 0x40:
|
||||
finish = data.index(0, pos, end)
|
||||
record['symbols'].append((pos, finish, data[pos:finish], imm))
|
||||
pos = finish + 1
|
||||
elif opcode in (0x70, 0x80, 0xa0):
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
elif opcode == 0x60:
|
||||
pos = sleb_skip(data, pos, end)
|
||||
elif opcode == 0xc0:
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
_, pos, _ = uleb(data, pos, end)
|
||||
elif opcode in (0x50, 0x90, 0xb0):
|
||||
if opcode == 0x90:
|
||||
record['binds'] += 1
|
||||
else:
|
||||
raise ValueError(f'Unsupported lazy opcode {opcode:#x}')
|
||||
require(not record['symbols'] and not record['ordinals'] and not record['binds'],
|
||||
'Unterminated lazy record')
|
||||
return records
|
||||
|
||||
|
||||
def detect_legacy_target_mapping(data):
|
||||
m = Macho(data)
|
||||
deps = []
|
||||
dyld_cmds = []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= nameoff < size, 'Invalid dependency')
|
||||
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
|
||||
if cmd in (0x22, 0x80000022):
|
||||
dyld_cmds.append(off)
|
||||
if '/usr/lib/libSystem.B.dylib' not in deps or not dyld_cmds:
|
||||
return {}
|
||||
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
new = len(deps) + 1
|
||||
old_width = 1 if old < 16 else 2
|
||||
new_width = 1 if new < 16 else 2
|
||||
delta = new_width - old_width
|
||||
require(delta in (0, 1), f'Unsupported ordinal width delta: {delta}')
|
||||
table = EQUAL_LEN_MAPPING if delta == 0 else SHRINK1_MAPPING
|
||||
fields = struct.unpack_from('<10I', m.d, dyld_cmds[0] + 8)
|
||||
lo, ls = fields[6:8]
|
||||
records = parse_lazy_records(data, lo, ls)
|
||||
found = {}
|
||||
for rec in records:
|
||||
for _, _, sym_bytes, _ in rec['symbols']:
|
||||
name = sym_bytes.decode('utf-8')
|
||||
if name in REPORT_TARGET_SYMBOLS:
|
||||
require(name in table, f'Missing legacy alias for {name} (width delta={delta})')
|
||||
found[name] = table[name]
|
||||
return found
|
||||
|
||||
|
||||
def rewrite(data, expected_sha, mapping=None):
|
||||
require(hashlib.sha256(data).hexdigest() == expected_sha, 'Input hash changed')
|
||||
m = Macho(data)
|
||||
require(m.filetype == 6 and m.flags & 0x80, 'Expected two-level dylib')
|
||||
require(not any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds),
|
||||
'Chained imports require redirect_framework_imports')
|
||||
deps, dyld, symtab, sections = [], [], [], []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= nameoff < size, 'Invalid dependency')
|
||||
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
|
||||
if cmd in (0x22, 0x80000022):
|
||||
dyld.append(off)
|
||||
if cmd == 2:
|
||||
symtab.append(off)
|
||||
if cmd == LC_SEGMENT_64:
|
||||
for i in range(struct.unpack_from('<I', m.d, off + 64)[0]):
|
||||
section = off + 72 + i * 80
|
||||
length, fileoff = struct.unpack_from('<QI', m.d, section + 40)
|
||||
flags = struct.unpack_from('<I', m.d, section + 64)[0] & 255
|
||||
if length and flags not in (1, 0xc, 0x12):
|
||||
require(fileoff > 0 and fileoff + length <= len(data), 'Invalid section')
|
||||
sections.append((fileoff, length))
|
||||
require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables')
|
||||
require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict')
|
||||
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
new = len(deps) + 1
|
||||
old_width = 1 if old < 16 else 2
|
||||
new_width = 1 if new < 16 else 2
|
||||
delta = new_width - old_width
|
||||
allowed_table = EQUAL_LEN_MAPPING if delta == 0 else SHRINK1_MAPPING if delta == 1 else {}
|
||||
require(bool(allowed_table), f'Unsupported ordinal width delta: {delta}')
|
||||
|
||||
if mapping is None:
|
||||
mapping = detect_legacy_target_mapping(data)
|
||||
require(bool(mapping) and all(k in allowed_table and allowed_table[k] == v for k, v in mapping.items()),
|
||||
'Mapping must match allowed legacy wrapper table')
|
||||
byte_mapping = {k.encode('ascii'): v.encode('ascii') for k, v in mapping.items()}
|
||||
|
||||
fields = struct.unpack_from('<10I', m.d, dyld[0] + 8)
|
||||
for i in (1, 2):
|
||||
offset, size = fields[i * 2:i * 2 + 2]
|
||||
bind_syms = parse_bind_symbols(data, offset, size)
|
||||
for src in byte_mapping:
|
||||
require(src not in bind_syms,
|
||||
f'{src.decode()} appears in regular or weak binding')
|
||||
|
||||
records = parse_lazy_records(data, fields[6], fields[7])
|
||||
selected = []
|
||||
for rec in records:
|
||||
if any(s[2] in byte_mapping for s in rec['symbols']):
|
||||
require(len(rec['symbols']) == len(rec['ordinals']) == rec['binds'] == 1,
|
||||
'Shared or multi-bind lazy record')
|
||||
selected.append(rec)
|
||||
require({r['symbols'][0][2] for r in selected} == set(byte_mapping),
|
||||
'Not all mapped symbols matched unique lazy records')
|
||||
|
||||
allowed = set()
|
||||
def write(at, content):
|
||||
require(at >= 0 and at + len(content) <= len(m.d), 'Write out of range')
|
||||
m.d[at:at + len(content)] = content
|
||||
allowed.update(range(at, at + len(content)))
|
||||
|
||||
new_ord_bytes = bytes([0x10 | new]) if new < 16 else b'\x20' + encode_uleb(new)
|
||||
changes = []
|
||||
for rec in selected:
|
||||
start, finish, src_sym, flags = rec['symbols'][0]
|
||||
dst_sym = byte_mapping[src_sym]
|
||||
ord_start, ord_stop, ordinal, _ = rec['ordinals'][0]
|
||||
require(flags == 0 and ordinal == old, 'Unexpected symbol flags or provider')
|
||||
sym_opcode_pos = start - 1
|
||||
require(data[sym_opcode_pos] == 0x40, 'Expected SET_SYMBOL_TRAILING_FLAGS_IMM(0) before symbol')
|
||||
require(ord_stop == sym_opcode_pos, 'Expected ordinal opcode immediately before symbol opcode')
|
||||
old_span = finish + 1 - ord_start
|
||||
replacement = new_ord_bytes + b'\x40' + dst_sym + b'\0'
|
||||
require(len(replacement) == old_span, 'Replacement size would shift lazy records')
|
||||
write(ord_start, replacement)
|
||||
changes.append(dict(table='lazy', source=src_sym.decode(), destination=dst_sym.decode(),
|
||||
old_ordinal=old, new_ordinal=new))
|
||||
|
||||
so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8)
|
||||
require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table')
|
||||
matched = {}
|
||||
intervals = []
|
||||
target_spans = []
|
||||
for i in range(count):
|
||||
entry = so + i * 16
|
||||
index, typ, _, desc, value = struct.unpack_from('<IBBHQ', data, entry)
|
||||
require(index < stringsize, 'Symbol name outside pool')
|
||||
nameend = data.index(0, strings + index, strings + stringsize)
|
||||
sym = data[strings + index:nameend]
|
||||
intervals.append((strings + index, nameend + 1, sym))
|
||||
require(sym not in byte_mapping.values(), 'Target symbol already exists in symbol table')
|
||||
if sym in byte_mapping and typ == 1 and value == 0:
|
||||
require((desc >> 8) == old and not (desc & 0x40), 'Unexpected nlist provider or weak symbol')
|
||||
dst = byte_mapping[sym]
|
||||
require(len(dst) <= len(sym), 'Destination longer than source in string pool')
|
||||
span = (strings + index, nameend + 1, sym)
|
||||
target_spans.append(span)
|
||||
write(strings + index, dst + b'\0' * (len(sym) + 1 - len(dst)))
|
||||
write(entry + 6, struct.pack('<H', (desc & 255) | (new << 8)))
|
||||
matched[sym] = matched.get(sym, 0) + 1
|
||||
changes.append(dict(table='nlist', source=sym.decode(), destination=dst.decode(),
|
||||
old_ordinal=old, new_ordinal=new))
|
||||
require(set(matched) == set(byte_mapping) and all(v == 1 for v in matched.values()),
|
||||
'Missing or duplicate nlist symbol')
|
||||
for b1, e1, n1 in target_spans:
|
||||
require(all(n2 == n1 or e2 <= b1 or b2 >= e1 for b2, e2, n2 in intervals),
|
||||
'Shared symbol-name suffix')
|
||||
|
||||
name = DEPENDENCY.encode() + b'\0'
|
||||
length = (24 + len(name) + 7) & ~7
|
||||
at = 32 + m.sizeofcmds
|
||||
require(at + length <= min(s[0] for s in sections), 'Insufficient header padding')
|
||||
require(not any(data[at:at + length]), 'Nonzero header padding')
|
||||
command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name
|
||||
write(at, command + bytes(length - len(command)))
|
||||
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + length))
|
||||
|
||||
result = bytes(m.d)
|
||||
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), 'Unexpected mutation')
|
||||
require(all(data[o:o + n] == result[o:o + n] for o, n in sections), 'Section bytes changed')
|
||||
Macho(result)
|
||||
return result, dict(
|
||||
input_sha256=expected_sha,
|
||||
output_sha256=hashlib.sha256(result).hexdigest(),
|
||||
dependency=DEPENDENCY,
|
||||
old_ordinal=old,
|
||||
new_ordinal=new,
|
||||
ordinal_width_delta=delta,
|
||||
lazy_offsets_preserved=True,
|
||||
section_bytes_unchanged=True,
|
||||
changes=changes,
|
||||
total_symbols=len(mapping),
|
||||
)
|
||||
|
||||
|
||||
def patch(source, destination, expected_sha256, mapping=None):
|
||||
source, destination = Path(source), Path(destination)
|
||||
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
|
||||
output, report = rewrite(source.read_bytes(), expected_sha256, mapping)
|
||||
destination.write_bytes(output)
|
||||
destination.chmod(source.stat().st_mode)
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source', type=Path)
|
||||
p.add_argument('destination', type=Path)
|
||||
p.add_argument('--expected-sha256', required=True)
|
||||
p.add_argument('--report', type=Path, required=True)
|
||||
p.add_argument('--mapping', type=Path)
|
||||
a = p.parse_args()
|
||||
result, report = rewrite(a.source.read_bytes(), a.expected_sha256,
|
||||
json.loads(a.mapping.read_text()) if a.mapping else None)
|
||||
with a.output.open('xb') if hasattr(a, 'output') else a.destination.open('xb') as stream:
|
||||
stream.write(result)
|
||||
a.destination.chmod(a.source.stat().st_mode)
|
||||
a.report.write_text(json.dumps(report, indent=2) + '\n')
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""核对同次构建的 arm64 可执行文件中所列文件方法确实调用保护入口。
|
||||
|
||||
需要保留本地符号的验证构建;符号缺失直接失败,不将未知判为通过。
|
||||
只验证所列方法的直接 BL/B 调用边,不代表全包系统调用整改完成。
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from machox import Macho
|
||||
from batch import Slice
|
||||
from redirect_to_runtime import defined_symbols, target
|
||||
|
||||
EXPECTED = {
|
||||
'+[STSCommonUtil convertPcmToWav:wavFilePath:]': {'fopen': 1},
|
||||
'-[GCDWebServerMultiPartFile dealloc]': {'unlink': 1},
|
||||
'-[GCDWebServerMIMEStreamParser dealloc]': {'close': 1, 'unlink': 1},
|
||||
'-[GCDWebServerMIMEStreamParser _parseData]': {'open': 1, 'write': 2, 'close': 1},
|
||||
'-[GCDWebServerFileRequest dealloc]': {'unlink': 1},
|
||||
'-[GCDWebServerFileRequest open:]': {'open': 1},
|
||||
'-[GCDWebServerFileRequest writeData:error:]': {'write': 1},
|
||||
'-[GCDWebServerFileRequest close:]': {'close': 1},
|
||||
'-[GCDWebServerFileResponse open:]': {'open': 1, 'close': 1},
|
||||
'-[GCDWebServerFileResponse readData:]': {'read': 1},
|
||||
'-[GCDWebServerFileResponse close]': {'close': 1},
|
||||
}
|
||||
|
||||
|
||||
ZIPZAP = {
|
||||
'-[ZZFileChannel newOutput:]': {'open': 1},
|
||||
'-[ZZFileChannelOutput writeData:error:]': {'write': 1},
|
||||
'-[ZZFileChannelOutput close]': {'close': 1},
|
||||
}
|
||||
|
||||
|
||||
def verify(path, include_zipzap=False):
|
||||
expected = EXPECTED | ZIPZAP if include_zipzap else EXPECTED
|
||||
data = Path(path).read_bytes()
|
||||
macho = Macho(data)
|
||||
view = Slice(data, 0)
|
||||
if not view.text:
|
||||
raise ValueError('缺少 __text')
|
||||
start, size, offset = view.text
|
||||
symbols = defined_symbols(macho)
|
||||
boundaries = sorted({v for v in symbols.values() if start <= v < start + size} | {start + size})
|
||||
stubs = view.stub_symbol_map()
|
||||
all_protected = {name for wanted in expected.values() for name in wanted}
|
||||
result = []
|
||||
for method, wanted in expected.items():
|
||||
if method not in symbols or not start <= symbols[method] < start + size:
|
||||
raise ValueError(f'缺少可核验的业务方法符号:{method}')
|
||||
address = symbols[method]
|
||||
end = next(v for v in boundaries if v > address)
|
||||
calls = []
|
||||
for site in range(address, end, 4):
|
||||
word, = struct.unpack_from('<I', data, offset + site - start)
|
||||
if word & 0xfc000000 in (0x94000000, 0x14000000):
|
||||
calls.append((site, target(word, site)))
|
||||
for site, dest in calls:
|
||||
if stubs.get(dest) in {'_' + n for n in all_protected}:
|
||||
raise ValueError(f'{method} 仍直接调用 {stubs[dest]} @ {site:#x}')
|
||||
for name, minimum in wanted.items():
|
||||
guard = '_IG_dispatch_' + name
|
||||
if guard not in symbols:
|
||||
raise ValueError(f'保护入口未链接或符号缺失:{guard}')
|
||||
sites = [hex(site) for site, dest in calls if dest == symbols[guard]]
|
||||
if len(sites) < minimum:
|
||||
raise ValueError(f'{method} 未实际调用 {guard}')
|
||||
result.append(dict(caller=method, destination=guard, sites=sites))
|
||||
return dict(status='passed_selected_call_edges', executable=str(Path(path).resolve()),
|
||||
sha256=hashlib.sha256(data).hexdigest(), verified_edges=result,
|
||||
scope='仅所列方法;不代表全包或真机验收')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--include-zipzap', action='store_true', help='同时核验 ZipZap 输出文件调用')
|
||||
args = parser.parse_args()
|
||||
report = verify(args.executable, args.include_zipzap)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify prior direct calls from one archive now reach a specified local guard."""
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from attribute_callsites import attribute, load_link_map
|
||||
from batch import Slice
|
||||
from machox import Macho
|
||||
from redirect_to_runtime import defined_symbols, target
|
||||
|
||||
|
||||
def verify(previous_calls, executable, link_map, archive, source, guard):
|
||||
with previous_calls.open() as stream:
|
||||
expected = Counter(row['caller'] for row in csv.DictReader(stream)
|
||||
if row['symbol'] == source
|
||||
and Path(row['object'].split('(')[0]).name == archive)
|
||||
if not expected:
|
||||
raise ValueError('No prior calls selected')
|
||||
remaining = [r for r in attribute(executable, link_map)
|
||||
if r['symbol'] == source
|
||||
and Path(r.get('object', '').split('(')[0]).name == archive]
|
||||
if remaining:
|
||||
raise ValueError(f'{len(remaining)} direct calls remain')
|
||||
data = executable.read_bytes()
|
||||
symbols = defined_symbols(Macho(data))
|
||||
if guard not in symbols:
|
||||
raise ValueError('Guard symbol missing')
|
||||
destination = symbols[guard]
|
||||
view = Slice(data, 0)
|
||||
if not view.text:
|
||||
raise ValueError('Missing __text')
|
||||
start, length, offset = view.text
|
||||
objects, entries = load_link_map(link_map)
|
||||
found = defaultdict(list)
|
||||
for address, size, obj, name in entries:
|
||||
owner = Path(objects.get(obj, '').split('(')[0]).name
|
||||
if owner != archive or name not in expected:
|
||||
continue
|
||||
if not start <= address < address + size <= start + length:
|
||||
raise ValueError('Selected method outside __text')
|
||||
for site in range(address, address + size, 4):
|
||||
word, = struct.unpack_from('<I', data, offset + site - start)
|
||||
if word & 0xfc000000 in (0x94000000, 0x14000000) and target(word, site) == destination:
|
||||
found[name].append(hex(site))
|
||||
if Counter({k: len(v) for k, v in found.items()}) != expected:
|
||||
raise ValueError('Guard calls do not match prior call counts')
|
||||
return dict(executable_sha256=hashlib.sha256(data).hexdigest(), archive=archive,
|
||||
source=source, guard=guard, verified_calls=sum(expected.values()),
|
||||
callers=dict(found))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('previous_calls', 'executable', 'link_map', 'output'):
|
||||
parser.add_argument(name, type=Path)
|
||||
parser.add_argument('--archive', required=True)
|
||||
parser.add_argument('--source', required=True)
|
||||
parser.add_argument('--guard', required=True)
|
||||
args = parser.parse_args()
|
||||
report = verify(args.previous_calls, args.executable, args.link_map,
|
||||
args.archive, args.source, args.guard)
|
||||
with args.output.open('x') as stream:
|
||||
json.dump(report, stream, indent=2)
|
||||
stream.write('\n')
|
||||
print(f'Verified {report["verified_calls"]} redirected calls')
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"_fopen": "_IG_dispatch_fopen",
|
||||
"_dlopen": "_IG_dispatch_dlopen",
|
||||
"_dlsym": "_IG_dispatch_dlsym",
|
||||
"_write": "_IG_dispatch_write",
|
||||
"_read": "_IG_dispatch_read",
|
||||
"_open": "_IG_dispatch_open",
|
||||
"_close": "_IG_dispatch_close",
|
||||
"_exit": "_IG_dispatch_exit",
|
||||
"_fork": "_IG_dispatch_fork",
|
||||
"_unlink": "_IG_dispatch_unlink",
|
||||
"_getpid": "_IG_dispatch_getpid"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"_fopen":"_IG_dispatch_fopen"}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"_open": "_IG_dispatch_open",
|
||||
"_write": "_IG_dispatch_write",
|
||||
"_close": "_IG_dispatch_close"
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare hash-verified Route 2 arm64 static SDK candidates and sdk-inputs manifest."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from redirect_bitcode_members import rewrite as rewrite_bitcode
|
||||
from redirect_symbols import ARCHIVE_MAGIC
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MAPPING_PATH = ROOT / 'tools/static_sdk_redirect/mappings/full_dispatch.json'
|
||||
PROFILE_PATH = ROOT / 'tools/macho_guard/profiles/main_residual_dispatch.json'
|
||||
|
||||
STATIC_INPUTS = [
|
||||
dict(
|
||||
name='NBReaderSDK',
|
||||
relative='readoor/3.0/Factorys/NBReaderSDK/NBReaderSDK.framework/NBReaderSDK',
|
||||
dest='NBReaderSDK.framework/NBReaderSDK',
|
||||
arguments=['-framework', 'NBReaderSDK'],
|
||||
framework_dir='readoor/3.0/Factorys/NBReaderSDK/NBReaderSDK.framework',
|
||||
),
|
||||
dict(
|
||||
name='TencentOpenAPI',
|
||||
relative='readoor/3.0/Factorys/QQ/TencentOpenAPI.framework/TencentOpenAPI',
|
||||
dest='TencentOpenAPI',
|
||||
arguments=['-framework', 'TencentOpenAPI'],
|
||||
),
|
||||
dict(
|
||||
name='STKouyuEngine',
|
||||
relative='readoor/BookShelf/Classes/Factorys/STKouyu/STKouyuEngine.framework/STKouyuEngine',
|
||||
dest='STKouyuEngine',
|
||||
arguments=['-framework', 'STKouyuEngine'],
|
||||
),
|
||||
dict(
|
||||
name='lame',
|
||||
relative='readoor/BookShelf/Classes/Factorys/TAI/lame.framework/lame',
|
||||
dest='lame',
|
||||
arguments=['-framework', 'lame'],
|
||||
),
|
||||
dict(
|
||||
name='speechsdk',
|
||||
relative='Pods/SpeechEngineToB/pod/libs/libspeechsdk.a',
|
||||
dest='libspeechsdk.a',
|
||||
arguments=['-lspeechsdk'],
|
||||
extra_mapping={'_syscall': '_IG_sdk_thread_selfid'},
|
||||
),
|
||||
dict(
|
||||
name='ZipZap',
|
||||
relative='readoor/BookShelf/Classes/Factorys/ZipZap/libZipZap.a',
|
||||
dest='libZipZap.a',
|
||||
arguments=['-lZipZap'],
|
||||
),
|
||||
dict(
|
||||
name='skegn',
|
||||
relative='readoor/3.0/Factorys/NBReaderSDK/libskegn-iphoneos.a',
|
||||
dest='libskegn-iphoneos.a',
|
||||
arguments=['-lskegn-iphoneos'],
|
||||
extra_passes=[{'_fopen$DARWIN_EXTSN': '_IG_dispatch_fopen'}],
|
||||
),
|
||||
dict(
|
||||
name='StsFreetypeLib',
|
||||
relative='readoor/BookShelf/Classes/Factorys/StsFcLib/StsFreetypeLib.xcframework/ios-arm64/libStsFreetypeLib_Device.a',
|
||||
dest='libStsFreetypeLib_Device.a',
|
||||
arguments=['-lStsFreetypeLib_Device'],
|
||||
),
|
||||
dict(
|
||||
name='StsPdfLib',
|
||||
relative='readoor/BookShelf/Classes/Factorys/StsFcLib/StsPdfLib.xcframework/ios-arm64/libStsPdfLib_Device.a',
|
||||
dest='libStsPdfLib_Device.a',
|
||||
arguments=['-lStsPdfLib_Device'],
|
||||
),
|
||||
dict(
|
||||
name='StsFcLib',
|
||||
relative='readoor/BookShelf/Classes/Factorys/StsFcLib/StsFcLib.xcframework/ios-arm64/libStsFcLib_Device.a',
|
||||
dest='libStsFcLib_Device.a',
|
||||
arguments=['-lStsFcLib_Device'],
|
||||
),
|
||||
dict(
|
||||
name='StsJpegLib',
|
||||
relative='readoor/BookShelf/Classes/Factorys/StsFcLib/StsJpegLib.xcframework/ios-arm64/libStsJpegLib_Device.a',
|
||||
dest='libStsJpegLib_Device.a',
|
||||
arguments=['-lStsJpegLib_Device'],
|
||||
),
|
||||
dict(
|
||||
name='TIWLogger',
|
||||
relative='readoor/BookShelf/Classes/Factorys/TAI/TIWLogger.framework/TIWLogger',
|
||||
dest='TIWLogger.framework/TIWLogger',
|
||||
arguments=None,
|
||||
framework_dir='readoor/BookShelf/Classes/Factorys/TAI/TIWLogger.framework',
|
||||
extra_mapping={'_syscall': '_IG_sdk_thread_selfid'},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def digest(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def run_xcrun(*args):
|
||||
return subprocess.check_output(['xcrun', *map(str, args)])
|
||||
|
||||
|
||||
def thin_arm64(source, dest):
|
||||
head = source.read_bytes()[:8]
|
||||
if head == ARCHIVE_MAGIC:
|
||||
shutil.copy2(source, dest)
|
||||
else:
|
||||
run_xcrun('lipo', source, '-thin', 'arm64', '-output', dest)
|
||||
|
||||
|
||||
def verify_no_target_imports(path, targets):
|
||||
out = run_xcrun('nm', '-A', '-u', path).decode(errors='replace')
|
||||
remaining = sorted({
|
||||
line.split()[-1]
|
||||
for line in out.splitlines()
|
||||
if line.split() and line.split()[-1] in targets
|
||||
})
|
||||
if remaining:
|
||||
raise ValueError(f'{path.name} still imports forbidden symbols: {remaining}')
|
||||
|
||||
|
||||
def prepare(app_source, output):
|
||||
if output.exists() or output.is_symlink():
|
||||
raise FileExistsError(output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
base_mapping = json.loads(MAPPING_PATH.read_text(encoding='utf-8'))
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='.route2-sdks-', dir=output.parent) as tmp:
|
||||
work = Path(tmp)
|
||||
stage = work / 'stage'
|
||||
stage.mkdir()
|
||||
|
||||
files = []
|
||||
replacements = []
|
||||
reports = {}
|
||||
|
||||
for entry in STATIC_INPUTS:
|
||||
source = (app_source / entry['relative']).resolve()
|
||||
if not source.is_file():
|
||||
raise FileNotFoundError(source)
|
||||
thin = work / f"{entry['name']}.thin.a"
|
||||
thin_arm64(source, thin)
|
||||
|
||||
dest = (stage / entry['dest']).resolve()
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if 'framework_dir' in entry:
|
||||
fw_src = app_source / entry['framework_dir']
|
||||
for sub in ('Headers', 'Modules'):
|
||||
if (fw_src / sub).exists():
|
||||
shutil.copytree(fw_src / sub, dest.parent / sub)
|
||||
if (fw_src / 'Info.plist').exists():
|
||||
shutil.copy2(fw_src / 'Info.plist', dest.parent / 'Info.plist')
|
||||
|
||||
mapping = dict(base_mapping)
|
||||
mapping.update(entry.get('extra_mapping', {}))
|
||||
extra_passes = entry.get('extra_passes', [])
|
||||
if extra_passes:
|
||||
cur_input = thin
|
||||
total_members = 0
|
||||
total_refs = 0
|
||||
pass_report = rewrite_bitcode(cur_input, work / f"{entry['name']}.pass0.a", mapping)
|
||||
total_members += len(pass_report['members'])
|
||||
total_refs += sum(m['references'] for m in pass_report['members'])
|
||||
cur_input = work / f"{entry['name']}.pass0.a"
|
||||
for idx, ex_map in enumerate(extra_passes):
|
||||
is_last = (idx == len(extra_passes) - 1)
|
||||
out_target = dest if is_last else (work / f"{entry['name']}.pass{idx + 1}.a")
|
||||
ex_rep = rewrite_bitcode(cur_input, out_target, ex_map, allow_darwin_extsn=True)
|
||||
total_members += len(ex_rep['members'])
|
||||
total_refs += sum(m['references'] for m in ex_rep['members'])
|
||||
cur_input = out_target
|
||||
members_changed = total_members
|
||||
refs_redirected = total_refs
|
||||
else:
|
||||
report = rewrite_bitcode(thin, dest, mapping)
|
||||
members_changed = len(report['members'])
|
||||
refs_redirected = sum(m['references'] for m in report['members'])
|
||||
forbidden = set(mapping) | {'_fopen$DARWIN_EXTSN'}
|
||||
verify_no_target_imports(dest, forbidden)
|
||||
|
||||
reports[entry['name']] = dict(
|
||||
source=str(source),
|
||||
source_sha256=digest(source),
|
||||
candidate=entry['dest'],
|
||||
candidate_sha256=digest(dest),
|
||||
members_changed=members_changed,
|
||||
references_redirected=refs_redirected,
|
||||
)
|
||||
files.append(dict(path=entry['dest'], sha256=digest(dest)))
|
||||
if entry['arguments'] is not None:
|
||||
replacements.append(dict(arguments=entry['arguments'], file=entry['dest']))
|
||||
|
||||
bridge = stage / 'IGThreadID.o'
|
||||
run_xcrun('--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
||||
'-miphoneos-version-min=15.0', '-O2', '-Wall', '-Wextra', '-Werror',
|
||||
'-c', ROOT / 'defender/call_bridge/IGThreadID.c', '-o', bridge)
|
||||
files.append(dict(path='IGThreadID.o', sha256=digest(bridge)))
|
||||
|
||||
profile_copied = stage / 'main_residual_dispatch.json'
|
||||
shutil.copy2(PROFILE_PATH, profile_copied)
|
||||
files.append(dict(path='main_residual_dispatch.json', sha256=digest(profile_copied)))
|
||||
|
||||
manifest = dict(
|
||||
executable='readoor31OtherPay',
|
||||
replacements=replacements,
|
||||
objects=['IGThreadID.o'],
|
||||
framework_search=['.'],
|
||||
patch_profile='main_residual_dispatch.json',
|
||||
files=files,
|
||||
sources=reports,
|
||||
)
|
||||
(stage / 'sdk-inputs.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
stage.rename(output)
|
||||
return manifest
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('app_source', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
args = parser.parse_args()
|
||||
result = prepare(args.app_source.resolve(), args.output.resolve())
|
||||
print(json.dumps(result['sources'], indent=2))
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare arm64 release-link inputs for the two audited thread-ID SDK calls."""
|
||||
import argparse
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from redirect_symbols import redirect_object, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
INPUTS = {
|
||||
'TIWLogger': (
|
||||
'readoor/BookShelf/Classes/Factorys/TAI/TIWLogger.framework/TIWLogger',
|
||||
'bb09043399f923dde47e7d53ee2d7b499064b5e98039243a41b48123c9cdfd97',
|
||||
),
|
||||
'speechsdk': (
|
||||
'Pods/SpeechEngineToB/pod/libs/libspeechsdk.a',
|
||||
'ef80016562b2d408da3425aa5824fde8e81f4eacac68b73e7188dae13709484e',
|
||||
),
|
||||
}
|
||||
MAPPING = {'_syscall': '_IG_sdk_thread_selfid'}
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(['xcrun', *map(str, args)])
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def symbols(*args):
|
||||
return collections.Counter(command('nm', *args).decode().splitlines())
|
||||
|
||||
|
||||
def verify_imports(path):
|
||||
imports = command('nm', '-A', '-u', path).decode().splitlines()
|
||||
names = [line.split()[-1] for line in imports if line.split()]
|
||||
if '_syscall' in names or names.count('_IG_sdk_thread_selfid') != 1:
|
||||
raise ValueError(f'Unexpected imports in {path}')
|
||||
|
||||
|
||||
def prepare(app, output):
|
||||
sources = {}
|
||||
for name, (relative, expected) in INPUTS.items():
|
||||
source = app / relative
|
||||
if digest(source) != expected:
|
||||
raise ValueError(f'{name} changed. Re-audit the SDK before redirecting.')
|
||||
sources[name] = source
|
||||
|
||||
if output.exists() or output.is_symlink():
|
||||
raise FileExistsError(output)
|
||||
with tempfile.TemporaryDirectory(prefix='.thread-id-', dir=output.parent) as tmp:
|
||||
work = Path(tmp)
|
||||
stage = work / 'inputs'
|
||||
stage.mkdir()
|
||||
framework = stage / 'TIWLogger.framework'
|
||||
framework.mkdir()
|
||||
for name in ('Headers', 'Modules'):
|
||||
shutil.copytree(sources['TIWLogger'].parent / name, framework / name)
|
||||
shutil.copy2(sources['TIWLogger'].parent / 'Info.plist', framework)
|
||||
tiw = framework / 'TIWLogger'
|
||||
report = run(sources['TIWLogger'], tiw, MAPPING, require_all=True)
|
||||
members = report['changed_members']
|
||||
if report['references_redirected'] != 1 or [m['member'] for m in members] != ['Util.o']:
|
||||
raise ValueError('Unexpected TIWLogger reference set')
|
||||
verify_imports(tiw)
|
||||
|
||||
speech = stage / 'libspeechsdk.a'
|
||||
command('lipo', sources['speechsdk'], '-thin', 'arm64', '-output', speech)
|
||||
member = work / 'alog_util.o'
|
||||
member.write_bytes(command('ar', '-p', speech, member.name))
|
||||
original_exports = symbols('-gjU', member)
|
||||
native = work / 'alog_util.native.o'
|
||||
with (stage / 'speech-bitcode-compile.log').open('wb') as log:
|
||||
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang',
|
||||
'-target', 'arm64-apple-ios15.0', '-x', 'ir', '-c',
|
||||
str(member), '-o', str(native)], check=True, stderr=log)
|
||||
if original_exports != symbols('-gjU', native):
|
||||
raise ValueError('alog_util exports changed during bitcode compilation')
|
||||
body, count = redirect_object(native.read_bytes(), MAPPING)
|
||||
if count != 1:
|
||||
raise ValueError('Unexpected alog_util reference count')
|
||||
member.write_bytes(body)
|
||||
command('ar', '-r', speech, member)
|
||||
command('ranlib', speech)
|
||||
verify_imports(speech)
|
||||
|
||||
bridge = stage / 'IGThreadID.o'
|
||||
command('--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
||||
'-miphoneos-version-min=15.0', '-O2', '-Wall', '-Wextra', '-Werror',
|
||||
'-c', ROOT / 'defender/call_bridge/IGThreadID.c', '-o', bridge)
|
||||
artifacts = (tiw, speech, bridge)
|
||||
manifest = {
|
||||
'inputs': {name: expected for name, (_, expected) in INPUTS.items()},
|
||||
'artifacts': {str(path.relative_to(stage)): digest(path) for path in artifacts},
|
||||
'replacements': {'TIWLogger': 'Util.o', 'speechsdk': 'alog_util.o'},
|
||||
}
|
||||
(stage / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
stage.rename(output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('app_source', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
args = parser.parse_args()
|
||||
prepare(args.app_source.resolve(), args.output.resolve())
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Redirect selected imports in arm64 archive members, compiling matching LLVM bitcode."""
|
||||
import argparse
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import struct
|
||||
import tempfile
|
||||
|
||||
from redirect_symbols import ARCHIVE_MAGIC, redirect_object, validate_mapping
|
||||
|
||||
|
||||
def run_tool(*args):
|
||||
return subprocess.check_output(['xcrun', *map(str, args)])
|
||||
|
||||
|
||||
def embedded_bitcode(data):
|
||||
if data[:4] != b'\xcf\xfa\xed\xfe':
|
||||
return None
|
||||
offset = 32
|
||||
for _ in range(struct.unpack_from('<I', data, 16)[0]):
|
||||
cmd, size = struct.unpack_from('<II', data, offset)
|
||||
if size < 8 or offset + size > len(data):
|
||||
raise ValueError('Invalid Mach-O load command')
|
||||
if cmd == 0x19:
|
||||
sections = struct.unpack_from('<I', data, offset + 64)[0]
|
||||
if 72 + sections * 80 != size:
|
||||
raise ValueError('Invalid section table')
|
||||
for i in range(sections):
|
||||
section = offset + 72 + i * 80
|
||||
name = data[section:section + 16].split(b'\0')[0]
|
||||
segment = data[section + 16:section + 32].split(b'\0')[0]
|
||||
length, file_offset = struct.unpack_from('<QI', data, section + 40)
|
||||
if segment == b'__LLVM' and name == b'__bitcode' and length > 1:
|
||||
if file_offset + length > len(data):
|
||||
raise ValueError('Embedded bitcode outside object')
|
||||
return data[file_offset:file_offset + length]
|
||||
offset += size
|
||||
return None
|
||||
|
||||
|
||||
def rewrite(source, output, mapping, allow_darwin_extsn=False):
|
||||
validate_mapping(mapping, allow_darwin_extsn=allow_darwin_extsn)
|
||||
if output.exists() or output.is_symlink():
|
||||
raise FileExistsError(output)
|
||||
if not source.read_bytes().startswith(ARCHIVE_MAGIC):
|
||||
raise ValueError('Expected a thin arm64 archive')
|
||||
if not mapping:
|
||||
raise ValueError('Empty mapping')
|
||||
report = []
|
||||
with tempfile.TemporaryDirectory(dir=output.parent, prefix='.bitcode-') as tmp:
|
||||
work = Path(tmp)
|
||||
data = source.read_bytes()
|
||||
result = bytearray(ARCHIVE_MAGIC)
|
||||
cursor = len(ARCHIVE_MAGIC)
|
||||
while cursor < len(data):
|
||||
header = data[cursor:cursor + 60]
|
||||
if len(header) != 60 or header[58:] != b'`\n':
|
||||
raise ValueError('Invalid archive header')
|
||||
size = int(header[48:58])
|
||||
payload = data[cursor + 60:cursor + 60 + size]
|
||||
if len(payload) != size:
|
||||
raise ValueError('Truncated archive member')
|
||||
name = header[:16].rstrip()
|
||||
prefix = b''
|
||||
if name.startswith(b'#1/'):
|
||||
length = int(name[3:])
|
||||
if not 0 < length <= len(payload):
|
||||
raise ValueError('Invalid extended member name')
|
||||
prefix, payload = payload[:length], payload[length:]
|
||||
name = prefix.rstrip(b'\0')
|
||||
name = name.rstrip(b'/')
|
||||
if size % 2 and data[cursor + 60 + size:cursor + 61 + size] != b'\n':
|
||||
raise ValueError('Invalid archive padding')
|
||||
cursor += 60 + size + size % 2
|
||||
if name.startswith(b'__.SYMDEF'):
|
||||
continue
|
||||
member = work / 'member.o'
|
||||
member.write_bytes(payload)
|
||||
imports = {line.split()[-1] for line in run_tool('nm', '-u', member).decode().splitlines() if line.split()}
|
||||
if imports & set(mapping):
|
||||
before = collections.Counter(run_tool('nm', '-gjU', member).splitlines())
|
||||
embedded = embedded_bitcode(payload)
|
||||
compiled = embedded is not None or payload[:4] in (b'\xde\xc0\x17\x0b', b'BC\xc0\xde')
|
||||
if compiled:
|
||||
if embedded is not None:
|
||||
member.write_bytes(embedded)
|
||||
native = work / 'native.o'
|
||||
with (work / 'compile.log').open('wb') as log:
|
||||
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-target',
|
||||
'arm64-apple-ios15.0', '-x', 'ir', '-c', str(member),
|
||||
'-o', str(native)], check=True, stderr=log)
|
||||
payload = native.read_bytes()
|
||||
report_log = output.parent / (output.name + '.compile.log')
|
||||
with report_log.open('ab') as log:
|
||||
log.write(name + b'\n' + (work / 'compile.log').read_bytes())
|
||||
payload, count = redirect_object(payload, mapping, allow_darwin_extsn=allow_darwin_extsn)
|
||||
member.write_bytes(payload)
|
||||
if before != collections.Counter(run_tool('nm', '-gjU', member).splitlines()):
|
||||
raise ValueError('Defined symbols changed')
|
||||
report.append(dict(member=name.decode(), references=count, compiled_bitcode=compiled))
|
||||
body = prefix + payload
|
||||
result.extend(header[:48] + str(len(body)).encode().ljust(10) + header[58:])
|
||||
result.extend(body)
|
||||
if len(body) % 2:
|
||||
result.extend(b'\n')
|
||||
if not report:
|
||||
raise ValueError('No matching imports')
|
||||
candidate = work / 'candidate.a'
|
||||
candidate.write_bytes(result)
|
||||
run_tool('ranlib', candidate)
|
||||
# Publish without overwriting an existing output.
|
||||
import os
|
||||
os.link(candidate, output)
|
||||
return dict(source_sha256=hashlib.sha256(data).hexdigest(),
|
||||
output_sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
mapping=mapping, members=report)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('source', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
parser.add_argument('mapping', type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(rewrite(args.source, args.output, json.loads(args.mapping.read_text())), indent=2))
|
||||
@@ -32,12 +32,14 @@ def bounds(data, offset, length):
|
||||
"数据范围越界")
|
||||
|
||||
|
||||
def validate_mapping(mapping):
|
||||
def validate_mapping(mapping, allow_darwin_extsn=False):
|
||||
require(isinstance(mapping, dict) and bool(mapping), "映射必须是非空 JSON 对象")
|
||||
source_pattern = r"_[A-Za-z_][A-Za-z0-9_]*(\$DARWIN_EXTSN)?" if allow_darwin_extsn else r"_[A-Za-z_][A-Za-z0-9_]*"
|
||||
for source, target in mapping.items():
|
||||
for name in (source, target):
|
||||
require(isinstance(name, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", name),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(isinstance(source, str) and re.fullmatch(source_pattern, source),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(isinstance(target, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", target),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(len(set(mapping.values())) == len(mapping), "多个源符号不能共用一个目标")
|
||||
require(not set(mapping).intersection(mapping.values()), "不允许自映射、映射链或循环")
|
||||
return {source.encode("ascii"): target.encode("ascii") for source, target in mapping.items()}
|
||||
@@ -55,8 +57,10 @@ def load_mapping(path):
|
||||
return mapping
|
||||
|
||||
|
||||
def redirect_object(data, mapping=None):
|
||||
rewritten, counts = _redirect_object(data, validate_mapping(DEFAULT_MAPPING if mapping is None else mapping))
|
||||
def redirect_object(data, mapping=None, allow_darwin_extsn=False):
|
||||
encoded = validate_mapping(DEFAULT_MAPPING if mapping is None else mapping,
|
||||
allow_darwin_extsn=allow_darwin_extsn)
|
||||
rewritten, counts = _redirect_object(data, encoded)
|
||||
return rewritten, sum(counts.values())
|
||||
|
||||
|
||||
|
||||
Executable
+484
@@ -0,0 +1,484 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit exported IPA for Route 2 compliance, static hygiene, dSYM UUID consistency, and Mach-O hardening gates."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
TOOLS_DIR = SCRIPT_DIR.parent
|
||||
TOOLCHAIN_ROOT = TOOLS_DIR.parent
|
||||
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
sys.path.insert(0, str(TOOLS_DIR / 'macho_guard'))
|
||||
sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf'))
|
||||
|
||||
from route2_archive_common import ( # noqa: E402
|
||||
EXTERNAL_SYMBOLS,
|
||||
GUARD_FRAMEWORK_NAME,
|
||||
SYSTEM_SYMBOLS,
|
||||
collect_variant_stubs,
|
||||
)
|
||||
from verify_baseline import scan, validate_zip # noqa: E402
|
||||
import verify_macho_indirect_branches # noqa: E402
|
||||
import verify_macho_indirect_calls # noqa: E402
|
||||
import verify_macho_star_cfg # noqa: E402
|
||||
|
||||
_ANTI_HOOK_OBJDUMP_RE = re.compile(r'^\s*([0-9a-fA-F]+):\s+([0-9a-fA-F]{8})\s+(.+?)\s*$')
|
||||
_ANTI_HOOK_MOV_RE = re.compile(r'^(?:mov\s+(x1[67])\s*,\s*\1|orr\s+(x1[67])\s*,\s*xzr\s*,\s*\2)\b')
|
||||
_ANTI_HOOK_OPCODES = {'aa1103f1': 'x17', 'aa1003f0': 'x16'}
|
||||
|
||||
_FORBIDDEN_DEFENDER_CLUES = (
|
||||
b'IGDefender',
|
||||
b'IGAntiHook',
|
||||
b'IGAntiTamper',
|
||||
b'IGArchiveGuard',
|
||||
b'termination.jsonl',
|
||||
b'"action":"terminate"',
|
||||
)
|
||||
_JAILBREAK_QUERY_SCHEMES = {'cydia', 'sileo', 'zebra', 'zbra', 'filza', 'undecimus'}
|
||||
|
||||
|
||||
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_anti_hook_range(main_bin, start_addr, end_addr):
|
||||
if end_addr - start_addr < 8:
|
||||
return {
|
||||
'start_addr': hex(start_addr),
|
||||
'end_addr': hex(end_addr),
|
||||
'ok': False,
|
||||
'insns': [],
|
||||
'reason': 'function_shorter_than_8_bytes',
|
||||
}
|
||||
dis = subprocess.check_output(
|
||||
[
|
||||
'xcrun', 'llvm-objdump', '--disassemble',
|
||||
f'--start-address={hex(start_addr)}',
|
||||
f'--stop-address={hex(start_addr + 8)}',
|
||||
str(main_bin),
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
insns = []
|
||||
seen_regs = set()
|
||||
for line in dis.splitlines():
|
||||
m = _ANTI_HOOK_OBJDUMP_RE.match(line)
|
||||
if not m:
|
||||
continue
|
||||
addr = int(m.group(1), 16)
|
||||
ophex = m.group(2).lower()
|
||||
text = ' '.join(m.group(3).split())
|
||||
reg = _ANTI_HOOK_OPCODES.get(ophex)
|
||||
if reg is None:
|
||||
mm = _ANTI_HOOK_MOV_RE.match(text)
|
||||
if mm:
|
||||
reg = mm.group(1) or mm.group(2)
|
||||
insns.append({'addr': hex(addr), 'opcode': ophex, 'asm': text, 'reg': reg})
|
||||
if reg in ('x16', 'x17'):
|
||||
seen_regs.add(reg)
|
||||
ok = (
|
||||
len(insns) >= 2
|
||||
and insns[0]['addr'] == hex(start_addr)
|
||||
and insns[1]['addr'] == hex(start_addr + 4)
|
||||
and insns[0]['reg'] in ('x16', 'x17')
|
||||
and insns[1]['reg'] in ('x16', 'x17')
|
||||
and seen_regs == {'x16', 'x17'}
|
||||
)
|
||||
return {
|
||||
'start_addr': hex(start_addr),
|
||||
'end_addr': hex(end_addr),
|
||||
'ok': ok,
|
||||
'insns': insns[:2],
|
||||
}
|
||||
|
||||
|
||||
def _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit):
|
||||
ranges_map = verify_macho_star_cfg.parse_dwarf_text_ranges(dwarf_bin)
|
||||
verified = []
|
||||
failed = []
|
||||
dead_stripped = []
|
||||
to_check = []
|
||||
|
||||
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('anti_hook_functions') or []:
|
||||
cand_ranges = []
|
||||
for key in verify_macho_star_cfg._candidate_symbol_keys(raw_name):
|
||||
if key in ranges_map:
|
||||
cand_ranges = ranges_map[key]
|
||||
break
|
||||
if not cand_ranges:
|
||||
dead_stripped.append({'source': src_name, 'name': raw_name, 'reason': 'not_in_linked_dwarf'})
|
||||
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 = {}
|
||||
if unique_ranges:
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = pool.map(lambda se: _inspect_anti_hook_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, 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 not r['ok']]
|
||||
if bad:
|
||||
failed.append({
|
||||
'source': src_name,
|
||||
'name': raw_name,
|
||||
'reason': 'missing_anti_hook_x16_x17_prologue',
|
||||
'range_results': range_results,
|
||||
})
|
||||
else:
|
||||
verified.append({'source': src_name, 'name': raw_name, **range_results[0]})
|
||||
|
||||
summary = {
|
||||
'total_audited': len(verified) + len(failed) + len(dead_stripped),
|
||||
'linked_checked_count': len(verified) + len(failed),
|
||||
'verified_anti_hook_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 ValueError(f'[AntiHookGate] {len(failed)} function(s) failed x16/x17 prologue check:\n{preview}')
|
||||
return summary
|
||||
|
||||
|
||||
def _check_static_hygiene(app_dir, main_bin, info):
|
||||
"""Run static-hygiene checks on unpacked .app payload (zero hardcoded host paths)."""
|
||||
main_raw = main_bin.read_bytes()
|
||||
|
||||
fw_dir = app_dir / 'Frameworks'
|
||||
rd_coreio_bin = fw_dir / f'{GUARD_FRAMEWORK_NAME}.framework' / GUARD_FRAMEWORK_NAME
|
||||
rd_coreio_exists = rd_coreio_bin.is_file()
|
||||
ig_archive_guard_absent = not (fw_dir / 'IGArchiveGuard.framework').exists()
|
||||
|
||||
rd_coreio_ig_exports = []
|
||||
rd_coreio_ig_name_count = 0
|
||||
if rd_coreio_exists:
|
||||
core_raw = rd_coreio_bin.read_bytes()
|
||||
rd_coreio_ig_name_count = core_raw.count(b'IGArchiveGuard')
|
||||
nm_core = subprocess.check_output(['xcrun', 'nm', '-gU', str(rd_coreio_bin)], text=True, errors='replace')
|
||||
rd_coreio_ig_exports = sorted(
|
||||
sym for ln in nm_core.splitlines()
|
||||
if ln.strip() and (sym := ln.split()[-1]).startswith('_ig_')
|
||||
)
|
||||
|
||||
staticized_framework_leaks = [
|
||||
name for name in ('RDEpubReaderView.framework', 'RDPDFReaderView.framework')
|
||||
if (fw_dir / name).exists()
|
||||
]
|
||||
|
||||
otool_l = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True, errors='replace').splitlines()
|
||||
cryptokit_load_cmds = [ln.strip() for ln in otool_l if 'CryptoKit' in ln]
|
||||
|
||||
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(main_bin)], text=True, errors='replace').splitlines()
|
||||
cryptokit_imports = sorted({
|
||||
ln.strip() for ln in nm_u
|
||||
if ln.strip() and ('CryptoKit' in ln or '9CryptoKit' in ln)
|
||||
})
|
||||
|
||||
nm_gu = subprocess.check_output(['xcrun', 'nm', '-gU', str(main_bin)], text=True, errors='replace')
|
||||
defined_exports = sorted({ln.split()[-1] for ln in nm_gu.splitlines() if ln.strip()})
|
||||
allowed_exports = {'_main', '__mh_execute_header'}
|
||||
main_exports_locked = set(defined_exports).issubset(allowed_exports)
|
||||
|
||||
forbidden_clue_counts = {
|
||||
pat.decode('ascii', errors='replace'): main_raw.count(pat)
|
||||
for pat in _FORBIDDEN_DEFENDER_CLUES
|
||||
}
|
||||
|
||||
ats = info.get('NSAppTransportSecurity') or {}
|
||||
ats_arbitrary_disabled = ats.get('NSAllowsArbitraryLoads') is not True
|
||||
schemes = {str(s).lower() for s in (info.get('LSApplicationQueriesSchemes') or [])}
|
||||
jb_schemes_found = sorted(schemes & _JAILBREAK_QUERY_SCHEMES)
|
||||
|
||||
checks = {
|
||||
'guard_framework_present': rd_coreio_exists,
|
||||
'ig_archive_guard_absent': ig_archive_guard_absent,
|
||||
'guard_no_ig_exports': not rd_coreio_ig_exports,
|
||||
'guard_no_ig_name_string': rd_coreio_ig_name_count == 0,
|
||||
'self_frameworks_staticized': not staticized_framework_leaks,
|
||||
'cryptokit_completely_absent': not cryptokit_load_cmds and not cryptokit_imports,
|
||||
'main_exports_locked': main_exports_locked,
|
||||
'defender_clues_absent': sum(forbidden_clue_counts.values()) == 0,
|
||||
'ats_arbitrary_loads_disabled': ats_arbitrary_disabled,
|
||||
'jailbreak_schemes_absent': not jb_schemes_found,
|
||||
}
|
||||
return {
|
||||
'passed': all(checks.values()),
|
||||
'checks': checks,
|
||||
'rd_coreio_ig_exports': rd_coreio_ig_exports,
|
||||
'rd_coreio_ig_name_count': rd_coreio_ig_name_count,
|
||||
'staticized_framework_leaks': staticized_framework_leaks,
|
||||
'cryptokit_load_cmds': cryptokit_load_cmds,
|
||||
'cryptokit_imports': cryptokit_imports,
|
||||
'main_defined_exports': defined_exports,
|
||||
'forbidden_clue_counts': forbidden_clue_counts,
|
||||
'jailbreak_schemes_found': jb_schemes_found,
|
||||
}
|
||||
|
||||
|
||||
def _check_obf_audit_counts(obf_audit, policy):
|
||||
failures = []
|
||||
checks = [
|
||||
('flatten_targets', 'total_flattened'),
|
||||
('opaque_const_targets', 'total_opaque_constants'),
|
||||
('arithmetic_targets', 'total_arithmetic_rewrites'),
|
||||
('indirect_branch_targets', 'total_indirect_branches'),
|
||||
('string_encrypt_stack_targets', 'total_strings_stack_encrypted'),
|
||||
('anti_hooking_targets', 'total_anti_hook_functions'),
|
||||
('function_outline_targets', 'total_functions_outlined'),
|
||||
('opaque_field_targets', 'total_opaque_field_access'),
|
||||
('bb_split_targets', 'total_bb_split_count'),
|
||||
]
|
||||
for pol_key, audit_key in checks:
|
||||
if policy.get(pol_key) and int(obf_audit.get(audit_key) or 0) <= 0:
|
||||
failures.append(f'{audit_key} expected > 0')
|
||||
|
||||
has_str = any(
|
||||
policy.get(k)
|
||||
for k in ('string_encrypt_targets', 'string_encrypt_objc_targets', 'string_encrypt_swift_targets')
|
||||
)
|
||||
if has_str and int(obf_audit.get('total_strings_encrypted') or 0) <= 0:
|
||||
failures.append('total_strings_encrypted expected > 0')
|
||||
|
||||
if policy.get('arithmetic_nonlinear_mba') or any(r.get('nonlinear_mba') for r in (policy.get('arithmetic_targets') or [])):
|
||||
if int(obf_audit.get('total_nonlinear_mba') or 0) <= 0:
|
||||
failures.append('total_nonlinear_mba expected > 0')
|
||||
|
||||
if policy.get('opaque_const_opaque_zero') or any(r.get('opaque_zero') for r in (policy.get('opaque_const_targets') or [])):
|
||||
if int(obf_audit.get('total_opaque_zero') or 0) <= 0:
|
||||
failures.append('total_opaque_zero expected > 0')
|
||||
|
||||
policy_reqs = {r['id']: r for r in (policy.get('required_targets') or []) if isinstance(r, dict) and r.get('id')}
|
||||
if policy_reqs and isinstance(obf_audit.get('required_targets'), list):
|
||||
got_map = {r['id']: r for r in obf_audit['required_targets'] if isinstance(r, dict) and r.get('id')}
|
||||
for tid, req in policy_reqs.items():
|
||||
got = got_map.get(tid)
|
||||
if got is None:
|
||||
failures.append(f'missing required_target: {tid}')
|
||||
continue
|
||||
if int(got.get('flattened_hits') or 0) < int(req.get('min_flattened', 0)):
|
||||
failures.append(f'{tid} flattened_hits={got.get("flattened_hits")} < {req.get("min_flattened", 0)}')
|
||||
if int(got.get('strings_encrypted_hits') or 0) < int(req.get('min_strings_encrypted', 0)):
|
||||
failures.append(
|
||||
f'{tid} strings_encrypted_hits={got.get("strings_encrypted_hits")} < {req.get("min_strings_encrypted", 0)}'
|
||||
)
|
||||
|
||||
return failures
|
||||
|
||||
|
||||
def _load_policy(policy_path=None):
|
||||
cand = Path(policy_path) if policy_path else (TOOLCHAIN_ROOT / 'config' / 'ig_llvm_policy.json')
|
||||
if cand.is_file():
|
||||
return json.loads(cand.read_text(encoding='utf-8'))
|
||||
return {}
|
||||
|
||||
|
||||
def _find_dwarf_in_archive(archive_path, app_name, exec_name):
|
||||
dsyms_dir = Path(archive_path) / 'dSYMs'
|
||||
if not dsyms_dir.is_dir():
|
||||
return None
|
||||
for cand_name in (f'{app_name}.dSYM', f'{exec_name}.app.dSYM'):
|
||||
dwarf_p = dsyms_dir / cand_name / 'Contents' / 'Resources' / 'DWARF' / exec_name
|
||||
if dwarf_p.is_file():
|
||||
return dwarf_p
|
||||
for dsym in sorted(dsyms_dir.glob('*.app.dSYM')):
|
||||
dwarf_p = dsym / 'Contents' / 'Resources' / 'DWARF' / dsym.name.removesuffix('.app.dSYM')
|
||||
if dwarf_p.is_file():
|
||||
return dwarf_p
|
||||
return None
|
||||
|
||||
|
||||
def audit_ipa(
|
||||
ipa,
|
||||
expected_bundle_id=None,
|
||||
archive_path=None,
|
||||
audit_json_path=None,
|
||||
policy_path=None,
|
||||
symbol_map_path=None,
|
||||
skip_macho_gates=False,
|
||||
report_out=None,
|
||||
):
|
||||
validate_zip(ipa)
|
||||
report = {
|
||||
'ipa': str(ipa),
|
||||
'passed': False,
|
||||
'errors': [],
|
||||
}
|
||||
try:
|
||||
with TemporaryDirectory(prefix='ig-export-audit-') as temporary_dir:
|
||||
unpacked = Path(temporary_dir)
|
||||
subprocess.run(['ditto', '-x', '-k', str(ipa), str(unpacked)], check=True)
|
||||
apps = sorted((unpacked / 'Payload').glob('*.app'))
|
||||
if len(apps) != 1:
|
||||
raise ValueError(f'IPA 应包含一个主 App,实际找到 {len(apps)} 个')
|
||||
|
||||
app = apps[0]
|
||||
with (app / 'Info.plist').open('rb') as plist_file:
|
||||
info = plistlib.load(plist_file)
|
||||
bundle_id = info['CFBundleIdentifier']
|
||||
if expected_bundle_id and bundle_id != expected_bundle_id:
|
||||
raise ValueError(f'IPA Bundle ID 为 {bundle_id},预期为 {expected_bundle_id}')
|
||||
|
||||
exec_name = info['CFBundleExecutable']
|
||||
main_bin = app / exec_name
|
||||
binaries, callsites = scan(app, unpacked, 'exported')
|
||||
if exec_name not in binaries:
|
||||
raise ValueError('IPA 主可执行文件未纳入 Mach-O 扫描')
|
||||
|
||||
counts = dict.fromkeys(EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS, 0)
|
||||
invalid_images = []
|
||||
for relative_path, binary in binaries.items():
|
||||
if any(section['cryptid'] for section in binary['slices']):
|
||||
raise ValueError(f'无法静态检查已加密的 Mach-O:{relative_path}')
|
||||
for section in binary['slices']:
|
||||
for symbol, count in section['counts'].items():
|
||||
counts[symbol] += count
|
||||
variants = collect_variant_stubs(app / relative_path)
|
||||
if variants:
|
||||
invalid_images.append(f'{relative_path}: {", ".join(variants)}')
|
||||
|
||||
external = sum(counts[symbol] for symbol in EXTERNAL_SYMBOLS)
|
||||
system = sum(counts[symbol] for symbol in SYSTEM_SYMBOLS)
|
||||
report['bundle_id'] = bundle_id
|
||||
report['route2'] = {
|
||||
'binaries': len(binaries),
|
||||
'external_calls': external,
|
||||
'system_calls': system,
|
||||
'callsites_total': callsites,
|
||||
'variant_stubs': invalid_images,
|
||||
}
|
||||
if callsites or invalid_images:
|
||||
raise ValueError(
|
||||
f'IPA Route 2 审计失败:外部函数直接调用 {external},系统函数直接调用 {system},'
|
||||
f'变体符号 {invalid_images}'
|
||||
)
|
||||
|
||||
hygiene = _check_static_hygiene(app, main_bin, info)
|
||||
report['static_hygiene'] = hygiene
|
||||
if not hygiene['passed']:
|
||||
failed_keys = [k for k, v in hygiene['checks'].items() if not v]
|
||||
raise ValueError(f'IPA 静态卫生门禁失败: {failed_keys}')
|
||||
|
||||
policy = _load_policy(policy_path)
|
||||
obf_audit = None
|
||||
if audit_json_path and Path(audit_json_path).is_file():
|
||||
obf_audit = json.loads(Path(audit_json_path).read_text(encoding='utf-8'))
|
||||
audit_failures = _check_obf_audit_counts(obf_audit, policy)
|
||||
report['obf_audit_summary'] = {
|
||||
k: obf_audit.get(k)
|
||||
for k in (
|
||||
'total_flattened', 'total_strings_encrypted', 'total_strings_stack_encrypted',
|
||||
'total_indirect_calls', 'total_opaque_constants', 'total_arithmetic_rewrites',
|
||||
'total_nonlinear_mba', 'total_opaque_zero', 'total_indirect_branches',
|
||||
'total_anti_hook_functions', 'total_functions_outlined',
|
||||
'total_opaque_field_access', 'total_bb_split_count', 'static_frameworks_obfuscated',
|
||||
)
|
||||
}
|
||||
if audit_failures:
|
||||
raise ValueError(f'LLVM 混淆审计计数不满足策略: {"; ".join(audit_failures)}')
|
||||
|
||||
if archive_path and Path(archive_path).is_dir():
|
||||
dwarf_bin = _find_dwarf_in_archive(archive_path, app.name, exec_name)
|
||||
if dwarf_bin is None:
|
||||
raise ValueError(f'xcarchive 缺少 DWARF 文件: {archive_path}')
|
||||
ipa_uuids = _uuids_of(main_bin)
|
||||
dwarf_uuids = _uuids_of(dwarf_bin)
|
||||
report['dsym_uuid_match'] = {
|
||||
'ipa_uuids': sorted(ipa_uuids),
|
||||
'dwarf_uuids': sorted(dwarf_uuids),
|
||||
'matched': bool(ipa_uuids) and ipa_uuids == dwarf_uuids,
|
||||
}
|
||||
if not report['dsym_uuid_match']['matched']:
|
||||
raise ValueError(f'IPA 与 dSYM UUID 不一致: ipa={ipa_uuids}, dwarf={dwarf_uuids}')
|
||||
|
||||
if obf_audit is not None and not skip_macho_gates:
|
||||
star_gate = verify_macho_star_cfg.verify_binary_star_cfg(
|
||||
main_bin, dwarf_bin, obf_audit, require_topology='sparse_switch'
|
||||
)
|
||||
report['star_cfg_gate'] = star_gate
|
||||
if policy.get('flatten_targets') and star_gate['verified_star_count'] <= 0:
|
||||
raise ValueError('StarCFGGate verified_star_count 为 0')
|
||||
|
||||
ibr_gate = verify_macho_indirect_branches.verify_binary_indirect_branches(
|
||||
main_bin, dwarf_bin, obf_audit
|
||||
)
|
||||
report['indirect_branch_gate'] = ibr_gate
|
||||
if policy.get('indirect_branch_targets') and ibr_gate['verified_ibr_count'] <= 0:
|
||||
raise ValueError('IndirectBranchGate verified_ibr_count 为 0')
|
||||
|
||||
icall_gate = verify_macho_indirect_calls.analyze_macho_calls(
|
||||
main_bin,
|
||||
dwarf_bin,
|
||||
symbol_map_path=Path(symbol_map_path) if symbol_map_path else None,
|
||||
require_zero_keybox_direct_bl=bool(policy.get('indirect_call_targets')),
|
||||
)
|
||||
report['indirect_call_gate'] = {
|
||||
'text_call_summary': icall_gate['text_call_summary'],
|
||||
'keybox_total_direct_call_xrefs': icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs'],
|
||||
'gate_passed': icall_gate['gate_passed'],
|
||||
'violations': icall_gate['violations'],
|
||||
}
|
||||
if not icall_gate['gate_passed']:
|
||||
raise ValueError(f"IndirectCallGate failed: {icall_gate['violations']}")
|
||||
|
||||
anti_hook_gate = _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit)
|
||||
report['anti_hook_gate'] = anti_hook_gate
|
||||
if policy.get('anti_hooking_targets') and anti_hook_gate['verified_anti_hook_count'] <= 0:
|
||||
raise ValueError('AntiHookGate verified_anti_hook_count 为 0')
|
||||
|
||||
report['passed'] = True
|
||||
print(
|
||||
f'IPA 审计通过:{bundle_id},{len(binaries)} 个 Mach-O,'
|
||||
f'外部函数直接调用 {external},系统函数直接调用 {system},'
|
||||
f'StaticHygieneGate=PASS'
|
||||
)
|
||||
return report
|
||||
except Exception as exc:
|
||||
report['errors'].append(str(exc))
|
||||
raise
|
||||
finally:
|
||||
if report_out:
|
||||
out_p = Path(report_out)
|
||||
out_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_p.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('ipa', type=Path)
|
||||
parser.add_argument('--bundle-id')
|
||||
parser.add_argument('--archive', type=Path, default=None)
|
||||
parser.add_argument('--audit-json', type=Path, default=None)
|
||||
parser.add_argument('--policy', type=Path, default=None)
|
||||
parser.add_argument('--symbol-map', type=Path, default=None)
|
||||
parser.add_argument('--report-out', type=Path, default=None)
|
||||
parser.add_argument('--skip-macho-gates', action='store_true')
|
||||
arguments = parser.parse_args()
|
||||
try:
|
||||
audit_ipa(
|
||||
arguments.ipa,
|
||||
expected_bundle_id=arguments.bundle_id,
|
||||
archive_path=arguments.archive,
|
||||
audit_json_path=arguments.audit_json,
|
||||
policy_path=arguments.policy,
|
||||
symbol_map_path=arguments.symbol_map,
|
||||
skip_macho_gates=arguments.skip_macho_gates,
|
||||
report_out=arguments.report_out,
|
||||
)
|
||||
except (OSError, ValueError, AssertionError, subprocess.CalledProcessError) as error:
|
||||
parser.exit(1, f'{error}\n')
|
||||
Executable
+413
@@ -0,0 +1,413 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Xcode Release arm64 C/ObjC compiler wrapper (3-stage LLVM bitcode -> opt -> native Mach-O)."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
TOOLS_DIR = SCRIPT_DIR.parent
|
||||
TOOLCHAIN_ROOT = TOOLS_DIR.parent
|
||||
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf'))
|
||||
|
||||
from ig_toolchain_resolver import ( # noqa: E402
|
||||
detect_sdk_info,
|
||||
detect_stock_tool,
|
||||
detect_xcode_info,
|
||||
discover_active_app_repo,
|
||||
file_sha256,
|
||||
resolve_effective_policy,
|
||||
resolve_opt,
|
||||
)
|
||||
|
||||
SOURCE_EXTENSIONS = {'.c', '.m', '.mm', '.cc', '.cpp', '.cxx', '.c++'}
|
||||
|
||||
|
||||
def resolve_default_policy(profile='default'):
|
||||
names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else []
|
||||
names.append('ig_llvm_policy.json')
|
||||
for name in names:
|
||||
for cand in (
|
||||
TOOLCHAIN_ROOT / 'config' / name,
|
||||
TOOLCHAIN_ROOT / 'llvm_obf' / name,
|
||||
):
|
||||
if cand.is_file():
|
||||
return str(cand)
|
||||
return ''
|
||||
|
||||
|
||||
def expand_response_files(args):
|
||||
expanded = []
|
||||
for arg in args:
|
||||
if arg.startswith('@') and len(arg) > 1:
|
||||
resp = Path(arg[1:])
|
||||
if resp.is_file():
|
||||
text = resp.read_text(encoding='utf-8', errors='replace')
|
||||
expanded.extend(shlex.split(text))
|
||||
continue
|
||||
expanded.append(arg)
|
||||
return expanded
|
||||
|
||||
|
||||
def parse_control_token(expanded_args):
|
||||
"""Extract control tuple from `-DIG_OBF_CTL_<mode>__<filter>__<route2>__<all_off>__<seed>__<stamp>[__<profile>]=1`."""
|
||||
ctl = {
|
||||
'mode': 'full',
|
||||
'filter': 'all',
|
||||
'route2': 'on',
|
||||
'all_off': '0',
|
||||
'seed': 'm0_seed_20261119_v1',
|
||||
'stamp': 'default',
|
||||
'policy_profile': 'default',
|
||||
}
|
||||
prefix = '-DIG_OBF_CTL_'
|
||||
for arg in expanded_args:
|
||||
if arg.startswith(prefix):
|
||||
body = arg[len(prefix):]
|
||||
if '=' in body:
|
||||
body = body.split('=', 1)[0]
|
||||
parts = body.split('__')
|
||||
if len(parts) >= 7:
|
||||
ctl['mode'] = parts[0] or ctl['mode']
|
||||
ctl['filter'] = parts[1] or ctl['filter']
|
||||
ctl['route2'] = parts[2] or ctl['route2']
|
||||
ctl['all_off'] = parts[3] or ctl['all_off']
|
||||
ctl['seed'] = parts[4] or ctl['seed']
|
||||
ctl['stamp'] = parts[5] or ctl['stamp']
|
||||
ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile']
|
||||
elif len(parts) >= 6:
|
||||
ctl['mode'] = parts[0] or ctl['mode']
|
||||
ctl['filter'] = parts[1] or ctl['filter']
|
||||
ctl['route2'] = parts[2] or ctl['route2']
|
||||
ctl['all_off'] = parts[3] or ctl['all_off']
|
||||
ctl['seed'] = parts[4] or ctl['seed']
|
||||
ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp']
|
||||
elif len(parts) >= 1 and parts[0]:
|
||||
ctl['mode'] = parts[0]
|
||||
|
||||
# Env overrides take precedence if explicitly set
|
||||
if os.environ.get('IG_DISABLE_LLVM_OBF') == '1':
|
||||
ctl['mode'] = 'off'
|
||||
if os.environ.get('IG_ALL_GUARD_OFF') == '1':
|
||||
ctl['all_off'] = '1'
|
||||
ctl['mode'] = 'off'
|
||||
if os.environ.get('IG_OBF_MODE'):
|
||||
ctl['mode'] = os.environ['IG_OBF_MODE']
|
||||
if os.environ.get('IG_LLVM_PASS_FILTER'):
|
||||
ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER']
|
||||
if os.environ.get('IG_RELEASE_SEED'):
|
||||
ctl['seed'] = os.environ['IG_RELEASE_SEED']
|
||||
if os.environ.get('IG_POLICY_PROFILE'):
|
||||
ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE']
|
||||
if ctl['all_off'] == '1':
|
||||
ctl['mode'] = 'off'
|
||||
return ctl
|
||||
|
||||
|
||||
def parse_compile_metadata(raw_args, expanded_args):
|
||||
has_c = '-c' in expanded_args
|
||||
out_path = None
|
||||
top_out_idx = None
|
||||
for idx, arg in enumerate(raw_args):
|
||||
if arg == '-o' and idx + 1 < len(raw_args):
|
||||
top_out_idx = idx + 1
|
||||
out_path = raw_args[idx + 1]
|
||||
|
||||
if out_path is None:
|
||||
for idx, arg in enumerate(expanded_args):
|
||||
if arg == '-o' and idx + 1 < len(expanded_args):
|
||||
out_path = expanded_args[idx + 1]
|
||||
|
||||
lang = None
|
||||
isysroot = None
|
||||
target = None
|
||||
arch = None
|
||||
min_ver_flag = None
|
||||
opt_flag = None
|
||||
debug_flags = []
|
||||
extra_codegen = []
|
||||
source_path = None
|
||||
|
||||
i = 0
|
||||
skip_next_flags = {
|
||||
'-o', '-I', '-isystem', '-iquote', '-F', '-iframework', '-include',
|
||||
'-include-pch', '-MT', '-MF', '-MQ', '-D', '-U', '-x', '-target',
|
||||
'-arch', '-isysroot', '-ivfsoverlay', '-index-store-path',
|
||||
'-index-unit-output-path', '--serialize-diagnostics', '-dependency-info',
|
||||
'-pch-output-dir', '-fmodule-map-file', '-Xclang', '-Xpreprocessor',
|
||||
'-idirafter', '-iprefix', '-iwithprefix', '-iwithprefixbefore', '-B',
|
||||
}
|
||||
while i < len(expanded_args):
|
||||
a = expanded_args[i]
|
||||
nxt = expanded_args[i + 1] if i + 1 < len(expanded_args) else None
|
||||
if a == '-x' and nxt is not None:
|
||||
lang = nxt
|
||||
i += 2
|
||||
continue
|
||||
if a == '-target' and nxt is not None:
|
||||
target = nxt
|
||||
i += 2
|
||||
continue
|
||||
if a.startswith('--target='):
|
||||
target = a.split('=', 1)[1]
|
||||
i += 1
|
||||
continue
|
||||
if a == '-arch' and nxt is not None:
|
||||
arch = nxt
|
||||
i += 2
|
||||
continue
|
||||
if a == '-isysroot' and nxt is not None:
|
||||
isysroot = nxt
|
||||
i += 2
|
||||
continue
|
||||
if a.startswith('-miphoneos-version-min=') or a.startswith('-mllvm'):
|
||||
if a.startswith('-miphoneos-version-min='):
|
||||
min_ver_flag = a
|
||||
elif nxt is not None:
|
||||
i += 2
|
||||
continue
|
||||
i += 1
|
||||
continue
|
||||
if a in ('-O0', '-O1', '-O2', '-O3', '-Os', '-Oz', '-Ofast'):
|
||||
opt_flag = a
|
||||
i += 1
|
||||
continue
|
||||
if a.startswith('-g') and not a.startswith('-gmodules') and a != '-g0':
|
||||
debug_flags.append(a)
|
||||
i += 1
|
||||
continue
|
||||
if a in ('-fPIC', '-fpic', '-fno-common', '-fstrict-aliasing', '-fno-strict-aliasing') or (
|
||||
a.startswith('-fvisibility=')
|
||||
or a.startswith('-fstack-protector')
|
||||
or a.startswith('-ffile-prefix-map=')
|
||||
or a.startswith('-fdebug-prefix-map=')
|
||||
or a.startswith('-fembed-bitcode')
|
||||
):
|
||||
extra_codegen.append(a)
|
||||
i += 1
|
||||
continue
|
||||
if a in skip_next_flags and nxt is not None:
|
||||
i += 2
|
||||
continue
|
||||
if not a.startswith('-'):
|
||||
if Path(a).suffix.lower() in SOURCE_EXTENSIONS:
|
||||
source_path = a
|
||||
i += 1
|
||||
|
||||
return {
|
||||
'has_c': has_c,
|
||||
'out_path': out_path,
|
||||
'top_out_idx': top_out_idx,
|
||||
'lang': lang,
|
||||
'isysroot': isysroot,
|
||||
'target': target,
|
||||
'arch': arch,
|
||||
'min_ver_flag': min_ver_flag,
|
||||
'opt_flag': opt_flag or '-Os',
|
||||
'debug_flags': debug_flags,
|
||||
'extra_codegen': extra_codegen,
|
||||
'source_path': source_path,
|
||||
}
|
||||
|
||||
|
||||
def should_passthrough(meta, expanded_args, ctl, policy):
|
||||
if ctl['all_off'] == '1' or ctl['mode'] == 'off':
|
||||
return True, f"mode={ctl['mode']} all_off={ctl['all_off']}"
|
||||
if os.environ.get('PLATFORM_NAME') and os.environ.get('PLATFORM_NAME') != 'iphoneos':
|
||||
return True, f"platform={os.environ.get('PLATFORM_NAME')}"
|
||||
if os.environ.get('CONFIGURATION') and os.environ.get('CONFIGURATION') != 'Release':
|
||||
return True, f"config={os.environ.get('CONFIGURATION')}"
|
||||
if not meta['has_c'] or not meta['out_path']:
|
||||
return True, 'not single -c object compile'
|
||||
if any(f in expanded_args for f in ('-E', '-M', '-MM', '-fsyntax-only', '--analyze', '-emit-llvm', '-S')):
|
||||
return True, 'preprocess/syntax/emit-llvm/asm mode'
|
||||
if meta['lang'] and (meta['lang'].endswith('-header') or meta['lang'] in ('ir', 'assembler', 'assembler-with-cpp')):
|
||||
return True, f"lang={meta['lang']}"
|
||||
out_suf = Path(meta['out_path']).suffix.lower()
|
||||
if out_suf in ('.pch', '.gch', '.pcm'):
|
||||
return True, f'precompiled header output {out_suf}'
|
||||
if meta['arch'] and meta['arch'] != 'arm64':
|
||||
return True, f"non-arm64 arch {meta['arch']}"
|
||||
if meta['target'] and 'arm64' not in meta['target']:
|
||||
return True, f"non-arm64 target {meta['target']}"
|
||||
if meta['isysroot'] and 'iPhoneSimulator' in meta['isysroot']:
|
||||
return True, 'simulator sdk'
|
||||
src = meta['source_path'] or ''
|
||||
if not src:
|
||||
return True, 'no C/ObjC/C++ source path'
|
||||
for ex in policy.get('exempt_path_substrings', []):
|
||||
if ex in src:
|
||||
return True, f'exempt path ({ex})'
|
||||
return False, ''
|
||||
|
||||
|
||||
def build_stage3_flags(meta):
|
||||
flags = []
|
||||
if meta['target']:
|
||||
flags.extend(['-target', meta['target']])
|
||||
else:
|
||||
flags.extend(['-arch', meta['arch'] or 'arm64'])
|
||||
if meta['min_ver_flag']:
|
||||
flags.append(meta['min_ver_flag'])
|
||||
if meta['isysroot']:
|
||||
flags.extend(['-isysroot', meta['isysroot']])
|
||||
if meta['target'] and meta['min_ver_flag'] and 'ios' not in meta['target']:
|
||||
flags.append(meta['min_ver_flag'])
|
||||
flags.append(meta['opt_flag'])
|
||||
flags.extend(meta['debug_flags'])
|
||||
flags.extend(meta['extra_codegen'])
|
||||
flags.extend(['-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c'])
|
||||
return flags
|
||||
|
||||
|
||||
def infer_obj_cache_dir(out_path):
|
||||
env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR')
|
||||
if env_dir:
|
||||
return Path(env_dir)
|
||||
for parent in out_path.parents:
|
||||
if parent.name in ('Intermediates.noindex', 'Build'):
|
||||
return parent / 'ig-obf-obj-cache'
|
||||
return out_path.parent / '.ig-obf-obj-cache'
|
||||
|
||||
|
||||
def run_wrapper(argv=None, cxx=False):
|
||||
raw_args = list(sys.argv[1:] if argv is None else argv)
|
||||
tool_name = 'clang++' if cxx else 'clang'
|
||||
real_cc = detect_stock_tool(tool_name)
|
||||
expanded_args = expand_response_files(raw_args)
|
||||
ctl = parse_control_token(expanded_args)
|
||||
|
||||
policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default'))
|
||||
policy = {}
|
||||
if policy_path and Path(policy_path).is_file():
|
||||
policy = json.loads(Path(policy_path).read_text(encoding='utf-8'))
|
||||
|
||||
meta = parse_compile_metadata(raw_args, expanded_args)
|
||||
passthrough, _ = should_passthrough(meta, expanded_args, ctl, policy)
|
||||
if passthrough:
|
||||
if meta.get('out_path'):
|
||||
stale_audit = Path(str(meta['out_path']) + '.ig-audit.json')
|
||||
if stale_audit.exists():
|
||||
try:
|
||||
stale_audit.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
os.execv(real_cc, [real_cc, *raw_args])
|
||||
return 0
|
||||
|
||||
require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop')
|
||||
tc = resolve_opt(require_obf=require_obf)
|
||||
opt_path = tc.get('opt_path')
|
||||
if not opt_path:
|
||||
sys.stderr.write(f"[IGCC] WARNING: {tc.get('warning', 'opt unavailable')}; falling back to stock {tool_name}\n")
|
||||
os.execv(real_cc, [real_cc, *raw_args])
|
||||
return 0
|
||||
|
||||
out_path = Path(meta['out_path'])
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
audit_sidecar = Path(str(out_path) + '.ig-audit.json')
|
||||
|
||||
app_repo = discover_active_app_repo([meta.get('source_path') or ''])
|
||||
eff_policy_path, _eff_policy = resolve_effective_policy(policy_path, app_repo, infer_obj_cache_dir(out_path))
|
||||
|
||||
stage3_prefix = build_stage3_flags(meta)
|
||||
xc_build = tc['xcode']['xcode_build']
|
||||
sdk_info = detect_sdk_info(meta['isysroot']) if meta['isysroot'] else {'sdk_version': ''}
|
||||
wrapper_sha = file_sha256(__file__)
|
||||
policy_sha = file_sha256(eff_policy_path) if eff_policy_path and Path(eff_policy_path).is_file() else 'none'
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='.ig-cc-', dir=out_path.parent) as td:
|
||||
work = Path(td)
|
||||
bc_path = work / 'stage1.bc'
|
||||
obf_bc_path = work / 'stage2.obf.bc'
|
||||
|
||||
# Stage 1: stock clang -> bitcode (preserving .pch, .d, .dia generation!)
|
||||
s1_args = list(raw_args)
|
||||
if meta['top_out_idx'] is not None:
|
||||
s1_args[meta['top_out_idx']] = str(bc_path)
|
||||
else:
|
||||
s1_args.extend(['-o', str(bc_path)])
|
||||
s1_args.append('-emit-llvm')
|
||||
|
||||
p1 = subprocess.run([real_cc, *s1_args])
|
||||
if p1.returncode != 0:
|
||||
return p1.returncode
|
||||
|
||||
bc_sha = file_sha256(bc_path)
|
||||
key_hash = hashlib.sha256(
|
||||
json.dumps(
|
||||
{
|
||||
'kind': 'cc_v1',
|
||||
'bc_sha256': bc_sha,
|
||||
'xcode_build': xc_build,
|
||||
'sdk_version': sdk_info.get('sdk_version', ''),
|
||||
'opt_sha256': tc['opt_sha256'],
|
||||
'wrapper_sha256': wrapper_sha,
|
||||
'policy_sha256': policy_sha,
|
||||
'mode': ctl['mode'],
|
||||
'filter': ctl['filter'],
|
||||
'seed': ctl['seed'],
|
||||
'stamp': ctl['stamp'],
|
||||
'stage3': stage3_prefix,
|
||||
},
|
||||
sort_keys=True,
|
||||
).encode('utf-8')
|
||||
).hexdigest()[:24]
|
||||
|
||||
cache_dir = infer_obj_cache_dir(out_path) / key_hash[:2]
|
||||
cached_obj = cache_dir / f'{key_hash}.o'
|
||||
cached_audit = cache_dir / f'{key_hash}.audit.json'
|
||||
|
||||
if cached_obj.is_file() and cached_audit.is_file():
|
||||
shutil.copy2(cached_obj, out_path)
|
||||
shutil.copy2(cached_audit, audit_sidecar)
|
||||
return 0
|
||||
|
||||
# Stage 2: standalone opt
|
||||
opt_cmd = [
|
||||
opt_path,
|
||||
'-passes=ig-obfuscate',
|
||||
f'--ig-policy={eff_policy_path}',
|
||||
f"--ig-mode={ctl['mode']}",
|
||||
f"--ig-pass-filter={ctl['filter']}",
|
||||
f"--ig-seed={ctl['seed']}",
|
||||
f"--ig-source-path={meta['source_path'] or ''}",
|
||||
f'--ig-audit-out={audit_sidecar}',
|
||||
str(bc_path),
|
||||
'-o',
|
||||
str(obf_bc_path),
|
||||
]
|
||||
p2 = subprocess.run(opt_cmd)
|
||||
if p2.returncode != 0:
|
||||
return p2.returncode
|
||||
|
||||
# Stage 3: stock clang pure backend lowering (no duplicate middle-end IR passes)
|
||||
s3_cmd = [real_cc, *stage3_prefix, str(obf_bc_path), '-o', str(out_path)]
|
||||
p3 = subprocess.run(s3_cmd)
|
||||
if p3.returncode != 0:
|
||||
return p3.returncode
|
||||
|
||||
# Atomic cache save (.o + .audit.json sidecar)
|
||||
try:
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
tmp_o = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.o'
|
||||
tmp_a = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json'
|
||||
shutil.copy2(out_path, tmp_o)
|
||||
shutil.copy2(audit_sidecar, tmp_a)
|
||||
tmp_o.replace(cached_obj)
|
||||
tmp_a.replace(cached_audit)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(run_wrapper(cxx=False))
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Xcode Release arm64 C++/ObjC++ compiler wrapper."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from ig_cc_wrapper import run_wrapper # noqa: E402
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(run_wrapper(cxx=True))
|
||||
+599
@@ -0,0 +1,599 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Xcode Release arm64 Run Script phase for IGArchiveGuard, dynamic framework rebinding, and whole-app audit."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
TOOLS_DIR = SCRIPT_DIR.parent
|
||||
TOOLCHAIN_ROOT = TOOLS_DIR.parent
|
||||
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
sys.path.insert(0, str(TOOLS_DIR / 'macho_guard'))
|
||||
sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf'))
|
||||
|
||||
from batch import arm64_slices, iter_macho_files # noqa: E402
|
||||
from machox import Macho, LC_DYLD_CHAINED_FIXUPS # noqa: E402
|
||||
from redirect_framework_imports import ( # noqa: E402
|
||||
DEPENDENCY,
|
||||
detect_chained_target_mapping,
|
||||
rewrite as rewrite_chained,
|
||||
)
|
||||
from redirect_legacy_imports import ( # noqa: E402
|
||||
detect_legacy_target_mapping,
|
||||
rewrite as rewrite_legacy,
|
||||
)
|
||||
from route2_archive_common import ( # noqa: E402
|
||||
EXPECTED_ARCHIVE_EXPORTS,
|
||||
EXTERNAL_SYMBOLS,
|
||||
FORBIDDEN_SYMBOLS,
|
||||
GUARD_BUNDLE_ID,
|
||||
GUARD_FRAMEWORK_NAME,
|
||||
SYSTEM_SYMBOLS,
|
||||
collect_variant_stubs,
|
||||
file_sha256,
|
||||
resolve_app_repo,
|
||||
resolve_defender_dir,
|
||||
)
|
||||
from verify_baseline import inspect_binary, scan # noqa: E402
|
||||
import ig_toolchain_resolver # noqa: E402
|
||||
|
||||
APPSTORE_PLIST_KEYS = (
|
||||
'DTCompiler', 'DTPlatformBuild', 'DTPlatformName', 'DTPlatformVersion',
|
||||
'DTSDKBuild', 'DTSDKName', 'DTXcode', 'DTXcodeBuild', 'UIDeviceFamily',
|
||||
)
|
||||
DYLIB_LOAD_CMDS = {0x0c, 0x18, 0x1f, 0x80000018, 0x8000001f}
|
||||
|
||||
|
||||
def run_cmd(*args, env=None, cwd=None):
|
||||
return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True)
|
||||
|
||||
|
||||
def macho_load_dylibs(raw):
|
||||
m = Macho(raw)
|
||||
libs = []
|
||||
for cmd, cmdsize, off in m.cmds:
|
||||
if cmd in DYLIB_LOAD_CMDS and cmdsize >= 24:
|
||||
name_off, = struct.unpack_from('<I', m.d, off + 8)
|
||||
if 0 < name_off < cmdsize:
|
||||
libs.append(m.d[off + name_off:off + cmdsize].split(b'\0', 1)[0].decode(errors='replace'))
|
||||
return libs
|
||||
|
||||
|
||||
def thin_if_fat(binary_path):
|
||||
raw = binary_path.read_bytes()
|
||||
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
|
||||
with tempfile.NamedTemporaryFile(dir=binary_path.parent, delete=False) as tf:
|
||||
tmp = Path(tf.name)
|
||||
try:
|
||||
subprocess.run(['xcrun', 'lipo', str(binary_path), '-thin', 'arm64', '-output', str(tmp)], check=True)
|
||||
shutil.copymode(binary_path, tmp)
|
||||
tmp.replace(binary_path)
|
||||
return True
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
return False
|
||||
|
||||
|
||||
def codesign_framework(fw_dir, preserve_metadata=False):
|
||||
if os.environ.get('CODE_SIGNING_ALLOWED') == 'NO' or os.environ.get('CODE_SIGNING_REQUIRED') == 'NO':
|
||||
return 'skipped_disabled'
|
||||
identity = os.environ.get('EXPANDED_CODE_SIGN_IDENTITY', '').strip()
|
||||
if not identity:
|
||||
if os.environ.get('AD_HOC_CODE_SIGNING_ALLOWED') == 'YES':
|
||||
identity = '-'
|
||||
else:
|
||||
return 'skipped_no_identity'
|
||||
cmd = ['codesign', '--force', '--sign', identity]
|
||||
if preserve_metadata:
|
||||
cmd.append('--preserve-metadata=identifier,entitlements')
|
||||
if identity == '-':
|
||||
cmd.append('--timestamp=none')
|
||||
cmd.append(str(fw_dir))
|
||||
subprocess.run(cmd, check=True)
|
||||
return f'signed:{identity}'
|
||||
|
||||
|
||||
def build_archive_guard(defender_dir, fw_dir, app_plist_path=None, dsym_folder=None, debug_info_format='', app_repo=None):
|
||||
if fw_dir.exists():
|
||||
shutil.rmtree(fw_dir)
|
||||
fw_dir.mkdir(parents=True)
|
||||
binary = fw_dir / GUARD_FRAMEWORK_NAME
|
||||
sources = [
|
||||
defender_dir / 'dispatch/IGArchiveGuard.c',
|
||||
defender_dir / 'resolve/IGResolve.c',
|
||||
defender_dir / 'anti_hook/IGAntiHook.c',
|
||||
]
|
||||
dsym_generated = None
|
||||
obf_mode = os.environ.get('IG_OBF_MODE', 'full')
|
||||
all_off = os.environ.get('IG_ALL_GUARD_OFF', '0') == '1'
|
||||
require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1'
|
||||
opt_path = None
|
||||
if not all_off and obf_mode != 'off':
|
||||
try:
|
||||
tc = ig_toolchain_resolver.resolve_opt(require_obf=require_obf)
|
||||
opt_path = tc.get('opt_path')
|
||||
except Exception:
|
||||
if require_obf:
|
||||
raise
|
||||
opt_path = None
|
||||
|
||||
real_clang = ig_toolchain_resolver.detect_stock_tool('clang')
|
||||
sdk_path = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
|
||||
def_roots = list(dict.fromkeys([str(defender_dir), str(defender_dir.resolve())]))
|
||||
prefix_flags = []
|
||||
for root in def_roots:
|
||||
prefix_flags.extend([f'-ffile-prefix-map={root}=.', f'-fmacro-prefix-map={root}=.', f'-fdebug-prefix-map={root}=.'])
|
||||
|
||||
common_cflags = [
|
||||
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path,
|
||||
'-O2', '-Wall', '-Wextra', '-Werror', '-fvisibility=hidden',
|
||||
'-DIG_ARCHIVE_INTERNAL_RESOLVE=1',
|
||||
*prefix_flags,
|
||||
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
|
||||
]
|
||||
opt_used = False
|
||||
with tempfile.TemporaryDirectory(prefix='ig-guard-objs-') as tmp_obj_dir:
|
||||
obj_dir = Path(tmp_obj_dir)
|
||||
policy_path = obj_dir / 'guard_policy.json'
|
||||
if opt_path:
|
||||
guard_policy = {
|
||||
'schema_version': 3,
|
||||
'flatten_topology': 'sparse_switch',
|
||||
'flatten_bogus_blocks': 2,
|
||||
'flatten_split_linear_blocks': True,
|
||||
'opaque_const_max_per_fn': 48,
|
||||
'arithmetic_rounds': 1,
|
||||
'arithmetic_max_per_fn': 96,
|
||||
'string_encrypt_stack_max_len': 128,
|
||||
'indirect_call_dual_table': True,
|
||||
'exempt_path_substrings': [],
|
||||
'exempt_function_prefixes': [
|
||||
'__ig_', 'ig_archive_warmup', 'ig_anti_hook_warmup',
|
||||
'rd_a0', 'rd_f', 'rd_a1', 'rd_a2', 'rd_a3', 'rd_a4',
|
||||
'rd_u00', 'rd_o', 'rdo', 'rd_r', 'rdr', 'rd_w0', 'rd_w',
|
||||
'rd_c0', 'rd_c', 'rd_p00', 'rd_p0', 'rd_e', 'rd_k',
|
||||
'rd_l00', 'rd_s0', 'rd_s', 'llvm.',
|
||||
],
|
||||
'scrub_path_substrings': list(dict.fromkeys([
|
||||
*def_roots,
|
||||
'/tmp/ig-',
|
||||
f'{Path.home()}/',
|
||||
*([str(app_repo)] if app_repo else []),
|
||||
])),
|
||||
'string_encrypt_targets': [
|
||||
{'id': 'rdcoreio_guard_str', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_str', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_str', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'indirect_call_same_image_prefixes': [
|
||||
'ig_', 'rd_io_', 'checked', 'prepare', 'validate',
|
||||
'initialize', 'locate_bindings', 'check_bindings',
|
||||
],
|
||||
'indirect_call_targets': [
|
||||
{'id': 'rdcoreio_guard_icall', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_icall', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_icall', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'flatten_targets': [
|
||||
{'id': 'rdcoreio_guard_flat', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_flat', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_flat', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'opaque_const_targets': [
|
||||
{'id': 'rdcoreio_guard_const', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_const', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_const', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'arithmetic_targets': [
|
||||
{'id': 'rdcoreio_guard_arith', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_arith', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_arith', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'indirect_branch_targets': [
|
||||
{'id': 'rdcoreio_guard_ibr', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_ibr', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_ibr', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'string_encrypt_stack_targets': [
|
||||
{'id': 'rdcoreio_guard_sstr', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_sstr', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_sstr', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
'anti_hooking_targets': [
|
||||
{'id': 'rdcoreio_guard_antihook', 'path_contains': 'IGArchiveGuard.c'},
|
||||
{'id': 'rdcoreio_resolve_antihook', 'path_contains': 'IGResolve.c'},
|
||||
{'id': 'rdcoreio_antihook_antihook', 'path_contains': 'IGAntiHook.c'},
|
||||
],
|
||||
}
|
||||
policy_path.write_text(json.dumps(guard_policy, indent=2) + '\n', encoding='utf-8')
|
||||
objects = []
|
||||
seed = os.environ.get('IG_RELEASE_SEED', 'rdcoreio_seed_v1')
|
||||
for src in sources:
|
||||
obj = obj_dir / f'{src.stem}.o'
|
||||
if opt_path:
|
||||
bc_path = obj_dir / f'{src.stem}.bc'
|
||||
obf_bc = obj_dir / f'{src.stem}.obf.bc'
|
||||
audit_p = obj_dir / f'{src.stem}.audit.json'
|
||||
subprocess.run([real_clang, '-g', *common_cflags, '-emit-llvm', '-c', str(src), '-o', str(bc_path)], check=True)
|
||||
subprocess.run([
|
||||
opt_path, '-passes=ig-obfuscate',
|
||||
f'--ig-policy={policy_path}',
|
||||
f'--ig-mode={obf_mode}',
|
||||
'--ig-pass-filter=all',
|
||||
f'--ig-seed={seed}',
|
||||
f'--ig-source-path={src}',
|
||||
f'--ig-audit-out={audit_p}',
|
||||
str(bc_path), '-o', str(obf_bc),
|
||||
], check=True)
|
||||
subprocess.run([
|
||||
real_clang, '-g', '-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path,
|
||||
'-O2', '-fvisibility=hidden', '-Xclang', '-disable-llvm-passes',
|
||||
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj),
|
||||
], check=True)
|
||||
opt_used = True
|
||||
else:
|
||||
subprocess.run([real_clang, '-g', *common_cflags, '-c', str(src), '-o', str(obj)], check=True)
|
||||
objects.append(str(obj))
|
||||
|
||||
subprocess.run([
|
||||
real_clang,
|
||||
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-isysroot', sdk_path, '-dynamiclib',
|
||||
*objects,
|
||||
'-Wl,-install_name,' + DEPENDENCY,
|
||||
'-o', str(binary),
|
||||
], check=True)
|
||||
|
||||
if dsym_folder and debug_info_format == 'dwarf-with-dsym':
|
||||
dsym_dir = Path(dsym_folder)
|
||||
dsym_dir.mkdir(parents=True, exist_ok=True)
|
||||
dsym_out = dsym_dir / f'{GUARD_FRAMEWORK_NAME}.framework.dSYM'
|
||||
if dsym_out.exists():
|
||||
shutil.rmtree(dsym_out)
|
||||
subprocess.run(['xcrun', 'dsymutil', str(binary), '-o', str(dsym_out)], check=True)
|
||||
dsym_generated = str(dsym_out)
|
||||
|
||||
subprocess.run(['xcrun', 'strip', '-x', str(binary)], check=True)
|
||||
|
||||
plist = {
|
||||
'CFBundleExecutable': GUARD_FRAMEWORK_NAME,
|
||||
'CFBundleIdentifier': GUARD_BUNDLE_ID,
|
||||
'CFBundleInfoDictionaryVersion': '6.0',
|
||||
'CFBundleName': GUARD_FRAMEWORK_NAME,
|
||||
'CFBundlePackageType': 'FMWK',
|
||||
'CFBundleShortVersionString': '1.0',
|
||||
'CFBundleSupportedPlatforms': ['iPhoneOS'],
|
||||
'CFBundleVersion': '1',
|
||||
'MinimumOSVersion': '15.0',
|
||||
}
|
||||
if app_plist_path and Path(app_plist_path).is_file():
|
||||
app_plist = plistlib.loads(Path(app_plist_path).read_bytes())
|
||||
for key in APPSTORE_PLIST_KEYS:
|
||||
if key in app_plist:
|
||||
plist[key] = app_plist[key]
|
||||
if 'MinimumOSVersion' in app_plist:
|
||||
plist['MinimumOSVersion'] = app_plist['MinimumOSVersion']
|
||||
with (fw_dir / 'Info.plist').open('wb') as stream:
|
||||
plistlib.dump(plist, stream)
|
||||
|
||||
exports_out = run_cmd('xcrun', 'nm', '-gU', binary)
|
||||
exported = {line.split()[-1] for line in exports_out.splitlines() if line.split()}
|
||||
missing = EXPECTED_ARCHIVE_EXPORTS - exported
|
||||
if missing:
|
||||
raise ValueError(f'{GUARD_FRAMEWORK_NAME} missing expected exports: {sorted(missing)}')
|
||||
leaked_ig = sorted(s for s in exported if s.startswith('_ig_'))
|
||||
if leaked_ig:
|
||||
raise ValueError(f'{GUARD_FRAMEWORK_NAME} leaked _ig_* exports: {leaked_ig}')
|
||||
|
||||
undef_out = run_cmd('xcrun', 'nm', '-u', binary)
|
||||
undef = {line.split()[-1] for line in undef_out.splitlines() if line.split()}
|
||||
forbidden_undef = undef & FORBIDDEN_SYMBOLS
|
||||
if forbidden_undef:
|
||||
raise ValueError(f'{GUARD_FRAMEWORK_NAME} has forbidden undefined imports: {sorted(forbidden_undef)}')
|
||||
|
||||
info, sites = inspect_binary(binary)
|
||||
if sites:
|
||||
raise ValueError(f'{GUARD_FRAMEWORK_NAME} has direct target calls: {sites}')
|
||||
sign_status = codesign_framework(fw_dir, preserve_metadata=False)
|
||||
return dict(
|
||||
sha256=file_sha256(binary),
|
||||
exported_count=len(exported),
|
||||
obfuscated=opt_used,
|
||||
dsym=dsym_generated,
|
||||
sign_status=sign_status,
|
||||
inspect=info,
|
||||
)
|
||||
|
||||
|
||||
def process_framework(fw_dir, orig_backup_dir=None):
|
||||
name = fw_dir.stem
|
||||
binary = fw_dir / name
|
||||
if not binary.is_file():
|
||||
raise FileNotFoundError(binary)
|
||||
|
||||
raw_initial = binary.read_bytes()
|
||||
slices_initial = arm64_slices(raw_initial)
|
||||
initial_load_dylibs = macho_load_dylibs(raw_initial) if (len(slices_initial) == 1 and slices_initial[0][0] == 0) else []
|
||||
if DEPENDENCY not in initial_load_dylibs and orig_backup_dir is not None:
|
||||
orig_backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup_path = orig_backup_dir / f'{name}.orig'
|
||||
shutil.copy2(binary, backup_path)
|
||||
|
||||
if len(slices_initial) == 1 and slices_initial[0][0] == 0:
|
||||
if DEPENDENCY in initial_load_dylibs:
|
||||
info, sites = inspect_binary(binary)
|
||||
variants = collect_variant_stubs(binary)
|
||||
if not sites and not variants:
|
||||
return dict(
|
||||
framework=name,
|
||||
mode='already_guarded',
|
||||
modified=False,
|
||||
thinned=False,
|
||||
before_total=0,
|
||||
after_total=0,
|
||||
symbols_redirected=0,
|
||||
sign_status='preserved',
|
||||
)
|
||||
|
||||
thinned = thin_if_fat(binary)
|
||||
raw = binary.read_bytes()
|
||||
slices = arm64_slices(raw)
|
||||
if len(slices) != 1 or slices[0][0] != 0:
|
||||
raise ValueError(f'{name}: expected single thin arm64 Mach-O')
|
||||
m = Macho(raw)
|
||||
has_chained = any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds)
|
||||
has_dyld_info = any(c in (0x22, 0x80000022) for c, _, _ in m.cmds)
|
||||
|
||||
include_stdio_rw = (name == 'SSZipArchive')
|
||||
if has_chained:
|
||||
mapping = detect_chained_target_mapping(raw, include_stdio_rw=include_stdio_rw)
|
||||
mode = 'chained'
|
||||
elif has_dyld_info:
|
||||
mapping = detect_legacy_target_mapping(raw)
|
||||
mode = 'legacy_dyld_info'
|
||||
else:
|
||||
mapping = {}
|
||||
mode = 'none'
|
||||
|
||||
before_info, _ = inspect_binary(binary)
|
||||
before_total = sum(s['total'] for s in before_info['slices'])
|
||||
|
||||
if mapping:
|
||||
in_sha = hashlib.sha256(raw).hexdigest()
|
||||
if mode == 'chained':
|
||||
out_bytes, report = rewrite_chained(raw, in_sha, mapping)
|
||||
else:
|
||||
out_bytes, report = rewrite_legacy(raw, in_sha, mapping)
|
||||
binary.write_bytes(out_bytes)
|
||||
after_info, after_sites = inspect_binary(binary)
|
||||
if after_sites:
|
||||
raise ValueError(f'{name}: remaining direct calls after rewrite: {after_sites}')
|
||||
variants = collect_variant_stubs(binary)
|
||||
if variants:
|
||||
raise ValueError(f'{name}: remaining Darwin-variant stubs after rewrite: {variants}')
|
||||
codesig = fw_dir / '_CodeSignature'
|
||||
if codesig.exists():
|
||||
shutil.rmtree(codesig)
|
||||
sign_status = codesign_framework(fw_dir, preserve_metadata=True)
|
||||
return dict(
|
||||
framework=name,
|
||||
mode=mode,
|
||||
modified=True,
|
||||
thinned=thinned,
|
||||
before_total=before_total,
|
||||
after_total=sum(s['total'] for s in after_info['slices']),
|
||||
symbols_redirected=len(mapping),
|
||||
mapping=mapping,
|
||||
output_sha256=report['output_sha256'],
|
||||
sign_status=sign_status,
|
||||
)
|
||||
|
||||
if before_total > 0:
|
||||
raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}')
|
||||
|
||||
sign_status = 'preserved'
|
||||
if thinned:
|
||||
codesig = fw_dir / '_CodeSignature'
|
||||
if codesig.exists():
|
||||
shutil.rmtree(codesig)
|
||||
sign_status = codesign_framework(fw_dir, preserve_metadata=True)
|
||||
return dict(
|
||||
framework=name,
|
||||
mode='clean_no_change' if not thinned else 'thinned_clean',
|
||||
modified=thinned,
|
||||
thinned=thinned,
|
||||
before_total=0,
|
||||
after_total=0,
|
||||
symbols_redirected=0,
|
||||
sign_status=sign_status,
|
||||
)
|
||||
|
||||
|
||||
def run_phase(app_dir, main_bin, audit_dir, app_repo, defender_dir, dsym_folder=None, debug_info_format=''):
|
||||
frameworks_dir = app_dir / 'Frameworks'
|
||||
frameworks_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
guard_report = build_archive_guard(
|
||||
defender_dir,
|
||||
frameworks_dir / f'{GUARD_FRAMEWORK_NAME}.framework',
|
||||
app_plist_path=app_dir / 'Info.plist',
|
||||
dsym_folder=dsym_folder,
|
||||
debug_info_format=debug_info_format,
|
||||
app_repo=app_repo,
|
||||
)
|
||||
|
||||
orig_backup_dir = audit_dir / 'orig_frameworks'
|
||||
fw_reports = []
|
||||
for fw_dir in sorted(frameworks_dir.glob('*.framework')):
|
||||
if fw_dir.name == f'{GUARD_FRAMEWORK_NAME}.framework':
|
||||
continue
|
||||
fw_reports.append(process_framework(fw_dir, orig_backup_dir=orig_backup_dir))
|
||||
|
||||
# Incremental builds may already have a stale RDKnownImages.plist before Generate Image Whitelist runs.
|
||||
whitelist_plist = app_dir / 'RDKnownImages.plist'
|
||||
if whitelist_plist.exists():
|
||||
wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
|
||||
if wl_script.is_file():
|
||||
env = dict(os.environ)
|
||||
env['TARGET_BUILD_DIR'] = str(app_dir.parent)
|
||||
env['WRAPPER_NAME'] = app_dir.name
|
||||
env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent)))
|
||||
subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True)
|
||||
|
||||
audit_dir.mkdir(parents=True, exist_ok=True)
|
||||
(audit_dir / 'route2-frameworks.json').write_text(json.dumps(fw_reports, indent=2) + '\n')
|
||||
|
||||
binaries, callsite_total = scan(app_dir, audit_dir, 'route2')
|
||||
combined_counts = {}
|
||||
for info in binaries.values():
|
||||
for sl in info['slices']:
|
||||
for sym, cnt in sl['counts'].items():
|
||||
combined_counts[sym] = combined_counts.get(sym, 0) + cnt
|
||||
|
||||
external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS)
|
||||
system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS)
|
||||
if external_call_total != 0 or system_call_total != 0 or callsite_total != 0:
|
||||
raise RuntimeError(
|
||||
f'[IGRoute2] Non-zero residual callsites across {app_dir.name}: '
|
||||
f'external={external_call_total}, system={system_call_total}, total={callsite_total}, counts={combined_counts}'
|
||||
)
|
||||
|
||||
variant_stubs = []
|
||||
for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))):
|
||||
found = collect_variant_stubs(mpath)
|
||||
if found:
|
||||
variant_stubs.append((str(mpath.relative_to(app_dir)), found))
|
||||
if variant_stubs:
|
||||
raise RuntimeError(f'[IGRoute2] Found Darwin-variant stubs in {app_dir.name}: {variant_stubs}')
|
||||
|
||||
main_undef_out = run_cmd('xcrun', 'nm', '-u', main_bin)
|
||||
main_undef = {line.split()[-1] for line in main_undef_out.splitlines() if line.split()}
|
||||
forbidden_main_undef = sorted(main_undef & FORBIDDEN_SYMBOLS)
|
||||
forbidden_variant_undef = sorted(u for u in main_undef if any(u.startswith(f + '$') for f in FORBIDDEN_SYMBOLS))
|
||||
if forbidden_variant_undef:
|
||||
raise RuntimeError(
|
||||
f'[IGRoute2] Main binary {main_bin.name} still has Darwin-variant undefined imports: '
|
||||
f'{forbidden_variant_undef}'
|
||||
)
|
||||
|
||||
summary = dict(
|
||||
app=app_dir.name,
|
||||
binaries=len(binaries),
|
||||
external_call_total=external_call_total,
|
||||
system_call_total=system_call_total,
|
||||
direct_calls=combined_counts,
|
||||
main_binary_forbidden_undef=forbidden_main_undef,
|
||||
ig_archive_guard=guard_report,
|
||||
frameworks_total=len(fw_reports),
|
||||
frameworks_rewritten=sum(1 for r in fw_reports if r['symbols_redirected'] > 0),
|
||||
frameworks_already_guarded=sum(1 for r in fw_reports if r['mode'] == 'already_guarded'),
|
||||
frameworks_thinned=sum(1 for r in fw_reports if r['thinned']),
|
||||
)
|
||||
(audit_dir / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
|
||||
return summary
|
||||
|
||||
|
||||
def restore_route2_off(app_dir, main_bin, audit_dir, app_repo, dsym_folder=None):
|
||||
"""Remove RDCoreIO.framework (and legacy IGArchiveGuard.framework) & restore pre-Route2 backups."""
|
||||
frameworks_dir = app_dir / 'Frameworks'
|
||||
removed_guard = False
|
||||
for fw_name in (GUARD_FRAMEWORK_NAME, 'IGArchiveGuard'):
|
||||
guard_fw = frameworks_dir / f'{fw_name}.framework'
|
||||
if guard_fw.exists():
|
||||
shutil.rmtree(guard_fw)
|
||||
removed_guard = True
|
||||
if dsym_folder:
|
||||
guard_dsym = Path(dsym_folder) / f'{fw_name}.framework.dSYM'
|
||||
if guard_dsym.exists():
|
||||
shutil.rmtree(guard_dsym)
|
||||
|
||||
restored = []
|
||||
orig_backup_dir = audit_dir / 'orig_frameworks'
|
||||
if frameworks_dir.is_dir() and orig_backup_dir.is_dir():
|
||||
for fw_dir in sorted(frameworks_dir.glob('*.framework')):
|
||||
name = fw_dir.stem
|
||||
binary = fw_dir / name
|
||||
backup = orig_backup_dir / f'{name}.orig'
|
||||
if binary.is_file() and backup.is_file():
|
||||
if DEPENDENCY in macho_load_dylibs(binary.read_bytes()):
|
||||
shutil.copy2(backup, binary)
|
||||
codesig = fw_dir / '_CodeSignature'
|
||||
if codesig.exists():
|
||||
shutil.rmtree(codesig)
|
||||
codesign_framework(fw_dir, preserve_metadata=True)
|
||||
restored.append(name)
|
||||
|
||||
whitelist_plist = app_dir / 'RDKnownImages.plist'
|
||||
if (removed_guard or restored) and whitelist_plist.exists():
|
||||
wl_script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
|
||||
if wl_script.is_file():
|
||||
env = dict(os.environ)
|
||||
env['TARGET_BUILD_DIR'] = str(app_dir.parent)
|
||||
env['WRAPPER_NAME'] = app_dir.name
|
||||
env.setdefault('EXECUTABLE_PATH', str(main_bin.relative_to(app_dir.parent)))
|
||||
subprocess.run([sys.executable, str(wl_script)], env=env, cwd=app_repo, check=True)
|
||||
return removed_guard, restored
|
||||
|
||||
|
||||
def main():
|
||||
off_reason = None
|
||||
if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1':
|
||||
off_reason = 'IG_DISABLE_ROUTE2_ARCHIVE=1'
|
||||
elif os.environ.get('IG_ALL_GUARD_OFF') == '1':
|
||||
off_reason = 'IG_ALL_GUARD_OFF=1'
|
||||
elif os.environ.get('IG_ROUTE2_MODE') == 'off':
|
||||
off_reason = 'IG_ROUTE2_MODE=off'
|
||||
|
||||
config = os.environ.get('CONFIGURATION', '')
|
||||
platform = os.environ.get('PLATFORM_NAME', '')
|
||||
if config != 'Release' or platform != 'iphoneos':
|
||||
print(f'[IGRoute2] frameworks phase skipped: CONFIGURATION={config} PLATFORM_NAME={platform}')
|
||||
return 0
|
||||
|
||||
target_build_dir = Path(os.environ['TARGET_BUILD_DIR'])
|
||||
wrapper_name = os.environ['WRAPPER_NAME']
|
||||
app_dir = target_build_dir / wrapper_name
|
||||
exec_rel = os.environ.get('EXECUTABLE_PATH') or f'{wrapper_name}/{Path(wrapper_name).stem}'
|
||||
main_bin = target_build_dir / exec_rel
|
||||
target_temp_dir = Path(os.environ.get('TARGET_TEMP_DIR') or str(target_build_dir))
|
||||
audit_dir = target_temp_dir / 'ig-route2-audit'
|
||||
app_repo = resolve_app_repo(TOOLCHAIN_ROOT)
|
||||
|
||||
if off_reason:
|
||||
removed_guard, restored = restore_route2_off(
|
||||
app_dir, main_bin, audit_dir, app_repo, dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH')
|
||||
)
|
||||
print(
|
||||
f'[IGRoute2] frameworks phase off ({off_reason}): '
|
||||
f'removed_guard={removed_guard}, restored={len(restored)}'
|
||||
)
|
||||
return 0
|
||||
|
||||
defender_dir = resolve_defender_dir(TOOLCHAIN_ROOT, app_repo)
|
||||
summary = run_phase(
|
||||
app_dir=app_dir,
|
||||
main_bin=main_bin,
|
||||
audit_dir=audit_dir,
|
||||
app_repo=app_repo,
|
||||
defender_dir=defender_dir,
|
||||
dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH'),
|
||||
debug_info_format=os.environ.get('DEBUG_INFORMATION_FORMAT', ''),
|
||||
)
|
||||
print(
|
||||
f'[IGRoute2] frameworks audit OK for {app_dir.name}: '
|
||||
f'binaries={summary["binaries"]}, rewritten={summary["frameworks_rewritten"]}, '
|
||||
f'already_guarded={summary["frameworks_already_guarded"]}, external=0, system=0'
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+1452
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
"""Shared constants and Mach-O helpers for Route 2 Xcode Archive integration."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from batch import arm64_slices, Slice
|
||||
|
||||
EXTERNAL_SYMBOLS = {'_fopen', '_dlopen', '_dlsym'}
|
||||
SYSTEM_SYMBOLS = {'_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid'}
|
||||
FORBIDDEN_SYMBOLS = EXTERNAL_SYMBOLS | SYSTEM_SYMBOLS
|
||||
|
||||
EXPECTED_DISPATCH_SYMBOLS = {
|
||||
'_IG_dispatch_fopen', '_IG_dispatch_dlopen', '_IG_dispatch_dlsym',
|
||||
'_IG_dispatch_write', '_IG_dispatch_read', '_IG_dispatch_open',
|
||||
'_IG_dispatch_close', '_IG_dispatch_exit', '_IG_dispatch_fork',
|
||||
'_IG_dispatch_unlink', '_IG_dispatch_getpid',
|
||||
}
|
||||
|
||||
GUARD_FRAMEWORK_NAME = 'RDCoreIO'
|
||||
GUARD_BUNDLE_ID = 'cn.touchv.readoor.coreio'
|
||||
|
||||
EXPECTED_ARCHIVE_EXPORTS = {
|
||||
'_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4',
|
||||
'_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w',
|
||||
'_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k',
|
||||
'_rd_l00', '_rd_s0', '_rd_s',
|
||||
'_rd_io_cfg', '_rd_io_chk', '_rd_io_ev',
|
||||
}
|
||||
|
||||
|
||||
def file_sha256(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def resolve_app_repo(toolchain_root):
|
||||
"""Resolve active readoor repository root, preferring SRCROOT for isolated build snapshots."""
|
||||
candidates = []
|
||||
srcroot = os.environ.get('SRCROOT')
|
||||
if srcroot:
|
||||
candidates.append(Path(srcroot).resolve())
|
||||
candidates.extend([
|
||||
(toolchain_root / 'readoor-test').resolve(),
|
||||
toolchain_root.parent / 'readoor-test',
|
||||
])
|
||||
for candidate in candidates:
|
||||
if (candidate / 'readoor.xcodeproj').exists():
|
||||
return candidate
|
||||
raise FileNotFoundError(f'Unable to resolve readoor-test repository root from {toolchain_root}')
|
||||
|
||||
|
||||
def resolve_defender_dir(toolchain_root, app_repo):
|
||||
in_toolchain = (toolchain_root / 'defender').resolve()
|
||||
if (in_toolchain / 'dispatch/IGArchiveGuard.c').is_file():
|
||||
return in_toolchain
|
||||
in_repo = app_repo / 'readoor/3.0/Base/Security/IGDefender'
|
||||
if (in_repo / 'dispatch/IGArchiveGuard.c').is_file():
|
||||
return in_repo
|
||||
raise FileNotFoundError(f'Unable to resolve IGDefender directory under {toolchain_root} or {app_repo}')
|
||||
|
||||
|
||||
def collect_variant_stubs(binary_path):
|
||||
"""Return any Darwin-suffixed stub imports (e.g. _fopen$DARWIN_EXTSN) for forbidden targets."""
|
||||
data = Path(binary_path).read_bytes()
|
||||
found = set()
|
||||
for off, _ in arm64_slices(data):
|
||||
sl = Slice(data, off)
|
||||
if not (sl.stubs and sl.symtab and sl.dysym):
|
||||
continue
|
||||
symoff, _, stroff, _ = sl.symtab
|
||||
indoff = sl.dysym[12]
|
||||
_, ssize, _, sr1, sr2 = sl.stubs
|
||||
for idx_pos in range(ssize // sr2):
|
||||
symi, = struct.unpack_from('<I', data, off + indoff + (sr1 + idx_pos) * 4)
|
||||
strx, = struct.unpack_from('<I', data, off + symoff + symi * 16)
|
||||
sname = data[off + stroff + strx:data.index(b'\0', off + stroff + strx)].decode(errors='replace')
|
||||
if sname == '_fopen$DARWIN_EXTSN' or any(sname.startswith(f + '$') for f in FORBIDDEN_SYMBOLS):
|
||||
found.add(sname)
|
||||
return sorted(found)
|
||||
Reference in New Issue
Block a user