- 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
249 lines
10 KiB
Python
249 lines
10 KiB
Python
"""Unit tests for M2 passes: IGOpaqueConstants and IGArithmetic (Linear MBA)."""
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
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() -> str:
|
|
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 macos_sdk_path() -> str:
|
|
return subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip()
|
|
|
|
|
|
class TestMbaAndOpaqueConstantsPass(unittest.TestCase):
|
|
def test_mba_all_ops_edge_values_and_const_hiding_execution(self):
|
|
opt_path = require_host_opt()
|
|
clang = detect_stock_tool('clang')
|
|
sdk = macos_sdk_path()
|
|
|
|
with tempfile.TemporaryDirectory(prefix='ig-m2-mba-') as td:
|
|
p = Path(td)
|
|
policy_path = p / 'policy.json'
|
|
policy_path.write_text(json.dumps({
|
|
'exempt_path_substrings': [],
|
|
'exempt_function_prefixes': [],
|
|
'opaque_const_max_per_fn': 64,
|
|
'arithmetic_rounds': 2,
|
|
'arithmetic_max_per_fn': 256,
|
|
'opaque_const_targets': [{'path_contains': 'mba_test.c'}],
|
|
'arithmetic_targets': [{'path_contains': 'mba_test.c'}],
|
|
'opaque_const_exempt_functions': ['rd_sd_sha256_transform'],
|
|
'arithmetic_exempt_functions': ['rd_sd_sha256_transform'],
|
|
}), encoding='utf-8')
|
|
|
|
src_c = p / 'mba_test.c'
|
|
src_c.write_text(
|
|
'''#include <stdint.h>
|
|
#include <limits.h>
|
|
#include <stdio.h>
|
|
|
|
__attribute__((noinline))
|
|
uint32_t mba_ops32(uint32_t x, uint32_t y) {
|
|
uint32_t a = x + y;
|
|
uint32_t b = a - (y ^ 0xA55A3C19u);
|
|
uint32_t c = (b ^ x) | (a & 0x5A3C96E1u);
|
|
uint32_t d = (c + 0x13579BDFu) & (b + 1u);
|
|
if (d == 0x2468ACE0u) {
|
|
return d ^ 0x77777777u;
|
|
}
|
|
return a ^ b ^ c ^ d ^ 0xCAFEBABEu;
|
|
}
|
|
|
|
__attribute__((noinline))
|
|
uint64_t mba_ops64(uint64_t x, uint64_t y) {
|
|
uint64_t a = x + y;
|
|
uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL);
|
|
uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL);
|
|
uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL);
|
|
return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL;
|
|
}
|
|
|
|
__attribute__((noinline))
|
|
uint32_t rd_sd_sha256_transform(uint32_t x, uint32_t y) {
|
|
return (x + y) ^ 0x428A2F98u;
|
|
}
|
|
|
|
__attribute__((noinline))
|
|
static uint32_t ref_ops32(uint32_t x, uint32_t y) {
|
|
uint32_t a = x + y;
|
|
uint32_t b = a - (y ^ 0xA55A3C19u);
|
|
uint32_t c = (b ^ x) | (a & 0x5A3C96E1u);
|
|
uint32_t d = (c + 0x13579BDFu) & (b + 1u);
|
|
if (d == 0x2468ACE0u) {
|
|
return d ^ 0x77777777u;
|
|
}
|
|
return a ^ b ^ c ^ d ^ 0xCAFEBABEu;
|
|
}
|
|
|
|
__attribute__((noinline))
|
|
static uint64_t ref_ops64(uint64_t x, uint64_t y) {
|
|
uint64_t a = x + y;
|
|
uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL);
|
|
uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL);
|
|
uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL);
|
|
return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL;
|
|
}
|
|
|
|
int main(void) {
|
|
const uint32_t vals32[] = {
|
|
0u, 1u, 2u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu,
|
|
0x12345678u, 0xA55A3C19u, 0x5A3C96E1u, 0xCAFEBABEu
|
|
};
|
|
const uint64_t vals64[] = {
|
|
0ULL, 1ULL, 2ULL, 0x7FFFFFFFFFFFFFFFULL, 0x8000000000000000ULL,
|
|
0xFFFFFFFFFFFFFFFFULL, 0xA5C3F10E7B2D4968ULL, 0x0123456789ABCDEFULL
|
|
};
|
|
size_t n32 = sizeof(vals32) / sizeof(vals32[0]);
|
|
for (size_t i = 0; i < n32; ++i) {
|
|
for (size_t j = 0; j < n32; ++j) {
|
|
if (mba_ops32(vals32[i], vals32[j]) != ref_ops32(vals32[i], vals32[j])) {
|
|
fprintf(stderr, "32-bit mismatch at %zu,%zu\\n", i, j);
|
|
return 2;
|
|
}
|
|
}
|
|
}
|
|
size_t n64 = sizeof(vals64) / sizeof(vals64[0]);
|
|
for (size_t i = 0; i < n64; ++i) {
|
|
for (size_t j = 0; j < n64; ++j) {
|
|
if (mba_ops64(vals64[i], vals64[j]) != ref_ops64(vals64[i], vals64[j])) {
|
|
fprintf(stderr, "64-bit mismatch at %zu,%zu\\n", i, j);
|
|
return 3;
|
|
}
|
|
}
|
|
}
|
|
if (rd_sd_sha256_transform(17u, 29u) != ((17u + 29u) ^ 0x428A2F98u)) {
|
|
return 4;
|
|
}
|
|
return 0;
|
|
}
|
|
''',
|
|
encoding='utf-8',
|
|
)
|
|
bc_p = p / 'mba.bc'
|
|
subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p)], check=True)
|
|
|
|
def compile_mode(tag: str, seed: str, pass_filter: str):
|
|
obf_bc = p / f'{tag}.obf.bc'
|
|
obj_o = p / f'{tag}.o'
|
|
aud_p = p / f'{tag}.audit.json'
|
|
exe_p = p / f'{tag}.exe'
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_path}',
|
|
'--ig-mode=full',
|
|
f'--ig-pass-filter={pass_filter}',
|
|
f'--ig-seed={seed}',
|
|
f'--ig-source-path={src_c}',
|
|
f'--ig-audit-out={aud_p}',
|
|
str(bc_p), '-o', str(obf_bc),
|
|
], check=True)
|
|
subprocess.run([
|
|
clang, '-isysroot', sdk, '-O2',
|
|
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
|
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
|
], check=True)
|
|
subprocess.run([clang, '-isysroot', sdk, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p)], check=True)
|
|
return obj_o, exe_p, json.loads(aud_p.read_text(encoding='utf-8'))
|
|
|
|
o_a1, exe_a1, aud_a1 = compile_mode('a1', 'seed_m2_1', 'all')
|
|
o_a2, _, _ = compile_mode('a2', 'seed_m2_1', 'all')
|
|
o_b1, exe_b1, aud_b1 = compile_mode('b1', 'seed_m2_2', 'all')
|
|
_, exe_const, aud_const = compile_mode('const_only', 'seed_m2_1', 'const')
|
|
_, exe_arith, aud_arith = compile_mode('arith_only', 'seed_m2_1', 'arith')
|
|
|
|
# Determinism and seed polymorphism
|
|
self.assertEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_a2.read_bytes()).hexdigest())
|
|
self.assertNotEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_b1.read_bytes()).hexdigest())
|
|
|
|
# Pass filter isolation & exemptions
|
|
self.assertGreaterEqual(aud_a1['opaque_constants_count'], 4)
|
|
self.assertGreaterEqual(aud_a1['arithmetic_rewrites_count'], 8)
|
|
self.assertEqual(aud_const['arithmetic_rewrites_count'], 0)
|
|
self.assertEqual(aud_const['functions_flattened'], [])
|
|
self.assertEqual(aud_arith['opaque_constants_count'], 0)
|
|
self.assertEqual(aud_arith['functions_flattened'], [])
|
|
self.assertNotIn('rd_sd_sha256_transform', aud_a1['opaque_constants_functions'])
|
|
self.assertNotIn('rd_sd_sha256_transform', aud_a1['arithmetic_functions'])
|
|
|
|
# Execute obfuscated arm64 binaries to confirm 100% bit-exact arithmetic equivalence
|
|
for exe in (exe_a1, exe_b1, exe_const, exe_arith):
|
|
self.assertEqual(subprocess.run([str(exe)]).returncode, 0, f'{exe} execution failed')
|
|
|
|
# Verify plaintext magic constants disappeared from mba_ops32 / mba_ops64 disassembly
|
|
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True)
|
|
m32_dis = dis.split('<_mba_ops32>:', 1)[1].split('<_mba_ops64>:', 1)[0].lower()
|
|
for needle in ('a55a', '3c19', 'babe'):
|
|
self.assertNotIn(needle, m32_dis)
|
|
m64_dis = dis.split('<_mba_ops64>:', 1)[1].split('<_rd_sd_sha256_transform>:', 1)[0].lower()
|
|
for needle in ('7b2d', '4968', 'fedc'):
|
|
self.assertNotIn(needle, m64_dis)
|
|
|
|
def test_sd_keybox_real_file_with_m2_passes(self):
|
|
opt_path = require_host_opt()
|
|
clang = detect_stock_tool('clang')
|
|
sdk = macos_sdk_path()
|
|
keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c'
|
|
defender_dir = ROOT / 'defender'
|
|
policy_path = ROOT / 'config/ig_llvm_policy.json'
|
|
|
|
with tempfile.TemporaryDirectory(prefix='ig-m2-kb-') as td:
|
|
p = Path(td)
|
|
raw_bc = p / 'RDSDKeyBox.bc'
|
|
obf_bc = p / 'RDSDKeyBox.obf.bc'
|
|
aud_p = p / 'audit.json'
|
|
obj_o = p / 'RDSDKeyBox.o'
|
|
subprocess.run([
|
|
clang, '-isysroot', 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)
|
|
subprocess.run([
|
|
opt_path, '-passes=ig-obfuscate',
|
|
f'--ig-policy={policy_path}',
|
|
'--ig-mode=full',
|
|
'--ig-pass-filter=all',
|
|
'--ig-seed=m2_kb_test_seed',
|
|
f'--ig-source-path={keybox_c}',
|
|
f'--ig-audit-out={aud_p}',
|
|
str(raw_bc), '-o', str(obf_bc),
|
|
], check=True)
|
|
subprocess.run([
|
|
clang, '-isysroot', sdk, '-Os',
|
|
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
|
|
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
|
|
], check=True)
|
|
aud = json.loads(aud_p.read_text(encoding='utf-8'))
|
|
self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 10, aud)
|
|
self.assertGreaterEqual(aud.get('arithmetic_rewrites_count', 0), 10, aud)
|
|
self.assertNotIn('_rd_sd_sha256_transform', aud.get('arithmetic_functions', []))
|
|
self.assertNotIn('rd_sd_sha256_transform', aud.get('arithmetic_functions', []))
|
|
self.assertNotIn('rd_sd_md5_hex', aud.get('arithmetic_functions', []))
|
|
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True)
|
|
# 0xA55A3C19 should not appear as literal immediate operands in non-exempt _rd_sd_sha256_init
|
|
init_dis = dis.split('<_rd_sd_sha256_init>:', 1)[1].split('<_rd_sd_sha256_update>:', 1)[0].lower()
|
|
self.assertNotIn('0x3c19', init_dis)
|
|
self.assertNotIn('0xa55a', init_dis)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|