"""Unit tests for M9: nonlinear MBA, table-free OpaqueZero, IGBasicBlockSplit, and per-rule overrides.""" 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 TestM9NonlinearAndBBSplitPass(unittest.TestCase): def test_nonlinear_mba_32_and_64_bit_exact_and_mul_survives(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-m9-nlmba-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'arithmetic_rounds': 1, 'arithmetic_max_per_fn': 64, 'arithmetic_targets': [ { 'id': 'nl_test', 'path_contains': 'nlmba.c', 'function_contains': 'nl_ops', 'nonlinear_mba': True, 'rounds': 1, 'max_per_fn': 64, 'probability': 100, } ], }), encoding='utf-8') src_c = p / 'nlmba.c' src_c.write_text( '''#include #include #include __attribute__((noinline)) uint32_t nl_ops32(uint32_t x, uint32_t y) { uint32_t s = x + y; uint32_t d = s - (y ^ 0xA55A3C19u); uint32_t m = (d ^ x) & (s | 0x5A3C96E1u); uint32_t o = m | (d + 0x13579BDFu); return s ^ d ^ m ^ o; } __attribute__((noinline)) uint64_t nl_ops64(uint64_t x, uint64_t y) { uint64_t s = x + y; uint64_t d = s - (y ^ 0xA5C3F10E7B2D4968ULL); uint64_t m = (d ^ x) & (s | 0x0F1E2D3C4B5A6978ULL); uint64_t o = m | (d + 0x0102030405060708ULL); return s ^ d ^ m ^ o; } __attribute__((noinline)) static uint32_t ref_ops32(uint32_t x, uint32_t y) { uint32_t s = x + y; uint32_t d = s - (y ^ 0xA55A3C19u); uint32_t m = (d ^ x) & (s | 0x5A3C96E1u); uint32_t o = m | (d + 0x13579BDFu); return s ^ d ^ m ^ o; } __attribute__((noinline)) static uint64_t ref_ops64(uint64_t x, uint64_t y) { uint64_t s = x + y; uint64_t d = s - (y ^ 0xA5C3F10E7B2D4968ULL); uint64_t m = (d ^ x) & (s | 0x0F1E2D3C4B5A6978ULL); uint64_t o = m | (d + 0x0102030405060708ULL); return s ^ d ^ m ^ o; } int main(void) { const uint32_t v32[] = {0u, 1u, 0xFFFFFFFFu, (uint32_t)INT32_MIN, (uint32_t)INT32_MAX, 0x12345678u, 0x80000001u}; const uint64_t v64[] = {0ULL, 1ULL, UINT64_MAX, (uint64_t)INT64_MIN, (uint64_t)INT64_MAX, 0xDEADBEEFCAFEBABEULL}; for (unsigned i = 0; i < sizeof(v32) / sizeof(v32[0]); ++i) { for (unsigned j = 0; j < sizeof(v32) / sizeof(v32[0]); ++j) { if (nl_ops32(v32[i], v32[j]) != ref_ops32(v32[i], v32[j])) return 1; } } for (unsigned i = 0; i < sizeof(v64) / sizeof(v64[0]); ++i) { for (unsigned j = 0; j < sizeof(v64) / sizeof(v64[0]); ++j) { if (nl_ops64(v64[i], v64[j]) != ref_ops64(v64[i], v64[j])) return 2; } } uint64_t state = 0x9E3779B97F4A7C15ULL; for (int k = 0; k < 200; ++k) { state = state * 6364136223846793005ULL + 1442695040888963407ULL; uint64_t y = (state >> 17) ^ (state << 29); if (nl_ops64(state, y) != ref_ops64(state, y)) return 3; if (nl_ops32((uint32_t)state, (uint32_t)y) != ref_ops32((uint32_t)state, (uint32_t)y)) return 4; } return 0; } ''', encoding='utf-8', ) bc_h = p / 'nl_h.bc' obf_h = p / 'nl_h.obf.bc' obj_h = p / 'nl_h.o' exe_h = p / 'nl_h_exe' aud_h = p / 'nl_h.audit.json' subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_nl_1', f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', str(bc_h), '-o', str(obf_h), ], check=True) audit = json.loads(aud_h.read_text(encoding='utf-8')) self.assertGreaterEqual(audit['nonlinear_mba_count'], 5) subprocess.run([ clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_h), '-o', str(obj_h), ], check=True) subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) rc = subprocess.run([str(exe_h)]).returncode self.assertEqual(rc, 0) # iOS arm64 check + objdump verifying mul instruction survives backend CodeGen bc_ios = p / 'nl_ios.bc' obf_ios = p / 'nl_ios.obf.bc' obj_ios = p / 'nl_ios.o' aud_ios = p / 'nl_ios.audit.json' subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios), ], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_nl_ios', f'--ig-source-path={src_c}', f'--ig-audit-out={aud_ios}', str(bc_ios), '-o', str(obf_ios), ], check=True) subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), ], check=True) disasm = subprocess.check_output(['xcrun', 'objdump', '-d', str(obj_ios)], text=True) self.assertIn('\tmul\t', disasm) def test_opaque_zero_hides_literals_without_data_pool(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-m9-oz-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'opaque_const_targets': [ {'id': 'oz_rule', 'path_contains': 'oz.c', 'function_contains': 'oz_', 'opaque_zero': True} ], }), encoding='utf-8') src_c = p / 'oz.c' src_c.write_text( '''#include #include __attribute__((noinline)) uint32_t oz_magic32(uint32_t x) { uint32_t h = x ^ 0x13579BDFu; if (h == 0x2468ACE0u) { return h + 0x55AA1122u; } return h + 0x76543211u; } __attribute__((noinline)) uint64_t oz_magic64(void) { return (uint64_t)0x5A3C96F12468ACE0ULL; } __attribute__((noinline)) uint64_t oz_magic64_arg(uint64_t seed) { return (seed + 0x1020304050607080ULL) ^ 0x5A3C96F12468ACE0ULL; } int main(void) { if (oz_magic32(0x13579BDFu ^ 0x2468ACE0u) != (0x2468ACE0u + 0x55AA1122u)) return 1; if (oz_magic32(123u) != ((123u ^ 0x13579BDFu) + 0x76543211u)) return 2; if (oz_magic64() != 0x5A3C96F12468ACE0ULL) return 3; if (oz_magic64_arg(0x1111111111111111ULL) != ((0x1111111111111111ULL + 0x1020304050607080ULL) ^ 0x5A3C96F12468ACE0ULL)) return 4; return 0; } ''', encoding='utf-8', ) bc_h = p / 'oz_h.bc' obf_ll = p / 'oz_h.obf.ll' obj_h = p / 'oz_h.o' exe_h = p / 'oz_h_exe' aud_h = p / 'oz_h.audit.json' subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) subprocess.run([ opt_path, '-S', '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_oz_1', f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', str(bc_h), '-o', str(obf_ll), ], check=True) ir_text = obf_ll.read_text(encoding='utf-8') non_dbg_ir = '\n'.join(l for l in ir_text.splitlines() if '#dbg_' not in l) self.assertNotIn('__ig_ocp_', non_dbg_ir, 'Table-free OpaqueZero should not allocate __ig_ocp_ pool') self.assertNotIn('324508639', non_dbg_ir) # 0x13579BDF self.assertNotIn('6502235449435991264', non_dbg_ir) # 0x5A3C96F12468ACE0 audit = json.loads(aud_h.read_text(encoding='utf-8')) self.assertGreaterEqual(audit['opaque_zero_count'], 2) 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) subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0) # iOS arm64 check: verify literal chunks of 0x13579BDF and 0x5A3C96F12468ACE0 absent in disasm bc_ios = p / 'oz_ios.bc' obf_ios = p / 'oz_ios.obf.bc' obj_ios = p / 'oz_ios.o' subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_ios), ], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_oz_ios', f'--ig-source-path={src_c}', f'--ig-audit-out={p / "oz_ios.audit.json"}', str(bc_ios), '-o', str(obf_ios), ], check=True) subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), ], check=True) disasm = subprocess.check_output(['xcrun', 'objdump', '-d', str(obj_ios)], text=True) # Low 16-bit of 0x13579BDF = 0x9bdf, high = 0x1357 self.assertNotIn('#0x9bdf', disasm.lower()) self.assertNotIn('#0x1357', disasm.lower()) self.assertNotIn('#0x5a3c', disasm.lower()) def test_bbsplit_and_per_rule_overrides_with_flattening(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') sdk_host = macos_sdk_path() with tempfile.TemporaryDirectory(prefix='ig-m9-bb-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'bb_split_max_per_fn': 4, 'bb_split_min_insts': 4, 'bb_split_targets': [ {'id': 'bb_rule', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'max_per_fn': 2} ], 'flatten_targets': [{'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn'}], 'opaque_const_targets': [ {'id': 'cap_const', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'max_per_fn': 2} ], 'arithmetic_targets': [ {'id': 'cap_arith', 'path_contains': 'bbs.c', 'function_contains': 'long_linear_fn', 'rounds': 2, 'max_per_fn': 3} ], }), encoding='utf-8') src_c = p / 'bbs.c' src_c.write_text( '''#include __attribute__((noinline)) uint32_t long_linear_fn(uint32_t x, uint32_t y) { uint32_t a = (x * 7u) ^ 0x11111111u; uint32_t b = (y * 13u) + 0x22222222u; uint32_t c = (a + b) ^ (x >> 3); uint32_t d = (c - y) + (a & 0x33333333u); uint32_t e = (d ^ b) | (c & 0x44444444u); uint32_t f = (e + a) ^ (d * 5u); return f + c; } int main(void) { uint32_t r = long_linear_fn(0x1234u, 0x5678u); uint32_t x = 0x1234u, y = 0x5678u; uint32_t a = (x * 7u) ^ 0x11111111u; uint32_t b = (y * 13u) + 0x22222222u; uint32_t c = (a + b) ^ (x >> 3); uint32_t d = (c - y) + (a & 0x33333333u); uint32_t e = (d ^ b) | (c & 0x44444444u); uint32_t f = (e + a) ^ (d * 5u); return (r == (f + c)) ? 0 : 1; } ''', encoding='utf-8', ) bc_h = p / 'bb.bc' obf_h = p / 'bb.obf.bc' obj_h = p / 'bb.o' exe_h = p / 'bb_exe' aud_h = p / 'bb.audit.json' subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_h)], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m9_bb_1', f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}', str(bc_h), '-o', str(obf_h), ], check=True) audit = json.loads(aud_h.read_text(encoding='utf-8')) self.assertGreaterEqual(audit['bb_split_count'], 1) self.assertLessEqual(audit['bb_split_count'], 2) # Single linear block was split so flattening should now transform it cleanly! self.assertIn('long_linear_fn', audit['functions_flattened']) self.assertLessEqual(audit['opaque_constants_count'], 2) self.assertLessEqual(audit['arithmetic_rewrites_count'], 3) subprocess.run([ clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_h), '-o', str(obj_h), ], check=True) subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True) self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0) if __name__ == '__main__': unittest.main()