feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固

- 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
This commit is contained in:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+3 -3
View File
@@ -14,7 +14,7 @@ int main(int argc, char **argv) {
assert(argc == 3);
void *sdk = dlopen(argv[1], RTLD_NOW); if (!sdk) { puts(dlerror()); return 1; }
int (*io)(const char *,const char *,size_t) = dlsym(sdk,"archive_fixture_io");
int (*check)(void) = dlsym(sdk,"ig_archive_check");
int (*check)(void) = dlsym(sdk,"rd_io_chk");
uint64_t (*counter)(unsigned) = dlsym(sdk,"ig_archive_counter");
assert(io && check && counter && check() == 0);
assert(!io(argv[2],"abcdef",6));
@@ -59,7 +59,7 @@ int main(int argc, char **argv) {
for (uint64_t k=0;k<s->size/8;k++) {
uint32_t n=indirect[s->reserved1+k];
if (n&(INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
if (!strcmp(strings+symbols[n].n_un.n_strx,"_ig_a0")) slot=(void *)(slide+s->addr+k*8);
if (!strcmp(strings+symbols[n].n_un.n_strx,"_rd_a0")) slot=(void *)(slide+s->addr+k*8);
}
}
}
@@ -71,7 +71,7 @@ int main(int argc, char **argv) {
assert(vm_protect(mach_task_self(),page,vm_page_size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)==KERN_SUCCESS);
*slot=(uintptr_t)dlsym(RTLD_DEFAULT,"fopen");
assert(check()==1);
FILE *(*close_entry)(const char *,const char *) = dlsym(sdk,"ig_a0");
FILE *(*close_entry)(const char *,const char *) = dlsym(sdk,"rd_a0");
assert(close_entry && !close_entry("unused","rb") && errno==EACCES);
*slot=original;
assert(check()==0);
+19 -4
View File
@@ -34,12 +34,19 @@ __attribute__((noinline)) static void *getpid_address(void) { return (void *)get
static int imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
static int imp_replaced(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
static Class make_fixture_class(void) {
Class existing = objc_getClass("IGFixtureHookTarget");
if (existing) return existing;
Class c = objc_allocateClassPair(objc_getClass("NSObject"), "IGFixtureHookTarget", 0);
if (!c) return NULL;
if (!class_addMethod(c, sel_registerName("value"), (IMP)imp_original, "i16@0:8")) {
objc_disposeClassPair(c);
return NULL;
}
Class meta = object_getClass((id)c);
if (!meta || !class_addMethod(meta, sel_registerName("classValue"), (IMP)imp_original, "i16@0:8")) {
objc_disposeClassPair(c);
return NULL;
}
objc_registerClassPair(c);
return c;
}
@@ -143,23 +150,31 @@ int main(int argc, char **argv) {
if (!make_fixture_class()) return 9;
const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } };
if (ig_objc_baseline_capture(watch,1)!=1) return 10;
const IGObjCWatch cls_watch[] = { { "IGFixtureHookTarget", "classValue" } };
if (ig_objc_baseline_append(cls_watch,1)!=1 || ig_objc_baseline_count()!=2) return 12;
if (ig_objc_baseline_append(watch,1)!=0 || ig_objc_baseline_count()!=2) return 13;
/* 未登记的方法在 check 中不产生条目;登记方法未变 → 0 detected。 */
const IGObjCWatch none[] = { { "IGClassThatNeverExists123", "x" } };
ig_objc_baseline_capture(none,1);
if (ig_objc_baseline_check(collect,&f)!=0) return 11; /* 类不可解析不登记 → 仍 no-op */
ig_objc_baseline_capture(watch,1);
ig_objc_baseline_append(cls_watch,1);
int hits=ig_objc_baseline_check(collect,&f);
return hits!=0 || f.detected || f.unavailable;
}
if (!strcmp(argv[1],"objc-swap")) {
Class c=make_fixture_class();
if (!c) return 9;
const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } };
if (ig_objc_baseline_capture(watch,1)!=1) return 10;
/* class_replaceMethod:IMP 换人(等价 swizzle 效果)→ 期望 DETECTED(110)。 */
const IGObjCWatch watch[] = {
{ "IGFixtureHookTarget", "value" },
{ "IGFixtureHookTarget", "+classValue" }
};
if (ig_objc_baseline_capture(watch,2)!=2) return 10;
/* class_replaceMethod:实例方法与类方法同时换人 → 期望 DETECTED(110) x2。 */
class_replaceMethod(c, sel_registerName("value"), (IMP)imp_replaced, "i16@0:8");
class_replaceMethod(object_getClass((id)c), sel_registerName("classValue"), (IMP)imp_replaced, "i16@0:8");
int hits=ig_objc_baseline_check(collect,&f);
return hits!=1 || f.reasons[IG_REASON_OBJC_IMP_CHANGED]!=1;
return hits!=2 || f.reasons[IG_REASON_OBJC_IMP_CHANGED]!=2;
}
return 2;
}
+92 -2
View File
@@ -10,6 +10,8 @@
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
static int early_ok;
__attribute__((constructor)) static void early(void) {
@@ -64,8 +66,75 @@ int main(int argc,char **argv) {
} else if (!strcmp(argv[1],"init-failure")) {
assert(IG_dispatch_write(-1,"x",1)==-1 && errno==ENOSYS);
assert(IG_dispatch_close(-1)==-1 && errno==ENOSYS);
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==2);
assert(reasons[IG_REASON_DISPATCH_UNAVAILABLE]==2);
char b;
assert(IG_dispatch_read(-1,&b,1)==-1 && errno==ENOSYS);
assert(IG_dispatch_open("/dev/null",O_RDONLY)==-1 && errno==ENOSYS);
assert(IG_dispatch_unlink("/tmp/ig-must-not-remove")==-1 && errno==ENOSYS);
assert(IG_dispatch_getpid()==-1 && errno==ENOSYS);
assert(IG_dispatch_fork()==-1 && errno==ENOSYS);
assert(IG_dispatch_dlopen(NULL,RTLD_LAZY)==NULL && errno==ENOSYS);
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==NULL && errno==ENOSYS);
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==11);
assert(reasons[IG_REASON_DISPATCH_UNAVAILABLE]==11);
} else if (!strcmp(argv[1],"extended")) {
char path[]="/tmp/ig-dispatch-XXXXXX";
int fd=mkstemp(path); assert(fd>=0); close(fd); unlink(path);
mode_t mask=umask(0);
errno=EDOM; fd=IG_dispatch_open(path,O_CREAT|O_EXCL|O_RDWR,0600);
umask(mask);
assert(fd>=0 && errno==EDOM);
struct stat st; assert(fstat(fd,&st)==0 && (st.st_mode & 0777)==0600);
assert(IG_dispatch_write(fd,"abc",3)==3); assert(lseek(fd,0,SEEK_SET)==0);
char bytes[16]={0}; errno=ERANGE;
assert(IG_dispatch_read(fd,bytes,sizeof(bytes))==3 && !memcmp(bytes,"abc",3) && errno==ERANGE);
assert(IG_dispatch_read(fd,bytes,sizeof(bytes))==0);
assert(IG_dispatch_close(fd)==0);
fd=IG_dispatch_open(path,O_RDONLY); assert(fd>=0); assert(IG_dispatch_close(fd)==0);
assert(IG_dispatch_open(path,O_CREAT|O_EXCL|O_RDWR,0600)==-1 && errno==EEXIST);
FILE *stream=IG_dispatch_fopen(path,"r");
assert(stream && fgetc(stream)=='a' && fclose(stream)==0);
assert(IG_dispatch_unlink(path)==0);
assert(IG_dispatch_fopen(path,"r")==NULL && errno==ENOENT);
assert(IG_dispatch_open(path,O_RDONLY)==-1 && errno==ENOENT);
assert(IG_dispatch_unlink(path)==-1 && errno==ENOENT);
assert(IG_dispatch_read(-1,bytes,1)==-1 && errno==EBADF);
errno=EDOM; assert(IG_dispatch_getpid()==getpid() && errno==EDOM);
void *self_handle=IG_dispatch_dlopen(NULL,RTLD_LAZY);
assert(self_handle!=NULL);
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==dlsym(RTLD_DEFAULT,"getpid"));
pid_t child=IG_dispatch_fork();
assert(child>=0);
if (child==0) IG_dispatch_exit(42);
int wstatus=0;
assert(waitpid(child,&wstatus,0)==child && WIFEXITED(wstatus) && WEXITSTATUS(wstatus)==42);
} else if (!strcmp(argv[1],"extended-tamper")) {
pid_t child=fork();
assert(child>=0);
if (child==0) {
ig_dispatch_test_override(7,(void *)fake_close);
IG_dispatch_exit(37);
}
int wstatus=0;
assert(waitpid(child,&wstatus,0)==child && WIFEXITED(wstatus) && WEXITSTATUS(wstatus)==37);
for (unsigned i=2;i<11;i++) ig_dispatch_test_override(i,(void *)fake_close);
char bytes[1];
assert(IG_dispatch_read(-1,bytes,1)==-1 && errno==EACCES);
assert(IG_dispatch_open("/dev/null",O_RDONLY)==-1 && errno==EACCES);
assert(IG_dispatch_unlink("/tmp/ig-must-not-remove")==-1 && errno==EACCES);
assert(IG_dispatch_getpid()==-1 && errno==EACCES);
assert(IG_dispatch_fopen("/dev/null","r")==NULL && errno==EACCES);
assert(IG_dispatch_fork()==-1 && errno==EACCES);
assert(IG_dispatch_dlopen(NULL,RTLD_LAZY)==NULL && errno==EACCES);
assert(IG_dispatch_dlsym(RTLD_DEFAULT,"getpid")==NULL && errno==EACCES);
assert(ig_dispatch_check(collect,NULL)==9 && reasons[IG_REASON_DISPATCH_TAMPER]==9);
} else if (!strcmp(argv[1],"read-eintr")) {
int p[2]; assert(pipe(p)==0);
struct sigaction action={0};action.sa_handler=signal_handler;sigemptyset(&action.sa_mask);
assert(sigaction(SIGUSR1,&action,NULL)==0);
main_thread=pthread_self();pthread_t thread;
assert(pthread_create(&thread,NULL,interruptor,NULL)==0);
char b; assert(IG_dispatch_read(p[0],&b,1)==-1 && errno==EINTR);
pthread_join(thread,NULL);IG_dispatch_close(p[1]);IG_dispatch_close(p[0]);
} else if (!strcmp(argv[1],"semantics")) {
assert(ig_dispatch_check(collect,NULL)==0 && unavailable==0);
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
@@ -123,9 +192,30 @@ int main(int argc,char **argv) {
} else if (!strcmp(argv[1],"prologue")) {
assert(ig_arm64_suspicious_prologue(0x14000001,0));
assert(ig_arm64_suspicious_prologue(0x58000050,0xd61f0200));
assert(ig_arm64_suspicious_prologue(0x58000049,0xd61f0120)); /* ldr x9; br x9 */
assert(!ig_arm64_suspicious_prologue(0x58000050,0xd61f0220));
assert(!ig_arm64_suspicious_prologue(0x18000050,0xd61f0200));
assert(!ig_arm64_suspicious_prologue(0xd503245f,0xd65f03c0));
const uint32_t clean_win[8] = {
0xd503237fu, 0xa9bf7bfdu, 0x910003fdu, 0xaa0003f3u,
0xf100001fu, 0x54000080u, 0xd503201fu, 0xd65f03c0u
};
assert(!ig_arm64_suspicious_window(clean_win, 8));
const uint32_t adrp_win[8] = {
0xd503237fu, 0x9000000au, 0x9100414au, 0xd61f0140u,
0xd503201fu, 0xd503201fu, 0xd503201fu, 0xd503201fu
};
assert(ig_arm64_suspicious_window(adrp_win, 8));
const uint32_t movk_win[8] = {
0xd280000bu, 0xf2c2468bu, 0xd61f0160u, 0xd503201fu,
0xd503201fu, 0xd503201fu, 0xd503201fu, 0xd503201fu
};
assert(ig_arm64_suspicious_window(movk_win, 8));
const uint32_t mid_ldr_win[8] = {
0xd503237fu, 0xa9bf7bfdu, 0x910003fdu, 0x58000050u,
0xd61f0200u, 0xd503201fu, 0xd503201fu, 0xd503201fu
};
assert(ig_arm64_suspicious_window(mid_ldr_win, 8));
} else return 2;
return 0;
}
+106
View File
@@ -0,0 +1,106 @@
#import <Foundation/Foundation.h>
#import "GCDWebServerPrivate.h"
#include "dispatch/IGDispatch.h"
#include <assert.h>
#include <dlfcn.h>
#include <errno.h>
#include <unistd.h>
static void forbidden(void) { abort(); }
static GCDWebServerFileRequest *request(void) {
return [[GCDWebServerFileRequest alloc] initWithMethod:@"POST"
url:[NSURL URLWithString:@"http://localhost/upload"]
headers:@{@"Content-Type": @"application/octet-stream", @"Content-Length": @"10"}
path:@"/upload" query:nil];
}
static void multipart(BOOL reject) {
NSString *path = nil;
@autoreleasepool {
GCDWebServerMultiPartFormRequest *upload = [[GCDWebServerMultiPartFormRequest alloc]
initWithMethod:@"POST" url:[NSURL URLWithString:@"http://localhost/upload"]
headers:@{@"Content-Type": @"multipart/form-data; boundary=ig-test-boundary",
@"Content-Length": @"1024"} path:@"/upload" query:nil];
assert([upload open:NULL]);
NSString *body = [@"0123456789" stringByPaddingToLength:512 withString:@"abcdefghij" startingAtIndex:0];
NSString *first = [@"--ig-test-boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"sample.txt\"\r\n\r\n"
stringByAppendingString:body];
assert([upload writeData:[first dataUsingEncoding:NSUTF8StringEncoding] error:NULL]);
if (reject) ig_dispatch_test_override(0, (void *)forbidden);
NSError *error = nil;
NSData *last = [@"\r\n--ig-test-boundary--\r\n" dataUsingEncoding:NSUTF8StringEncoding];
if (reject) {
assert(![upload writeData:last error:&error] && error);
assert(upload.files.count == 0);
assert(![upload close:NULL]);
} else {
assert([upload writeData:last error:&error]);
assert([upload close:&error]);
assert(upload.files.count == 1);
path = [upload.files.firstObject.temporaryPath copy];
assert([[NSData dataWithContentsOfFile:path] isEqualToData:[body dataUsingEncoding:NSUTF8StringEncoding]]);
}
}
if (path) assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
}
int main(int argc, char **argv) {
assert(argc == 2);
@autoreleasepool {
NSString *mode = @(argv[1]);
ig_dispatch_response_configure(0, -1);
if ([mode hasPrefix:@"multipart"]) {
multipart([mode isEqualToString:@"multipart-tamper"]);
return 0;
}
NSString *path;
@autoreleasepool {
GCDWebServerFileRequest *upload = request();
path = [upload.temporaryPath copy];
NSError *error = nil;
if ([mode isEqualToString:@"open-tamper"]) {
ig_dispatch_test_override(3, (void *)forbidden);
assert(![upload open:&error] && error.code == EACCES);
assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
return 0;
}
int stdinCopy = -1;
if ([mode isEqualToString:@"fd-zero"]) {
stdinCopy = dup(STDIN_FILENO);
close(STDIN_FILENO);
}
assert([upload open:&error]);
NSData *body = [@"0123456789" dataUsingEncoding:NSUTF8StringEncoding];
if ([mode isEqualToString:@"write-tamper"]) {
ig_dispatch_test_override(0, (void *)forbidden);
assert(![upload writeData:body error:&error] && error.code == EACCES);
assert([NSData dataWithContentsOfFile:path].length == 0);
assert([upload close:NULL]);
return 0;
}
assert([upload writeData:body error:&error]);
assert([upload close:&error]);
if (stdinCopy >= 0) { assert(dup2(stdinCopy, STDIN_FILENO) >= 0); close(stdinCopy); }
assert([[NSData dataWithContentsOfFile:path] isEqualToData:body]);
GCDWebServerFileResponse *response = [GCDWebServerFileResponse
responseWithFile:path byteRange:NSMakeRange(2, 4)];
assert(response && [response open:&error]);
if ([mode isEqualToString:@"read-tamper"] || [mode isEqualToString:@"terminate"]) {
ig_dispatch_test_override(2, (void *)forbidden);
if ([mode isEqualToString:@"terminate"]) ig_dispatch_response_configure(1, -1);
assert([response readData:&error] == nil && error.code == EACCES);
assert(![mode isEqualToString:@"terminate"]);
} else {
NSData *chunk = [response readData:&error];
assert([chunk isEqualToData:[@"2345" dataUsingEncoding:NSUTF8StringEncoding]]);
assert([response readData:&error].length == 0);
}
[response close];
}
// 请求生命周期结束后仍通过受保护 unlink 清理临时文件。
assert(![[NSFileManager defaultManager] fileExistsAtPath:path]);
}
return 0;
}
+315
View File
@@ -0,0 +1,315 @@
"""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 <stdint.h>
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
__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()
+16 -1
View File
@@ -32,6 +32,21 @@ class FrameworkRewriteTests(unittest.TestCase):
m = Macho(data)
self.assertEqual(m.ncmds, Macho(self.data).ncmds+1)
self.assertEqual(data[32768:212992], self.data[32768:212992])
def test_explicit_fopen_subset(self):
data, report = rewrite(self.data, SHA, {'_fopen': '_rd_a0'})
self.assertEqual(report['total_symbols'], 1)
self.assertEqual(len(report['changes']), 2)
self.assertEqual({r['source'] for r in report['changes']}, {'_fopen'})
self.assertIn(b'_fread\0', data)
self.assertIn(b'_fwrite\0', data)
self.assertIn(b'_fclose\0', data)
self.assertTrue(report['machine_code_unchanged'])
def test_unknown_or_empty_subset_rejected(self):
for mapping in ({}, {'_fopen': '_unexpected'}, {'_open': '_rd_a0'}):
with self.subTest(mapping=mapping), self.assertRaises(ValueError):
rewrite(self.data, SHA, mapping)
def test_wrong_hash(self):
with self.assertRaises(ValueError): rewrite(self.data, '0'*64)
def test_repeat_rejected(self):
@@ -95,7 +110,7 @@ class ArchiveBindingIntegrationTests(unittest.TestCase):
def test_real_dyld_binding_and_got_tamper(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder)
guard = root/'IGArchiveGuard.framework/IGArchiveGuard'
guard = root/'RDCoreIO.framework/RDCoreIO'
sdk = root/'SSZipArchive.framework/SSZipArchive'
guard.parent.mkdir(); sdk.parent.mkdir()
common = ['xcrun','--sdk','macosx','clang','-arch','arm64','-mmacosx-version-min=13.0','-O2']
+12
View File
@@ -25,6 +25,9 @@ class DispatchTests(unittest.TestCase):
def run_mode(self,mode):
p=subprocess.run([str(self.exe),mode],capture_output=True,text=True,env=self.env,timeout=30)
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
def test_extended_file_semantics(self):self.run_mode('extended')
def test_extended_tamper_rejected(self):self.run_mode('extended-tamper')
def test_read_eintr(self):self.run_mode('read-eintr')
def test_semantics(self):self.run_mode('semantics')
def test_short_write(self):self.run_mode('short-write')
def test_eintr(self):self.run_mode('eintr')
@@ -52,6 +55,15 @@ class DispatchTests(unittest.TestCase):
'-c',str(ROOT/'defender'/p),'-o',str(Path(self.tmp.name)/f'{i}.o')],
capture_output=True,text=True)
self.assertEqual(r.returncode,0,r.stderr)
# The Release objects must not introduce direct references to
# any of the 12 report symbols they shield or use internally.
forbidden = {'_write','_close','_read','_open','_unlink','_getpid','_fopen',
'_exit','_fork','_dlopen','_dlsym','_syscall'}
for i in range(len(SOURCES)):
r=subprocess.run(['xcrun','nm','-u',str(Path(self.tmp.name)/f'{i}.o')],
capture_output=True,text=True,check=True)
undefined={line.split()[-1] for line in r.stdout.splitlines() if line.split()}
self.assertFalse(undefined & forbidden, f'{SOURCES[i]}: {r.stdout}')
def test_initialization_failure(self):
obj=Path(self.tmp.name)/'missing-resolver.o'
exe=Path(self.tmp.name)/'init-failure'
+82
View File
@@ -0,0 +1,82 @@
"""编译 App 副本的真实 GCDWebServer 和 Defender,验证文件流程与异常处置。"""
from pathlib import Path
import os
import signal
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
APP = ROOT / 'readoor-test/readoor'
GCD = APP / 'BookShelf/Classes/Factorys/GCDWebServer'
DEFENDER = APP / '3.0/Base/Security/IGDefender'
@unittest.skipUnless(sys.platform == 'darwin' and GCD.exists(), '需要 macOS 和 App 副本')
class GCDFileIntegrationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.exe = Path(cls.tmp.name) / 'gcd-file-test'
cls.env = dict(os.environ)
cls.env.pop('DYLD_INSERT_LIBRARIES', None)
cls.includes = [arg for p in (GCD/'Core', GCD/'Requests', GCD/'Responses',
DEFENDER, DEFENDER/'include') for arg in ('-I', str(p))]
sources = [str(p) for p in GCD.rglob('*.m')]
sources += [str(DEFENDER/p) for p in ('dispatch/IGDispatch.c', 'resolve/IGResolve.c',
'anti_hook/IGAntiHook.c')]
command = ['xcrun', '--sdk', 'macosx', 'clang', '-O2', '-fobjc-arc',
'-DIG_DISPATCH_TESTING', '-DIG_HOOK_TERMINATE_DEFAULT=0',
*cls.includes, str(ROOT/'tests/fixtures/gcd_file_integration.m'), *sources,
'-framework', 'Foundation', '-framework', 'CFNetwork',
'-framework', 'SystemConfiguration', '-framework', 'Security',
'-framework', 'CoreServices',
'-lz', '-o', str(cls.exe)]
result = subprocess.run(command, capture_output=True, text=True, env=cls.env)
if result.returncode:
raise RuntimeError(result.stderr)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_mode(self, mode, expected=0):
result = subprocess.run([str(self.exe), mode], capture_output=True, text=True,
env=self.env, timeout=30)
self.assertEqual(result.returncode, expected, result.stdout + result.stderr)
def test_upload_range_read_and_cleanup(self): self.run_mode('normal')
def test_multipart_stream_and_cleanup(self): self.run_mode('multipart-normal')
def test_multipart_failed_write(self): self.run_mode('multipart-tamper')
def test_descriptor_zero_is_valid(self): self.run_mode('fd-zero')
def test_open_tamper_creates_no_file(self): self.run_mode('open-tamper')
def test_write_tamper_writes_no_data(self): self.run_mode('write-tamper')
def test_read_tamper_returns_error(self): self.run_mode('read-tamper')
def test_existing_termination_policy_is_preserved(self):
result = subprocess.run([str(self.exe), 'terminate'], capture_output=True, text=True,
env=self.env, timeout=30)
self.assertIn(result.returncode, (-signal.SIGTRAP, -signal.SIGILL), result.stdout + result.stderr)
def test_ios_release_objects_use_protected_entries(self):
for relative, protected in [
('Core/GCDWebServer.m', {'close'}),
('Core/GCDWebServerConnection.m', {'close'}),
('Requests/GCDWebServerMultiPartFormRequest.m', {'open', 'write', 'close', 'unlink'}),
('Requests/GCDWebServerFileRequest.m', {'open', 'write', 'close', 'unlink'}),
('Responses/GCDWebServerFileResponse.m', {'open', 'read', 'close'})
]:
obj = Path(self.tmp.name) / (Path(relative).stem + '.o')
result = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
'-miphoneos-version-min=15.0', '-O2', '-fobjc-arc', *self.includes,
'-c', str(GCD/relative), '-o', str(obj)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run(['xcrun', 'nm', '-u', str(obj)],
capture_output=True, text=True, check=True)
symbols = {line.split()[-1] for line in result.stdout.splitlines() if line.split()}
self.assertTrue({'_IG_dispatch_' + n for n in protected} <= symbols, symbols)
self.assertFalse({'_' + n for n in protected} & symbols, symbols)
if __name__ == '__main__':
unittest.main()
+398
View File
@@ -0,0 +1,398 @@
"""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 <stdint.h>
__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 <Foundation/Foundation.h>
@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<O2>,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()
+460
View File
@@ -0,0 +1,460 @@
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
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()
class TestIndirectCallPass(unittest.TestCase):
def test_c_same_tu_cross_tu_dead_strip_and_dylib_safety(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-c-') 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': 'caller.c'}],
'indirect_call_targets': [{'path_contains': 'caller.c'}],
'indirect_call_same_image_prefixes': ['rd_ext_'],
'flatten_targets': [{'path_contains': 'caller.c'}],
}), encoding='utf-8')
(p / 'ext_callee.c').write_text(
'int rd_ext_compute(int a, int b) {\n'
' return (a * 3) + (b ^ 0x11);\n'
'}\n'
'int rd_ext_unused(int x) {\n'
' return x * 999;\n'
'}\n',
encoding='utf-8',
)
(p / 'caller.c').write_text(
'#include <stdlib.h>\n'
'#include <unistd.h>\n'
'extern int rd_ext_compute(int a, int b);\n'
'__attribute__((noinline)) static int local_step(int v) {\n'
' return v + 19;\n'
'}\n'
'__attribute__((noinline)) int run_pipeline(int x) {\n'
' const char *env = getenv("IG_NONEXISTENT_ENV_TEST");\n'
' int pid_bit = (getpid() > 0) ? 1 : 0;\n'
' int a = local_step(x + pid_bit);\n'
' int b = rd_ext_compute(a, env ? 7 : 5);\n'
' return local_step(b);\n'
'}\n'
'int main(void) {\n'
' int got = run_pipeline(10);\n'
' return (got == 129) ? 0 : 2;\n'
'}\n',
encoding='utf-8',
)
# Verify expected math: pid_bit=1 -> a=local_step(11)=30 -> b=30*3+(5^0x11)=90+20=110 -> local_step(110)=129
subprocess.run([clang, '-isysroot', sdk, '-O2', '-c', str(p / 'ext_callee.c'), '-o', str(p / 'ext.o')], check=True)
subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(p / 'caller.c'), '-o', str(p / 'caller.bc')], check=True)
def build_with(seed: str, pass_filter: str, tag: str):
obf_bc = p / f'caller_{tag}.bc'
obj_o = p / f'caller_{tag}.o'
audit_p = p / f'audit_{tag}.json'
exe_p = p / f'exe_{tag}'
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={p / "caller.c"}',
f'--ig-audit-out={audit_p}',
str(p / 'caller.bc'), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-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, str(obj_o), str(p / 'ext.o'),
'-Wl,-dead_strip', '-o', str(exe_p),
], check=True)
return obj_o, exe_p, json.loads(audit_p.read_text(encoding='utf-8'))
o_a1, exe_a1, aud_a1 = build_with('seed_alpha', 'all', 'a1')
o_a2, _, aud_a2 = build_with('seed_alpha', 'all', 'a2')
o_b1, exe_b1, aud_b1 = build_with('seed_beta', 'all', 'b1')
_, exe_icall, aud_icall = build_with('seed_alpha', 'icall', 'icall_only')
_, _, aud_str = build_with('seed_alpha', 'str', 'str_only')
# Determinism & polymorphism
self.assertEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_a2.read_bytes()).hexdigest())
self.assertNotEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_b1.read_bytes()).hexdigest())
self.assertEqual(aud_a1['indirect_calls_count'], 4) # 2x local_step + 1x rd_ext_compute + 1x main->run_pipeline
self.assertEqual(aud_a2['indirect_calls_count'], 4)
self.assertEqual(aud_b1['indirect_calls_count'], 4)
# Pass filter isolation
self.assertEqual(aud_icall['indirect_calls_count'], 4)
self.assertEqual(aud_icall['strings_encrypted_count'], 0)
self.assertEqual(len(aud_icall['functions_flattened']), 0)
self.assertEqual(aud_str['indirect_calls_count'], 0)
# Runtime execution on host arm64
for exe in (exe_a1, exe_b1, exe_icall):
rc = subprocess.run([str(exe)]).returncode
self.assertEqual(rc, 0)
# Disassembly & dead_strip checks
nm_exe = subprocess.check_output(['xcrun', 'nm', str(exe_a1)], text=True)
self.assertIn('_rd_ext_compute', nm_exe)
self.assertNotIn('_rd_ext_unused', nm_exe) # dead_strip still strips unreferenced function
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*_rd_ext_compute\b', dis))
self.assertIsNone(re.search(r'\bbl\s+.*_local_step\b', dis))
self.assertIsNone(re.search(r'\bbl\s+.*_run_pipeline\b', dis))
self.assertIsNotNone(re.search(r'\bblr\s+x\d+\b', dis))
def test_objc_arc_attachedcall_rv_preservation(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-arc-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'indirect_call_targets': [{'path_contains': 'arc_caller.m'}],
'indirect_call_same_image_prefixes': ['rd_arc_'],
'flatten_targets': [{'path_contains': 'arc_caller.m'}],
}), encoding='utf-8')
(p / 'arc_provider.m').write_text(
'#import <Foundation/Foundation.h>\n'
'NSString *rd_arc_make_token(int idx) {\n'
' return [NSString stringWithFormat:@"tok_%d_ok", idx ^ 0x2a];\n'
'}\n',
encoding='utf-8',
)
(p / 'arc_caller.m').write_text(
'#import <Foundation/Foundation.h>\n'
'extern NSString *rd_arc_make_token(int idx);\n'
'__attribute__((noinline)) static NSUInteger verify_batch(int n) {\n'
' NSUInteger total = 0;\n'
' for (int i = 0; i < n; ++i) {\n'
' NSString *s = rd_arc_make_token(i);\n'
' total += s.length;\n'
' }\n'
' return total;\n'
'}\n'
'int main(void) {\n'
' @autoreleasepool {\n'
' NSUInteger got = verify_batch(500);\n'
' return (got > 3000) ? 0 : 3;\n'
' }\n'
'}\n',
encoding='utf-8',
)
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-c', str(p / 'arc_provider.m'), '-o', str(p / 'prov.o')], check=True)
subprocess.run([clang, '-isysroot', sdk, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(p / 'arc_caller.m'), '-o', str(p / 'caller.bc')], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-seed=arc_seed_1',
f'--ig-source-path={p / "arc_caller.m"}',
f'--ig-audit-out={p / "audit.json"}',
str(p / 'caller.bc'), '-o', str(p / 'caller.obf.bc'),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-O2',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(p / 'caller.obf.bc'), '-o', str(p / 'caller.o'),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-framework', 'Foundation',
str(p / 'caller.o'), str(p / 'prov.o'), '-Wl,-dead_strip', '-o', str(p / 'arc_exe'),
], check=True)
audit = json.loads((p / 'audit.json').read_text(encoding='utf-8'))
self.assertGreaterEqual(audit['indirect_calls_count'], 2)
rc = subprocess.run([str(p / 'arc_exe')]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'arc_exe')], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*_rd_arc_make_token\b', dis))
def test_swift_cross_file_throws_and_extension_indirect_calls(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
swiftc = detect_stock_tool('swiftc')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-swift-') as td:
p = Path(td).resolve()
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'indirect_call_targets': [{'path_contains': '.swift'}],
'flatten_targets': [{'path_contains': '.swift'}],
}), encoding='utf-8')
(p / 'Callee.swift').write_text(
'import Foundation\n'
'enum DemoErr: Error { case bad }\n'
'public struct KeyWorker {\n'
' @inline(never)\n'
' public static func derive(_ x: Int) throws -> Int {\n'
' if x < 0 { throw DemoErr.bad }\n'
' return (x * 7) ^ 0x33\n'
' }\n'
'}\n',
encoding='utf-8',
)
(p / 'ExtOnly.swift').write_text(
'import Foundation\n'
'extension NSString {\n'
' @inline(never)\n'
' func callModuleWorker(_ v: Int) -> Int {\n'
' return ((try? KeyWorker.derive(v)) ?? -1) + self.length\n'
' }\n'
'}\n',
encoding='utf-8',
)
(p / 'Main.swift').write_text(
'import Foundation\n'
'@main\n'
'struct Runner {\n'
' static func main() {\n'
' let s: NSString = "hello"\n'
' let r1 = s.callModuleWorker(6)\n'
' let r2 = (try? KeyWorker.derive(-3)) ?? 99\n'
' if r1 != ((42 ^ 0x33) + 5) || r2 != 99 {\n'
' exit(4)\n'
' }\n'
' }\n'
'}\n',
encoding='utf-8',
)
# Compile multi-file Swift module with -lto=llvm-thin to produce per-file bitcode just like Xcode Release
ofm = {
str(p / 'Callee.swift'): {'object': str(p / 'Callee.bc')},
str(p / 'ExtOnly.swift'): {'object': str(p / 'ExtOnly.bc')},
str(p / 'Main.swift'): {'object': str(p / 'Main.bc')},
}
(p / 'ofm.json').write_text(json.dumps(ofm), encoding='utf-8')
subprocess.run([
swiftc, '-sdk', sdk, '-module-name', 'IcallDemoApp',
'-O', '-whole-module-optimization', '-num-threads', '3',
'-g', '-lto=llvm-thin', '-parse-as-library',
'-output-file-map', str(p / 'ofm.json'),
'-c', str(p / 'Callee.swift'), str(p / 'ExtOnly.swift'), str(p / 'Main.swift'),
], cwd=p, check=True)
objs = []
audits = {}
for stem in ('Callee', 'ExtOnly', 'Main'):
bc_p = p / f'{stem}.bc'
obf_bc = p / f'{stem}.obf.bc'
obj_o = p / f'{stem}.o'
aud_p = p / f'{stem}.audit.json'
subprocess.run([
opt_path, '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-seed=swift_icall_seed',
f'--ig-source-path={p / (stem + ".swift")}',
'--ig-swift-module=IcallDemoApp',
f'--ig-audit-out={aud_p}',
str(bc_p), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-O2',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
objs.append(str(obj_o))
audits[stem] = json.loads(aud_p.read_text(encoding='utf-8'))
subprocess.run([
swiftc, '-sdk', sdk, *objs, '-Xlinker', '-dead_strip', '-o', str(p / 'swift_exe'),
], check=True)
# Both ExtOnly.swift (extension-only file!) and Main.swift must indirect-call cross-file Swift targets
self.assertGreaterEqual(audits['ExtOnly']['indirect_calls_count'], 1)
self.assertGreaterEqual(audits['Main']['indirect_calls_count'], 2)
rc = subprocess.run([str(p / 'swift_exe')]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(p / 'swift_exe')], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*KeyWorker.*derive', dis))
self.assertIsNone(re.search(r'\bbl\s+.*callModuleWorker', dis))
def test_source_path_scrubbing_pass(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-scrub-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'scrub_path_substrings': ['/tmp/ig-ipa-work/', '/Users/shenlei/', '/src/readoor/'],
'string_encrypt_targets': [{'path_contains': 'TargetFile.c'}],
'indirect_call_targets': [],
'flatten_targets': [],
}), encoding='utf-8')
(p / 'TargetFile.c').write_text(
'#include <stdio.h>\n'
'const char *get_paths(int idx) {\n'
' static const char *const kPaths[] = {\n'
' "/tmp/ig-ipa-work/src/readoor/3.0/Secret.swift",\n'
' "/Users/shenlei/Work/Secret.m",\n'
' "./readoor/BookView/Reader.swift",\n'
' "readoorApp/OnlyFile.swift",\n'
' "KEEP_NON_PATH_TOKEN",\n'
' };\n'
' return kPaths[idx % 5];\n'
'}\n'
'int main(void) {\n'
' puts(get_paths(0));\n'
' puts(get_paths(3));\n'
' puts(get_paths(4));\n'
' return 0;\n'
'}\n',
encoding='utf-8',
)
bc_p = p / 'TargetFile.bc'
obf_bc = p / 'TargetFile.obf.bc'
obj_o = p / 'TargetFile.o'
audit_p = p / 'scrub.audit.json'
subprocess.run([clang, '-isysroot', sdk, '-O2', '-emit-llvm', '-c', str(p / 'TargetFile.c'), '-o', str(bc_p)], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-pass-filter=all',
'--ig-seed=scrub_seed_1',
'--ig-source-path=TargetFile.c',
'--ig-swift-module=readoorApp',
f'--ig-audit-out={audit_p}',
str(bc_p), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
audit = json.loads(audit_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(audit.get('paths_scrubbed_count', 0), 4, audit)
obj_raw = obj_o.read_bytes()
for leaked in (b'/tmp/ig-ipa-work/', b'/Users/shenlei/', b'Secret.swift', b'OnlyFile.swift'):
self.assertNotIn(leaked, obj_raw)
self.assertIn(b'ig_p_', obj_raw)
def test_indirect_call_dual_table_mode(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-icall-dual-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'indirect_call_targets': [{'path_contains': 'dual_icall.c'}],
'indirect_call_same_image_prefixes': ['dt_'],
'indirect_call_dual_table': True,
}), encoding='utf-8')
src_c = p / 'dual_icall.c'
src_c.write_text(
'''#include <stdint.h>
__attribute__((noinline))
int dt_helper_add(int a, int b) { return a + b + 3; }
__attribute__((noinline))
int dt_helper_mul(int a, int b) { return a * b ^ 0x17; }
int main(void) {
int x = dt_helper_add(5, 9);
int y = dt_helper_mul(x, 4);
if (x != 17 || y != (68 ^ 0x17)) return 1;
return 0;
}
''',
encoding='utf-8',
)
bc_p = p / 'dual_icall.bc'
obf_ll = p / 'dual_icall.obf.ll'
obj_o = p / 'dual_icall.o'
exe_p = p / 'dual_icall_exe'
audit_p = p / 'dual_icall.audit.json'
subprocess.run([clang, '-isysroot', sdk, '-O2', '-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=full',
'--ig-seed=dual_table_seed_1',
f'--ig-source-path={src_c}',
f'--ig-audit-out={audit_p}',
str(bc_p), '-o', str(obf_ll),
], check=True)
ir_txt = obf_ll.read_text(encoding='utf-8')
audit = json.loads(audit_p.read_text(encoding='utf-8'))
self.assertTrue(audit.get('indirect_call_dual_table'), audit)
self.assertGreaterEqual(audit.get('indirect_calls_count', 0), 2, audit)
self.assertIn('__ig_cs1_', ir_txt)
self.assertIn('__ig_cs2_', ir_txt)
self.assertNotIn('__ig_ct_', ir_txt)
subprocess.run([
clang, '-isysroot', sdk, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_o),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, str(obj_o), '-Wl,-dead_strip', '-o', str(exe_p),
], check=True)
rc = subprocess.run([str(exe_p)]).returncode
self.assertEqual(rc, 0)
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_p)], text=True)
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_add', dis), dis)
self.assertIsNone(re.search(r'\bbl\s+.*dt_helper_mul', dis), dis)
if __name__ == '__main__':
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""Exercise legacy lazy binding on the reviewed AliyunPlayer arm64 SDK."""
import hashlib
from pathlib import Path
import struct
import sys
import unittest
import zipfile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/macho_guard'))
from batch import arm64_slices, Slice
from redirect_legacy_fopen import rewrite
from machox import Macho
IPA = ROOT / 'appstore.ipa'
@unittest.skipUnless(IPA.exists(), '需要归档 IPA 中的 AliyunPlayer')
class LegacyFopenTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with zipfile.ZipFile(IPA) as archive:
names = [n for n in archive.namelist() if n.endswith('/AliyunPlayer.framework/AliyunPlayer')]
if len(names) != 1:
raise ValueError('需要唯一 AliyunPlayer')
data = archive.read(names[0])
offset, size = arm64_slices(data)[0]
cls.data = data[offset:offset + size]
def apply(self, data):
return rewrite(data, hashlib.sha256(data).hexdigest())
def test_real_lazy_binding(self):
result, report = self.apply(self.data)
self.assertTrue(report['lazy_offsets_preserved'])
self.assertTrue(report['section_bytes_unchanged'])
self.assertEqual(Slice(self.data, 0).scan()['_fopen'], 28)
self.assertEqual(Slice(result, 0).scan()['_fopen'], 0)
self.assertEqual(len(result), len(self.data))
before = Macho(self.data)
after = Macho(result)
old = next(o for c, _, o in before.cmds if c == 0x80000022)
new = next(o for c, _, o in after.cmds if c == 0x80000022)
self.assertEqual(self.data[old + 8:old + 48], result[new + 8:new + 48])
self.assertEqual(report['new_ordinal'], 33)
def test_hash_mismatch(self):
with self.assertRaises(ValueError):
rewrite(self.data, '0' * 64)
def test_repeat_rejected(self):
result, _ = self.apply(self.data)
with self.assertRaises(ValueError):
self.apply(result)
def test_no_header_space(self):
data = bytearray(self.data)
data[32 + Macho(data).sizeofcmds] = 1
with self.assertRaises(ValueError):
self.apply(bytes(data))
def test_wrong_lazy_provider(self):
data = bytearray(self.data)
m = Macho(data)
off = next(o for c, _, o in m.cmds if c == 0x80000022)
lazy, size = struct.unpack_from('<II', data, off + 32)
symbol = data.index(b'_fopen\0', lazy, lazy + size)
self.assertEqual(data[symbol - 3:symbol], b'\x20\x20\x40')
data[symbol - 2] = 1
with self.assertRaises(ValueError):
self.apply(bytes(data))
if __name__ == '__main__':
unittest.main()
+415
View File
@@ -0,0 +1,415 @@
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 <Foundation/Foundation.h>\n'
'#include <stdlib.h>\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 <pthread.h>\n'
'#include <stdatomic.h>\n'
'#include <stdio.h>\n'
'#include <string.h>\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()
+234
View File
@@ -0,0 +1,234 @@
import hashlib
import json
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'
APP_REPO = ROOT / 'readoor-test'
sys.path.insert(0, str(TOOLS_LLVM_OBF))
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # 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 TestLLVMObfM1(unittest.TestCase):
def test_polymorphic_flattening_topologies_encodings_and_inline_asm_skip(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': 'poly_test.c'}],
}), encoding='utf-8')
src = p / 'poly_test.c'
src.write_text(
'#include <stdio.h>\n'
'#include <stdint.h>\n'
'__attribute__((noinline)) int leaf_fn(int a, int b) { return a * 17 + b * 31; }\n'
'int poly_multi_branch(int x, int y) {\n'
' int acc = 7;\n'
' if (x & 1) acc += leaf_fn(x, 1);\n'
' if (x & 2) acc ^= leaf_fn(y, 2);\n'
' if (x & 4) acc += leaf_fn(x + y, 3);\n'
' if (x & 8) acc -= leaf_fn(y - x, 4);\n'
' if (x > 12) acc += leaf_fn(x, y);\n'
' if (y < 0) acc ^= 0x5A5A;\n'
' if (acc > 200) acc -= 19;\n'
' return acc;\n'
'}\n'
'int has_inline_asm(int v) {\n'
' int out = v;\n'
' if (v > 3) { __asm__ volatile("" : "+r"(out)); }\n'
' return out + 1;\n'
'}\n'
'int main(void) {\n'
' uint32_t h = 2166136261u;\n'
' for (int x = -4; x < 24; ++x) {\n'
' for (int y = -3; y < 5; ++y) {\n'
' uint32_t v = (uint32_t)poly_multi_branch(x, y);\n'
' h = (h ^ v) * 16777619u;\n'
' }\n'
' }\n'
' printf("HASH=%08x ASM=%d\\n", h, has_inline_asm(5));\n'
' return 0;\n'
'}\n',
encoding='utf-8',
)
bc_p = p / 'poly.bc'
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', '-g', '-emit-llvm', '-c', str(src), '-o', str(bc_p)], check=True)
# Reference un-obfuscated output
ref_bin = p / 'poly_ref'
subprocess.run([clang, '-isysroot', macos_sdk, '-Os', str(src), '-o', str(ref_bin)], check=True)
ref_out = subprocess.check_output([str(ref_bin)], text=True).strip()
seen_topos = set()
seen_encs = set()
asm_skip_seen = False
for idx in range(24):
seed = f'm1_poly_probe_{idx}'
obf_bc = p / f'poly_{idx}.obf.bc'
obj_o = p / f'poly_{idx}.o'
bin_p = p / f'poly_{idx}'
audit_p = p / f'audit_{idx}.json'
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_p}', '--ig-mode=full',
f'--ig-seed={seed}', f'--ig-source-path={src}',
f'--ig-audit-out={audit_p}', str(bc_p), '-o', str(obf_bc),
], check=True)
audit = json.loads(audit_p.read_text(encoding='utf-8'))
for det in audit.get('functions_flattened_details') or []:
if 'poly_multi_branch' in det['name']:
seen_topos.add(det['topology'])
seen_encs.add(det['encoding'])
for sk in audit.get('functions_skipped') or []:
if 'has_inline_asm' in sk['name'] and sk['reason'] == 'inline_asm':
asm_skip_seen = True
# Execute every topology/encoding variant and check exact semantic output!
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_o),
], check=True)
subprocess.run([clang, '-isysroot', macos_sdk, str(obj_o), '-o', str(bin_p)], check=True)
out = subprocess.check_output([str(bin_p)], text=True).strip()
self.assertEqual(out, ref_out, f'Semantic mismatch on seed={seed}: {out} vs {ref_out}')
self.assertEqual(seen_topos, {'sparse_switch', 'cascaded_subdisp', 'asymmetric_cmp_tree'}, f'Missing topologies: {seen_topos}')
self.assertEqual(seen_encs, {'xor_rot', 'odd_affine_mul', 'add_xor'}, f'Missing encodings: {seen_encs}')
self.assertTrue(asm_skip_seen, 'Expected inline_asm skip reason for has_inline_asm')
def test_epub_keybox_derivation_obfuscation_and_poisoning(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()
keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.c'
keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDEpubKeyBox.h'
defender_dir = ROOT / 'defender'
poison_c = defender_dir / 'poison/IGPoison.c'
policy_path = ROOT / 'config/ig_llvm_policy.json'
self.assertTrue(keybox_c.is_file() and keybox_h.is_file())
with tempfile.TemporaryDirectory() as td:
p = Path(td)
kb_bc = p / 'RDEpubKeyBox.bc'
kb_obf_bc = p / 'RDEpubKeyBox.obf.bc'
kb_o = p / 'RDEpubKeyBox.o'
audit_p = p / 'kb.audit.json'
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os', '-g', '-fvisibility=hidden',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
'-I', str(keybox_c.parent),
'-emit-llvm', '-c', str(keybox_c), '-o', str(kb_bc),
], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full',
'--ig-seed=m1_unit_kb_seed', f'--ig-source-path={keybox_c}',
f'--ig-audit-out={audit_p}', str(kb_bc), '-o', str(kb_obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(kb_obf_bc), '-o', str(kb_o),
], check=True)
audit = json.loads(audit_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(audit['strings_encrypted_count'], 2, audit)
self.assertGreaterEqual(len(audit['functions_flattened']), 2, audit)
self.assertTrue(audit['functions_flattened_details'])
raw_o = kb_o.read_bytes()
self.assertNotIn(b'startiasoft', raw_o)
self.assertNotIn(b'_rdep_', raw_o)
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(kb_o)], text=True)
self.assertNotIn('_CC_MD5', nm_u)
harness_c = p / 'harness.c'
harness_c.write_text(
'#include <stdio.h>\n'
'#include <string.h>\n'
'#include "RDEpubKeyBox.h"\n'
'#include "poison/IGPoison.h"\n'
'int main(void) {\n'
' char out[512];\n'
' const char *books[] = {"", "BK2026", "book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};\n'
' for (int i = 0; i < 3; ++i) {\n'
' size_t n = rd_epub_derive_book_key(books[i], strlen(books[i]), out, sizeof(out));\n'
' printf("BOOK|%d|%zu|%s\\n", i, n, out);\n'
' }\n'
' const char *imgs[] = {"", "fig1.jpg", "章节图_01_45678901234567890123456789012345678901234567890.png"};\n'
' for (int i = 0; i < 3; ++i) {\n'
' size_t n = rd_epub_derive_media_key(imgs[i], strlen(imgs[i]), out, sizeof(out));\n'
' printf("MEDIA|%d|%zu|%s\\n", i, n, out);\n'
' }\n'
' size_t pn = rd_epub_legacy_url_prefix(out, sizeof(out));\n'
' printf("PREFIX|%zu|%s\\n", pn, out);\n'
' ig_poison_mark(0x1122334455667788ULL);\n'
' size_t bn = rd_epub_derive_book_key("BK2026", 6, out, sizeof(out));\n'
' printf("POISON_BOOK|%zu|", bn);\n'
' for (size_t k = 0; k < bn; ++k) printf("%02x", (unsigned char)out[k]);\n'
' printf("\\n");\n'
' return 0;\n'
'}\n',
encoding='utf-8',
)
bin_p = p / 'kb_runner'
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
'-I', str(keybox_c.parent),
str(harness_c), str(poison_c), str(kb_o), '-o', str(bin_p),
], check=True)
lines = subprocess.check_output([str(bin_p)], text=True).splitlines()
salt = 'startiasoft'
books = ['', 'BK2026', 'book-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']
imgs = ['', 'fig1.jpg', '章节图_01_45678901234567890123456789012345678901234567890.png']
expected_bk = None
for line in lines:
parts = line.split('|')
if parts[0] == 'BOOK':
i = int(parts[1])
exp = (salt + books[i]) * 2
self.assertEqual(int(parts[2]), len(exp))
self.assertEqual(parts[3], exp)
if i == 1:
expected_bk = exp.encode('utf-8').hex()
elif parts[0] == 'MEDIA':
i = int(parts[1])
digest = hashlib.md5((imgs[i] + salt).encode('utf-8')).hexdigest()
exp = (salt + digest) * 2
self.assertEqual(int(parts[2]), len(exp))
self.assertEqual(parts[3], exp)
elif parts[0] == 'PREFIX':
self.assertEqual(int(parts[1]), 6)
self.assertEqual(parts[2], '_rdep_')
elif parts[0] == 'POISON_BOOK':
self.assertNotEqual(parts[2], expected_bk)
if __name__ == '__main__':
unittest.main()
+251
View File
@@ -0,0 +1,251 @@
import hashlib
import json
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'
APP_REPO = ROOT / 'readoor-test'
sys.path.insert(0, str(TOOLS_LLVM_OBF))
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # 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
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def file_sha256(path: Path) -> str:
return sha256_bytes(path.read_bytes())
class TestLLVMObfM2(unittest.TestCase):
def test_m2_policy_and_diag_events_config(self):
diag_path = ROOT / 'config' / 'ig_diag_events.json'
policy_path = ROOT / 'config' / 'ig_llvm_policy.json'
diag = json.loads(diag_path.read_text(encoding='utf-8'))
policy = json.loads(policy_path.read_text(encoding='utf-8'))
events = diag.get('events') or {}
expected_codes = (
[f'E-41{i:02d}' for i in range(1, 12)]
+ [f'E-51{i:02d}' for i in range(1, 37)]
+ [f'E-519{i}' for i in range(1, 5)]
+ [f'E-61{i:02d}' for i in range(1, 13)]
)
missing = [c for c in expected_codes if c not in events]
self.assertEqual(missing, [], f'Missing M2 diagnostic codes in ig_diag_events.json: {missing}')
required_ids = {t.get('id') for t in (policy.get('required_targets') or [])}
expected_req = {
'c_rd_sd_keybox',
'swift_sd_key_manager',
'swift_sd_signer',
'swift_iap_handler',
'objc_iap_verify_handler',
}
self.assertTrue(expected_req.issubset(required_ids), f'Missing required_targets: {expected_req - required_ids}')
def test_sd_keybox_obfuscation_derivation_and_seed_polymorphism(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()
keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c'
keybox_h = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.h'
defender_dir = ROOT / 'defender'
poison_c = defender_dir / 'poison/IGPoison.c'
policy_path = ROOT / 'config/ig_llvm_policy.json'
self.assertTrue(keybox_c.is_file() and keybox_h.is_file())
with tempfile.TemporaryDirectory(prefix='ig-m2-unit-') as td:
p = Path(td)
raw_bc = p / 'RDSDKeyBox.bc'
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os', '-g', '-fvisibility=hidden',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
'-I', str(keybox_c.parent),
'-emit-llvm', '-c', str(keybox_c), '-o', str(raw_bc),
], check=True)
def compile_variant(tag: str, seed: str):
obf_bc = p / f'{tag}.obf.bc'
obj_o = p / f'{tag}.o'
audit_p = p / f'{tag}.audit.json'
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-pass-filter=all',
f'--ig-seed={seed}',
f'--ig-source-path={keybox_c}',
f'--ig-audit-out={audit_p}',
str(raw_bc), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
disasm = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True)
return {
'obf_bc': obf_bc,
'obj_o': obj_o,
'obf_bc_sha256': file_sha256(obf_bc),
'obj_sha256': file_sha256(obj_o),
'text_disasm_sha256': sha256_bytes(disasm.encode('utf-8')),
'audit': json.loads(audit_p.read_text(encoding='utf-8')),
}
unit = compile_variant('unit', 'm2_unit_kb_seed')
audit = unit['audit']
self.assertGreaterEqual(audit.get('strings_encrypted_count', 0), 6, audit)
flattened = audit.get('functions_flattened') or []
self.assertGreaterEqual(len(flattened), 6, audit)
self.assertTrue(any('rd_sd_derive_aes256_key' in name for name in flattened), audit)
self.assertTrue(any('rd_sd_derive_v31_seed' in name for name in flattened), audit)
self.assertTrue(any('rd_sd_derive_v31_dt_pwd' in name for name in flattened), audit)
raw_o = unit['obj_o'].read_bytes()
for leaked in (
b'readoor_sd_v32',
b'KSDPrivateKeyPEM',
b'rd_net_cfg_v1',
b'rd_glyph_lut_v2',
b'encrypted_private_key',
b'cn.touchv.payment.models.keychain',
b'7ARrksiF7AoWXXBlmxfz9suSmTka7A',
):
self.assertNotIn(leaked, raw_o, f'Plaintext {leaked!r} leaked into RDSDKeyBox.o')
harness_c = p / 'harness.c'
harness_c.write_text(
'#include <stdio.h>\n'
'#include <stdint.h>\n'
'#include <string.h>\n'
'#include "RDSDKeyBox.h"\n'
'#include "poison/IGPoison.h"\n'
'int main(void) {\n'
' uint8_t key[32];\n'
' int null_rc = rd_sd_derive_aes256_key(NULL);\n'
' int ok_rc = rd_sd_derive_aes256_key(key);\n'
' printf("DERIVE|%d|%d|", null_rc, ok_rc);\n'
' for (size_t i = 0; i < sizeof(key); ++i) printf("%02x", key[i]);\n'
' printf("\\n");\n'
' char buf[128];\n'
' size_t n_slot = rd_sd_keychain_slot_name(buf, sizeof(buf));\n'
' printf("SLOT|%zu|%s\\n", n_slot, buf);\n'
' size_t n_stem = rd_sd_bundle_asset_stem(buf, sizeof(buf));\n'
' printf("STEM|%zu|%s\\n", n_stem, buf);\n'
' size_t n_acct = rd_iap_keychain_account_name(buf, sizeof(buf));\n'
' printf("ACCT|%zu|%s\\n", n_acct, buf);\n'
' size_t n_v31 = rd_sd_derive_v31_seed(buf, sizeof(buf));\n'
' printf("V31SEED|%zu|%s\\n", n_v31, buf);\n'
' const char *nonce = "n1234567890";\n'
' const char *suffix = "1700000000000GUID_V1iOS";\n'
' size_t n_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), buf, sizeof(buf));\n'
' printf("V31DT|%zu|%s\\n", n_dt, buf);\n'
' printf("SMALL|%zu|%zu|%zu\\n",\n'
' rd_sd_keychain_slot_name(NULL, 10),\n'
' rd_sd_bundle_asset_stem(buf, 0),\n'
' rd_iap_keychain_account_name(buf, 4));\n'
' ig_poison_mark(0xCAFEBABE12345678ULL);\n'
' char pbuf[64], pdt[64];\n'
' size_t pn_v31 = rd_sd_derive_v31_seed(pbuf, sizeof(pbuf));\n'
' size_t pn_dt = rd_sd_derive_v31_dt_pwd(nonce, strlen(nonce), suffix, strlen(suffix), pdt, sizeof(pdt));\n'
' printf("PV31SEED|%zu|%zu|%s\\n", pn_v31, strlen(pbuf), strcmp(pbuf, "7ARrksiF7AoWXXBlmxfz9suSmTka7A") != 0 ? "CHANGED" : "SAME");\n'
' printf("PV31DT|%zu|%s\\n", pn_dt, pdt);\n'
' return 0;\n'
'}\n',
encoding='utf-8',
)
runner = p / 'kb_runner'
subprocess.run([
clang, '-isysroot', macos_sdk, '-Os',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
'-I', str(keybox_c.parent),
str(harness_c),
str(poison_c),
str(defender_dir / 'resolve/IGResolve.c'),
str(defender_dir / 'anti_hook/IGAntiHook.c'),
str(defender_dir / 'dispatch/IGDispatch.c'),
str(unit['obj_o']),
'-framework', 'Security', '-framework', 'CoreFoundation',
'-o', str(runner),
], check=True)
lines = subprocess.check_output([str(runner)], text=True).splitlines()
expected_key = hashlib.pbkdf2_hmac(
'sha256',
b'readoor_sd_v32_ci_key_2026',
b'readoor_sd_v32_salt_fixed',
100_000,
32,
).hex()
expected_v31_seed = '7ARrksiF7AoWXXBlmxfz9suSmTka7A'
expected_v31_dt = hashlib.md5(
('n1234567890' + expected_v31_seed + '1700000000000GUID_V1iOS').encode('utf-8')
).hexdigest()
seen_tags = set()
for line in lines:
parts = line.split('|')
seen_tags.add(parts[0])
if parts[0] == 'DERIVE':
self.assertEqual(parts[1], '-1')
self.assertEqual(parts[2], '0')
self.assertEqual(parts[3], expected_key)
elif parts[0] == 'SLOT':
self.assertEqual(int(parts[1]), 16)
self.assertEqual(parts[2], 'KSDPrivateKeyPEM')
elif parts[0] == 'STEM':
self.assertEqual(int(parts[1]), 15)
self.assertEqual(parts[2], 'rd_glyph_lut_v2')
elif parts[0] == 'ACCT':
self.assertEqual(int(parts[1]), 33)
self.assertEqual(parts[2], 'cn.touchv.payment.models.keychain')
elif parts[0] == 'V31SEED':
self.assertEqual(int(parts[1]), 30)
self.assertEqual(parts[2], expected_v31_seed)
elif parts[0] == 'V31DT':
self.assertEqual(int(parts[1]), 32)
self.assertEqual(parts[2], expected_v31_dt)
elif parts[0] == 'PV31SEED':
self.assertEqual(parts[1], '30')
self.assertEqual(parts[2], '30')
self.assertEqual(parts[3], 'CHANGED')
elif parts[0] == 'PV31DT':
self.assertEqual(parts[1], '32')
self.assertEqual(len(parts[2]), 32)
self.assertNotEqual(parts[2], expected_v31_dt)
elif parts[0] == 'SMALL':
self.assertEqual(parts[1:], ['0', '0', '0'])
self.assertEqual(
seen_tags,
{'DERIVE', 'SLOT', 'STEM', 'ACCT', 'V31SEED', 'V31DT', 'PV31SEED', 'PV31DT', 'SMALL'},
)
# Same-seed determinism & cross-seed polymorphism
det_a = compile_variant('det_a', 'm2_seed_alpha')
det_b = compile_variant('det_b', 'm2_seed_alpha')
self.assertEqual(det_a['obf_bc_sha256'], det_b['obf_bc_sha256'])
self.assertEqual(det_a['obj_sha256'], det_b['obj_sha256'])
seeds = ['m2_seed_alpha', 'm2_seed_beta', 'm2_seed_gamma']
variants = {s: compile_variant(f'seed_{s}', s) for s in seeds}
self.assertEqual(len({variants[s]['text_disasm_sha256'] for s in seeds}), len(seeds))
if __name__ == '__main__':
unittest.main()
File diff suppressed because it is too large Load Diff
+366
View File
@@ -0,0 +1,366 @@
"""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 <stdint.h>
#include <stdio.h>
#include <limits.h>
__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 <stdint.h>
#include <stdio.h>
__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 <stdint.h>
__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()
+248
View File
@@ -0,0 +1,248 @@
"""Unit tests for M2 passes: IGOpaqueConstants and IGArithmetic (Linear MBA)."""
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'
APP_REPO = ROOT / 'readoor-test'
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()
class TestMbaAndOpaqueConstantsPass(unittest.TestCase):
def test_mba_all_ops_edge_values_and_const_hiding_execution(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m2-mba-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'opaque_const_max_per_fn': 64,
'arithmetic_rounds': 2,
'arithmetic_max_per_fn': 256,
'opaque_const_targets': [{'path_contains': 'mba_test.c'}],
'arithmetic_targets': [{'path_contains': 'mba_test.c'}],
'opaque_const_exempt_functions': ['rd_sd_sha256_transform'],
'arithmetic_exempt_functions': ['rd_sd_sha256_transform'],
}), encoding='utf-8')
src_c = p / 'mba_test.c'
src_c.write_text(
'''#include <stdint.h>
#include <limits.h>
#include <stdio.h>
__attribute__((noinline))
uint32_t mba_ops32(uint32_t x, uint32_t y) {
uint32_t a = x + y;
uint32_t b = a - (y ^ 0xA55A3C19u);
uint32_t c = (b ^ x) | (a & 0x5A3C96E1u);
uint32_t d = (c + 0x13579BDFu) & (b + 1u);
if (d == 0x2468ACE0u) {
return d ^ 0x77777777u;
}
return a ^ b ^ c ^ d ^ 0xCAFEBABEu;
}
__attribute__((noinline))
uint64_t mba_ops64(uint64_t x, uint64_t y) {
uint64_t a = x + y;
uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL);
uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL);
uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL);
return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL;
}
__attribute__((noinline))
uint32_t rd_sd_sha256_transform(uint32_t x, uint32_t y) {
return (x + y) ^ 0x428A2F98u;
}
__attribute__((noinline))
static uint32_t ref_ops32(uint32_t x, uint32_t y) {
uint32_t a = x + y;
uint32_t b = a - (y ^ 0xA55A3C19u);
uint32_t c = (b ^ x) | (a & 0x5A3C96E1u);
uint32_t d = (c + 0x13579BDFu) & (b + 1u);
if (d == 0x2468ACE0u) {
return d ^ 0x77777777u;
}
return a ^ b ^ c ^ d ^ 0xCAFEBABEu;
}
__attribute__((noinline))
static uint64_t ref_ops64(uint64_t x, uint64_t y) {
uint64_t a = x + y;
uint64_t b = a - (y ^ 0xA5C3F10E7B2D4968ULL);
uint64_t c = (b ^ x) | (a & 0x0F1E2D3C4B5A6978ULL);
uint64_t d = (c + 0x0102030405060708ULL) & (b + 3ULL);
return a ^ b ^ c ^ d ^ 0xFEDCBA9876543210ULL;
}
int main(void) {
const uint32_t vals32[] = {
0u, 1u, 2u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu,
0x12345678u, 0xA55A3C19u, 0x5A3C96E1u, 0xCAFEBABEu
};
const uint64_t vals64[] = {
0ULL, 1ULL, 2ULL, 0x7FFFFFFFFFFFFFFFULL, 0x8000000000000000ULL,
0xFFFFFFFFFFFFFFFFULL, 0xA5C3F10E7B2D4968ULL, 0x0123456789ABCDEFULL
};
size_t n32 = sizeof(vals32) / sizeof(vals32[0]);
for (size_t i = 0; i < n32; ++i) {
for (size_t j = 0; j < n32; ++j) {
if (mba_ops32(vals32[i], vals32[j]) != ref_ops32(vals32[i], vals32[j])) {
fprintf(stderr, "32-bit mismatch at %zu,%zu\\n", i, j);
return 2;
}
}
}
size_t n64 = sizeof(vals64) / sizeof(vals64[0]);
for (size_t i = 0; i < n64; ++i) {
for (size_t j = 0; j < n64; ++j) {
if (mba_ops64(vals64[i], vals64[j]) != ref_ops64(vals64[i], vals64[j])) {
fprintf(stderr, "64-bit mismatch at %zu,%zu\\n", i, j);
return 3;
}
}
}
if (rd_sd_sha256_transform(17u, 29u) != ((17u + 29u) ^ 0x428A2F98u)) {
return 4;
}
return 0;
}
''',
encoding='utf-8',
)
bc_p = p / 'mba.bc'
subprocess.run([clang, '-isysroot', sdk, '-O2', '-g', '-emit-llvm', '-c', str(src_c), '-o', str(bc_p)], check=True)
def compile_mode(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_p), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-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, 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'))
o_a1, exe_a1, aud_a1 = compile_mode('a1', 'seed_m2_1', 'all')
o_a2, _, _ = compile_mode('a2', 'seed_m2_1', 'all')
o_b1, exe_b1, aud_b1 = compile_mode('b1', 'seed_m2_2', 'all')
_, exe_const, aud_const = compile_mode('const_only', 'seed_m2_1', 'const')
_, exe_arith, aud_arith = compile_mode('arith_only', 'seed_m2_1', 'arith')
# Determinism and seed polymorphism
self.assertEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_a2.read_bytes()).hexdigest())
self.assertNotEqual(hashlib.sha256(o_a1.read_bytes()).hexdigest(), hashlib.sha256(o_b1.read_bytes()).hexdigest())
# Pass filter isolation & exemptions
self.assertGreaterEqual(aud_a1['opaque_constants_count'], 4)
self.assertGreaterEqual(aud_a1['arithmetic_rewrites_count'], 8)
self.assertEqual(aud_const['arithmetic_rewrites_count'], 0)
self.assertEqual(aud_const['functions_flattened'], [])
self.assertEqual(aud_arith['opaque_constants_count'], 0)
self.assertEqual(aud_arith['functions_flattened'], [])
self.assertNotIn('rd_sd_sha256_transform', aud_a1['opaque_constants_functions'])
self.assertNotIn('rd_sd_sha256_transform', aud_a1['arithmetic_functions'])
# Execute obfuscated arm64 binaries to confirm 100% bit-exact arithmetic equivalence
for exe in (exe_a1, exe_b1, exe_const, exe_arith):
self.assertEqual(subprocess.run([str(exe)]).returncode, 0, f'{exe} execution failed')
# Verify plaintext magic constants disappeared from mba_ops32 / mba_ops64 disassembly
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(exe_a1)], text=True)
m32_dis = dis.split('<_mba_ops32>:', 1)[1].split('<_mba_ops64>:', 1)[0].lower()
for needle in ('a55a', '3c19', 'babe'):
self.assertNotIn(needle, m32_dis)
m64_dis = dis.split('<_mba_ops64>:', 1)[1].split('<_rd_sd_sha256_transform>:', 1)[0].lower()
for needle in ('7b2d', '4968', 'fedc'):
self.assertNotIn(needle, m64_dis)
def test_sd_keybox_real_file_with_m2_passes(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk = macos_sdk_path()
keybox_c = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c'
defender_dir = ROOT / 'defender'
policy_path = ROOT / 'config/ig_llvm_policy.json'
with tempfile.TemporaryDirectory(prefix='ig-m2-kb-') as td:
p = Path(td)
raw_bc = p / 'RDSDKeyBox.bc'
obf_bc = p / 'RDSDKeyBox.obf.bc'
aud_p = p / 'audit.json'
obj_o = p / 'RDSDKeyBox.o'
subprocess.run([
clang, '-isysroot', sdk, '-Os', '-g', '-fvisibility=hidden',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
'-I', str(keybox_c.parent),
'-emit-llvm', '-c', str(keybox_c), '-o', str(raw_bc),
], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}',
'--ig-mode=full',
'--ig-pass-filter=all',
'--ig-seed=m2_kb_test_seed',
f'--ig-source-path={keybox_c}',
f'--ig-audit-out={aud_p}',
str(raw_bc), '-o', str(obf_bc),
], check=True)
subprocess.run([
clang, '-isysroot', sdk, '-Os',
'-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-g',
'-x', 'ir', '-c', str(obf_bc), '-o', str(obj_o),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 10, aud)
self.assertGreaterEqual(aud.get('arithmetic_rewrites_count', 0), 10, aud)
self.assertNotIn('_rd_sd_sha256_transform', aud.get('arithmetic_functions', []))
self.assertNotIn('rd_sd_sha256_transform', aud.get('arithmetic_functions', []))
self.assertNotIn('rd_sd_md5_hex', aud.get('arithmetic_functions', []))
dis = subprocess.check_output(['xcrun', 'llvm-objdump', '--disassemble', str(obj_o)], text=True)
# 0xA55A3C19 should not appear as literal immediate operands in non-exempt _rd_sd_sha256_init
init_dis = dis.split('<_rd_sd_sha256_init>:', 1)[1].split('<_rd_sd_sha256_update>:', 1)[0].lower()
self.assertNotIn('0x3c19', init_dis)
self.assertNotIn('0xa55a', init_dis)
if __name__ == '__main__':
unittest.main()
+716
View File
@@ -0,0 +1,716 @@
"""Regressions for RDBaseNetworkService plaintext-bypass fix, v3.1 C KeyBox, and Release diagnostic stripping."""
import hashlib
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
import zlib
ROOT = Path(__file__).resolve().parents[1]
APP_REPO = ROOT / 'readoor-test'
NETWORK_SVC = APP_REPO / 'readoor/3.0/Network/RDBaseNetworkService.swift'
API_RESULT = APP_REPO / 'readoor/3.0/Network/RDRequestApiResult.swift'
SD_KEYBOX_C = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.c'
SD_KEYBOX_H = APP_REPO / 'readoor/3.0/Base/Security/RDSDKeyBox.h'
POISON_C = ROOT / 'defender/poison/IGPoison.c'
DEFENDER_DIR = ROOT / 'defender'
DEFENDER_SOURCES = [
'IGDefender.c',
'anti_hook/IGAntiHook.c',
'anti_hook/IGObjCBaseline.c',
'anti_frida/IGAntiInject.c',
'anti_debug/IGAntiDebug.c',
'anti_jailbreak/IGAntiJailbreak.c',
'syscall/IGSyscall.c',
'resolve/IGResolve.c',
'dispatch/IGDispatch.c',
]
def _have_macos_tools() -> bool:
return sys.platform == 'darwin' and shutil.which('xcrun') is not None
@unittest.skipUnless(_have_macos_tools(), '需要 Xcode/macOS 工具链')
class NetworkAndKeyBoxHardeningTests(unittest.TestCase):
def test_parse_response_data_blocks_all_plaintext_bypasses(self):
self.assertTrue(NETWORK_SVC.is_file() and API_RESULT.is_file())
with tempfile.TemporaryDirectory(prefix='ig-net-test-') as td:
p = Path(td)
mod_dir = p / 'modules'
mod_dir.mkdir()
macos_sdk = subprocess.check_output(
['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True
).strip()
swifty_json_swift = p / 'SwiftyJSON.swift'
swifty_json_swift.write_text(
'''
import Foundation
public struct JSON {
private let raw: Any?
private let present: Bool
public init(_ object: Any) {
self.raw = object
self.present = !(object is NSNull)
}
private init(raw: Any?, present: Bool) {
self.raw = raw
self.present = present
}
public init(data: Data) throws {
let obj = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
self.init(obj)
}
public func exists() -> Bool {
return present
}
public subscript(key: String) -> JSON {
if let dict = raw as? [String: Any], let val = dict[key] {
return JSON(raw: val, present: !(val is NSNull))
}
return JSON(raw: nil, present: false)
}
public var intValue: Int {
if let n = raw as? NSNumber {
return n.intValue
}
if let s = raw as? String {
return Int(s) ?? 0
}
return 0
}
public var stringValue: String {
if let s = raw as? String {
return s
}
if let n = raw as? NSNumber {
return n.stringValue
}
return ""
}
}
''',
encoding='utf-8',
)
alamofire_swift = p / 'Alamofire.swift'
alamofire_swift.write_text(
'''
import Foundation
public typealias Parameters = [String: Any]
public protocol URLConvertible {}
extension String: URLConvertible {}
extension URL: URLConvertible {}
public struct HTTPMethod {
public let rawValue: String
public static let post = HTTPMethod(rawValue: "POST")
public static let get = HTTPMethod(rawValue: "GET")
}
public struct HTTPHeaders {
public init() {}
public mutating func add(name: String, value: String) {}
}
public enum AFError: Error {
case sessionTaskFailed(error: Error)
case responseValidationFailed(reason: ResponseValidationFailureReason)
public enum ResponseValidationFailureReason {
case unacceptableStatusCode(code: Int)
}
public var isSessionTaskError: Bool {
if case .sessionTaskFailed = self { return true }
return false
}
}
public struct AFDataResponse {
public let result: Result<Data, Error> = .failure(NSError(domain: "test", code: -1))
public let response: HTTPURLResponse? = nil
}
public final class AFRequest {
public func responseData(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) {}
public func responseData() -> AFDataResponse { return AFDataResponse() }
public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping (Progress) -> Void) -> AFRequest { return self }
}
public final class MultipartFormData {
public func append(_ data: Data, withName: String, fileName: String? = nil, mimeType: String? = nil) {}
}
public enum AF {
public static func request(_ convertible: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, headers: HTTPHeaders? = nil) -> AFRequest {
return AFRequest()
}
public static func upload(multipartFormData: (MultipartFormData) -> Void, to: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> AFRequest {
return AFRequest()
}
}
public final class NetworkReachabilityManager {
public init?() {}
public var isReachable: Bool { return true }
}
''',
encoding='utf-8',
)
jk_swift = p / 'JKSwiftExtension.swift'
jk_swift.write_text('import Foundation\npublic let ig_jk_shim = 1\n', encoding='utf-8')
for mod_name, src in (
('SwiftyJSON', swifty_json_swift),
('Alamofire', alamofire_swift),
('JKSwiftExtension', jk_swift),
):
subprocess.run([
'xcrun', '--sdk', 'macosx', 'swiftc', '-parse-as-library',
'-emit-module', '-emit-module-path', str(mod_dir / f'{mod_name}.swiftmodule'),
'-module-name', mod_name, '-sdk', macos_sdk,
'-c', str(src), '-o', str(p / f'{mod_name}.o'),
], check=True)
main_swift = p / 'main.swift'
main_swift.write_text(
r'''
import Foundation
import Compression
import SwiftyJSON
import Alamofire
final class RDAccountLoginModel {
static let shared = RDAccountLoginModel()
var token: String? = "tok"
}
enum RDOSLogManager {
static var diagCodes: [String] = []
static func logDebug(_ msg: String) {}
static func logError(_ msg: String) {}
static func logDiag(_ code: String) { diagCodes.append(code) }
}
enum RDRequestParamsFormat {
static func fdkldftierjkfioemcop(_ param: Any) -> [String: Any] { return [:] }
static func fdjkweiojcxmewkqw(_ paramDic: [String: Any], ct: String) -> (parameters: [String: Any]?, key: String, headers: [String: String]?) {
return (paramDic, "", nil)
}
}
enum StsSimpleCrypt {
static func sfc_strDecrypt(_ key1: String, key2: String, str: String) -> String! {
let prefix = "ENC:\(key1):"
guard str.hasPrefix(prefix) else { return nil }
return String(str.dropFirst(prefix.count))
}
}
extension NSData {
func uncompressZipped() -> Data? {
let marker = Data("GZ:".utf8)
let raw = self as Data
guard raw.starts(with: marker) else { return nil }
return raw.dropFirst(marker.count)
}
}
extension RDBaseNetworkService {
static func printRequestStartLog(convertible: URLConvertible, method: HTTPMethod) {}
static func printRequestMetadataLog(convertible: URLConvertible, action: String, statusCode: Int? = nil, failed: Bool = false) {}
static func printRequestLog(convertible: URLConvertible, httpHeaders: HTTPHeaders?, parameters: Parameters?, responseData: Any) {}
static func printRequestErrorLog(convertible: URLConvertible, method: HTTPMethod, httpHeaders: HTTPHeaders?, parameters: Parameters?, statusCode: Int?, businessCode: String? = nil, error: Error? = nil, message: String? = nil) {}
}
func assertRejectsDataError(_ label: String, _ work: () throws -> JSON) {
do {
_ = try work()
fatalError("Expected failure on case: \(label)")
} catch RDRequestApiError.dataError {
print("REJECT_OK|\(label)")
} catch {
fatalError("Unexpected error \(error) on case: \(label)")
}
}
// 1) key == "" allows plaintext JSON
let j1 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"data":{"ok":1}}"#.utf8), key: "")
assert(j1["status"].intValue == 1)
print("PASS|plain_key_empty")
// 2) key != "" + valid encrypted JSON
let j2 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"ENC:k31:{"status":1,"msg":"ok"}"#.utf8), key: "k31")
assert(j2["status"].intValue == 1 && j2["msg"].stringValue == "ok")
print("PASS|enc_plain_json")
// 3) key != "" + valid encrypted base64+gzipped JSON
let gzPayload = Data("GZ:".utf8) + Data(#"{"status":1,"book":"ok"}"#.utf8)
let b64 = gzPayload.base64EncodedString()
let j3 = try RDBaseNetworkService.parseResponseData(responseData: Data("ENC:k31:\(b64)".utf8), key: "k31")
assert(j3["status"].intValue == 1 && j3["book"].stringValue == "ok")
print("PASS|enc_b64_gz_json")
// 4) key != "" + plaintext error status == 0 is allowed
let j4 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":0,"message":"无权访问"}"#.utf8), key: "k31")
assert(j4["status"].intValue == 0 && j4["message"].stringValue == "无权访问")
print("PASS|plain_err_status0")
// 5) key != "" + plaintext err_code error without status is allowed
let j5 = try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"err_code":"TOKEN_EXPIRED","message":"expired"}"#.utf8), key: "k31")
assert(j5["err_code"].stringValue == "TOKEN_EXPIRED")
print("PASS|plain_err_code")
// 6) key != "" + plaintext status == 1 MUST BE REJECTED
assertRejectsDataError("plain_status_int_1") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"data":{"vip":1}}"#.utf8), key: "k31")
}
// 7) key != "" + string "1", whitespace " 1 ", and boolean true MUST BE REJECTED
assertRejectsDataError("plain_status_str_1") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":"1","data":{"vip":1}}"#.utf8), key: "k31")
}
assertRejectsDataError("plain_status_ws_1") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":" 1 ","data":{"vip":1}}"#.utf8), key: "k31")
}
assertRejectsDataError("plain_status_bool_true") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":true,"data":{"vip":1}}"#.utf8), key: "k31")
}
// 8) key != "" + err_code / HTML bypass trick MUST BE REJECTED (not fall through to raw JSON parse)
assertRejectsDataError("bypass_err_code_with_status1") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{"status":1,"err_code":"","note":"<div>"}"#.utf8), key: "k31")
}
// 9) key != "" + top-level array / empty JSON / malformed HTML error MUST BE REJECTED
assertRejectsDataError("plain_top_array") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"[{"status":1}]"#.utf8), key: "k31")
}
assertRejectsDataError("plain_empty_obj") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"{}"#.utf8), key: "k31")
}
assertRejectsDataError("malformed_html_error") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"<div>fatal.php</b> </div>"#.utf8), key: "k31")
}
assertRejectsDataError("decrypt_nil") {
try RDBaseNetworkService.parseResponseData(responseData: Data(#"CORRUPT_CIPHER"#.utf8), key: "k31")
}
print("DIAG|\(RDOSLogManager.diagCodes.joined(separator: ","))")
''',
encoding='utf-8',
)
exe = p / 'net_test'
subprocess.run([
'xcrun', '--sdk', 'macosx', 'swiftc',
'-I', str(mod_dir), '-sdk', macos_sdk,
str(API_RESULT), str(NETWORK_SVC), str(main_swift),
str(p / 'SwiftyJSON.o'), str(p / 'Alamofire.o'), str(p / 'JKSwiftExtension.o'),
'-o', str(exe),
], check=True)
out = subprocess.check_output([str(exe)], text=True).splitlines()
self.assertIn('PASS|plain_key_empty', out)
self.assertIn('PASS|enc_plain_json', out)
self.assertIn('PASS|enc_b64_gz_json', out)
self.assertIn('PASS|plain_err_status0', out)
self.assertIn('PASS|plain_err_code', out)
for tag in (
'plain_status_int_1',
'plain_status_str_1',
'plain_status_ws_1',
'plain_status_bool_true',
'bypass_err_code_with_status1',
'plain_top_array',
'plain_empty_obj',
'malformed_html_error',
'decrypt_nil',
):
self.assertIn(f'REJECT_OK|{tag}', out)
diag_line = [ln for ln in out if ln.startswith('DIAG|')][0]
self.assertIn('E-4112', diag_line)
self.assertIn('E-4113', diag_line)
self.assertIn('E-4114', diag_line)
def test_v31_keybox_md5_boundaries_poison_and_zero_call_edges(self):
self.assertTrue(SD_KEYBOX_C.is_file() and SD_KEYBOX_H.is_file())
with tempfile.TemporaryDirectory(prefix='ig-v31-kb-') as td:
p = Path(td)
macos_sdk = subprocess.check_output(
['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True
).strip()
kb_o = p / 'RDSDKeyBox.o'
subprocess.run([
'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk,
'-Os', '-Wall', '-Wextra', '-Werror', '-fvisibility=hidden',
'-I', str(DEFENDER_DIR), '-I', str(DEFENDER_DIR / 'include'),
'-I', str(SD_KEYBOX_C.parent),
'-c', str(SD_KEYBOX_C), '-o', str(kb_o),
], check=True)
nm_u = subprocess.check_output(['xcrun', 'nm', '-u', str(kb_o)], text=True)
for forbidden_u in (
'_CC_MD5',
'_ig_poison_',
'_CCKeyDerivationPBKDF',
'_SecKeyCreateWithData',
'_SecKeyCreateSignature',
'_CCCrypt',
'_CCHmac',
'_sysctl',
):
self.assertNotIn(forbidden_u, nm_u)
self.assertIn('_ig_pstate', nm_u)
self.assertIn('_ig_resolve_verified', nm_u)
raw_kb_o = kb_o.read_bytes()
raw_kb_lower = raw_kb_o.lower()
kb_strings_lower = subprocess.check_output(['strings', '-a', str(kb_o)], text=True, errors='replace').lower()
for leaked in (
b'7ARrksiF7AoWXXBlmxfz9suSmTka7A',
b'startiasoftstartiasoft',
b'startiasoftvvportal',
b'readoorstartiasoft',
b'd9800fb39d16c3f1cc0ddb5618af8378',
b'rd_glyph_lut_v2',
b'rd_net_cfg_v1',
):
self.assertNotIn(leaked, raw_kb_o)
for jb_needle in (
'cydia',
'mobilesubstrate',
'trollstore',
'/var/jb',
'jailbreak',
'/user/applications',
'frida',
'.rd_eprobe',
'127.0.0.1',
):
self.assertNotIn(jb_needle.encode('ascii'), raw_kb_lower)
self.assertNotIn(jb_needle, kb_strings_lower)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
pem_path = APP_REPO / 'AutoPacking/sd_priv_ios_v1.pem'
plain_pem = pem_path.read_bytes()
pbkdf_key = hashlib.pbkdf2_hmac('sha256', b'readoor_sd_v32_ci_key_2026', b'readoor_sd_v32_salt_fixed', 100_000, 32)
nonce12 = b'\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc'
sealed_asset = nonce12 + AESGCM(pbkdf_key).encrypt(nonce12, plain_pem, None)
(p / 'asset.bin').write_bytes(sealed_asset)
tampered_asset = bytearray(sealed_asset)
tampered_asset[-1] ^= 0xFF
(p / 'asset_tamper.bin').write_bytes(bytes(tampered_asset))
from cryptography.hazmat.primitives import serialization
der_path = p / 'priv_pkcs1.der'
priv_obj = serialization.load_pem_private_key(plain_pem, password=None)
der_path.write_bytes(
priv_obj.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
harness = p / 'harness.c'
harness.write_text(
r'''
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Security/Security.h>
#include "RDSDKeyBox.h"
#include "poison/IGPoison.h"
static void fill_pattern(char *buf, size_t n, char ch) {
for (size_t i = 0; i < n; ++i) buf[i] = (char)(ch + (i % 10));
buf[n] = '\0';
}
static uint8_t *read_all(const char *path, size_t *out_len) {
FILE *f = fopen(path, "rb");
if (!f) return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *buf = (uint8_t *)malloc((size_t)n);
if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) { fclose(f); free(buf); return NULL; }
fclose(f);
*out_len = (size_t)n;
return buf;
}
int main(int argc, char **argv) {
if (argc < 4) return 99;
char out[64];
if (rd_sd_derive_v31_seed(NULL, 32) != 0) return 1;
if (rd_sd_derive_v31_seed(out, 30) != 0) return 2;
if (rd_sd_derive_v31_dt_pwd("a", 1, "b", 1, out, 32) != 0) return 3;
if (rd_sd_derive_v31_dt_pwd(NULL, 2, "b", 1, out, 33) != 0) return 4;
size_t slen = rd_sd_derive_v31_seed(out, 31);
printf("SEED|%zu|%s\n", slen, out);
char sbuf64[64];
size_t n_stem = rd_sd_bundle_asset_stem(sbuf64, sizeof(sbuf64));
printf("STEM|%zu|%s\n", n_stem, sbuf64);
size_t n_m = rd_sd_media_decrypt_pwd(sbuf64, sizeof(sbuf64));
printf("MEDIA|%zu|%s\n", n_m, sbuf64);
size_t n_db = rd_sd_db_secret_key(sbuf64, sizeof(sbuf64));
printf("DBKEY|%zu|%s\n", n_db, sbuf64);
size_t n_tk = rd_sd_device_token_key(sbuf64, sizeof(sbuf64));
printf("TOKEN|%zu|%s\n", n_tk, sbuf64);
size_t n_cs = rd_sd_course_sign_prefix(sbuf64, sizeof(sbuf64));
printf("COURSE|%zu|%s\n", n_cs, sbuf64);
size_t n_wx = rd_sd_wx_pay_secret(sbuf64, sizeof(sbuf64));
printf("WXSEC|%zu|%s\n", n_wx, sbuf64);
size_t asset_len = 0, tamper_len = 0, der_len = 0;
uint8_t *asset = read_all(argv[1], &asset_len);
uint8_t *tamper = read_all(argv[2], &tamper_len);
uint8_t *der = read_all(argv[3], &der_len);
if (!asset || !tamper || !der) return 5;
uint8_t *dec = (uint8_t *)malloc(asset_len);
size_t dec_len = 0;
int gcm_ok = rd_sd_decrypt_bundled_asset(asset, asset_len, dec, asset_len, &dec_len);
size_t bad_len = 999;
int gcm_bad = rd_sd_decrypt_bundled_asset(tamper, tamper_len, dec, tamper_len, &bad_len);
printf("GCM|%d|%zu|%zu|%d|%zu\n", gcm_ok, dec_len, asset_len - 28u, gcm_bad, bad_len);
CFDataRef derData = CFDataCreate(kCFAllocatorDefault, der, (CFIndex)der_len);
const void *keys[] = { kSecAttrKeyType, kSecAttrKeyClass };
const void *vals[] = { kSecAttrKeyTypeRSA, kSecAttrKeyClassPrivate };
CFDictionaryRef attrs = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFErrorRef err = NULL;
SecKeyRef privKey = rd_sd_seckey_create_with_data(derData, attrs, &err);
const char *msg = "ig_test_msg";
CFDataRef msgData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)msg, (CFIndex)strlen(msg));
CFDataRef sig = privKey ? rd_sd_seckey_create_signature(privKey, kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256, msgData, &err) : NULL;
printf("SECKEY|%d|%ld\n", privKey != NULL ? 1 : 0, sig ? (long)CFDataGetLength(sig) : -1L);
if (sig) CFRelease(sig);
if (privKey) CFRelease(privKey);
CFRelease(msgData); CFRelease(attrs); CFRelease(derData);
const uint8_t hkey[4] = { 'k', 'e', 'y', '1' };
const uint8_t hmsg[3] = { 'a', 'b', 'c' };
uint8_t mac[32];
int hrc = rd_sd_cc_hmac(2u, hkey, sizeof(hkey), hmsg, sizeof(hmsg), mac);
printf("HMAC|%d|", hrc);
for (int i = 0; i < 32; ++i) printf("%02x", mac[i]);
printf("\n");
const uint8_t aes_key[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
const uint8_t aes_iv[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};
const uint8_t plain16[17] = "0123456789abcdef";
uint8_t ct[32], pt[32];
size_t ct_moved = 0, pt_moved = 0;
int enc_rc = rd_sd_cc_crypt(0u, 0u, 1u, aes_key, 16u, aes_iv, plain16, 16u, ct, sizeof(ct), &ct_moved);
int dec_rc = rd_sd_cc_crypt(1u, 0u, 1u, aes_key, 16u, aes_iv, ct, ct_moved, pt, sizeof(pt), &pt_moved);
printf("CCCRYPT|%d|%zu|%d|%zu|%d\n", enc_rc, ct_moved, dec_rc, pt_moved, (pt_moved == 16u && memcmp(pt, plain16, 16u) == 0) ? 1 : 0);
int traced = rd_sd_is_traced();
printf("TRACED|%d\n", traced);
free(asset); free(tamper); free(der); free(dec);
size_t extra_lens[] = {0, 24, 25, 26, 34, 98};
for (size_t i = 0; i < sizeof(extra_lens) / sizeof(extra_lens[0]); ++i) {
size_t total = extra_lens[i];
size_t nl = total / 2;
size_t sl = total - nl;
char nbuf[128], sbuf[128];
fill_pattern(nbuf, nl, 'a');
fill_pattern(sbuf, sl, 'A');
size_t r = rd_sd_derive_v31_dt_pwd(nbuf, nl, sbuf, sl, out, sizeof(out));
printf("MD5|%zu|%s|%s|%zu|%s\n", total, nbuf, sbuf, r, out);
}
ig_poison_mark(0x123456789ABCDEF0ULL);
char pseed[64], pdt[64];
size_t pslen = rd_sd_derive_v31_seed(pseed, sizeof(pseed));
size_t pdtlen = rd_sd_derive_v31_dt_pwd("n0", 2, "s0", 2, pdt, sizeof(pdt));
printf("POISON|%zu|%zu|", pslen, strlen(pseed));
for (size_t i = 0; i < pslen; ++i) printf("%02x", (unsigned char)pseed[i]);
printf("|%zu|%s\n", pdtlen, pdt);
size_t hash_lens[] = {0, 3, 55, 56, 63, 64, 128};
for (size_t i = 0; i < sizeof(hash_lens) / sizeof(hash_lens[0]); ++i) {
size_t hl = hash_lens[i];
uint8_t hbuf[128];
for (size_t j = 0; j < hl; ++j) hbuf[j] = (uint8_t)('a' + (j % 26));
char s256[80], md5h[64];
size_t s256_rc = rd_sd_sha256_hex(hl ? hbuf : NULL, hl, s256, sizeof(s256));
size_t md5_rc = rd_sd_md5_hex(hl ? hbuf : NULL, hl, md5h, sizeof(md5h));
printf("SHA256HEX|%zu|%zu|%s\n", hl, s256_rc, s256);
printf("MD5HEX|%zu|%zu|%s\n", hl, md5_rc, md5h);
}
uint8_t chunk_buf[128];
for (size_t j = 0; j < 128; ++j) chunk_buf[j] = (uint8_t)('a' + (j % 26));
rd_sd_sha256_ctx sctx;
rd_sd_sha256_init(&sctx);
rd_sd_sha256_update(&sctx, chunk_buf, 10);
rd_sd_sha256_update(&sctx, chunk_buf + 10, 54);
rd_sd_sha256_update(&sctx, chunk_buf + 64, 1);
rd_sd_sha256_update(&sctx, chunk_buf + 65, 63);
uint8_t sraw[32];
rd_sd_sha256_final(&sctx, sraw);
printf("SHA256STREAM|");
for (size_t j = 0; j < 32; ++j) printf("%02x", sraw[j]);
printf("\n");
int32_t env0 = rd_sd_probe_env_artifacts(0u);
int32_t env1 = rd_sd_probe_env_artifacts(0x1u);
printf("ENVPROBE|%d|%d\n", (int)env0, (int)env1);
return 0;
}
''',
encoding='utf-8',
)
exe = p / 'kb_boundary'
subprocess.run([
'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk,
'-Os', '-Wall', '-Wextra', '-Werror',
'-I', str(DEFENDER_DIR), '-I', str(DEFENDER_DIR / 'include'),
'-I', str(SD_KEYBOX_C.parent),
str(harness), str(kb_o), str(POISON_C),
str(DEFENDER_DIR / 'resolve/IGResolve.c'),
str(DEFENDER_DIR / 'anti_hook/IGAntiHook.c'),
str(DEFENDER_DIR / 'dispatch/IGDispatch.c'),
'-framework', 'Security', '-framework', 'CoreFoundation',
'-o', str(exe),
], check=True)
lines = subprocess.check_output([str(exe), str(p / 'asset.bin'), str(p / 'asset_tamper.bin'), str(der_path)], text=True).splitlines()
expected_seed = '7ARrksiF7AoWXXBlmxfz9suSmTka7A'
import hmac as py_hmac
expected_hmac = py_hmac.new(b'key1', b'abc', hashlib.sha256).hexdigest()
for line in lines:
parts = line.split('|')
if parts[0] == 'SEED':
self.assertEqual(parts[1], '30')
self.assertEqual(parts[2], expected_seed)
elif parts[0] == 'STEM':
self.assertEqual(parts[1:], ['15', 'rd_glyph_lut_v2'])
elif parts[0] == 'MEDIA':
self.assertEqual(parts[1:], ['22', 'startiasoftstartiasoft'])
elif parts[0] == 'DBKEY':
self.assertEqual(parts[1:], ['19', 'startiasoftvvportal'])
elif parts[0] == 'TOKEN':
self.assertEqual(parts[1:], ['18', 'readoorstartiasoft'])
elif parts[0] == 'COURSE':
self.assertEqual(parts[1:], ['11', 'startiasoft'])
elif parts[0] == 'WXSEC':
self.assertEqual(parts[1:], ['32', 'd9800fb39d16c3f1cc0ddb5618af8378'])
elif parts[0] == 'GCM':
self.assertEqual(parts[1], '0')
self.assertEqual(int(parts[2]), len(plain_pem))
self.assertEqual(parts[2], parts[3])
self.assertEqual(parts[4], '-2')
self.assertEqual(parts[5], '0')
elif parts[0] == 'SECKEY':
self.assertEqual(parts[1], '1')
self.assertGreater(int(parts[2]), 100)
elif parts[0] == 'HMAC':
self.assertEqual(parts[1], '0')
self.assertEqual(parts[2], expected_hmac)
elif parts[0] == 'CCCRYPT':
self.assertEqual(parts[1:], ['0', '32', '0', '16', '1'])
elif parts[0] == 'TRACED':
self.assertIn(parts[1], ('0', '1'))
elif parts[0] == 'MD5':
nonce_val, suffix_val, rc, got_hex = parts[2], parts[3], parts[4], parts[5]
self.assertEqual(rc, '32')
exp_hex = hashlib.md5(
(nonce_val + expected_seed + suffix_val).encode('utf-8')
).hexdigest()
self.assertEqual(got_hex, exp_hex, f'Mismatch at total={parts[1]}')
elif parts[0] == 'POISON':
self.assertEqual(parts[1], '30')
self.assertEqual(parts[2], '30')
self.assertNotEqual(parts[3], expected_seed.encode('ascii').hex())
self.assertEqual(parts[4], '32')
exp_clean = hashlib.md5(f'n0{expected_seed}s0'.encode('utf-8')).hexdigest()
self.assertNotEqual(parts[5], exp_clean)
self.assertTrue(all(c in '0123456789abcdef' for c in parts[5]))
elif parts[0] == 'SHA256HEX':
hl = int(parts[1])
self.assertEqual(parts[2], '64')
payload = bytes((ord('a') + (j % 26)) for j in range(hl))
self.assertEqual(parts[3], hashlib.sha256(payload).hexdigest())
elif parts[0] == 'MD5HEX':
hl = int(parts[1])
self.assertEqual(parts[2], '32')
payload = bytes((ord('a') + (j % 26)) for j in range(hl))
self.assertEqual(parts[3], hashlib.md5(payload).hexdigest())
elif parts[0] == 'SHA256STREAM':
payload = bytes((ord('a') + (j % 26)) for j in range(128))
self.assertEqual(parts[1], hashlib.sha256(payload).hexdigest())
elif parts[0] == 'ENVPROBE':
self.assertEqual(parts[1], '0')
self.assertNotEqual(int(parts[2]) & 1, 0)
def test_defender_diagnostic_gating_release_vs_observation(self):
with tempfile.TemporaryDirectory(prefix='ig-diag-gate-') as td:
p = Path(td)
macos_sdk = subprocess.check_output(
['xcrun', '--sdk', 'macosx', '--show-sdk-path'], text=True
).strip()
def build_and_probe(tag: str, extra_flags: list[str]):
objs = []
for idx, src_rel in enumerate(DEFENDER_SOURCES):
obj = p / f'{tag}-{idx}.o'
subprocess.run([
'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk,
'-O2', '-Wall', '-Wextra', '-Werror',
*extra_flags,
'-I', str(DEFENDER_DIR / 'include'), '-I', str(DEFENDER_DIR),
'-c', str(DEFENDER_DIR / src_rel), '-o', str(obj),
], check=True)
objs.append(obj)
exe = p / f'defender-{tag}'
subprocess.run([
'xcrun', '--sdk', 'macosx', 'clang', '-isysroot', macos_sdk,
'-O2', '-Wall', '-Wextra', '-Werror',
'-I', str(DEFENDER_DIR / 'include'), '-I', str(DEFENDER_DIR),
str(ROOT / 'tests/fixtures/defender_host.c'),
*(str(o) for o in objs),
'-lobjc', '-o', str(exe),
], check=True)
out_unres = subprocess.check_output([str(exe), 'unresolved'], text=True).strip()
out_env = subprocess.check_output([str(exe), 'env'], text=True).strip()
return objs, out_unres, out_env
rel_objs, rel_unres, rel_env = build_and_probe('release', [])
_, obs_unres, obs_env = build_and_probe('observe', ['-DIG_OBSERVATION=1'])
self.assertEqual(rel_unres, 'status=2 reason=103 subject= evidence=')
self.assertIn('status=1 reason=202 subject= evidence=', rel_env)
self.assertNotIn('ig_fixture_a', rel_env)
rel_cstrings = b'\n'.join(
subprocess.check_output(['strings', '-a', str(o)])
for o in rel_objs
).decode('utf-8', errors='replace')
for forbidden in ('DYLD_INSERT_LIBRARIES', 'P_TRACED', 'dispatch-write', '导出表无法解析'):
self.assertNotIn(forbidden, rel_cstrings)
self.assertIn('subject=IG_fixture_symbol_that_does_not_exist_123', obs_unres)
self.assertIn('evidence=导出表无法解析该符号', obs_unres)
self.assertIn('subject=/tmp/ig_fixture_a', obs_env)
self.assertIn('DYLD_INSERT_LIBRARIES 条目=/tmp/ig_fixture_a', obs_env)
if __name__ == '__main__':
unittest.main()
+355
View File
@@ -0,0 +1,355 @@
"""Unit tests for M6: ObjC CFConstantString, Swift String, multi-fn memcpy stack decrypt, and string replace rules."""
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 TestObjCSwiftStringEncryption(unittest.TestCase):
def test_objc_cfconstantstring_ascii_utf16_phi_and_ios_link(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-m6-objcstr-') 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': 'objc_str.m'}],
'string_encrypt_objc_targets': [
{'path_contains': 'objc_str.m', 'function_contains': 'obf_'}
],
}), encoding='utf-8')
src_m = p / 'objc_str.m'
src_m.write_text(
'''#import <Foundation/Foundation.h>
__attribute__((noinline))
NSString *obf_ascii_tok(void) {
return @"OBJC_SECRET_ASCII_TOKEN";
}
__attribute__((noinline))
NSString *obf_utf16_tok(void) {
return @"OBJC_中文密钥_UTF16";
}
__attribute__((noinline))
NSString *obf_branch_tok(int flag) {
NSString *s = nil;
if (flag > 0) {
s = @"OBJC_PHI_TRUE_KEY";
} else {
s = @"OBJC_PHI_FALSE_KEY";
}
return [s copy];
}
__attribute__((noinline))
NSString *untouched_fn(void) {
return @"OBJC_UNTOUCHED_OK";
}
int main(void) {
@autoreleasepool {
NSString *a = obf_ascii_tok();
NSString *u = obf_utf16_tok();
NSString *bt = obf_branch_tok(1);
NSString *bf = obf_branch_tok(0);
NSString *ut = untouched_fn();
NSDictionary *dict = @{ a: @10, u: @20, bt: @30 };
if (![a isEqualToString:[@"OBJC_SECRET_ASCII_" stringByAppendingString:@"TOKEN"]] || a.length != 23) return 1;
const unichar encoded_u[] = {
'O'^1,'B'^1,'J'^1,'C'^1,'_'^1,0x4E2D^1,0x6587^1,0x5BC6^1,0x94A5^1,'_'^1,'U'^1,'T'^1,'F'^1,'1'^1,'6'^1
};
volatile unichar mask = 1;
unichar expected_u[15];
for (int i = 0; i < 15; ++i) expected_u[i] = encoded_u[i] ^ mask;
NSString *expU = [NSString stringWithCharacters:expected_u length:15];
if (![u isEqualToString:expU] || u.length != 15) return 2;
if ([dict[a] intValue] != 10 || [dict[u] intValue] != 20 || [dict[bt] intValue] != 30) return 3;
if (![bt hasSuffix:@"TRUE_KEY"] || ![bf hasSuffix:@"FALSE_KEY"]) return 4;
if (![ut isEqualToString:@"OBJC_UNTOUCHED_OK"]) return 5;
}
return 0;
}
''',
encoding='utf-8',
)
# Host macOS compile, verify IR/binary bytes & run
bc_h = p / 'objc_h.bc'
obf_ll = p / 'objc_h.obf.ll'
obj_h = p / 'objc_h.o'
exe_h = p / 'objc_h_exe'
aud_p = p / 'objc_h.audit.json'
subprocess.run([clang, '-isysroot', sdk_host, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_h)], check=True)
subprocess.run([
opt_path, '-S', '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_1',
f'--ig-source-path={src_m}', f'--ig-audit-out={aud_p}',
str(bc_h), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(aud.get('objc_strings_encrypted_count', 0), 4, aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertIn('@__ig_dec_cf_', ir_txt)
subprocess.run([
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c', str(obf_ll), '-o', str(obj_h),
], check=True)
obj_raw = obj_h.read_bytes()
for needle in (b'OBJC_SECRET_ASCII_TOKEN', b'OBJC_PHI_TRUE_KEY', b'OBJC_PHI_FALSE_KEY'):
self.assertNotIn(needle, obj_raw)
self.assertNotIn('中文密钥'.encode('utf-16-le'), obj_raw)
self.assertIn(b'OBJC_UNTOUCHED_OK', obj_raw)
subprocess.run([clang, '-isysroot', sdk_host, '-framework', 'Foundation', '-Wl,-dead_strip', str(obj_h), '-o', str(exe_h)], check=True)
self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0)
# iOS arm64 link verification
bc_i = p / 'objc_i.bc'
obf_i = p / 'objc_i.obf.bc'
obj_i = p / 'objc_i.o'
dylib_i = p / 'libobjc_i.dylib'
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-fobjc-arc', '-O2', '-g', '-emit-llvm', '-c', str(src_m), '-o', str(bc_i)], check=True)
subprocess.run([
opt_path, '-passes=ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=str', '--ig-seed=m6_objc_ios',
f'--ig-source-path={src_m}', f'--ig-audit-out={p / "objc_i.audit.json"}',
str(bc_i), '-o', str(obf_i),
], check=True)
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_i), '-o', str(obj_i),
], check=True)
subprocess.run([clang, '-target', 'arm64-apple-ios15.0', '-isysroot', sdk_ios, '-dynamiclib', str(obj_i), '-framework', 'Foundation', '-Wl,-dead_strip', '-o', str(dylib_i)], check=True)
def test_swift_large_immortal_and_small_string_encryption(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
swiftc = detect_stock_tool('swiftc')
sdk_host = macos_sdk_path()
sdk_ios = iphoneos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m6-swiftstr-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': ['__ig_', 'llvm.', '__swift_'],
'string_encrypt_targets': [{'path_contains': 'sw_str.swift'}],
'string_encrypt_swift_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}],
'opaque_const_targets': [{'path_contains': 'sw_str.swift', 'function_contains': 'secret'}],
'opaque_const_max_per_fn': 64,
}), encoding='utf-8')
src_sw = p / 'sw_str.swift'
src_sw.write_text(
'''import Foundation
@inline(never)
public func secretBranch(_ flag: Bool) -> String {
let s: String
if flag {
s = "SWIFT_IMMORTAL_BRANCH_ALPHA_01"
} else {
s = "SWIFT_IMMORTAL_BRANCH_BETA_002"
}
return s
}
@inline(never)
public func secretUtf8AndSmall(_ v: Int) -> (String, String) {
let large = "SWIFT_中文密钥_LARGE_IMMORTAL_888"
let small = "SML_KEY_1234"
return v > 0 ? (large, small) : (small, large)
}
@main
struct Runner {
static func main() {
let a = secretBranch(true)
let b = secretBranch(false)
let (l, s) = secretUtf8AndSmall(1)
let dict = [a: 11, b: 22, l: 33, s: 44]
let ns: NSString = a as NSString
if a.count != 30 || ns.length != 30 || dict[a] != 11 || dict[b] != 22 { exit(1) }
if !a.hasSuffix("ALPHA_01") || !b.hasSuffix("BETA_002") { exit(2) }
if dict[l] != 33 || dict[s] != 44 || s.count != 12 { exit(3) }
if !l.contains("中文密钥") || !s.hasPrefix("SML_KEY_") { exit(4) }
}
}
''',
encoding='utf-8',
)
bc_h = p / 'sw_h.bc'
obf_ll = p / 'sw_h.obf.ll'
obj_h = p / 'sw_h.o'
exe_h = p / 'sw_h_exe'
aud_p = p / 'sw_h.audit.json'
subprocess.run([swiftc, '-sdk', sdk_host, '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(src_sw), '-o', str(bc_h)], check=True)
subprocess.run([
opt_path, '-S', '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_1',
f'--ig-source-path={src_sw}', f'--ig-audit-out={aud_p}',
str(bc_h), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertGreaterEqual(aud.get('swift_strings_encrypted_count', 0), 3, aud)
self.assertGreaterEqual(aud.get('opaque_constants_count', 0), 1, aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertIn('@__ig_dec_sw_', 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_h),
], check=True)
obj_raw = obj_h.read_bytes()
for needle in (b'SWIFT_IMMORTAL_BRANCH_ALPHA_01', b'SWIFT_IMMORTAL_BRANCH_BETA_002', 'SWIFT_中文密钥_LARGE_IMMORTAL_888'.encode('utf-8')):
self.assertNotIn(needle, obj_raw)
# Packed small-string i64 word "SML_KEY_" must be obfuscated away
small_qword = struct.pack('<Q', int.from_bytes(b'SML_KEY_', 'little'))
self.assertNotIn(small_qword, obj_raw)
subprocess.run([swiftc, '-sdk', sdk_host, str(obj_h), '-Xlinker', '-dead_strip', '-o', str(exe_h)], check=True)
self.assertEqual(subprocess.run([str(exe_h)]).returncode, 0)
# Verify iOS arm64 link compatibility
bc_i = p / 'sw_i.bc'
obf_i = p / 'sw_i.obf.bc'
obj_i = p / 'sw_i.o'
subprocess.run([swiftc, '-sdk', sdk_ios, '-target', 'arm64-apple-ios15.0', '-O', '-g', '-lto=llvm-thin', '-parse-as-library', '-c', str(src_sw), '-o', str(bc_i)], check=True)
subprocess.run([
opt_path, '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m6_sw_ios',
f'--ig-source-path={src_sw}', f'--ig-audit-out={p / "sw_i.audit.json"}',
str(bc_i), '-o', str(obf_i),
], check=True)
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_i), '-o', str(obj_i),
], check=True)
subprocess.run([swiftc, '-sdk', sdk_ios, '-target', 'arm64-apple-ios15.0', '-emit-library', str(obj_i), '-Xlinker', '-dead_strip', '-o', str(p / 'libsw_i.dylib')], check=True)
def test_stack_decrypt_memcpy_multifn_and_string_replace(self):
opt_path = require_host_opt()
clang = detect_stock_tool('clang')
sdk_host = macos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m6-stackrep-') 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_rep.c'}],
'string_encrypt_stack_targets': [{'path_contains': 'stack_rep.c'}],
'string_encrypt_stack_max_len': 64,
'string_replace_rules': [{'exact': 'REPLACE_ME_SECRET_99', 'replace': 'CLEANED'}],
}), encoding='utf-8')
src_c = p / 'stack_rep.c'
src_c.write_text(
'''#include <string.h>
__attribute__((noinline))
int copy_shared_a(char *out) {
memcpy(out, "MULTI_FN_STACK_TOKEN", 21);
return 1;
}
__attribute__((noinline))
int copy_shared_b(const char *probe) {
return strcmp(probe, "MULTI_FN_STACK_TOKEN") == 0;
}
__attribute__((noinline))
int read_replaced(char *out) {
memcpy(out, "REPLACE_ME_SECRET_99", 21);
return 1;
}
int main(void) {
char buf1[32] = {0};
char buf2[32] = {0};
copy_shared_a(buf1);
if (!copy_shared_b(buf1)) return 1;
read_replaced(buf2);
if (strcmp(buf2, "CLEANED") != 0) return 2;
return 0;
}
''',
encoding='utf-8',
)
bc_p = p / 'stack_rep.bc'
obf_ll = p / 'stack_rep.obf.ll'
obj_o = p / 'stack_rep.o'
exe_p = p / 'stack_rep_exe'
aud_p = p / 'stack_rep.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=m6_stackrep_1',
f'--ig-source-path={src_c}', f'--ig-audit-out={aud_p}',
str(bc_p), '-o', str(obf_ll),
], check=True)
aud = json.loads(aud_p.read_text(encoding='utf-8'))
self.assertEqual(aud.get('strings_replaced_count'), 1, aud)
self.assertGreaterEqual(aud.get('strings_stack_encrypted_count'), 2, aud)
self.assertEqual(aud.get('strings_encrypted_count'), aud.get('strings_stack_encrypted_count'), aud)
ir_txt = obf_ll.read_text(encoding='utf-8')
self.assertNotIn('.ig.buf.', ir_txt)
self.assertNotIn('REPLACE_ME_SECRET_99', ir_txt)
self.assertNotIn('MULTI_FN_STACK_TOKEN', ir_txt)
self.assertNotIn('CLEANED', ir_txt)
self.assertIn('store volatile i8 0,', ir_txt)
subprocess.run([
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-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)
self.assertEqual(subprocess.run([str(exe_p)]).returncode, 0)
if __name__ == '__main__':
unittest.main()
+248
View File
@@ -0,0 +1,248 @@
"""Unit tests for M8: IGFunctionOutline (CodeExtractor -> ig_sub_*) and IGOpaqueFieldAccess."""
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 TestOpaqueFieldAndOutlinePass(unittest.TestCase):
def test_c_outline_routed_via_icall_field_masking_and_runtime_exact(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-m8-c-') as td:
p = Path(td)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'function_outline_max_per_fn': 2,
'function_outline_min_insts': 4,
'function_outline_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}],
'opaque_field_max_per_fn': 32,
'opaque_field_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}],
'indirect_call_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}],
'indirect_call_same_image_prefixes': ['ig_sub_'],
'flatten_targets': [{'path_contains': 'm8_field.c', 'function_contains': 'compute_box_digest'}],
}), encoding='utf-8')
src_c = p / 'm8_field.c'
src_c.write_text(
'''#include <stdint.h>
#include <stdio.h>
struct BoxState {
uint32_t header;
uint32_t salt;
uint64_t quota;
uint32_t flags;
uint32_t checksum;
};
uint32_t g_secret_multiplier = 0x9E3779B1u;
static uint64_t g_secret_offset = 0x123456789ABCDEF0ULL;
__attribute__((noinline))
uint64_t compute_box_digest(struct BoxState *st, uint32_t mode) {
uint64_t acc = st->quota ^ g_secret_offset;
if (mode > 0) {
uint32_t a = st->header * g_secret_multiplier;
uint32_t b = (st->salt ^ 0xA55AA55Au) + mode;
uint32_t c = (a ^ b) + st->flags;
uint64_t d = ((uint64_t)c << 17) ^ ((uint64_t)st->checksum * 33ULL);
acc += d + (uint64_t)a * 7ULL + (uint64_t)b;
} else {
acc ^= ((uint64_t)st->flags << 3) + st->salt + 19ULL;
}
if ((acc & 1ULL) != 0ULL) {
g_secret_multiplier ^= (uint32_t)(mode & 3u);
}
return acc ^ ((uint64_t)st->checksum + 0x55AAULL);
}
int main(void) {
struct BoxState s1 = {0x11223344u, 0x55667788u, 0xCAFEBABE00112233ULL, 7u, 0x99AABBCCu};
struct BoxState s2 = {0xDEADBEEFu, 0x10203040u, 0x0102030405060708ULL, 13u, 0x0A0B0C0Du};
uint64_t r1 = compute_box_digest(&s1, 0);
uint64_t r2 = compute_box_digest(&s1, 5);
uint64_t r3 = compute_box_digest(&s2, 12);
printf("%016llx:%016llx:%016llx\\n",
(unsigned long long)r1, (unsigned long long)r2, (unsigned long long)r3);
return 0;
}
''',
encoding='utf-8',
)
# Reference un-obfuscated output
ref_exe = p / 'ref_exe'
subprocess.run([clang, '-isysroot', sdk_host, '-O2', str(src_c), '-o', str(ref_exe)], check=True)
ref_out = subprocess.check_output([str(ref_exe)], text=True).strip()
# Obfuscated host build
bc_h = p / 'm8_h.bc'
obf_ll_h = p / 'm8_h.obf.ll'
aud_h = p / 'm8_h.audit.json'
obj_h = p / 'm8_h.o'
exe_h = p / 'm8_h_exe'
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=m8_c_seed_1',
f'--ig-source-path={src_c}', f'--ig-audit-out={aud_h}',
str(bc_h), '-o', str(obf_ll_h),
], check=True)
ir_text = obf_ll_h.read_text(encoding='utf-8')
self.assertIn('define internal ', ir_text)
self.assertIn('ig_sub_', ir_text)
self.assertIn('__ig_fop_', ir_text)
self.assertIn('__ig_gba_', ir_text)
audit = json.loads(aud_h.read_text(encoding='utf-8'))
self.assertGreaterEqual(audit['functions_outlined_count'], 1)
self.assertGreaterEqual(audit['opaque_field_access_count'], 2)
self.assertGreaterEqual(audit['indirect_calls_count'], 1)
subprocess.run([
clang, '-isysroot', sdk_host, '-O2', '-Xclang', '-disable-llvm-passes',
'-fno-builtin', '-Wno-override-module', '-g', '-x', 'ir', '-c', str(obf_ll_h), '-o', str(obj_h),
], check=True)
subprocess.run([clang, '-isysroot', sdk_host, str(obj_h), '-o', str(exe_h)], check=True)
obf_out = subprocess.check_output([str(exe_h)], text=True).strip()
self.assertEqual(obf_out, ref_out)
# iOS arm64 bitcode lowering verification
bc_ios = p / 'm8_ios.bc'
obf_ios = p / 'm8_ios.obf.bc'
obj_ios = p / 'm8_ios.o'
aud_ios = p / 'm8_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=m8_ios_seed_1',
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)
magic = struct.unpack_from('<I', obj_ios.read_bytes(), 0)[0]
self.assertEqual(magic, 0xFEEDFACF)
def test_swift_debug_info_outline_and_opaque_field_lowering(self):
opt_path = require_host_opt()
swiftc = detect_stock_tool('swiftc')
clang = detect_stock_tool('clang')
sdk_ios = iphoneos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m8-sw-') as td:
p = Path(td)
src_sw = p / 'm8_swift.swift'
src_sw.write_text(
'''import Foundation
public final class TrialRecord {
public var bookId: Int = 101
public var readablePages: Int = 5
public var bonusPages: Int = 2
public var watermarkSeed: UInt64 = 0x13572468ACE01122
public init() {}
}
private var gTrialCounter: Int = 9
@inline(never)
public func evaluateTrialRecord(_ rec: TrialRecord, _ page: Int) -> UInt64 {
var acc = rec.watermarkSeed ^ UInt64(gTrialCounter)
if page > rec.readablePages {
let a = UInt64(rec.bookId &* 131) ^ UInt64(rec.bonusPages &* 17)
let b = (acc &+ a) ^ 0x55AA33CC11223344
let c = b &* 3 &+ UInt64(page ^ 0x77)
acc = (c ^ a) &+ UInt64(rec.readablePages)
} else {
acc = acc &+ UInt64(rec.bookId + page)
}
if (acc & 1) == 0 {
gTrialCounter += 1
}
return acc
}
''',
encoding='utf-8',
)
policy_path = p / 'policy.json'
policy_path.write_text(json.dumps({
'exempt_path_substrings': [],
'exempt_function_prefixes': [],
'function_outline_max_per_fn': 2,
'function_outline_min_insts': 4,
'function_outline_targets': [{'path_contains': 'm8_swift.swift'}],
'opaque_field_max_per_fn': 32,
'opaque_field_targets': [{'path_contains': 'm8_swift.swift'}],
'indirect_call_targets': [{'path_contains': 'm8_swift.swift'}],
'indirect_call_same_image_prefixes': ['ig_sub_'],
'flatten_targets': [{'path_contains': 'm8_swift.swift'}],
}), encoding='utf-8')
bc_sw = p / 'm8_sw.bc'
obf_sw = p / 'm8_sw.obf.bc'
obj_sw = p / 'm8_sw.o'
aud_sw = p / 'm8_sw.audit.json'
subprocess.run([
swiftc, '-target', 'arm64-apple-ios15.0', '-sdk', sdk_ios,
'-O', '-lto=llvm-thin', '-g', '-module-name', 'M8Mod',
'-parse-as-library', '-c', str(src_sw), '-o', str(bc_sw),
], check=True)
subprocess.run([
opt_path, '-passes=default<O2>,ig-obfuscate',
f'--ig-policy={policy_path}', '--ig-mode=full', '--ig-seed=m8_sw_1',
f'--ig-source-path={src_sw}', '--ig-swift-module=M8Mod',
f'--ig-audit-out={aud_sw}', str(bc_sw), '-o', str(obf_sw),
], 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_sw), '-o', str(obj_sw),
], check=True)
audit = json.loads(aud_sw.read_text(encoding='utf-8'))
self.assertGreaterEqual(audit['functions_outlined_count'], 1)
self.assertGreaterEqual(audit['opaque_field_access_count'], 1)
magic = struct.unpack_from('<I', obj_sw.read_bytes(), 0)[0]
self.assertEqual(magic, 0xFEEDFACF)
if __name__ == '__main__':
unittest.main()
+361
View File
@@ -0,0 +1,361 @@
"""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()
+246
View File
@@ -1,11 +1,17 @@
"""用真实策略源码做宿主测试,覆盖观察/强制模式和 unavailable。"""
import hashlib
import hmac
from pathlib import Path
import plistlib
import re
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[1]
POLICY=ROOT/'readoor-test/readoor/3.0/Base/Security/RDSecurityPolicy.swift'
INJECTION=ROOT/'readoor-test/readoor/3.0/Base/Security/RDInjectionDetector.swift'
SECRET=ROOT/'readoor-test/readoor/3.0/Base/Security/Generated/RDWhitelistSecret.swift'
@unittest.skipUnless(POLICY.exists(),'需要 App 副本中的策略源码')
class SecurityPolicyTests(unittest.TestCase):
@@ -14,6 +20,7 @@ class SecurityPolicyTests(unittest.TestCase):
main=Path(td)/'main.swift';exe=Path(td)/'policy'
main.write_text('''
import Foundation
import CommonCrypto
struct RDDefenderFinding {
let status: Int32; let reason: Int32
var isDetected: Bool { status == 1 }
@@ -22,6 +29,13 @@ struct RDDefenderFinding {
struct RDSecurityRiskContext {
let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool
}
// 毒化写入侧 C 桥的宿主桩:记录调用次数与最后熵,供断言毒化门行为。
var poisonMarkCount = 0
var lastPoisonEntropy: UInt64 = 0
func rd_epub_poison_mark(_ entropy: UInt64) { poisonMarkCount += 1; lastPoisonEntropy = entropy }
func dz(_ r: Int32) -> RDDefenderFinding { RDDefenderFinding(status:1,reason:r) } // detected 便捷构造
func jb() -> RDSecurityRiskContext { RDSecurityRiskContext(debuggerDetected:false,injectedDylibDetected:false,jailbreakDetected:true) }
let legacy=RDSecurityRiskContext(debuggerDetected:false,injectedDylibDetected:false,jailbreakDetected:false)
let policy=RDSecurityPolicy.shared
let clean=policy.evaluate(findings:[],legacy:legacy)
@@ -34,9 +48,241 @@ assert(tamper.action == .restrictSensitive && tamper.shouldRestrict(in:.enforce)
assert(!tamper.shouldRestrict(in:.observe))
let weak=policy.evaluate(findings:[RDDefenderFinding(status:1,reason:201)],legacy:legacy)
assert(weak.action == .monitor && !weak.shouldRestrict(in:.enforce))
// ---- 毒化门(applyPoisonDisposition):严于 terminate 门,守误报底线 ----
// observe 模式绝不毒化(即便 STRONG inline-hook 101 命中)。
policy.mode = .observe
assert(policy.applyPoisonDisposition(findings:[dz(101)],legacy:legacy) == false)
assert(poisonMarkCount == 0)
// enforce:STRONG 单条即触发(inline-hook 101),熵非 0。
policy.mode = .enforce
assert(policy.applyPoisonDisposition(findings:[dz(101)],legacy:legacy) == true)
assert(poisonMarkCount == 1 && lastPoisonEntropy != 0)
// 单个 MEDIUM(符号提供方 100)不触发——需 ≥2 个不同 MEDIUM。
assert(policy.applyPoisonDisposition(findings:[dz(100)],legacy:legacy) == false)
assert(poisonMarkCount == 1)
// 两个不同 MEDIUM(100 + Frida 线程 203)触发。
assert(policy.applyPoisonDisposition(findings:[dz(100),dz(203)],legacy:legacy) == true)
assert(poisonMarkCount == 2)
// 弱信号(201/204)永不触发毒化。
assert(policy.applyPoisonDisposition(findings:[dz(201),dz(204)],legacy:legacy) == false)
assert(poisonMarkCount == 2)
// 二进制篡改 500/501 本轮不参与毒化(仅观察)。
assert(policy.applyPoisonDisposition(findings:[dz(500),dz(501)],legacy:legacy) == false)
assert(poisonMarkCount == 2)
// legacy 越狱即 STRONG,单条触发。
assert(policy.applyPoisonDisposition(findings:[],legacy:jb()) == true)
assert(poisonMarkCount == 3)
''')
p=subprocess.run(['xcrun','--sdk','macosx','swiftc','-module-cache-path',str(Path(td)/'module-cache'),str(main),str(POLICY),'-o',str(exe)],capture_output=True,text=True)
self.assertEqual(p.returncode,0,p.stderr)
subprocess.run([str(exe)],check=True,capture_output=True)
@unittest.skipUnless(INJECTION.exists() and SECRET.exists() and POLICY.exists(), '需要 App 注入检测源码')
def test_injection_detector_whitelist_tamper_and_dyld_insert(self):
secret_bytes = bytes(int(x, 16) for x in re.findall(r'0x([0-9a-fA-F]{2})', SECRET.read_text()))
self.assertGreaterEqual(len(secret_bytes), 16)
with tempfile.TemporaryDirectory() as td:
t = Path(td)
entries = [
{'name': 'RDCoreIO', 'path': 'Frameworks/RDCoreIO.framework/RDCoreIO'},
{'name': 'Alamofire', 'path': 'Frameworks/Alamofire.framework/Alamofire'},
{'name': 'readoor31', 'path': 'readoor31'},
]
msg = '\n'.join(f"{e['name']}|{e['path']}" for e in sorted(entries, key=lambda x: (x['name'], x['path'])))
digest = hmac.new(secret_bytes, msg.encode('utf-8'), hashlib.sha256).hexdigest()
valid_plist = t / 'valid.plist'
with valid_plist.open('wb') as f:
plistlib.dump({'known_images': entries, 'digest': digest}, f)
tampered_plist = t / 'tampered.plist'
tampered_entries = entries + [{'name': 'HelperKit', 'path': 'Frameworks/HelperKit.dylib'}]
with tampered_plist.open('wb') as f:
plistlib.dump({'known_images': tampered_entries, 'digest': digest}, f)
main = t / 'main.swift'
main.write_text(f'''
import Foundation
import CommonCrypto
struct RDDefenderFinding {{
let status: Int32; let reason: Int32
var isDetected: Bool {{ status == 1 }}
var isUnavailable: Bool {{ status == 2 }}
}}
struct RDSecurityRiskContext {{
let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool
}}
enum RDOSLogManager {{
enum LogLevel {{ case debug, info, warning, error }}
static func logWarning(_ message: String) {{}}
static func logInfo(_ message: String) {{}}
static func logDiag(_ code: String, level: LogLevel = .error) {{}}
}}
var poisonMarkCount = 0
func rd_epub_poison_mark(_ entropy: UInt64) {{ poisonMarkCount += 1 }}
func rd_sd_cc_hmac(
_ alg: UInt32,
_ key: UnsafeRawPointer?,
_ keyLen: Int,
_ data: UnsafeRawPointer?,
_ dataLen: Int,
_ macOut: UnsafeMutableRawPointer?
) -> Int32 {{
CCHmac(CCHmacAlgorithm(alg), key, keyLen, data, dataLen, macOut)
return 0
}}
let detector = RDInjectionDetector.shared
let bundle = "/tmp/FakeApp.app"
let validImages = [
"/usr/lib/libSystem.B.dylib",
"\\(bundle)/readoor31",
"\\(bundle)/Frameworks/Alamofire.framework/Alamofire",
"\\(bundle)/Frameworks/RDCoreIO.framework/RDCoreIO"
]
let helperImages = validImages + ["\\(bundle)/Frameworks/HelperKit.dylib"]
let missingWL = detector.loadWhitelist(from: nil)
let tamperedWL = detector.loadWhitelist(from: URL(fileURLWithPath: "{tampered_plist}"))
let validWL = detector.loadWhitelist(from: URL(fileURLWithPath: "{valid_plist}"))
assert(!missingWL.isValid)
assert(!tamperedWL.isValid)
assert(validWL.isValid)
#if DEBUG
let expectedInvalidDefault = false
assert(RDInjectionDetector.defaultFailClosedOnInvalidWhitelist == false)
#else
let expectedInvalidDefault = true
assert(RDInjectionDetector.defaultFailClosedOnInvalidWhitelist == true)
#endif
// 1. 缺失 RDKnownImages.plist: Debug 放行,Release fail-closed 拦截
assert(detector.evaluate(
whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
) == expectedInvalidDefault)
// 2. 篡改 RDKnownImages.plist(HMAC 不匹配): Debug 放行,Release fail-closed 拦截
assert(detector.evaluate(
whitelistResult: tamperedWL, dyldInsertEnv: nil, loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
) == expectedInvalidDefault)
// 无论 Debug/Release,显式 failClosed=true(hasSecurityRisk 同语义)在缺失/篡改时均告警
assert(detector.evaluate(whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages, bundlePath: bundle, failClosedOnInvalidWhitelist: true))
// 3. 合法白名单 + 匹配镜像: Debug/Release 均通过
assert(!detector.evaluate(
whitelistResult: validWL, dyldInsertEnv: nil, loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
))
// 4. 合法白名单 + 未授权包内库 HelperKit.dylib: Debug/Release 均拦截
assert(detector.evaluate(
whitelistResult: validWL, dyldInsertEnv: nil, loadedImagePaths: helperImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
))
// 5. 白名单失效下,DYLD_INSERT_LIBRARIES(单条或冒号拼接)仍先于白名单校验被拦截
assert(detector.evaluate(
whitelistResult: missingWL, dyldInsertEnv: "/tmp/evil.dylib", loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: false
))
assert(detector.evaluate(
whitelistResult: tamperedWL, dyldInsertEnv: "/usr/lib/libSystem.B.dylib:/tmp/evil.dylib", loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: false
))
// 6. 合法系统与 Cryptex 路径 DYLD_INSERT_LIBRARIES 放行
assert(!detector.evaluate(
whitelistResult: validWL,
dyldInsertEnv: "/usr/lib/libViewDebuggerSupport.dylib:/private/preboot/Cryptexes/OS/usr/lib/libfoo.dylib",
loadedImagePaths: validImages,
bundlePath: bundle,
failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
))
// 7. Release fail-closed 结果并入 RDSecurityPolicy:触发 reason=900 与密钥毒化
if RDInjectionDetector.defaultFailClosedOnInvalidWhitelist {{
let detected = detector.evaluate(
whitelistResult: missingWL, dyldInsertEnv: nil, loadedImagePaths: validImages,
bundlePath: bundle, failClosedOnInvalidWhitelist: RDInjectionDetector.defaultFailClosedOnInvalidWhitelist
)
let ctx = RDSecurityRiskContext(debuggerDetected: false, injectedDylibDetected: detected, jailbreakDetected: false)
let policy = RDSecurityPolicy.shared
policy.mode = .enforce
let decision = policy.evaluate(findings: [], legacy: ctx)
assert(decision.action == .restrictSensitive && decision.strongReasons == [900])
assert(policy.applyPoisonDisposition(findings: [], legacy: ctx))
assert(poisonMarkCount == 1)
}}
''')
mcache = t / 'module-cache'
for label, extra_flags in [('debug', ['-DDEBUG']), ('release', [])]:
exe = t / f'inject_{label}'
cmd = [
'xcrun', '--sdk', 'macosx', 'swiftc',
*extra_flags,
'-module-cache-path', str(mcache),
str(main), str(INJECTION), str(SECRET), str(POLICY),
'-o', str(exe),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
self.assertEqual(proc.returncode, 0, f'{label} compile failed:\n{proc.stderr}')
subprocess.run([str(exe)], check=True, capture_output=True)
def test_appstore_distribution_anti_tamper_enforcement(self):
with tempfile.TemporaryDirectory() as td:
t = Path(td)
main = t / 'main.swift'
exe = t / 'appstore_policy'
main.write_text('''
import Foundation
import CommonCrypto
struct RDDefenderFinding {
let status: Int32; let reason: Int32
var isDetected: Bool { status == 1 }
var isUnavailable: Bool { status == 2 }
}
struct RDSecurityRiskContext {
let debuggerDetected: Bool; let injectedDylibDetected: Bool; let jailbreakDetected: Bool
}
var poisonMarkCount = 0
var lastPoisonEntropy: UInt64 = 0
func rd_epub_poison_mark(_ entropy: UInt64) { poisonMarkCount += 1; lastPoisonEntropy = entropy }
func dz(_ r: Int32) -> RDDefenderFinding { RDDefenderFinding(status: 1, reason: r) }
let legacy = RDSecurityRiskContext(debuggerDetected: false, injectedDylibDetected: false, jailbreakDetected: false)
let policy = RDSecurityPolicy.shared
// Release 默认已收敛为 .enforce(不直接暴露 .terminateConfirmed 秒退与明文 jsonl)
assert(policy.mode == .enforce)
let dec = policy.evaluate(findings: [dz(500)], legacy: legacy)
assert(dec.action == .restrictSensitive)
assert(dec.strongReasons == [500])
assert(dec.terminationReasons == [500])
assert(policy.applyPoisonDisposition(findings: [dz(500)], legacy: legacy) == true)
assert(poisonMarkCount == 1 && lastPoisonEntropy != 0)
let signDec = policy.evaluate(findings: [dz(501)], legacy: legacy)
assert(signDec.strongReasons == [501])
assert(policy.applyPoisonDisposition(findings: [dz(501)], legacy: legacy) == true)
assert(poisonMarkCount == 2)
''')
cmd = [
'xcrun', '--sdk', 'macosx', 'swiftc',
'-DIG_APPSTORE_DISTRIBUTION',
'-module-cache-path', str(t / 'module-cache'),
str(main), str(POLICY), '-o', str(exe),
]
proc = subprocess.run(cmd, capture_output=True, text=True)
self.assertEqual(proc.returncode, 0, proc.stderr)
subprocess.run([str(exe)], check=True, capture_output=True)
if __name__=='__main__':unittest.main()
+205
View File
@@ -0,0 +1,205 @@
"""Unit tests for M7: static framework ThinLTO bitcode extraction, obfuscation & repacking."""
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'
TOOLS_XCODE_ARCHIVE = ROOT / 'tools' / 'xcode_archive'
sys.path.insert(0, str(TOOLS_LLVM_OBF))
sys.path.insert(0, str(TOOLS_XCODE_ARCHIVE))
from ig_toolchain_resolver import detect_stock_tool, resolve_opt # noqa: E402
import ig_ld_wrapper # 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 iphoneos_sdk_path() -> str:
return subprocess.check_output(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'], text=True).strip()
class TestStaticFrameworkObfuscation(unittest.TestCase):
def test_convert_static_framework_bitcode_repacks_arm64_macho_and_audits(self):
require_host_opt()
swiftc = detect_stock_tool('swiftc')
clang = detect_stock_tool('clang')
sdk_ios = iphoneos_sdk_path()
with tempfile.TemporaryDirectory(prefix='ig-m7-staticfw-') as td:
root = Path(td)
repo = root / 'repo'
trial_dir = repo / 'Vendor/RDPDFReaderView/Sources'
trial_dir.mkdir(parents=True)
trial_swift = trial_dir / 'RDPDFReaderTrial.swift'
trial_swift.write_text(
'''import Foundation
public struct RDPDFReaderTrialPolicy {
public var readablePageCount: Int
public init(readablePageCount: Int) {
self.readablePageCount = readablePageCount
}
}
@inline(never)
public func evaluateTrialQuota(_ page: Int, _ policy: RDPDFReaderTrialPolicy) -> Int {
let secretTag = "RD_PDF_TRIAL_WALL_SECRET_GATE_12345"
var res = page ^ 0x1357
if policy.readablePageCount > 0 && page >= policy.readablePageCount {
res = (res + secretTag.count) & 0x7fff
} else if page < 0 {
res = 0x2468
}
if res > 100 {
return res ^ 0x55
}
return res + 17
}
''',
encoding='utf-8',
)
dummy_c = root / 'RDPDFReaderView-dummy.c'
dummy_c.write_text('int rd_pdf_dummy_marker(void) { return 42; }\n', encoding='utf-8')
obj_dir = root / 'objs'
obj_dir.mkdir()
bc_o = obj_dir / 'RDPDFReaderTrial.o'
dummy_o = obj_dir / 'RDPDFReaderView-dummy.o'
subprocess.run([
swiftc,
'-target', 'arm64-apple-ios15.0',
'-sdk', sdk_ios,
'-O', '-lto=llvm-thin',
'-g', '-file-prefix-map', f'{repo}=.',
'-module-name', 'RDPDFReaderView',
'-parse-as-library', '-c',
str(trial_swift), '-o', str(bc_o),
], check=True)
subprocess.run([
clang,
'-target', 'arm64-apple-ios15.0',
'-isysroot', sdk_ios,
'-O2', '-c', str(dummy_c), '-o', str(dummy_o),
], check=True)
self.assertTrue(ig_ld_wrapper.is_bitcode_wrapper(bc_o), 'Expected Swift -lto=llvm-thin to emit bitcode wrapper')
fw_dir = root / 'frameworks/RDPDFReaderView.framework'
fw_dir.mkdir(parents=True)
arch_bin = fw_dir / 'RDPDFReaderView'
subprocess.run(['xcrun', 'libtool', '-static', '-o', str(arch_bin), str(bc_o), str(dummy_o)], check=True)
policy_path = root / 'policy.json'
policy = {
'exempt_path_substrings': ['/Pods/'],
'exempt_function_prefixes': [],
'obfuscate_static_frameworks': ['RDPDFReaderView'],
'string_encrypt_targets': [{'id': 'pdf_str', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'string_encrypt_swift_targets': [{'id': 'pdf_swstr', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'flatten_targets': [{'id': 'pdf_fla', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'opaque_const_targets': [{'id': 'pdf_const', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'arithmetic_targets': [{'id': 'pdf_arith', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'indirect_branch_targets': [{'id': 'pdf_ibr', 'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift'}],
'required_targets': [
{
'id': 'vendor_pdf_trial',
'path_contains': 'Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift',
'min_flattened': 1,
'min_strings_encrypted': 0,
}
],
}
policy_path.write_text(json.dumps(policy), encoding='utf-8')
out_bin = root / 'build/readoor31OtherPay.app/readoor31OtherPay'
out_bin.parent.mkdir(parents=True)
linkmap = root / 'build/LinkMap.txt'
ld_args = [
'-arch', 'arm64',
'-platform_version', 'ios', '15.0', '18.0',
'-syslibroot', sdk_ios,
'-F', str(fw_dir.parent),
'-framework', 'RDPDFReaderView',
'-flto=thin',
'-object_path_lto', str(root / 'build/lto.o'),
'-o', str(out_bin),
]
ctl = {
'mode': 'full',
'filter': 'all',
'route2': 'on',
'all_off': '0',
'seed': 'm7_fw_seed_1',
'stamp': 'test_stamp',
'policy_profile': 'default',
}
conv_report = {
'expected_swift_count': 0,
'converted_swift_count': 0,
'skipped_swift_count': 0,
'skipped_swift': [],
'swift_audits': [],
'objc_audits': [],
'replaced_entries': [],
'static_frameworks_obfuscated': [],
}
new_args, updated_report = ig_ld_wrapper.convert_static_framework_bitcode(
ld_args, out_bin, str(linkmap), ctl, str(policy_path), policy, repo, conv_report
)
if not ig_ld_wrapper.args_contain_remaining_bitcode(new_args, updated_report['replaced_entries']):
new_args = ig_ld_wrapper.strip_lto_link_flags(new_args)
self.assertNotIn('-framework', new_args)
self.assertNotIn('-flto=thin', new_args)
self.assertNotIn('-object_path_lto', new_args)
fw_recs = updated_report['static_frameworks_obfuscated']
self.assertEqual(len(fw_recs), 1)
self.assertEqual(fw_recs[0]['framework'], 'RDPDFReaderView')
self.assertEqual(fw_recs[0]['bitcode_members'], 1)
self.assertEqual(fw_recs[0]['passthrough_members'], 1)
obf_archive = Path(fw_recs[0]['output_archive'])
self.assertTrue(obf_archive.is_file())
self.assertIn(str(obf_archive), new_args)
# Inspect repacked archive members: zero bitcode remains, all Mach-O arm64 objects.
repacked_members = ig_ld_wrapper._parse_bsd_ar_members(obf_archive)
self.assertIsNotNone(repacked_members)
self.assertEqual(len(repacked_members), 2)
for m_name, payload in repacked_members:
self.assertNotIn(payload[:4], ig_ld_wrapper.BITCODE_MAGICS, f'Member {m_name} still bitcode!')
magic = struct.unpack_from('<I', payload, 0)[0]
self.assertEqual(magic, 0xFEEDFACF, f'Member {m_name} is not 64-bit Mach-O MH_OBJECT')
audit_summary = ig_ld_wrapper.evaluate_and_write_obf_audit(
out_bin, str(linkmap), ctl, str(policy_path), policy, updated_report
)
self.assertGreaterEqual(audit_summary['total_flattened'], 1)
self.assertGreaterEqual(audit_summary['total_opaque_constants'], 1)
self.assertGreaterEqual(audit_summary['total_arithmetic_rewrites'], 1)
self.assertEqual(len(audit_summary['required_targets']), 1)
self.assertEqual(audit_summary['required_targets'][0]['id'], 'vendor_pdf_trial')
self.assertGreaterEqual(audit_summary['required_targets'][0]['flattened_hits'], 1)
self.assertTrue(
any('Vendor/RDPDFReaderView/Sources/RDPDFReaderTrial.swift' in (a.get('source_path') or '')
for a in updated_report['swift_audits'])
)
if __name__ == '__main__':
unittest.main()
+69
View File
@@ -9,7 +9,9 @@
需 Xcode + iphoneos SDK;缺则跳过。
"""
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
@@ -138,6 +140,73 @@ class StaticHardeningTests(unittest.TestCase):
and ('__ig' in ln or '__poison' in ln or '__ig_p' in ln)]
self.assertEqual(leak, [], f'泄漏性命名 section(strip 抹不掉,会挂牌毒化副本位置):{leak}')
def test_no_diagnostic_strings_in_release(self):
"""Release 构建(无 DEBUG/IG_OBSERVATION)不得残留探针 subject/evidence 明文诊断串。"""
with tempfile.TemporaryDirectory() as td:
ar_dir = Path(td)
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'ar', 'x', str(self.lib)],
cwd=ar_dir, check=True)
cstrings = bytearray()
for obj in sorted(ar_dir.glob('*.o')):
out = subprocess.run(
['xcrun', '--sdk', 'iphoneos', 'otool', '-s', '__TEXT', '__cstring', str(obj)],
capture_output=True, text=True, check=True,
).stdout
for line in out.splitlines():
parts = line.split('\t')
if len(parts) == 2:
for hx in parts[1].strip().split():
try:
cstrings.append(int(hx, 16))
except ValueError:
pass
raw = bytes(cstrings)
diag_needles = [
b'cryptid==0',
b'CS_VALID',
b'get-task-allow',
b'P_TRACED',
b'DYLD_INSERT_LIBRARIES',
b'dispatch-write',
b'dispatch-target',
b'archive-target',
b'task_threads',
'蹦床'.encode('utf-8'),
'基线'.encode('utf-8'),
'重签'.encode('utf-8'),
'提供方'.encode('utf-8'),
'弱信号'.encode('utf-8'),
]
hits = [n.decode('utf-8', errors='replace') for n in diag_needles if n in raw]
self.assertEqual(hits, [], f'Release libIGDefender.a __cstring 残留诊断明文串:{hits}')
def test_m1_objc_hybrid_hardening_coverage(self):
"""M1:RDEpubCryptBridge 基线监控 >= 30 条,高敏 OC 扩展进入压平与串加密策略,核心 OC 类锁定 L1。"""
bridge_src = (ROOT / 'readoor-test/readoor/3.0/Base/Security/RDEpubCryptBridge.m').read_text(encoding='utf-8')
watch_count = len(re.findall(r'sel_getName\(@selector\(', bridge_src))
self.assertGreaterEqual(watch_count, 30, f'Expected >= 30 baseline watches, got {watch_count}')
policy = json.loads((ROOT / 'config/ig_llvm_policy.json').read_text(encoding='utf-8'))
expected_paths = [
'BookShelf/Classes/Features/IAP/Extension/',
'BookShelf/Classes/Features/Login/Extension/',
'BookShelf/Classes/Extension/ControllersExtension/STSBaseViewController+STSReadOrPayExtension.m',
'BookView/EPUB/Core/Classes/STSBaseViewController+STSEpubViewLoginOrPayExtension.m',
'BookView/PDF/Core/Classes/Stage/STSBaseViewController+STSPDFViewLoginOrPayExtension.m',
]
str_paths = {r.get('path_contains') for r in policy.get('string_encrypt_targets', [])}
fla_paths = {r.get('path_contains') for r in policy.get('flatten_targets', [])}
for p in expected_paths:
self.assertIn(p, str_paths, f'Missing from string_encrypt_targets: {p}')
self.assertIn(p, fla_paths, f'Missing from flatten_targets: {p}')
build_py = (ROOT / 'tools/llvm_obf/build_obfuscated_ipa.py').read_text(encoding='utf-8')
for cls_name in (
'STSIAPHandler', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler',
'STSIAPVerifyTask', 'STSJailbreakDetectTool',
):
self.assertIn(f"'{cls_name}'", build_py, f'Missing from unobfuscated_watch_classes: {cls_name}')
if __name__ == '__main__':
unittest.main()
+286
View File
@@ -0,0 +1,286 @@
import hashlib
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
TOOLS_LLVM_OBF = ROOT / 'tools' / 'llvm_obf'
sys.path.insert(0, str(TOOLS_LLVM_OBF))
import build_igopt_local # noqa: E402
import ig_toolchain_resolver as resolver # noqa: E402
def _make_fake_opt(path: Path, body: bytes = b'#!/bin/sh\nexit 0\n') -> str:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(body)
path.chmod(0o755)
return hashlib.sha256(body).hexdigest()
class TestToolchainSelfHeal(unittest.TestCase):
def test_parse_swift_version_output_and_real_detect(self):
sample = 'Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)\nTarget: arm64-apple-macosx26.0\n'
parsed = resolver.parse_swift_version_output(sample)
self.assertEqual(parsed['swift_version'], '6.4')
self.assertEqual(parsed['swiftlang_version'], '6.4.0')
self.assertEqual(parsed['swift_major_minor'], '6.4')
self.assertEqual(parsed['clang_version'], '2100.3.34.1')
live = resolver.detect_swift_info()
self.assertTrue(live['swift_version'])
self.assertTrue(live['swift_major_minor'])
def test_compute_passes_hash_deterministic_and_sensitive(self):
with tempfile.TemporaryDirectory() as td:
pdir = Path(td) / 'llvm_passes'
self.assertEqual(resolver.compute_passes_hash(pdir), 'legacy')
(pdir / 'src').mkdir(parents=True)
(pdir / 'CMakeLists.txt').write_text('project(IG)\n', encoding='utf-8')
cpp = pdir / 'src' / 'IGPass.cpp'
cpp.write_text('int f() { return 1; }\n', encoding='utf-8')
h1 = resolver.compute_passes_hash(pdir)
h2 = resolver.compute_passes_hash(pdir)
self.assertEqual(h1, h2)
self.assertEqual(len(h1), 64)
cpp.write_text('int f() { return 2; }\n', encoding='utf-8')
h3 = resolver.compute_passes_hash(pdir)
self.assertNotEqual(h1, h3)
def test_resolve_llvm_branch_for_swift_override_and_ls_remote(self):
with tempfile.TemporaryDirectory() as td:
map_p = Path(td) / 'map.json'
map_p.write_text(json.dumps({
'by_xcode_build': {'99Z999': 'custom/xcode-branch'},
'by_swiftlang': {'6.5.1': 'custom/swiftlang-branch'},
'by_swift_major_minor': {'6.5': 'custom/mm-branch'},
}), encoding='utf-8')
self.assertEqual(
resolver.resolve_llvm_branch_for_swift(
{'swiftlang_version': '6.5.1', 'swift_major_minor': '6.5'},
{'xcode_build': '99Z999'},
map_path=map_p,
),
'custom/xcode-branch',
)
self.assertEqual(
resolver.resolve_llvm_branch_for_swift(
{'swiftlang_version': '6.5.1', 'swift_major_minor': '6.5'},
{'xcode_build': '28A100'},
map_path=map_p,
),
'custom/swiftlang-branch',
)
ls_out = '\n'.join([
'aaa\trefs/heads/swift/release/6.4.0',
'bbb\trefs/heads/swift/release/6.5',
'ccc\trefs/heads/swift/release/6.6.1',
'ddd\trefs/heads/swift/release/6.6.2',
'eee\trefs/tags/swift-6.7.0-RELEASE',
'fff\trefs/tags/swift-6.7.0-RELEASE^{}',
])
empty_map = Path(td) / 'missing_map.json'
with patch('ig_toolchain_resolver.subprocess.check_output', return_value=ls_out):
self.assertEqual(
resolver.resolve_llvm_branch_for_swift(
{'swiftlang_version': '6.5.3', 'swift_major_minor': '6.5'},
{'xcode_build': '28A200'},
map_path=empty_map,
),
'swift/release/6.5',
)
self.assertEqual(
resolver.resolve_llvm_branch_for_swift(
{'swiftlang_version': '6.6.9', 'swift_major_minor': '6.6'},
{'xcode_build': '28B100'},
map_path=empty_map,
),
'swift/release/6.6.2',
)
self.assertEqual(
resolver.resolve_llvm_branch_for_swift(
{'swiftlang_version': '6.7.0', 'swift_major_minor': '6.7'},
{'xcode_build': '29A100'},
map_path=empty_map,
),
'swift-6.7.0-RELEASE',
)
def test_ensure_opt_l1_hit_l2_reuse_pruning_and_circuit_breaker(self):
with tempfile.TemporaryDirectory() as td:
root = Path(td)
cache_dir = root / 'toolchains'
pdir = root / 'llvm_passes'
(pdir / 'src').mkdir(parents=True)
(pdir / 'CMakeLists.txt').write_text('project(IG)\n', encoding='utf-8')
(pdir / 'src' / 'IGPass.cpp').write_text('int pass = 1;\n', encoding='utf-8')
passes_hash = resolver.compute_passes_hash(pdir)
h8 = passes_hash[:8]
# Seed 3 older versioned toolchains in cache_dir (one matching swift 6.4)
older_builds = ['26A100', '27A100', '27A9000']
for idx, bld in enumerate(older_builds):
d = cache_dir / f'{bld}-arm64-{h8}'
sha = _make_fake_opt(d / 'bin' / 'opt', f'#!/bin/sh\necho opt-{bld}\n'.encode('utf-8'))
(d / 'meta.json').write_text(json.dumps({
'schema_version': 1,
'xcode_build': bld,
'swift_major_minor': '6.3' if idx == 0 else '6.4',
'arch': 'arm64',
'passes_hash': passes_hash,
'opt_sha256': sha,
}), encoding='utf-8')
t_val = 1_700_000_000 + idx * 100
os.utime(d / 'meta.json', (t_val, t_val))
xc_new = {'xcode_version': '27.2', 'xcode_build': '27B100', 'developer_dir': '/Dev'}
sw_new = {'swift_version': '6.4', 'swiftlang_version': '6.4.0', 'swift_major_minor': '6.4', 'clang_version': '2100', 'raw': 'Apple Swift version 6.4'}
# 1) L2 reuse succeeds for 27B100, promotes newest compatible (27A9000), prunes oldest down to keep_versions=3
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new), \
patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_new), \
patch('ig_toolchain_resolver.verify_portability') as mock_port, \
patch('ig_toolchain_resolver.smoke_test_opt', return_value={'c_audit': {}, 'swift_audit': {}}) as mock_smoke:
res_reused = resolver.ensure_opt(
cache_root=cache_dir,
passes_dir=pdir,
keep_versions=3,
manifest_path=root / 'no_manifest.json',
default_cache_root=cache_dir,
)
self.assertEqual(res_reused['source_mode'], 'reused')
self.assertTrue(res_reused['updated'])
self.assertIn('27A9000', res_reused['reused_from'])
self.assertEqual(mock_port.call_count, 1)
self.assertEqual(mock_smoke.call_count, 1)
self.assertFalse((cache_dir / f'26A100-arm64-{h8}').exists())
self.assertTrue((cache_dir / f'27B100-arm64-{h8}' / 'meta.json').is_file())
# 2) L1 exact hit returns fast without calling smoke test
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new), \
patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_new), \
patch('ig_toolchain_resolver.smoke_test_opt') as should_not_smoke:
res_cached = resolver.ensure_opt(
cache_root=cache_dir,
passes_dir=pdir,
manifest_path=root / 'no_manifest.json',
default_cache_root=cache_dir,
)
self.assertEqual(res_cached['source_mode'], 'cached')
self.assertFalse(res_cached['updated'])
self.assertEqual(should_not_smoke.call_count, 0)
# Fast read-only resolve_opt hits the newly promoted dir
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new):
fast_res = resolver.resolve_opt(
manifest_path=root / 'no_manifest.json',
cache_root=cache_dir,
passes_dir=pdir,
require_obf=True,
)
self.assertEqual(fast_res['source_mode'], 'cached')
self.assertEqual(fast_res['opt_path'], res_reused['opt_path'])
# Editing llvm_passes source invalidates resolve_opt lookup
(pdir / 'src' / 'IGPass.cpp').write_text('int pass = 2;\n', encoding='utf-8')
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_new):
miss_res = resolver.resolve_opt(
manifest_path=root / 'no_manifest.json',
cache_root=cache_dir,
passes_dir=pdir,
require_obf=False,
)
self.assertIsNone(miss_res['opt_path'])
# 3) L4 failure triggers circuit breaker; repeated call fails fast; force_rebuild clears breaker
xc_major = {'xcode_version': '28.0', 'xcode_build': '28A50', 'developer_dir': '/Dev28'}
sw_major = {'swift_version': '6.5', 'swiftlang_version': '6.5.0', 'swift_major_minor': '6.5', 'clang_version': '2200', 'raw': 'Apple Swift version 6.5'}
pdir2 = root / 'llvm_passes_v2'
pdir2.mkdir()
(pdir2 / 'CMakeLists.txt').write_text('project(IG2)\n', encoding='utf-8')
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_major), \
patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_major), \
patch('ig_toolchain_resolver.find_cli_tool', return_value='/usr/bin/cmake'), \
patch('ig_toolchain_resolver.resolve_llvm_branch_for_swift', return_value='swift/release/6.5'), \
patch.object(build_igopt_local, 'build_opt', side_effect=RuntimeError('cmake boom')) as mock_build:
with self.assertRaisesRegex(RuntimeError, 'cmake boom'):
resolver.ensure_opt(
cache_root=cache_dir,
passes_dir=pdir2,
manifest_path=root / 'no_manifest.json',
default_cache_root=cache_dir,
)
self.assertEqual(mock_build.call_count, 1)
# Immediate retry blocked by circuit breaker without calling build_opt
with self.assertRaisesRegex(RuntimeError, 'Circuit breaker active'):
resolver.ensure_opt(
cache_root=cache_dir,
passes_dir=pdir2,
manifest_path=root / 'no_manifest.json',
default_cache_root=cache_dir,
)
self.assertEqual(mock_build.call_count, 1)
# Force rebuild clears breaker and succeeds
h8_v2 = resolver.compute_passes_hash(pdir2)[:8]
built_target = cache_dir / f'28A50-arm64-{h8_v2}'
built_sha = _make_fake_opt(built_target / 'bin' / 'opt', b'#!/bin/sh\necho built\n')
built_meta = {
'schema_version': 1,
'xcode_build': '28A50',
'swift_major_minor': '6.5',
'arch': 'arm64',
'passes_hash': resolver.compute_passes_hash(pdir2),
'opt_sha256': built_sha,
'source_mode': 'built',
}
(built_target / 'meta.json').write_text(json.dumps(built_meta), encoding='utf-8')
with patch('ig_toolchain_resolver.detect_xcode_info', return_value=xc_major), \
patch('ig_toolchain_resolver.detect_swift_info', return_value=sw_major), \
patch('ig_toolchain_resolver.find_cli_tool', return_value='/usr/bin/cmake'), \
patch('ig_toolchain_resolver.resolve_llvm_branch_for_swift', return_value='swift/release/6.5'), \
patch.object(build_igopt_local, 'build_opt', return_value={'opt_sha256': built_sha, 'meta': built_meta}) as mock_build_ok:
res_built = resolver.ensure_opt(
cache_root=cache_dir,
passes_dir=pdir2,
force_rebuild=True,
manifest_path=root / 'no_manifest.json',
default_cache_root=cache_dir,
)
self.assertEqual(mock_build_ok.call_count, 1)
self.assertEqual(res_built['source_mode'], 'built')
self.assertTrue(res_built['updated'])
def test_resolve_effective_policy_injects_dynamic_home_scrub_without_hardcoding(self):
with tempfile.TemporaryDirectory() as td:
p = Path(td)
repo = p / 'app_repo'
repo.mkdir()
(repo / 'readoor.xcodeproj').mkdir()
cache_dir = p / 'cache'
policy_p = p / 'policy.json'
policy_p.write_text(json.dumps({
'scrub_path_substrings': ['/tmp/ig-ipa-work/', '/src/readoor/'],
'flatten_targets': [],
}), encoding='utf-8')
eff_p, eff = resolver.resolve_effective_policy(str(policy_p), repo, cache_dir)
self.assertNotEqual(eff_p, str(policy_p))
self.assertTrue(Path(eff_p).is_file())
self.assertFalse(eff['l1_translation_active'])
self.assertIn(f'{Path.home()}/', eff['scrub_path_substrings'])
self.assertIn(f'{repo.resolve()}/', eff['scrub_path_substrings'])
if __name__ == '__main__':
unittest.main()