Files
iOSGuard/tests/fixtures/hook_device.m
shenleiandClaude Opus 4.8 599e1da5ce feat(defender): 可集成静态库 + readoor 接入方案(检测→分级→数据毒化闭环)
在 iOSGuard 侧产出可集成产物与接入文档,不修改 readoor 代码。

- defender/: anti_hook/anti_frida/anti_debug/anti_jailbreak 探针 + syscall 直发、
  policy 分级层、poison 数据依赖毒化、dispatch/resolve/call_bridge 等子模块
- poison: 三副本冗余、无分支掩码;健康恒等、毒化破坏 key(替代 if-exit 处置)
- policy: STRONG/MEDIUM/WEAK 分级,守误报底线,仅 DETECTED 参与、组合命中才毒化
- anti_jailbreak: IGSyscall 直发 svc 检测越狱文件(400)/沙盒逃逸(401),绕 libc hook
- tools/build_defender_lib.sh: 一键交叉编译打包 libIGDefender.a(arm64) + umbrella 头
- docs/18_READOOR_DEFENDER_INTEGRATION.md: 精确到文件/bridging/替换点/代码片段
- docs/05-17 + evidence + tests + macho_guard/static_sdk_redirect 工具链

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-12 22:16:47 +09:00

394 lines
18 KiB
Objective-C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* hook_device.m — 真机 HOOK 正向验证诊断进程(step11)。
*
* 目的:在非越狱真机的自身进程内构造四种受控攻击形态,验证 Defender 探针
* 在真机环境(真实 dyld、真实内存权限、真实线程/镜像枚举)下能命中对应 reason:
* 1. GOT 重绑定(fishhook 同款页权限改写自身 __got 槽)→ 期望 reason=102
* 2. 蹦床序言(导出符号首指令为 B / LDR-literal+BR x16)→ 期望 reason=100+101
* 3. frida 特征线程名(gum-js-loop)→ 期望 reason=203
* 4. 容器外注入 dylib(Documents 下 dlopen;或宿主以 DYLD_INSERT_LIBRARIES 启动)
* → 期望 reason=200(+201)(dlopen 路径)/ reason=202(插入库路径)
*
* 边界(如实声明):
* - 不修改任何系统代码页(非越狱不可行):inline-hook 用例针对受控导出符号的
* 真实代码字节验证「读取+分类」,不等同于对系统函数的真实 patch。
* - 攻击操作(可写 GOT、装载模拟 dylib、特征线程名)只存在于本诊断源码,
* 绝不编入业务库;诊断进程结束即退出,不触碰业务 App。
*/
#import <Foundation/Foundation.h>
#include "IGDefender.h"
#include "anti_hook/IGAntiHook.h"
#include "anti_hook/IGObjCBaseline.h"
#include "anti_frida/IGAntiInject.h"
#include <dlfcn.h>
#include <errno.h>
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/* ---------- 发现收集:只记 DETECTED,逐条打日志 ---------- */
#define IG_MAXF 64
static IGFinding g_findings[IG_MAXF];
static int g_nfindings;
static int collect(const IGFinding *f, void *ctx) {
(void)ctx;
if (f->status == IG_DETECTED && g_nfindings < IG_MAXF)
g_findings[g_nfindings++] = *f;
NSLog(@"IG_HOOK_FINDING status=%d reason=%d subject=%s evidence=%s",
f->status, f->reason, f->subject, f->evidence);
return 0;
}
static void reset_findings(void) { g_nfindings = 0; }
static const IGFinding *first_reason(int reason) {
for (int i = 0; i < g_nfindings; ++i)
if (g_findings[i].reason == reason) return &g_findings[i];
return NULL;
}
static const char *g_bundle; /* 主 bundle 路径,供各探针使用 */
/* 完整聚合扫描(anti_hook + 注入 + frida 线程)。 */
static int scan_all(void) {
reset_findings();
return ig_defender_scan(g_bundle, 0, collect, NULL);
}
/* ---------- 用例 1:GOT 重绑定(102)----------
* fishhook 同款走法:定位主可执行文件 __got 中绑定 getpid 的槽,
* 临时以 VM_PROT_COPY 改页为可写,写入本进程函数地址,恢复只读。
* 只写自身进程数据页,不改任何代码。 */
static int ig_rebind_stub(void) { return 4242; } /* 指给 GOT 的假实现 */
static void **find_main_got_slot(const char *bare_name) {
const struct mach_header_64 *mh =
(const struct mach_header_64 *)_dyld_get_image_header(0);
if (!mh || mh->magic != MH_MAGIC_64) return NULL;
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
const struct segment_command_64 *linkedit = NULL;
const struct symtab_command *symtab = NULL;
const struct dysymtab_command *dysymtab = NULL;
const uint8_t *cmd = (const uint8_t *)(mh + 1);
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
const struct load_command *lc = (const struct load_command *)cmd;
if (lc->cmd == LC_SEGMENT_64) {
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
if (strcmp(seg->segname, SEG_LINKEDIT) == 0) linkedit = seg;
} else if (lc->cmd == LC_SYMTAB) {
symtab = (const struct symtab_command *)lc;
} else if (lc->cmd == LC_DYSYMTAB) {
dysymtab = (const struct dysymtab_command *)lc;
}
}
if (!linkedit || !symtab || !dysymtab) return NULL;
uintptr_t le_base = (uintptr_t)slide + linkedit->vmaddr - linkedit->fileoff;
const struct nlist_64 *syms = (const struct nlist_64 *)(le_base + symtab->symoff);
const char *strtab = (const char *)(le_base + symtab->stroff);
const uint32_t *indirect = (const uint32_t *)(le_base + dysymtab->indirectsymoff);
size_t nlen = strlen(bare_name);
cmd = (const uint8_t *)(mh + 1);
for (uint32_t i = 0; i < mh->ncmds; ++i, cmd += ((const struct load_command *)cmd)->cmdsize) {
const struct load_command *lc = (const struct load_command *)cmd;
if (lc->cmd != LC_SEGMENT_64) continue;
const struct segment_command_64 *seg = (const struct segment_command_64 *)lc;
const struct section_64 *sect = (const struct section_64 *)(seg + 1);
for (uint32_t s = 0; s < seg->nsects; ++s) {
if ((sect[s].flags & SECTION_TYPE) != S_NON_LAZY_SYMBOL_POINTERS) continue;
size_t n = sect[s].size / sizeof(void *);
const uint32_t *idxs = indirect + sect[s].reserved1;
void **slots = (void **)((uintptr_t)slide + sect[s].addr);
for (size_t k = 0; k < n; ++k) {
uint32_t si = idxs[k];
if (si == INDIRECT_SYMBOL_ABS || si == INDIRECT_SYMBOL_LOCAL) continue;
const char *sym = strtab + syms[si].n_un.n_strx;
/* sym 形如 "_getpid":比较去下划线后的部分 */
if (sym[0] == '_' && strncmp(sym + 1, bare_name, nlen) == 0 &&
sym[1 + nlen] == '\0')
return &slots[k];
}
}
}
return NULL;
}
/* 改写自身 GOT 槽:VM_PROT_COPY 写副本页,写完恢复只读。返回 0 成功。 */
static int rebind_got_slot(void **slot, void *to) {
vm_address_t page = (vm_address_t)(uintptr_t)slot & ~0xfffull;
if (vm_protect(mach_task_self(), page, 0x1000, 0,
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY) != KERN_SUCCESS)
return -1;
*slot = to;
vm_protect(mach_task_self(), page, 0x1000, 0, VM_PROT_READ);
return 0;
}
/* ---------- 用例 2:蹦床序言导出符号(100+101)----------
* 两个文件级汇编符号,首指令分别是「无条件 B」与「LDR-literal x16 + BR x16」,
* 与 Frida/Dobby 蹦床形态一致。仅被 dlsym 解析和字节读取,从不执行。 */
asm(".globl _ig_hook_target_b\n"
".align 2\n"
"_ig_hook_target_b:\n"
" b .+64\n"
" ret\n");
asm(".globl _ig_hook_target_lb\n"
".align 2\n"
"_ig_hook_target_lb:\n"
" ldr x16, #8\n"
" br x16\n"
" .quad 0\n");
/* ---------- 用例 3:frida 特征线程名(203)---------- */
static void *gum_thread(void *arg) {
(void)arg;
pthread_setname_np("gum-js-loop");
usleep(600000); /* 确保扫描期间线程存活 */
return NULL;
}
/* ---------- 用例 6:ObjC 方法 IMP 基线(110)----------
* 运行期创建类并采集基线,class_replaceMethod 换实现后扫描 → 期望 110。 */
static int ig_objc_imp_original(void *self, SEL _cmd) { (void)self; (void)_cmd; return 1; }
static int ig_objc_imp_swapped(void *self, SEL _cmd) { (void)self; (void)_cmd; return 2; }
static Class make_objc_fixture_class(void) {
Class c = objc_allocateClassPair(objc_getClass("NSObject"), "IGHookFixtureTarget", 0);
if (!c) return NULL;
if (!class_addMethod(c, sel_registerName("value"), (IMP)ig_objc_imp_original, "i16@0:8")) {
objc_disposeClassPair(c);
return NULL;
}
objc_registerClassPair(c);
return c;
}
/* ---------- 输出协议(宿主 run_hook_device.py 解析)---------- */
static int g_pass = 0, g_fail = 0;
static void mark(const char *name, int pass, const char *detail) {
NSLog(@"IG_HOOK_CASE %s %s%s%s", name, pass ? "PASS" : "FAIL",
detail && *detail ? " detail=" : "", detail ? detail : "");
if (pass) ++g_pass; else ++g_fail;
}
int main(int argc, char **argv) {
(void)argc; (void)argv;
@autoreleasepool {
NSLog(@"IG_HOOK_MAIN");
g_bundle = NSBundle.mainBundle.bundlePath.UTF8String;
const char *insert = getenv("DYLD_INSERT_LIBRARIES");
if (insert && insert[0]) {
/* 相位 B:宿主经 DYLD_INSERT_LIBRARIES 启动本进程 → 真实 dyld 注入。 */
NSLog(@"IG_HOOK_INSERT_MODE value=%s", insert);
int hits = scan_all();
int r202 = first_reason(IG_REASON_DYLD_INSERT) != NULL;
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
NSLog(@"IG_HOOK_INSERT_SUMMARY detected=%d hits=%d reason202=%d reason200=%d",
g_nfindings, hits, r202, r200);
mark("dyld_insert", r202 || r200,
r202 ? "202+环境注入命中" : (r200 ? "200(插入镜像命中特征名)" : "未命中"));
NSLog(@"IG_HOOK_SUITE %s cases=1", g_fail ? "FAIL" : "PASS");
return g_fail ? 4 : 0;
}
/* ---- 相位 A:干净进程内的受控攻击形态 ---- */
/* 0. 基线:干净环境 0 命中。 */
int base = scan_all();
int base_unavail = 0; /* unavailable 已在 sink 日志逐条体现,不判失败 */
NSLog(@"IG_HOOK_BASELINE detected=%d", base);
mark("baseline_clean", g_nfindings == 0,
g_nfindings ? "干净环境出现 DETECTED(误报)" : "");
/* 1. 耗时小样本(5 次完整聚合扫描)。 */
{
mach_timebase_info_data_t tb;
mach_timebase_info(&tb);
double scale = (double)tb.numer / (double)tb.denom / 1e6; /* → ms */
double total = 0, best = 1e9;
for (int i = 0; i < 5; ++i) {
uint64_t t0 = mach_absolute_time();
scan_all();
double ms = (mach_absolute_time() - t0) * scale;
total += ms;
if (ms < best) best = ms;
}
NSLog(@"IG_HOOK_TIMING n=5 avg_ms=%.2f min_ms=%.2f", total / 5.0, best);
}
/* 2. GOT 重绑定 → 102;恢复 → 干净。 */
{
/* 确保可执行文件真实导入 getpid(否则 __got 无该槽)。 */
if (getpid() == -7) NSLog(@"unreachable");
void **slot = find_main_got_slot("getpid");
if (!slot) {
mark("got_rebind", 0, "未找到主程序 getpid 的 __got 槽(构建异常)");
} else {
void *orig = *slot;
NSLog(@"IG_HOOK_GOT slot=%p orig=%p", (void *)slot, orig);
if (rebind_got_slot(slot, (void *)ig_rebind_stub) != 0) {
mark("got_rebind", 0, "vm_protect 改写失败");
} else {
scan_all();
const IGFinding *f = first_reason(IG_REASON_GOT_REBIND);
int hit = f && strstr(f->subject, "getpid") != NULL;
mark("got_rebind", hit, f ? f->evidence : "未命中 102");
rebind_got_slot(slot, orig); /* 恢复,双写均经同一权限路径 */
int again = scan_all();
int clean = g_nfindings == 0;
NSLog(@"IG_HOOK_GOT_RESTORE detected=%d hits=%d", g_nfindings, again);
if (!clean)
mark("got_restore_clean", 0, "恢复后仍有 DETECTED");
else
mark("got_restore_clean", 1, "");
}
}
}
/* 3. 蹦床序言(经 dlsym+vm_read_overwrite 的完整探针链)→ 100+101。 */
{
const char *const names[] = {"ig_hook_target_b", "ig_hook_target_lb"};
reset_findings();
ig_anti_hook_check(names, 2, collect, NULL);
int b100 = 0, b101 = 0, lb100 = 0, lb101 = 0;
for (int i = 0; i < g_nfindings; ++i) {
const char *subj = g_findings[i].subject;
if (strstr(subj, "ig_hook_target_b")) {
b100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
b101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
} else if (strstr(subj, "ig_hook_target_lb")) {
lb100 |= g_findings[i].reason == IG_REASON_SYMBOL_PROVENANCE;
lb101 |= g_findings[i].reason == IG_REASON_INLINE_HOOK;
}
}
mark("prologue_b_branch", b100 && b101, b101 ? "首指令 B 被识别" : "未命中 101");
mark("prologue_ldr_br", lb100 && lb101, lb101 ? "LDR+BR 蹦床被识别" : "未命中 101");
}
/* 4. frida 特征线程名 → 203;join 后 → 干净。
* join 后内核回收线程对象存在延迟(task_threads 短期内仍可能列出已终止
* 线程),在 2s 窗口内轮询重扫:既能容忍回收延迟,又验证探针无粘滞缓存。 */
{
pthread_t t;
pthread_create(&t, NULL, gum_thread, NULL);
usleep(200000); /* 等线程命名完成 */
reset_findings();
ig_anti_frida_check(0, collect, NULL);
mark("frida_thread", first_reason(IG_REASON_FRIDA_THREAD) != NULL, "");
pthread_join(t, NULL);
int clean = 0;
for (int i = 0; i < 10 && !clean; ++i) {
usleep(200000);
reset_findings();
ig_anti_frida_check(0, collect, NULL);
clean = (g_nfindings == 0);
}
mark("frida_thread_gone", clean,
clean ? "join 后 2s 内恢复干净" : "join 后 2s 仍残留线程名(回收异常缓慢)");
}
/* 5. 注入证据两种形态:
* a) Documents/libfrida-sim.dylib —— 文件名命中注入特征 → 期望 200;
* (探针对命中特征的镜像即上报 200,不再重复报 Bundle 外,故不期望 201)
* b) Documents/libiosutil-sim.dylib —— 无特征命名的 Bundle 外镜像 → 期望 201。
* 相位 A 成功路径回显给宿主,供相位 B 的 DYLD_INSERT 使用。 */
{
NSString *res = [[NSBundle mainBundle] pathForResource:@"libfrida-sim"
ofType:@"dylib"];
NSString *docs = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];
NSString *dstA = [docs stringByAppendingPathComponent:@"libfrida-sim.dylib"];
NSString *dstB = [docs stringByAppendingPathComponent:@"libiosutil-sim.dylib"];
const char *chosen = NULL;
NSFileManager *fm = [NSFileManager defaultManager];
if (res) {
[fm removeItemAtPath:dstA error:nil];
[fm removeItemAtPath:dstB error:nil];
if ([fm copyItemAtPath:res toPath:dstA error:nil] &&
[fm copyItemAtPath:res toPath:dstB error:nil]) {
void *ha = dlopen(dstA.fileSystemRepresentation, RTLD_LOCAL);
if (ha) {
chosen = dstA.fileSystemRepresentation;
reset_findings();
ig_anti_inject_check(g_bundle, collect, NULL);
mark("injected_image",
first_reason(IG_REASON_INJECTED_IMAGE) != NULL,
"Documents 特征名装载命中 200");
} else {
const char *e = dlerror();
NSLog(@"IG_HOOK_DLOPEN_DOC_FAIL %s", e ? e : "?");
}
void *hb = dlopen(dstB.fileSystemRepresentation, RTLD_LOCAL);
if (hb) {
reset_findings();
ig_anti_inject_check(g_bundle, collect, NULL);
mark("foreign_image",
first_reason(IG_REASON_FOREIGN_IMAGE) != NULL,
"Documents 无特征名装载命中 201(弱信号)");
}
} else {
NSLog(@"IG_HOOK_COPY_FAIL %@", docs);
}
}
if (!chosen) {
/* 回退:从 .app 内 dlopen(Bundle 内只应命中 200)。 */
void *h = dlopen(res.fileSystemRepresentation, RTLD_LOCAL);
if (h) {
chosen = res.fileSystemRepresentation;
reset_findings();
ig_anti_inject_check(g_bundle, collect, NULL);
int r200 = first_reason(IG_REASON_INJECTED_IMAGE) != NULL;
int r201 = first_reason(IG_REASON_FOREIGN_IMAGE) != NULL;
mark("injected_image", r200 && !r201,
"容器外装载不可用,回退 Bundle 内(200 命中、201 不应命中)");
} else {
const char *e = dlerror();
mark("injected_image", 0, e ? e : "装载失败");
}
}
NSLog(@"IG_HOOK_DYLIB_PATH %s", chosen ? chosen : "none");
}
/* 6. ObjC IMP 基线:采集 → class_replaceMethod → 期望 110;未接入时聚合为 no-op。 */
{
Class c = make_objc_fixture_class();
if (!c) {
mark("objc_imp_baseline", 0, "运行期建类失败");
} else {
const IGObjCWatch watch[] = { { "IGHookFixtureTarget", "value" } };
size_t n = ig_objc_baseline_capture(watch, 1);
reset_findings();
int before = ig_objc_baseline_check(collect, NULL);
class_replaceMethod(c, sel_registerName("value"),
(IMP)ig_objc_imp_swapped, "i16@0:8");
reset_findings();
int after = ig_objc_baseline_check(collect, NULL);
mark("objc_imp_baseline", n == 1 && before == 0 && after == 1 &&
first_reason(IG_REASON_OBJC_IMP_CHANGED) != NULL,
after == 1 ? "替换后命中 110" : "未命中 110");
}
}
NSLog(@"IG_HOOK_SUITE %s cases=%d baseline_unavailable_logged=%d",
g_fail ? "FAIL" : "PASS", g_pass + g_fail, base_unavail);
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
return g_fail ? 4 : 0;
}
}