- 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
235 lines
11 KiB
Python
235 lines
11 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
|
|
|
|
|
|
class TestLLVMObfM1(unittest.TestCase):
|
|
def test_polymorphic_flattening_topologies_encodings_and_inline_asm_skip(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()
|
|
|
|
with tempfile.TemporaryDirectory() as td:
|
|
p = Path(td)
|
|
policy_p = p / 'policy.json'
|
|
policy_p.write_text(json.dumps({
|
|
'exempt_path_substrings': [],
|
|
'exempt_function_prefixes': [],
|
|
'string_encrypt_targets': [],
|
|
'flatten_targets': [{'path_contains': 'poly_test.c'}],
|
|
}), encoding='utf-8')
|
|
|
|
src = p / 'poly_test.c'
|
|
src.write_text(
|
|
'#include <stdio.h>\n'
|
|
'#include <stdint.h>\n'
|
|
'__attribute__((noinline)) int leaf_fn(int a, int b) { return a * 17 + b * 31; }\n'
|
|
'int poly_multi_branch(int x, int y) {\n'
|
|
' int acc = 7;\n'
|
|
' if (x & 1) acc += leaf_fn(x, 1);\n'
|
|
' if (x & 2) acc ^= leaf_fn(y, 2);\n'
|
|
' if (x & 4) acc += leaf_fn(x + y, 3);\n'
|
|
' if (x & 8) acc -= leaf_fn(y - x, 4);\n'
|
|
' if (x > 12) acc += leaf_fn(x, y);\n'
|
|
' if (y < 0) acc ^= 0x5A5A;\n'
|
|
' if (acc > 200) acc -= 19;\n'
|
|
' return acc;\n'
|
|
'}\n'
|
|
'int has_inline_asm(int v) {\n'
|
|
' int out = v;\n'
|
|
' if (v > 3) { __asm__ volatile("" : "+r"(out)); }\n'
|
|
' return out + 1;\n'
|
|
'}\n'
|
|
'int main(void) {\n'
|
|
' uint32_t h = 2166136261u;\n'
|
|
' for (int x = -4; x < 24; ++x) {\n'
|
|
' for (int y = -3; y < 5; ++y) {\n'
|
|
' uint32_t v = (uint32_t)poly_multi_branch(x, y);\n'
|
|
' h = (h ^ v) * 16777619u;\n'
|
|
' }\n'
|
|
' }\n'
|
|
' printf("HASH=%08x ASM=%d\\n", h, has_inline_asm(5));\n'
|
|
' return 0;\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
bc_p = p / 'poly.bc'
|
|
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-g', '-emit-llvm', '-c', str(src), '-o', str(bc_p)], check=True)
|
|
|
|
# Reference un-obfuscated output
|
|
ref_bin = p / 'poly_ref'
|
|
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', str(src), '-o', str(ref_bin)], check=True)
|
|
ref_out = subprocess.check_output([str(ref_bin)], text=True).strip()
|
|
|
|
seen_topos = set()
|
|
seen_encs = set()
|
|
asm_skip_seen = False
|
|
|
|
for idx in range(24):
|
|
seed = f'm1_poly_probe_{idx}'
|
|
obf_bc = p / f'poly_{idx}.obf.bc'
|
|
obj_o = p / f'poly_{idx}.o'
|
|
bin_p = p / f'poly_{idx}'
|
|
audit_p = p / f'audit_{idx}.json'
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_p}', '--ig-mode=full',
|
|
f'--ig-seed={seed}', f'--ig-source-path={src}',
|
|
f'--ig-audit-out={audit_p}', str(bc_p), '-o', str(obf_bc),
|
|
], check=True)
|
|
audit = json.loads(audit_p.read_text(encoding='utf-8'))
|
|
for det in audit.get('functions_flattened_details') or []:
|
|
if 'poly_multi_branch' in det['name']:
|
|
seen_topos.add(det['topology'])
|
|
seen_encs.add(det['encoding'])
|
|
for sk in audit.get('functions_skipped') or []:
|
|
if 'has_inline_asm' in sk['name'] and sk['reason'] == 'inline_asm':
|
|
asm_skip_seen = True
|
|
|
|
# Execute every topology/encoding variant and check exact semantic output!
|
|
subprocess.run([
|
|
clang, '-isysroot', macos_sdk, '-Os',
|
|
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
|
|
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
|
], check=True)
|
|
subprocess.run([clang, '-isysroot', macos_sdk, str(obj_o), '-o', str(bin_p)], check=True)
|
|
out = subprocess.check_output([str(bin_p)], text=True).strip()
|
|
self.assertEqual(out, ref_out, f'Semantic mismatch on seed={seed}: {out} vs {ref_out}')
|
|
|
|
self.assertEqual(seen_topos, {'sparse_switch', 'cascaded_subdisp', 'asymmetric_cmp_tree'}, f'Missing topologies: {seen_topos}')
|
|
self.assertEqual(seen_encs, {'xor_rot', 'odd_affine_mul', 'add_xor'}, f'Missing encodings: {seen_encs}')
|
|
self.assertTrue(asm_skip_seen, 'Expected inline_asm skip reason for has_inline_asm')
|
|
|
|
def test_epub_keybox_derivation_obfuscation_and_poisoning(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/RDEpubKeyBox.c'
|
|
keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.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() as td:
|
|
p = Path(td)
|
|
kb_bc = p / 'RDEpubKeyBox.bc'
|
|
kb_obf_bc = p / 'RDEpubKeyBox.obf.bc'
|
|
kb_o = p / 'RDEpubKeyBox.o'
|
|
audit_p = p / 'kb.audit.json'
|
|
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(kb_bc),
|
|
], check=True)
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_path}', '--ig-mode=full',
|
|
'--ig-seed=m1_unit_kb_seed', f'--ig-source-path={keybox_c}',
|
|
f'--ig-audit-out={audit_p}', str(kb_bc), '-o', str(kb_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(kb_obf_bc), '-o', str(kb_o),
|
|
], check=True)
|
|
|
|
audit = json.loads(audit_p.read_text(encoding='utf-8'))
|
|
self.assertGreaterEqual(audit['strings_encrypted_count'], 2, audit)
|
|
self.assertGreaterEqual(len(audit['functions_flattened']), 2, audit)
|
|
self.assertTrue(audit['functions_flattened_details'])
|
|
|
|
raw_o = kb_o.read_bytes()
|
|
self.assertNotIn(b'startiasoft', raw_o)
|
|
self.assertNotIn(b'_rdep_', raw_o)
|
|
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(kb_o)], text=True)
|
|
self.assertNotIn('_CC_MD5', nm_u)
|
|
|
|
harness_c = p / 'harness.c'
|
|
harness_c.write_text(
|
|
'#include <stdio.h>\n'
|
|
'#include <string.h>\n'
|
|
'#include "RDEpubKeyBox.h"\n'
|
|
'#include "poison/IGPoison.h"\n'
|
|
'int main(void) {\n'
|
|
' char out[512];\n'
|
|
' const char *books[] = {"", "BK2026", "book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};\n'
|
|
' for (int i = 0; i < 3; ++i) {\n'
|
|
' size_t n = rd_epub_derive_book_key(books[i], strlen(books[i]), out, sizeof(out));\n'
|
|
' printf("BOOK|%d|%zu|%s\\n", i, n, out);\n'
|
|
' }\n'
|
|
' const char *imgs[] = {"", "fig1.jpg", "章节图_01_45678901234567890123456789012345678901234567890.png"};\n'
|
|
' for (int i = 0; i < 3; ++i) {\n'
|
|
' size_t n = rd_epub_derive_media_key(imgs[i], strlen(imgs[i]), out, sizeof(out));\n'
|
|
' printf("MEDIA|%d|%zu|%s\\n", i, n, out);\n'
|
|
' }\n'
|
|
' size_t pn = rd_epub_legacy_url_prefix(out, sizeof(out));\n'
|
|
' printf("PREFIX|%zu|%s\\n", pn, out);\n'
|
|
' ig_poison_mark(0x1122334455667788ULL);\n'
|
|
' size_t bn = rd_epub_derive_book_key("BK2026", 6, out, sizeof(out));\n'
|
|
' printf("POISON_BOOK|%zu|", bn);\n'
|
|
' for (size_t k = 0; k < bn; ++k) printf("%02x", (unsigned char)out[k]);\n'
|
|
' printf("\\n");\n'
|
|
' return 0;\n'
|
|
'}\n',
|
|
encoding='utf-8',
|
|
)
|
|
bin_p = 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(kb_o), '-o', str(bin_p),
|
|
], check=True)
|
|
lines = subprocess.check_output([str(bin_p)], text=True).splitlines()
|
|
salt = 'startiasoft'
|
|
books = ['', 'BK2026', 'book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']
|
|
imgs = ['', 'fig1.jpg', '章节图_01_45678901234567890123456789012345678901234567890.png']
|
|
expected_bk = None
|
|
for line in lines:
|
|
parts = line.split('|')
|
|
if parts[0] == 'BOOK':
|
|
i = int(parts[1])
|
|
exp = (salt + books[i]) * 2
|
|
self.assertEqual(int(parts[2]), len(exp))
|
|
self.assertEqual(parts[3], exp)
|
|
if i == 1:
|
|
expected_bk = exp.encode('utf-8').hex()
|
|
elif parts[0] == 'MEDIA':
|
|
i = int(parts[1])
|
|
digest = hashlib.md5((imgs[i] + salt).encode('utf-8')).hexdigest()
|
|
exp = (salt + digest) * 2
|
|
self.assertEqual(int(parts[2]), len(exp))
|
|
self.assertEqual(parts[3], exp)
|
|
elif parts[0] == 'PREFIX':
|
|
self.assertEqual(int(parts[1]), 6)
|
|
self.assertEqual(parts[2], '_rdep_')
|
|
elif parts[0] == 'POISON_BOOK':
|
|
self.assertNotEqual(parts[2], expected_bk)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|