1120 lines
51 KiB
Python
1120 lines
51 KiB
Python
#!/usr/bin/env python3
|
|
"""Build a standalone full L1+L2+L3 obfuscated IPA artifact in an isolated temp workspace."""
|
|
import argparse
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
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
|
|
import zipfile
|
|
|
|
ROOT = Path('/Users/shenlei/Work/ReadBook/iOSGuard')
|
|
APP_REPO = ROOT / 'readoor-test'
|
|
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
|
|
TOOLS_MACHO = ROOT / 'tools' / 'macho_guard'
|
|
|
|
sys.path.insert(0, str(TOOLS_LLVM_OBF))
|
|
sys.path.insert(0, str(TOOLS_MACHO))
|
|
|
|
import ig_toolchain_resolver # noqa: E402
|
|
import run_m3_full_regression as m3 # noqa: E402
|
|
import verify_macho_indirect_branches # noqa: E402
|
|
import verify_macho_indirect_calls # noqa: E402
|
|
import verify_macho_star_cfg # noqa: E402
|
|
from verify_baseline import scan as scan_route2 # noqa: E402
|
|
|
|
WORK_ROOT = Path('/tmp/ig-ipa-work')
|
|
CACHE_ROOT = Path('/tmp/ig-ipa-cache')
|
|
DEFAULT_PROFILE = m3.DEFAULT_PROFILE
|
|
DEFAULT_IDENTITY = m3.DEFAULT_IDENTITY
|
|
|
|
_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'}
|
|
|
|
|
|
def _inspect_anti_hook_range(main_bin: Path, start_addr: int, end_addr: int) -> dict:
|
|
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: Path, dwarf_bin: Path, obf_audit: dict) -> dict:
|
|
"""Disassemble offset 0..8 of audited anti_hook_functions and verify mov x16/x17 prologues."""
|
|
ranges_map = verify_macho_star_cfg.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('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: dict[tuple[int, int], dict] = {}
|
|
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 AssertionError(
|
|
f'[AntiHookGate] {len(failed)} function(s) failed offset-0 x16/x17 prologue check:\n{preview}'
|
|
)
|
|
return summary
|
|
|
|
|
|
def _create_l1_snapshot(snapshot_src: Path, scheme: str, timestamp: str, seed: str, log_path: Path) -> dict:
|
|
"""Rsync readoor-test into isolated snapshot and apply L1 symbol/method obfuscation."""
|
|
m3.check_disk_budget()
|
|
if snapshot_src.exists():
|
|
shutil.rmtree(snapshot_src)
|
|
snapshot_src.parent.mkdir(parents=True, exist_ok=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 = subprocess.run(
|
|
['bash', str(snapshot_src / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh')],
|
|
cwd=snapshot_src, capture_output=True, text=True,
|
|
)
|
|
if pre.returncode != 0:
|
|
raise RuntimeError(f'Pre-L1 self-check failed:\n{pre.stdout}\n{pre.stderr}')
|
|
|
|
t0 = time.monotonic()
|
|
l1_res = subprocess.run([
|
|
'python3',
|
|
str(snapshot_src / 'AutoPacking/obfuscation/obfuscate_symbols.py'),
|
|
'--archive-mode',
|
|
'--target-name', scheme,
|
|
'--timestamp', timestamp,
|
|
'--salt', seed,
|
|
], cwd=snapshot_src, capture_output=True, text=True)
|
|
l1_elapsed = round(time.monotonic() - t0, 2)
|
|
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
log_path.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_p = snapshot_src / f'obfuscation_maps/symbol_map_{scheme}_{timestamp}.json'
|
|
meth_map_p = snapshot_src / f'obfuscation_maps/method_map_{scheme}_{timestamp}.json'
|
|
sym_payload = json.loads(sym_map_p.read_text(encoding='utf-8'))
|
|
meth_payload = json.loads(meth_map_p.read_text(encoding='utf-8'))
|
|
sym_mappings = sym_payload.get('mappings') or {}
|
|
meth_mappings = meth_payload.get('mappings') or {}
|
|
|
|
sample_types = {}
|
|
for cls_name in ('RDLoginView', 'RDSDAuthV32Signer', 'RDInjectionDetector', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', 'RDIAPHandler'):
|
|
val = sym_mappings.get(cls_name)
|
|
obf = val.get('obfuscated') if isinstance(val, dict) else val
|
|
if obf:
|
|
sample_types[cls_name] = obf
|
|
|
|
sample_methods = {}
|
|
for meth_name in ('buildSignatureHeaders(businessBody:headerFields:)', 'hasSuspiciousDyldInsertLibraries', 'logDiag'):
|
|
val = meth_mappings.get(meth_name)
|
|
obf = val.get('obfuscated') if isinstance(val, dict) else val
|
|
if obf:
|
|
sample_methods[meth_name] = obf
|
|
|
|
return {
|
|
'elapsed_s': l1_elapsed,
|
|
'symbol_map_path': sym_map_p,
|
|
'method_map_path': meth_map_p,
|
|
'type_mappings_count': len(sym_mappings),
|
|
'method_mappings_count': len(meth_mappings),
|
|
'sample_type_mappings': sample_types,
|
|
'sample_method_mappings': sample_methods,
|
|
}
|
|
|
|
|
|
def _inject_pods_prefix_map(snapshot_src: Path) -> int:
|
|
"""Inject source-path scrubbing flags into non-aggregate Pod release xcconfigs in-place."""
|
|
support_dir = snapshot_src / 'Pods/Target Support Files'
|
|
if not support_dir.is_dir():
|
|
return 0
|
|
roots = list(dict.fromkeys([str(snapshot_src), str(snapshot_src.resolve())]))
|
|
c_tokens: list[str] = []
|
|
swift_tokens: list[str] = []
|
|
for root in roots:
|
|
c_tokens.extend([
|
|
f'-ffile-prefix-map={root}=.',
|
|
f'-fmacro-prefix-map={root}=.',
|
|
f'-fdebug-prefix-map={root}=.',
|
|
])
|
|
swift_tokens.append(f'-file-prefix-map {root}=.')
|
|
swift_tokens.append('-enable-upcoming-feature ConciseMagicFile')
|
|
|
|
c_suffix = ' '.join(c_tokens)
|
|
swift_suffix = ' '.join(swift_tokens)
|
|
key_re = re.compile(r'^(\s*)(OTHER_CFLAGS|OTHER_CPLUSPLUSFLAGS|OTHER_SWIFT_FLAGS)(\s*=.*)$')
|
|
updated = 0
|
|
for cfg in sorted(support_dir.glob('*/*.release.xcconfig')):
|
|
if cfg.parent.name.startswith('Pods-'):
|
|
continue
|
|
lines = cfg.read_text(encoding='utf-8').splitlines()
|
|
seen_keys: set[str] = set()
|
|
new_lines: list[str] = []
|
|
for ln in lines:
|
|
m = key_re.match(ln)
|
|
if m:
|
|
indent, key, rest = m.groups()
|
|
seen_keys.add(key)
|
|
extra = swift_suffix if key == 'OTHER_SWIFT_FLAGS' else c_suffix
|
|
new_lines.append(f'{indent}{key}{rest} {extra}')
|
|
else:
|
|
new_lines.append(ln)
|
|
if 'OTHER_CFLAGS' not in seen_keys:
|
|
new_lines.append(f'OTHER_CFLAGS = $(inherited) {c_suffix}')
|
|
if 'OTHER_SWIFT_FLAGS' not in seen_keys:
|
|
new_lines.append(f'OTHER_SWIFT_FLAGS = $(inherited) {swift_suffix}')
|
|
cfg.write_text('\n'.join(new_lines) + '\n', encoding='utf-8')
|
|
updated += 1
|
|
return updated
|
|
|
|
|
|
def _is_macho_file(path: Path) -> bool:
|
|
if not path.is_file() or path.is_symlink():
|
|
return False
|
|
try:
|
|
magic = path.read_bytes()[:4]
|
|
except OSError:
|
|
return False
|
|
return magic in (
|
|
b'\xcf\xfa\xed\xfe',
|
|
b'\xfe\xed\xfa\xcf',
|
|
b'\xce\xfa\xed\xfe',
|
|
b'\xfe\xed\xfa\xce',
|
|
b'\xca\xfe\xba\xbe',
|
|
b'\xbe\xba\xfe\xca',
|
|
)
|
|
|
|
|
|
def _strip_embedded_binaries(staged_app: Path) -> list[str]:
|
|
stripped: list[str] = []
|
|
candidates = 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 nested in candidates:
|
|
targets: list[Path] = []
|
|
if nested.suffix == '.dylib' and _is_macho_file(nested):
|
|
targets.append(nested)
|
|
elif nested.suffix == '.framework' and nested.is_dir():
|
|
for doc_name in ('export.txt', 'README.md'):
|
|
doc_p = nested / doc_name
|
|
if doc_p.is_file() and not doc_p.is_symlink():
|
|
doc_p.unlink()
|
|
for sub in sorted(nested.rglob('*')):
|
|
rel_parts = sub.relative_to(nested).parts
|
|
if any(part.endswith(('.framework', '.dylib')) for part in rel_parts[:-1]):
|
|
continue
|
|
if sub.suffix == '.dylib' and len(rel_parts) > 1:
|
|
continue
|
|
if _is_macho_file(sub):
|
|
targets.append(sub)
|
|
for bin_p in targets:
|
|
subprocess.run(['xcrun', 'strip', '-x', str(bin_p)], check=True)
|
|
stripped.append(str(bin_p.relative_to(staged_app)))
|
|
subprocess.run(['codesign', '--force', '--sign', DEFAULT_IDENTITY, str(nested)], check=True)
|
|
return stripped
|
|
|
|
|
|
def _collect_static_hygiene_gate(
|
|
ipa_path: Path,
|
|
app_dir: Path,
|
|
main_bin: Path,
|
|
interm: Path,
|
|
scheme: str,
|
|
symbol_map_path: Path,
|
|
) -> dict:
|
|
"""Verify static-analysis hardening guarantees on the final IPA and object artifacts."""
|
|
main_raw = main_bin.read_bytes()
|
|
nm_gu = subprocess.check_output(['xcrun', 'nm', '-gU', str(main_bin)], text=True, errors='replace')
|
|
defined_exports = sorted({l.split()[-1] for l in nm_gu.splitlines() if l.strip()})
|
|
dyld_info_out = subprocess.check_output(['xcrun', 'dyld_info', '-exports', str(main_bin)], text=True, errors='replace')
|
|
dyld_exports = sorted({
|
|
parts[-1]
|
|
for ln in dyld_info_out.splitlines()
|
|
if (parts := ln.split()) and parts[0].startswith('0x')
|
|
})
|
|
allowed_exports = {'_main', '__mh_execute_header'}
|
|
main_exports_locked = (
|
|
set(defined_exports).issubset(allowed_exports)
|
|
and set(dyld_exports).issubset(allowed_exports)
|
|
)
|
|
|
|
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(main_bin)], text=True, errors='replace')
|
|
nm_u_syms = {l.strip() for l in nm_u.splitlines() if l.strip()}
|
|
forbidden_main_u = {
|
|
sym: (sym in nm_u_syms)
|
|
for sym in ('_SecKeyCreateWithData', '_SecKeyCreateSignature')
|
|
}
|
|
third_party_main_u = {
|
|
sym: (sym in nm_u_syms)
|
|
for sym in ('_CCKeyDerivationPBKDF', '_CCCrypt', '_CCHmac', '_sysctl')
|
|
}
|
|
cryptokit_imports = sorted(
|
|
s for s in nm_u_syms if 'CryptoKit' in s or '9CryptoKit' in s
|
|
)
|
|
otool_l_lines = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True, errors='replace').splitlines()
|
|
cryptokit_load_cmds = [l.strip() for l in otool_l_lines if 'CryptoKit' in l]
|
|
|
|
obj_dirs = [interm / 'Objects-normal/arm64', interm / 'Objects-normal/arm64/ig-swift-macho']
|
|
target_obj_prefixes = (
|
|
'RDSDKeyBox.o',
|
|
'RDEpubCryptBridge.o',
|
|
'RBCoreUtil.o',
|
|
'RDSDPrivateKeyManager',
|
|
'RDSDAuthV32Signer',
|
|
'RDInjectionDetector',
|
|
'RDJailbreakDetector',
|
|
'STSJailbreakDetectTool.o',
|
|
'RDTSParameterSetPatcher',
|
|
'RDRouterDebugTool',
|
|
)
|
|
all_jailbreak_needles = (
|
|
b'/Applications/Cydia.app',
|
|
b'/Library/MobileSubstrate/MobileSubstrate.dylib',
|
|
b'/Library/MobileSubstrate/DynamicLibraries',
|
|
b'/private/var/tmp/cydia.log',
|
|
b'/private/var/lib/cydia',
|
|
b'/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist',
|
|
b'/var/jb/usr/lib',
|
|
b'com.opa334.TrollStore.plist',
|
|
b'.jailbreak_test_',
|
|
b'/User/Applications/',
|
|
)
|
|
app_obj_stub_hits: dict[str, list[str]] = {}
|
|
app_objects_jailbreak_hits: dict[str, list[str]] = {}
|
|
app_obj_checked = 0
|
|
core_objs_matched: set[str] = set()
|
|
watched_stubs = {
|
|
'_SecKeyCreateWithData',
|
|
'_SecKeyCreateSignature',
|
|
'_CCKeyDerivationPBKDF',
|
|
'_CCCrypt',
|
|
'_CCHmac',
|
|
'_sysctl',
|
|
}
|
|
for od in obj_dirs:
|
|
if not od.is_dir():
|
|
continue
|
|
for obj_p in sorted(od.glob('*.o')):
|
|
app_obj_checked += 1
|
|
for pfx in target_obj_prefixes:
|
|
if obj_p.name == pfx or pfx in obj_p.name:
|
|
core_objs_matched.add(pfx)
|
|
o_u = subprocess.check_output(['xcrun', 'nm', '-u', str(obj_p)], text=True, errors='replace')
|
|
hits = sorted({l.strip() for l in o_u.splitlines() if l.strip()} & watched_stubs)
|
|
if hits:
|
|
app_obj_stub_hits[obj_p.name] = hits
|
|
obj_raw = obj_p.read_bytes()
|
|
jb_hits = [pat.decode('ascii', errors='replace') for pat in all_jailbreak_needles if pat in obj_raw]
|
|
if jb_hits:
|
|
app_objects_jailbreak_hits[obj_p.name] = jb_hits
|
|
|
|
sections = verify_macho_indirect_calls.parse_macho_sections(main_bin)
|
|
cstr_sec = sections.get('__TEXT,__cstring') or {}
|
|
cstrings: list[str] = []
|
|
if cstr_sec.get('size', 0) > 0:
|
|
mv = verify_macho_indirect_calls._select_arm64_slice(main_raw)
|
|
cstr_bytes = bytes(mv[cstr_sec['offset']:cstr_sec['offset'] + cstr_sec['size']])
|
|
cstrings = [s.decode('utf-8', errors='replace') for s in cstr_bytes.split(b'\x00') if s]
|
|
|
|
tmp_work_leaks = main_raw.count(b'/tmp/ig-ipa-work/')
|
|
users_path_leaks = main_raw.count(b'/Users/shenlei/')
|
|
src_readoor_leaks = main_raw.count(b'/src/readoor/')
|
|
readoor_src_re = re.compile(r'^(?:\./|/)?readoor/.*\.(?:swift|m|mm|c|h)$')
|
|
readoor_rel_cstrings = [s for s in cstrings if readoor_src_re.match(s)]
|
|
swift_mod_file_re = re.compile(rf'^(?:{re.escape(scheme)}|readoor31|readoor)/.*\.swift$')
|
|
swift_module_file_cstrings = [s for s in cstrings if swift_mod_file_re.match(s)]
|
|
pdf_bridge_cstrings = [s for s in cstrings if '[PDF]' in s or '[Bridge]' in s]
|
|
business_debug_needles = (
|
|
'RDHLSLocalProxy',
|
|
'[RDBaseNetworkService]',
|
|
'initializeParser: PDF',
|
|
'映射表解密失败',
|
|
'缺少 pdfMap 字节偏移',
|
|
'PDF SDK 状态保存失败',
|
|
'置换token时签名已过期',
|
|
'强制置换一次 token',
|
|
'服务端未返回有效 token',
|
|
'当前需要置换token',
|
|
'当前不需要置换token',
|
|
'保存用户 token 失败',
|
|
)
|
|
business_debug_cstrings = [
|
|
s for s in cstrings if any(needle in s for needle in business_debug_needles)
|
|
]
|
|
jailbreak_needles = {
|
|
pat.decode('ascii', errors='replace'): main_raw.count(pat)
|
|
for pat in (
|
|
b'/Library/MobileSubstrate/DynamicLibraries',
|
|
b'/private/var/tmp/cydia.log',
|
|
b'/private/var/lib/cydia',
|
|
b'/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist',
|
|
b'/var/jb/usr/lib',
|
|
b'com.opa334.TrollStore.plist',
|
|
b'.jailbreak_test_',
|
|
b'/User/Applications/',
|
|
)
|
|
}
|
|
third_party_jailbreak_needles = {
|
|
pat.decode('ascii', errors='replace'): main_raw.count(pat)
|
|
for pat in (
|
|
b'/Applications/Cydia.app',
|
|
b'/Library/MobileSubstrate/MobileSubstrate.dylib',
|
|
)
|
|
}
|
|
placeholder_url_count = main_raw.count(b'your-api.com/upload')
|
|
|
|
secret_leaks = {
|
|
pat.decode('ascii', errors='replace'): main_raw.count(pat)
|
|
for pat in (
|
|
b'startiasoftstartiasoft',
|
|
b'startiasoftvvportal',
|
|
b'readoorstartiasoft',
|
|
b'startiasoft%@',
|
|
b'd9800fb39d16c3f1cc0ddb5618af8378',
|
|
)
|
|
}
|
|
dev_domain_leaks = {
|
|
pat.decode('ascii'): main_raw.count(pat)
|
|
for pat in (
|
|
b'api3-dev.readoor.cn',
|
|
b'uc-dev.readoor.cn',
|
|
b'statupload-dev.readoor.cn',
|
|
)
|
|
}
|
|
|
|
otool_ov = subprocess.check_output(['xcrun', 'otool', '-oV', str(main_bin)], text=True, errors='replace')
|
|
unobfuscated_watch_classes = (
|
|
'RDEpubCryptBridge',
|
|
'EpubParser',
|
|
'EpubChapter',
|
|
'LoadEpub',
|
|
'RDSecurityGuard',
|
|
'RDIAPTransactionGate',
|
|
'RD30EpubEntry',
|
|
'RDEpubReaderLauncher',
|
|
'STSIAPHandler',
|
|
'STSIAPVerifyHandler',
|
|
'STSIAPKeyChainHandler',
|
|
'STSIAPVerifyTask',
|
|
'STSJailbreakDetectTool',
|
|
)
|
|
unobfuscated_objc_hits = [
|
|
name for name in unobfuscated_watch_classes
|
|
if (
|
|
f'_OBJC_CLASS_$_{name}' in otool_ov
|
|
or f'_OBJC_METACLASS_$_{name}' in otool_ov
|
|
or f'{len(name)}{name}' in otool_ov
|
|
)
|
|
]
|
|
unobfuscated_class_raw_hits = {
|
|
name: main_raw.count(name.encode('ascii'))
|
|
for name in (
|
|
'RDEpubCryptBridge',
|
|
'RDSecurityGuard',
|
|
'RDIAPTransactionGate',
|
|
'RD30EpubEntry',
|
|
'RDEpubReaderLauncher',
|
|
)
|
|
}
|
|
|
|
sym_map = json.loads(symbol_map_path.read_text(encoding='utf-8')).get('mappings') or {}
|
|
expected_l1_renamed = {
|
|
cls: bool((sym_map.get(cls) or {}).get('obfuscated') if isinstance(sym_map.get(cls), dict) else sym_map.get(cls))
|
|
for cls in (
|
|
'RDRouterDebugTool',
|
|
'RDPlayerControlView',
|
|
'EpubParser',
|
|
'EpubChapter',
|
|
'LoadEpub',
|
|
'RDSecurityGuard',
|
|
'RDIAPTransactionGate',
|
|
'RD30EpubEntry',
|
|
'RDEpubReaderLauncher',
|
|
)
|
|
}
|
|
|
|
embedded_checked = 0
|
|
embedded_with_locals: dict[str, int] = {}
|
|
embedded_with_tmp_leaks: dict[str, int] = {}
|
|
rd_coreio_found = False
|
|
rd_coreio_ig_exports: list[str] = []
|
|
rd_coreio_ig_name_count: int | None = None
|
|
main_ig_archive_guard_count = main_raw.count(b'IGArchiveGuard')
|
|
with tempfile.TemporaryDirectory(prefix='ig-ipa-verify-') as td:
|
|
vdir = Path(td)
|
|
with zipfile.ZipFile(ipa_path, 'r') as zf:
|
|
names = set(zf.namelist())
|
|
app_prefix = f'Payload/{scheme}.app/'
|
|
plist_member = f'{app_prefix}Info.plist'
|
|
info_plist = plistlib.loads(zf.read(plist_member))
|
|
redundant_plist_absent = f'{app_prefix}readoor31.plist' not in names
|
|
neutral_asset_present = (
|
|
f'{app_prefix}rd_glyph_lut_v2.dat' in names
|
|
and f'{app_prefix}rd_net_cfg_v1.dat' not in names
|
|
)
|
|
readme_hits = sorted(
|
|
n for n in names
|
|
if n == f'{app_prefix}README.md'
|
|
or (
|
|
n.startswith(f'{app_prefix}Frameworks/')
|
|
and n.rsplit('/', 1)[-1] in ('README.md', 'export.txt')
|
|
)
|
|
)
|
|
macosx_junk_entries = sorted(
|
|
n for n in names
|
|
if n.startswith('__MACOSX/') or '/__MACOSX/' in n or n.rsplit('/', 1)[-1].startswith('._')
|
|
)
|
|
dirty_plist_keys_found = sorted(
|
|
k for k in ('Appilcation support iTunes file sharing', 'Supports opening documents in place')
|
|
if k in info_plist
|
|
)
|
|
ig_archive_guard_entries = sorted(
|
|
n for n in names if n.startswith(f'{app_prefix}Frameworks/IGArchiveGuard.framework/')
|
|
)
|
|
staticized_framework_leaks = sorted(
|
|
n for n in names
|
|
if n.startswith(f'{app_prefix}Frameworks/RDEpubReaderView.framework/')
|
|
or n.startswith(f'{app_prefix}Frameworks/RDPDFReaderView.framework/')
|
|
)
|
|
rd_coreio_member = f'{app_prefix}Frameworks/RDCoreIO.framework/RDCoreIO'
|
|
for member in sorted(names):
|
|
if not member.startswith(f'{app_prefix}Frameworks/') and not member.startswith(f'{app_prefix}PlugIns/'):
|
|
continue
|
|
if member.endswith('/') or '/_CodeSignature/' in member or member.endswith('.plist'):
|
|
continue
|
|
zf.extract(member, vdir)
|
|
fp = vdir / member
|
|
if _is_macho_file(fp):
|
|
embedded_checked += 1
|
|
fw_raw = fp.read_bytes()
|
|
tmp_cnt = fw_raw.count(b'/tmp/ig-ipa-work/')
|
|
if tmp_cnt > 0:
|
|
embedded_with_tmp_leaks[member] = tmp_cnt
|
|
nm_res = subprocess.run(
|
|
['xcrun', 'nm', str(fp)],
|
|
capture_output=True, text=True, errors='replace',
|
|
)
|
|
local_cnt = sum(
|
|
1 for ln in nm_res.stdout.splitlines()
|
|
if len(ln.split()) >= 2 and ln.split()[-2] in ('t', 'd', 's', 'b')
|
|
)
|
|
if local_cnt > 0:
|
|
embedded_with_locals[member] = local_cnt
|
|
if member == rd_coreio_member:
|
|
rd_coreio_found = True
|
|
rd_coreio_ig_name_count = fw_raw.count(b'IGArchiveGuard')
|
|
coreio_exports = subprocess.check_output(
|
|
['xcrun', 'nm', '-gU', str(fp)],
|
|
text=True, errors='replace',
|
|
)
|
|
rd_coreio_ig_exports = sorted(
|
|
sym for ln in coreio_exports.splitlines()
|
|
if ln.strip() and (sym := ln.split()[-1]).startswith('_ig_')
|
|
)
|
|
|
|
schemes = {str(s).lower() for s in (info_plist.get('LSApplicationQueriesSchemes') or [])}
|
|
jb_schemes_found = sorted(schemes & {'cydia', 'sileo', 'zbra', 'filza'})
|
|
ats = info_plist.get('NSAppTransportSecurity') or {}
|
|
ats_arbitrary_disabled = ats.get('NSAllowsArbitraryLoads') is False
|
|
|
|
cryptokit_absent = not cryptokit_imports and not cryptokit_load_cmds
|
|
checks = {
|
|
'main_exports_locked': main_exports_locked,
|
|
'embedded_frameworks_stripped': embedded_checked > 0 and not embedded_with_locals,
|
|
'embedded_frameworks_tmp_leaks_absent': embedded_checked > 0 and not embedded_with_tmp_leaks,
|
|
'source_paths_scrubbed': (
|
|
tmp_work_leaks == 0
|
|
and users_path_leaks == 0
|
|
and src_readoor_leaks == 0
|
|
and not readoor_rel_cstrings
|
|
and not swift_module_file_cstrings
|
|
),
|
|
'pdf_debug_logs_scrubbed': not pdf_bridge_cstrings,
|
|
'business_debug_logs_scrubbed': not business_debug_cstrings,
|
|
'jailbreak_needles_scrubbed': (
|
|
sum(jailbreak_needles.values()) == 0
|
|
and not app_objects_jailbreak_hits
|
|
),
|
|
'placeholder_urls_absent': placeholder_url_count == 0,
|
|
'secrets_scrubbed': sum(secret_leaks.values()) == 0,
|
|
'dev_domains_scrubbed': sum(dev_domain_leaks.values()) == 0,
|
|
'redundant_readoor31_plist_absent': redundant_plist_absent,
|
|
'readme_absent': not readme_hits,
|
|
'macosx_junk_absent': not macosx_junk_entries,
|
|
'plist_dirty_keys_absent': not dirty_plist_keys_found,
|
|
'neutral_asset_present': neutral_asset_present,
|
|
'jailbreak_schemes_absent': not jb_schemes_found,
|
|
'ats_arbitrary_loads_disabled': ats_arbitrary_disabled,
|
|
'cryptokit_completely_absent': cryptokit_absent,
|
|
'main_crypto_stubs_absent': not any(forbidden_main_u.values()) and cryptokit_absent,
|
|
'app_objects_crypto_stubs_absent': (
|
|
len(core_objs_matched) == len(target_obj_prefixes)
|
|
and app_obj_checked >= 50
|
|
and not app_obj_stub_hits
|
|
),
|
|
'unobfuscated_classes_absent': (
|
|
not unobfuscated_objc_hits
|
|
and all(v == 0 for v in unobfuscated_class_raw_hits.values())
|
|
and all(expected_l1_renamed.values())
|
|
),
|
|
'guard_framework_neutralized': (
|
|
not ig_archive_guard_entries
|
|
and rd_coreio_found
|
|
and not rd_coreio_ig_exports
|
|
and rd_coreio_ig_name_count == 0
|
|
and main_ig_archive_guard_count == 0
|
|
),
|
|
'self_frameworks_staticized': not staticized_framework_leaks,
|
|
}
|
|
return {
|
|
'passed': all(checks.values()),
|
|
'checks': checks,
|
|
'main_exported_defined_symbols': defined_exports,
|
|
'main_exported_defined_symbols_count': len(defined_exports),
|
|
'main_dyld_exports': dyld_exports,
|
|
'main_dyld_exports_count': len(dyld_exports),
|
|
'embedded_frameworks_checked': embedded_checked,
|
|
'embedded_frameworks_with_local_symbols': embedded_with_locals,
|
|
'embedded_frameworks_with_tmp_leaks': embedded_with_tmp_leaks,
|
|
'tmp_work_path_leaks': tmp_work_leaks,
|
|
'users_path_leaks': users_path_leaks,
|
|
'src_readoor_path_leaks': src_readoor_leaks,
|
|
'readoor_rel_cstring_leaks': readoor_rel_cstrings[:10],
|
|
'readoor_rel_cstring_leaks_count': len(readoor_rel_cstrings),
|
|
'swift_module_file_leaks': swift_module_file_cstrings[:10],
|
|
'swift_module_file_leaks_count': len(swift_module_file_cstrings),
|
|
'pdf_bridge_cstrings': pdf_bridge_cstrings[:10],
|
|
'pdf_bridge_cstrings_count': len(pdf_bridge_cstrings),
|
|
'business_debug_cstrings': business_debug_cstrings[:10],
|
|
'business_debug_cstrings_count': len(business_debug_cstrings),
|
|
'jailbreak_needles': jailbreak_needles,
|
|
'third_party_jailbreak_needles': third_party_jailbreak_needles,
|
|
'app_objects_jailbreak_hits': app_objects_jailbreak_hits,
|
|
'placeholder_url_count': placeholder_url_count,
|
|
'readme_hits': readme_hits,
|
|
'macosx_junk_entries_count': len(macosx_junk_entries),
|
|
'dirty_plist_keys_found': dirty_plist_keys_found,
|
|
'secret_leaks': secret_leaks,
|
|
'dev_domain_leaks': dev_domain_leaks,
|
|
'jailbreak_schemes_found': jb_schemes_found,
|
|
'ats_arbitrary_loads': ats.get('NSAllowsArbitraryLoads'),
|
|
'forbidden_main_u': forbidden_main_u,
|
|
'third_party_main_u': third_party_main_u,
|
|
'cryptokit_imports': cryptokit_imports,
|
|
'cryptokit_load_cmds': cryptokit_load_cmds,
|
|
'app_objects_checked': app_obj_checked,
|
|
'core_objects_matched': sorted(core_objs_matched),
|
|
'app_objects_stub_hits': app_obj_stub_hits,
|
|
'unobfuscated_objc_hits': unobfuscated_objc_hits,
|
|
'unobfuscated_class_raw_hits': unobfuscated_class_raw_hits,
|
|
'expected_l1_renamed': expected_l1_renamed,
|
|
'ig_archive_guard_entries': ig_archive_guard_entries,
|
|
'rd_coreio_found': rd_coreio_found,
|
|
'rd_coreio_ig_exports': rd_coreio_ig_exports,
|
|
'rd_coreio_ig_name_count': rd_coreio_ig_name_count,
|
|
'main_ig_archive_guard_count': main_ig_archive_guard_count,
|
|
'staticized_framework_leaks': staticized_framework_leaks,
|
|
}
|
|
|
|
|
|
def _sign_and_package_ipa(app_dir: Path, stage_dir: Path, ipa_path: Path, scheme: str) -> tuple[str, str]:
|
|
"""Sign .app preserving its original Info.plist CFBundleIdentifier and archive Payload/ into .ipa."""
|
|
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('Signing identity does not match provisioning profile')
|
|
|
|
if stage_dir.exists():
|
|
shutil.rmtree(stage_dir)
|
|
ipa_root = stage_dir / 'ipa_root'
|
|
payload_dir = ipa_root / 'Payload'
|
|
payload_dir.mkdir(parents=True, exist_ok=True)
|
|
staged_app = payload_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())
|
|
bundle_id = str(info['CFBundleIdentifier'])
|
|
shutil.copy2(DEFAULT_PROFILE, staged_app / 'embedded.mobileprovision')
|
|
|
|
for appex in sorted({p for p in staged_app.rglob('*.appex') if not p.is_symlink()}, key=lambda p: (-len(p.parts), str(p))):
|
|
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 = stage_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)
|
|
|
|
_strip_embedded_binaries(staged_app)
|
|
|
|
allowed = dict(ent)
|
|
allowed['application-identifier'] = f'{prefix}.{bundle_id}'
|
|
allowed['keychain-access-groups'] = [f'{prefix}.{bundle_id}']
|
|
ent_path = stage_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)
|
|
|
|
ipa_path.parent.mkdir(parents=True, exist_ok=True)
|
|
if ipa_path.exists():
|
|
ipa_path.unlink()
|
|
subprocess.run(['ditto', '-c', '-k', '--norsrc', str(ipa_root), str(ipa_path)], check=True)
|
|
|
|
with zipfile.ZipFile(ipa_path, 'r') as zf:
|
|
expected_prefix = f'Payload/{scheme}.app/'
|
|
if not any(n.startswith(expected_prefix) for n in zf.namelist()):
|
|
raise RuntimeError(f'IPA missing expected {expected_prefix} entries')
|
|
|
|
return bundle_id, m3.sha256_bytes(ipa_path.read_bytes())
|
|
|
|
|
|
def build_ipa(scheme: str, output_dir: Path, seed: str, expected_binaries: int, dist_channel: str = 'dev') -> dict:
|
|
"""Run full L1+L2+L3 archive, verify binary obfuscation & Route 2 audit, and export signed IPA."""
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
snapshot_src = WORK_ROOT / 'src'
|
|
dd_path = WORK_ROOT / 'dd'
|
|
archive_path = WORK_ROOT / 'archives' / f'{scheme}.xcarchive'
|
|
stage_dir = WORK_ROOT / 'stage'
|
|
obj_cache = CACHE_ROOT / 'obj_cache'
|
|
sdk_cache = CACHE_ROOT / 'sdk_cache'
|
|
|
|
try:
|
|
for d in (WORK_ROOT, CACHE_ROOT):
|
|
if d.exists():
|
|
shutil.rmtree(d)
|
|
|
|
print('=== [0] Sync toolchain & verify integration ===', flush=True)
|
|
m3.sync_toolchain_and_integrate()
|
|
policy_path = ROOT / 'config/ig_llvm_policy.json'
|
|
policy = json.loads(policy_path.read_text(encoding='utf-8'))
|
|
policy_stamp = ig_toolchain_resolver.file_sha256(policy_path)[:12]
|
|
|
|
print(f'=== [1] L1 Snapshot & Obfuscation ({scheme}, seed={seed}) ===', flush=True)
|
|
l1_info = _create_l1_snapshot(snapshot_src, scheme, '20261120_ipa', seed, output_dir / 'l1_apply.log')
|
|
print(
|
|
f"[L1] types={l1_info['type_mappings_count']}, methods={l1_info['method_mappings_count']}, elapsed={l1_info['elapsed_s']}s",
|
|
flush=True,
|
|
)
|
|
pods_cfg_count = _inject_pods_prefix_map(snapshot_src)
|
|
print(f'[PodsPrefixMap] injected={pods_cfg_count}', flush=True)
|
|
|
|
free_gb = m3.check_disk_budget()
|
|
print(f'=== [2] L1+L2+L3 Production Archive ({scheme}, disk_free={free_gb}GB) ===', flush=True)
|
|
archive_path.parent.mkdir(parents=True, exist_ok=True)
|
|
dd_path.mkdir(parents=True, exist_ok=True)
|
|
obj_cache.mkdir(parents=True, exist_ok=True)
|
|
sdk_cache.mkdir(parents=True, exist_ok=True)
|
|
|
|
env = os.environ.copy()
|
|
env['IG_REQUIRE_LLVM_OBF'] = '1'
|
|
env['IG_OBF_OBJ_CACHE_DIR'] = str(obj_cache)
|
|
env['IG_SDK_CACHE_DIR'] = str(sdk_cache)
|
|
|
|
cmd = [
|
|
'xcodebuild',
|
|
'-workspace', str(snapshot_src / 'readoor.xcworkspace'),
|
|
'-scheme', scheme,
|
|
'-configuration', 'Release',
|
|
'-destination', 'generic/platform=iOS',
|
|
'-derivedDataPath', str(dd_path),
|
|
'CODE_SIGNING_ALLOWED=NO',
|
|
'IG_OBF_MODE=full',
|
|
'IG_POLICY_PROFILE=default',
|
|
f'IG_POLICY_STAMP={policy_stamp}',
|
|
f'IG_RELEASE_SEED={seed}',
|
|
f'IG_DIST_CHANNEL={dist_channel}',
|
|
'IG_SWIFT_EXTRA_FLAGS=',
|
|
'IG_C_EXTRA_FLAGS=',
|
|
'-archivePath', str(archive_path),
|
|
'archive',
|
|
]
|
|
t0 = time.monotonic()
|
|
res = subprocess.run(cmd, cwd=snapshot_src, env=env, capture_output=True, text=True)
|
|
archive_elapsed = round(time.monotonic() - t0, 2)
|
|
full_log = res.stdout + '\n' + res.stderr
|
|
tail_lines = [
|
|
l for l in full_log.splitlines()
|
|
if '[IGRoute2]' in l or '[IGObf]' in l or 'ARCHIVE ' in l or 'error:' in l
|
|
or 'ld:' in l or 'fixup' in l or 'Undefined' in l or 'Traceback' in l
|
|
]
|
|
(output_dir / 'xcodebuild.log').write_text(
|
|
'\n'.join(tail_lines[-160:] + ['', '--- tail ---'] + full_log.splitlines()[-100:]) + '\n',
|
|
encoding='utf-8',
|
|
)
|
|
if res.returncode != 0:
|
|
raise RuntimeError(f'xcodebuild archive failed (rc={res.returncode}):\n' + '\n'.join(full_log.splitlines()[-120:]))
|
|
print(f'[Archive] succeeded in {archive_elapsed}s', flush=True)
|
|
|
|
print('=== [3] Verify Mach-O UUID, Route 2, L2 Audit & Clues ===', flush=True)
|
|
app_dir = archive_path / 'Products/Applications' / f'{scheme}.app'
|
|
main_bin = app_dir / scheme
|
|
dsyms_dir = archive_path / 'dSYMs'
|
|
uuids_bin = m3.uuids_of(main_bin)
|
|
uuids_dsym = m3.uuids_of(dsyms_dir / f'{scheme}.app.dSYM')
|
|
assert uuids_bin and uuids_bin == uuids_dsym, (uuids_bin, uuids_dsym)
|
|
|
|
r2_out_dir = output_dir / 'route2'
|
|
r2_out_dir.mkdir(parents=True, exist_ok=True)
|
|
binaries, direct_total = scan_route2(app_dir, r2_out_dir, f'{scheme}_ipa')
|
|
r2_counts = {}
|
|
for info in binaries.values():
|
|
for sl in info['slices']:
|
|
for k, v in sl['counts'].items():
|
|
r2_counts[k] = r2_counts.get(k, 0) + v
|
|
assert len(binaries) == expected_binaries and direct_total == 0, (len(binaries), direct_total)
|
|
|
|
interm = dd_path / f'Build/Intermediates.noindex/ArchiveIntermediates/{scheme}/IntermediateBuildFilesPath/readoor.build/Release-iphoneos/{scheme}.build'
|
|
audit_src = interm / 'ig-route2-audit/ig_obfuscation_audit.json'
|
|
shutil.copy2(audit_src, output_dir / 'ig_obfuscation_audit.json')
|
|
obf_audit = m3.verify_required_targets(audit_src, policy, expect_l1_translation=True)
|
|
if policy.get('opaque_const_targets'):
|
|
assert int(obf_audit.get('total_opaque_constants') or 0) > 0, obf_audit
|
|
if policy.get('arithmetic_targets'):
|
|
assert int(obf_audit.get('total_arithmetic_rewrites') or 0) > 0, obf_audit
|
|
if policy.get('indirect_branch_targets'):
|
|
assert int(obf_audit.get('total_indirect_branches') or 0) > 0, obf_audit
|
|
if policy.get('string_encrypt_stack_targets'):
|
|
assert int(obf_audit.get('total_strings_stack_encrypted') or 0) > 0, obf_audit
|
|
if policy.get('anti_hooking_targets'):
|
|
assert int(obf_audit.get('total_anti_hook_functions') or 0) > 0, obf_audit
|
|
if policy.get('function_outline_targets'):
|
|
assert int(obf_audit.get('total_functions_outlined') or 0) > 0, obf_audit
|
|
if policy.get('opaque_field_targets'):
|
|
assert int(obf_audit.get('total_opaque_field_access') or 0) > 0, obf_audit
|
|
if policy.get('bb_split_targets'):
|
|
assert int(obf_audit.get('total_bb_split_count') or 0) > 0, obf_audit
|
|
if policy.get('arithmetic_nonlinear_mba') or any(r.get('nonlinear_mba') for r in (policy.get('arithmetic_targets') or [])):
|
|
assert int(obf_audit.get('total_nonlinear_mba') or 0) > 0, obf_audit
|
|
if policy.get('opaque_const_opaque_zero') or any(r.get('opaque_zero') for r in (policy.get('opaque_const_targets') or [])):
|
|
assert int(obf_audit.get('total_opaque_zero') or 0) > 0, obf_audit
|
|
clues = m3.audit_m3_static_clues(main_bin, interm / 'Objects-normal/arm64', snapshot_src)
|
|
for pat, cnt in clues['main_binary_forbidden_counts'].items():
|
|
assert cnt == 0, f'Forbidden string {pat!r} occurred {cnt}x'
|
|
|
|
main_raw = main_bin.read_bytes()
|
|
guard_bin = app_dir / 'Frameworks/RDCoreIO.framework/RDCoreIO'
|
|
guard_raw = guard_bin.read_bytes() if guard_bin.is_file() else b''
|
|
beacon_absent = {
|
|
'termination_jsonl_main': main_raw.count(b'termination.jsonl') == 0,
|
|
'terminate_json_main': main_raw.count(b'"action":"terminate"') == 0,
|
|
'terminate_json_guard': guard_raw.count(b'"action":"terminate"') == 0,
|
|
}
|
|
assert all(beacon_absent.values()), f'Unexpected release beacon string: {beacon_absent}'
|
|
|
|
diag_needles = {
|
|
'cryptid==0': b'cryptid==0',
|
|
'CS_VALID': b'CS_VALID',
|
|
'kinfo_proc.p_flag': b'kinfo_proc.p_flag',
|
|
'dispatch-write': b'dispatch-write',
|
|
'dispatch-target': b'dispatch-target',
|
|
'archive-target': b'archive-target',
|
|
'DYLD_INSERT_LIBRARIES': b'DYLD_INSERT_LIBRARIES',
|
|
'trampoline_zh': '跳转蹦床'.encode('utf-8'),
|
|
'baseline_zh': '启动基线'.encode('utf-8'),
|
|
}
|
|
diag_absent = {}
|
|
for k, pat in diag_needles.items():
|
|
diag_absent[f'main_{k}'] = main_raw.count(pat) == 0
|
|
diag_absent[f'guard_{k}'] = guard_raw.count(pat) == 0
|
|
assert all(diag_absent.values()), f'Unexpected release diagnostic string: {diag_absent}'
|
|
|
|
otool_deps = subprocess.check_output(['xcrun', 'otool', '-L', str(main_bin)], text=True).splitlines()
|
|
guard_dep_lines = [l.strip() for l in otool_deps if 'RDCoreIO' in l]
|
|
dwarf_bin = dsyms_dir / f'{scheme}.app.dSYM/Contents/Resources/DWARF/{scheme}'
|
|
nm_out = subprocess.check_output(['xcrun', 'nm', '-n', str(dwarf_bin)], text=True).splitlines()
|
|
star_gate = verify_macho_star_cfg.verify_binary_star_cfg(
|
|
main_bin, dwarf_bin, obf_audit, require_topology='sparse_switch'
|
|
)
|
|
print(
|
|
f"[StarCFGGate] verified={star_gate['verified_star_count']}/{star_gate['linked_checked_count']} "
|
|
f"(dead_stripped={star_gate['dead_stripped_count']}, failed={star_gate['failed_count']})",
|
|
flush=True,
|
|
)
|
|
require_zero_kb_bl = bool(policy.get('indirect_call_targets'))
|
|
icall_gate = verify_macho_indirect_calls.analyze_macho_calls(
|
|
main_bin,
|
|
dwarf_bin,
|
|
symbol_map_path=Path(l1_info['symbol_map_path']),
|
|
require_zero_keybox_direct_bl=require_zero_kb_bl,
|
|
)
|
|
print(
|
|
f"[IndirectCallGate] internal_bl={icall_gate['text_call_summary']['internal_text_bl']} "
|
|
f"blr={icall_gate['text_call_summary']['indirect_blr_total']} "
|
|
f"keybox_direct_xrefs={icall_gate['keybox_and_bridge_15_symbols']['total_direct_call_xrefs']}",
|
|
flush=True,
|
|
)
|
|
assert icall_gate['gate_passed'], f"IndirectCallGate failed: {icall_gate['violations']}"
|
|
ibr_gate = verify_macho_indirect_branches.verify_binary_indirect_branches(
|
|
main_bin, dwarf_bin, obf_audit,
|
|
required_sources=policy.get('required_indirect_branch_sources') or (),
|
|
)
|
|
print(
|
|
f"[IndirectBranchGate] verified={ibr_gate['verified_ibr_count']}/{ibr_gate['linked_checked_count']} "
|
|
f"(dead_stripped={ibr_gate['dead_stripped_count']}, failed={ibr_gate['failed_count']})",
|
|
flush=True,
|
|
)
|
|
if policy.get('indirect_branch_targets'):
|
|
assert ibr_gate['verified_ibr_count'] > 0, ibr_gate
|
|
anti_hook_gate = _verify_binary_anti_hook_prologues(main_bin, dwarf_bin, obf_audit)
|
|
print(
|
|
f"[AntiHookGate] verified={anti_hook_gate['verified_anti_hook_count']}/{anti_hook_gate['linked_checked_count']} "
|
|
f"(dead_stripped={anti_hook_gate['dead_stripped_count']}, failed={anti_hook_gate['failed_count']})",
|
|
flush=True,
|
|
)
|
|
if policy.get('anti_hooking_targets'):
|
|
assert anti_hook_gate['verified_anti_hook_count'] > 0, anti_hook_gate
|
|
inlined_c_helpers_absent = {}
|
|
for helper_sym in (
|
|
'_rd_kb_unmask_seed', '_rd_kb_unmask_prefix',
|
|
'_rd_kb_md5_transform', '_rd_kb_md5_lower_hex',
|
|
'_rd_sd_unmask_rolling', '_rd_sd_md5_transform',
|
|
'_rd_sd_md5_3part_lower_hex',
|
|
):
|
|
inlined_c_helpers_absent[helper_sym] = not any(l.split()[-1] == helper_sym for l in nm_out if l.strip())
|
|
assert inlined_c_helpers_absent[helper_sym], f'Expected C helper {helper_sym} to be inlined'
|
|
|
|
obf_symbol_samples = []
|
|
for orig, obf in list(l1_info['sample_type_mappings'].items()):
|
|
hits = [l.split()[-1] for l in nm_out if obf in l][:3]
|
|
obf_symbol_samples.append({'original': orig, 'obfuscated': obf, 'dwarf_hits': hits})
|
|
|
|
print('=== [4] Strip Frameworks, Sign & Export IPA + dSYMs + Maps ===', flush=True)
|
|
ipa_path = output_dir / f'{scheme}.ipa'
|
|
bundle_id, ipa_sha = _sign_and_package_ipa(app_dir, stage_dir, ipa_path, scheme)
|
|
hygiene_gate = _collect_static_hygiene_gate(
|
|
ipa_path, app_dir, main_bin, interm, scheme, Path(l1_info['symbol_map_path'])
|
|
)
|
|
print(
|
|
f"[StaticHygieneGate] passed={hygiene_gate['passed']} "
|
|
f"exports={hygiene_gate['main_exported_defined_symbols_count']} "
|
|
f"fw_unstripped={len(hygiene_gate['embedded_frameworks_with_local_symbols'])}/{hygiene_gate['embedded_frameworks_checked']} "
|
|
f"tmp_leaks={hygiene_gate['tmp_work_path_leaks']} rel_leaks={hygiene_gate['readoor_rel_cstring_leaks_count']}",
|
|
flush=True,
|
|
)
|
|
dsyms_zip = output_dir / 'dSYMs.zip'
|
|
if dsyms_zip.exists():
|
|
dsyms_zip.unlink()
|
|
subprocess.run(['ditto', '-c', '-k', '--norsrc', str(dsyms_dir), str(dsyms_zip)], check=True)
|
|
|
|
maps_dst = output_dir / 'obfuscation_maps'
|
|
if maps_dst.exists():
|
|
shutil.rmtree(maps_dst)
|
|
maps_dst.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(l1_info['symbol_map_path'], maps_dst / l1_info['symbol_map_path'].name)
|
|
shutil.copy2(l1_info['method_map_path'], maps_dst / l1_info['method_map_path'].name)
|
|
|
|
summary = {
|
|
'scheme': scheme,
|
|
'dist_channel': dist_channel,
|
|
'bundle_id': bundle_id,
|
|
'seed': seed,
|
|
'policy_stamp': policy_stamp,
|
|
'ipa_path': str(ipa_path),
|
|
'ipa_bytes': ipa_path.stat().st_size,
|
|
'ipa_sha256': ipa_sha,
|
|
'dsyms_zip_path': str(dsyms_zip),
|
|
'main_binary_bytes': main_bin.stat().st_size,
|
|
'main_text_bytes': m3.text_section_bytes(main_bin),
|
|
'main_uuids': sorted(uuids_bin),
|
|
'timings_s': {
|
|
'l1_apply': l1_info['elapsed_s'],
|
|
'xcode_archive': archive_elapsed,
|
|
'total_build': round(l1_info['elapsed_s'] + archive_elapsed, 2),
|
|
},
|
|
'l1_obfuscation': {
|
|
'type_mappings_count': l1_info['type_mappings_count'],
|
|
'method_mappings_count': l1_info['method_mappings_count'],
|
|
'sample_type_mappings': l1_info['sample_type_mappings'],
|
|
'sample_method_mappings': l1_info['sample_method_mappings'],
|
|
'dwarf_symbol_samples': obf_symbol_samples,
|
|
},
|
|
'route2': {
|
|
'binaries': len(binaries),
|
|
'direct_call_total': direct_total,
|
|
'direct_call_counts': r2_counts,
|
|
'guard_framework_deps': guard_dep_lines,
|
|
},
|
|
'l2_obf_audit': {
|
|
'l1_translation_active': obf_audit.get('l1_translation_active'),
|
|
'expected_swift_count': obf_audit.get('expected_swift_count'),
|
|
'converted_swift_count': obf_audit.get('converted_swift_count'),
|
|
'objc_audited_count': obf_audit.get('objc_audited_count'),
|
|
'total_flattened': obf_audit.get('total_flattened'),
|
|
'total_strings_encrypted': obf_audit.get('total_strings_encrypted'),
|
|
'total_strings_stack_encrypted': int(obf_audit.get('total_strings_stack_encrypted') or 0),
|
|
'total_objc_strings_encrypted': int(obf_audit.get('total_objc_strings_encrypted') or 0),
|
|
'total_swift_strings_encrypted': int(obf_audit.get('total_swift_strings_encrypted') or 0),
|
|
'total_strings_replaced': int(obf_audit.get('total_strings_replaced') or 0),
|
|
'total_paths_scrubbed': int(obf_audit.get('total_paths_scrubbed') or 0),
|
|
'total_indirect_calls': int(obf_audit.get('total_indirect_calls') or 0),
|
|
'total_opaque_constants': int(obf_audit.get('total_opaque_constants') or 0),
|
|
'total_arithmetic_rewrites': int(obf_audit.get('total_arithmetic_rewrites') or 0),
|
|
'total_indirect_branches': int(obf_audit.get('total_indirect_branches') or 0),
|
|
'total_anti_hook_functions': int(obf_audit.get('total_anti_hook_functions') or 0),
|
|
'total_functions_outlined': int(obf_audit.get('total_functions_outlined') or 0),
|
|
'total_opaque_field_access': int(obf_audit.get('total_opaque_field_access') or 0),
|
|
'total_bb_split_count': int(obf_audit.get('total_bb_split_count') or 0),
|
|
'total_bb_split_functions': int(obf_audit.get('total_bb_split_functions') or 0),
|
|
'total_nonlinear_mba': int(obf_audit.get('total_nonlinear_mba') or 0),
|
|
'total_opaque_zero': int(obf_audit.get('total_opaque_zero') or 0),
|
|
'required_targets': obf_audit.get('required_targets'),
|
|
'static_frameworks_obfuscated': obf_audit.get('static_frameworks_obfuscated') or [],
|
|
},
|
|
'macho_star_cfg_gate': star_gate,
|
|
'macho_indirect_branch_gate': ibr_gate,
|
|
'macho_anti_hook_gate': anti_hook_gate,
|
|
'macho_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'],
|
|
},
|
|
'keybox_helpers_inlined_absent_in_dwarf': inlined_c_helpers_absent,
|
|
'release_beacon_absent': beacon_absent,
|
|
'defender_diag_absent': diag_absent,
|
|
'static_clues': clues,
|
|
'static_hygiene_gate': hygiene_gate,
|
|
}
|
|
(output_dir / 'build_summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
|
if not hygiene_gate['passed']:
|
|
raise RuntimeError(f"StaticHygieneGate failed: {json.dumps(hygiene_gate, ensure_ascii=False)}")
|
|
print(f"[DONE] IPA={ipa_path} ({summary['ipa_bytes']} bytes), archive_elapsed={archive_elapsed}s", flush=True)
|
|
return summary
|
|
finally:
|
|
for d in (WORK_ROOT, CACHE_ROOT):
|
|
if d.exists():
|
|
shutil.rmtree(d)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--scheme', default='readoor31OtherPay')
|
|
parser.add_argument('--output-dir', default=str(ROOT / 'test-results' / '20261120-readoor31OtherPay-obf-ipa'))
|
|
parser.add_argument('--seed', default='prod_otherpay_20261120')
|
|
parser.add_argument('--expected-binaries', type=int, default=42)
|
|
parser.add_argument('--dist-channel', choices=['dev', 'appstore'], default='dev')
|
|
args = parser.parse_args()
|
|
build_ipa(args.scheme, Path(args.output_dir), args.seed, args.expected_binaries, dist_channel=args.dist_channel)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|