- 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
1078 lines
56 KiB
Python
1078 lines
56 KiB
Python
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
APP_REPO = ROOT / 'readoor-test'
|
|
OBF_DIR = APP_REPO / 'AutoPacking' / 'obfuscation'
|
|
TOOLS_CRASH = ROOT / 'tools' / 'crash_restore'
|
|
TOOLS_OBF = ROOT / 'tools' / 'llvm_obf'
|
|
|
|
sys.path.insert(0, str(OBF_DIR))
|
|
sys.path.insert(0, str(TOOLS_CRASH))
|
|
sys.path.insert(0, str(TOOLS_OBF))
|
|
|
|
import ig_toolchain_resolver # noqa: E402
|
|
import obfuscate_symbols as obf # noqa: E402
|
|
import restore_crash_report # noqa: E402
|
|
import verify_macho_star_cfg # noqa: E402
|
|
|
|
|
|
class TestMilestone3ObfuscationAndPolicy(unittest.TestCase):
|
|
def _stage_obf_runtime(self, dst_repo: Path):
|
|
dst_obf = dst_repo / 'AutoPacking' / 'obfuscation'
|
|
dst_obf.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(OBF_DIR / 'obfuscate_symbols.py', dst_obf / 'obfuscate_symbols.py')
|
|
shutil.copytree(OBF_DIR / 'obfuscation_runtime', dst_obf / 'obfuscation_runtime', dirs_exist_ok=True)
|
|
(dst_obf / 'scripts').mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(OBF_DIR / 'scripts' / 'obfuscation_self_check.sh', dst_obf / 'scripts' / 'obfuscation_self_check.sh')
|
|
return dst_obf
|
|
|
|
def test_nscoding_auto_exemption_on_real_readoor_sources(self):
|
|
real_files_to_check = [
|
|
APP_REPO / 'readoor/BookShelf/Classes/Models/STSPayOrderInfoObject.h',
|
|
APP_REPO / 'readoor/BookShelf/Classes/Models/STSPayOrderInfoObject.m',
|
|
APP_REPO / 'readoor/BookView/PDF/Core/Classes/Stage/SubViews/PaintingViews/RBCorePenLineData.h',
|
|
APP_REPO / 'readoor/BookView/PDF/Core/Classes/Stage/SubViews/PaintingViews/RBCorePenLineData.m',
|
|
APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintModel.h',
|
|
APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintModel.m',
|
|
APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintLayerModel.h',
|
|
APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintPageLayerModel.h',
|
|
APP_REPO / 'readoor/BookView/GLPaintView/Model/STSPaintStack.h',
|
|
APP_REPO / 'readoor/3.0/Base/MediaCache/RDPlayerCacheMedia.swift',
|
|
APP_REPO / 'readoor/3.0/Base/MediaCache/RDPlayerCacheMediaConfiguration.swift',
|
|
APP_REPO / 'readoor/3.0/Features/Account/Login/Views/RDLoginView.swift',
|
|
]
|
|
# 清空内存 cache / 直接测解析逻辑以确认非仅靠 seed 命中
|
|
swift_detected = set()
|
|
objc_detected = set()
|
|
parents = {}
|
|
for fp in real_files_to_check:
|
|
txt = fp.read_text(encoding='utf-8')
|
|
is_sw = fp.suffix == '.swift'
|
|
masked = obf._mask_non_code_preserving_lines(txt, is_swift=is_sw, mask_imports=False)
|
|
info = obf._extract_nscoding_info_from_code(masked, is_swift=is_sw)
|
|
if is_sw:
|
|
swift_detected.update(info['direct'])
|
|
else:
|
|
objc_detected.update(info['direct'])
|
|
for k, vs in info['parents'].items():
|
|
parents.setdefault(k, []).extend(vs)
|
|
|
|
# synthetic subclasses
|
|
sub_swift = obf._extract_nscoding_info_from_code(
|
|
'class RDCustomCacheMedia: RDPlayerCacheMedia { var tag: String = "" }',
|
|
is_swift=True,
|
|
)
|
|
sub_objc = obf._extract_nscoding_info_from_code(
|
|
'@interface STSCustomOrder : STSPayOrderInfoObject\n@end',
|
|
is_swift=False,
|
|
)
|
|
for pdict in (sub_swift['parents'], sub_objc['parents']):
|
|
for k, vs in pdict.items():
|
|
parents.setdefault(k, []).extend(vs)
|
|
|
|
detected = swift_detected | objc_detected
|
|
changed = True
|
|
while changed:
|
|
changed = False
|
|
for child, supers in parents.items():
|
|
if child not in detected and any(s in detected for s in supers):
|
|
detected.add(child)
|
|
changed = True
|
|
|
|
for expected in (
|
|
'STSPayOrderInfoObject',
|
|
'RBCorePenLineData', # 头文件中未声明 <NSCoding>,靠 .m 中 encodeWithCoder:/initWithCoder: 识别
|
|
'STSPaintModel',
|
|
'STSPaintLayerModel',
|
|
'STSPaintPageLayerModel',
|
|
'STSPaintStack',
|
|
'RDPlayerCacheMedia',
|
|
'RDPlayerCacheMediaConfiguration',
|
|
'RDCustomCacheMedia',
|
|
'STSCustomOrder',
|
|
):
|
|
self.assertIn(expected, detected, f'Missing auto-detected NSCoding class: {expected}')
|
|
self.assertNotIn('RDLoginView', detected, 'UIView subclass with only required init?(coder:) must not be exempted as NSCoding')
|
|
|
|
def test_real_binary_over_install_nscoding_unarchiving(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
dst_obf = self._stage_obf_runtime(root)
|
|
src = root / 'Sources'
|
|
src.mkdir()
|
|
|
|
(src / 'STSModels.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'@interface STSPayOrderInfoObject : NSObject<NSCoding>\n'
|
|
'@property (nonatomic, copy) NSString *orderId;\n'
|
|
'@property (nonatomic, copy) NSString *receiptData;\n'
|
|
'@end\n'
|
|
'@interface RBCorePenLineData : NSObject\n'
|
|
'@property (nonatomic, copy) NSString *lineKey;\n'
|
|
'@property (nonatomic, assign) double lineWidth;\n'
|
|
'@end\n'
|
|
'@interface STSPaintModel : NSObject<NSCoding, NSSecureCoding>\n'
|
|
'@property (nonatomic, copy) NSString *brushName;\n'
|
|
'@end\n'
|
|
'@interface STSOrderTransientNote : NSObject\n'
|
|
'- (NSString *)renderSummary:(NSString *)tag stepMarker:(NSInteger)marker;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'STSModels.m').write_text(
|
|
'#import "STSModels.h"\n'
|
|
'@implementation STSPayOrderInfoObject\n'
|
|
'- (void)encodeWithCoder:(NSCoder *)coder {\n'
|
|
' [coder encodeObject:self.orderId forKey:@"orderId"];\n'
|
|
' [coder encodeObject:self.receiptData forKey:@"receiptData"];\n'
|
|
'}\n'
|
|
'- (instancetype)initWithCoder:(NSCoder *)coder {\n'
|
|
' if (self = [super init]) {\n'
|
|
' self.orderId = [coder decodeObjectForKey:@"orderId"];\n'
|
|
' self.receiptData = [coder decodeObjectForKey:@"receiptData"];\n'
|
|
' }\n'
|
|
' return self;\n'
|
|
'}\n'
|
|
'@end\n'
|
|
'@implementation RBCorePenLineData\n'
|
|
'- (void)encodeWithCoder:(NSCoder *)coder {\n'
|
|
' [coder encodeObject:self.lineKey forKey:@"lineKey"];\n'
|
|
' [coder encodeDouble:self.lineWidth forKey:@"lineWidth"];\n'
|
|
'}\n'
|
|
'- (instancetype)initWithCoder:(NSCoder *)coder {\n'
|
|
' if (self = [super init]) {\n'
|
|
' self.lineKey = [coder decodeObjectForKey:@"lineKey"];\n'
|
|
' self.lineWidth = [coder decodeDoubleForKey:@"lineWidth"];\n'
|
|
' }\n'
|
|
' return self;\n'
|
|
'}\n'
|
|
'@end\n'
|
|
'@implementation STSPaintModel\n'
|
|
'+ (BOOL)supportsSecureCoding { return YES; }\n'
|
|
'- (void)encodeWithCoder:(NSCoder *)coder {\n'
|
|
' [coder encodeObject:self.brushName forKey:@"brushName"];\n'
|
|
'}\n'
|
|
'- (instancetype)initWithCoder:(NSCoder *)coder {\n'
|
|
' if (self = [super init]) {\n'
|
|
' self.brushName = [coder decodeObjectForKey:@"brushName"];\n'
|
|
' }\n'
|
|
' return self;\n'
|
|
'}\n'
|
|
'@end\n'
|
|
'@implementation STSOrderTransientNote\n'
|
|
'- (NSString *)renderSummary:(NSString *)tag stepMarker:(NSInteger)marker {\n'
|
|
' return [NSString stringWithFormat:@"%@:%ld", tag, (long)marker];\n'
|
|
'}\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'RDTransientHelper.swift').write_text(
|
|
'import Foundation\n'
|
|
'class RDCodedConfig: NSObject, NSCoding {\n'
|
|
' var endpoint: String\n'
|
|
' init(endpoint: String) { self.endpoint = endpoint }\n'
|
|
' func encode(with coder: NSCoder) { coder.encode(endpoint, forKey: "endpoint") }\n'
|
|
' required init?(coder: NSCoder) {\n'
|
|
' guard let ep = coder.decodeObject(forKey: "endpoint") as? String else { return nil }\n'
|
|
' self.endpoint = ep\n'
|
|
' }\n'
|
|
'}\n'
|
|
'final class RDTransientHelper {\n'
|
|
' func computeSummary() -> String {\n'
|
|
' let n = STSOrderTransientNote()\n'
|
|
' return n.renderSummary("ok", stepMarker: 42)\n'
|
|
' }\n'
|
|
'}\n'
|
|
'@main struct Harness {\n'
|
|
' static func main() {\n'
|
|
' let args = CommandLine.arguments\n'
|
|
' let outDir = URL(fileURLWithPath: args[2])\n'
|
|
' if args[1] == "archive" {\n'
|
|
' let order = STSPayOrderInfoObject()\n'
|
|
' order.orderId = "ORD_991"\n'
|
|
' order.receiptData = "RCPT_XYZ"\n'
|
|
' let d1 = try! NSKeyedArchiver.archivedData(withRootObject: order, requiringSecureCoding: false)\n'
|
|
' try! d1.write(to: outDir.appendingPathComponent("order.dat"))\n'
|
|
' let pen = RBCorePenLineData()\n'
|
|
' pen.lineKey = "PEN_7"\n'
|
|
' pen.lineWidth = 3.25\n'
|
|
' let d2 = try! NSKeyedArchiver.archivedData(withRootObject: pen, requiringSecureCoding: false)\n'
|
|
' try! d2.write(to: outDir.appendingPathComponent("pen.dat"))\n'
|
|
' let paint = STSPaintModel()\n'
|
|
' paint.brushName = "marker_gold"\n'
|
|
' let d3 = try! NSKeyedArchiver.archivedData(withRootObject: paint, requiringSecureCoding: true)\n'
|
|
' try! d3.write(to: outDir.appendingPathComponent("paint.dat"))\n'
|
|
' let cfg = RDCodedConfig(endpoint: "https://api.example.com")\n'
|
|
' let d4 = try! NSKeyedArchiver.archivedData(withRootObject: cfg, requiringSecureCoding: false)\n'
|
|
' try! d4.write(to: outDir.appendingPathComponent("cfg.dat"))\n'
|
|
' } else {\n'
|
|
' let d1 = try! Data(contentsOf: outDir.appendingPathComponent("order.dat"))\n'
|
|
' let order = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d1) as! STSPayOrderInfoObject\n'
|
|
' let d2 = try! Data(contentsOf: outDir.appendingPathComponent("pen.dat"))\n'
|
|
' let pen = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d2) as! RBCorePenLineData\n'
|
|
' let d3 = try! Data(contentsOf: outDir.appendingPathComponent("paint.dat"))\n'
|
|
' let paint = try! NSKeyedUnarchiver.unarchivedObject(ofClass: STSPaintModel.self, from: d3)!\n'
|
|
' let d4 = try! Data(contentsOf: outDir.appendingPathComponent("cfg.dat"))\n'
|
|
' let cfg = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(d4) as! RDCodedConfig\n'
|
|
' let payload: [String: Any] = [\n'
|
|
' "orderId": order.orderId ?? "",\n'
|
|
' "receiptData": order.receiptData ?? "",\n'
|
|
' "lineKey": pen.lineKey ?? "",\n'
|
|
' "lineWidth": pen.lineWidth,\n'
|
|
' "brushName": paint.brushName ?? "",\n'
|
|
' "endpoint": cfg.endpoint,\n'
|
|
' "helper": RDTransientHelper().computeSummary(),\n'
|
|
' "transientCls": NSStringFromClass(STSOrderTransientNote.self),\n'
|
|
' ]\n'
|
|
' let jd = try! JSONSerialization.data(withJSONObject: payload)\n'
|
|
' print(String(data: jd, encoding: .utf8)!)\n'
|
|
' }\n'
|
|
' }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
|
|
archives = root / 'archives'
|
|
archives.mkdir()
|
|
|
|
def compile_binary(out_bin: Path):
|
|
obj = root / 'STSModels.o'
|
|
subprocess.run(
|
|
['xcrun', 'clang', '-fobjc-arc', '-c', str(src / 'STSModels.m'), '-o', str(obj)],
|
|
check=True,
|
|
)
|
|
subprocess.run(
|
|
[
|
|
'xcrun', 'swiftc',
|
|
'-parse-as-library',
|
|
'-module-name', 'AppTest',
|
|
'-import-objc-header', str(src / 'STSModels.h'),
|
|
str(src / 'RDTransientHelper.swift'),
|
|
str(obj),
|
|
'-o', str(out_bin),
|
|
],
|
|
check=True,
|
|
)
|
|
|
|
v1 = root / 'bin_v1'
|
|
compile_binary(v1)
|
|
subprocess.run([str(v1), 'archive', str(archives)], check=True)
|
|
|
|
# Apply obfuscation in-place in isolated root
|
|
subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(dst_obf / 'obfuscate_symbols.py'),
|
|
'--archive-mode',
|
|
'--target-name', 'readoor31',
|
|
'--timestamp', '20261119_unit',
|
|
'--salt', 'm3_unit_seed_01',
|
|
],
|
|
cwd=root,
|
|
check=True,
|
|
)
|
|
|
|
sym_map_p = root / 'obfuscation_maps' / 'symbol_map_readoor31_20261119_unit.json'
|
|
meth_map_p = root / 'obfuscation_maps' / 'method_map_readoor31_20261119_unit.json'
|
|
self.assertTrue(sym_map_p.is_file())
|
|
self.assertTrue(meth_map_p.is_file())
|
|
sym_json = json.loads(sym_map_p.read_text(encoding='utf-8'))
|
|
meth_json = json.loads(meth_map_p.read_text(encoding='utf-8'))
|
|
self.assertEqual(sym_json['schema_version'], 2)
|
|
self.assertEqual(meth_json['schema_version'], 2)
|
|
for kept in ('STSPayOrderInfoObject', 'RBCorePenLineData', 'STSPaintModel', 'RDCodedConfig'):
|
|
self.assertNotIn(kept, sym_json['mappings'])
|
|
self.assertIn('STSOrderTransientNote', sym_json['mappings'])
|
|
self.assertIn('RDTransientHelper', sym_json['mappings'])
|
|
self.assertIn('renderSummary:stepMarker:', meth_json['mappings'])
|
|
self.assertNotRegex(sym_json['mappings']['RDTransientHelper']['obfuscated'], r'^(?:YMH|ymh)[0-9a-f]+$')
|
|
|
|
v2 = root / 'bin_v2'
|
|
compile_binary(v2)
|
|
out_v2 = subprocess.check_output([str(v2), 'unarchive', str(archives)], text=True).strip()
|
|
decoded = json.loads(out_v2)
|
|
self.assertEqual(decoded['orderId'], 'ORD_991')
|
|
self.assertEqual(decoded['receiptData'], 'RCPT_XYZ')
|
|
self.assertEqual(decoded['lineKey'], 'PEN_7')
|
|
self.assertAlmostEqual(decoded['lineWidth'], 3.25)
|
|
self.assertEqual(decoded['brushName'], 'marker_gold')
|
|
self.assertEqual(decoded['endpoint'], 'https://api.example.com')
|
|
self.assertEqual(decoded['helper'], 'ok:42')
|
|
self.assertEqual(
|
|
decoded['transientCls'],
|
|
sym_json['mappings']['STSOrderTransientNote']['obfuscated'],
|
|
)
|
|
|
|
def test_double_backslash_regex_and_override_dynamic_fixes(self):
|
|
self.assertIsNotNone(obf.OBJC_SELECTOR_RE.search('@selector(foo:bar:)'))
|
|
self.assertEqual(obf.OBJC_SELECTOR_RE.search('@selector( submitButtonTap )').group(1), 'submitButtonTap')
|
|
self.assertFalse(obf.is_safe_to_rename_method('customLayoutPass', ' override func customLayoutPass() {'))
|
|
self.assertFalse(obf.is_safe_to_rename_method('observableAction', ' dynamic func observableAction() {'))
|
|
self.assertTrue(obf.is_safe_to_rename_method('computeToken', ' private func computeToken() {'))
|
|
|
|
def test_lexical_scanner_preserves_strings_comments_imports_interpolations(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
dst_obf = self._stage_obf_runtime(root)
|
|
(root / 'STSWorker.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'// RDAlphaService secretNote\n'
|
|
'@interface STSWorker : NSObject\n'
|
|
'- (void)performTask:(NSString *)a withMode:(int)b;\n'
|
|
'- (void)triggerPing;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(root / 'STSWorker.m').write_text(
|
|
'#import "STSWorker.h"\n'
|
|
'// STSWorker triggerPing performTask:withMode:\n'
|
|
'/* class RDAlphaService {} @selector(triggerPing) */\n'
|
|
'@implementation STSWorker\n'
|
|
'- (void)performTask:(NSString *)a withMode:(int)b {\n'
|
|
' NSString *s1 = @"STSWorker triggerPing performTask:withMode:";\n'
|
|
' SEL sel = @selector(triggerPing);\n'
|
|
' SEL sel2 = @selector(performTask:withMode:);\n'
|
|
' if (sel && sel2 && s1) { [self triggerPing]; }\n'
|
|
'}\n'
|
|
'- (void)triggerPing {}\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(root / 'RDAlphaService.swift').write_text(
|
|
'import Foundation\n'
|
|
'import RDAlphaService\n'
|
|
'// RDAlphaService runCore\n'
|
|
'/*\n'
|
|
' class RDAlphaService {}\n'
|
|
' func runCore() {}\n'
|
|
'*/\n'
|
|
'class RDAlphaService {\n'
|
|
' let literal = "RDAlphaService runCore"\n'
|
|
' let multi = """\n'
|
|
' RDAlphaService\n'
|
|
' func runCore() {}\n'
|
|
' """\n'
|
|
' let raw = #"RDAlphaService runCore"#\n'
|
|
' func runCore() -> String {\n'
|
|
' return "prefix-\\(RDAlphaService.helperTag())-RDAlphaService"\n'
|
|
' }\n'
|
|
' static func helperTag() -> String { return "STSWorker" }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(dst_obf / 'obfuscate_symbols.py'),
|
|
'--archive-mode',
|
|
'--target-name', 'readoor31',
|
|
'--timestamp', '20261119_lex',
|
|
'--salt', 'lex_seed_01',
|
|
],
|
|
cwd=root,
|
|
check=True,
|
|
)
|
|
sw_after = (root / 'RDAlphaService.swift').read_text(encoding='utf-8')
|
|
m_after = (root / 'STSWorker.m').read_text(encoding='utf-8')
|
|
sym_map = json.loads((root / 'obfuscation_maps' / 'symbol_map_readoor31_20261119_lex.json').read_text())['mappings']
|
|
meth_map = json.loads((root / 'obfuscation_maps' / 'method_map_readoor31_20261119_lex.json').read_text())['mappings']
|
|
|
|
obf_cls = sym_map['RDAlphaService']['obfuscated']
|
|
obf_worker = sym_map['STSWorker']['obfuscated']
|
|
obf_tag = meth_map['helperTag']['obfuscated']
|
|
obf_ping = meth_map['triggerPing']['obfuscated']
|
|
obf_perf = meth_map['performTask:withMode:']['obfuscated']
|
|
|
|
# Imports, comments, and literals preserved verbatim
|
|
self.assertIn('#import "STSWorker.h"', m_after)
|
|
self.assertIn('// STSWorker triggerPing performTask:withMode:', m_after)
|
|
self.assertIn('/* class RDAlphaService {} @selector(triggerPing) */', m_after)
|
|
self.assertIn('NSString *s1 = @"STSWorker triggerPing performTask:withMode:";', m_after)
|
|
self.assertIn(f'@interface {obf_worker} : NSObject', (root / 'STSWorker.h').read_text())
|
|
self.assertIn(f'@selector({obf_ping})', m_after)
|
|
self.assertIn(f'@selector({obf_perf})', m_after)
|
|
|
|
self.assertIn('import RDAlphaService', sw_after)
|
|
self.assertIn('// RDAlphaService runCore', sw_after)
|
|
self.assertIn(' class RDAlphaService {}', sw_after)
|
|
self.assertIn('let literal = "RDAlphaService runCore"', sw_after)
|
|
self.assertIn(' RDAlphaService\n', sw_after)
|
|
self.assertIn('let raw = #"RDAlphaService runCore"#', sw_after)
|
|
self.assertIn('return "STSWorker"', sw_after)
|
|
# Interpolation code WAS rewritten while trailing literal suffix stayed intact
|
|
self.assertIn(f'return "prefix-\\({obf_cls}.{obf_tag}())-RDAlphaService"', sw_after)
|
|
|
|
def test_natural_camelcase_determinism_self_check_and_source_restore(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
r1 = root / 'r1'
|
|
r2 = root / 'r2'
|
|
r3 = root / 'r3'
|
|
for r in (r1, r2, r3):
|
|
self._stage_obf_runtime(r)
|
|
(r / 'RDSampleBox.swift').write_text(
|
|
'import Foundation\n'
|
|
'final class RDSampleBox {\n'
|
|
' func computeHash() -> Int { return 7 }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
(r / 'STSBoxHelper.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'@interface STSBoxHelper : NSObject\n'
|
|
'- (void)applyRule:(NSString *)r count:(int)c;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(r / 'STSBoxHelper.m').write_text(
|
|
'#import "STSBoxHelper.h"\n'
|
|
'@implementation STSBoxHelper\n'
|
|
'- (void)applyRule:(NSString *)r count:(int)c {}\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
|
|
# Clean self check passes
|
|
res_clean = subprocess.run(
|
|
['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertEqual(res_clean.returncode, 0, res_clean.stdout + res_clean.stderr)
|
|
|
|
orig_swift = (r1 / 'RDSampleBox.swift').read_text(encoding='utf-8')
|
|
orig_objc = (r1 / 'STSBoxHelper.m').read_text(encoding='utf-8')
|
|
|
|
for r, salt in ((r1, 'seed_same'), (r2, 'seed_same'), (r3, 'seed_other')):
|
|
subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(r / 'AutoPacking/obfuscation/obfuscate_symbols.py'),
|
|
'--archive-mode',
|
|
'--target-name', 'readoor31',
|
|
'--timestamp', '20261119_det',
|
|
'--salt', salt,
|
|
],
|
|
cwd=r,
|
|
check=True,
|
|
)
|
|
|
|
m1 = json.loads((r1 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings']
|
|
m2 = json.loads((r2 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings']
|
|
m3 = json.loads((r3 / 'obfuscation_maps/symbol_map_readoor31_20261119_det.json').read_text())['mappings']
|
|
self.assertEqual(m1, m2)
|
|
self.assertNotEqual(m1, m3)
|
|
|
|
# Self-check catches obfuscated natural tokens
|
|
res_obf = subprocess.run(
|
|
['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertNotEqual(res_obf.returncode, 0)
|
|
|
|
# Self-check catches legacy lowercase ymh<hex> too
|
|
(r1 / 'RDSampleBox.swift').write_text('func ymh1234567890() {}\n', encoding='utf-8')
|
|
res_legacy = subprocess.run(
|
|
['bash', str(r1 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r1)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertNotEqual(res_legacy.returncode, 0)
|
|
|
|
# Restore r2 back from obfuscation_maps
|
|
subprocess.run(
|
|
[
|
|
sys.executable,
|
|
str(r2 / 'AutoPacking/obfuscation/obfuscate_symbols.py'),
|
|
'--restore-source-from-map-dir', 'obfuscation_maps',
|
|
],
|
|
cwd=r2,
|
|
check=True,
|
|
)
|
|
self.assertEqual((r2 / 'RDSampleBox.swift').read_text(encoding='utf-8'), orig_swift)
|
|
self.assertEqual((r2 / 'STSBoxHelper.m').read_text(encoding='utf-8'), orig_objc)
|
|
res_restored = subprocess.run(
|
|
['bash', str(r2 / 'AutoPacking/obfuscation/scripts/obfuscation_self_check.sh'), str(r2)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertEqual(res_restored.returncode, 0, res_restored.stdout + res_restored.stderr)
|
|
|
|
def test_v2_crash_restoration_and_l1_to_l2_policy_translation(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
maps = root / 'obfuscation_maps'
|
|
maps.mkdir()
|
|
sym_p = maps / 'symbol_map_readoor31_20261119_t.json'
|
|
meth_p = maps / 'method_map_readoor31_20261119_t.json'
|
|
sym_p.write_text(json.dumps({
|
|
'schema_version': 2,
|
|
'kind': 'symbol_map',
|
|
'target': 'readoor31',
|
|
'timestamp': '20261119_t',
|
|
'seed': 's1',
|
|
'mappings': {
|
|
'RDInjectionDetector': {'obfuscated': 'LumenCipherEngine', 'language': 'swift'},
|
|
'STSJailbreakDetectTool': {'obfuscated': 'CanopyShieldBroker', 'language': 'objc'},
|
|
'STSIAPVerifyHandler': {'obfuscated': 'HarborRelayAgent', 'language': 'objc'},
|
|
},
|
|
}), encoding='utf-8')
|
|
meth_p.write_text(json.dumps({
|
|
'schema_version': 2,
|
|
'kind': 'method_map',
|
|
'target': 'readoor31',
|
|
'timestamp': '20261119_t',
|
|
'seed': 's1',
|
|
'mappings': {
|
|
'hasSuspiciousDyldInsertLibraries': {
|
|
'kind': 'direct_method',
|
|
'token': 'auditCobaltSignal',
|
|
'obfuscated': 'auditCobaltSignal',
|
|
},
|
|
'detectCurrentDeviceIsJailbroken': {
|
|
'kind': 'direct_method',
|
|
'token': 'verifyKestrelPulse',
|
|
'obfuscated': 'verifyKestrelPulse',
|
|
},
|
|
'transactionDidStoreInKeyChainWithTransactionIdentifier:count:': {
|
|
'kind': 'objc_selector',
|
|
'token': 'alignBirchLedger',
|
|
'obfuscated': 'alignBirchLedger:phaseCobalt:',
|
|
'parts': ['alignBirchLedger:', 'phaseCobalt:'],
|
|
'swift_alias': 'alignBirchLedger(_:phaseCobalt:)',
|
|
},
|
|
},
|
|
}), encoding='utf-8')
|
|
|
|
cls_rev, sel_rev = restore_crash_report.load_reverse_maps(sym_p, meth_p)
|
|
restored_objc = restore_crash_report.deobfuscate_symbol_text(
|
|
'-[HarborRelayAgent alignBirchLedger:phaseCobalt:] (in readoor31)',
|
|
cls_rev,
|
|
sel_rev,
|
|
)
|
|
self.assertIn('-[STSIAPVerifyHandler transactionDidStoreInKeyChainWithTransactionIdentifier:count:]', restored_objc)
|
|
restored_swift = restore_crash_report.deobfuscate_symbol_text(
|
|
'LumenCipherEngine.auditCobaltSignal() -> Bool',
|
|
cls_rev,
|
|
sel_rev,
|
|
)
|
|
self.assertIn('RDInjectionDetector.hasSuspiciousDyldInsertLibraries() -> Bool', restored_swift)
|
|
|
|
eff_path, eff_policy = ig_toolchain_resolver.resolve_effective_policy(
|
|
str(ROOT / 'config' / 'ig_llvm_policy.json'),
|
|
root,
|
|
root / 'cache',
|
|
)
|
|
self.assertTrue(Path(eff_path).is_file())
|
|
flat_subs = {r.get('function_contains') for r in eff_policy['flatten_targets'] if r.get('function_contains')}
|
|
self.assertIn('17auditCobaltSignal', flat_subs)
|
|
self.assertIn('verifyKestrelPulse', flat_subs)
|
|
self.assertIn('alignBirchLedger', flat_subs)
|
|
req_map = {r['id']: r for r in eff_policy['required_targets']}
|
|
self.assertIn('17auditCobaltSignal', req_map['swift_rd_injection_dyld_check']['symbol_contains_any'])
|
|
self.assertIn('17LumenCipherEngineC', req_map['swift_rd_injection_dyld_check']['str_symbol_contains_any'])
|
|
|
|
def test_generic_overloads_first_class_func_refs_and_dotted_sdk_types(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
dst_obf = self._stage_obf_runtime(root)
|
|
mock_sdk = root / 'Factorys' / 'MockAuthSDK'
|
|
mock_sdk.mkdir(parents=True)
|
|
(mock_sdk / 'TXCommonHandler.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'@interface TXCommonHandler : NSObject\n'
|
|
'- (void)accelerateLoginPageWithTimeout:(double)timeout;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
src = root / 'Sources'
|
|
src.mkdir()
|
|
(src / 'STSWebServerHandler.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'@interface STSWebServerHandler : NSObject\n'
|
|
'- (void)addHandlerForMethod:(NSString *)method path:(NSString *)path;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'STSWebServerHandler.m').write_text(
|
|
'#import "STSWebServerHandler.h"\n'
|
|
'@implementation STSWebServerHandler\n'
|
|
'- (void)addHandlerForMethod:(NSString *)method path:(NSString *)path {}\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'RDRouterDynamicParamsMapping.h').write_text(
|
|
'#import <Foundation/Foundation.h>\n'
|
|
'@interface RDRouterDynamicParamsMapping : NSObject\n'
|
|
'+ (instancetype)router;\n'
|
|
'- (id)routerGetInstanceWithClassName:(NSString *)className;\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'RDRouterDynamicParamsMapping.m').write_text(
|
|
'#import "RDRouterDynamicParamsMapping.h"\n'
|
|
'@implementation RDRouterDynamicParamsMapping\n'
|
|
'+ (instancetype)router { return [[self alloc] init]; }\n'
|
|
'- (id)routerGetInstanceWithClassName:(NSString *)className { return nil; }\n'
|
|
'@end\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'App-Bridging-Header.h').write_text(
|
|
'#import "STSWebServerHandler.h"\n'
|
|
'#import "RDRouterDynamicParamsMapping.h"\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'Info.plist').write_text(
|
|
'<plist version="1.0"><dict>'
|
|
'<key>UISceneDelegateClassName</key>'
|
|
'<string>$(PRODUCT_MODULE_NAME).RBCoreSceneDelegate</string>'
|
|
'</dict></plist>\n',
|
|
encoding='utf-8',
|
|
)
|
|
|
|
# 同时包含:public struct Configuration(应全局取消混淆 Configuration)、
|
|
# UIButton.Configuration / EncodingError.Context 点号后系统嵌套类型、
|
|
# generic 重载 static func stableIdentifier<Bytes: Sequence>(for:)、
|
|
# 无括号一等公民函数值引用 compactMap(clampedNormalizedRect) / sorted(by: isBeforeInReadingOrder)、
|
|
# 同名局部变量 guard let helperKey 与方法 helperKey() 消歧、
|
|
# public protocol 内方法要求不得重命名。
|
|
(src / 'RDPublicContract.swift').write_text(
|
|
'import Foundation\n'
|
|
'import UIKit\n'
|
|
'public protocol RDPublicStore {\n'
|
|
' func persistItem(_ item: String)\n'
|
|
'}\n'
|
|
'public class RDPublicViewer: UIViewController {\n'
|
|
' public struct Configuration {\n'
|
|
' public var scale: CGFloat = 1.0\n'
|
|
' }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
(src / 'RDEpubPanelHelper.swift').write_text(
|
|
'import Foundation\n'
|
|
'import UIKit\n'
|
|
'import WebKit\n'
|
|
'final class RDEpubPanelHelper {\n'
|
|
' struct Configuration { var label: String }\n'
|
|
' private struct ItemRow { let rank: Int; let text: String }\n'
|
|
' func configureButton() -> UIButton.Configuration {\n'
|
|
' var cfg = UIButton.Configuration.filled()\n'
|
|
' cfg.title = Configuration(label: "x").label\n'
|
|
' return cfg\n'
|
|
' }\n'
|
|
' static func stableIdentifier(for value: String) -> String {\n'
|
|
' stableIdentifier(for: Array(value.utf8))\n'
|
|
' }\n'
|
|
' static func stableIdentifier<Bytes: Sequence>(for bytes: Bytes) -> String where Bytes.Element == UInt8 {\n'
|
|
' var h: UInt64 = 14695981039346656037\n'
|
|
' for b in bytes { h ^= UInt64(b); h &*= 1099511628211 }\n'
|
|
' return String(h, radix: 16)\n'
|
|
' }\n'
|
|
' func sortValues(_ raw: [Int?]) -> [Int] {\n'
|
|
' let clamped = raw.compactMap(clampedRank)\n'
|
|
' let rows = clamped.map { ItemRow(rank: $0, text: RDEpubPanelHelper.stableIdentifier(for: "k")) }\n'
|
|
' return Self.sortRows(rows)\n'
|
|
' }\n'
|
|
' private static func sortRows(_ rows: [ItemRow]) -> [Int] {\n'
|
|
' rows.sorted(by: isBeforeInReadingOrder).map { $0.rank }\n'
|
|
' }\n'
|
|
' private func clampedRank(_ v: Int?) -> Int? { guard let v, v >= 0 else { return nil }; return v }\n'
|
|
' private static func isBeforeInReadingOrder(_ a: ItemRow, _ b: ItemRow) -> Bool { a.rank < b.rank }\n'
|
|
' func resolveKey() -> String {\n'
|
|
' guard let helperKey = Self.buildSecretKey() else { return "" }\n'
|
|
' return consumeKey(helperKey)\n'
|
|
' }\n'
|
|
' private func consumeKey(_ s: String) -> String { s }\n'
|
|
' private static func buildSecretKey() -> String? { "k" }\n'
|
|
'}\n'
|
|
'final class RDLocalKeyHolder {\n'
|
|
' func helperKey() -> String { "other" }\n'
|
|
'}\n'
|
|
'struct Environment { let name: String }\n'
|
|
'enum RDActionRoute { case fetchItem; case payload(Int) }\n'
|
|
'final class RDReflectedService: NSObject {}\n'
|
|
'final class RDEnumAndStdlibProbe {\n'
|
|
' func flatMap<T>(_ transform: (Int) -> T) -> T { transform(1) }\n'
|
|
' static func fetchItem() -> RDActionRoute {\n'
|
|
' _ = [1, 2].flatMap { [$0, $0] }\n'
|
|
' _ = Optional(3).flatMap { $0 + 1 }\n'
|
|
' _ = Environment(name: "prod")\n'
|
|
' _ = NSClassFromString("RDReflectedService")\n'
|
|
' return .payload(computePayload())\n'
|
|
' }\n'
|
|
' private static func computePayload() -> Int { 7 }\n'
|
|
' func callCustomFlatMap() -> Int { flatMap { $0 + 1 } }\n'
|
|
' func removeScriptMessageHandler() {}\n'
|
|
' func tidyWeb(_ c: WKUserContentController) {\n'
|
|
' c.removeScriptMessageHandler(forName: "b")\n'
|
|
' removeScriptMessageHandler()\n'
|
|
' }\n'
|
|
' private func scopedItem(_ v: Int) -> Int? { v > 0 ? v : nil }\n'
|
|
' func checkScoped() -> Int {\n'
|
|
' let pre = scopedItem(1) ?? 0\n'
|
|
' guard let scopedItem = scopedItem(3) else { return pre }\n'
|
|
' return scopedItem + pre\n'
|
|
' }\n'
|
|
' func accelerateLoginPage() {}\n'
|
|
' struct Box<T> { static func snapPhoto(_ flag: Bool) -> Int { flag ? 1 : 0 } }\n'
|
|
' static func snapPhoto() -> Int { RDEnumAndStdlibProbe.Box<UIImage>.snapPhoto(true) }\n'
|
|
' static func navDiagnosticName(_ value: Int) -> String { "\\(value)" }\n'
|
|
' static func checkBridgingAndNewlineFuncValue() -> (String, String, Any?) {\n'
|
|
' let fnBare = navDiagnosticName\n'
|
|
' let fnQualified = RDEnumAndStdlibProbe.navDiagnosticName\n'
|
|
' STSWebServerHandler().add(forMethod: "GET", path: "/")\n'
|
|
' let obj = RDRouterDynamicParamsMapping.router().routerGetInstance(withClassName: "Foo")\n'
|
|
' return (fnBare(1), fnQualified(2), obj)\n'
|
|
' }\n'
|
|
' private let rotateCfg: RDRotateCfg = .defaultConfigure()\n'
|
|
'}\n'
|
|
'class RDRotateCfg {\n'
|
|
' fileprivate class func defaultConfigure() -> RDRotateCfg { RDRotateCfg() }\n'
|
|
'}\n'
|
|
'final class RBCoreSceneDelegate: UIResponder, UIWindowSceneDelegate {}\n',
|
|
encoding='utf-8',
|
|
)
|
|
|
|
subprocess.run(
|
|
[
|
|
'python3', str(dst_obf / 'obfuscate_symbols.py'),
|
|
'--archive-mode',
|
|
'--target-name', 'readoor31',
|
|
'--timestamp', '20261119_ast',
|
|
'--salt', 'm3_ast_seed_01',
|
|
],
|
|
cwd=root, check=True,
|
|
)
|
|
|
|
sym_map = json.loads((root / 'obfuscation_maps/symbol_map_readoor31_20261119_ast.json').read_text())['mappings']
|
|
meth_map = json.loads((root / 'obfuscation_maps/method_map_readoor31_20261119_ast.json').read_text())['mappings']
|
|
# public struct Configuration 不得进入映射;public protocol RDPublicStore.persistItem 不得进入方法映射
|
|
self.assertNotIn('Configuration', sym_map)
|
|
self.assertNotIn('Environment', sym_map)
|
|
self.assertNotIn('RDReflectedService', sym_map)
|
|
self.assertNotIn('persistItem', meth_map)
|
|
self.assertNotIn('flatMap', meth_map)
|
|
self.assertNotIn('fetchItem', meth_map)
|
|
self.assertNotIn('payload', meth_map)
|
|
self.assertNotIn('removeScriptMessageHandler', meth_map)
|
|
self.assertNotIn('accelerateLoginPage', meth_map)
|
|
self.assertIn('RDEpubPanelHelper', sym_map)
|
|
self.assertIn('RDActionRoute', sym_map)
|
|
self.assertIn('RDEnumAndStdlibProbe', sym_map)
|
|
self.assertIn('clampedRank', meth_map)
|
|
self.assertIn('isBeforeInReadingOrder', meth_map)
|
|
self.assertIn('stableIdentifier', meth_map)
|
|
self.assertIn('computePayload', meth_map)
|
|
self.assertIn('scopedItem', meth_map)
|
|
self.assertIn('snapPhoto', meth_map)
|
|
self.assertNotIn('STSWebServerHandler', sym_map)
|
|
self.assertIn('router', meth_map)
|
|
self.assertNotIn('routerGetInstanceWithClassName:', meth_map)
|
|
self.assertNotIn('addHandlerForMethod:path:', meth_map)
|
|
self.assertIn('navDiagnosticName', meth_map)
|
|
self.assertNotIn('RBCoreSceneDelegate', sym_map)
|
|
self.assertIn('defaultConfigure', meth_map)
|
|
|
|
obf_src = (src / 'RDEpubPanelHelper.swift').read_text(encoding='utf-8')
|
|
self.assertIn('UIButton.Configuration.filled()', obf_src)
|
|
self.assertNotIn('clampedRank', obf_src)
|
|
self.assertNotIn('isBeforeInReadingOrder', obf_src)
|
|
self.assertNotIn('stableIdentifier', obf_src)
|
|
self.assertIn('guard let helperKey =', obf_src)
|
|
self.assertIn(f'{meth_map["consumeKey"]["obfuscated"]}(helperKey)', obf_src)
|
|
self.assertIn('.flatMap {', obf_src)
|
|
self.assertIn('Environment(name: "prod")', obf_src)
|
|
self.assertIn(f'.payload({meth_map["computePayload"]["obfuscated"]}())', obf_src)
|
|
obf_scoped = meth_map['scopedItem']['obfuscated']
|
|
self.assertIn(f'let pre = {obf_scoped}(1) ?? 0', obf_src)
|
|
self.assertIn(f'guard let scopedItem = {obf_scoped}(3) else', obf_src)
|
|
self.assertIn('return scopedItem + pre', obf_src)
|
|
obf_box = sym_map['Box']['obfuscated'] if 'Box' in sym_map else 'Box'
|
|
self.assertIn(f'{obf_box}<UIImage>.{meth_map["snapPhoto"]["obfuscated"]}(true)', obf_src)
|
|
obf_nav = meth_map['navDiagnosticName']['obfuscated']
|
|
obf_probe = sym_map['RDEnumAndStdlibProbe']['obfuscated']
|
|
self.assertIn(f'let fnBare = {obf_nav}\n', obf_src)
|
|
self.assertIn(f'let fnQualified = {obf_probe}.{obf_nav}\n', obf_src)
|
|
self.assertIn(f'= .{meth_map["defaultConfigure"]["obfuscated"]}()', obf_src)
|
|
|
|
sdk_path = subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
|
|
subprocess.run(
|
|
[
|
|
'xcrun', '--sdk', 'iphoneos', 'swiftc',
|
|
'-typecheck',
|
|
'-target', 'arm64-apple-ios16.0',
|
|
'-sdk', sdk_path,
|
|
'-import-objc-header', str(src / 'App-Bridging-Header.h'),
|
|
str(src / 'RDPublicContract.swift'),
|
|
str(src / 'RDEpubPanelHelper.swift'),
|
|
],
|
|
check=True,
|
|
)
|
|
|
|
def test_effective_policy_disk_cache_early_return_and_9k_scale(self):
|
|
import time
|
|
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
maps_dir = root / 'obfuscation_maps'
|
|
maps_dir.mkdir(parents=True)
|
|
cache_dir = root / 'cache'
|
|
|
|
sym_entries = {f'RDMockType{i:04d}': {'obfuscated': f'CobaltType{i:04d}', 'language': 'swift'} for i in range(2199)}
|
|
sym_entries['RDInjectionDetector'] = {'obfuscated': 'LumenCipherEngine', 'language': 'swift'}
|
|
meth_entries = {f'mockAction{i:04d}': {'obfuscated': f'traceAction{i:04d}', 'language': 'swift'} for i in range(6799)}
|
|
meth_entries['hasSuspiciousDyldInsertLibraries'] = {'obfuscated': 'auditCobaltSignal', 'language': 'swift'}
|
|
|
|
sym_path = maps_dir / 'symbol_map_readoor31_bench.json'
|
|
meth_path = maps_dir / 'method_map_readoor31_bench.json'
|
|
sym_path.write_text(json.dumps({'schema_version': 2, 'kind': 'symbol_map', 'mappings': sym_entries}), encoding='utf-8')
|
|
meth_path.write_text(json.dumps({'schema_version': 2, 'kind': 'method_map', 'mappings': meth_entries}), encoding='utf-8')
|
|
|
|
policy_src = str(ROOT / 'config' / 'ig_llvm_policy.json')
|
|
t0 = time.perf_counter()
|
|
eff_path, eff_policy = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir)
|
|
cold_s = time.perf_counter() - t0
|
|
|
|
self.assertTrue(eff_policy['l1_translation_active'])
|
|
req_map = {r['id']: r for r in eff_policy['required_targets']}
|
|
self.assertIn('17auditCobaltSignal', req_map['swift_rd_injection_dyld_check']['symbol_contains_any'])
|
|
self.assertIn('17LumenCipherEngineC', req_map['swift_rd_injection_dyld_check']['str_symbol_contains_any'])
|
|
|
|
# Clear in-process sha cache to simulate 1,072 fresh subprocess invocations hitting disk cache
|
|
t1 = time.perf_counter()
|
|
for _ in range(1072):
|
|
ig_toolchain_resolver._MEM_SHA_CACHE.clear()
|
|
p2, pol2 = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir)
|
|
self.assertEqual(p2, eff_path)
|
|
warm_total_s = time.perf_counter() - t1
|
|
total_s = cold_s + warm_total_s
|
|
print(f'[perf] resolve_effective_policy 9k maps: cold={cold_s:.4f}s, 1072_warm={warm_total_s:.4f}s, total_1073={total_s:.4f}s')
|
|
|
|
self.assertLess(cold_s, 0.2)
|
|
self.assertLess(total_s, 2.5)
|
|
self.assertTrue(pol2['l1_translation_active'])
|
|
|
|
# Mutate L1 map -> cache key must invalidate immediately and produce updated translation
|
|
sym_entries['RDInjectionDetector'] = {'obfuscated': 'OspreyBeaconVault', 'language': 'swift'}
|
|
sym_path.write_text(json.dumps({'schema_version': 2, 'kind': 'symbol_map', 'mappings': sym_entries}), encoding='utf-8')
|
|
eff_path2, eff_policy2 = ig_toolchain_resolver.resolve_effective_policy(policy_src, root, cache_dir)
|
|
self.assertNotEqual(eff_path2, eff_path)
|
|
req_map2 = {r['id']: r for r in eff_policy2['required_targets']}
|
|
self.assertIn('17OspreyBeaconVaultC', req_map2['swift_rd_injection_dyld_check']['str_symbol_contains_any'])
|
|
|
|
def test_star_switch_bogus_linear_split_odr_and_macho_gate(self):
|
|
tc = ig_toolchain_resolver.resolve_opt(require_obf=False)
|
|
opt_path = tc.get('opt_path')
|
|
if not opt_path:
|
|
self.skipTest(f"Standalone opt unavailable: {tc.get('warning')}")
|
|
|
|
clang = ig_toolchain_resolver.detect_stock_tool('clang')
|
|
macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
|
|
|
with tempfile.TemporaryDirectory() as td:
|
|
p = Path(td)
|
|
policy_p = p / 'star_policy.json'
|
|
policy_p.write_text(json.dumps({
|
|
'flatten_topology': 'sparse_switch',
|
|
'flatten_bogus_blocks': 2,
|
|
'flatten_split_linear_blocks': True,
|
|
'exempt_path_substrings': [],
|
|
'exempt_function_prefixes': ['__swift_'],
|
|
'string_encrypt_targets': [{'path_contains': 'star_probe'}],
|
|
'flatten_targets': [{'path_contains': 'star_probe'}],
|
|
}), encoding='utf-8')
|
|
|
|
src = p / 'star_probe.cpp'
|
|
src.write_text(
|
|
'#include <stdio.h>\n'
|
|
'#include <stdint.h>\n'
|
|
'static inline __attribute__((always_inline)) uint32_t mix_step(uint32_t v, uint32_t k) {\n'
|
|
' uint32_t x = v ^ k;\n'
|
|
' return (x << 5) | (x >> 27);\n'
|
|
'}\n'
|
|
'__attribute__((noinline)) uint32_t linear_hash(uint32_t a, uint32_t b) {\n'
|
|
' uint32_t acc = a + 0x9e3779b9u;\n'
|
|
' acc = mix_step(acc, b);\n'
|
|
' acc *= 0x85ebca6bu;\n'
|
|
' acc = mix_step(acc, a ^ 0x13572468u);\n'
|
|
' acc += 0xc2b2ae35u;\n'
|
|
' return acc ^ (acc >> 16);\n'
|
|
'}\n'
|
|
'inline uint32_t weak_odr_helper(uint32_t x) { return x * 3u + 1u; }\n'
|
|
'__attribute__((noinline)) int branch_calc(int x, uint32_t (*fn)(uint32_t)) {\n'
|
|
' if (x > 10) return (int)(fn((uint32_t)x) + 7u);\n'
|
|
' if (x < 0) return (int)(linear_hash((uint32_t)(-x), 9u));\n'
|
|
' return (int)linear_hash((uint32_t)x, 3u);\n'
|
|
'}\n'
|
|
'int main(void) {\n'
|
|
' printf("%u|%d|%d\\n", linear_hash(11u, 22u), branch_calc(-3, &weak_odr_helper), branch_calc(12, &weak_odr_helper));\n'
|
|
' return 0;\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
bc_p = p / 'star_probe.bc'
|
|
obf_bc = p / 'star_probe.obf.bc'
|
|
obj_p = p / 'star_probe.o'
|
|
bin_p = p / 'star_probe'
|
|
audit_p = p / 'star.audit.json'
|
|
dsym_p = p / 'star_probe.dSYM'
|
|
|
|
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-g', '-emit-llvm', '-c', str(src), '-o', str(bc_p)], check=True)
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_p}', '--ig-mode=full',
|
|
'--ig-seed=star_unit_seed_1', f'--ig-source-path={src}',
|
|
f'--ig-audit-out={audit_p}', str(bc_p), '-o', str(obf_bc),
|
|
], check=True)
|
|
subprocess.run([
|
|
clang, '-isysroot', macos_sdk, '-Os', '-g',
|
|
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
|
|
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_p),
|
|
], check=True)
|
|
subprocess.run([clang, '-isysroot', macos_sdk, '-g', str(obj_p), '-o', str(bin_p)], check=True)
|
|
subprocess.run(['xcrun', 'dsymutil', str(bin_p), '-o', str(dsym_p)], check=True)
|
|
|
|
audit = json.loads(audit_p.read_text(encoding='utf-8'))
|
|
details = audit.get('functions_flattened_details') or []
|
|
self.assertTrue(details)
|
|
for det in details:
|
|
self.assertEqual(det['topology'], 'sparse_switch', det)
|
|
self.assertNotIn('weak_odr_helper', det['name'])
|
|
self.assertTrue(any('linear_hash' in det['name'] for det in details), details)
|
|
self.assertTrue(any(
|
|
'weak_odr_helper' in sk['name'] and sk['reason'] == 'weak_or_linkonce_odr'
|
|
for sk in (audit.get('functions_skipped') or [])
|
|
), audit.get('functions_skipped'))
|
|
|
|
ref_bin = p / 'star_ref'
|
|
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', str(src), '-o', str(ref_bin)], check=True)
|
|
self.assertEqual(
|
|
subprocess.check_output([str(bin_p)], text=True),
|
|
subprocess.check_output([str(ref_bin)], text=True),
|
|
)
|
|
|
|
dwarf_bin = dsym_p / 'Contents/Resources/DWARF/star_probe'
|
|
gate = verify_macho_star_cfg.verify_binary_star_cfg(
|
|
bin_p,
|
|
dwarf_bin,
|
|
{'module_audits': [{'source_path': str(src), 'functions_flattened_details': details}]},
|
|
require_topology='sparse_switch',
|
|
fail_on_missing=True,
|
|
)
|
|
self.assertEqual(gate['failed_count'], 0)
|
|
self.assertGreaterEqual(gate['verified_star_count'], 3)
|
|
|
|
# Verify Swift multi-TU bitcode pipeline skips compiler-synthesized internal glue
|
|
# (block_copy_helper, *Tm, *CMa) so unflattened UI TUs cannot collide in dSYM.
|
|
swift_frontend = subprocess.check_output(['xcrun', '--sdk', 'macosx', '-f', 'swift-frontend'], text=True).strip()
|
|
swiftc_bin = subprocess.check_output(['xcrun', '--sdk', 'macosx', '-f', 'swiftc'], text=True).strip()
|
|
arch_triple = 'arm64-apple-macosx13.0' if os.uname().machine == 'arm64' else 'x86_64-apple-macosx13.0'
|
|
sw_prot = p / 'ProtectedSvc.swift'
|
|
sw_ui = p / 'UnprotectedUI.swift'
|
|
sw_prot.write_text(
|
|
'import Foundation\n'
|
|
'public final class ProtectedSvc {\n'
|
|
' public var tag: String = "sec"\n'
|
|
' public init() {}\n'
|
|
' @inline(never)\n'
|
|
' public func dispatchWork() {\n'
|
|
' let q = DispatchQueue.main\n'
|
|
' q.async { [weak self] in\n'
|
|
' self?.tag = "done"\n'
|
|
' }\n'
|
|
' }\n'
|
|
' @inline(never)\n'
|
|
' public func compute(v: Int) -> Int {\n'
|
|
' let a = (v &+ 13) &* 7\n'
|
|
' let b = a ^ 0x5a5a\n'
|
|
' return b &- 3\n'
|
|
' }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
sw_ui.write_text(
|
|
'import Foundation\n'
|
|
'public final class UnprotectedUI {\n'
|
|
' public var label: String = "ui"\n'
|
|
' public init() {}\n'
|
|
' @inline(never)\n'
|
|
' public func render() -> Int {\n'
|
|
' let q = DispatchQueue.main\n'
|
|
' q.async { [weak self] in\n'
|
|
' self?.label = "shown"\n'
|
|
' }\n'
|
|
' return label.count\n'
|
|
' }\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
sw_pol = p / 'sw_policy.json'
|
|
sw_pol.write_text(json.dumps({
|
|
'flatten_topology': 'sparse_switch',
|
|
'flatten_bogus_blocks': 2,
|
|
'flatten_split_linear_blocks': True,
|
|
'exempt_path_substrings': [],
|
|
'exempt_function_prefixes': ['__swift_'],
|
|
'string_encrypt_targets': [],
|
|
'flatten_targets': [{'path_contains': 'ProtectedSvc.swift'}],
|
|
}), encoding='utf-8')
|
|
sw_bc1 = p / 'ProtectedSvc.bc'
|
|
sw_bc2 = p / 'UnprotectedUI.bc'
|
|
for cur, other, bc_out in [(sw_prot, sw_ui, sw_bc1), (sw_ui, sw_prot, sw_bc2)]:
|
|
subprocess.run([
|
|
swift_frontend, '-target', arch_triple, '-sdk', macos_sdk,
|
|
'-O', '-g', '-module-name', 'StarSwiftMod',
|
|
'-primary-file', str(cur), str(other),
|
|
'-emit-bc', '-o', str(bc_out),
|
|
], check=True)
|
|
sw_obf1 = p / 'ProtectedSvc.obf.bc'
|
|
sw_aud1 = p / 'ProtectedSvc.audit.json'
|
|
subprocess.run([
|
|
opt_path, '-passes=default<O2>,ig-obfuscate',
|
|
f'--ig-policy={sw_pol}', '--ig-mode=full',
|
|
'--ig-seed=star_sw_unit_1', f'--ig-source-path={sw_prot}',
|
|
f'--ig-audit-out={sw_aud1}', str(sw_bc1), '-o', str(sw_obf1),
|
|
], check=True)
|
|
sw_o1 = p / 'ProtectedSvc.o'
|
|
sw_o2 = p / 'UnprotectedUI.o'
|
|
for b_in, o_out in [(sw_obf1, sw_o1), (sw_bc2, sw_o2)]:
|
|
subprocess.run([
|
|
clang, '-target', arch_triple, '-isysroot', macos_sdk,
|
|
'-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
|
'-x', 'ir', '-c', str(b_in), '-o', str(o_out),
|
|
], check=True)
|
|
sw_bin = p / 'StarSwiftBin'
|
|
sw_dsym = p / 'StarSwiftBin.dSYM'
|
|
subprocess.run([
|
|
swiftc_bin, '-target', arch_triple, '-sdk', macos_sdk,
|
|
'-Xlinker', '-e', '-Xlinker', '__mh_execute_header',
|
|
str(sw_o1), str(sw_o2), '-o', str(sw_bin),
|
|
], check=True)
|
|
subprocess.run(['xcrun', 'dsymutil', str(sw_bin), '-o', str(sw_dsym)], check=True)
|
|
|
|
sw_audit = json.loads(sw_aud1.read_text(encoding='utf-8'))
|
|
sw_flat_names = sw_audit.get('functions_flattened') or []
|
|
self.assertTrue(any('ProtectedSvc' in n and 'compute' in n for n in sw_flat_names), sw_flat_names)
|
|
for forbidden in ('block_copy_helper', 'block_destroy_helper'):
|
|
self.assertFalse(any(forbidden in n for n in sw_flat_names), sw_flat_names)
|
|
self.assertFalse(any(n.endswith(('Tm', 'CMa', 'Wl', 'TA')) for n in sw_flat_names), sw_flat_names)
|
|
if os.uname().machine == 'arm64':
|
|
sw_gate = verify_macho_star_cfg.verify_binary_star_cfg(
|
|
sw_bin,
|
|
sw_dsym / 'Contents/Resources/DWARF/StarSwiftBin',
|
|
{'module_audits': [sw_audit]},
|
|
require_topology='sparse_switch',
|
|
)
|
|
self.assertEqual(sw_gate['failed_count'], 0)
|
|
self.assertGreaterEqual(sw_gate['verified_star_count'], 1)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|