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
+355
View File
@@ -0,0 +1,355 @@
"""Unit tests for M6: ObjC CFConstantString, Swift String, multi-fn memcpy stack decrypt, and string replace rules."""
import json
from pathlib import Path
import struct
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()
def iphoneos_sdk_path() -> str:
return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
class TestObjCSwiftStringEncryption(unittest.TestCase):
def test_objc_cfconstantstring_ascii_utf16_phi_and_ios_link(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk_host = macos_sdk_path()
sdk_ios = iphoneos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m6-objcstr-') 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': 'objc_str.m'}],
'string_encrypt_objc_targets': [
{'path_contains': 'objc_str.m', 'function_contains': 'obf_'}
],
}), encoding='utf-8')
src_m = p / 'objc_str.m'
src_m.write_text(
'''#import <Foundation/Foundation.h>
__attribute__((noinline))
NSString *obf_ascii_tok(void) {
return @"OBJC_SECRET_ASCII_TOKEN";
}
__attribute__((noinline))
NSString *obf_utf16_tok(void) {
return @"OBJC_中文密钥_UTF16";
}
__attribute__((noinline))
NSString *obf_branch_tok(int flag) {
NSString *s = nil;
if (flag > 0) {
s = @"OBJC_PHI_TRUE_KEY";
} else {
s = @"OBJC_PHI_FALSE_KEY";
}
return [s copy];
}
__attribute__((noinline))
NSString *untouched_fn(void) {
return @"OBJC_UNTOUCHED_OK";
}
int main(void) {
@autoreleasepool {
NSString *a = obf_ascii_tok();
NSString *u = obf_utf16_tok();
NSString *bt = obf_branch_tok(1);
NSString *bf = obf_branch_tok(0);
NSString *ut = untouched_fn();
NSDictionary *dict = @{ a: @10, u: @20, bt: @30 };
if (![a isEqualToString:[@"OBJC_SECRET_ASCII_" stringByAppendingString:@"TOKEN"]] || a.length != 23) return 1;
const unichar encoded_u[] = {
'O'^1,'B'^1,'J'^1,'C'^1,'_'^1,0x4E2D^1,0x6587^1,0x5BC6^1,0x94A5^1,'_'^1,'U'^1,'T'^1,'F'^1,'1'^1,'6'^1
};
volatile unichar mask = 1;
unichar expected_u[15];
for (int i = 0; i < 15; ++i) expected_u[i] = encoded_u[i] ^ mask;
NSString *expU = [NSString stringWithCharacters:expected_u length:15];
if (![u isEqualToString:expU] || u.length != 15) return 2;
if ([dict[a] intValue] != 10 || [dict[u] intValue] != 20 || [dict[bt] intValue] != 30) return 3;
if (![bt hasSuffix:@"TRUE_KEY"] || ![bf hasSuffix:@"FALSE_KEY"]) return 4;
if (![ut isEqualToString:@"OBJC_UNTOUCHED_OK"]) return 5;
}
return 0;
}
''',
encoding='utf-8',
)
# Host macOS compile, verify IR/binary bytes & run
bc_h = p / 'objc_h.bc'
obf_ll = p / 'objc_h.obf.ll'
obj_h = p / 'objc_h.o'
exe_h = p / 'objc_h_exe'
aud_p = p / 'objc_h.audit.json'
subprocess.run([clang, '-isysroot', sdk_host, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_h)], check=True)
subprocess.run([
opt_path, '-S', '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_1',
f'--ig-source-path={src_m}', f'--ig-audit-out={aud_p}',
str(bc_h), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(aud.get('objc_strings_encrypted_count', 0), 4, aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertIn('@__ig_dec_cf_', ir_txt)
subprocess.run([
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_h),
], check=True)
obj_raw = obj_h.read_bytes()
for needle in (b'OBJC_SECRET_ASCII_TOKEN', b'OBJC_PHI_TRUE_KEY', b'OBJC_PHI_FALSE_KEY'):
self.assertNotIn(needle, obj_raw)
self.assertNotIn('中文密钥'.encode('utf-16-le'), obj_raw)
self.assertIn(b'OBJC_UNTOUCHED_OK', obj_raw)
subprocess.run([clang, '-isysroot', sdk_host, '-framework', 'Foundation', '-Wl,-dead_strip', str(obj_h), '-o', str(exe_h)], check=True)
self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0)
# iOS arm64 link verification
bc_i = p / 'objc_i.bc'
obf_i = p / 'objc_i.obf.bc'
obj_i = p / 'objc_i.o'
dylib_i = p / 'libobjc_i.dylib'
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_i)], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_ios',
f'--ig-source-path={src_m}', f'--ig-audit-out={p / "objc_i.audit.json"}',
str(bc_i), '-o', str(obf_i),
], check=True)
subprocess.run([
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
'-x', 'ir', '-c', str(obf_i), '-o', str(obj_i),
], check=True)
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-dynamiclib', str(obj_i), '-framework', 'Foundation', '-Wl,-dead_strip', '-o', str(dylib_i)], check=True)
def test_swift_large_immortal_and_small_string_encryption(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
swiftc = detect_stock_tool('swiftc')
sdk_host = macos_sdk_path()
sdk_ios = iphoneos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m6-swiftstr-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': ['__ig_', 'llvm.', '__swift_'],
'string_encrypt_targets': [{'path_contains': 'sw_str.swift'}],
'string_encrypt_swift_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}],
'opaque_const_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}],
'opaque_const_max_per_fn': 64,
}), encoding='utf-8')
src_sw = p / 'sw_str.swift'
src_sw.write_text(
'''import Foundation
@inline(never)
public func secretBranch(_ flag: Bool) -> String {
let s: String
if flag {
s = "SWIFT_IMMORTAL_BRANCH_ALPHA_01"
} else {
s = "SWIFT_IMMORTAL_BRANCH_BETA_002"
}
return s
}
@inline(never)
public func secretUtf8AndSmall(_ v: Int) -> (String, String) {
let large = "SWIFT_中文密钥_LARGE_IMMORTAL_888"
let small = "SML_KEY_1234"
return v > 0 ? (large, small) : (small, large)
}
@main
struct Runner {
static func main() {
let a = secretBranch(true)
let b = secretBranch(false)
let (l, s) = secretUtf8AndSmall(1)
let dict = [a: 11, b: 22, l: 33, s: 44]
let ns: NSString = a as NSString
if a.count != 30 || ns.length != 30 || dict[a] != 11 || dict[b] != 22 { exit(1) }
if !a.hasSuffix("ALPHA_01") || !b.hasSuffix("BETA_002") { exit(2) }
if dict[l] != 33 || dict[s] != 44 || s.count != 12 { exit(3) }
if !l.contains("中文密钥") || !s.hasPrefix("SML_KEY_") { exit(4) }
}
}
''',
encoding='utf-8',
)
bc_h = p / 'sw_h.bc'
obf_ll = p / 'sw_h.obf.ll'
obj_h = p / 'sw_h.o'
exe_h = p / 'sw_h_exe'
aud_p = p / 'sw_h.audit.json'
subprocess.run([swiftc, '-sdk', sdk_host, '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(src_sw), '-o', str(bc_h)], check=True)
subprocess.run([
opt_path, '-S', '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_1',
f'--ig-source-path={src_sw}', f'--ig-audit-out={aud_p}',
str(bc_h), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(aud.get('swift_strings_encrypted_count', 0), 3, aud)
self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 1, aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertIn('@__ig_dec_sw_', ir_txt)
subprocess.run([
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_h),
], check=True)
obj_raw = obj_h.read_bytes()
for needle in (b'SWIFT_IMMORTAL_BRANCH_ALPHA_01', b'SWIFT_IMMORTAL_BRANCH_BETA_002', 'SWIFT_中文密钥_LARGE_IMMORTAL_888'.encode('utf-8')):
self.assertNotIn(needle, obj_raw)
# Packed small-string i64 word "SML_KEY_" must be obfuscated away
small_qword = struct.pack('<Q', int.from_bytes(b'SML_KEY_', 'little'))
self.assertNotIn(small_qword, obj_raw)
subprocess.run([swiftc, '-sdk', sdk_host, str(obj_h), '-Xlinker', '-dead_strip', '-o', str(exe_h)], check=True)
self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0)
# Verify iOS arm64 link compatibility
bc_i = p / 'sw_i.bc'
obf_i = p / 'sw_i.obf.bc'
obj_i = p / 'sw_i.o'
subprocess.run([swiftc, '-sdk', sdk_ios, '-target', 'arm64-apple-ios15.0', '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(src_sw), '-o', str(bc_i)], check=True)
subprocess.run([
opt_path, '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_ios',
f'--ig-source-path={src_sw}', f'--ig-audit-out={p / "sw_i.audit.json"}',
str(bc_i), '-o', str(obf_i),
], check=True)
subprocess.run([
clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module',
'-x', 'ir', '-c', str(obf_i), '-o', str(obj_i),
], check=True)
subprocess.run([swiftc, '-sdk', sdk_ios, '-target', 'arm64-apple-ios15.0', '-emit-library', str(obj_i), '-Xlinker', '-dead_strip', '-o', str(p / 'libsw_i.dylib')], check=True)
def test_stack_decrypt_memcpy_multifn_and_string_replace(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk_host = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m6-stackrep-') 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': 'stack_rep.c'}],
'string_encrypt_stack_targets': [{'path_contains': 'stack_rep.c'}],
'string_encrypt_stack_max_len': 64,
'string_replace_rules': [{'exact': 'REPLACE_ME_SECRET_99', 'replace': 'CLEANED'}],
}), encoding='utf-8')
src_c = p / 'stack_rep.c'
src_c.write_text(
'''#include <string.h>
__attribute__((noinline))
int copy_shared_a(char *out) {
memcpy(out, "MULTI_FN_STACK_TOKEN", 21);
return 1;
}
__attribute__((noinline))
int copy_shared_b(const char *probe) {
return strcmp(probe, "MULTI_FN_STACK_TOKEN") == 0;
}
__attribute__((noinline))
int read_replaced(char *out) {
memcpy(out, "REPLACE_ME_SECRET_99", 21);
return 1;
}
int main(void) {
char buf1[32] = {0};
char buf2[32] = {0};
copy_shared_a(buf1);
if (!copy_shared_b(buf1)) return 1;
read_replaced(buf2);
if (strcmp(buf2, "CLEANED") != 0) return 2;
return 0;
}
''',
encoding='utf-8',
)
bc_p = p / 'stack_rep.bc'
obf_ll = p / 'stack_rep.obf.ll'
obj_o = p / 'stack_rep.o'
exe_p = p / 'stack_rep_exe'
aud_p = p / 'stack_rep.audit.json'
subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-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=str', '--ig-seed=m6_stackrep_1',
f'--ig-source-path={src_c}', f'--ig-audit-out={aud_p}',
str(bc_p), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertEqual(aud.get('strings_replaced_count'), 1, aud)
self.assertGreaterEqual(aud.get('strings_stack_encrypted_count'), 2, aud)
self.assertEqual(aud.get('strings_encrypted_count'), aud.get('strings_stack_encrypted_count'), aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertNotIn('.ig.buf.', ir_txt)
self.assertNotIn('REPLACE_ME_SECRET_99', ir_txt)
self.assertNotIn('MULTI_FN_STACK_TOKEN', ir_txt)
self.assertNotIn('CLEANED', ir_txt)
self.assertIn('store volatile i8 0,', ir_txt)
subprocess.run([
clang, '-isysroot', sdk_host, '-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_host, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p)], check=True)
self.assertEqual(subprocess.run([str(exe_p)]).returncode, 0)
if __name__ == '__main__':
unittest.main()