- 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
362 lines
19 KiB
Python
362 lines
19 KiB
Python
"""Route 2 tests: dlsym-free Export Trie resolution, legacy lazy rebinding, and extended RDCoreIO."""
|
|
import hashlib
|
|
import os
|
|
import platform
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tools/macho_guard'))
|
|
from redirect_framework_imports import DEPENDENCY, detect_chained_target_mapping, rewrite as rewrite_chained
|
|
from redirect_legacy_imports import detect_legacy_target_mapping, rewrite as rewrite_legacy
|
|
|
|
|
|
@unittest.skipUnless(sys.platform == 'darwin', '需要 Apple 工具链')
|
|
class Route2DefenderTests(unittest.TestCase):
|
|
def test_export_trie_resolution_and_zero_forbidden_imports(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
env = dict(os.environ)
|
|
env.pop('DYLD_INSERT_LIBRARIES', None)
|
|
host_c = root / 'host.c'
|
|
host_c.write_text('''
|
|
#include "resolve/IGResolve.h"
|
|
#include "dispatch/IGArchiveGuard.h"
|
|
#include <assert.h>
|
|
#include <dlfcn.h>
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
|
|
int main(int argc, char **argv) {
|
|
assert(argc == 2);
|
|
const char *syms[] = {
|
|
"fopen","fread","fwrite","fclose","dlopen","dlsym",
|
|
"write","read","open","close","exit","fork","syscall","unlink","getpid"
|
|
};
|
|
for (int i = 0; i < 15; i++) {
|
|
void *a = dlsym(RTLD_DEFAULT, syms[i]);
|
|
void *b = ig_resolve_export_default(syms[i]);
|
|
assert(a && b && a == b);
|
|
}
|
|
assert(ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "rd_a0") == NULL);
|
|
void *handle = dlopen(argv[1], RTLD_NOW);
|
|
assert(handle);
|
|
void *exp_check = ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "rd_io_chk");
|
|
assert(exp_check && exp_check == dlsym(handle, "rd_io_chk"));
|
|
assert(ig_resolve_image_export("/RDCoreIO.framework/RDCoreIO", "no_such_sym_123") == NULL);
|
|
return 0;
|
|
}
|
|
''')
|
|
guard = root / 'RDCoreIO.framework/RDCoreIO'
|
|
guard.parent.mkdir()
|
|
guard_srcs = [str(ROOT / 'defender' / s) for s in (
|
|
'dispatch/IGArchiveGuard.c', 'resolve/IGResolve.c', 'anti_hook/IGAntiHook.c'
|
|
)]
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0',
|
|
'-O2', '-dynamiclib', '-fvisibility=hidden',
|
|
'-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'),
|
|
*guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(guard)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
exe = root / 'trie-host'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0',
|
|
'-O2', '-Wall', '-Wextra', '-Werror',
|
|
'-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'),
|
|
str(host_c), str(ROOT / 'defender/resolve/IGResolve.c'),
|
|
str(ROOT / 'defender/anti_hook/IGAntiHook.c'), '-o', str(exe)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
run = subprocess.run([str(exe), str(guard)], check=True, env=env, capture_output=True, text=True)
|
|
self.assertEqual(run.returncode, 0)
|
|
|
|
forbidden = {
|
|
'_fopen', '_dlopen', '_dlsym', '_write', '_read', '_open',
|
|
'_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid',
|
|
}
|
|
ios_guard = root / 'RDCoreIO_ios'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
'-O2', '-dynamiclib', '-fvisibility=hidden',
|
|
'-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'),
|
|
*guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(ios_guard)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
nm_out = subprocess.check_output(['xcrun', 'nm', '-u', str(ios_guard)], text=True)
|
|
undef = {line.split()[-1] for line in nm_out.splitlines() if line.split()}
|
|
self.assertFalse(undef & forbidden, nm_out)
|
|
|
|
# Check IGAntiInject.o & IGAntiTamper.o as well
|
|
for rel in ('anti_frida/IGAntiInject.c', 'anti_tamper/IGAntiTamper.c'):
|
|
obj = root / (Path(rel).stem + '.o')
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
'-O2', '-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'),
|
|
'-c', str(ROOT / 'defender' / rel), '-o', str(obj)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
nm_obj = subprocess.check_output(['xcrun', 'nm', '-u', str(obj)], text=True)
|
|
obj_undef = {line.split()[-1] for line in nm_obj.splitlines() if line.split()}
|
|
self.assertFalse(obj_undef & forbidden, f'{rel}: {nm_obj}')
|
|
|
|
app_defender = ROOT / 'readoor-test/readoor/3.0/Base/Security/IGDefender'
|
|
if app_defender.exists():
|
|
for rel in ('resolve/IGResolve.c', 'anti_hook/IGAntiHook.c',
|
|
'anti_tamper/IGAntiTamper.c', 'anti_frida/IGAntiInject.c'):
|
|
obj = root / ('app_' + Path(rel).stem + '.o')
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
'-O2', '-I', str(app_defender), '-I', str(app_defender / 'include'),
|
|
'-c', str(app_defender / rel), '-o', str(obj)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
nm_obj = subprocess.check_output(['xcrun', 'nm', '-u', str(obj)], text=True)
|
|
obj_undef = {line.split()[-1] for line in nm_obj.splitlines() if line.split()}
|
|
self.assertFalse(obj_undef & forbidden, f'app {rel}: {nm_obj}')
|
|
|
|
shader = ROOT / 'readoor-test/readoor/BookView/GLPaintView/Utils/STSShaderHelper.m'
|
|
shader_obj = root / 'STSShaderHelper.o'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
'-O2', '-fobjc-arc', '-include', 'UIKit/UIKit.h',
|
|
'-I', str(app_defender), '-I', str(app_defender / 'include'),
|
|
'-c', str(shader), '-o', str(shader_obj)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
nm_shader = subprocess.check_output(['xcrun', 'nm', '-u', str(shader_obj)], text=True)
|
|
shader_undef = {line.split()[-1] for line in nm_shader.splitlines() if line.split()}
|
|
self.assertIn('_IG_dispatch_exit', shader_undef)
|
|
self.assertFalse(shader_undef & forbidden, nm_shader)
|
|
|
|
@unittest.skipUnless(platform.machine() == 'arm64', '需要 Apple Silicon')
|
|
def test_legacy_dyld_info_lazy_rebinding_and_runtime_execution(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
env = dict(os.environ)
|
|
env.pop('DYLD_INSERT_LIBRARIES', None)
|
|
guard = root / 'RDCoreIO.framework/RDCoreIO'
|
|
sdk = root / 'LegacyFixture.framework/LegacyFixture'
|
|
guard.parent.mkdir()
|
|
sdk.parent.mkdir()
|
|
guard_srcs = [str(ROOT / 'defender' / s) for s in (
|
|
'dispatch/IGArchiveGuard.c', 'resolve/IGResolve.c', 'anti_hook/IGAntiHook.c'
|
|
)]
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0',
|
|
'-O2', '-dynamiclib', '-fvisibility=hidden', '-DIG_OBSERVATION',
|
|
'-I', str(ROOT / 'defender'), '-I', str(ROOT / 'defender/include'),
|
|
*guard_srcs, '-Wl,-install_name,' + DEPENDENCY, '-o', str(guard)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
|
|
sdk_c = root / 'legacy_sdk.c'
|
|
sdk_c.write_text('''
|
|
#include <dlfcn.h>
|
|
#include <fcntl.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
int legacy_exercise(const char *path) {
|
|
int fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0600);
|
|
if (fd < 0) return 1;
|
|
if (write(fd, "hello", 5) != 5) return 2;
|
|
lseek(fd, 0, SEEK_SET);
|
|
char buf[16] = {0};
|
|
if (read(fd, buf, 5) != 5 || memcmp(buf, "hello", 5) != 0) return 3;
|
|
if (close(fd) != 0) return 4;
|
|
FILE *f = fopen(path, "rb");
|
|
if (!f) return 5;
|
|
fclose(f);
|
|
if (unlink(path) != 0) return 6;
|
|
if (getpid() <= 0) return 7;
|
|
if (!dlsym(RTLD_DEFAULT, "getpid")) return 8;
|
|
return 0;
|
|
}
|
|
''')
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=11.0',
|
|
'-O2', '-dynamiclib', str(sdk_c),
|
|
'-Wl,-install_name,@rpath/LegacyFixture.framework/LegacyFixture',
|
|
'-Wl,-headerpad,0x4000', '-Wl,-rpath,@loader_path/..', '-o', str(sdk)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
|
|
raw = sdk.read_bytes()
|
|
sha = hashlib.sha256(raw).hexdigest()
|
|
mapping = detect_legacy_target_mapping(raw)
|
|
self.assertEqual(set(mapping.keys()), {
|
|
'_open', '_write', '_read', '_close', '_fopen', '_unlink', '_getpid', '_dlsym'
|
|
})
|
|
rewritten, report = rewrite_legacy(raw, sha, mapping)
|
|
self.assertTrue(report['lazy_offsets_preserved'])
|
|
self.assertTrue(report['section_bytes_unchanged'])
|
|
sdk.write_bytes(rewritten)
|
|
subprocess.run(['codesign', '--force', '--sign', '-', str(guard)], check=True, capture_output=True)
|
|
subprocess.run(['codesign', '--force', '--sign', '-', str(sdk)], check=True, capture_output=True)
|
|
|
|
driver_c = root / 'driver.c'
|
|
driver_c.write_text('''
|
|
#include <assert.h>
|
|
#include <dlfcn.h>
|
|
#include <stdio.h>
|
|
|
|
int main(int argc, char **argv) {
|
|
assert(argc == 3);
|
|
void *sdk = dlopen(argv[1], RTLD_NOW);
|
|
assert(sdk);
|
|
int (*check)(void) = dlsym(sdk, "rd_io_chk");
|
|
int (*exercise)(const char *) = dlsym(sdk, "legacy_exercise");
|
|
assert(check && exercise);
|
|
/* Before lazy symbols are triggered, lazy slots point to __stub_helper in __TEXT -> must still be CLEAR! */
|
|
assert(check() == 0);
|
|
assert(exercise(argv[2]) == 0);
|
|
/* After lazy slots bind to RDCoreIO wrappers -> still CLEAR! */
|
|
assert(check() == 0);
|
|
return 0;
|
|
}
|
|
''')
|
|
driver = root / 'driver'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'macosx', 'clang', '-arch', 'arm64', '-mmacosx-version-min=13.0',
|
|
'-O2', str(driver_c), '-o', str(driver)
|
|
], check=True, env=env, capture_output=True, text=True)
|
|
res = subprocess.run([str(driver), str(sdk), str(root / 'test.bin')],
|
|
check=True, env=env, capture_output=True, text=True)
|
|
self.assertEqual(res.returncode, 0)
|
|
|
|
def test_ttnetworkmanager_ordinal_width_jump_if_present(self):
|
|
tt = ROOT / 'readoor-test/Pods/TTNetworkManager/TTNetworkManager/TTNetworkManager.xcframework/ios-arm64/TTNetworkManager.framework/TTNetworkManager'
|
|
if not tt.exists():
|
|
self.skipTest('需要 TTNetworkManager 副本')
|
|
raw = tt.read_bytes()
|
|
mapping = detect_legacy_target_mapping(raw)
|
|
self.assertEqual(mapping['_fopen'], '_rd_f')
|
|
self.assertEqual(mapping['_open'], '_rdo')
|
|
out, rep = rewrite_legacy(raw, hashlib.sha256(raw).hexdigest(), mapping)
|
|
self.assertEqual(rep['ordinal_width_delta'], 1)
|
|
self.assertTrue(rep['section_bytes_unchanged'])
|
|
self.assertEqual(len(out), len(raw))
|
|
|
|
def test_darwin_extsn_source_redirection_opt_in(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = Path(td)
|
|
c_src = root / 'extsn.c'
|
|
c_src.write_text('extern void *fopen_ext(const char *p, const char *m) __asm("_fopen$DARWIN_EXTSN");\n'
|
|
'void *call_ext(const char *p, const char *m) { return fopen_ext(p, m); }\n')
|
|
obj, lib, out_a = root / 'extsn.o', root / 'extsn.a', root / 'extsn_out.a'
|
|
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
|
'-miphoneos-version-min=15.0', '-O2', '-c', str(c_src), '-o', str(obj)], check=True)
|
|
subprocess.run(['xcrun', 'ar', 'rcs', str(lib), str(obj)], check=True)
|
|
sys.path.insert(0, str(ROOT / 'tools/static_sdk_redirect'))
|
|
from redirect_symbols import validate_mapping
|
|
from redirect_bitcode_members import rewrite as rewrite_ar
|
|
with self.assertRaises(ValueError):
|
|
validate_mapping({'_fopen$DARWIN_EXTSN': '_IG_dispatch_fopen'})
|
|
rep = rewrite_ar(lib, out_a, {'_fopen$DARWIN_EXTSN': '_IG_dispatch_fopen'}, allow_darwin_extsn=True)
|
|
self.assertEqual(sum(m['references'] for m in rep['members']), 1)
|
|
nm_out = subprocess.check_output(['xcrun', 'nm', '-u', str(out_a)], text=True)
|
|
self.assertIn('_IG_dispatch_fopen', nm_out)
|
|
self.assertNotIn('_fopen$DARWIN_EXTSN', nm_out)
|
|
|
|
|
|
def test_xcode_archive_ld_wrapper_passthrough_and_arg_rewrite(self):
|
|
tools_xa = ROOT / 'tools/xcode_archive'
|
|
sys.path.insert(0, str(tools_xa))
|
|
import ig_ld_wrapper
|
|
|
|
self.assertTrue(ig_ld_wrapper.should_passthrough(['-dylib', '-o', '/tmp/Foo.app/Foo'], '/tmp/Foo.app/Foo')[0])
|
|
self.assertTrue(ig_ld_wrapper.should_passthrough(['-o', '/tmp/Foo.xctest/Foo'], '/tmp/Foo.xctest/Foo')[0])
|
|
self.assertFalse(ig_ld_wrapper.should_passthrough(['-arch', 'arm64', '-o', '/tmp/Foo.app/Foo'], '/tmp/Foo.app/Foo')[0])
|
|
lto_args = ['-o', '/tmp/Foo.app/Foo', '-object_path_lto', '/tmp/Foo_lto.o']
|
|
self.assertEqual(ig_ld_wrapper.parse_flag_value(lto_args, '-o'), '/tmp/Foo.app/Foo')
|
|
self.assertFalse(ig_ld_wrapper.should_passthrough(lto_args, ig_ld_wrapper.parse_flag_value(lto_args, '-o'))[0])
|
|
with self.assertRaises(RuntimeError):
|
|
ig_ld_wrapper.check_coverage_absent(['/tmp/libclang_rt.profile_ios.a'])
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
t = Path(tmp)
|
|
stage = t / 'stage'
|
|
stage.mkdir()
|
|
(stage / 'libZipZap.a').write_bytes(b'stub')
|
|
(stage / 'TencentOpenAPI').write_bytes(b'stub')
|
|
app_repo = t / 'repo'
|
|
(app_repo / 'readoor/BookShelf/Classes/Factorys/ZipZap').mkdir(parents=True)
|
|
(app_repo / 'readoor/BookShelf/Classes/Factorys/ZipZap/libZipZap.a').write_bytes(b'orig')
|
|
|
|
args = ['-arch', 'arm64', '-F/some/fw', '-framework', 'TencentOpenAPI', '-lZipZap', '-o', str(t / 'App.app/App')]
|
|
rewritten, replaced = ig_ld_wrapper.build_rewritten_ld_args(
|
|
args, app_repo, stage, t / 'unpatched', t / 'map.txt', False,
|
|
)
|
|
self.assertEqual(replaced, ['-framework TencentOpenAPI', '-lZipZap'])
|
|
self.assertIn('-F', rewritten)
|
|
self.assertLess(rewritten.index(str(stage)), rewritten.index('-F/some/fw'))
|
|
self.assertIn(str(stage / 'TencentOpenAPI'), rewritten)
|
|
self.assertIn(str(stage / 'libZipZap.a'), rewritten)
|
|
self.assertIn(str(stage / 'IGThreadID.o'), rewritten)
|
|
self.assertIn('-map', rewritten)
|
|
|
|
def test_xcode_archive_frameworks_phase_idempotent(self):
|
|
tools_xa = ROOT / 'tools/xcode_archive'
|
|
sys.path.insert(0, str(tools_xa))
|
|
import ig_guard_frameworks_phase as phase
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
t = Path(tmp)
|
|
app_dir = t / 'Demo.app'
|
|
fw_root = app_dir / 'Frameworks'
|
|
fw_dir = fw_root / 'DemoKit.framework'
|
|
fw_dir.mkdir(parents=True)
|
|
|
|
main_c = t / 'main.c'
|
|
main_c.write_text('int main(void) { return 0; }\n')
|
|
main_bin = app_dir / 'Demo'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
str(main_c), '-o', str(main_bin),
|
|
], check=True)
|
|
|
|
fw_c = t / 'demokit.c'
|
|
fw_c.write_text('#include <stdio.h>\nFILE *demo_open(const char *p, const char *m) { return fopen(p, m); }\n')
|
|
fw_bin = fw_dir / 'DemoKit'
|
|
subprocess.run([
|
|
'xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64', '-miphoneos-version-min=15.0',
|
|
'-dynamiclib', '-Wl,-install_name,@rpath/DemoKit.framework/DemoKit',
|
|
str(fw_c), '-o', str(fw_bin),
|
|
], check=True)
|
|
(fw_dir / '_CodeSignature').mkdir()
|
|
(fw_dir / '_CodeSignature/CodeResources').write_text('stale')
|
|
|
|
first = phase.process_framework(fw_dir)
|
|
self.assertTrue(first['modified'])
|
|
self.assertGreater(first['symbols_redirected'], 0)
|
|
self.assertFalse((fw_dir / '_CodeSignature').exists())
|
|
|
|
(fw_dir / '_CodeSignature').mkdir()
|
|
(fw_dir / '_CodeSignature/CodeResources').write_text('signed')
|
|
second = phase.process_framework(fw_dir)
|
|
self.assertEqual(second['mode'], 'already_guarded')
|
|
self.assertFalse(second['modified'])
|
|
self.assertEqual(second['sign_status'], 'preserved')
|
|
self.assertTrue((fw_dir / '_CodeSignature/CodeResources').is_file())
|
|
|
|
guard_fw = fw_root / 'RDCoreIO.framework'
|
|
dsym_root = t / 'dSYMs'
|
|
report = phase.build_archive_guard(
|
|
ROOT / 'readoor-test/readoor/3.0/Base/Security/IGDefender',
|
|
guard_fw,
|
|
dsym_folder=dsym_root,
|
|
debug_info_format='dwarf-with-dsym',
|
|
)
|
|
dwarf = dsym_root / 'RDCoreIO.framework.dSYM/Contents/Resources/DWARF/RDCoreIO'
|
|
self.assertTrue(dwarf.is_file())
|
|
self.assertEqual(Path(report['dsym']), dsym_root / 'RDCoreIO.framework.dSYM')
|
|
bin_uuid = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(guard_fw / 'RDCoreIO')], text=True).split()[1]
|
|
dsym_uuid = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dwarf)], text=True).split()[1]
|
|
self.assertEqual(bin_uuid, dsym_uuid)
|
|
guard_exports = subprocess.check_output(['xcrun', 'nm', '-gU', str(guard_fw / 'RDCoreIO')], text=True)
|
|
guard_export_syms = {ln.split()[-1] for ln in guard_exports.splitlines() if ln.split()}
|
|
self.assertFalse(any(sym.startswith('_ig_') for sym in guard_export_syms), guard_exports)
|
|
self.assertIn('_rd_io_chk', guard_export_syms)
|
|
self.assertIn('_rd_a0', guard_export_syms)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|