"""Unit tests for M4 features: IGAntiHooking prologue & IGStringEncryption stack-decrypt + volatile wipe.""" 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() def iphoneos_sdk_path() -> str: return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip() class TestAntiHookingAndStackStringPass(unittest.TestCase): def test_anti_hooking_prologue_ios_link_and_host_exec(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-m4-antihook-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'anti_hooking_targets': [{'path_contains': 'hook_target'}], 'anti_hooking_exempt_functions': ['exempt_hook_fn'], }), encoding='utf-8') src_cpp = p / 'hook_target.cpp' src_cpp.write_text( '''#include extern "C" __attribute__((noinline, used)) int safe_c_guard(int x) noexcept { int acc = x ^ 0x33; if (acc < 0) acc += 19; return acc * 3 + 7; } __attribute__((noinline)) int may_throw_worker(int x) { if (x < 0) throw 42; return x + 11; } extern "C" __attribute__((noinline, used)) int exempt_hook_fn(int x) noexcept { return x + 5; } int main() { int a = safe_c_guard(9); int b = exempt_hook_fn(4); int c = 0; try { c = may_throw_worker(-1); } catch (int v) { c = v; } if (a != ((9 ^ 0x33) * 3 + 7) || b != 9 || c != 42) { return 1; } return 0; } ''', encoding='utf-8', ) # 1. Verify iOS arm64 compilation + -Wl,-dead_strip dynamic link + dsymutil + otool -tV bc_ios = p / 'hook_ios.bc' obf_ios = p / 'hook_ios.obf.bc' obj_ios = p / 'hook_ios.o' dylib_ios = p / 'libhook_ios.dylib' aud_ios_p = p / 'hook_ios.audit.json' subprocess.run([ clang, '-x', 'c++', '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-g', '-fexceptions', '-emit-llvm', '-c', str(src_cpp), '-o', str(bc_ios), ], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-pass-filter=antihook', '--ig-seed=antihook_ios_1', f'--ig-source-path={src_cpp}', f'--ig-audit-out={aud_ios_p}', str(bc_ios), '-o', str(obf_ios), ], check=True) subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ios), '-o', str(obj_ios), ], check=True) subprocess.run([ clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-dynamiclib', str(obj_ios), '-lc++', '-Wl,-dead_strip', '-o', str(dylib_ios), ], check=True) subprocess.run(['xcrun', 'dsymutil', str(dylib_ios), '-o', str(p / 'libhook_ios.dylib.dSYM')], check=True) aud_ios = json.loads(aud_ios_p.read_text(encoding='utf-8')) self.assertGreaterEqual(aud_ios['anti_hook_functions_count'], 1) hooked_fns = aud_ios['anti_hook_functions'] self.assertIn('safe_c_guard', hooked_fns) self.assertNotIn('exempt_hook_fn', hooked_fns) self.assertFalse(any('may_throw_worker' in fn for fn in hooked_fns), hooked_fns) otool_txt = subprocess.check_output(['xcrun', 'otool', '-tV', str(dylib_ios)], text=True) m = re.search(r'^_safe_c_guard:\n([^\n]+)\n([^\n]+)', otool_txt, re.MULTILINE) self.assertIsNotNone(m, otool_txt) first_two = f"{m.group(1)}\n{m.group(2)}" self.assertIn('mov\tx17, x17', first_two) self.assertIn('mov\tx16, x16', first_two) # 2. Verify host macOS arm64 execution (both nounwind + throwing catch path run cleanly) bc_host = p / 'hook_host.bc' obf_host = p / 'hook_host.obf.bc' obj_host = p / 'hook_host.o' exe_host = p / 'hook_host_exe' aud_host_p = p / 'hook_host.audit.json' subprocess.run([ clang, '-x', 'c++', '-isysroot', sdk_host, '-Os', '-g', '-fexceptions', '-emit-llvm', '-c', str(src_cpp), '-o', str(bc_host), ], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-pass-filter=antihook', '--ig-seed=antihook_host_1', f'--ig-source-path={src_cpp}', f'--ig-audit-out={aud_host_p}', str(bc_host), '-o', str(obf_host), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_host), '-o', str(obj_host), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, str(obj_host), '-lc++', '-Wl,-dead_strip', '-o', str(exe_host), ], check=True) rc = subprocess.run([str(exe_host)]).returncode self.assertEqual(rc, 0) # 3. Verify -ig-pass-filter=fla skips IGAntiHooking cleanly aud_fla_p = p / 'hook_fla.audit.json' subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-pass-filter=fla', '--ig-seed=antihook_fla_1', f'--ig-source-path={src_cpp}', f'--ig-audit-out={aud_fla_p}', str(bc_host), '-o', str(p / 'hook_fla.obf.bc'), ], check=True) aud_fla = json.loads(aud_fla_p.read_text(encoding='utf-8')) self.assertEqual(aud_fla['anti_hook_functions_count'], 0) def test_stack_string_encryption_volatile_wipe_and_fallbacks(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') sdk_host = macos_sdk_path() with tempfile.TemporaryDirectory(prefix='ig-m4-stackstr-') 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_str.c'}], 'string_encrypt_stack_targets': [{'path_contains': 'stack_str.c'}], 'string_encrypt_stack_max_len': 20, }), encoding='utf-8') src_c = p / 'stack_str.c' src_c.write_text( '''#include #include #include __attribute__((noinline)) void store_global_fallback(const char **out) { *out = "STORE_GLOBAL_OK"; } __attribute__((noinline)) const char *strstr_arg0_fallback(const char *needle) { return strstr("HAYSTACK_GLOBAL_ALPHA", needle); } __attribute__((noinline)) int too_long_fallback(const char *probe) { return strcmp(probe, "OVER_MAX_LEN_GLOBAL_STRING_12345"); } __attribute__((noinline)) int stack_checks(const char *s1, const char *s2) { int ok = 1; if (strcmp(s1, "STACK_TOK_1") != 0) ok = 0; if (strstr(s2, "NEEDLE_2") == NULL) ok = 0; for (int i = 0; i < 3; ++i) { if (strcmp(s1, "STACK_TOK_1") != 0) ok = 0; } const char *envv = getenv("IG_UNSET_STACK_ENV"); if (envv != NULL) ok = 0; return ok; } int main(void) { volatile char b1[] = {'S','T','A','C','K','_','T','O','K','_','X',0}; b1[10] = '1'; char s1[16]; for (int i = 0; i < 12; ++i) s1[i] = b1[i]; if (!stack_checks(s1, "prefix_NEEDLE_2_suffix")) return 1; const char *stored = NULL; store_global_fallback(&stored); if (!stored || strcmp(stored, "STORE_GLOBAL_OK") != 0) return 2; volatile char nb[] = {'A','L','P','H','X',0}; nb[4] = 'A'; char needle[8]; for (int i = 0; i < 6; ++i) needle[i] = nb[i]; const char *found = strstr_arg0_fallback(needle); if (!found || strcmp(found, "ALPHA") != 0) return 3; volatile char lb[] = { 'O','V','E','R','_','M','A','X','_','L','E','N','_', 'G','L','O','B','A','L','_','S','T','R','I','N','G','_', '1','2','3','4','X',0 }; lb[31] = '5'; char long_probe[40]; for (int i = 0; i < 33; ++i) long_probe[i] = lb[i]; if (too_long_fallback(long_probe) != 0) return 4; return 0; } ''', encoding='utf-8', ) bc_p = p / 'stack_str.bc' obf_ll = p / 'stack_str.obf.ll' obj_o = p / 'stack_str.o' exe_p = p / 'stack_str_exe' aud_p = p / 'stack_str.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=stackstr_seed_1', f'--ig-source-path={src_c}', f'--ig-audit-out={aud_p}', str(bc_p), '-o', str(obf_ll), ], check=True) ir_txt = obf_ll.read_text(encoding='utf-8') aud = json.loads(aud_p.read_text(encoding='utf-8')) # 3 stack-only short literals in stack_checks ("STACK_TOK_1", "NEEDLE_2", "IG_UNSET_STACK_ENV"), # plus global fallback literals (stored pointer, strstr arg-0, over-max-len string, etc.) self.assertGreaterEqual(aud['strings_stack_encrypted_count'], 3, aud) self.assertGreaterEqual(aud['strings_encrypted_count'], aud['strings_stack_encrypted_count'] + 3, aud) self.assertIn('alloca [12 x i8]', ir_txt) # "STACK_TOK_1\0" -> 12 bytes self.assertIn('store volatile i8 0,', ir_txt) self.assertIn('@__ig_str_dec_stack', ir_txt) # Global fallback strings must still create .ig.buf. / .ig.state. self.assertIn('.ig.buf.', ir_txt) # Plaintext literals must not remain in IR self.assertNotIn('STACK_TOK_1', ir_txt) self.assertNotIn('NEEDLE_2', ir_txt) self.assertNotIn('IG_UNSET_STACK_ENV', ir_txt) self.assertNotIn('STORE_GLOBAL_OK', ir_txt) self.assertNotIn('HAYSTACK_GLOBAL_ALPHA', ir_txt) self.assertNotIn('OVER_MAX_LEN_GLOBAL_STRING_12345', 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_o), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p), ], check=True) rc = subprocess.run([str(exe_p)]).returncode self.assertEqual(rc, 0) if __name__ == '__main__': unittest.main()