"""Unit tests for M3 pass: IGIndirectBranch (encrypted jump-table indirectbr).""" 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 import verify_macho_indirect_branches # noqa: E402 import verify_macho_star_cfg # 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 TestIndirectBranchPass(unittest.TestCase): def test_c_flattened_and_unflattened_indirect_branch_link_and_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-m3-ibr-c-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'flatten_topology': 'sparse_switch', 'flatten_bogus_blocks': 2, 'flatten_split_linear_blocks': True, 'flatten_targets': [{'path_contains': 'ibr_c.c', 'function_contains': 'compute_flow'}], 'indirect_branch_targets': [{'path_contains': 'ibr_c.c'}], 'indirect_branch_exempt_functions': ['exempt_branch_fn'], }), encoding='utf-8') src_c = p / 'ibr_c.c' src_c.write_text( '''#include __attribute__((noinline)) int compute_flow(int x, int mode) { int acc = 17; if (x < 0) { acc = (acc * 3) ^ (-x); } else if (x == 0) { acc = 91; } else { for (int i = 0; i < 4; ++i) { acc = (acc + (x ^ i)) ^ (mode + i); } } switch (mode & 3) { case 0: acc += 11; break; case 1: acc ^= 0x55; break; case 2: acc -= 7; break; default: acc += 3; break; } return acc; } __attribute__((noinline)) static int internal_helper(int v) { if (v > 10) return v * 2 + 1; if (v < 0) return -v + 3; return v + 9; } __attribute__((noinline)) static int dead_unused_helper(int v) { if (v > 5) return v + 100; return v - 100; } __attribute__((noinline)) int exempt_branch_fn(int v) { if (v > 0) return v + 2; return v - 2; } int main(void) { int inputs[][2] = {{-5, 0}, {0, 1}, {7, 2}, {13, 3}, {4, 0}}; int sum = 0; for (int i = 0; i < 5; ++i) { sum ^= compute_flow(inputs[i][0], inputs[i][1]); sum += internal_helper(inputs[i][0]); } sum += exempt_branch_fn(5); // Expected deterministic value computed directly from reference: // i=0: compute_flow(-5,0)=71, internal(-5)=8 // i=1: compute_flow(0,1)=14 (91 ^ 0x55), internal(0)=9 // i=2: compute_flow(7,2): acc starts 17; i=0:(24^2=26),i=1:(32^3=35),i=2:(40^4=44),i=3:(48^5=53) =>53-7=46? Wait: use exact volatile compare in test or exact oracle! (void)dead_unused_helper; return (sum != 0) ? sum : 0; } ''', encoding='utf-8', ) # Compile un-obfuscated reference binary on host to get exact golden return value ref_exe = p / 'ref_host' subprocess.run([clang, '-isysroot', sdk_host, '-O2', str(src_c), '-o', str(ref_exe)], check=True) ref_rc = subprocess.run([str(ref_exe)]).returncode bc_host = p / 'ibr_host.bc' subprocess.run([clang, '-isysroot', sdk_host, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_host)], check=True) def build_host(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_host), '-o', str(obf_bc), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, '-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_host, 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')) o1, exe1, aud1 = build_host('h1', 'ibr_seed_1', 'all') o2, _, _ = build_host('h2', 'ibr_seed_1', 'all') o3, exe3, _ = build_host('h3', 'ibr_seed_2', 'all') _, exe_ibr_only, aud_ibr_only = build_host('ibr_only', 'ibr_seed_1', 'ibr') self.assertEqual(hashlib.sha256(o1.read_bytes()).hexdigest(), hashlib.sha256(o2.read_bytes()).hexdigest()) self.assertNotEqual(hashlib.sha256(o1.read_bytes()).hexdigest(), hashlib.sha256(o3.read_bytes()).hexdigest()) self.assertGreaterEqual(aud1['indirect_branches_count'], 4, aud1) self.assertIn('compute_flow', aud1['indirect_branches_functions']) self.assertNotIn('exempt_branch_fn', aud1['indirect_branches_functions']) self.assertEqual(aud_ibr_only['functions_flattened'], []) self.assertGreaterEqual(aud_ibr_only['indirect_branches_count'], 2) for exe in (exe1, exe3, exe_ibr_only): self.assertEqual(subprocess.run([str(exe)]).returncode, ref_rc) # Verify StarCFGGate + IndirectBranchGate on linked host Mach-O + dSYM dsym1 = p / 'h1.dSYM' subprocess.run(['xcrun', 'dsymutil', str(exe1), '-o', str(dsym1)], check=True) dwarf1 = dsym1 / 'Contents/Resources/DWARF' / exe1.name audit_wrapper = {'module_audits': [{ 'source_path': str(src_c), 'functions_flattened_details': aud1['functions_flattened_details'], 'indirect_branches_functions': aud1['indirect_branches_functions'], }]} star_res = verify_macho_star_cfg.verify_binary_star_cfg( exe1, dwarf1, audit_wrapper, require_topology='' ) self.assertEqual(star_res['failed_count'], 0) ibr_res = verify_macho_indirect_branches.verify_binary_indirect_branches(exe1, dwarf1, audit_wrapper) self.assertEqual(ibr_res['failed_count'], 0) self.assertGreaterEqual(ibr_res['verified_ibr_count'], 2) nm_exe = subprocess.check_output(['xcrun', 'nm', str(exe1)], text=True) self.assertNotIn('dead_unused_helper', nm_exe) # Cross-compile & link for arm64-apple-ios15.0 with -Wl,-dead_strip to validate ld64 PIC relocations bc_ios = p / 'ibr_ios.bc' obf_ios = p / 'ibr_ios.obf.bc' obj_ios = p / 'ibr_ios.o' bin_ios = p / 'ibr_ios.bin' subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-Os', '-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-pass-filter=all', '--ig-seed=ios_ibr_seed', f'--ig-source-path={src_c}', 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, '-Wl,-dead_strip', str(obj_ios), '-o', str(bin_ios)], check=True) dis_ios = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(bin_ios)], text=True) self.assertIsNotNone(re.search(r'\bbr\s+x\d+\b', dis_ios)) def test_objc_and_swift_async_throws_indirect_branch(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') swiftc = detect_stock_tool('swiftc') sdk_host = macos_sdk_path() with tempfile.TemporaryDirectory(prefix='ig-m3-ibr-mix-') as td: p = Path(td).resolve() policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'flatten_topology': 'sparse_switch', 'flatten_targets': [{'path_contains': 'ibr_'}], 'indirect_branch_targets': [{'path_contains': 'ibr_'}], }), encoding='utf-8') objc_m = p / 'ibr_objc.m' objc_m.write_text( '''#import @interface IBRBox : NSObject - (NSInteger)computeScore:(NSInteger)x flag:(BOOL)flag; @end @implementation IBRBox - (NSInteger)computeScore:(NSInteger)x flag:(BOOL)flag { NSInteger r = 5; if (flag) r += x * 3; else r -= x; if (r > 20) return r ^ 0x12; return r + 4; } @end int main(void) { @autoreleasepool { IBRBox *b = [[IBRBox alloc] init]; return ([b computeScore:8 flag:YES] == (29 ^ 0x12) && [b computeScore:3 flag:NO] == 6) ? 0 : 1; } } ''', encoding='utf-8', ) bc_m = p / 'ibr_objc.bc' obf_m = p / 'ibr_objc.obf.bc' o_m = p / 'ibr_objc.o' exe_m = p / 'ibr_objc.exe' aud_m = p / 'aud_m.json' subprocess.run([clang, '-isysroot', sdk_host, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(objc_m), '-o', str(bc_m)], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m3_objc', f'--ig-source-path={objc_m}', f'--ig-audit-out={aud_m}', str(bc_m), '-o', str(obf_m), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_m), '-o', str(o_m), ], check=True) subprocess.run([clang, '-isysroot', sdk_host, '-framework', 'Foundation', '-Wl,-dead_strip', str(o_m), '-o', str(exe_m)], check=True) self.assertEqual(subprocess.run([str(exe_m)]).returncode, 0) aud_m_j = json.loads(aud_m.read_text(encoding='utf-8')) self.assertGreaterEqual(aud_m_j['indirect_branches_count'], 1) sw_file = p / 'ibr_swift.swift' sw_file.write_text( '''import Foundation @inline(never) func swEval(_ a: Int) -> Int { var acc = a + 3 if acc > 10 { acc ^= 0x1F } else { acc += 7 } if acc < 5 { return acc - 2 } return acc + 1 } @main struct Runner { static func main() { let v = swEval(12) ^ swEval(1) if v != ((15 ^ 0x1F) + 1) ^ ((4 + 7) + 1) { exit(4) } } } ''', encoding='utf-8', ) bc_s = p / 'ibr_sw.bc' obf_s = p / 'ibr_sw.obf.bc' o_s = p / 'ibr_sw.o' exe_s = p / 'ibr_sw.exe' aud_s = p / 'aud_s.json' subprocess.run([swiftc, '-sdk', sdk_host, '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(sw_file), '-o', str(bc_s)], check=True) subprocess.run([ opt_path, '-passes=default,ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m3_sw', f'--ig-source-path={sw_file}', f'--ig-audit-out={aud_s}', str(bc_s), '-o', str(obf_s), ], check=True) subprocess.run([ clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_s), '-o', str(o_s), ], check=True) subprocess.run([swiftc, '-sdk', sdk_host, str(o_s), '-Xlinker', '-dead_strip', '-o', str(exe_s)], check=True) self.assertEqual(subprocess.run([str(exe_s)]).returncode, 0) aud_s_j = json.loads(aud_s.read_text(encoding='utf-8')) self.assertGreaterEqual(aud_s_j['indirect_branches_count'], 1) def test_only_conditional_branches_and_dead_blocks_ios_codegen(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') sdk_ios = iphoneos_sdk_path() with tempfile.TemporaryDirectory(prefix='ig-m3-ibr-edge-') as td: p = Path(td) policy_path = p / 'policy.json' policy_path.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'indirect_branch_targets': [{'path_contains': 'ibr_edge.ll'}], }), encoding='utf-8') ll_p = p / 'ibr_edge.ll' ll_p.write_text( '''target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" target triple = "arm64-apple-ios15.0.0" define i32 @only_cond_branches(i32 %x) { entry: %c1 = icmp sgt i32 %x, 0 br i1 %c1, label %pos, label %neg pos: %c2 = icmp sgt i32 %x, 10 br i1 %c2, label %big, label %small big: ret i32 100 small: ret i32 10 neg: ret i32 -1 } define i32 @dead_block_and_const_cond(i32 %x) { entry: br i1 true, label %live_branch, label %dead_arm live_branch: %c1 = icmp sgt i32 %x, 5 br i1 %c1, label %gt, label %le gt: ret i32 1 le: ret i32 2 dead_arm: %c2 = icmp eq i32 %x, 99 br i1 %c2, label %gt, label %dead_unr dead_unr: ret i32 -999 } ''', encoding='utf-8', ) obf_ll = p / 'ibr_edge.obf.ll' obj_o = p / 'ibr_edge.o' aud_p = p / 'ibr_edge.audit.json' subprocess.run([ opt_path, '-S', '-passes=ig-obfuscate', f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-pass-filter=ibr', '--ig-seed=ibr_edge_1', f'--ig-source-path={ll_p}', f'--ig-audit-out={aud_p}', str(ll_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')) self.assertGreaterEqual(aud['indirect_branches_count'], 3, aud) self.assertIn('only_cond_branches', aud['indirect_branches_functions']) self.assertIn('dead_block_and_const_cond', aud['indirect_branches_functions']) self.assertNotIn('ig.ibr.decoy', ir_txt) self.assertNotIn('blockaddress(@dead_block_and_const_cond, %dead_arm)', ir_txt) self.assertNotIn('blockaddress(@dead_block_and_const_cond, %dead_unr)', ir_txt) res = 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_ll), '-o', str(obj_o), ], capture_output=True, text=True) self.assertEqual(res.returncode, 0, res.stderr) if __name__ == '__main__': unittest.main()