import hashlib import json import os from pathlib import Path import subprocess import sys import tempfile import unittest ROOT = Path(__file__).resolve().parents[1] TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf' TOOLS_ARCHIVE = ROOT / 'tools' / 'xcode_archive' TOOLS_CRASH = ROOT / 'tools' / 'crash_restore' sys.path.insert(0, str(TOOLS_LLVM_OBF)) sys.path.insert(0, str(TOOLS_ARCHIVE)) sys.path.insert(0, str(TOOLS_CRASH)) from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402 import ig_ld_wrapper # noqa: E402 import restore_crash_report # noqa: E402 def require_host_opt(): 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 class TestLLVMObfM0(unittest.TestCase): def test_zero_hit_negative_gate_and_modes(self): with tempfile.TemporaryDirectory() as td: p = Path(td) out_bin = p / 'readoor31.app' / 'readoor31' out_bin.parent.mkdir(parents=True) linkmap = p / 'LinkMap.txt' policy_path = str(ROOT / 'config' / 'ig_llvm_policy.json') policy = json.loads(Path(policy_path).read_text(encoding='utf-8')) conv_empty = { 'expected_swift_count': 1, 'converted_swift_count': 0, 'skipped_swift_count': 1, 'swift_audits': [], 'objc_audits': [], } ctl_full = { 'mode': 'full', 'filter': 'all', 'route2': 'on', 'all_off': '0', 'seed': 's1', 'stamp': 'st1', } with self.assertRaisesRegex(RuntimeError, 'Audit gate failed'): ig_ld_wrapper.evaluate_and_write_obf_audit( out_bin, str(linkmap), ctl_full, policy_path, policy, conv_empty ) # str mode with unexpected flattening fails closed conv_bad_str = { 'expected_swift_count': 1, 'converted_swift_count': 1, 'skipped_swift_count': 0, 'swift_audits': [{ 'source_path': '3.0/Base/Security/RDInjectionDetector.swift', 'functions_flattened': ['$s9readoor3119RDInjectionDetectorC32hasSuspiciousDyldInsertLibraries'], 'strings_encrypted_count': 1, 'strings_encrypted_functions': ['$s9readoor3119RDInjectionDetectorC6detect'], }], 'objc_audits': [{ 'source_path': 'STSJailbreakDetectTool.m', 'functions_flattened': [], 'strings_encrypted_count': 1, 'strings_encrypted_functions': ['printEnv'], }], } ctl_str = dict(ctl_full, mode='str', filter='str') with self.assertRaisesRegex(RuntimeError, 'str mode expected total_flattened=0'): ig_ld_wrapper.evaluate_and_write_obf_audit( out_bin, str(linkmap), ctl_str, policy_path, policy, conv_bad_str ) # noop mode accepts zero edits conv_noop = { 'expected_swift_count': 1, 'converted_swift_count': 1, 'skipped_swift_count': 0, 'swift_audits': [{'source_path': 'A.swift', 'functions_flattened': [], 'strings_encrypted_count': 0}], 'objc_audits': [{'source_path': 'B.m', 'functions_flattened': [], 'strings_encrypted_count': 0}], } ctl_noop = dict(ctl_full, mode='noop') res = ig_ld_wrapper.evaluate_and_write_obf_audit( out_bin, str(linkmap), ctl_noop, policy_path, policy, conv_noop ) self.assertEqual(res['total_flattened'], 0) self.assertEqual(res['total_strings_encrypted'], 0) def test_audit_matches_swift_word_compressed_mangled_symbols(self): with tempfile.TemporaryDirectory() as td: p = Path(td) out_bin = p / 'readoor31OtherPay.app' / 'readoor31OtherPay' out_bin.parent.mkdir(parents=True) linkmap = p / 'LinkMap.txt' comp_policy = { 'required_targets': [ { 'id': 'swift_rd_injection_dyld_check', 'path_contains': 'RDInjectionDetector.swift', 'symbol_contains': '32hasSuspiciousDyldInsertLibraries', 'symbol_contains_any': ['32hasSuspiciousDyldInsertLibraries', '21balanceMeridianKernel'], 'str_symbol_contains': '19RDInjectionDetectorC', 'str_symbol_contains_any': ['19RDInjectionDetectorC', '20MeridianCipherAnchorC'], 'min_flattened': 1, 'min_strings_encrypted': 1, } ] } compressed_fn = ( '$s17readoor31OtherPay20MeridianCipherAnchorC07balanceD6Kernel' '33_DF35DDC8CC6FD804893D3B0253F67019LL8rawValue15whitelistResult' '10bundlePathSbSSSg_AC18LindenSensorWorkerVSStF' ) conv = { 'expected_swift_count': 1, 'converted_swift_count': 1, 'skipped_swift_count': 0, 'swift_audits': [ { 'source_path': '/tmp/ig-ipa-work/src/readoor/3.0/Base/Security/RDInjectionDetector.swift', 'functions_flattened': [compressed_fn], 'strings_encrypted_count': 1, 'strings_encrypted_functions': [compressed_fn], } ], 'objc_audits': [], } ctl_full = { 'mode': 'full', 'filter': 'all', 'route2': 'on', 'all_off': '0', 'seed': 's1', 'stamp': 'st1', } res = ig_ld_wrapper.evaluate_and_write_obf_audit( out_bin, str(linkmap), ctl_full, str(p / 'policy.json'), comp_policy, conv ) self.assertEqual(res['required_targets'][0]['flattened_hits'], 1) self.assertEqual(res['required_targets'][0]['strings_encrypted_hits'], 1) def test_string_encryption_use_def_exclusion_and_acceptance(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() with tempfile.TemporaryDirectory() as td: p = Path(td) policy_p = p / 'policy.json' policy_p.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'string_encrypt_targets': [{'path_contains': 'usedef_test.m'}], 'flatten_targets': [], }), encoding='utf-8') src = p / 'usedef_test.m' src.write_text( '#import \n' '#include \n' 'static const char *g_table[] = { "TABLE_ENTRY_LITERAL_ONE", "TABLE_ENTRY_LITERAL_TWO" };\n' 'const char *read_table(int idx) { return g_table[idx & 1]; }\n' 'NSString *get_cfstr(void) { return @"OBJC_CFSTRING_LITERAL_VALUE"; }\n' 'const char *get_controlled(void) { return getenv("CONTROLLED_M0_ENV_KEY_VAR"); }\n', encoding='utf-8', ) subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-fobjc-arc', '-emit-llvm', '-c', str(src), '-o', str(p / 'in.bc')], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_p}', '--ig-mode=str', '--ig-seed=ud_seed', f'--ig-source-path={src}', f'--ig-audit-out={p / "audit.json"}', str(p / 'in.bc'), '-o', str(p / 'out.bc'), ], check=True) subprocess.run([ clang, '-S', '-emit-llvm', '-Xclang', '-disable-llvm-passes', '-x', 'ir', str(p / 'out.bc'), '-o', str(p / 'out.ll'), ], check=True) audit = json.loads((p / 'audit.json').read_text(encoding='utf-8')) ll = (p / 'out.ll').read_text(encoding='utf-8') self.assertEqual(audit['strings_encrypted_count'], 1) self.assertGreaterEqual(audit['strings_skipped_count'], 1) self.assertIn('__ig_dec_str_0', ll) self.assertNotIn('CONTROLLED_M0_ENV_KEY_VAR', ll) self.assertIn('TABLE_ENTRY_LITERAL_ONE', ll) self.assertIn('OBJC_CFSTRING_LITERAL_VALUE', ll) def test_concurrent_string_decryption_and_flattening_host_stress(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() with tempfile.TemporaryDirectory() as td: p = Path(td) policy_p = p / 'policy.json' policy_p.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'string_encrypt_targets': [{'path_contains': 'stress.c'}], 'flatten_targets': [{'path_contains': 'stress.c', 'function_contains': 'branchy_secret'}], }), encoding='utf-8') src = p / 'stress.c' src.write_text( '#include \n' '#include \n' '#include \n' '#include \n' 'static atomic_int g_go = 0;\n' '__attribute__((noinline)) void consume_a(const char *s, char *out) { snprintf(out, 64, "%s", s); }\n' '__attribute__((noinline)) void consume_b(const char *s, char *out) { snprintf(out, 64, "%s!", s); }\n' '__attribute__((noinline)) void consume_c(const char *s, char *out) { snprintf(out, 64, "%s?", s); }\n' '__attribute__((noinline)) void consume_d(const char *s, char *out) { snprintf(out, 64, "%s.", s); }\n' '__attribute__((noinline)) int branchy_secret(int mode, char *out) {\n' ' if (mode == 1) { consume_a("MULTI_THREAD_CONCURRENT_TOKEN_A", out); return 11; }\n' ' if (mode == 2) { consume_b("MULTI_THREAD_CONCURRENT_TOKEN_B", out); return 22; }\n' ' if (mode == 3) { consume_c("MULTI_THREAD_CONCURRENT_TOKEN_C", out); return 33; }\n' ' consume_d("MULTI_THREAD_CONCURRENT_TOKEN_D", out); return 44;\n' '}\n' 'static void *worker(void *arg) {\n' ' int idx = (int)(long)arg;\n' ' while (!atomic_load_explicit(&g_go, memory_order_acquire)) {}\n' ' char buf[64];\n' ' int rc = branchy_secret((idx % 4) + 1, buf);\n' ' if (rc == 11 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_A", 31) == 0) return (void *)1;\n' ' if (rc == 22 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_B!", 32) == 0) return (void *)1;\n' ' if (rc == 33 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_C?", 32) == 0) return (void *)1;\n' ' if (rc == 44 && strncmp(buf, "MULTI_THREAD_CONCURRENT_TOKEN_D.", 32) == 0) return (void *)1;\n' ' return (void *)0;\n' '}\n' 'int main(void) {\n' ' pthread_t th[8];\n' ' for (long i = 0; i < 8; ++i) pthread_create(&th[i], NULL, worker, (void *)i);\n' ' atomic_store_explicit(&g_go, 1, memory_order_release);\n' ' for (int i = 0; i < 8; ++i) {\n' ' void *res = NULL; pthread_join(th[i], &res);\n' ' if (res != (void *)1) return 2;\n' ' }\n' ' return 0;\n' '}\n', encoding='utf-8', ) subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-emit-llvm', '-c', str(src), '-o', str(p / 's.bc')], check=True) subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_p}', '--ig-mode=full', '--ig-seed=stress_seed', f'--ig-source-path={src}', f'--ig-audit-out={p / "s_audit.json"}', str(p / 's.bc'), '-o', str(p / 's_obf.bc'), ], check=True) subprocess.run([ clang, '-isysroot', macos_sdk, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(p / 's_obf.bc'), '-o', str(p / 's.o'), ], check=True) subprocess.run([clang, '-isysroot', macos_sdk, str(p / 's.o'), '-lpthread', '-o', str(p / 'stress_bin')], check=True) audit = json.loads((p / 's_audit.json').read_text(encoding='utf-8')) self.assertIn('branchy_secret', audit['functions_flattened'][0] if audit['functions_flattened'] else '') self.assertGreaterEqual(audit['strings_encrypted_count'], 4) # Confirm encrypted binary omits original plain tokens (Note: worker strcmp also uses them? Wait: only branchy_secret was obfuscated unless strcmp tokens in main/worker also encrypted since whole stress.c matches!) raw_bin = (p / 'stress_bin').read_bytes() self.assertNotIn(b'MULTI_THREAD_CONCURRENT_TOKEN_A', raw_bin) for _ in range(15): subprocess.run([str(p / 'stress_bin')], check=True) def test_flattening_seed_determinism_and_diversity(self): opt_path = require_host_opt() clang = detect_stock_tool('clang') macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() with tempfile.TemporaryDirectory() as td: p = Path(td) policy_p = p / 'policy.json' policy_p.write_text(json.dumps({ 'exempt_path_substrings': [], 'exempt_function_prefixes': [], 'string_encrypt_targets': [], 'flatten_targets': [{'path_contains': 'det.c', 'function_contains': 'det_fn'}], }), encoding='utf-8') src = p / 'det.c' src.write_text( 'extern int det_ext_a(int);\n' 'extern int det_ext_b(int);\n' 'extern int det_ext_c(int);\n' 'int det_fn(int a, int b) {\n' ' int r = a;\n' ' if (a > 10) r += det_ext_a(b * 3);\n' ' else r -= det_ext_b(b);\n' ' if (r & 1) r ^= det_ext_c(0x5a5a);\n' ' else r += 17;\n' ' if (r < 0) return -r;\n' ' return r;\n' '}\n', encoding='utf-8', ) subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-emit-llvm', '-c', str(src), '-o', str(p / 'det.bc')], check=True) def compile_with_seed(tag, seed): obf_bc = p / f'{tag}.bc' obj = p / f'{tag}.o' subprocess.run([ opt_path, '-passes=ig-obfuscate', f'--ig-policy={policy_p}', '--ig-mode=full', f'--ig-seed={seed}', f'--ig-source-path={src}', str(p / 'det.bc'), '-o', str(obf_bc), ], check=True) subprocess.run([ clang, '-isysroot', macos_sdk, '-Os', '-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj), ], check=True) dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble-symbols=_det_fn', str(obj)], text=True) dis_body = '\n'.join(dis.splitlines()[2:]) return hashlib.sha256(obj.read_bytes()).hexdigest(), dis_body h_a1, dis_a1 = compile_with_seed('a1', 'seed_alpha') h_a2, dis_a2 = compile_with_seed('a2', 'seed_alpha') h_b, dis_b = compile_with_seed('b', 'seed_beta') self.assertEqual(h_a1, h_a2) self.assertEqual(dis_a1, dis_a2) self.assertNotEqual(h_a1, h_b) self.assertNotEqual(dis_a1, dis_b) def test_restore_crash_report_dual_formats_and_uuid_guard(self): clang = detect_stock_tool('clang') macos_sdk = subprocess.check_output(['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True).strip() with tempfile.TemporaryDirectory() as td: p = Path(td) (p / 'fw.c').write_text('int fw_work(int x) {\n return x * 7 + 3;\n}\n', encoding='utf-8') (p / 'main.c').write_text('int fw_work(int x);\nint main(void) {\n return fw_work(6);\n}\n', encoding='utf-8') fw = p / 'libDummyKit.dylib' app = p / 'DummyApp' subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-O0', '-c', str(p / 'fw.c'), '-o', str(p / 'fw.o')], check=True) subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-O0', '-c', str(p / 'main.c'), '-o', str(p / 'main.o')], check=True) subprocess.run([clang, '-isysroot', macos_sdk, '-g', '-dynamiclib', str(p / 'fw.o'), '-Wl,-install_name,@rpath/libDummyKit.dylib', '-o', str(fw)], check=True) subprocess.run([clang, '-isysroot', macos_sdk, '-g', str(p / 'main.o'), str(fw), '-o', str(app)], check=True) dsym_dir = p / 'dsyms' dsym_dir.mkdir() subprocess.run(['xcrun', 'dsymutil', str(fw), '-o', str(dsym_dir / 'libDummyKit.dylib.dSYM')], check=True) subprocess.run(['xcrun', 'dsymutil', str(app), '-o', str(dsym_dir / 'DummyApp.dSYM')], check=True) idx = restore_crash_report.index_dsyms(dsym_dir) self.assertEqual(len(idx), 2) def get_uuid_and_sym(bin_p, sym): out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(bin_p)], text=True) uid = out.split()[1] nm = subprocess.check_output(['nm', str(bin_p)], text=True) addr = next(int(l.split()[0], 16) for l in nm.splitlines() if f' {sym}' in l or l.endswith(f' {sym}')) return uid, addr app_uid, main_vm = get_uuid_and_sym(app, '_main') fw_uid, fw_vm = get_uuid_and_sym(fw, '_fw_work') # Real VM layout check from otool -l __TEXT vmaddr def text_vmaddr(bin_p): ot = subprocess.check_output(['otool', '-l', str(bin_p)], text=True).splitlines() for i, l in enumerate(ot): if 'segname __TEXT' in l: for j in range(i + 1, min(i + 6, len(ot))): if 'vmaddr' in ot[j]: return int(ot[j].split()[1], 16) return 0 app_base_static = text_vmaddr(app) fw_base_static = text_vmaddr(fw) app_load = 0x104000000 fw_load = 0x108000000 app_off = main_vm - app_base_static + 4 fw_off = fw_vm - fw_base_static + 4 ips_path = p / 'sample.ips' ips_header = json.dumps({'app_name': 'DummyApp', 'bug_type': '309'}) ips_body = json.dumps({ 'usedImages': [ {'base': app_load, 'size': 16384, 'uuid': app_uid, 'name': 'DummyApp', 'arch': 'arm64', 'path': '/private/var/DummyApp.app/DummyApp'}, {'base': fw_load, 'size': 16384, 'uuid': fw_uid, 'name': 'libDummyKit.dylib', 'arch': 'arm64', 'path': '/private/var/DummyApp.app/Frameworks/libDummyKit.dylib'}, ], 'threads': [{ 'triggered': True, 'frames': [ {'imageIndex': 0, 'imageOffset': app_off}, {'imageIndex': 1, 'imageOffset': fw_off}, ], }], }) ips_path.write_text(ips_header + '\n' + ips_body + '\n', encoding='utf-8') res_ips = restore_crash_report.restore_report(ips_path, dsym_dir) self.assertEqual(res_ips['format'], 'ips_json') frames = res_ips['threads'][0]['frames'] self.assertIn('main.c:', frames[0]['restored_frames'][0]) self.assertIn('fw.c:', frames[1]['restored_frames'][0]) crash_path = p / 'sample.crash' crash_path.write_text( 'Thread 0 Crashed:\n' f'0 DummyApp {hex(app_load + app_off)} {hex(app_load)} + {app_off}\n' f'1 libDummyKit.dylib {hex(fw_load + fw_off)} {hex(fw_load)} + {fw_off}\n\n' 'Binary Images:\n' f' {hex(app_load)} - {hex(app_load + 0x4000)} DummyApp arm64 <{app_uid}> /private/var/DummyApp.app/DummyApp\n' f' {hex(fw_load)} - {hex(fw_load + 0x4000)} libDummyKit.dylib arm64 <{fw_uid}> /private/var/DummyApp.app/Frameworks/libDummyKit.dylib\n', encoding='utf-8', ) res_crash = restore_crash_report.restore_report(crash_path, dsym_dir) self.assertEqual(res_crash['format'], 'crash_text') self.assertIn('main.c:', res_crash['frames'][0]['restored_frames'][0]) self.assertIn('fw.c:', res_crash['frames'][1]['restored_frames'][0]) # Negative UUID mismatch check bad_ips = p / 'bad.ips' bad_ips.write_text( ips_header + '\n' + ips_body.replace(app_uid, '00000000-0000-0000-0000-000000000000') + '\n', encoding='utf-8', ) with self.assertRaisesRegex(RuntimeError, 'UUID mismatch'): restore_crash_report.restore_report(bad_ips, dsym_dir) if __name__ == '__main__': unittest.main()