feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固

- 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
This commit is contained in:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+460
View File
@@ -0,0 +1,460 @@
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'
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 TestIndirectCallPass(unittest.TestCase):
def test_c_same_tu_cross_tu_dead_strip_and_dylib_safety(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-c-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'string_encrypt_targets': [{'path_contains': 'caller.c'}],
'indirect_call_targets': [{'path_contains': 'caller.c'}],
'indirect_call_same_image_prefixes': ['rd_ext_'],
'flatten_targets': [{'path_contains': 'caller.c'}],
}), encoding='utf-8')
(p / 'ext_callee.c').write_text(
'int rd_ext_compute(int a, int b) {\n'
' return (a * 3) + (b ^ 0x11);\n'
'}\n'
'int rd_ext_unused(int x) {\n'
' return x * 999;\n'
'}\n',
encoding='utf-8',
)
(p / 'caller.c').write_text(
'#include <stdlib.h>\n'
'#include <unistd.h>\n'
'extern int rd_ext_compute(int a, int b);\n'
'__attribute__((noinline)) static int local_step(int v) {\n'
' return v + 19;\n'
'}\n'
'__attribute__((noinline)) int run_pipeline(int x) {\n'
' const char *env = getenv("IG_NONEXISTENT_ENV_TEST");\n'
' int pid_bit = (getpid() > 0) ? 1 : 0;\n'
' int a = local_step(x + pid_bit);\n'
' int b = rd_ext_compute(a, env ? 7 : 5);\n'
' return local_step(b);\n'
'}\n'
'int main(void) {\n'
' int got = run_pipeline(10);\n'
' return (got == 129) ? 0 : 2;\n'
'}\n',
encoding='utf-8',
)
# Verify expected math: pid_bit=1 -> a=local_step(11)=30 -> b=30*3+(5^0x11)=90+20=110 -> local_step(110)=129
subprocess.run([clang, '-isysroot', sdk, '-O2', '-c', str(p / 'ext_callee.c'), '-o', str(p / 'ext.o')], check=True)
subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(p / 'caller.c'), '-o', str(p / 'caller.bc')], check=True)
def build_with(seed: str, pass_filter: str, tag: str):
obf_bc = p / f'caller_{tag}.bc'
obj_o = p / f'caller_{tag}.o'
audit_p = p / f'audit_{tag}.json'
exe_p = p / f'exe_{tag}'
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={p / "caller.c"}',
f'--ig-audit-out={audit_p}',
str(p / 'caller.bc'), '-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), str(p / 'ext.o'),
'-Wl,-dead_strip', '-o', str(exe_p),
], check=True)
return obj_o, exe_p, json.loads(audit_p.read_text(encoding='utf-8'))
o_a1, exe_a1, aud_a1 = build_with('seed_alpha', 'all', 'a1')
o_a2, _, aud_a2 = build_with('seed_alpha', 'all', 'a2')
o_b1, exe_b1, aud_b1 = build_with('seed_beta', 'all', 'b1')
_, exe_icall, aud_icall = build_with('seed_alpha', 'icall', 'icall_only')
_, _, aud_str = build_with('seed_alpha', 'str', 'str_only')
# Determinism & 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())
self.assertEqual(aud_a1['indirect_calls_count'], 4) # 2x local_step + 1x rd_ext_compute + 1x main->run_pipeline
self.assertEqual(aud_a2['indirect_calls_count'], 4)
self.assertEqual(aud_b1['indirect_calls_count'], 4)
# Pass filter isolation
self.assertEqual(aud_icall['indirect_calls_count'], 4)
self.assertEqual(aud_icall['strings_encrypted_count'], 0)
self.assertEqual(len(aud_icall['functions_flattened']), 0)
self.assertEqual(aud_str['indirect_calls_count'], 0)
# Runtime execution on host arm64
for exe in (exe_a1, exe_b1, exe_icall):
rc = subprocess.run([str(exe)]).returncode
self.assertEqual(rc, 0)
# Disassembly & dead_strip checks
nm_exe = subprocess.check_output(['xcrun', 'nm', str(exe_a1)], text=True)
self.assertIn('_rd_ext_compute', nm_exe)
self.assertNotIn('_rd_ext_unused', nm_exe) # dead_strip still strips unreferenced function
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*_rd_ext_compute\b', dis))
self.assertIsNone(re.search(r'\bbl\s+.*_local_step\b', dis))
self.assertIsNone(re.search(r'\bbl\s+.*_run_pipeline\b', dis))
self.assertIsNotNone(re.search(r'\bblr\s+x\d+\b', dis))
def test_objc_arc_attachedcall_rv_preservation(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-arc-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'indirect_call_targets': [{'path_contains': 'arc_caller.m'}],
'indirect_call_same_image_prefixes': ['rd_arc_'],
'flatten_targets': [{'path_contains': 'arc_caller.m'}],
}), encoding='utf-8')
(p / 'arc_provider.m').write_text(
'#import <Foundation/Foundation.h>\n'
'NSString *rd_arc_make_token(int idx) {\n'
' return [NSString stringWithFormat:@"tok_%d_ok", idx ^ 0x2a];\n'
'}\n',
encoding='utf-8',
)
(p / 'arc_caller.m').write_text(
'#import <Foundation/Foundation.h>\n'
'extern NSString *rd_arc_make_token(int idx);\n'
'__attribute__((noinline)) static NSUInteger verify_batch(int n) {\n'
' NSUInteger total = 0;\n'
' for (int i = 0; i < n; ++i) {\n'
' NSString *s = rd_arc_make_token(i);\n'
' total += s.length;\n'
' }\n'
' return total;\n'
'}\n'
'int main(void) {\n'
' @autoreleasepool {\n'
' NSUInteger got = verify_batch(500);\n'
' return (got > 3000) ? 0 : 3;\n'
' }\n'
'}\n',
encoding='utf-8',
)
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-c', str(p / 'arc_provider.m'), '-o', str(p / 'prov.o')], check=True)
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(p / 'arc_caller.m'), '-o', str(p / 'caller.bc')], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-seed=arc_seed_1',
f'--ig-source-path={p / "arc_caller.m"}',
f'--ig-audit-out={p / "audit.json"}',
str(p / 'caller.bc'), '-o', str(p / 'caller.obf.bc'),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-O2',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(p / 'caller.obf.bc'), '-o', str(p / 'caller.o'),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-framework', 'Foundation',
str(p / 'caller.o'), str(p / 'prov.o'), '-Wl,-dead_strip', '-o', str(p / 'arc_exe'),
], check=True)
audit = json.loads((p / 'audit.json').read_text(encoding='utf-8'))
self.assertGreaterEqual(audit['indirect_calls_count'], 2)
rc = subprocess.run([str(p / 'arc_exe')]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'arc_exe')], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*_rd_arc_make_token\b', dis))
def test_swift_cross_file_throws_and_extension_indirect_calls(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
swiftc = detect_stock_tool('swiftc')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-swift-') as td:
p = Path(td).resolve()
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'indirect_call_targets': [{'path_contains': '.swift'}],
'flatten_targets': [{'path_contains': '.swift'}],
}), encoding='utf-8')
(p / 'Callee.swift').write_text(
'import Foundation\n'
'enum DemoErr: Error { case bad }\n'
'public struct KeyWorker {\n'
' @inline(never)\n'
' public static func derive(_ x: Int) throws -> Int {\n'
' if x < 0 { throw DemoErr.bad }\n'
' return (x * 7) ^ 0x33\n'
' }\n'
'}\n',
encoding='utf-8',
)
(p / 'ExtOnly.swift').write_text(
'import Foundation\n'
'extension NSString {\n'
' @inline(never)\n'
' func callModuleWorker(_ v: Int) -> Int {\n'
' return ((try? KeyWorker.derive(v)) ?? -1) + self.length\n'
' }\n'
'}\n',
encoding='utf-8',
)
(p / 'Main.swift').write_text(
'import Foundation\n'
'@main\n'
'struct Runner {\n'
' static func main() {\n'
' let s: NSString = "hello"\n'
' let r1 = s.callModuleWorker(6)\n'
' let r2 = (try? KeyWorker.derive(-3)) ?? 99\n'
' if r1 != ((42 ^ 0x33) + 5) || r2 != 99 {\n'
' exit(4)\n'
' }\n'
' }\n'
'}\n',
encoding='utf-8',
)
# Compile multi-file Swift module with -lto=llvm-thin to produce per-file bitcode just like Xcode Release
ofm = {
str(p / 'Callee.swift'): {'object': str(p / 'Callee.bc')},
str(p / 'ExtOnly.swift'): {'object': str(p / 'ExtOnly.bc')},
str(p / 'Main.swift'): {'object': str(p / 'Main.bc')},
}
(p / 'ofm.json').write_text(json.dumps(ofm), encoding='utf-8')
subprocess.run([
swiftc, '-sdk', sdk, '-module-name', 'IcallDemoApp',
'-O', '-whole-module-optimization', '-num-threads', '3',
'-g', '-lto=llvm-thin', '-parse-as-library',
'-output-file-map', str(p / 'ofm.json'),
'-c', str(p / 'Callee.swift'), str(p / 'ExtOnly.swift'), str(p / 'Main.swift'),
], cwd=p, check=True)
objs = []
audits = {}
for stem in ('Callee', 'ExtOnly', 'Main'):
bc_p = p / f'{stem}.bc'
obf_bc = p / f'{stem}.obf.bc'
obj_o = p / f'{stem}.o'
aud_p = p / f'{stem}.audit.json'
subprocess.run([
opt_path, '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-seed=swift_icall_seed',
f'--ig-source-path={p / (stem + ".swift")}',
'--ig-swift-module=IcallDemoApp',
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)
objs.append(str(obj_o))
audits[stem] = json.loads(aud_p.read_text(encoding='utf-8'))
subprocess.run([
swiftc, '-sdk', sdk, *objs, '-Xlinker', '-dead_strip', '-o', str(p / 'swift_exe'),
], check=True)
# Both ExtOnly.swift (extension-only file!) and Main.swift must indirect-call cross-file Swift targets
self.assertGreaterEqual(audits['ExtOnly']['indirect_calls_count'], 1)
self.assertGreaterEqual(audits['Main']['indirect_calls_count'], 2)
rc = subprocess.run([str(p / 'swift_exe')]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'swift_exe')], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*KeyWorker.*derive', dis))
self.assertIsNone(re.search(r'\bbl\s+.*callModuleWorker', dis))
def test_source_path_scrubbing_pass(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-scrub-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'scrub_path_substrings': ['/tmp/ig-ipa-work/', '/Users/shenlei/', '/src/readoor/'],
'string_encrypt_targets': [{'path_contains': 'TargetFile.c'}],
'indirect_call_targets': [],
'flatten_targets': [],
}), encoding='utf-8')
(p / 'TargetFile.c').write_text(
'#include <stdio.h>\n'
'const char *get_paths(int idx) {\n'
' static const char *const kPaths[] = {\n'
' "/tmp/ig-ipa-work/src/readoor/3.0/Secret.swift",\n'
' "/Users/shenlei/Work/Secret.m",\n'
' "./readoor/BookView/Reader.swift",\n'
' "readoorApp/OnlyFile.swift",\n'
' "KEEP_NON_PATH_TOKEN",\n'
' };\n'
' return kPaths[idx % 5];\n'
'}\n'
'int main(void) {\n'
' puts(get_paths(0));\n'
' puts(get_paths(3));\n'
' puts(get_paths(4));\n'
' return 0;\n'
'}\n',
encoding='utf-8',
)
bc_p = p / 'TargetFile.bc'
obf_bc = p / 'TargetFile.obf.bc'
obj_o = p / 'TargetFile.o'
audit_p = p / 'scrub.audit.json'
subprocess.run([clang, '-isysroot', sdk, '-O2', '-emit-llvm', '-c', str(p / 'TargetFile.c'), '-o', str(bc_p)], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-pass-filter=all',
'--ig-seed=scrub_seed_1',
'--ig-source-path=TargetFile.c',
'--ig-swift-module=readoorApp',
f'--ig-audit-out={audit_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', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
audit = json.loads(audit_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(audit.get('paths_scrubbed_count', 0), 4, audit)
obj_raw = obj_o.read_bytes()
for leaked in (b'/tmp/ig-ipa-work/', b'/Users/shenlei/', b'Secret.swift', b'OnlyFile.swift'):
self.assertNotIn(leaked, obj_raw)
self.assertIn(b'ig_p_', obj_raw)
def test_indirect_call_dual_table_mode(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-dual-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'indirect_call_targets': [{'path_contains': 'dual_icall.c'}],
'indirect_call_same_image_prefixes': ['dt_'],
'indirect_call_dual_table': True,
}), encoding='utf-8')
src_c = p / 'dual_icall.c'
src_c.write_text(
'''#include <stdint.h>
__attribute__((noinline))
int dt_helper_add(int a, int b) { return a + b + 3; }
__attribute__((noinline))
int dt_helper_mul(int a, int b) { return a * b ^ 0x17; }
int main(void) {
int x = dt_helper_add(5, 9);
int y = dt_helper_mul(x, 4);
if (x != 17 || y != (68 ^ 0x17)) return 1;
return 0;
}
''',
encoding='utf-8',
)
bc_p = p / 'dual_icall.bc'
obf_ll = p / 'dual_icall.obf.ll'
obj_o = p / 'dual_icall.o'
exe_p = p / 'dual_icall_exe'
audit_p = p / 'dual_icall.audit.json'
subprocess.run([clang, '-isysroot', sdk, '-O2', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p)], check=True)
subprocess.run([
opt_path, '-S', '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-seed=dual_table_seed_1',
f'--ig-source-path={src_c}',
f'--ig-audit-out={audit_p}',
str(bc_p), '-o', str(obf_ll),
], check=True)
ir_txt = obf_ll.read_text(encoding='utf-8')
audit = json.loads(audit_p.read_text(encoding='utf-8'))
self.assertTrue(audit.get('indirect_call_dual_table'), audit)
self.assertGreaterEqual(audit.get('indirect_calls_count', 0), 2, audit)
self.assertIn('__ig_cs1_', ir_txt)
self.assertIn('__ig_cs2_', ir_txt)
self.assertNotIn('__ig_ct_', ir_txt)
subprocess.run([
clang, '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_o),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p),
], check=True)
rc = subprocess.run([str(exe_p)]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_p)], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_add', dis), dis)
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_mul', dis), dis)
if __name__ == '__main__':
unittest.main()