- 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
252 lines
12 KiB
Python
252 lines
12 KiB
Python
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
|
|
APP_REPO = ROOT / 'readoor-test'
|
|
|
|
sys.path.insert(0, str(TOOLS_LLVM_OBF))
|
|
|
|
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
|
|
|
|
|
|
def require_host_opt():
|
|
tc = resolve_opt(require_obf=False)
|
|
opt_path = tc.get('opt_path')
|
|
if not opt_path:
|
|
raise unittest.SkipTest(f"Standalone opt not built yet: {tc.get('warning')}")
|
|
return opt_path
|
|
|
|
|
|
def sha256_bytes(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def file_sha256(path: Path) -> str:
|
|
return sha256_bytes(path.read_bytes())
|
|
|
|
|
|
class TestLLVMObfM2(unittest.TestCase):
|
|
def test_m2_policy_and_diag_events_config(self):
|
|
diag_path = ROOT / 'config' / 'ig_diag_events.json'
|
|
policy_path = ROOT / 'config' / 'ig_llvm_policy.json'
|
|
diag = json.loads(diag_path.read_text(encoding='utf-8'))
|
|
policy = json.loads(policy_path.read_text(encoding='utf-8'))
|
|
|
|
events = diag.get('events') or {}
|
|
expected_codes = (
|
|
[f'E-41{i:02d}' for i in range(1, 12)]
|
|
+ [f'E-51{i:02d}' for i in range(1, 37)]
|
|
+ [f'E-519{i}' for i in range(1, 5)]
|
|
+ [f'E-61{i:02d}' for i in range(1, 13)]
|
|
)
|
|
missing = [c for c in expected_codes if c not in events]
|
|
self.assertEqual(missing, [], f'Missing M2 diagnostic codes in ig_diag_events.json: {missing}')
|
|
|
|
required_ids = {t.get('id') for t in (policy.get('required_targets') or [])}
|
|
expected_req = {
|
|
'c_rd_sd_keybox',
|
|
'swift_sd_key_manager',
|
|
'swift_sd_signer',
|
|
'swift_iap_handler',
|
|
'objc_iap_verify_handler',
|
|
}
|
|
self.assertTrue(expected_req.issubset(required_ids), f'Missing required_targets: {expected_req - required_ids}')
|
|
|
|
def test_sd_keybox_obfuscation_derivation_and_seed_polymorphism(self):
|
|
opt_path = require_host_opt()
|
|
clang = detect_stock_tool('clang')
|
|
macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
|
|
|
keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c'
|
|
keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.h'
|
|
defender_dir = ROOT / 'defender'
|
|
poison_c = defender_dir / 'poison/IGPoison.c'
|
|
policy_path = ROOT / 'config/ig_llvm_policy.json'
|
|
self.assertTrue(keybox_c.is_file() and keybox_h.is_file())
|
|
|
|
with tempfile.TemporaryDirectory(prefix='ig-m2-unit-') as td:
|
|
p = Path(td)
|
|
raw_bc = p / 'RDSDKeyBox.bc'
|
|
subprocess.run([
|
|
clang, '-isysroot', macos_sdk, '-Os', '-g', '-fvisibility=hidden',
|
|
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
|
|
'-I', str(keybox_c.parent),
|
|
'-emit-llvm', '-c', str(keybox_c), '-o', str(raw_bc),
|
|
], check=True)
|
|
|
|
def compile_variant(tag: str, seed: str):
|
|
obf_bc = p / f'{tag}.obf.bc'
|
|
obj_o = p / f'{tag}.o'
|
|
audit_p = p / f'{tag}.audit.json'
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_path}',
|
|
'--ig-mode=full',
|
|
'--ig-pass-filter=all',
|
|
f'--ig-seed={seed}',
|
|
f'--ig-source-path={keybox_c}',
|
|
f'--ig-audit-out={audit_p}',
|
|
str(raw_bc), '-o', str(obf_bc),
|
|
], check=True)
|
|
subprocess.run([
|
|
clang, '-isysroot', macos_sdk, '-Os',
|
|
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
|
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
|
], check=True)
|
|
disasm = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True)
|
|
return {
|
|
'obf_bc': obf_bc,
|
|
'obj_o': obj_o,
|
|
'obf_bc_sha256': file_sha256(obf_bc),
|
|
'obj_sha256': file_sha256(obj_o),
|
|
'text_disasm_sha256': sha256_bytes(disasm.encode('utf-8')),
|
|
'audit': json.loads(audit_p.read_text(encoding='utf-8')),
|
|
}
|
|
|
|
unit = compile_variant('unit', 'm2_unit_kb_seed')
|
|
audit = unit['audit']
|
|
self.assertGreaterEqual(audit.get('strings_encrypted_count', 0), 6, audit)
|
|
flattened = audit.get('functions_flattened') or []
|
|
self.assertGreaterEqual(len(flattened), 6, audit)
|
|
self.assertTrue(any('rd_sd_derive_aes256_key' in name for name in flattened), audit)
|
|
self.assertTrue(any('rd_sd_derive_v31_seed' in name for name in flattened), audit)
|
|
self.assertTrue(any('rd_sd_derive_v31_dt_pwd' in name for name in flattened), audit)
|
|
|
|
raw_o = unit['obj_o'].read_bytes()
|
|
for leaked in (
|
|
b'readoor_sd_v32',
|
|
b'KSDPrivateKeyPEM',
|
|
b'rd_net_cfg_v1',
|
|
b'rd_glyph_lut_v2',
|
|
b'encrypted_private_key',
|
|
b'cn.touchv.payment.models.keychain',
|
|
b'7ARrksiF7AoWXXBlmxfz9suSmTka7A',
|
|
):
|
|
self.assertNotIn(leaked, raw_o, f'Plaintext {leaked!r} leaked into RDSDKeyBox.o')
|
|
|
|
harness_c = p / 'harness.c'
|
|
harness_c.write_text(
|
|
'#include <stdio.h>\n'
|
|
'#include <stdint.h>\n'
|
|
'#include <string.h>\n'
|
|
'#include "RDSDKeyBox.h"\n'
|
|
'#include "poison/IGPoison.h"\n'
|
|
'int main(void) {\n'
|
|
' uint8_t key[32];\n'
|
|
' int null_rc = rd_sd_derive_aes256_key(NULL);\n'
|
|
' int ok_rc = rd_sd_derive_aes256_key(key);\n'
|
|
' printf("DERIVE|%d|%d|", null_rc, ok_rc);\n'
|
|
' for (size_t i = 0; i < sizeof(key); ++i) printf("%02x", key[i]);\n'
|
|
' printf("\\n");\n'
|
|
' char buf[128];\n'
|
|
' size_t n_slot = rd_sd_keychain_slot_name(buf, sizeof(buf));\n'
|
|
' printf("SLOT|%zu|%s\\n", n_slot, buf);\n'
|
|
' size_t n_stem = rd_sd_bundle_asset_stem(buf, sizeof(buf));\n'
|
|
' printf("STEM|%zu|%s\\n", n_stem, buf);\n'
|
|
' size_t n_acct = rd_iap_keychain_account_name(buf, sizeof(buf));\n'
|
|
' printf("ACCT|%zu|%s\\n", n_acct, buf);\n'
|
|
' size_t n_v31 = rd_sd_derive_v31_seed(buf, sizeof(buf));\n'
|
|
' printf("V31SEED|%zu|%s\\n", n_v31, buf);\n'
|
|
' const char *nonce = "n1234567890";\n'
|
|
' const char *suffix = "1700000000000GUID_V1iOS";\n'
|
|
' size_t n_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), buf, sizeof(buf));\n'
|
|
' printf("V31DT|%zu|%s\\n", n_dt, buf);\n'
|
|
' printf("SMALL|%zu|%zu|%zu\\n",\n'
|
|
' rd_sd_keychain_slot_name(NULL, 10),\n'
|
|
' rd_sd_bundle_asset_stem(buf, 0),\n'
|
|
' rd_iap_keychain_account_name(buf, 4));\n'
|
|
' ig_poison_mark(0xCAFEBABE12345678ULL);\n'
|
|
' char pbuf[64], pdt[64];\n'
|
|
' size_t pn_v31 = rd_sd_derive_v31_seed(pbuf, sizeof(pbuf));\n'
|
|
' size_t pn_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), pdt, sizeof(pdt));\n'
|
|
' printf("PV31SEED|%zu|%zu|%s\\n", pn_v31, strlen(pbuf), strcmp(pbuf, "7ARrksiF7AoWXXBlmxfz9suSmTka7A") != 0 ? "CHANGED" : "SAME");\n'
|
|
' printf("PV31DT|%zu|%s\\n", pn_dt, pdt);\n'
|
|
' return 0;\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
runner = p / 'kb_runner'
|
|
subprocess.run([
|
|
clang, '-isysroot', macos_sdk, '-Os',
|
|
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
|
|
'-I', str(keybox_c.parent),
|
|
str(harness_c),
|
|
str(poison_c),
|
|
str(defender_dir / 'resolve/IGResolve.c'),
|
|
str(defender_dir / 'anti_hook/IGAntiHook.c'),
|
|
str(defender_dir / 'dispatch/IGDispatch.c'),
|
|
str(unit['obj_o']),
|
|
'-framework', 'Security', '-framework', 'CoreFoundation',
|
|
'-o', str(runner),
|
|
], check=True)
|
|
lines = subprocess.check_output([str(runner)], text=True).splitlines()
|
|
expected_key = hashlib.pbkdf2_hmac(
|
|
'sha256',
|
|
b'readoor_sd_v32_ci_key_2026',
|
|
b'readoor_sd_v32_salt_fixed',
|
|
100_000,
|
|
32,
|
|
).hex()
|
|
expected_v31_seed = '7ARrksiF7AoWXXBlmxfz9suSmTka7A'
|
|
expected_v31_dt = hashlib.md5(
|
|
('n1234567890' + expected_v31_seed + '1700000000000GUID_V1iOS').encode('utf-8')
|
|
).hexdigest()
|
|
|
|
seen_tags = set()
|
|
for line in lines:
|
|
parts = line.split('|')
|
|
seen_tags.add(parts[0])
|
|
if parts[0] == 'DERIVE':
|
|
self.assertEqual(parts[1], '-1')
|
|
self.assertEqual(parts[2], '0')
|
|
self.assertEqual(parts[3], expected_key)
|
|
elif parts[0] == 'SLOT':
|
|
self.assertEqual(int(parts[1]), 16)
|
|
self.assertEqual(parts[2], 'KSDPrivateKeyPEM')
|
|
elif parts[0] == 'STEM':
|
|
self.assertEqual(int(parts[1]), 15)
|
|
self.assertEqual(parts[2], 'rd_glyph_lut_v2')
|
|
elif parts[0] == 'ACCT':
|
|
self.assertEqual(int(parts[1]), 33)
|
|
self.assertEqual(parts[2], 'cn.touchv.payment.models.keychain')
|
|
elif parts[0] == 'V31SEED':
|
|
self.assertEqual(int(parts[1]), 30)
|
|
self.assertEqual(parts[2], expected_v31_seed)
|
|
elif parts[0] == 'V31DT':
|
|
self.assertEqual(int(parts[1]), 32)
|
|
self.assertEqual(parts[2], expected_v31_dt)
|
|
elif parts[0] == 'PV31SEED':
|
|
self.assertEqual(parts[1], '30')
|
|
self.assertEqual(parts[2], '30')
|
|
self.assertEqual(parts[3], 'CHANGED')
|
|
elif parts[0] == 'PV31DT':
|
|
self.assertEqual(parts[1], '32')
|
|
self.assertEqual(len(parts[2]), 32)
|
|
self.assertNotEqual(parts[2], expected_v31_dt)
|
|
elif parts[0] == 'SMALL':
|
|
self.assertEqual(parts[1:], ['0', '0', '0'])
|
|
self.assertEqual(
|
|
seen_tags,
|
|
{'DERIVE', 'SLOT', 'STEM', 'ACCT', 'V31SEED', 'V31DT', 'PV31SEED', 'PV31DT', 'SMALL'},
|
|
)
|
|
|
|
# Same-seed determinism & cross-seed polymorphism
|
|
det_a = compile_variant('det_a', 'm2_seed_alpha')
|
|
det_b = compile_variant('det_b', 'm2_seed_alpha')
|
|
self.assertEqual(det_a['obf_bc_sha256'], det_b['obf_bc_sha256'])
|
|
self.assertEqual(det_a['obj_sha256'], det_b['obj_sha256'])
|
|
|
|
seeds = ['m2_seed_alpha', 'm2_seed_beta', 'm2_seed_gamma']
|
|
variants = {s: compile_variant(f'seed_{s}', s) for s in seeds}
|
|
self.assertEqual(len({variants[s]['text_disasm_sha256'] for s in seeds}), len(seeds))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|