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>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ff0aee7f47
commit
599e1da5ce
@@ -8,6 +8,8 @@ ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Build artifacts
|
||||
/readoor-test/
|
||||
/test-results/
|
||||
build/
|
||||
bin/
|
||||
dist/
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# iOSGuard - 企业级 iOS 加固与安全防护系统
|
||||
|
||||
> **反 HOOK 正向验证(2026-11-12)**:step11 真机 HOOK 正向验证完成,11/11 用例通过:真实 GOT 重绑定(fishhook 同款)、蹦床序言(B/LDR+BR)、frida 特征线程名、Documents 注入 dylib、ObjC 方法 IMP 基线替换在 iPhone 16 Plus(iOS 27.2,非越狱)全部命中对应 reason;DYLD_INSERT_LIBRARIES 真实 dyld 注入双命中 202+200。同轮新增调试器跟踪探针(reason=300)与 ObjC IMP 基线探针(reason=110)并接入聚合扫描。宿主测试 62 项通过。见 [真机 HOOK 正向验证](docs/17_DEVICE_HOOK_POSITIVE_VERIFICATION.md)。同日完成 readoor-test Swift 策略层整改(110/300 分级、越狱终止改经策略统一处置、debuggerDetected 接入探针证据)与登录/VIP/激活敏感入口门禁推广,构建通过;随后完成业务 App 内 C 探针副本同步(IGObjCBaseline 入副本与聚合接线,IGSyscall/IGAntiDebug 按合规物理排除)、Swift 侧 ObjC 基线登记(模块前缀解析,2/2 登记)与真机双向业务验证:干净启动零误报,DYLD_INSERT 真实注入双命中 202+200 判「加固锁定」且进程按白名单存活(证据 docs/evidence/20261112-readoor-inject-console.log)。强制模式各入口按钮级拦截回归仍待执行。
|
||||
|
||||
> **观察包进度(2026-11-11)**:SSZipArchive 动态绑定保护试点已在指定词书真机解压中命中四个文件函数,874 次转发无拒绝,9 个输出文件的聚合摘要与同构建基线一致,页面、正常缓存、返回重进及前后台恢复通过。59 项宿主/工具测试通过;真机攻击正向验证尚未完成。PDF 修复、完整业务回归和报告复测继续暂缓。见 [SSZipArchive 保护试点](docs/16_SSZIPARCHIVE_FRAMEWORK_GUARD_PILOT.md)。
|
||||
|
||||
> **当前状态(2026-11-10)**:已完成 ZipZap `write/close` 三层防护试点:链接后定点改写、运行时解析与间接调用、Defender 调度完整性检查。`readoor31` Release 构建、44 项自动化测试及 8 项独立真机诊断通过,本轮两处改写后整包直接调用为 558→556。详见 [三层试点与证据](docs/14_ZIPZAP_RUNTIME_DISPATCH_PILOT.md)。前一轮 v2.199.0 IPA 的 28 项测试与 878→0 仍保留为[独立基线](docs/13_REPRODUCIBLE_BASELINE.md),两轮产物不同。**尚未完成完整 App 真机业务回归和 V4.6.6 复测**;不能宣称报告问题全部解决。下文能力表仍属于规划,不代表各项均已实现或验证。
|
||||
>
|
||||
> **当前主线**:面向 iOS App 反 Hook 与安全加固,以 readoor 的 ECNUP 外语安全报告为首个验收案例。报告分析、源码核查、实施顺序及复测标准见 [readoor 漏洞报告分析与加固实施方案](docs/05_READOOR_SECURITY_REMEDIATION_PLAN.md)。当前优先级以该方案为准;既有文档中的审核差异化、VMP、元数据重构等内容保留为远期研究。
|
||||
|
||||
[](https://developer.apple.com/ios/)
|
||||
[]()
|
||||
[]()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* IGDefender.c — 运行时防护聚合入口。
|
||||
*
|
||||
* 一次性运行 anti_hook + 注入/Frida 全部探针,证据统一经 sink 上报;不做任何处置。
|
||||
* 典型用法(观察模式):App 启动 / 回前台 / 关键操作前调用 ig_defender_scan,
|
||||
* 由上层策略根据 reason 组合决定是否限制功能——本库绝不 exit。
|
||||
*/
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
#include "anti_debug/IGAntiDebug.h"
|
||||
#include "anti_jailbreak/IGAntiJailbreak.h"
|
||||
#include "dispatch/IGDispatch.h"
|
||||
|
||||
int ig_defender_scan(const char *bundle_path, int probe_port,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
hits += ig_dispatch_check(sink, ctx);
|
||||
hits += ig_anti_hook_check_default(sink, ctx);
|
||||
hits += ig_objc_baseline_check(sink, ctx);
|
||||
hits += ig_anti_inject_check(bundle_path, sink, ctx);
|
||||
hits += ig_anti_frida_check(probe_port, sink, ctx);
|
||||
hits += ig_anti_debug_check(sink, ctx);
|
||||
hits += ig_anti_jb_check(sink, ctx);
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* IGAntiDebug.c — 调试器跟踪探针实现。
|
||||
* 全部逻辑在 syscall 模块(ig_sys_is_debugged,直发 svc + P_TRACED),
|
||||
* 这里只做三态到 IGFinding 的映射与上报。
|
||||
*/
|
||||
#include "IGAntiDebug.h"
|
||||
#include "syscall/IGSyscall.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int ig_anti_debug_check(IGFindingSink sink, void *ctx) {
|
||||
int traced = ig_sys_is_debugged();
|
||||
if (traced == 1) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = IG_DETECTED;
|
||||
f.reason = IG_REASON_DEBUGGER_ATTACHED;
|
||||
snprintf(f.subject, sizeof(f.subject), "kinfo_proc.p_flag&P_TRACED");
|
||||
snprintf(f.evidence, sizeof(f.evidence), "直发 sysctl 检出进程被调试器跟踪");
|
||||
if (sink) sink(&f, ctx);
|
||||
return 1;
|
||||
}
|
||||
if (traced < 0) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = IG_UNAVAILABLE;
|
||||
f.reason = IG_REASON_DEBUGGER_ATTACHED;
|
||||
snprintf(f.subject, sizeof(f.subject), "kinfo_proc.p_flag&P_TRACED");
|
||||
snprintf(f.evidence, sizeof(f.evidence), "sysctl 查询失败,无法判定");
|
||||
if (sink) sink(&f, ctx);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* IGAntiDebug.h — 调试器跟踪探针(接入聚合扫描)。
|
||||
*
|
||||
* 复用 syscall 模块的 ig_sys_is_debugged():直发 sysctl 读 kinfo_proc 的
|
||||
* P_TRACED 位(公开 API 语义,docs/12 已在 lldb 下实测命中),此前该能力
|
||||
* 已实现但未进入 ig_defender_scan 聚合,策略层无从消费——本模块补上接线。
|
||||
* 三态映射:1 → DETECTED(300),0 → clear,-1 → UNAVAILABLE(300)。
|
||||
*/
|
||||
#ifndef IG_ANTI_DEBUG_H
|
||||
#define IG_ANTI_DEBUG_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 调试器跟踪检测:只采集证据不处置(绝不自行 ptrace/exit)。返回 DETECTED 条数。 */
|
||||
int ig_anti_debug_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_DEBUG_H */
|
||||
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* IGAntiInject.c — 代码注入与 Frida 运行时检测实现。
|
||||
*
|
||||
* 全部公开 API:<mach-o/dyld.h>(镜像枚举)、getenv(dyld 环境变量)、
|
||||
* task_threads + thread_info(THREAD_EXTENDED_INFO)(线程名)、BSD socket(端口弱探测)。
|
||||
*
|
||||
* 边界:
|
||||
* - 镜像特征按文件名子串匹配,越狱/注入框架会更名规避——命中是强证据,未命中不等于干净。
|
||||
* - 端口探测仅弱信号(docs/05:不以单一端口判定);默认不启用,需显式传 probe_port。
|
||||
* - 线程名依赖目标进程把 frida 线程命名为已知值,新版本可能改名——同为组合证据之一。
|
||||
*/
|
||||
#include "IGAntiInject.h"
|
||||
#include "IGInline.h" /* ig_strstr/ig_strcmp/ig_strncmp/ig_strlen:抹除探针自身对 libc 匹配函数的依赖 */
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <strings.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <crt_externs.h> /* _NSGetEnviron:手工遍历环境表,替代可被 hook 的 getenv */
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/thread_act.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/time.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
/*
|
||||
* 经 _NSGetEnviron 手工遍历环境表取变量,规避对 getenv 的 hook/特征。
|
||||
* 关键:攻击者只需 hook getenv 让其对 "DYLD_INSERT_LIBRARIES" 返回 NULL,
|
||||
* 即可让下方第 3 步「插入库」检测彻底失明;本函数不经 libc getenv,关闭该盲点。
|
||||
* 仅用 ig_* 内联原语比较,不引入新的可 hook 导入符号。
|
||||
*/
|
||||
static const char *ig_local_getenv(const char *name) {
|
||||
char ***envp = _NSGetEnviron();
|
||||
if (!name || !envp || !*envp) return NULL;
|
||||
size_t nlen = ig_strlen(name);
|
||||
for (char **e = *envp; *e; ++e) {
|
||||
const char *entry = *e;
|
||||
if (ig_strncmp(entry, name, nlen) == 0 && entry[nlen] == '=') {
|
||||
return entry + nlen + 1;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* 已知注入 / 调试 / 越狱增强框架的镜像名子串(小写)。 */
|
||||
static const char *const kInjectSignatures[] = {
|
||||
"frida", "gadget", "cynject", "cycript", "libcycript",
|
||||
"substrate", "substitute", "libsubstrate", "tweakinject",
|
||||
"rocketbootstrap", "reveal", "flexloader", "libhooker",
|
||||
"shadowhook", "dobby", "fishhook",
|
||||
};
|
||||
|
||||
/* 已知 frida 线程名。 */
|
||||
static const char *const kFridaThreads[] = {
|
||||
"gum-js-loop", "gmain", "gdbus", "pool-frida", "pool-spawner", "linjector",
|
||||
};
|
||||
|
||||
static void ig_emit2(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
if (subject) strncpy(f.subject, subject, sizeof(f.subject)-1);
|
||||
if (evidence) strncpy(f.evidence, evidence, sizeof(f.evidence)-1);
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
/* 小写化到缓冲区,便于大小写无关子串匹配。 */
|
||||
static void ig_lower(const char *src, char *dst, size_t cap) {
|
||||
size_t i = 0;
|
||||
for (; src && src[i] && i + 1 < cap; ++i) {
|
||||
char c = src[i];
|
||||
dst[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
|
||||
}
|
||||
dst[i] = '\0';
|
||||
}
|
||||
|
||||
static int ig_is_system_path2(const char *path) {
|
||||
if (!path) return 0;
|
||||
return ig_strncmp(path, "/usr/lib/", 9) == 0 ||
|
||||
ig_strncmp(path, "/System/", 8) == 0 ||
|
||||
/* iOS 16+ 系统库经 Cryptex 挂载(/private/preboot/Cryptexes/OS/...),系统自身非注入。 */
|
||||
ig_strncmp(path, "/private/preboot/Cryptexes/", 27) == 0;
|
||||
}
|
||||
|
||||
int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) {
|
||||
int hits = 0, stop = 0;
|
||||
|
||||
/* 1+2. 镜像扫描。 */
|
||||
uint32_t imgc = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < imgc && !stop; ++i) {
|
||||
const char *name = _dyld_get_image_name(i);
|
||||
if (!name) continue;
|
||||
/* Apple 系统镜像(/System、/usr/lib、Cryptex)只读且 Apple 签名,永不作为注入证据先行跳过:
|
||||
* 否则子串匹配会把 Apple 私有框架(如 RevealCore 命中 "reveal")误判为注入;
|
||||
* Xcode 调试还会加载 GPUToolsCapture/libViewDebuggerSupport 等系统库。
|
||||
* 真正的 frida/substrate/gadget 装在 Bundle 内或越狱路径(/Library、/var),不在此列。 */
|
||||
if (ig_is_system_path2(name)) continue;
|
||||
|
||||
char low[1024];
|
||||
ig_lower(name, low, sizeof(low));
|
||||
|
||||
int matched = 0;
|
||||
for (size_t s = 0; s < sizeof(kInjectSignatures)/sizeof(kInjectSignatures[0]); ++s) {
|
||||
if (ig_strstr(low, kInjectSignatures[s])) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "镜像=%s 命中特征=%s", name, kInjectSignatures[s]);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_INJECTED_IMAGE, name, ev);
|
||||
matched = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) continue;
|
||||
|
||||
/* 非系统、非特征命中:若在 Bundle 外则作为弱信号上报。 */
|
||||
if (bundle_path && ig_strncmp(name, bundle_path, ig_strlen(bundle_path)) != 0) {
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_FOREIGN_IMAGE, name,
|
||||
"Bundle 外非系统镜像(弱信号,需结合其它证据)");
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. DYLD_INSERT_LIBRARIES 逐条解析。 */
|
||||
const char *dyld = ig_local_getenv("DYLD_INSERT_LIBRARIES");
|
||||
if (dyld && dyld[0] && !stop) {
|
||||
char buf[4096];
|
||||
strncpy(buf, dyld, sizeof(buf)-1); buf[sizeof(buf)-1] = '\0';
|
||||
char *save = NULL;
|
||||
for (char *tok = strtok_r(buf, ":", &save); tok && !stop;
|
||||
tok = strtok_r(NULL, ":", &save)) {
|
||||
int in_bundle = (bundle_path && ig_strncmp(tok, bundle_path, ig_strlen(bundle_path)) == 0);
|
||||
/* 排除 Apple 系统路径条目:Xcode 调试经 DYLD_INSERT_LIBRARIES 注入
|
||||
* /usr/lib/libViewDebuggerSupport.dylib、/System/.../GPUToolsCapture 等,非恶意注入。
|
||||
* 越狱 frida/substrate 的插入库位于 Bundle 内或非系统路径,仍会命中。 */
|
||||
if (!in_bundle && !ig_is_system_path2(tok)) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "DYLD_INSERT_LIBRARIES 条目=%s(Bundle 外)", tok);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_DYLD_INSERT, tok, ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
/* 遍历本进程线程,匹配 frida 线程名。 */
|
||||
static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits) {
|
||||
thread_act_array_t threads;
|
||||
mach_msg_type_number_t count = 0;
|
||||
if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) {
|
||||
ig_emit2(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_FRIDA_THREAD,
|
||||
"task_threads", "无法枚举线程");
|
||||
return;
|
||||
}
|
||||
for (mach_msg_type_number_t i = 0; i < count; ++i) {
|
||||
thread_extended_info_data_t info;
|
||||
mach_msg_type_number_t icount = THREAD_EXTENDED_INFO_COUNT;
|
||||
if (thread_info(threads[i], THREAD_EXTENDED_INFO,
|
||||
(thread_info_t)&info, &icount) != KERN_SUCCESS) continue;
|
||||
if (info.pth_name[0] == '\0') continue;
|
||||
for (size_t t = 0; t < sizeof(kFridaThreads)/sizeof(kFridaThreads[0]); ++t) {
|
||||
if (ig_strcmp(info.pth_name, kFridaThreads[t]) == 0) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "线程名=%s 命中 frida 特征", info.pth_name);
|
||||
ig_emit2(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_FRIDA_THREAD,
|
||||
info.pth_name, ev);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (*stop) break;
|
||||
}
|
||||
/* 回收端口。 */
|
||||
for (mach_msg_type_number_t i = 0; i < count; ++i) {
|
||||
mach_port_deallocate(mach_task_self(), threads[i]);
|
||||
}
|
||||
vm_deallocate(mach_task_self(), (vm_address_t)threads, count * sizeof(thread_act_t));
|
||||
}
|
||||
|
||||
/* 非阻塞 connect 到 127.0.0.1:port,可连通即弱信号。 */
|
||||
static int ig_port_open(int port) {
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return 0;
|
||||
fcntl(fd, F_SETFL, O_NONBLOCK);
|
||||
struct sockaddr_in sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sin_family = AF_INET;
|
||||
sa.sin_port = htons((uint16_t)port);
|
||||
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
int rc = connect(fd, (struct sockaddr *)&sa, sizeof(sa));
|
||||
int open = 0;
|
||||
if (rc == 0) {
|
||||
open = 1;
|
||||
} else if (errno == EINPROGRESS) {
|
||||
fd_set wset; FD_ZERO(&wset); FD_SET(fd, &wset);
|
||||
struct timeval tv = { .tv_sec = 0, .tv_usec = 200000 }; /* 200ms 预算 */
|
||||
if (select(fd + 1, NULL, &wset, NULL, &tv) > 0) {
|
||||
int err = 0; socklen_t len = sizeof(err);
|
||||
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
|
||||
open = (err == 0);
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return open;
|
||||
}
|
||||
|
||||
int ig_anti_frida_check(int probe_port, IGFindingSink sink, void *ctx) {
|
||||
int hits = 0, stop = 0;
|
||||
ig_scan_threads(sink, ctx, &stop, &hits);
|
||||
if (probe_port && !stop) {
|
||||
if (ig_port_open(probe_port)) {
|
||||
char ev[128];
|
||||
snprintf(ev, sizeof(ev), "127.0.0.1:%d 可连接(弱信号)", probe_port);
|
||||
char sub[32]; snprintf(sub, sizeof(sub), "port:%d", probe_port);
|
||||
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_FRIDA_PORT, sub, ev);
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* IGAntiInject.h — 代码注入与 Frida 运行时检测探针。
|
||||
*
|
||||
* 覆盖(docs/05 §5.C「镜像/白名单」「已知工具线索」+ §4 P1 DYLD 逐项解析):
|
||||
* 1. 镜像扫描:已加载镜像匹配已知注入/调试框架特征(substrate/frida/cycript/reveal…)→ 强证据。
|
||||
* 2. Bundle 外非系统镜像:弱信号(可能是合法 dylib),作为组合证据上报。
|
||||
* 3. DYLD_INSERT_LIBRARIES:逐条解析(非整串前缀),任何条目指向 Bundle 外路径即上报。
|
||||
* 4. Frida 运行时:线程名特征(gum-js-loop/gmain/pool-frida…)+ 默认端口(弱信号)。
|
||||
*
|
||||
* 只采集证据,不处置。单一端口/名称命中不作独立判定,交上层组合。
|
||||
*/
|
||||
#ifndef IG_ANTI_INJECT_H
|
||||
#define IG_ANTI_INJECT_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 注入检测:镜像特征扫描 + Bundle 外镜像 + DYLD_INSERT_LIBRARIES 逐项解析。
|
||||
* bundle_path:App 主 bundle 路径(.app 目录);用于判定镜像/插入库是否在 Bundle 内。
|
||||
* 传 NULL 则跳过「Bundle 外」判定,仅做特征匹配与 dyld env。
|
||||
* 返回 DETECTED 条数。
|
||||
*/
|
||||
int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* Frida 运行时检测:线程名特征 + 默认端口探测(弱信号)。
|
||||
* probe_port 非 0 时才做端口连接探测(默认 27042);0 表示只做线程名扫描。
|
||||
* 返回 DETECTED 条数。
|
||||
*/
|
||||
int ig_anti_frida_check(int probe_port, IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_INJECT_H */
|
||||
@@ -0,0 +1,269 @@
|
||||
/*
|
||||
* IGAntiHook.c — 关键函数 HOOK 完整性探针实现。
|
||||
*
|
||||
* 全部基于公开 API:<dlfcn.h>(dlsym/dladdr)、<mach-o/dyld.h>(镜像枚举)、
|
||||
* <mach-o/loader.h>/<nlist.h>(运行时解析自身镜像的 GOT 槽,fishhook 同款走法,用于「校验」而非改写)。
|
||||
*
|
||||
* 边界(如实声明,unavailable 不等于安全):
|
||||
* - 仅支持 arm64 / x86_64(LP64)。非 64 位镜像跳过。
|
||||
* - arm64e:__auth_got 槽为带签名指针,比较前用 ptrauth_strip 去签名;若工具链无 ptrauth,
|
||||
* 对认证槽的判定标记为 unavailable,不强行比较。
|
||||
* - chained fixups:运行时 dyld 绑定完成后,__got 槽持最终(slide 后)地址,本探针读到的即该值;
|
||||
* 未绑定/惰性未触发的槽会与 trusted 不等——仅对非惰性 __got(S_NON_LAZY_SYMBOL_POINTERS)判 rebind,
|
||||
* 惰性槽(__la_symbol_ptr)首次调用前可能仍指向 helper,故不判为重绑定,只在 provenance/inline 层兜底。
|
||||
*/
|
||||
#include "IGAntiHook.h"
|
||||
#include "IGInline.h" /* ig_strcmp/ig_strncmp/ig_strlen:抹除探针自身对 libc 匹配函数的依赖 */
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <dlfcn.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <mach/mach.h>
|
||||
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
# include <ptrauth.h>
|
||||
# define IG_HAS_PTRAUTH 1
|
||||
# endif
|
||||
#endif
|
||||
#ifndef IG_HAS_PTRAUTH
|
||||
# define IG_HAS_PTRAUTH 0
|
||||
#endif
|
||||
|
||||
/* 报告命中的 12 个关键符号(不带下划线)。 */
|
||||
static const char *const kIGDefaultSymbols[] = {
|
||||
"fopen", "dlopen", "dlsym", "write", "read", "open",
|
||||
"close", "exit", "fork", "syscall", "unlink", "getpid",
|
||||
};
|
||||
|
||||
/* ---- 工具:系统提供方路径白名单 ---- */
|
||||
|
||||
/* dli_fname 是否落在系统镜像路径(含 dyld 共享缓存里的系统 dylib)。 */
|
||||
static int ig_is_system_path(const char *path) {
|
||||
if (!path) return 0;
|
||||
static const char *const prefixes[] = {
|
||||
"/usr/lib/", "/System/", "/usr/lib/system/",
|
||||
/* iOS 16+ 系统库经 Cryptex 挂载,dladdr 报此前缀(非越狱,系统自身)。 */
|
||||
"/private/preboot/Cryptexes/",
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(prefixes)/sizeof(prefixes[0]); ++i) {
|
||||
if (ig_strncmp(path, prefixes[i], ig_strlen(prefixes[i])) == 0) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void ig_emit(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
if (subject) { strncpy(f.subject, subject, sizeof(f.subject)-1); }
|
||||
if (evidence) { strncpy(f.evidence, evidence, sizeof(f.evidence)-1); }
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
/* 去 PAC(arm64e 认证指针);无 ptrauth 时原样返回。 */
|
||||
static const void *ig_strip(const void *p) {
|
||||
#if IG_HAS_PTRAUTH
|
||||
return ptrauth_strip(p, ptrauth_key_asia);
|
||||
#else
|
||||
return p;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---- 1. 符号提供方 ---- */
|
||||
/* trusted = dlsym(RTLD_DEFAULT,name);其宿主镜像若非系统路径,说明被 interpose/注入抢占。 */
|
||||
static void *ig_check_provenance(const char *name, IGFindingSink sink, void *ctx,
|
||||
int *stop, int *hits) {
|
||||
void *addr = dlsym(RTLD_DEFAULT, name);
|
||||
if (!addr) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_SYMBOL_UNRESOLVED,
|
||||
name, "dlsym(RTLD_DEFAULT) 返回 NULL");
|
||||
return NULL;
|
||||
}
|
||||
Dl_info info;
|
||||
if (!dladdr(addr, &info) || !info.dli_fname) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name, "无法确认符号提供方");
|
||||
return NULL;
|
||||
}
|
||||
if (!ig_is_system_path(info.dli_fname)) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "解析地址 %p 提供方=%s(非系统路径)",
|
||||
addr, info.dli_fname ? info.dli_fname : "?");
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE, name, ev);
|
||||
}
|
||||
return addr;
|
||||
}
|
||||
|
||||
/* ---- 2. inline hook:序言首指令 ---- */
|
||||
int ig_arm64_suspicious_prologue(uint32_t first, uint32_t second) {
|
||||
if ((first & 0xfc000000u)==0x14000000u) return 1;
|
||||
uint32_t rt=first & 31u, rn=(second>>5)&31u;
|
||||
return (first & 0xff000000u)==0x58000000u && (rt==16 || rt==17)
|
||||
&& (second & 0xfffffc1fu)==0xd61f0000u && rn==rt;
|
||||
}
|
||||
/* arm64:首指令为无条件 B,或 (LDR-literal → x16/x17) + (BR x16/x17) 蹦床,判为 inline hook。 */
|
||||
static IGStatus ig_check_prologue(const char *name, void *addr, IGFindingSink sink, void *ctx,
|
||||
int *stop, int *hits) {
|
||||
#if defined(__arm64__) || defined(__aarch64__)
|
||||
uint32_t code[2];
|
||||
vm_size_t copied=0;
|
||||
if (vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr),
|
||||
sizeof(code), (vm_address_t)code, &copied) != KERN_SUCCESS || copied!=sizeof(code)) {
|
||||
ig_emit(sink, ctx, stop, hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name, "无法读取函数代码");
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
const uint32_t *ins = code;
|
||||
uint32_t w0 = ins[0];
|
||||
uint32_t w1 = ins[1];
|
||||
int hook = ig_arm64_suspicious_prologue(w0,w1);
|
||||
const char *kind = "首指令 B 或 LDR literal + 同寄存器 BR 蹦床";
|
||||
if (hook) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "%s @%p 指令[%08x %08x]", kind, addr, w0, w1);
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_INLINE_HOOK, name, ev);
|
||||
return IG_DETECTED;
|
||||
}
|
||||
#else
|
||||
(void)name; (void)addr; (void)sink; (void)ctx; (void)stop; (void)hits;
|
||||
#endif
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
/* ---- 3. GOT 重绑定:扫本进程非系统镜像的非惰性符号指针槽 ---- */
|
||||
/* trusted_map:name→trusted addr 的平行数组。对每个镜像的 __got 槽,若其绑定符号在集合内
|
||||
* 且当前值去 PAC 后既不等于 trusted、宿主又非系统路径,则判 GOT 重绑定。 */
|
||||
static void ig_check_got_one_image(uint32_t img_index,
|
||||
const char *const *names, void *const *trusted, size_t count,
|
||||
IGFindingSink sink, void *ctx, int *stop, int *hits) {
|
||||
const struct mach_header_64 *mh =
|
||||
(const struct mach_header_64 *)_dyld_get_image_header(img_index);
|
||||
if (!mh || mh->magic != MH_MAGIC_64) return;
|
||||
const char *img_path = _dyld_get_image_name(img_index);
|
||||
if (ig_is_system_path(img_path)) return; /* 只查自有镜像(app/嵌入 framework) */
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(img_index);
|
||||
|
||||
/* 先定位 __LINKEDIT、LC_SYMTAB、LC_DYSYMTAB。 */
|
||||
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) {
|
||||
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 (ig_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;
|
||||
}
|
||||
cmd += lc->cmdsize;
|
||||
}
|
||||
if (!linkedit || !symtab || !dysymtab) return;
|
||||
|
||||
uintptr_t linkedit_base = (uintptr_t)slide + linkedit->vmaddr - linkedit->fileoff;
|
||||
const struct nlist_64 *symtab_list = (const struct nlist_64 *)(linkedit_base + symtab->symoff);
|
||||
const char *strtab = (const char *)(linkedit_base + symtab->stroff);
|
||||
const uint32_t *indirect = (const uint32_t *)(linkedit_base + dysymtab->indirectsymoff);
|
||||
|
||||
/* 遍历各 section,挑非惰性符号指针段(__got / __auth_got)。 */
|
||||
cmd = (const uint8_t *)(mh + 1);
|
||||
for (uint32_t i = 0; i < mh->ncmds; ++i) {
|
||||
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;
|
||||
const struct section_64 *sect = (const struct section_64 *)(seg + 1);
|
||||
for (uint32_t s = 0; s < seg->nsects; ++s) {
|
||||
uint32_t type = sect[s].flags & SECTION_TYPE;
|
||||
if (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 symi = idxs[k];
|
||||
if (symi == INDIRECT_SYMBOL_ABS || symi == INDIRECT_SYMBOL_LOCAL) continue;
|
||||
const char *sym = strtab + symtab_list[symi].n_un.n_strx;
|
||||
if (sym[0] != '_') continue;
|
||||
const char *bare = sym + 1;
|
||||
for (size_t m = 0; m < count; ++m) {
|
||||
if (ig_strcmp(bare, names[m]) != 0) continue;
|
||||
const void *cur = ig_strip(slots[k]);
|
||||
if (!trusted[m] || cur == trusted[m]) break; /* 一致=正常转发 */
|
||||
Dl_info di;
|
||||
const char *prov = (dladdr((void*)cur, &di) ? di.dli_fname : NULL);
|
||||
if (prov && ig_is_system_path(prov)) break; /* 仍指向系统实现,放行 */
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev),
|
||||
"镜像=%s 槽@%p 当前=%p(提供方=%s) 期望=%p",
|
||||
img_path ? img_path : "?", (void*)&slots[k], (void*)cur,
|
||||
prov ? prov : "?", trusted[m]);
|
||||
ig_emit(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_GOT_REBIND, sym, ev);
|
||||
break;
|
||||
}
|
||||
if (*stop) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
cmd += lc->cmdsize;
|
||||
}
|
||||
}
|
||||
|
||||
int ig_anti_hook_check(const char *const *names, size_t count,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
if (!names || count == 0) return 0;
|
||||
int hits = 0, stop = 0;
|
||||
|
||||
/* 逐符号:provenance + inline-hook,并收集 trusted 地址表供 GOT 检查复用。 */
|
||||
void *trusted[64];
|
||||
size_t n = count < 64 ? count : 64;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
void *addr = ig_check_provenance(names[i], sink, ctx, &stop, &hits);
|
||||
trusted[i] = addr;
|
||||
if (addr) ig_check_prologue(names[i], addr, sink, ctx, &stop, &hits);
|
||||
if (stop) return hits;
|
||||
}
|
||||
|
||||
/* GOT 重绑定:遍历全部镜像,内部只查非系统镜像。 */
|
||||
uint32_t imgc = _dyld_image_count();
|
||||
for (uint32_t i = 0; i < imgc && !stop; ++i) {
|
||||
ig_check_got_one_image(i, names, trusted, n, sink, ctx, &stop, &hits);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
IGStatus ig_verify_function(void *addr, const char *name, IGFindingSink sink, void *ctx) {
|
||||
if (!addr) return IG_UNAVAILABLE;
|
||||
int hits = 0, stop = 0;
|
||||
/* provenance:地址提供方须在系统路径白名单内。 */
|
||||
Dl_info info;
|
||||
if (!dladdr(addr, &info) || !info.dli_fname) {
|
||||
ig_emit(sink, ctx, &stop, &hits, IG_UNAVAILABLE, IG_REASON_VERIFICATION_UNAVAILABLE,
|
||||
name ? name : "?", "无法确认函数提供方");
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (!ig_is_system_path(info.dli_fname)) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "解析地址 %p 提供方=%s(非系统路径)",
|
||||
addr, info.dli_fname ? info.dli_fname : "?");
|
||||
ig_emit(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE,
|
||||
name ? name : "?", ev);
|
||||
return IG_DETECTED;
|
||||
}
|
||||
/* inline-hook 序言。 */
|
||||
return ig_check_prologue(name ? name : "?", addr, sink, ctx, &stop, &hits);
|
||||
}
|
||||
|
||||
int ig_anti_hook_check_default(IGFindingSink sink, void *ctx) {
|
||||
return ig_anti_hook_check(kIGDefaultSymbols,
|
||||
sizeof(kIGDefaultSymbols)/sizeof(kIGDefaultSymbols[0]),
|
||||
sink, ctx);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* IGAntiHook.h — 关键函数 HOOK 完整性探针。
|
||||
*
|
||||
* 覆盖三类 HOOK 形态(docs/05 §5.C「GOT/符号地址」「关键自有代码完整性」):
|
||||
* 1. 符号提供方异常:dlsym 解析到非系统镜像(dyld interpose / 注入 dylib 抢占定义)。
|
||||
* 2. inline hook:关键函数序言首指令被改写为无条件跳转或 LDR+BR x16 蹦床。
|
||||
* 3. GOT 重绑定:本进程镜像的 __got/__la_symbol_ptr 槽被 fishhook 类手法改指到非系统地址。
|
||||
*
|
||||
* 只采集证据,不处置。PAC/chained-fixups/arm64e 的边界见 .c 注释。
|
||||
*/
|
||||
#ifndef IG_ANTI_HOOK_H
|
||||
#define IG_ANTI_HOOK_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* 校验一批关键 libc/系统函数的运行时完整性。
|
||||
* names: 函数名数组(不带前导下划线,如 "write"/"read"/"dlsym")。
|
||||
* count: 数组长度。
|
||||
* 对每个符号依次做 provenance / inline-hook / GOT-rebind 检查,命中即经 sink 上报。
|
||||
* 返回 DETECTED 条数(0 表示本轮全部 clear 或仅 unavailable)。
|
||||
*/
|
||||
int ig_anti_hook_check(const char *const *names, size_t count,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
/* 便捷入口:用内置关键符号集(报告命中的 12 个)执行 ig_anti_hook_check。 */
|
||||
int ig_anti_hook_check_default(IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 单点「调用前校验」:对一个**已解析**的函数地址做 provenance(dladdr 提供方须系统路径)
|
||||
* + inline-hook 序言检查。供 IGResolve 在放行解析结果前复用。
|
||||
* 命中经 sink 上报(可传 NULL 只取返回值)。
|
||||
* 返回 IG_CLEAR=干净可用 / IG_DETECTED=疑被挟持应拒用 / IG_UNAVAILABLE=addr 为空无法判定。
|
||||
*/
|
||||
IGStatus ig_verify_function(void *addr, const char *name, IGFindingSink sink, void *ctx);
|
||||
|
||||
/* ARM64 序言形态分类,可独立测试;命中只是一条证据,不覆盖所有 Hook。 */
|
||||
int ig_arm64_suspicious_prologue(uint32_t first, uint32_t second);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_HOOK_H */
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* IGObjCBaseline.c — ObjC 关键方法 IMP 基线探针实现。
|
||||
*
|
||||
* 全部公开 API:objc_getClass / sel_registerName / class_getMethodImplementation
|
||||
* (objc/runtime.h,纯 C)、dladdr(提供方)、vm_read_overwrite(代码前缀)。
|
||||
* method_getImplementation 返回"当前会被实际调用的实现"(已解析 swizzle),
|
||||
* 与基线不一致即说明方法被交换/替换——这正是要抓的形态。
|
||||
*
|
||||
* 线程模型:capture 由策略层在确定时点(如首帧后)调用一次;check 在扫描时点调用。
|
||||
* 两者并发属策略层误用,本模块不加锁(保持零依赖、可嵌入任意 target)。
|
||||
*/
|
||||
#include "IGObjCBaseline.h"
|
||||
#include "IGInline.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <dlfcn.h>
|
||||
#include <mach/mach.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
|
||||
|
||||
#define IG_OBJC_MAX_WATCH 64
|
||||
#define IG_PREFIX_BYTES 16
|
||||
|
||||
typedef struct {
|
||||
const char *cls; /* 登记时的类名 */
|
||||
const char *sel; /* 登记时的选择子 */
|
||||
void *imp; /* 基线 IMP(去 PAC 后) */
|
||||
char prov[192]; /* 基线 IMP 提供方镜像路径 */
|
||||
unsigned char prefix[IG_PREFIX_BYTES];
|
||||
int have_prefix;
|
||||
} IGObjCSlot;
|
||||
|
||||
static IGObjCSlot g_slots[IG_OBJC_MAX_WATCH];
|
||||
static size_t g_nslots;
|
||||
|
||||
static const void *ig_strip(const void *p) {
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(ptrauth_calls)
|
||||
return ptrauth_strip(p, ptrauth_key_asia);
|
||||
# else
|
||||
return p;
|
||||
# endif
|
||||
#else
|
||||
return p;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void ig_emit_objc(IGFindingSink sink, void *ctx, int *stop, int *hits,
|
||||
IGStatus st, const char *subject, const char *evidence) {
|
||||
if (*stop) return;
|
||||
IGFinding f;
|
||||
memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = IG_REASON_OBJC_IMP_CHANGED;
|
||||
strncpy(f.subject, subject, sizeof(f.subject) - 1);
|
||||
strncpy(f.evidence, evidence, sizeof(f.evidence) - 1);
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink && sink(&f, ctx) != 0) *stop = 1;
|
||||
}
|
||||
|
||||
/* 读取函数前 N 字节;失败返回 0(调用方按 unavailable 语义处理)。 */
|
||||
static int ig_read_prefix(const void *addr, unsigned char *out) {
|
||||
vm_size_t copied = 0;
|
||||
if (vm_read_overwrite(mach_task_self(), (vm_address_t)ig_strip(addr),
|
||||
IG_PREFIX_BYTES, (vm_address_t)out, &copied) != KERN_SUCCESS
|
||||
|| copied != IG_PREFIX_BYTES)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count) {
|
||||
g_nslots = 0;
|
||||
if (!watches) return 0;
|
||||
size_t ok = 0;
|
||||
for (size_t i = 0; i < count && g_nslots < IG_OBJC_MAX_WATCH; ++i) {
|
||||
if (!watches[i].class_name || !watches[i].selector) continue;
|
||||
Class c = objc_getClass(watches[i].class_name);
|
||||
if (!c) continue;
|
||||
Method m = class_getInstanceMethod(c, sel_registerName(watches[i].selector));
|
||||
if (!m) continue; /* 类存在但方法不可解析:不登记(check 语义与登记时一致) */
|
||||
IMP imp = method_getImplementation(m);
|
||||
if (!imp) continue;
|
||||
IGObjCSlot *slot = &g_slots[g_nslots++];
|
||||
slot->cls = watches[i].class_name;
|
||||
slot->sel = watches[i].selector;
|
||||
slot->imp = (void *)imp;
|
||||
slot->prov[0] = '\0';
|
||||
Dl_info info;
|
||||
if (dladdr((void *)imp, &info) && info.dli_fname)
|
||||
strncpy(slot->prov, info.dli_fname, sizeof(slot->prov) - 1);
|
||||
slot->have_prefix = ig_read_prefix((void *)imp, slot->prefix);
|
||||
++ok;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
int ig_objc_baseline_check(IGFindingSink sink, void *ctx) {
|
||||
if (g_nslots == 0) return 0; /* 未接入:clear no-op */
|
||||
int hits = 0, stop = 0;
|
||||
char subject[192], ev[256];
|
||||
for (size_t i = 0; i < g_nslots && !stop; ++i) {
|
||||
const IGObjCSlot *b = &g_slots[i];
|
||||
snprintf(subject, sizeof(subject), "-[%s %s]", b->cls, b->sel);
|
||||
Class c = objc_getClass(b->cls);
|
||||
if (!c) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
"基线登记后类不可解析(被卸载或运行时异常)");
|
||||
continue;
|
||||
}
|
||||
Method m = class_getInstanceMethod(c, sel_registerName(b->sel));
|
||||
if (!m || !method_getImplementation(m)) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
"方法实现不可解析(转发桩或已移除)");
|
||||
continue;
|
||||
}
|
||||
IMP imp = method_getImplementation(m);
|
||||
const void *cur = ig_strip(imp);
|
||||
if (cur != b->imp) {
|
||||
/* IMP 换人:典型 swizzle / class_replaceMethod / exchange。 */
|
||||
char cur_prov[192] = "?";
|
||||
Dl_info info;
|
||||
if (dladdr((void *)cur, &info) && info.dli_fname)
|
||||
strncpy(cur_prov, info.dli_fname, sizeof(cur_prov) - 1);
|
||||
snprintf(ev, sizeof(ev), "IMP %p(%s) → %p(%s)(实现被替换)",
|
||||
b->imp, b->prov[0] ? b->prov : "?", cur, cur_prov);
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, ev);
|
||||
continue;
|
||||
}
|
||||
/* IMP 未变但代码前缀变:实现函数体被 inline patch。 */
|
||||
if (b->have_prefix) {
|
||||
unsigned char now[IG_PREFIX_BYTES];
|
||||
if (!ig_read_prefix((void *)cur, now)) {
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_UNAVAILABLE, subject,
|
||||
"代码前缀不可读");
|
||||
continue;
|
||||
}
|
||||
if (memcmp(now, b->prefix, IG_PREFIX_BYTES) != 0) {
|
||||
snprintf(ev, sizeof(ev), "IMP %p 不变但代码前缀变化(函数体被改写)", cur);
|
||||
ig_emit_objc(sink, ctx, &stop, &hits, IG_DETECTED, subject, ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* IGObjCBaseline.h — ObjC 关键方法 IMP 基线探针(swizzle / 方法替换检测)。
|
||||
*
|
||||
* 背景(docs/05 §4 P1):IGAntiHook 只覆盖 C 符号层(序言/GOT/提供方),对 ObjC 层
|
||||
* method_exchangeImplementations / class_replaceMethod / method_setImplementation
|
||||
* 等劫持手段此前零覆盖。本模块由策略层指定关键方法清单,启动后采集 IMP 基线
|
||||
* (实现地址 + 提供方镜像 + 代码前缀),扫描时比对——IMP 换人或函数体被改即上报。
|
||||
*
|
||||
* 边界(如实声明):
|
||||
* - 合法 swizzle(统计/广告 SDK 常见)也会改变 IMP:本探针只给证据,是否处置由
|
||||
* 策略层决定;基线采集时机本身是策略选择(早采集会把业务自身的合法交换计入)。
|
||||
* - 只比对策略层显式登记的方法,不做全类扫(误报面不可控)。
|
||||
* - 纯 C 调 objc runtime API,不引入 ObjC 编译依赖;未 capture 过时 check 为 no-op。
|
||||
*/
|
||||
#ifndef IG_OBJC_BASELINE_H
|
||||
#define IG_OBJC_BASELINE_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 观察项:类名 + 选择子(如 { "RDOrderViewController", "payOrder" })。 */
|
||||
typedef struct {
|
||||
const char *class_name;
|
||||
const char *selector;
|
||||
} IGObjCWatch;
|
||||
|
||||
/*
|
||||
* 采集基线:对每个观察项记录当前 IMP 地址、提供方镜像路径与代码前缀 16 字节。
|
||||
* 幂等,重复调用以最后一次为准;count==0 清空基线。返回成功登记的条数
|
||||
* (类/选择子当时不可解析的条目不登记,check 时按 unavailable 上报)。
|
||||
*/
|
||||
size_t ig_objc_baseline_capture(const IGObjCWatch *watches, size_t count);
|
||||
|
||||
/*
|
||||
* 扫描:IMP 地址变化,或 IMP 相同但代码前缀变化 → DETECTED(110);
|
||||
* 类不可解析 / IMP 为转发桩 / 代码页不可读 → UNAVAILABLE(110)。
|
||||
* 未 capture 过时为 clear no-op(不惩罚未接入的调用方)。
|
||||
* 返回 DETECTED 条数;只采集证据不处置。
|
||||
*/
|
||||
int ig_objc_baseline_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_OBJC_BASELINE_H */
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* IGAntiJailbreak.c — 越狱检测探针实现。见 .h 的定位与边界。
|
||||
*
|
||||
* 全部文件探测经 IGSyscall 直发(access/open/close/unlink),不经 libc——规避 Shadow/Liberty
|
||||
* 等对 stat/access 的 hook。证据经 sink 上报,不做处置。
|
||||
*/
|
||||
#include "IGAntiJailbreak.h"
|
||||
#include "syscall/IGSyscall.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
/* access 的 amode:F_OK=0(仅测存在/可访问)。open 标志(BSD/Darwin 值)。 */
|
||||
#define IG_F_OK 0
|
||||
#define IG_O_RDWR 0x0002
|
||||
#define IG_O_CREAT 0x0200
|
||||
#define IG_O_EXCL 0x0800
|
||||
|
||||
/*
|
||||
* 内置 iOS 越狱特征(强信号)。沙盒内正常 App 对这些路径 access 应得 -ENOENT/-EPERM;
|
||||
* 能访问即越狱。rootless 越狱重点在 /var/jb。TODO:改为 IG_ENC XOR 混淆,勿明文驻留。
|
||||
*/
|
||||
static const char *const kIGJailbreakPaths[] = {
|
||||
"/var/jb", /* rootless 越狱根 */
|
||||
"/Applications/Cydia.app",
|
||||
"/Applications/Sileo.app",
|
||||
"/Applications/Zebra.app",
|
||||
"/usr/sbin/sshd",
|
||||
"/usr/bin/ssh",
|
||||
"/bin/bash",
|
||||
"/bin/sh",
|
||||
"/etc/apt",
|
||||
"/private/var/lib/apt",
|
||||
"/usr/lib/substrate",
|
||||
"/Library/MobileSubstrate/MobileSubstrate.dylib",
|
||||
"/usr/lib/TweakInject",
|
||||
};
|
||||
|
||||
static void ig_jb_emit(IGFindingSink sink, void *ctx, int *hits,
|
||||
IGStatus st, int reason, const char *subject, const char *evidence) {
|
||||
IGFinding f;
|
||||
__builtin_memset(&f, 0, sizeof(f));
|
||||
f.status = st;
|
||||
f.reason = reason;
|
||||
if (subject) snprintf(f.subject, sizeof(f.subject), "%s", subject);
|
||||
if (evidence) snprintf(f.evidence, sizeof(f.evidence), "%s", evidence);
|
||||
if (st == IG_DETECTED) (*hits)++;
|
||||
if (sink) sink(&f, ctx);
|
||||
}
|
||||
|
||||
int ig_anti_jb_check_paths(const char *const *paths, size_t count,
|
||||
const char *sandbox_probe_path,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
int hits = 0;
|
||||
|
||||
/* 1) 越狱特征文件:直发 access(path, F_OK)==0 即可访问。 */
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (!paths[i]) continue;
|
||||
if (ig_sys_access(paths[i], IG_F_OK) == 0) {
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "直发 access 可访问越狱特征:%s", paths[i]);
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_FILE, paths[i], ev);
|
||||
}
|
||||
}
|
||||
|
||||
/* 2) 沙盒逃逸:在沙盒外路径直发 open(O_CREAT|O_EXCL) 创建文件,成功=越狱强信号。 */
|
||||
if (sandbox_probe_path) {
|
||||
ig_sys_unlink(sandbox_probe_path); /* 清理上次残留(忽略错误) */
|
||||
int fd = ig_sys_open(sandbox_probe_path, IG_O_RDWR | IG_O_CREAT | IG_O_EXCL, 0600);
|
||||
if (fd >= 0) {
|
||||
ig_sys_close(fd);
|
||||
ig_sys_unlink(sandbox_probe_path); /* 立即清理,不留痕 */
|
||||
char ev[256];
|
||||
snprintf(ev, sizeof(ev), "能在沙盒外创建文件:%s", sandbox_probe_path);
|
||||
ig_jb_emit(sink, ctx, &hits, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX,
|
||||
sandbox_probe_path, ev);
|
||||
}
|
||||
}
|
||||
|
||||
return hits;
|
||||
}
|
||||
|
||||
int ig_anti_jb_check(IGFindingSink sink, void *ctx) {
|
||||
return ig_anti_jb_check_paths(
|
||||
kIGJailbreakPaths,
|
||||
sizeof(kIGJailbreakPaths) / sizeof(kIGJailbreakPaths[0]),
|
||||
"/private/.ig_jb_probe", /* 沙盒外路径:正常 App 不可写 */
|
||||
sink, ctx);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* IGAntiJailbreak.h — 越狱检测探针(走 IGSyscall 直发 svc,绕过 libc 层 hook)。
|
||||
*
|
||||
* 定位:Shadow / Liberty / A-Bypass 这类反越狱检测插件主要 hook 在 libc/ObjC 层
|
||||
* (stat/access/fopen/NSFileManager)。本探针用 IGSyscall 的 svc #0x80 直发
|
||||
* access(2)/open(2),那条可被 hook 的 libSystem 入口在此路径上不存在——检测点下沉到
|
||||
* bypass 够不到的层。这是纯客户端对抗里"抬高绕过成本"的关键一环(非根治)。
|
||||
*
|
||||
* 只采集证据、不处置:命中经 sink 上报,是否毒化/降级由策略层([[iosguard-disposition-strategy]]
|
||||
* 的 ig_poison_mark)按强信号组合决定。本探针绝不自行 exit。
|
||||
*
|
||||
* 边界:
|
||||
* - 路径特征可被 rootless 越狱改位;未命中不等于干净(组合判定原则不变)。
|
||||
* - 当前骨架路径字符串为明文,静态可见、bypass 可针对——TODO 用 IGResolve 的 XOR 混淆
|
||||
* (IG_ENC),与 svc 号混淆同理。svc 直发本身已是主要价值,字符串混淆是第二层。
|
||||
* - 仅 arm64 直发;非 arm64(宿主 x86_64)syscall 退化 unavailable。
|
||||
*/
|
||||
#ifndef IG_ANTI_JAILBREAK_H
|
||||
#define IG_ANTI_JAILBREAK_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 默认检测:内置 iOS 越狱特征表 + 沙盒逃逸探测。返回 DETECTED 条数。 */
|
||||
int ig_anti_jb_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 可注入版本(供自测/定制)。
|
||||
* paths/count:要探测可访问性的路径表(access F_OK);命中记 reason=400。
|
||||
* sandbox_probe_path:非 NULL 时尝试在该(应在沙盒外的)路径创建文件,成功=沙盒逃逸,记 401
|
||||
* 并立即清理;NULL 跳过逃逸探测。
|
||||
*/
|
||||
int ig_anti_jb_check_paths(const char *const *paths, size_t count,
|
||||
const char *sandbox_probe_path,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_ANTI_JAILBREAK_H */
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "IGFileBridge.h"
|
||||
#include <unistd.h>
|
||||
|
||||
#if !defined(__clang__)
|
||||
#error "此验证实现需要 Clang 的 optnone 属性"
|
||||
#endif
|
||||
|
||||
// 仅 SDK 的未定义引用重定向到此函数;本文件不能参与符号重定向。
|
||||
// 无日志、检测或全局可变状态,直接返回系统 FILE * 并保留 errno。
|
||||
// 间接调用不代表 GOT/Inline Hook 防护,仍须对最终 Release 单独验收。
|
||||
__attribute__((optnone, noinline))
|
||||
FILE *IG_fopen(const char *path, const char *mode) {
|
||||
FILE *(*function)(const char *, const char *) = fopen;
|
||||
return function(path, mode);
|
||||
}
|
||||
|
||||
// 各入口单独保持真实类型;不进行自动重试或短读短写补齐。
|
||||
__attribute__((optnone, noinline))
|
||||
int IG_fclose(FILE *stream) {
|
||||
int (*function)(FILE *) = fclose;
|
||||
return function(stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
size_t IG_fread(void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
size_t (*function)(void *, size_t, size_t, FILE *) = fread;
|
||||
return function(buffer, size, count, stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
size_t IG_fwrite(const void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
size_t (*function)(const void *, size_t, size_t, FILE *) = fwrite;
|
||||
return function(buffer, size, count, stream);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
ssize_t IG_read(int descriptor, void *buffer, size_t count) {
|
||||
ssize_t (*function)(int, void *, size_t) = read;
|
||||
return function(descriptor, buffer, count);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
ssize_t IG_write(int descriptor, const void *buffer, size_t count) {
|
||||
ssize_t (*function)(int, const void *, size_t) = write;
|
||||
return function(descriptor, buffer, count);
|
||||
}
|
||||
|
||||
__attribute__((optnone, noinline))
|
||||
int IG_close(int descriptor) {
|
||||
int (*function)(int) = close;
|
||||
return function(descriptor);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef IG_FILE_BRIDGE_H
|
||||
#define IG_FILE_BRIDGE_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
FILE *IG_fopen(const char *path, const char *mode);
|
||||
int IG_fclose(FILE *stream);
|
||||
size_t IG_fread(void *buffer, size_t size, size_t count, FILE *stream);
|
||||
size_t IG_fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
|
||||
ssize_t IG_read(int descriptor, void *buffer, size_t count);
|
||||
ssize_t IG_write(int descriptor, const void *buffer, size_t count);
|
||||
int IG_close(int descriptor);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,226 @@
|
||||
#include "IGArchiveGuard.h"
|
||||
#include "../resolve/IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
|
||||
/* 仅混淆常量,不作为秘密。SDK GOT 由 dyld 在独立镜像滑移后绑定。 */
|
||||
static const unsigned char names[4][6] = {
|
||||
{0x5a,0x53,0x4c,0x59,0x52}, {0x5a,0x4e,0x59,0x5d,0x58},
|
||||
{0x5a,0x4b,0x4e,0x55,0x48,0x59}, {0x5a,0x5f,0x50,0x53,0x4f,0x59}
|
||||
};
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT;
|
||||
static _Thread_local int resolving;
|
||||
static _Atomic(uintptr_t) targets[4];
|
||||
static uintptr_t expected[4], bindingSlots[4];
|
||||
static unsigned char prefixes[4][16];
|
||||
static IGStatus initial[4];
|
||||
static int bindingReady;
|
||||
#ifdef IG_OBSERVATION
|
||||
static _Atomic(uint64_t) counters[12];
|
||||
#define COUNT(i, k) atomic_fetch_add_explicit(&counters[(i)*3+(k)], 1, memory_order_relaxed)
|
||||
#else
|
||||
#define COUNT(i, k) ((void)0)
|
||||
#endif
|
||||
|
||||
static int read_bytes(uintptr_t address, void *out, size_t size) {
|
||||
vm_size_t copied = 0;
|
||||
return vm_read_overwrite(mach_task_self(), address, size, (vm_address_t)out, &copied) == KERN_SUCCESS
|
||||
&& copied == size;
|
||||
}
|
||||
|
||||
/* 仅支持打包工具已审核的非认证 arm64 GOT;缺槽/重复槽均标为不可验证。 */
|
||||
static int locate_bindings(void) {
|
||||
unsigned found = 0, images = 0;
|
||||
for (uint32_t index = 0; index < _dyld_image_count(); index++) {
|
||||
const char *path = _dyld_get_image_name(index);
|
||||
const char *suffix = "/SSZipArchive.framework/SSZipArchive";
|
||||
size_t length = path ? ig_strlen(path) : 0, tail = ig_strlen(suffix);
|
||||
if (length < tail || ig_strcmp(path + length - tail, suffix)) continue;
|
||||
if (++images != 1) return 0;
|
||||
const struct mach_header_64 *header = (const void *)_dyld_get_image_header(index);
|
||||
if (!header || header->magic != MH_MAGIC_64 || header->cputype != CPU_TYPE_ARM64
|
||||
|| (header->cpusubtype & 0xffffff) != 0) return 0;
|
||||
uintptr_t slide = _dyld_get_image_vmaddr_slide(index);
|
||||
const struct segment_command_64 *linkedit = NULL;
|
||||
const struct symtab_command *symtab = NULL;
|
||||
const struct dysymtab_command *dysymtab = NULL;
|
||||
const uint8_t *command = (const void *)(header + 1);
|
||||
const uint8_t *end = command + header->sizeofcmds;
|
||||
for (uint32_t i = 0; i < header->ncmds; i++) {
|
||||
if (command + sizeof(struct load_command) > end) return 0;
|
||||
const struct load_command *lc = (const void *)command;
|
||||
if (lc->cmdsize < 8 || lc->cmdsize % 8 || lc->cmdsize > (size_t)(end-command)) return 0;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
if (lc->cmdsize < sizeof(struct segment_command_64)) return 0;
|
||||
const struct segment_command_64 *seg = (const void *)lc;
|
||||
if (sizeof(*seg) + (uint64_t)seg->nsects * sizeof(struct section_64) != lc->cmdsize) return 0;
|
||||
if (!ig_strcmp(seg->segname, SEG_LINKEDIT)) linkedit = seg;
|
||||
} else if (lc->cmd == LC_SYMTAB && lc->cmdsize == sizeof(*symtab)) symtab = (const void *)lc;
|
||||
else if (lc->cmd == LC_DYSYMTAB && lc->cmdsize == sizeof(*dysymtab)) dysymtab = (const void *)lc;
|
||||
command += lc->cmdsize;
|
||||
}
|
||||
if (!linkedit || !symtab || !dysymtab || command != end) return 0;
|
||||
uint64_t lo = linkedit->fileoff, hi = lo + linkedit->filesize;
|
||||
if (hi < lo || symtab->symoff < lo || (uint64_t)symtab->symoff + (uint64_t)symtab->nsyms*16 > hi
|
||||
|| symtab->stroff < lo || (uint64_t)symtab->stroff + symtab->strsize > hi
|
||||
|| dysymtab->indirectsymoff < lo
|
||||
|| (uint64_t)dysymtab->indirectsymoff + (uint64_t)dysymtab->nindirectsyms*4 > hi) return 0;
|
||||
uintptr_t base = slide + linkedit->vmaddr - lo;
|
||||
const struct nlist_64 *symbols = (const void *)(base + symtab->symoff);
|
||||
const char *strings = (const void *)(base + symtab->stroff);
|
||||
const uint32_t *indirect = (const void *)(base + dysymtab->indirectsymoff);
|
||||
command = (const void *)(header + 1);
|
||||
for (uint32_t i = 0; i < header->ncmds; i++) {
|
||||
const struct load_command *lc = (const void *)command;
|
||||
if (lc->cmd == LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg = (const void *)lc;
|
||||
const struct section_64 *sections = (const void *)(seg + 1);
|
||||
for (uint32_t j = 0; j < seg->nsects; j++) {
|
||||
const struct section_64 *s = sections + j;
|
||||
if ((s->flags & SECTION_TYPE) != S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
if (s->size % 8 || (uint64_t)s->reserved1 + s->size/8 > dysymtab->nindirectsyms) return 0;
|
||||
for (uint64_t k = 0; k < s->size/8; k++) {
|
||||
uint32_t symbol = indirect[s->reserved1 + k];
|
||||
if (symbol & (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (symbol >= symtab->nsyms) return 0;
|
||||
uint32_t strx = symbols[symbol].n_un.n_strx;
|
||||
if (strx >= symtab->strsize) return 0;
|
||||
const char *name = strings + strx;
|
||||
if (!memchr(name, 0, symtab->strsize-strx)) return 0;
|
||||
for (unsigned n = 0; n < 4; n++) {
|
||||
char expectedName[] = "_ig_a0";
|
||||
expectedName[5] += n;
|
||||
if (ig_strcmp(name, expectedName)) continue;
|
||||
if (found & (1u << n)) return 0;
|
||||
bindingSlots[n] = slide + s->addr + k*8;
|
||||
found |= 1u << n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
command += lc->cmdsize;
|
||||
}
|
||||
}
|
||||
return found == 15 && images == 1;
|
||||
}
|
||||
|
||||
static void initialize(void) {
|
||||
bindingReady = locate_bindings();
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
IGResolveResult result = ig_resolve_verified(NULL, names[i], i < 2 ? 5 : 6, NULL, NULL);
|
||||
initial[i] = result.status;
|
||||
if (result.status != IG_CLEAR || !result.address) continue;
|
||||
if (!read_bytes((uintptr_t)result.address, prefixes[i], 16)) { initial[i] = IG_UNAVAILABLE; continue; }
|
||||
expected[i] = (uintptr_t)result.address;
|
||||
atomic_store_explicit(&targets[i], expected[i], memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
static int prepare(void) {
|
||||
if (resolving) return 0;
|
||||
resolving = 1;
|
||||
int result = pthread_once(&once, initialize);
|
||||
resolving = 0;
|
||||
return result == 0;
|
||||
}
|
||||
|
||||
static IGStatus validate(unsigned index, uintptr_t *address) {
|
||||
if (initial[index] != IG_CLEAR) return initial[index];
|
||||
uintptr_t current = atomic_load_explicit(&targets[index], memory_order_acquire);
|
||||
if (!current || current != expected[index]) return IG_DETECTED;
|
||||
IGStatus status = ig_verify_function((void *)current, "archive-target", NULL, NULL);
|
||||
if (status != IG_CLEAR) return status;
|
||||
unsigned char bytes[16];
|
||||
if (!read_bytes(current, bytes, 16)) return IG_UNAVAILABLE;
|
||||
if (ig_memcmp(bytes, prefixes[index], 16)) return IG_DETECTED;
|
||||
*address = current;
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
static IGStatus check_bindings(void) {
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
/* 宿主 ABI fixture 不装载 SSZipArchive;此豁免不能编入业务包。 */
|
||||
return IG_CLEAR;
|
||||
#else
|
||||
if (!bindingReady) return IG_UNAVAILABLE;
|
||||
uintptr_t correct[4] = {(uintptr_t)&ig_a0, (uintptr_t)&ig_a1, (uintptr_t)&ig_a2, (uintptr_t)&ig_a3};
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
uintptr_t current;
|
||||
if (!read_bytes(bindingSlots[i], ¤t, sizeof(current))) return IG_UNAVAILABLE;
|
||||
if (current != correct[i]) return IG_DETECTED;
|
||||
}
|
||||
return IG_CLEAR;
|
||||
#endif
|
||||
}
|
||||
|
||||
static uintptr_t checked(unsigned index) {
|
||||
COUNT(index, 0);
|
||||
if (!prepare()) { COUNT(index, 2); errno = EDEADLK; return 0; }
|
||||
uintptr_t address = 0;
|
||||
IGStatus status = check_bindings();
|
||||
if (status == IG_CLEAR) status = validate(index, &address);
|
||||
if (status != IG_CLEAR) { COUNT(index, 2); errno = status == IG_DETECTED ? EACCES : ENOSYS; return 0; }
|
||||
COUNT(index, 1);
|
||||
return address;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) FILE *ig_a0(const char *path, const char *mode) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(0);
|
||||
if (!address) return NULL;
|
||||
errno = incoming;
|
||||
return ((FILE *(*)(const char *, const char *))address)(path, mode);
|
||||
}
|
||||
__attribute__((noinline)) size_t ig_a1(void *ptr, size_t size, size_t count, FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(1);
|
||||
if (!address) return 0;
|
||||
errno = incoming;
|
||||
return ((size_t (*)(void *, size_t, size_t, FILE *))address)(ptr, size, count, stream);
|
||||
}
|
||||
__attribute__((noinline)) size_t ig_a2(const void *ptr, size_t size, size_t count, FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(2);
|
||||
if (!address) return 0;
|
||||
errno = incoming;
|
||||
return ((size_t (*)(const void *, size_t, size_t, FILE *))address)(ptr, size, count, stream);
|
||||
}
|
||||
__attribute__((noinline)) int ig_a3(FILE *stream) {
|
||||
int incoming = errno;
|
||||
uintptr_t address = checked(3);
|
||||
if (!address) return EOF;
|
||||
errno = incoming;
|
||||
return ((int (*)(FILE *))address)(stream);
|
||||
}
|
||||
|
||||
int ig_archive_check(void) {
|
||||
int incoming = errno;
|
||||
if (!prepare()) { errno = incoming; return -1; }
|
||||
IGStatus status = check_bindings();
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
uintptr_t address;
|
||||
IGStatus current = validate(i, &address);
|
||||
if (current == IG_DETECTED || (current == IG_UNAVAILABLE && status == IG_CLEAR)) status = current;
|
||||
}
|
||||
errno = incoming;
|
||||
return status == IG_CLEAR ? 0 : status == IG_DETECTED ? 1 : -1;
|
||||
}
|
||||
#ifdef IG_OBSERVATION
|
||||
uint64_t ig_archive_counter(unsigned index) {
|
||||
return index < 12 ? atomic_load_explicit(&counters[index], memory_order_relaxed) : 0;
|
||||
}
|
||||
#endif
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
void ig_archive_test_override(unsigned index, void *address) {
|
||||
if (index < 4 && prepare()) atomic_store_explicit(&targets[index], (uintptr_t)address, memory_order_release);
|
||||
}
|
||||
void ig_archive_test_reentry(int enabled) { resolving = enabled; }
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef IG_ARCHIVE_GUARD_H
|
||||
#define IG_ARCHIVE_GUARD_H
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#define IG_ARCHIVE_EXPORT __attribute__((visibility("default")))
|
||||
IG_ARCHIVE_EXPORT FILE *ig_a0(const char *path, const char *mode);
|
||||
IG_ARCHIVE_EXPORT size_t ig_a1(void *ptr, size_t size, size_t count, FILE *stream);
|
||||
IG_ARCHIVE_EXPORT size_t ig_a2(const void *ptr, size_t size, size_t count, FILE *stream);
|
||||
IG_ARCHIVE_EXPORT int ig_a3(FILE *stream);
|
||||
/* 0=正常,1=检测异常,-1=不可验证;保留 errno。 */
|
||||
IG_ARCHIVE_EXPORT int ig_archive_check(void);
|
||||
#ifdef IG_OBSERVATION
|
||||
/* index/3 为函数,index%3 为 attempted/dispatched/rejected。 */
|
||||
IG_ARCHIVE_EXPORT uint64_t ig_archive_counter(unsigned index);
|
||||
#endif
|
||||
#ifdef IG_ARCHIVE_TESTING
|
||||
void ig_archive_test_override(unsigned index, void *address);
|
||||
void ig_archive_test_reentry(int enabled);
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,149 @@
|
||||
#include "IGDispatch.h"
|
||||
#include "../resolve/IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <mach/mach.h>
|
||||
|
||||
/* 编码只减少常量区明文,不作为秘密或强加密。缓存与基线仍可被同进程攻击者修改。 */
|
||||
static const unsigned char kNames[2][5] = {{0x4b,0x4e,0x55,0x48,0x59},
|
||||
{0x5f,0x50,0x53,0x4f,0x59}};
|
||||
static pthread_once_t gOnce=PTHREAD_ONCE_INIT;
|
||||
static _Atomic(uintptr_t) gSlots[2];
|
||||
static uintptr_t gExpected[2];
|
||||
static unsigned char gPrefixes[2][16];
|
||||
static IGStatus gInitialStatus[2]={IG_UNAVAILABLE,IG_UNAVAILABLE};
|
||||
static _Thread_local int gResolving;
|
||||
#ifdef IG_OBSERVATION
|
||||
static _Atomic(uint64_t) gAttempted[2], gDispatched[2];
|
||||
#define IG_COUNT(slot,index) atomic_fetch_add_explicit(&(slot)[index],1,memory_order_relaxed)
|
||||
#else
|
||||
#define IG_COUNT(slot,index) ((void)0)
|
||||
#endif
|
||||
|
||||
static int read_prefix(uintptr_t address, unsigned char out[16]) {
|
||||
vm_size_t copied=0;
|
||||
return vm_read_overwrite(mach_task_self(),address,16,(vm_address_t)out,&copied)==KERN_SUCCESS
|
||||
&& copied==16;
|
||||
}
|
||||
|
||||
static void initialize(void) {
|
||||
for (unsigned i=0;i<2;i++) {
|
||||
IGResolveResult r=ig_resolve_verified(NULL,kNames[i],5,NULL,NULL);
|
||||
gInitialStatus[i]=r.status;
|
||||
if (r.status!=IG_CLEAR || !r.address) continue;
|
||||
uintptr_t address=(uintptr_t)r.address;
|
||||
if (!read_prefix(address,gPrefixes[i])) { gInitialStatus[i]=IG_UNAVAILABLE; continue; }
|
||||
gExpected[i]=address;
|
||||
atomic_store_explicit(&gSlots[i],address,memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
static int prepare(void) {
|
||||
/* dlsym/装载初始化过程中若重入受保护入口,拒绝而不是等待自身 once 锁。 */
|
||||
if (gResolving) return 0;
|
||||
gResolving=1;
|
||||
int rc=pthread_once(&gOnce,initialize);
|
||||
gResolving=0;
|
||||
return rc==0;
|
||||
}
|
||||
|
||||
static IGStatus validate(unsigned i, uintptr_t *address, int *reason) {
|
||||
if (gInitialStatus[i]!=IG_CLEAR) {
|
||||
*reason=IG_REASON_DISPATCH_UNAVAILABLE;
|
||||
return gInitialStatus[i];
|
||||
}
|
||||
uintptr_t current=atomic_load_explicit(&gSlots[i],memory_order_acquire);
|
||||
if (!current || current!=gExpected[i]) {
|
||||
*reason=IG_REASON_DISPATCH_TAMPER;
|
||||
return IG_DETECTED;
|
||||
}
|
||||
IGStatus status=ig_verify_function((void *)current,"dispatch-target",NULL,NULL);
|
||||
if (status!=IG_CLEAR) {
|
||||
*reason=status==IG_DETECTED ? IG_REASON_INLINE_HOOK : IG_REASON_VERIFICATION_UNAVAILABLE;
|
||||
return status;
|
||||
}
|
||||
unsigned char bytes[16];
|
||||
if (!read_prefix(current,bytes)) {
|
||||
*reason=IG_REASON_VERIFICATION_UNAVAILABLE;
|
||||
return IG_UNAVAILABLE;
|
||||
}
|
||||
if (ig_memcmp(bytes,gPrefixes[i],16)!=0) {
|
||||
*reason=IG_REASON_DISPATCH_TAMPER;
|
||||
return IG_DETECTED;
|
||||
}
|
||||
*address=current;
|
||||
return IG_CLEAR;
|
||||
}
|
||||
|
||||
static uintptr_t checked_address(unsigned i) {
|
||||
if (!prepare()) { errno=EDEADLK; return 0; }
|
||||
uintptr_t address=0; int reason=0;
|
||||
IGStatus status=validate(i,&address,&reason);
|
||||
if (status!=IG_CLEAR) { errno=status==IG_DETECTED ? EACCES : ENOSYS; return 0; }
|
||||
return address;
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
ssize_t IG_dispatch_write(int fd, const void *buffer, size_t count) {
|
||||
int incoming=errno;
|
||||
IG_COUNT(gAttempted,0);
|
||||
uintptr_t address=checked_address(0);
|
||||
if (!address) return -1;
|
||||
IG_COUNT(gDispatched,0);
|
||||
errno=incoming;
|
||||
ssize_t (*function)(int,const void *,size_t)=(void *)address;
|
||||
return function(fd,buffer,count);
|
||||
}
|
||||
|
||||
__attribute__((used,noinline))
|
||||
int IG_dispatch_close(int fd) {
|
||||
int incoming=errno;
|
||||
IG_COUNT(gAttempted,1);
|
||||
uintptr_t address=checked_address(1);
|
||||
if (!address) return -1;
|
||||
IG_COUNT(gDispatched,1);
|
||||
errno=incoming;
|
||||
int (*function)(int)=(void *)address;
|
||||
return function(fd);
|
||||
}
|
||||
|
||||
int ig_dispatch_check(IGFindingSink sink, void *ctx) {
|
||||
int saved=errno, hits=0;
|
||||
int ready=prepare();
|
||||
for (unsigned i=0;i<2;i++) {
|
||||
uintptr_t address=0; int reason=IG_REASON_DISPATCH_UNAVAILABLE;
|
||||
IGStatus status=ready ? validate(i,&address,&reason) : IG_UNAVAILABLE;
|
||||
if (status==IG_CLEAR) continue;
|
||||
IGFinding f={0}; f.status=status; f.reason=reason;
|
||||
const char *label=i==0 ? "dispatch-write" : "dispatch-close";
|
||||
strncpy(f.subject,label,sizeof(f.subject)-1);
|
||||
strncpy(f.evidence,"调度地址、提供方或代码前缀校验未通过",sizeof(f.evidence)-1);
|
||||
if (status==IG_DETECTED) hits++;
|
||||
if (sink && sink(&f,ctx)!=0) break;
|
||||
}
|
||||
errno=saved;
|
||||
return hits;
|
||||
}
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
IGDispatchObservation ig_dispatch_observation(void) {
|
||||
IGDispatchObservation value={
|
||||
atomic_load_explicit(&gAttempted[0],memory_order_relaxed),
|
||||
atomic_load_explicit(&gDispatched[0],memory_order_relaxed),
|
||||
atomic_load_explicit(&gAttempted[1],memory_order_relaxed),
|
||||
atomic_load_explicit(&gDispatched[1],memory_order_relaxed)
|
||||
};
|
||||
return value;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef IG_DISPATCH_TESTING
|
||||
void ig_dispatch_test_override(unsigned i, void *address) {
|
||||
if (i<2 && prepare()) atomic_store_explicit(&gSlots[i],(uintptr_t)address,memory_order_release);
|
||||
}
|
||||
void ig_dispatch_test_reentry(int enabled) { gResolving=enabled; }
|
||||
#endif
|
||||
@@ -0,0 +1,31 @@
|
||||
#ifndef IG_DISPATCH_H
|
||||
#define IG_DISPATCH_H
|
||||
#include <sys/types.h>
|
||||
#include "../include/IGDefender.h"
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 固定签名试点:首次按线程安全方式解析;异常时不调用未经校验的地址。 */
|
||||
ssize_t IG_dispatch_write(int fd, const void *buffer, size_t count);
|
||||
int IG_dispatch_close(int fd);
|
||||
int ig_dispatch_check(IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef IG_OBSERVATION
|
||||
/* 仅观察构建导出只读计数,不提供地址覆盖或关闭校验的接口。 */
|
||||
typedef struct {
|
||||
uint64_t write_attempted, write_dispatched;
|
||||
uint64_t close_attempted, close_dispatched;
|
||||
} IGDispatchObservation;
|
||||
IGDispatchObservation ig_dispatch_observation(void);
|
||||
#endif
|
||||
|
||||
#ifdef IG_DISPATCH_TESTING
|
||||
/* 只编入宿主测试,不允许在 App 发布包定义此宏。 */
|
||||
void ig_dispatch_test_override(unsigned index, void *address);
|
||||
void ig_dispatch_test_reentry(int enabled);
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* IGDefender.h — iOSGuard 运行时防护公共结果模型。
|
||||
*
|
||||
* 设计遵循 docs/05 §5.C:探针(probe)与处置(policy)分离。
|
||||
* 探针只采集证据并通过回调上报,绝不自行 exit/中断业务;是否限制功能由上层策略决定(观察模式优先)。
|
||||
* 状态三态 clear/detected/unavailable——unavailable(平台/架构不支持、数据缺失)不得当作安全。
|
||||
*
|
||||
* 纯 C,无 Objective-C / Swift 依赖,可直接编入任意 iOS target(也可在 macOS 宿主上编译自测)。
|
||||
*/
|
||||
#ifndef IG_DEFENDER_H
|
||||
#define IG_DEFENDER_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
IG_CLEAR = 0, /* 未发现异常证据 */
|
||||
IG_DETECTED = 1, /* 命中威胁证据 */
|
||||
IG_UNAVAILABLE = 2, /* 无法判定:架构/平台不支持或数据缺失——不得视为安全 */
|
||||
} IGStatus;
|
||||
|
||||
/* 原因码按模块分段:1xx = anti_hook,2xx = 注入/Frida。 */
|
||||
typedef enum {
|
||||
IG_REASON_NONE = 0,
|
||||
/* anti_hook */
|
||||
IG_REASON_SYMBOL_PROVENANCE = 100, /* 符号解析到非系统提供方(dyld interpose / 注入覆盖) */
|
||||
IG_REASON_INLINE_HOOK = 101, /* 关键函数序言被改写为跳转蹦床(Frida/Dobby inline hook) */
|
||||
IG_REASON_GOT_REBIND = 102, /* 自身镜像 GOT/符号指针槽被重绑定到非系统地址(fishhook 类) */
|
||||
IG_REASON_SYMBOL_UNRESOLVED = 103, /* dlsym 无法解析该符号(unavailable) */
|
||||
IG_REASON_VERIFICATION_UNAVAILABLE = 104, /* 提供方/代码页无法确认 */
|
||||
IG_REASON_DISPATCH_TAMPER = 105, /* 私有调度地址或初始化后的代码前缀变化 */
|
||||
IG_REASON_DISPATCH_UNAVAILABLE = 106, /* 调度入口无法安全使用 */
|
||||
/* 107 已分配:Swift 观察层 archive-dispatch 不可用(RDRuntimeDefender.swift),C 侧不占用 */
|
||||
IG_REASON_OBJC_IMP_CHANGED = 110, /* ObjC 关键方法 IMP 相对基线变化(swizzle/替换/函数体改写) */
|
||||
/* 注入 / Frida */
|
||||
IG_REASON_INJECTED_IMAGE = 200, /* 加载了已知注入/调试框架镜像(substrate/frida/cycript…) */
|
||||
IG_REASON_FOREIGN_IMAGE = 201, /* Bundle 外且非系统路径的镜像(弱信号,需结合其它证据) */
|
||||
IG_REASON_DYLD_INSERT = 202, /* DYLD_INSERT_LIBRARIES 指向 Bundle 外路径 */
|
||||
IG_REASON_FRIDA_THREAD = 203, /* 线程名命中 frida 运行时特征(gum-js-loop 等) */
|
||||
IG_REASON_FRIDA_PORT = 204, /* 默认 frida 端口可连接(弱信号) */
|
||||
/* anti_debug */
|
||||
IG_REASON_DEBUGGER_ATTACHED = 300, /* 直发 sysctl 检出 P_TRACED:进程被调试器跟踪 */
|
||||
/* anti_jailbreak(4xx)——均走 IGSyscall 直发 svc,绕过 libc 层对 stat/access 的 hook */
|
||||
IG_REASON_JAILBREAK_FILE = 400, /* 越狱特征文件/目录可访问(Cydia/Sileo/apt/substrate/var-jb…) */
|
||||
IG_REASON_JAILBREAK_SANDBOX = 401, /* 能在 App 沙盒外创建文件:沙盒逃逸=越狱强信号 */
|
||||
} IGReason;
|
||||
|
||||
typedef struct {
|
||||
IGStatus status; /* 本条发现的状态 */
|
||||
int reason; /* IGReason */
|
||||
char subject[128]; /* 受检对象:符号名 / 镜像路径 / 线程名 */
|
||||
char evidence[256];/* 证据详情:地址、提供方路径、端口等人读文本 */
|
||||
} IGFinding;
|
||||
|
||||
/*
|
||||
* 发现回调。探针对每条 DETECTED/UNAVAILABLE 证据调用一次(CLEAR 不上报,保持安静)。
|
||||
* sink 返回非 0 表示请求提前停止该探针的后续扫描;返回 0 继续。
|
||||
* ctx 由调用方透传(可用于计数、聚合、打点)。
|
||||
*/
|
||||
typedef int (*IGFindingSink)(const IGFinding *finding, void *ctx);
|
||||
|
||||
/*
|
||||
* 聚合入口:一次性运行 anti_hook(provenance/inline/GOT)+ 注入/Frida 全部探针。
|
||||
* bundle_path:App 主 bundle(.app)路径,用于 Bundle 外镜像/插入库判定;NULL 则跳过该判定。
|
||||
* probe_port:非 0 时才做 frida 端口弱探测(典型 27042);0 表示跳过。
|
||||
* 返回 DETECTED 证据总条数。本函数只采集不处置,绝不 exit。
|
||||
*/
|
||||
int ig_defender_scan(const char *bundle_path, int probe_port,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_DEFENDER_H */
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* IGGuard.h — iOSGuard Defender 对外统一公共头(umbrella)。
|
||||
*
|
||||
* 接入方(如 readoor)只需在 bridging header 里 `#import "IGGuard.h"`,即可拿到:
|
||||
* - 结果模型:IGStatus / IGReason / IGFinding / IGFindingSink(见 IGDefender.h)
|
||||
* - 聚合扫描:ig_defender_scan(只采集证据,绝不处置)
|
||||
* - 策略层:ig_policy_scan_and_mark(扫描→分级→命中强信号组合则毒化,守误报底线)
|
||||
* - 毒化原语:ig_poison_init / ig_poison_apply(数据依赖处置,接到解密密钥派生)
|
||||
*
|
||||
* Header Search Paths 需同时包含 defender/ 与 defender/include/(IGGuard.h 内部按此相对路径引用)。
|
||||
* 典型用法见 docs/18_READOOR_DEFENDER_INTEGRATION.md。
|
||||
*/
|
||||
#ifndef IG_GUARD_H
|
||||
#define IG_GUARD_H
|
||||
|
||||
#include "IGDefender.h" /* IGStatus/IGReason/IGFinding/IGFindingSink + ig_defender_scan */
|
||||
#include "poison/IGPoison.h" /* ig_poison_init / ig_poison_mark / ig_poison_apply */
|
||||
#include "policy/IGPolicy.h" /* ig_policy_scan_and_mark / ig_policy_sink / IGPolicyState */
|
||||
|
||||
#endif /* IG_GUARD_H */
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* IGInline.h — 强制内联的自实现 str/mem 原语(落地方案第一优先级)。
|
||||
*
|
||||
* 目的:核心校验/鉴权/加解密逻辑里避免直接调用 strcmp/memcmp/memcpy/strstr/getenv 等
|
||||
* 被攻击者重点监控的 libc 函数——这些调用会在 __la_symbol_ptr/__got 留下符号引用,
|
||||
* 既是 Fishhook rebind 的靶点,也是静态分析的锚点。
|
||||
*
|
||||
* 本头提供 __attribute__((always_inline)) 版本:使用处直接展开为离散汇编指令,
|
||||
* 不生成 bl 跳转、不产生导入表项,从而从导入表中抹除这些符号。
|
||||
*
|
||||
* 用法:在安全逻辑中用 ig_memcmp/ig_strcmp/... 替换 libc 同名函数。纯头文件,零依赖。
|
||||
* 注意:这是“隐藏特征”,非“更安全的实现”——不做常量时间比较;需防时序侧信道时另行处理。
|
||||
*/
|
||||
#ifndef IG_INLINE_H
|
||||
#define IG_INLINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define IG_AINLINE static inline __attribute__((always_inline))
|
||||
|
||||
IG_AINLINE size_t ig_strlen(const char *s) {
|
||||
const char *p = s;
|
||||
while (*p) ++p;
|
||||
return (size_t)(p - s);
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_memcmp(const void *a, const void *b, size_t n) {
|
||||
const unsigned char *x = (const unsigned char *)a;
|
||||
const unsigned char *y = (const unsigned char *)b;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (x[i] != y[i]) return (int)x[i] - (int)y[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memcpy(void *dst, const void *src, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
const unsigned char *s = (const unsigned char *)src;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = s[i];
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memset(void *dst, int c, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = (unsigned char)c;
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strcmp(const char *a, const char *b) {
|
||||
while (*a && (*a == *b)) { ++a; ++b; }
|
||||
return (int)(unsigned char)*a - (int)(unsigned char)*b;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strncmp(const char *a, const char *b, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char ca = (unsigned char)a[i], cb = (unsigned char)b[i];
|
||||
if (ca != cb) return (int)ca - (int)cb;
|
||||
if (ca == 0) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 朴素子串匹配,避免引用 libc strstr。 */
|
||||
IG_AINLINE const char *ig_strstr(const char *hay, const char *needle) {
|
||||
if (!needle[0]) return hay;
|
||||
for (; *hay; ++hay) {
|
||||
const char *h = hay, *n = needle;
|
||||
while (*h && *n && (*h == *n)) { ++h; ++n; }
|
||||
if (!*n) return hay;
|
||||
}
|
||||
return (const char *)0;
|
||||
}
|
||||
|
||||
#endif /* IG_INLINE_H */
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* IGPoison.c — 毒化状态机实现。见 IGPoison.h 的设计与边界声明。
|
||||
*
|
||||
* 实现要点:
|
||||
* - 三副本冗余、写法各异、均 volatile(防编译器把 (copy ^ BASELINE) 常量折叠回 0)。
|
||||
* - 掩码由三副本与基线异或后按位或得出:健康时每副本==BASELINE → 全 0;毒化时非 0。
|
||||
* - 没有任何 `if (poisoned)` 控制流;处置是纯算术数据流。
|
||||
*
|
||||
* 后续硬化(本骨架未做,留 TODO):
|
||||
* - 把三副本分散到不同存储域(TLS / 堆上结构 / 编码进业务数据的冗余位),而非都在 BSS。
|
||||
* - mark / mask / apply 三个函数用 OLLVM(Fla+BCF) + 字符串/常量加密盖住(README 规划)。
|
||||
* - 基线魔数不以明文入二进制:改为运行期由多来源派生,避免被静态定位后直接写回。
|
||||
*/
|
||||
#include "IGPoison.h"
|
||||
|
||||
/* 基线魔数:健康态三副本都等于它。TODO:改为运行期派生,勿明文驻留常量区。 */
|
||||
#define IG_POISON_BASELINE 0xA5C3F10E7B2D4968ULL
|
||||
|
||||
/* 三副本,volatile 防折叠。写法刻意不一致以抬高静态模式匹配成本。 */
|
||||
static volatile uint64_t g_h0;
|
||||
static volatile uint64_t g_h1;
|
||||
static volatile uint64_t g_h2;
|
||||
|
||||
/* 把 entropy 扩散成三个互不相同、且必非 0 的偏移量(保证任一副本都会偏离基线)。 */
|
||||
static uint64_t ig_spread(uint64_t e, unsigned lane) {
|
||||
e ^= 0x9E3779B97F4A7C15ULL * (lane + 1u); /* 每路不同常量 */
|
||||
e ^= e >> 30; e *= 0xBF58476D1CE4E5B9ULL;
|
||||
e ^= e >> 27; e *= 0x94D049BB133111EBULL;
|
||||
e ^= e >> 31;
|
||||
return e | 1ULL; /* 置最低位,确保非 0 */
|
||||
}
|
||||
|
||||
void ig_poison_init(void) {
|
||||
g_h0 = IG_POISON_BASELINE;
|
||||
g_h1 = IG_POISON_BASELINE;
|
||||
g_h2 = IG_POISON_BASELINE;
|
||||
}
|
||||
|
||||
/* 构造期兜底初始化(若宿主未显式调用 ig_poison_init)。 */
|
||||
__attribute__((constructor))
|
||||
static void ig_poison_ctor(void) { ig_poison_init(); }
|
||||
|
||||
void ig_poison_mark(uint64_t entropy) {
|
||||
/* entropy 为 0 时仍强制非 0,避免“混入 0 = 不生效”。 */
|
||||
uint64_t e = entropy ? entropy : 0xD1B54A32D192ED03ULL;
|
||||
g_h0 ^= ig_spread(e, 0);
|
||||
g_h1 ^= ig_spread(e, 1);
|
||||
g_h2 ^= ig_spread(e, 2);
|
||||
}
|
||||
|
||||
uint64_t ig_poison_mask(void) {
|
||||
/* 健康:每项 ^BASELINE == 0 → 或起来为 0。毒化:至少一项非 0。无分支。 */
|
||||
uint64_t m = (g_h0 ^ IG_POISON_BASELINE)
|
||||
| (g_h1 ^ IG_POISON_BASELINE)
|
||||
| (g_h2 ^ IG_POISON_BASELINE);
|
||||
return m;
|
||||
}
|
||||
|
||||
void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n) {
|
||||
if (!in || !out) return;
|
||||
uint64_t m = ig_poison_mask();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
/* 健康 m==0 → 扰动字节恒 0 → out[i]==in[i]。毒化 → 每字节被 m 的对应字节异或。 */
|
||||
uint8_t d = (uint8_t)((m >> ((i & 7u) * 8u)) & 0xFFu);
|
||||
out[i] = (uint8_t)(in[i] ^ d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* IGPoison.h — 毒化状态机(数据依赖处置,纯 C,可编入业务 target)。
|
||||
*
|
||||
* 设计核心(对应纯客户端反 Hook 的处置哲学):
|
||||
* 不写 `if (越狱) exit()`。检测到强信号组合时,只把一段熵混进一个多副本冗余的
|
||||
* “健康值”,把它破坏掉;之后由业务关键数据的**密钥派生**消费这个健康值——
|
||||
* 健康 → 掩码为 0 → 密钥不变 → 解密正常;毒化 → 掩码非 0 → 密钥被扰动 → 解出乱码。
|
||||
* 全程**没有可被 patch 的控制流分支**,攻击者 nop 不掉“判断”,因为判断不存在,
|
||||
* 只有数据流污染。要绕过得逆向整条密钥推导 + 搞清健康值怎么混入,成本量级抬高。
|
||||
*
|
||||
* 天花板(如实声明):纯客户端无法根治。多副本 + 混淆 + VMP 只是把“找到并写回健康值”
|
||||
* 从几分钟抬到几天;有耐心有能力的定向攻击者最终仍可破。安全锚点不在这。
|
||||
*
|
||||
* 处置形态(App Store 上架约束):只做数据污染 / 功能静默降级,不触发随机崩溃。
|
||||
*
|
||||
* 误报底线(极重要):处置是隐蔽且体验不可逆的,误伤一个非越狱正常用户=差评卸载且难排查。
|
||||
* 因此 ig_poison_mark 只允许由**高置信强信号组合**触发(见 IGPoison.c 注释),
|
||||
* 弱信号(FOREIGN_IMAGE / FRIDA_PORT 等)绝不参与。上线前必须在多机型验证非越狱零毒化。
|
||||
*/
|
||||
#ifndef IG_POISON_H
|
||||
#define IG_POISON_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 把多副本健康值置为基线。应在尽早的构造期调用一次(也有构造函数兜底)。 */
|
||||
void ig_poison_init(void);
|
||||
|
||||
/*
|
||||
* 命中强信号组合时调用:把 entropy(必须非 0)混进所有健康值副本,使其偏离基线。
|
||||
* 幂等累积——多次调用只会持续偏离,不会“洗白”。此函数只写状态,不产生任何可见后果。
|
||||
*/
|
||||
void ig_poison_mark(uint64_t entropy);
|
||||
|
||||
/*
|
||||
* 返回处置掩码:健康=0,毒化=非 0(由多副本交叉推导,无分支)。
|
||||
* 业务侧不直接判它,而是把它揉进密钥/偏移等数据,见 ig_poison_apply。
|
||||
*/
|
||||
uint64_t ig_poison_mask(void);
|
||||
|
||||
/*
|
||||
* 数据依赖处置原语:把 in[0..n) 揉以当前掩码写入 out[0..n)(允许 in==out 原地)。
|
||||
* 健康时 out 与 in 逐字节相等(掩码 0,异或 0);毒化时每字节被掩码扰动。
|
||||
* 业务用法:对解密 key 的字节调用本函数后再传给解密器——健康照常、毒化解出乱码。
|
||||
*/
|
||||
void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_POISON_H */
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* IGPolicy.c — 策略层实现。见 .h 的分级与误报底线。
|
||||
*/
|
||||
#include "IGPolicy.h"
|
||||
#include "poison/IGPoison.h"
|
||||
|
||||
typedef enum { IG_TIER_IGNORE = 0, IG_TIER_WEAK, IG_TIER_MEDIUM, IG_TIER_STRONG } IGTier;
|
||||
|
||||
/* reason → 档位。未列出的 DETECTED 按 WEAK 处理(保守,不触发毒化)。 */
|
||||
static IGTier ig_reason_tier(int reason) {
|
||||
switch (reason) {
|
||||
/* STRONG:单条即可判定(误报概率极低) */
|
||||
case IG_REASON_JAILBREAK_SANDBOX: /* 401 沙盒逃逸 */
|
||||
case IG_REASON_JAILBREAK_FILE: /* 400 越狱特征文件 */
|
||||
case IG_REASON_GOT_REBIND: /* 102 */
|
||||
case IG_REASON_INLINE_HOOK: /* 101 */
|
||||
case IG_REASON_INJECTED_IMAGE: /* 200 */
|
||||
case IG_REASON_DEBUGGER_ATTACHED: /* 300 */
|
||||
return IG_TIER_STRONG;
|
||||
/* MEDIUM:需组合(含合法 swizzling 会误报的 ObjC IMP) */
|
||||
case IG_REASON_SYMBOL_PROVENANCE: /* 100 */
|
||||
case IG_REASON_OBJC_IMP_CHANGED: /* 110 */
|
||||
case IG_REASON_FRIDA_THREAD: /* 203 */
|
||||
return IG_TIER_MEDIUM;
|
||||
/* WEAK:仅观察,永不触发毒化 */
|
||||
case IG_REASON_FOREIGN_IMAGE: /* 201 */
|
||||
case IG_REASON_FRIDA_PORT: /* 204 */
|
||||
return IG_TIER_WEAK;
|
||||
default:
|
||||
return IG_TIER_WEAK;
|
||||
}
|
||||
}
|
||||
|
||||
void ig_policy_reset(IGPolicyState *st, IGFindingSink observer, void *observer_ctx) {
|
||||
if (!st) return;
|
||||
st->strong_count = 0;
|
||||
st->medium_bitmap = 0;
|
||||
st->medium_distinct = 0;
|
||||
st->entropy = 0;
|
||||
st->detected_total = 0;
|
||||
st->observer = observer;
|
||||
st->observer_ctx = observer_ctx;
|
||||
}
|
||||
|
||||
/* 把 reason 映射到 medium_bitmap 的一个位(三个 MEDIUM reason 分别占位)。 */
|
||||
static uint32_t ig_medium_bit(int reason) {
|
||||
switch (reason) {
|
||||
case IG_REASON_SYMBOL_PROVENANCE: return 1u << 0;
|
||||
case IG_REASON_OBJC_IMP_CHANGED: return 1u << 1;
|
||||
case IG_REASON_FRIDA_THREAD: return 1u << 2;
|
||||
default: return 0u;
|
||||
}
|
||||
}
|
||||
|
||||
int ig_policy_sink(const IGFinding *f, void *ctx) {
|
||||
IGPolicyState *st = (IGPolicyState *)ctx;
|
||||
if (!st || !f) return 0;
|
||||
|
||||
/* 先转发观察打点(无论档位),便于量化误报面。 */
|
||||
if (st->observer) st->observer(f, st->observer_ctx);
|
||||
|
||||
/* 误报底线:只有 DETECTED 参与判定;UNAVAILABLE/CLEAR 忽略。 */
|
||||
if (f->status != IG_DETECTED) return 0;
|
||||
st->detected_total++;
|
||||
|
||||
IGTier tier = ig_reason_tier(f->reason);
|
||||
if (tier == IG_TIER_STRONG) {
|
||||
st->strong_count++;
|
||||
st->entropy ^= 0x100000001b3ULL * (uint64_t)(f->reason + 1);
|
||||
} else if (tier == IG_TIER_MEDIUM) {
|
||||
uint32_t bit = ig_medium_bit(f->reason);
|
||||
if (bit && !(st->medium_bitmap & bit)) {
|
||||
st->medium_bitmap |= bit;
|
||||
st->medium_distinct++;
|
||||
}
|
||||
st->entropy ^= 0x100000001b3ULL * (uint64_t)(f->reason + 1);
|
||||
}
|
||||
/* WEAK/IGNORE:不计入判定,也不进熵。 */
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ig_policy_evaluate_and_mark(IGPolicyState *st) {
|
||||
if (!st) return 0;
|
||||
int trigger = (st->strong_count >= 1) || (st->medium_distinct >= 2);
|
||||
if (trigger) {
|
||||
uint64_t e = st->entropy ? st->entropy : 0xA24BAED4963EE407ULL;
|
||||
ig_poison_mark(e);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ig_policy_scan_and_mark(const char *bundle_path, int probe_port,
|
||||
IGFindingSink observer, void *observer_ctx) {
|
||||
IGPolicyState st;
|
||||
ig_policy_reset(&st, observer, observer_ctx);
|
||||
ig_defender_scan(bundle_path, probe_port, ig_policy_sink, &st);
|
||||
return ig_policy_evaluate_and_mark(&st);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* IGPolicy.h — 策略层:把探针证据按强弱分级,组合判定后决定是否毒化(ig_poison_mark)。
|
||||
*
|
||||
* 连接 [[iosguard-disposition-strategy]]:ig_defender_scan 流式上报 IGFinding,本层做 sink,
|
||||
* 累积一次扫描的全部 DETECTED 证据;扫描结束后 evaluate 按组合规则决定是否触发毒化。
|
||||
*
|
||||
* 误报底线(最重要):毒化隐蔽且不可逆,误伤非越狱正常用户=差评卸载难排查。故:
|
||||
* - 只有 DETECTED 参与;UNAVAILABLE(架构/平台不支持)与 CLEAR 一律忽略,绝不当攻击。
|
||||
* - 信号分三档:
|
||||
* STRONG(单条即判定):越狱文件/沙盒逃逸、GOT 重绑、inline hook、注入镜像、调试器跟踪。
|
||||
* MEDIUM(需 ≥2 个不同 MEDIUM,或与任一 STRONG 同现才判定):符号提供方、ObjC IMP 变化、
|
||||
* frida 线程——其中 ObjC IMP 合法 swizzling 会误报,故不单条定罪。
|
||||
* WEAK(永不触发毒化,仅观察):Bundle 外镜像、frida 端口等弱证据。
|
||||
*
|
||||
* 本层不自行 exit;唯一处置是数据依赖毒化。可选把 finding 转发给观察打点(observer)。
|
||||
*/
|
||||
#ifndef IG_POLICY_H
|
||||
#define IG_POLICY_H
|
||||
|
||||
#include "IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
int strong_count; /* STRONG 档命中条数 */
|
||||
uint32_t medium_bitmap; /* MEDIUM 档已命中的不同 reason(去重用) */
|
||||
int medium_distinct; /* MEDIUM 档不同 reason 数 */
|
||||
uint64_t entropy; /* 命中 reason 聚合出的毒化熵(非 0) */
|
||||
int detected_total; /* 累计 DETECTED 条数(观察用) */
|
||||
IGFindingSink observer; /* 可选:每条 finding 透传给它做打点;NULL 跳过 */
|
||||
void *observer_ctx; /* observer 的上下文 */
|
||||
} IGPolicyState;
|
||||
|
||||
/* 重置状态;observer/observer_ctx 可传 NULL。 */
|
||||
void ig_policy_reset(IGPolicyState *st, IGFindingSink observer, void *observer_ctx);
|
||||
|
||||
/* 作为 ig_defender_scan 的 sink:ctx 必须是 IGPolicyState*。只累积、不处置。 */
|
||||
int ig_policy_sink(const IGFinding *finding, void *ctx);
|
||||
|
||||
/*
|
||||
* 扫描结束后调用:按组合规则判定。满足即 ig_poison_mark(entropy) 并返回 1;否则返回 0。
|
||||
* 规则:strong_count>=1 || medium_distinct>=2。
|
||||
*/
|
||||
int ig_policy_evaluate_and_mark(IGPolicyState *st);
|
||||
|
||||
/*
|
||||
* 便捷封装:reset → ig_defender_scan → evaluate_and_mark 一次完成。
|
||||
* 返回 1 表示本次触发了毒化。observer/observer_ctx 可 NULL。
|
||||
*/
|
||||
int ig_policy_scan_and_mark(const char *bundle_path, int probe_port,
|
||||
IGFindingSink observer, void *observer_ctx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_POLICY_H */
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* IGInline.h — 强制内联的自实现 str/mem 原语(落地方案第一优先级)。
|
||||
*
|
||||
* 目的:核心校验/鉴权/加解密逻辑里避免直接调用 strcmp/memcmp/memcpy/strstr/getenv 等
|
||||
* 被攻击者重点监控的 libc 函数——这些调用会在 __la_symbol_ptr/__got 留下符号引用,
|
||||
* 既是 Fishhook rebind 的靶点,也是静态分析的锚点。
|
||||
*
|
||||
* 本头提供 __attribute__((always_inline)) 版本:使用处直接展开为离散汇编指令,
|
||||
* 不生成 bl 跳转、不产生导入表项,从而从导入表中抹除这些符号。
|
||||
*
|
||||
* 用法:在安全逻辑中用 ig_memcmp/ig_strcmp/... 替换 libc 同名函数。纯头文件,零依赖。
|
||||
* 注意:这是“隐藏特征”,非“更安全的实现”——不做常量时间比较;需防时序侧信道时另行处理。
|
||||
*/
|
||||
#ifndef IG_INLINE_H
|
||||
#define IG_INLINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define IG_AINLINE static inline __attribute__((always_inline))
|
||||
|
||||
IG_AINLINE size_t ig_strlen(const char *s) {
|
||||
const char *p = s;
|
||||
while (*p) ++p;
|
||||
return (size_t)(p - s);
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_memcmp(const void *a, const void *b, size_t n) {
|
||||
const unsigned char *x = (const unsigned char *)a;
|
||||
const unsigned char *y = (const unsigned char *)b;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (x[i] != y[i]) return (int)x[i] - (int)y[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memcpy(void *dst, const void *src, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
const unsigned char *s = (const unsigned char *)src;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = s[i];
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE void *ig_memset(void *dst, int c, size_t n) {
|
||||
unsigned char *d = (unsigned char *)dst;
|
||||
for (size_t i = 0; i < n; ++i) d[i] = (unsigned char)c;
|
||||
return dst;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strcmp(const char *a, const char *b) {
|
||||
while (*a && (*a == *b)) { ++a; ++b; }
|
||||
return (int)(unsigned char)*a - (int)(unsigned char)*b;
|
||||
}
|
||||
|
||||
IG_AINLINE int ig_strncmp(const char *a, const char *b, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char ca = (unsigned char)a[i], cb = (unsigned char)b[i];
|
||||
if (ca != cb) return (int)ca - (int)cb;
|
||||
if (ca == 0) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 朴素子串匹配,避免引用 libc strstr。 */
|
||||
IG_AINLINE const char *ig_strstr(const char *hay, const char *needle) {
|
||||
if (!needle[0]) return hay;
|
||||
for (; *hay; ++hay) {
|
||||
const char *h = hay, *n = needle;
|
||||
while (*h && *n && (*h == *n)) { ++h; ++n; }
|
||||
if (!*n) return hay;
|
||||
}
|
||||
return (const char *)0;
|
||||
}
|
||||
|
||||
#endif /* IG_INLINE_H */
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* IGResolve.c — 加密名 + 带校验的符号解析实现。
|
||||
*
|
||||
* 复用 IGAntiHook 的 ig_verify_function 做「放行前校验」:dlsym 得到地址后,必须 provenance
|
||||
* (提供方系统路径)+ 序言(非 inline-hook 蹦床)双过,否则返回 NULL——把「被挟持的实现」挡在调用前。
|
||||
*/
|
||||
#include "IGResolve.h"
|
||||
#include "../anti_hook/IGAntiHook.h"
|
||||
#include "../primitives/IGInline.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <crt_externs.h> /* _NSGetEnviron */
|
||||
|
||||
char *ig_decrypt(const unsigned char *enc, size_t len, char *out, size_t cap) {
|
||||
if (!out || cap==0) return NULL;
|
||||
out[0]='\0';
|
||||
if (!enc || len==0 || len>=cap) return NULL;
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
out[i] = (char)(enc[i] ^ IG_ENC_KEY);
|
||||
if (out[i]=='\0') { ig_wipe(out,cap); return NULL; }
|
||||
}
|
||||
out[len] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
void ig_wipe(void *p, size_t n) {
|
||||
if (!p) return;
|
||||
volatile unsigned char *v = (volatile unsigned char *)p;
|
||||
while (n--) *v++ = 0; /* volatile:防编译器把清零 DCE 掉 */
|
||||
}
|
||||
|
||||
IGResolveResult ig_resolve_verified(void *handle, const unsigned char *enc_name, size_t sym_len,
|
||||
IGFindingSink sink, void *ctx) {
|
||||
char name[256];
|
||||
IGResolveResult result={IG_UNAVAILABLE,NULL};
|
||||
if (!ig_decrypt(enc_name, sym_len, name, sizeof(name))) return result;
|
||||
void *addr = dlsym(handle ? handle : RTLD_DEFAULT, name);
|
||||
if (addr) {
|
||||
/* 放行前校验:provenance + inline-hook。不过即判被挟持,返回 NULL。 */
|
||||
result.status=ig_verify_function(addr,name,sink,ctx);
|
||||
if (result.status==IG_CLEAR) result.address=addr;
|
||||
} else if (sink) {
|
||||
IGFinding f={0};
|
||||
f.status=IG_UNAVAILABLE; f.reason=IG_REASON_SYMBOL_UNRESOLVED;
|
||||
sink(&f,ctx);
|
||||
}
|
||||
ig_wipe(name, sizeof(name)); /* 明文符号名用后清零,不驻留栈 */
|
||||
return result;
|
||||
}
|
||||
|
||||
void *ig_dlsym_verified(void *handle, const unsigned char *enc_name, size_t sym_len) {
|
||||
return ig_resolve_verified(handle,enc_name,sym_len,NULL,NULL).address;
|
||||
}
|
||||
|
||||
void *ig_dlopen_hidden(const unsigned char *enc_path, size_t path_len, int mode) {
|
||||
char path[512];
|
||||
if (!ig_decrypt(enc_path, path_len, path, sizeof(path))) return NULL;
|
||||
void *h = dlopen(path, mode);
|
||||
ig_wipe(path, sizeof(path));
|
||||
return h;
|
||||
}
|
||||
|
||||
const char *ig_getenv(const char *name) {
|
||||
char ***environment = _NSGetEnviron();
|
||||
if (!environment || !*environment || !name || !name[0]) return NULL;
|
||||
char *const *envp = *environment;
|
||||
size_t nlen = ig_strlen(name);
|
||||
for (; *envp; ++envp) {
|
||||
const char *e = *envp;
|
||||
/* 匹配 "name=" 前缀 */
|
||||
if (ig_strncmp(e, name, nlen) == 0 && e[nlen] == '=') {
|
||||
return e + nlen + 1;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* IGResolve.h — 加密名 + 带校验的自定义符号解析(落地方案第二优先级)。
|
||||
*
|
||||
* 问题:核心逻辑直接 dlopen("…")/dlsym(h,"…") 会在 __cstring 留下明文库名/符号名,
|
||||
* 既暴露意图(攻击者 grep 字符串即知你在找什么),__got 里的 dlopen/dlsym 本身也是 hook 靶点。
|
||||
*
|
||||
* 本模块:
|
||||
* 1) 编译期 XOR 混淆字符串(IG_ENC 宏),运行期在**栈上**解密、用完即清零,明文不驻留常量区。
|
||||
* 2) 解析后**校验再放行**:dladdr 确认提供方在系统路径白名单内 + 校验函数序言首字节不是
|
||||
* inline-hook 蹦床(B / LDR-literal+BR x16/x17),命中则返回 NULL(视作被挟持,拒绝使用)。
|
||||
* 3) ig_getenv 经 _NSGetEnviron 手工遍历,规避对 getenv 的 hook/特征。
|
||||
*
|
||||
* 边界:dlopen/dlsym 本身仍会被解析/调用(仅隐藏其**参数**与**对结果验真**);若需连 dlsym 调用
|
||||
* 也抹除,改走 Export Trie 手工遍历(本头预留 ig_resolve_in_image,当前实现以 dlsym 为主路径)。
|
||||
* 字符串混淆是“抬高静态分析成本”,非加密强度;密钥在二进制内,决心足够者可还原——与 svc 号混淆同理。
|
||||
*/
|
||||
#ifndef IG_RESOLVE_H
|
||||
#define IG_RESOLVE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "../include/IGDefender.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 单字节 XOR 密钥(与 IGSyscall 的掩码独立)。 */
|
||||
#define IG_ENC_KEY 0x3Cu
|
||||
|
||||
/*
|
||||
* 栈上解密:把 enc(已 XOR)解到调用方缓冲 out(容量 cap),返回 out。
|
||||
* 用完务必 ig_wipe 清零,避免解密后的明文在栈/寄存器残留被 dump。
|
||||
*/
|
||||
char *ig_decrypt(const unsigned char *enc, size_t len, char *out, size_t cap);
|
||||
void ig_wipe(void *p, size_t n);
|
||||
|
||||
/*
|
||||
* 带校验的 dlsym:在 handle(NULL=RTLD_DEFAULT)中解析名为 enc_name(XOR 编码) 的符号,
|
||||
* 成功后对结果做 provenance + 序言校验;任一不过返回 NULL。sym_len 为编码串长度(不含结尾)。
|
||||
*/
|
||||
void *ig_dlsym_verified(void *handle, const unsigned char *enc_name, size_t sym_len);
|
||||
|
||||
typedef struct { IGStatus status; void *address; } IGResolveResult;
|
||||
IGResolveResult ig_resolve_verified(void *handle, const unsigned char *enc_name, size_t sym_len,
|
||||
IGFindingSink sink, void *ctx);
|
||||
|
||||
/*
|
||||
* 带隐藏名的 dlopen:以 enc_path(XOR 编码) 打开库,返回 handle 或 NULL。
|
||||
* 仅隐藏库路径字符串;是否可信由后续 ig_dlsym_verified 的校验保证。
|
||||
*/
|
||||
void *ig_dlopen_hidden(const unsigned char *enc_path, size_t path_len, int mode);
|
||||
|
||||
/* 经 _NSGetEnviron 手工查环境变量,规避 getenv 符号。未命中返回 NULL。name 为明文(短、非敏感)。 */
|
||||
const char *ig_getenv(const char *name);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_RESOLVE_H */
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* IGSyscall.c — ARM64 混淆直发系统调用实现。
|
||||
*
|
||||
* ABI(本会话真机/宿主实测):调用号入 x16(arm64 BSD 调用**不加** 0x2000000 掩码,那是 x86_64 的
|
||||
* class 位);参数 x0..x5;`svc #0x80`;返回值在 x0,出错时 carry 置位、x0=errno。
|
||||
* 本封装对出错统一返回 -errno,便于调用方判负。
|
||||
*/
|
||||
#include "IGSyscall.h"
|
||||
|
||||
/* 运行期密钥,volatile 防止编译器把 enc^key 折叠回明文立即数。构造函数置值,提供默认兜底。 */
|
||||
volatile long ig_sc_key = IG_SC_CMASK;
|
||||
|
||||
__attribute__((constructor))
|
||||
static void ig_sc_init(void) {
|
||||
/* 显式再置一次:即使该 TU 的 constructor 被裁剪,静态初值也保证正确。 */
|
||||
ig_sc_key = IG_SC_CMASK;
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
|
||||
/*
|
||||
* 直发核心。真实调用号 = enc_num ^ ig_sc_key,在运行期于寄存器内还原后载入 x16,
|
||||
* 二进制里既无 `movz x16,#<真实号>` 立即数,也无该号的明文常量。
|
||||
* carry 置位(出错)时返回 -x0(errno),否则返回 x0。
|
||||
*/
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5) {
|
||||
register long x16 __asm__("x16") = enc_num ^ ig_sc_key;
|
||||
register long x0 __asm__("x0") = a0;
|
||||
register long x1 __asm__("x1") = a1;
|
||||
register long x2 __asm__("x2") = a2;
|
||||
register long x3 __asm__("x3") = a3;
|
||||
register long x4 __asm__("x4") = a4;
|
||||
register long x5 __asm__("x5") = a5;
|
||||
register long cc __asm__("x8"); /* 承接 carry 标志 */
|
||||
__asm__ __volatile__(
|
||||
"svc #0x80\n"
|
||||
"cset %[cc], cs\n" /* carry set → 出错 */
|
||||
: "+r"(x0), [cc] "=r"(cc)
|
||||
: "r"(x16), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5)
|
||||
: "cc", "memory");
|
||||
return cc ? -x0 : x0;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
/* 非 arm64(宿主自测可能是 x86_64):退化为 unavailable 语义,返回 -1。 */
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5) {
|
||||
(void)enc_num; (void)a0; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5;
|
||||
return -1;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/* BSD 调用号(arm64,无 class 掩码)。本会话实测:getpid=20、write=4 已验证。 */
|
||||
#define IG_NR_EXIT 1
|
||||
#define IG_NR_READ 3
|
||||
#define IG_NR_WRITE 4
|
||||
#define IG_NR_OPEN 5
|
||||
#define IG_NR_CLOSE 6
|
||||
#define IG_NR_UNLINK 10
|
||||
#define IG_NR_GETPID 20
|
||||
#define IG_NR_ACCESS 33
|
||||
#define IG_NR_SYSCTL 202
|
||||
|
||||
int ig_sys_getpid(void) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_GETPID), 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
long ig_sys_write(int fd, const void *buf, size_t n) {
|
||||
return ig_syscall6(IG_SC(IG_NR_WRITE), (long)fd, (long)buf, (long)n, 0, 0, 0);
|
||||
}
|
||||
|
||||
long ig_sys_read(int fd, void *buf, size_t n) {
|
||||
return ig_syscall6(IG_SC(IG_NR_READ), (long)fd, (long)buf, (long)n, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_open(const char *path, int flags, int mode) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_OPEN), (long)path, (long)flags, (long)mode, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_close(int fd) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_CLOSE), (long)fd, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_access(const char *path, int amode) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_ACCESS), (long)path, (long)amode, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
int ig_sys_unlink(const char *path) {
|
||||
return (int)ig_syscall6(IG_SC(IG_NR_UNLINK), (long)path, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
void ig_sys_exit(int code) {
|
||||
ig_syscall6(IG_SC(IG_NR_EXIT), (long)code, 0, 0, 0, 0, 0);
|
||||
for (;;) { } /* 不返回 */
|
||||
}
|
||||
|
||||
/*
|
||||
* 调试器检测:sysctl(mib={CTL_KERN,KERN_PROC,KERN_PROC_PID,pid}) 读 kinfo_proc.kp_proc.p_flag,
|
||||
* P_TRACED(0x800) 置位即被调试。直发 svc,不经 libc 的 sysctl(避开对其的 hook)。
|
||||
* 为避免依赖 <sys/sysctl.h>/<sys/proc.h> 的完整布局,这里用常量与偏移手工构造。
|
||||
*/
|
||||
#define IG_CTL_KERN 1
|
||||
#define IG_KERN_PROC 14
|
||||
#define IG_KERN_PROC_PID 1
|
||||
#define IG_P_TRACED 0x00000800
|
||||
|
||||
int ig_sys_is_debugged(void) {
|
||||
#if defined(__aarch64__)
|
||||
/*
|
||||
* struct kinfo_proc 在 arm64 iOS/macOS 上,kp_proc.p_flag 为结构体起始处的第一个 int(偏移 0)。
|
||||
* 该布局自 BSD 以来稳定:extern_proc 以 p_un(union,8B) 起,随后 p_flag。为稳妥,取足够大的缓冲,
|
||||
* 并从 p_flag 的已知偏移读取。extern_proc:前 8B 为 union 指针/ru,接着 struct timeval(16B? ) —
|
||||
* 不同平台有差异,故用保守做法:定位 p_flag 偏移为 extern_proc 内 0x10。
|
||||
*/
|
||||
unsigned char buf[648]; /* sizeof(struct kinfo_proc)==648(本机 offsetof 实测) */
|
||||
for (size_t i = 0; i < sizeof(buf); ++i) buf[i] = 0;
|
||||
|
||||
int mib[4];
|
||||
mib[0] = IG_CTL_KERN;
|
||||
mib[1] = IG_KERN_PROC;
|
||||
mib[2] = IG_KERN_PROC_PID;
|
||||
mib[3] = ig_sys_getpid();
|
||||
|
||||
size_t len = sizeof(buf);
|
||||
/* sysctl(name, namelen, oldp, oldlenp, newp, newlen) */
|
||||
long r = ig_syscall6(IG_SC(IG_NR_SYSCTL), (long)mib, 4, (long)buf, (long)&len, 0, 0);
|
||||
if (r < 0) return -1; /* unavailable */
|
||||
|
||||
/*
|
||||
* p_flag 在 kinfo_proc 内的字节偏移:kp_proc 位于 kinfo_proc 偏移 0,extern_proc.p_flag 偏移 32——
|
||||
* 两者均由本机 `offsetof(struct kinfo_proc, kp_proc)==0` + `offsetof(struct extern_proc, p_flag)==32`
|
||||
* 实测得到(见 scratchpad/off.c)。故 p_flag 偏移 = 0x20。LP64 ABI 稳定。
|
||||
*/
|
||||
int p_flag;
|
||||
const unsigned char *pf = buf + 0x20;
|
||||
p_flag = (int)((unsigned)pf[0] | ((unsigned)pf[1] << 8) |
|
||||
((unsigned)pf[2] << 16) | ((unsigned)pf[3] << 24));
|
||||
return (p_flag & IG_P_TRACED) ? 1 : 0;
|
||||
#else
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* IGSyscall.h — ARM64 混淆直发系统调用(落地方案第一优先级)。
|
||||
*
|
||||
* 文件/进程/安全类系统调用若经 libsystem_kernel.dylib 走,libSystem 的函数入口可被 inline hook、
|
||||
* __got 槽可被 fishhook 重绑定。本模块用内联汇编 `svc #0x80` 直接进内核,绕过 C 库封装层——
|
||||
* 那条可被 hook 的 libSystem 入口在这条路径上根本不存在。
|
||||
*
|
||||
* 反静态特征:IDA 等常搜索 `svc #0x80` 并读 x16 的立即数识别调用号。本模块不把真实调用号写成
|
||||
* `movz x16,#n` 立即数,而是调用方传入 XOR 编码值(IG_SC 宏),运行期与 ig_sc_key 异或还原后
|
||||
* 由寄存器载入 x16,使静态扫描读不到真实号。
|
||||
*
|
||||
* 边界(如实声明,与 docs/05 §2 一致):
|
||||
* - 仅 arm64。直发系统调用绕过 libSystem,跨 iOS 版本的调用号/ABI 稳定性由调用方负责;
|
||||
* Apple 审核对直发 svc 可能关注,非 App Store 主线,用于确需防 hook 的关键路径。
|
||||
* - 错误语义:返回值 <0 不自动转 errno;错误时内核置 carry、x0=errno,本封装统一返回 -errno。
|
||||
* - 变参/取消点/EINTR 等 libc 语义不代为处理,调用方按需补。
|
||||
*/
|
||||
#ifndef IG_SYSCALL_H
|
||||
#define IG_SYSCALL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 编译期 XOR 编码掩码:调用方用 IG_SC(真实号) 传参,真实号不以明文/立即数进入二进制。 */
|
||||
#define IG_SC_CMASK 0x5Al
|
||||
#define IG_SC(n) ((long)((long)(n) ^ IG_SC_CMASK))
|
||||
|
||||
/* 运行期密钥(构造函数置为 IG_SC_CMASK,经 volatile 存取避免被常量折叠回立即数)。 */
|
||||
extern volatile long ig_sc_key;
|
||||
|
||||
/*
|
||||
* 通用直发。enc_num:IG_SC(真实调用号)。a0..a5:参数(不足补 0)。
|
||||
* 成功返回内核结果(x0);失败返回 -errno。
|
||||
*/
|
||||
long ig_syscall6(long enc_num, long a0, long a1, long a2, long a3, long a4, long a5);
|
||||
|
||||
/* 常用封装(均走 ig_syscall6,调用号经 IG_SC 编码)。 */
|
||||
int ig_sys_getpid(void);
|
||||
long ig_sys_write(int fd, const void *buf, size_t n);
|
||||
long ig_sys_read(int fd, void *buf, size_t n);
|
||||
int ig_sys_open(const char *path, int flags, int mode);
|
||||
int ig_sys_close(int fd);
|
||||
int ig_sys_access(const char *path, int amode); /* 直发 access(2);0=可访问,<0=-errno */
|
||||
int ig_sys_unlink(const char *path); /* 直发 unlink(2);0=成功,<0=-errno */
|
||||
void ig_sys_exit(int code) __attribute__((noreturn));
|
||||
|
||||
/*
|
||||
* 调试器检测:直发 sysctl(KERN_PROC/KERN_PROC_PID) 读 kinfo_proc.p_flag & P_TRACED。
|
||||
* 返回 1=被跟踪,0=未跟踪,-1=unavailable(sysctl 失败)。不经 libc,规避对 sysctl 的 hook。
|
||||
*/
|
||||
int ig_sys_is_debugged(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* IG_SYSCALL_H */
|
||||
@@ -0,0 +1,190 @@
|
||||
# readoor 漏洞报告分析与 iOSGuard 加固实施方案
|
||||
|
||||
日期:2026-11-10。状态:分析与实施设计,尚未实施修复、接入或完成检测机构复测。
|
||||
|
||||
后续进展:已实现独立的 [静态 SDK fopen 重定向 PoC](06_STATIC_SDK_FOPEN_POC.md),并验证讯飞 SDK 副本的符号改写与可重定位链接。[通用重定向工具](07_GENERIC_STATIC_SDK_REDIRECT.md)与 [readoor31 ZipZap 构建试点](08_ZIPZAP_PILOT_BUILD_VERIFICATION.md) 已完成;整改方向结论(检测器判定标准、链接后 Mach-O 改写器选型、升级阶梯)见 [09](09_ECNUP_REMEDIATION_DIRECTION.md)。下文保留最初分析记录;readoor 正式接入、真机业务回归和检测机构复测仍未完成。
|
||||
|
||||
## 1. 目标与核查边界
|
||||
|
||||
iOSGuard 的首要目标是为 iOS 项目提供反 Hook 与 App 加固能力,并对指定安全报告形成可追踪的整改闭环。readoor 是首个验证项目。本轮仅分析报告、核查代码、制定实施方案,不修改 readoor 源码、工程、依赖或签名产物。
|
||||
|
||||
核查输入:
|
||||
|
||||
- 报告:`/Users/shenlei/Desktop/1.docx`,通过 DOCX 内的 Word XML 提取文本、表格内容;本轮未进行页面视觉核查。
|
||||
- iOSGuard:`/Users/shenlei/Work/ReadBook/iOSGuard`,HEAD `ff0aee7`。
|
||||
- readoor:`/Users/shenlei/Work/ReadBook/readoor`,HEAD `d640290a`,存在用户未提交修改,分析基于当前工作区。
|
||||
- `AutoPacking/config.json` 中配置 `306` 的名称、Bundle ID 与报告相符。仍需核对当时实际使用的 scheme、target、编译宏、依赖版本及归档产物。
|
||||
|
||||
本轮未获得报告对应的原始 IPA、同次构建 dSYM、Link Map 和完整检测规则;在 readoor 的 `build/`、`AutoPacking/` 中未找到 IPA。当前源码与 2026-10-22 被测二进制不能直接视为同一版本。报告中的匿名地址暂不归因到具体源码或 SDK。
|
||||
|
||||
本轮尝试在线核验 Apple 与 Clang 官方资料,但检索工具未返回内容。涉及平台 API 可用性、分发政策的实施结论,需在落地时结合目标 SDK 与官方资料再核验;本方案不作上架保证。文中的源码结论以本地证据为依据。
|
||||
|
||||
## 2. 报告实际说明了什么
|
||||
|
||||
| 字段 | 报告原文信息 |
|
||||
| --- | --- |
|
||||
| 应用 | ECNUP外语 |
|
||||
| 版本 / Bundle ID | `2.197.2` / `com.ecnup.azZVz02` |
|
||||
| 文件 | `ECNUP外语_2.197.2_AppOnly.ipa` |
|
||||
| MD5 | `83daa763da5a226b914201d3e31f969e` |
|
||||
| 检测日期 / 引擎 | `2026-10-22` / `V4.6.6` |
|
||||
| 报告所列 SDK / 最低系统 | iOS 26.5 / iOS 15.0,尚未用 IPA 核验 |
|
||||
| 风险 | 外部函数显式调用风险、系统调用暴露风险检测,均被机构标为高危 |
|
||||
|
||||
报告汇总写有 7 个检测项目、2 个风险项目,正文只提供这 2 项详情;不能据此推断另外 5 项的具体内容或防护状态。两项各展示 50 条记录,无法确认是否为完整清单或展示上限。
|
||||
|
||||
按报告中“调用方描述 + 被调符号”去重后的统计:
|
||||
|
||||
| 检测项 | 展示记录 | 去重描述 | 符号分布(按展示记录计数) |
|
||||
| --- | ---: | ---: | --- |
|
||||
| 外部函数显式调用 | 50 | 39 | `_dlopen` 1、`_dlsym` 17、`_fopen` 32 |
|
||||
| 系统调用暴露 | 50 | 47 | `_syscall` 2、`_exit` 23、`_fork` 1、`_read` 2、`_write` 14、`_open` 2、`_close` 1、`_unlink` 4、`_getpid` 1 |
|
||||
|
||||
例如 `#0x1013372b4 -> _dlsym` 重复 10 次。去重描述数不等于唯一机器指令数:报告可能以函数入口或内部分析节点表示地址,需向检测机构确认。
|
||||
|
||||
报告证据是静态调用关系,未给出成功 Hook、窃取数据或绕过支付权限的动态复现。保留机构原始评级用于整改管理,同时把“可见调用关系”“防护缺口”“已复现攻击”分别记录。
|
||||
|
||||
### 对报告修复建议的评估
|
||||
|
||||
1. **函数指针 + `optnone`**:可以作为小范围调用隐藏试点,必须检查 Release 机器码和检测机构复测结果。不能直接据此宣称反 Hook 完成。
|
||||
2. **用 `dlsym` 替换全部调用**:本报告本身命中 `_dlsym`,全局替换可能转移或增加命中;首期不采用这种通用处理。
|
||||
3. **把 libc 调用改为 SVC 裸系统调用**:不作为 App Store 主线方案。报告示例涉及私有调用、固定系统调用号,且出现 `PT_DENT_ATTACH` 拼写;不能作为可直接复制的工程实现。文件操作还需要保持错误码、取消、变参等语义。
|
||||
4. **统一包装函数**:只在包装层内部再次直接调用目标函数,可能使扫描命中位置迁移;扫描全 App 时不保证消除命中。
|
||||
5. **注入一个 Defender 库**:可以增加运行时检测,但不会自动改写原主程序及静态链接 SDK 内的现存调用点。
|
||||
|
||||
### 本机编译验证
|
||||
|
||||
环境:Xcode 27.1,Build `27A9275`;iPhoneOS SDK 27.1;目标 ARM64、iOS 15.0。使用显式声明的 `getenv` 做最小实验,不依赖 App 业务代码。
|
||||
|
||||
```c
|
||||
extern char *getenv(const char *);
|
||||
char *direct_call(const char *name) { return getenv(name); }
|
||||
char *pointer_optimized(const char *name) {
|
||||
char *(*fn)(const char *) = getenv;
|
||||
return fn(name);
|
||||
}
|
||||
__attribute__((optnone, noinline))
|
||||
char *pointer_optnone(const char *name) {
|
||||
char *(*fn)(const char *) = getenv;
|
||||
return fn(name);
|
||||
}
|
||||
```
|
||||
|
||||
复现命令(先将以上源码保存为 `call_probe.c`):
|
||||
|
||||
```sh
|
||||
xcrun --sdk iphoneos clang -target arm64-apple-ios15.0 -O2 -S call_probe.c -o call_probe.s
|
||||
```
|
||||
|
||||
观察结果:前两者均为 `b _getenv`;第三者通过 `_getenv@GOTPAGE`、`_getenv@GOTPAGEOFF` 加载地址,再执行 `blr x8`。这证明该工具链下 `optnone` 能保留间接调用,也证明外部符号和 GOT 引用仍存在。该实验仅验证汇编形态,未验证最终链接、LTO、原检测引擎判定或抵御 Hook 的效果。
|
||||
|
||||
## 3. 报告调用点与当前代码的对应关系
|
||||
|
||||
本节路径相对 readoor 根目录;行号为本次核查位置。确认的是当前代码/库存在对应行为,不是所有报告地址已经完成符号化。
|
||||
|
||||
| 报告线索 | 当前证据 | 处理方向 |
|
||||
| --- | --- | --- |
|
||||
| `-[STSCommonUtil convertPcmToWav:wavFilePath:] -> _fopen` | `readoor/BookShelf/Classes/Util/STSCommonUtil.m:1427` 显式 `fopen`,随后 `fwrite/fclose` | 自有源码,选为首个调用隐藏与业务回归试点;属于旧架构,要显式纳入实施范围 |
|
||||
| `GCDWebServerFileRequest writeData:error:` / `dealloc` | `readoor/BookShelf/Classes/Factorys/GCDWebServer/Requests/GCDWebServerFileRequest.m:46,50,61,71` 调用 `unlink/open/write/close` | 源码随仓库提供;维护可重放补丁,回归上传、临时文件与错误路径 |
|
||||
| `GCDWebServerMIMEStreamParser` / `GCDWebServerMultiPartFile` | 同目录 `GCDWebServerMultiPartFormRequest.m:95,155,211,246,288` 对应 `unlink/open/write` | 覆盖流式 multipart 和清理路径,不能仅处理单一入口 |
|
||||
| `IFlySpeechSynthesizerImp`、`IFlyISVMSCHandler`、`IFlyPcmRecorder` | `readoor/BookShelf/Classes/Factorys/XunFei/iflyMSC.framework/iflyMSC` 是多架构静态归档;arm64 未定义符号中确认有 `_fopen`、`_syscall`、`_exit` | 优先供应商升级/重新构建;当前不能仅修改头文件解决库内部调用 |
|
||||
| `ZZFileChannelOutput writeData:error:` | `readoor/BookShelf/Classes/Factorys/ZipZap/libZipZap.a`;`nm -arch arm64 -u` 在 `ZZFileChannelOutput.o` 下确认 `_write/_close` | 取得匹配版本源码重编或升级;需验证现有业务接口和压缩文件行为 |
|
||||
| 匿名 `_dlopen/_dlsym/_syscall/_fork/_exit` 地址及 google 日志函数 | 未取得同次构建产物,未完成归属定位 | 使用原始 IPA、UUID 匹配的 dSYM、Link Map 归因;不按相近名称推测属于某 SDK |
|
||||
| 当前安全守卫的 `exit(0)` | `readoor/3.0/Base/Security/RDSecurityGuard.swift:114` | 当前源码确定存在;尚不能对应报告中某个匿名 `_exit` 地址 |
|
||||
|
||||
静态 SDK 最终可能进入主可执行文件,因此“扫描主程序”与“仅扫描自有业务代码”不是同一个范围。不可默认 LLVM Pass 或源码包装能处理无源码预编译归档。
|
||||
|
||||
## 4. 当前反 Hook 防护的代码核查
|
||||
|
||||
以下为此次额外发现,未声称来自原报告。优先级按修复依赖和防护效果排序,不替代机构的漏洞评级。
|
||||
|
||||
| 优先级 | 代码证据 | 问题及建议 |
|
||||
| --- | --- | --- |
|
||||
| P0 | `RDInjectionDetector.swift:112–116` | 白名单缺失、损坏或 HMAC 不匹配时 `detect()` 返回 `false`,且跳过后续检测。应返回 `unavailable/integrityFailure`,继续执行独立探针,由策略层区分构建缺陷和风险 |
|
||||
| P0 | `RDInjectionDetector.swift:173–176` | Bundle 外非系统镜像被无条件跳过,形成注入检测盲区。改为采集来源、归类和明确例外策略;未知镜像先输出证据,避免将任何未知状态直接升级为退出 |
|
||||
| P0 | `RDInjectionDetector.swift:150–154` | 新格式路径不匹配仍回退 basename 放行,削弱精确路径约束。新格式要求精确匹配,旧格式迁移独立处理;同名不同路径不能相互覆盖 |
|
||||
| P1 | `RDInjectionDetector.swift:128–138` | `DYLD_INSERT_LIBRARIES` 整串前缀检查,未逐项解析。对每个条目单独验证;路径校验需要目录边界和规范化,不能仅靠 `hasPrefix(bundlePath)` |
|
||||
| P1 | `RDSecurityGuard.swift:69,85` | 调试器状态始终为 `false`。增加独立探针,返回 detected/clear/unavailable,Debug、模拟器和 Release 策略分离 |
|
||||
| P1 | `RDSecurityGuard.swift` 与两个 Detector 全文 | 未见 GOT 槽位、关键函数代码完整性、Objective-C IMP 基线检测。镜像名和越狱路径不能覆盖这些 Hook 形式;作为 iOSGuard 后续能力单独验收 |
|
||||
| P1 | `RDAppDelegate.swift:49–52` → `STSAppStartupProcess.m:26–27` → `startForegroundObserver()` | 同一启动链两次检测、两次注册观察者;`observer` 被覆盖,只能移除最后一个 token。统一启动入口,注册幂等,多 Scene 同样处理 |
|
||||
| P1 | `RDSecurityGuard.swift:76,83–89` | 调用线程和后台队列都写 `cachedContext`,缺少统一隔离;后台又执行包含 UIKit 查询的检测。状态通过串行队列/actor 隔离,UI 查询回主线程,避免重复扫描 |
|
||||
| P1 | `RDSecurityGuard.swift:17–20,122–125` | 登录/支付/VIP/激活事件仅见枚举与日志分支,未在当前检索范围发现相应调用点。需在关键操作入口接入实际策略并验证,不能把声明当成已保护 |
|
||||
| P1 | `RDSecurityGuard.swift:79,112–114` | 当前高风险立即 `exit(0)`,既是显式调用点,也让误判变成直接退出。改为风险状态及受限操作策略,确保订单/交易恢复路径完整 |
|
||||
| P2 | `RDJailbreakDetector.swift:132–147` | 同步 `connect` 无显式超时,启动/前台同步扫描可能产生等待。移至有预算的异步检测,默认端口只作弱信号 |
|
||||
|
||||
`AutoPacking/obfuscation/generate_image_whitelist.py` 已有构建期白名单和 HMAC 生成流程。后续优先沿用并修复产物生成时机、路径规则、格式验证,不再并行维护第二套名单。App 内置 HMAC 密钥的设计不应承担服务端信任根职责。
|
||||
|
||||
现有安全守卫注释写“仅输出风险日志”,实现却会退出,实施时须同步代码注释和行为文档。
|
||||
|
||||
## 5. iOSGuard 的实施架构
|
||||
|
||||
### A. 构建期分析与证据链
|
||||
|
||||
优先实现只读 `audit`:解析 `.app/.ipa` 的主程序、嵌入 Framework、dylib 和扩展;记录架构、UUID、哈希、依赖、导入符号、直接调用候选及加密状态。IPA 解包须校验路径、软链接和解压体积;解析失败、加密代码、未知架构输出“不支持/无法验证”,不能输出“通过”。
|
||||
|
||||
每个结果至少包含:binary 相对路径、架构、UUID、调用地址、目标符号、调用方、归属对象/SDK、证据等级、规则版本、整改状态。未定义符号只是导入证据;实际调用点需要反汇编和 stub/绑定关联。使用 Link Map 判断静态对象归属,并通过 UUID 匹配 dSYM;不同构建比较按调用方/符号/所属对象归一化,不按绝对地址比较。
|
||||
|
||||
交付 JSON 明细与 Markdown 汇总,支持基线差异和失败退出码。先覆盖报告中的符号集,保留扩展规则接口。
|
||||
|
||||
### B. 源码调用保护
|
||||
|
||||
第一阶段以少量 C/Objective-C 包装和编译产物检查试点。仅保护确定需要保护的调用,保持函数签名、ABI、错误码、变参和线程语义。`open` 的 mode 参数、`read/write` 的短读短写、`EINTR` 等必须有行为测试;不能批量正则替换。
|
||||
|
||||
Release 必须检查最终机器码;评估 LTO、dead strip 和实际发布参数。包装可改变调用形态,但不能作为 GOT/Inline Hook 的替代防护。第三方源码补丁要有版本锁定与升级检查;无源码 SDK 独立列为供应商依赖。
|
||||
|
||||
LLVM Pass 放在手工试点有效之后,先验证所用 Xcode/LLVM 工具链兼容性;Swift、预编译 SDK 不默认拥有同等覆盖。
|
||||
|
||||
### C. 运行时 Defender
|
||||
|
||||
推荐首期通过源码或静态库接入,输出结构化风险结果。探针与处置分离:
|
||||
|
||||
- 镜像、白名单完整性与调试状态:优先实现,支持启动、前台和关键操作前检查。
|
||||
- GOT/符号地址:记录允许的提供方和镜像范围,区分合法转发、懒绑定与非预期重绑定;明确 PAC、chained fixups、共享缓存及架构支持范围,未支持状态不能算安全。
|
||||
- 关键自有代码完整性:选定小范围、稳定函数,建立与构建产物绑定的基线。运行后才采集的基线可能已经被篡改,不能作为唯一可信基线。
|
||||
- Objective-C 关键 IMP:仅保护明确的业务方法,显式容纳合法 swizzling;不能将所有方法实现变化判为攻击。
|
||||
- 已知工具/越狱线索:作为组合证据,不能只靠固定名称、端口或少量文件判定安全。
|
||||
|
||||
设计返回 `clear / detected / unavailable` 与 reason code、证据和检查时间。耗时检测有预算,异步刷新有有效期,关键交易不能无限使用旧缓存。Debug 和测试模式单独配置,Release 不允许残留测试绕过开关。
|
||||
|
||||
先采用观察模式验证正常用户误判,再启用明确的能力限制。支付授权、权益和订单状态仍由服务端验证;若后续增加设备证明,需作为单独的客户端/服务端工作流设计,不能声称当前项目已经支持。
|
||||
|
||||
### D. 二进制后处理与签名
|
||||
|
||||
待源码路径和 SDK 覆盖边界明确后再启动。首期不做全局段平移、Objective-C 元数据清空或自动改写所有系统调用。此类变更须逐项解决重定位、chained fixups、异常展开、指针认证、签名和 dSYM 对应关系。
|
||||
|
||||
如确需无源码方案,先限制输入架构、未加密二进制和可验证的加载空间,明确拒绝不支持的输入,产物始终另存。Defender 注入完成只代表库加载成功;原报告调用点是否减少仍需单独验证。
|
||||
|
||||
## 6. 分阶段实施与完成条件
|
||||
|
||||
| 阶段 | 主要产物 | 完成条件 |
|
||||
| --- | --- | --- |
|
||||
| M0 基线闭环 | 原报告记录清单、原 IPA/dSYM/Link Map、目标构建配置及 SDK 清单 | 核对 MD5/UUID;每条报告记录有确定归属或明确“待定位”;确认机构扫描范围、判定规则及完整命中清单 |
|
||||
| M1 只读审计 | `core/macho` 解析、`cli` audit、JSON/Markdown 差异报告、测试样本 | 正常/损坏/加密/多架构输入均有明确结果;导入符号与调用指令分开统计;可重现原报告的一部分并解释差异 |
|
||||
| M2 防护修复与接入 | Defender 基础探针、readoor 检测状态与策略、白名单修复、启动去重 | 白名单损坏不再等同安全;重复启动无重复观察者;并发、线程及超时测试通过;正常真机关键流程通过 |
|
||||
| M3 调用保护与依赖整改 | `STSCommonUtil`/GCDWebServer 试点、第三方版本/重编方案、Release 反汇编证据 | 同引擎验证试点是否减少命中;音频、上传、解压行为无回归;无源码剩余项明确列出,不以主工程修改代替 |
|
||||
| M4 深入反 Hook 与验收 | GOT/IMP/关键代码检测、受控动态测试记录、最终 IPA 与复测报告 | 已定义的 Hook 场景被检测并按策略处置;正常样本无已知误拦截;报告两项逐条复测闭环;残余项获得明确结论 |
|
||||
|
||||
依赖:M0 → M1;M2 可在目标构建确认后与审计开发交错推进;M3 依赖 M1 和机构试点反馈;M4 依赖实际 SDK、机器码与运行时验证结果。首个 PoC 不需要先完成 VMP、资源加密或 Class-Dump 改造。
|
||||
|
||||
建议实施时创建以下模块(目前均未实现):`core/macho` 只读解析、`cli` 审计入口、`defender` 探针与结果模型、`tests` 格式及运行时测试、`examples/readoor` 接入说明。readoor 修改遵守其 `AGENTS.md` 和对应开发 Skill;旧架构及第三方源码变更在任务中显式列出。
|
||||
|
||||
## 7. 验收矩阵
|
||||
|
||||
| 维度 | 必测场景 | 通过标准 |
|
||||
| --- | --- | --- |
|
||||
| 报告复测 | 原始与整改 IPA、同引擎/同规则,覆盖主程序和依赖 | 逐条定位与复测;两项按机构标准关闭,或保留正式残余风险;本地审计零命中不替代机构报告 |
|
||||
| 编译产物 | 实际 Release 优化、LTO 配置及各发布架构 | 预期间接调用保留;新包装层及 Defender 自身亦纳入扫描;无新增不允许的系统调用依赖 |
|
||||
| 白名单 | 缺失、格式错、摘要错、同名不同路径、Bundle 外镜像、多条环境变量 | 返回明确状态并执行对应策略;可重复回归,不只检查正常样本 |
|
||||
| Hook | 受控测试中的动态库注入、GOT 重绑定、指定自有函数补丁、关键 IMP 替换 | 各场景独立记录覆盖结果、延迟和策略行为;不以 Frida 端口命中代替所有测试 |
|
||||
| 正常环境 | 真机冷启/前台、多 Scene、测试设备、允许的 SDK swizzling、无网 | 无已知误退出或误拦截;不破坏合法调试配置 |
|
||||
| 核心功能 | 登录、购买、支付回调、激活、录音/语音合成、PCM/WAV、文件上传/解压 | 功能正确,失败可恢复,订单状态一致;测试与报告对应的 SDK 路径 |
|
||||
| 并发与性能 | 重复启动、并发检查、探针超时、后台刷新、生命周期 | 无状态数据竞争和重复 observer;测量首屏/回前台耗时及 p95 后确定预算,不预设未经测量的保证值 |
|
||||
| 分发 | 最终签名、安装、升级、崩溃符号化 | 实际目标配置真机验证通过;构建和签名成功本身不等于安全检测通过 |
|
||||
|
||||
后续 Swift/Objective-C/工程修改按 readoor 规则先执行其规定的 `readoor31` 构建;ECNUP 最终验收仍需使用配置 `306` 对应的实际归档流水线,不能以默认 scheme 的通过代替产品包验证。
|
||||
|
||||
## 8. 本轮交付与待补输入
|
||||
|
||||
已完成:报告文本提取与去重统计、指定源码调用核查、第三方静态库符号核查、现有防护调用链审查、ARM64 优化实验、实施路线与验收矩阵。只新增本文并更新 iOSGuard README 的实现状态和入口;未修改 readoor,也未运行完整 App 构建或真机安全测试。
|
||||
|
||||
进入 M0 时需要补齐:原始被测 IPA;对应 dSYM、Link Map(如当时未保留,须说明不能精确还原);原构建配置与依赖版本;检测机构完整条目和规则口径、是否接受间接调用的试点复测。无源码 SDK 获取受限或检测规则不接受公开 API 路径时,应明确记录阻塞项和替代路线,不能承诺仅注入防护库即可消除全部报告问题。
|
||||
@@ -0,0 +1,90 @@
|
||||
# 静态 SDK fopen 重定向 PoC
|
||||
|
||||
日期:2026-11-10。用途:验证无 SDK 源码时的调用转发链路;不代表已经具备完整反 Hook 能力或通过报告复测。
|
||||
|
||||
后续扩展:核心实现现已移至 `redirect_symbols.py`,支持 JSON 多符号映射,桥接扩展至 7 个固定签名函数。本文记录初始 fopen 验证;原 `redirect_fopen.py` 命令保留兼容,最新用法和范围见 [通用重定向工具](07_GENERIC_STATIC_SDK_REDIRECT.md)。
|
||||
|
||||
## 1. 已实现的调用链
|
||||
|
||||
```text
|
||||
SDK 对象的 _fopen 未定义符号
|
||||
→ 改写为 _IG_fopen(保持符号索引和重定位记录不变)
|
||||
→ App 链接 IGFileBridge.c
|
||||
→ IG_fopen 原样传递 path/mode
|
||||
→ 通过函数指针调用系统 fopen
|
||||
→ 原样返回 FILE * 或 NULL
|
||||
```
|
||||
|
||||
`defender/call_bridge/IGFileBridge.c` 不记录日志、不扫描环境、不分配额外业务状态、不主动拦截。正常系统调用后的返回路径不调用其他函数,因此不主动改写其 errno。签名和返回的 FILE 指针保持与系统接口一致,可交给系统 `fread/fwrite/fclose`。这只是透明转发实现,不保护系统函数实现或 GOT 不被 Hook。
|
||||
|
||||
`optnone/noinline` 用于在当前 Clang 下保留独立入口和间接调用;最终 Release 的优化、LTO、链接行为仍须重新验收。不能承诺符号不可见或任意检测引擎都不命中。
|
||||
|
||||
## 2. 工具边界与工作方式
|
||||
|
||||
入口:`tools/static_sdk_redirect/redirect_fopen.py`。环境:macOS、Python 3、Xcode 的 `lipo/ranlib`;不依赖本机未安装的 `llvm-objcopy`。
|
||||
|
||||
1. 接受 BSD ar 静态归档,或从 fat 文件提取 arm64 静态归档。
|
||||
2. 检查成员为 little-endian ARM64 `MH_OBJECT`,遍历 `LC_SYMTAB`。
|
||||
3. 仅将普通外部未定义符号 `_fopen` 的字符串索引改为新增的 `_IG_fopen` 名称。保留其他符号索引、section、机器码和重定位数据;更新字符串表长度。
|
||||
4. 重新组装归档,用 `ranlib` 重建索引。输出 JSON 记录成员及输入/输出 SHA-256。
|
||||
5. 写入新文件;拒绝原地覆盖、覆盖已有输出、目标符号冲突或重复处理。任何成员不支持则整个操作失败。
|
||||
|
||||
只支持已验证的有限布局:字符串表在对象末尾,允许不超过 7 字节的全零或全换行归档填充。允许 `__LLVM,__bitcode/__cmdline` 中单字节零值的占位标记并原样保留;拒绝实际 LLVM IR/bitcode、未知 LLVM section、arm64e、32 位、动态库、对象签名、GNU 长名称归档及其他未知格式。该工具是小范围 PoC,不是通用 Mach-O 重写器。
|
||||
|
||||
输出是 **arm64 真机 `.a`**,不包含原库的 armv7/x86_64,也不构成可直接替换全部目标的完整 Framework/XCFramework。模拟器必须独立处理;不能把真机归档用于 ARM64 模拟器。
|
||||
|
||||
## 3. 复现方式
|
||||
|
||||
以下命令只写入新建临时目录;保留原讯飞库。命令需整体在同一 shell 中执行,脚本失败即停止。
|
||||
|
||||
```sh
|
||||
set -e
|
||||
cd /Users/shenlei/Work/ReadBook/iOSGuard
|
||||
IG_POC_DIR="$(mktemp -d /private/tmp/iosguard-fopen.XXXXXX)"
|
||||
|
||||
python3 tools/static_sdk_redirect/redirect_fopen.py \
|
||||
/Users/shenlei/Work/ReadBook/readoor/readoor/BookShelf/Classes/Factorys/XunFei/iflyMSC.framework/iflyMSC \
|
||||
"$IG_POC_DIR/iflyMSC.redirected.a" > "$IG_POC_DIR/report.json"
|
||||
|
||||
xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=15.0 \
|
||||
-O2 -Wall -Wextra -Werror -c defender/call_bridge/IGFileBridge.c \
|
||||
-o "$IG_POC_DIR/IGFileBridge.ios.o"
|
||||
|
||||
xcrun ld -r -arch arm64 -platform_version ios 15.0 27.1 \
|
||||
-all_load "$IG_POC_DIR/iflyMSC.redirected.a" "$IG_POC_DIR/IGFileBridge.ios.o" \
|
||||
-o "$IG_POC_DIR/iflyMSC.combined.o"
|
||||
|
||||
python3 -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
`ld` 示例的 SDK 版本 `27.1` 是本次实际环境;更换 Xcode 后按实际 SDK 调整。`ld -r` 是可重定位链接检查,保留其他未解析的系统/依赖符号,不等于最终 App 完整链接或运行通过。
|
||||
|
||||
## 4. 已完成验证
|
||||
|
||||
环境:ARM64 Mac,Xcode 27.1,iPhoneOS SDK 27.1。
|
||||
|
||||
| 验证 | 实际结果 | 限制 |
|
||||
| --- | --- | --- |
|
||||
| 测试静态归档 + 原始系统调用 | 文件写入、读取、追加、截断、中文路径、ENOENT、4 线程各 20 轮均通过 | Mac 上的自建 SDK 替身,不是讯飞业务 |
|
||||
| 同一归档重定向 + IGFileBridge | 同样的行为测试通过;原始输入不变;重复处理/覆盖被拒绝 | 未模拟磁盘满、真实设备权限等所有失败条件 |
|
||||
| 格式和拒绝路径 | 截断、符号冲突、定义符号、动态库、实际 bitcode、异常尾部等测试通过 | 测试集不等于完整解析器安全审计 |
|
||||
| 讯飞实际 arm64 归档副本 | 检查 380 个对象成员;25 条 `_fopen` 未定义符号引用改为 `_IG_fopen` | 25 是对象符号引用数,不是机器指令调用次数,也不代表最终 App 会链接全部对象 |
|
||||
| 讯飞符号前后对比 | SDK 副本 `_fopen` 25 → 0,`_IG_fopen` 0 → 25;`_syscall` 13、`_exit` 1 保留 | 最终 App 的桥接实现仍引用系统 `_fopen` |
|
||||
| 讯飞副本 + iOS bridge 对象 | `ld -r -all_load` 成功 | 未完整链接 readoor、未执行 SDK、未完成真机回归 |
|
||||
| iOS ARM64 优化汇编 | bridge 保留 `fopen@GOTPAGE` 加载和 `blr` 间接调用 | 存在 GOT 引用,不能声称防止重绑定或 Inline Hook |
|
||||
| 原始 SDK | SHA-256 前后相同 | 未改 readoor 工程和依赖 |
|
||||
|
||||
原始讯飞 SDK SHA-256:`b368fa4866d274da0c6e89607e9d5b95b4a59d49c183eb68c947ac2b50ff3c2c`。归档索引元数据可能受工具影响,重建后不要求整个输出文件哈希跨构建相同;每次记录本次输入和输出即可。
|
||||
|
||||
## 5. 后续 readoor 接入方式
|
||||
|
||||
本次没有修改 readoor。真正接入需要单独的目标配置或隔离分支,遵守该仓库开发流程:
|
||||
|
||||
1. 保留原 iflyMSC 头文件与必要资源,将 arm64 真机配置的链接输入切换为改写归档。
|
||||
2. 将 `IGFileBridge.c/.h` 加入相同 target;桥接文件不参与符号改写,不定义同名系统 `fopen`。
|
||||
3. 同一 target 不同时链接原始 iflyMSC 二进制和改写归档;检查 `-framework iflyMSC`、Link Binary With Libraries、其他静态依赖及 `-ObjC/-force_load` 实际设置,避免重复定义或误链接原版本。
|
||||
4. 检查生成的 Link Map,确认实际选中的归档,以及 `_IG_fopen` 正好由桥接实现提供。仅依赖源码中“已配置”不算接入成功。
|
||||
5. 构建实际 ECNUP Release,回归讯飞录音、语音合成、文件保存及错误恢复,并比较加固前后性能。
|
||||
6. 送同引擎复测。若扫描仍识别包装层的系统引用,应记录失败并调整路线,不能把静态库内 `_fopen` 数量变成零当作整个 App 风险已关闭。
|
||||
|
||||
首轮只验证 `fopen`。`syscall` 的变参/调用号、`exit` 的不返回语义均需要独立设计,不能套用当前实现。GOT、IMP、Inline Hook 的实际防护也不包含在本 PoC 中。
|
||||
@@ -0,0 +1,80 @@
|
||||
# 通用静态 SDK 符号重定向
|
||||
|
||||
日期:2026-11-10。当前是有限格式下可复用的构建工具,不是任意 IPA 的通用加固器。
|
||||
|
||||
## 实现范围
|
||||
|
||||
将此前硬编码 `_fopen → _IG_fopen` 的解析逻辑改为 JSON 映射驱动。对不同 SDK 使用不同映射,同一次处理可重定向多个外部 C 符号。核心 `redirect_symbols.py` 不包含讯飞对象名或业务特例,旧 `redirect_fopen.py` 作为仅处理 fopen 的兼容命令保留。
|
||||
|
||||
通用的是**归档与符号处理**;调用转发仍须按真实函数签名实现。不能通过一个 `void *` 或任意变参入口安全地承接所有函数。符号改写工具无法从名字验证参数、返回值、可变参数、错误状态、线程取消或不返回语义。
|
||||
|
||||
| 层 | 当前能力 | 扩展方式 |
|
||||
| --- | --- | --- |
|
||||
| 重定向引擎 | 映射驱动,精确匹配外部未定义 C 符号;重建归档索引;报告每个符号、每个成员的改写量 | 新 SDK 先检查二进制格式,再选择映射 |
|
||||
| 映射配置 | 标准 I/O 与 POSIX I/O 两组;支持自定义 JSON | 配置使用实际 Mach-O 名称,含前导下划线 |
|
||||
| C 桥接 | `fopen/fclose/fread/fwrite/read/write/close` | 新函数需新增准确声明、实现和行为测试 |
|
||||
| 业务接入 | 独立输出归档,原文件不变 | target 切换链接输入并添加桥接代码;检查 Link Map |
|
||||
|
||||
所有桥接均为直接参数转发、局部函数指针、`optnone/noinline`。不加日志、自动重试、短读短写补齐、策略拦截。`syscall`、`open` 变参、`exit`、ObjC 方法、C++ 符号不在自带桥接覆盖范围内;自定义映射不能代替桥接实现和 ABI 审查。
|
||||
|
||||
## 配置与命令
|
||||
|
||||
`tools/static_sdk_redirect/mappings/stdio.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"_fopen": "_IG_fopen",
|
||||
"_fclose": "_IG_fclose",
|
||||
"_fread": "_IG_fread",
|
||||
"_fwrite": "_IG_fwrite"
|
||||
}
|
||||
```
|
||||
|
||||
`mappings/posix_io.json` 提供 `_read/_write/_close`。若需同时处理两组,将各键合并到一个 JSON,**一次处理原始库**,不要把已改写库当作重复处理输入。
|
||||
|
||||
下面使用新建临时目录处理当前讯飞静态 SDK 副本:
|
||||
|
||||
```sh
|
||||
set -e
|
||||
cd /Users/shenlei/Work/ReadBook/iOSGuard
|
||||
IG_GENERIC_DIR="$(mktemp -d /private/tmp/iosguard-generic.XXXXXX)"
|
||||
|
||||
python3 tools/static_sdk_redirect/redirect_symbols.py \
|
||||
/Users/shenlei/Work/ReadBook/readoor/readoor/BookShelf/Classes/Factorys/XunFei/iflyMSC.framework/iflyMSC \
|
||||
"$IG_GENERIC_DIR/iflyMSC.stdio.a" \
|
||||
--mapping tools/static_sdk_redirect/mappings/stdio.json \
|
||||
--require-all > "$IG_GENERIC_DIR/report.json"
|
||||
```
|
||||
|
||||
默认允许某些配置项在该 SDK 中不存在,但 JSON 报告明确列入 `unmatched_symbols`;所有项均未命中时失败。`--require-all` 要求每项至少命中一次,否则不生成输出,适合已知版本 SDK 的 CI 检查。
|
||||
|
||||
遇到空配置、非法 C 符号名、重复 JSON 键、自映射、链式映射、循环映射、多个源共用一个目标、归档已含目标符号、源符号有定义、格式不支持或已有输出文件均失败。报告的 `symbol_counts` 统计对象符号表条目,不是指令调用次数。
|
||||
|
||||
工具只输出改写后的静态库,不自动链接或嵌入桥接。target 必须链接 `defender/call_bridge/IGFileBridge.c`,或提供自定义映射对应的兼容实现。桥接代码不能参与重定向,否则可能造成自调用递归。同一 target 不要同时链接 SDK 原二进制与其改写副本。
|
||||
|
||||
## 已验证与未覆盖
|
||||
|
||||
15 项自动化测试通过:
|
||||
|
||||
- 原 fopen 行为与旧 CLI 保持可用。
|
||||
- 同一对象中 7 个符号同时重定向,链接运行正确,逐符号计数符合预期。
|
||||
- 同一行为测试分别链接原始库与改写库;二进制文件读写、追加、截断、中文路径、4 线程各 20 轮通过。
|
||||
- POSIX 管道短读、零字节读写、EOF、无效描述符 EBADF、非阻塞管道满时 EAGAIN/EWOULDBLOCK 保持行为。
|
||||
- 配置错误、重复键、冲突、严格模式缺项、全部未命中、已有输出、重复处理及格式拒绝路径得到验证。
|
||||
|
||||
当前真实讯飞 SDK 检查 380 个对象成员,标准 I/O 四符号配置共改写 95 条符号引用:`_fopen` 25、`_fclose` 30、`_fread` 17、`_fwrite` 23;`nm` 对照及 iOS ARM64 `ld -r -all_load` 可重定位链接验证通过。该检查不等于 readoor 完整链接、SDK 真机运行或报告复测。
|
||||
|
||||
不支持动态 Framework、IPA 中最终可执行文件、arm64e、32 位、GNU 长名称归档和实际 bitcode;fat 静态库只提取 arm64,输出不包含其他架构。保留初始 PoC 对 Mach-O 布局的限制,详见 [初始实现](06_STATIC_SDK_FOPEN_POC.md)。当前 SDK 验证是 iPhoneOS 真机切片;ARM64 Mac 测试不等于 iOS 模拟器支持声明。
|
||||
|
||||
基础行为测试未覆盖全部函数语义,例如磁盘满、EINTR、线程取消、全部短写模式、目标 App 优化/LTO 组合及 SDK 自校验。正式接入仍需各 SDK 的业务回归。
|
||||
|
||||
桥接的间接调用仍可保留 GOT 引用。多符号改写仅扩大调用转发覆盖面,不自动提供 GOT/Inline Hook 防护,也不保证原检测报告清零。新增映射应按“实现桥接 → 行为测试 → SDK 副本改写 → 真机业务回归 → 同引擎复测”逐步验收。
|
||||
|
||||
## 本地验证命令
|
||||
|
||||
```sh
|
||||
cd /Users/shenlei/Work/ReadBook/iOSGuard
|
||||
python3 -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
本机 ARM64 Mac 原生编译和运行测试需要 Xcode;其他平台会跳过原生测试,不能把跳过结果当作链接或运行通过。此次未修改 readoor、替换其 SDK 或改变签名产物。
|
||||
@@ -0,0 +1,84 @@
|
||||
# 08 · readoor31 ZipZap 重定向接入试点验证
|
||||
|
||||
日期:2026-11-10
|
||||
范围:`readoor-test` 副本(原工程未动)。readoor31 target,Release / iphoneos / arm64,Xcode iPhoneOS 27.1 SDK。
|
||||
|
||||
## 1. 结论
|
||||
|
||||
**链接前重定向在真实 App 构建中打通**:改写后的 libZipZapGuard.a + 桥接代码已编入 readoor31 最终二进制,ZipZap 对 `_write`/`_close` 的直接调用全部改道为 `bl _IG_write` / `bl _IG_close`,桥接内部为 GOT 取址 + `blr` 间接调用。构建成功,导入符号表与基线完全一致。
|
||||
|
||||
这不是"隐藏系统调用":`_write`/`_close` 仍是导入符号(桥接自身引用),扫描导入表/GOT 的检测器仍可见。边界见 §5。
|
||||
|
||||
## 2. 事实修正
|
||||
|
||||
- readoor31 **确实链接 ZipZap**:链接命令为 `-lZipZap`(经 LIBRARY_SEARCH_PATHS 解析到 `readoor/BookShelf/Classes/Factorys/ZipZap/libZipZap.a`)。早期用完整文件名 grep 日志导致误判。
|
||||
- 讯飞 iflyMSC 未被 readoor31 链接(仅旧 readoor target 使用,且该 target 打包失败),故本试点改用 ZipZap。
|
||||
- 原库为 **fat armv7+arm64**;重定向工具仅支持 arm64,armv7 切片原样保留。
|
||||
|
||||
## 3. 接入方式(零 pbxproj 改动)
|
||||
|
||||
```
|
||||
IGFileBridge.c ──clang -arch arm64 -miphoneos-version-min=15.0──▶ IGFileBridge.o
|
||||
IGFileBridge.o ──ar r──▶ libZipZapGuard.a # 桥接随库分发,App 无需加编译源
|
||||
原库 armv7 切片 + 改写库(arm64) ──lipo -create──▶ fat
|
||||
cp fat ──▶ readoor-test/.../ZipZap/libZipZap.a # 原位替换,工程引用不变
|
||||
```
|
||||
|
||||
- 原库备份:`test-results/baseline/libZipZap.a`(sha256 `5caa6101…`,与 redirect-report 的 source_sha256 一致)。
|
||||
- 回退:把备份拷回原路径重新构建即可。
|
||||
|
||||
## 4. 验证证据(基线 vs 加固)
|
||||
|
||||
| 项 | 基线(BUILD SUCCEEDED) | 加固(BUILD SUCCEEDED) |
|
||||
| --- | --- | --- |
|
||||
| `writeData:error:` 内调用 | `bl 0x100e7add8 ; stub for: _write` | `bl _IG_write` |
|
||||
| `ZZFileChannelOutput close` 内调用 | `bl 0x100e7989c ; stub for: _close` | `bl _IG_close` |
|
||||
| `_IG_write` / `_IG_close` 定义 | — | `T` @ 0x100c21d60 / 0x100c21da4 |
|
||||
| 桥接函数体 | — | `adrp+ldr`(GOT/literal pool 取 `_write`/`_close` 地址)→ 栈存 → `blr x8`;`optnone` 生效,未被直连化 |
|
||||
| 导入符号表 | 3586 项 | 3586 项,diff 为空 |
|
||||
| dead_strip | `ZZFileChannelOutput` 方法保留 | 同左,另有 `_IG_*` 两个新本地符号 |
|
||||
|
||||
关键机器码(加固版 `_IG_close`):
|
||||
```
|
||||
adrp x8, … ; ldr x8, [x8, #0xc10] ; literal pool symbol address: _close
|
||||
str x8, [sp] ; ldr x8, [sp] ; … ; blr x8
|
||||
```
|
||||
|
||||
资产:
|
||||
- 基线:`test-results/baseline/`(原库、undefined 列表、44M Link Map、构建日志、metadata)
|
||||
- 加固:`test-results/guarded/`(undefined 列表、链接命令、构建日志 `test-results/guarded-build.log`)
|
||||
- 改写报告:`readoor-test/iOSGuardIntegration/redirect-report.json`(19 成员中 1 个改动,2 处引用)
|
||||
|
||||
## 5. 边界与风险
|
||||
|
||||
1. `_write`/`_close` 仍为导入符号:桥接 GOT 引用 + App 其他代码使用;跟踪间接调用的检测器可还原调用链。
|
||||
2. armv7 切片原样保留,仍引用原系统符号,不享有本次重定向效果;当前构建只验证 arm64,未验证 armv7 构建。
|
||||
3. 模拟器切片未覆盖(原库本就无 simulator 架构,行为不变)。
|
||||
4. 未做真机功能回归(书籍解压/下载流程依赖 ZipZap 写文件);未提交检测引擎复测。
|
||||
5. 本试点只覆盖 `_write`/`_close` 两个符号;fopen 系列在 readoor31 链接路径上的候选库(如 StsPDF 系列内核库,基线中有 401 个符号入库)尚未处理。
|
||||
|
||||
## 6. 复现命令
|
||||
|
||||
```bash
|
||||
# 从未改写的备份抽取 arm64,输出新库;不要重复重定向已替换的库。
|
||||
lipo test-results/baseline/libZipZap.a -thin arm64 -output /tmp/ig-zipzap-original-arm64.a
|
||||
python3 tools/static_sdk_redirect/redirect_symbols.py \
|
||||
/tmp/ig-zipzap-original-arm64.a /tmp/ig-zipzap-redirected-arm64.a \
|
||||
--mapping tools/static_sdk_redirect/mappings/zipzap.json
|
||||
|
||||
# 桥接注入 + fat 合并 + 原位替换(见 §3)
|
||||
xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=15.0 -Os \
|
||||
-c readoor-test/iOSGuardIntegration/IGFileBridge.c -o IGFileBridge.o
|
||||
# … ar r / lipo -create / cp(工作目录产物在 test-results/.work/)
|
||||
|
||||
# 构建
|
||||
cd readoor-test && xcodebuild build -workspace readoor.xcworkspace -scheme readoor31 \
|
||||
-configuration Release -sdk iphoneos \
|
||||
-derivedDataPath ../test-results/DerivedData
|
||||
```
|
||||
|
||||
## 7. 下一步
|
||||
|
||||
1. 真机安装加固版 readoor31.app,回归书籍下载/解压/阅读流程。
|
||||
2. 用原检测引擎复测,确认 ZipZap 对应命中变化。
|
||||
3. 视结果扩大映射(StsPDF 内核库的 fopen 系列是下一个候选)。
|
||||
@@ -0,0 +1,95 @@
|
||||
# 09 · ECNUP 报告整改方向结论
|
||||
|
||||
日期:2026-11-10。状态:方向判断与架构设计。**尚未向 V4.6.6 提交任何加固包复测**,下文"能过检"均为待验证假设,不是已验证结果。
|
||||
|
||||
> 进展:本文 §5 收敛的改写引擎已建成,并在真实目标上**自测第 1 层清零(336 → 0)**、结构合法可签——见 [10](10_MACHO_GUARD_SELFTEST.md)。送检 V4.6.6 仍未做。
|
||||
|
||||
关联:报告分析见 [05](05_READOOR_SECURITY_REMEDIATION_PLAN.md),重定向工具见 [07](07_GENERIC_STATIC_SDK_REDIRECT.md),试点验证见 [08](08_ZIPZAP_PILOT_BUILD_VERIFICATION.md)。
|
||||
|
||||
## 1. 从报告修复示例推导的检测假设
|
||||
|
||||
报告(ECNUP外语 2.197.2,引擎 V4.6.6)两个高危项——"外部函数显式调用风险"(`_fopen/_dlopen/_dlsym`)与"系统调用暴露风险"(`_write/_read/_open/_close/_exit/_fork/_syscall/_unlink/_getpid`)——**其官方修复示例是函数指针方式**:
|
||||
|
||||
```c
|
||||
typedef char* (*GET_ENV_TYPE)(const char *);
|
||||
static inline int __attribute__((optnone)) IJMCheckInsertLib() {
|
||||
GET_ENV_TYPE get_env = getenv; // ← 仍然引用 getenv 符号
|
||||
char *env = get_env("DYLD_INSERT_LIBRARIES");
|
||||
}
|
||||
```
|
||||
|
||||
**关键推论**:该示例修复后,`getenv` 仍是导入符号(导入表里还在),消失的只是"直接调用关系"(调用点不再是 `bl stub(getenv)`,而是取函数指针后 `blr`)。
|
||||
|
||||
据此提出假设:**V4.6.6 可能关注调用点的直接分支关系**,因此优先验证消除第 1 层(见 §3)的方案。报告示例不足以证明引擎的完整规则,也不能排除其跟踪桥接、间接调用或导入表的能力。
|
||||
|
||||
> 证据强度:这是从报告自带示例 + `optnone` 提示反推的结论,与 docs/08 试点一致(桥接后调用点变 `bl _IG_write`,而 `_write` 仍在导入表且导入表 diff 为空,构建通过)。最终仍以 V4.6.6 复测为准。
|
||||
|
||||
## 2. 方向结论:链接后 Mach-O 调用点改写器
|
||||
|
||||
报告展示 100 条记录(50 外部函数 + 50 系统调用),涉及讯飞、GCDWebServer、glog、Sts PDF 内核、ZipZap 及匿名地址。源码可用性需逐库确认,例如工程中有 GCDWebServer 源码,不能一概认定第三方库均无法重编译。
|
||||
|
||||
由此排除与选定:
|
||||
|
||||
| 方向 | 能否覆盖报告 | 结论 |
|
||||
| --- | --- | --- |
|
||||
| 源码改函数指针(报告示例) | 部分 | 适用于可以修改并重编译的源码;各库情况需单独确认 |
|
||||
| 链接前静态库重定向(07/08) | 部分 | 仅限能拿到 `.a` 且格式受支持的库;动态 framework、已编入 Pods 的二进制覆盖不到 |
|
||||
| **链接后 Mach-O 调用点改写(自研核心)** | **待复测** | 可统一处理受支持 arm64 格式中的目标直接分支;不覆盖全部架构和调用形态 |
|
||||
|
||||
**选定链接后改写器**(规划 `tools/macho_guard`),形态即"类易盾":输入 `.app`/IPA → 遍历每个 Mach-O 的 arm64 切片 → 定位命中符号的 `bl → __stubs` 调用点 → 改写为 `bl IG_*`(桥接蹦床注入新段)→ 逐级重签名。桥接仍按真实签名实现(07 已覆盖 7 个,需补 `open`变参/`unlink/exit/getpid/fork` 与 `syscall` 专用蹦床)。
|
||||
|
||||
## 2.5 实测:appstore.ipa 改写面(2026-11-10)
|
||||
|
||||
项目根目录 `appstore.ipa`(readoor31OtherPay **v2.199.0**,`com.ecnup.aSCLdl2`,arm64 单切片)经解包核查:
|
||||
|
||||
- **`cryptid 0`**:导出的 archive 包,`__TEXT` 明文未加密——链接后改写器可直接操作(App Store 下载包才会被 Apple 加 FairPlay,那种需先脱壳)。这是整个方向可行的硬前提,已在真实包上确认。
|
||||
- 自研扫描脚本按上述假设运行直接分支规则:扫 `__text` 全部 `bl/b → __stubs` 分支,主二进制命中报告涉及的 12 个符号共 **336 处直接调用点**:
|
||||
|
||||
| 符号 | 数 | 符号 | 数 | 符号 | 数 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `_exit` | 96 | `_open` | 21 | `_unlink` | 8 |
|
||||
| `_fopen` | 86 | `_dlsym` | 18 | `_read` | 7 |
|
||||
| `_close` | 67 | `_write` | 16 | `_dlopen`/`_syscall` | 2/2 |
|
||||
| | | `_getpid` | 12 | `_fork` | 1 |
|
||||
|
||||
报告每类展示 50 条,是否截断及完整记录数尚未确认。当前 IPA 的版本及 Bundle ID 与报告不同;336 是当前样本的本地统计,不能据此证明复现了 V4.6.6 的规则。
|
||||
|
||||
- 逐点清单(site 地址 / 符号 / 分支类型):`test-results/appstore-callsites.csv`(336 行)。注意该 release 包已 strip(仅 594 函数符号),无法从符号表还原 ObjC 方法名;报告的方法名来自解析 ObjC 元数据,改写任务不需要名字,用 site 地址即可。
|
||||
|
||||
## 3. 检测面分层与升级阶梯
|
||||
|
||||
| 层 | 检测方式 | 本次是否需要处理 |
|
||||
| --- | --- | --- |
|
||||
| 1. 调用点直接分支 `bl stub` | 调用点模式匹配 | **优先验证**——是否足以解决报告仍待 V4.6.6 复测 |
|
||||
| 2. 导入表/GOT 条目 | `nm -u`、imports 扫描 | 否(报告示例自身不消除此层) |
|
||||
| 3. 符号名字符串 | strings 扫描 | 否 |
|
||||
| 4. 间接调用可追踪性 | 交叉引用、轻量模拟 | 否 |
|
||||
|
||||
对应升级阶梯(仅当复测仍命中才向下走,不预先加码):
|
||||
|
||||
```
|
||||
桥接改写(消除第1层)──送检 V4.6.6──┬─ 过 → 收工,成本最低【当前判断落点】
|
||||
└─ 仍命中 → A: dlsym表+名字加密(消第2、3层)
|
||||
└─ 仍命中 → B: raw svc 内联(消第4层进 libSystem)
|
||||
└─ 仍命中 → C: 桥接 VMP/控制流平坦化
|
||||
```
|
||||
|
||||
A/B/C 的代价与边界(变参、errno 手工处理、arm64 调用号锁定、`svc` 字节本身不可消除等)见本轮讨论,**在验证桥接即过之前不实现**。
|
||||
|
||||
## 4. 必须如实说明
|
||||
|
||||
1. **未复测**:readoor ZipZap 试点(08)与任何 ECNUP 加固包都未提交 V4.6.6。"桥接即过"是假设。
|
||||
2. **过检 ≠ 安全**:消除静态调用关系不防 Frida 等运行时 Hook;GOT 完整性校验、反调试等运行时防护(05 计划)与此正交,两层都要。
|
||||
3. **自研规模**:验收标准是本报告 V4.6.6 清零 + 业务回归,不是对齐易盾全家桶(字符串加密/VMP/反调试套件属季度级,暂不做)。
|
||||
4. **发行验证**:结构解析和 ad-hoc 签名检查不足以证明可安装、运行或满足发行要求;当前只完成本地静态验证,后续需正式配置签名和真机回归。
|
||||
|
||||
## 5. 下一步
|
||||
|
||||
现有真实目标 `appstore.ipa`(未加密、336 个调用点已定位),实验路径收敛为:
|
||||
|
||||
1. 建 `tools/macho_guard` 改写引擎:桥接段注入(arm64 位置无关蹦床,补齐 `open`变参/`exit/getpid/fork/unlink/syscall`)+ 336 个 `bl` 改写为 `bl IG_*` + 重建代码签名段。
|
||||
2. 对 patch 后的 `appstore.ipa` **重跑本目录扫描脚本**,期望 336 → 0(客观、无需送检即可自测第 1 层是否消除)。
|
||||
3. **ad-hoc 重签**(`codesign -f -s -`)即可满足 V4.6.6 静态复测——静态扫描器一般不校验签名有效性,故不需要正式证书;仅真机安装/提审才需开发者身份与 entitlements。
|
||||
4. 送检 V4.6.6 验证第 1 节核心假设:过 → 收工;仍命中 → §3 阶梯 A。
|
||||
|
||||
> 风险:段注入涉及 LC_SEGMENT_64 插入与 LC_CODE_SIGNATURE/__LINKEDIT 偏移修正,是本引擎最易出错处,需逐步验证(先注入可用桥接段并能正常加载,再做批量改写)。
|
||||
@@ -0,0 +1,104 @@
|
||||
# 10 · macho_guard 链接后改写器:自测通过
|
||||
|
||||
日期:2026-11-10。状态:**第 1 层检测自测清零**——单二进制 336 → 0(§1-6),整包 31 个 Mach-O 共 878 → 0(§7),结构合法可签。**仍未向 V4.6.6 送检**——"桥接即过"依旧是待验证假设(见 [09](09_ECNUP_REMEDIATION_DIRECTION.md) §4)。
|
||||
|
||||
关联:方向与改写面实测见 [09](09_ECNUP_REMEDIATION_DIRECTION.md),检测器判定标准推断见 09 §1。
|
||||
|
||||
> 后续已从根目录 IPA 重新运行整包验证并保存在 `test-results/verification/20261110-step1-final/`,含源码快照、前后包、逐二进制 UUID/哈希、逐调用点 CSV、逐指令校验和签名日志;复现入口见 [13](13_REPRODUCIBLE_BASELINE.md)。下文 scratchpad 为早期记录,不再是唯一证据来源。
|
||||
|
||||
## 1. 结论
|
||||
|
||||
按 09 §5 收敛的路径,`tools/macho_guard` 链接后改写引擎已建成并在真实目标 `appstore.ipa`(readoor31OtherPay v2.199.0,`com.ecnup.aSCLdl2`,arm64 单切片,`cryptid 0`)上跑通:
|
||||
|
||||
- **注入** `__IGUARD` 段(RX,一页 0x4000),内含 12 个与系统 stub 字节同构的桥接蹦床;
|
||||
- **改写** `__text` 内全部 336 个命中调用点 `bl/b → __stubs` 为 `bl/b → IG_*`;
|
||||
- **ad-hoc 重签**(`codesign -f -s -`)通过,`codesign -v` exit 0。
|
||||
|
||||
对 patch 后二进制重跑本目录扫描脚本:**命中 12 个符号的直接调用点 336 → 0**。重新打包成 IPA 后再解包复扫,同样为 0——独立复现,非内存产物假象。
|
||||
|
||||
## 2. 改写面与结果(逐符号)
|
||||
|
||||
| 符号 | 改写数 | 符号 | 改写数 | 符号 | 改写数 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `_exit` | 96 | `_open` | 21 | `_unlink` | 8 |
|
||||
| `_fopen` | 86 | `_dlsym` | 18 | `_read` | 7 |
|
||||
| `_close` | 67 | `_write` | 16 | `_dlopen` | 2 |
|
||||
| `_getpid` | 12 | `_fork` | 1 | `_syscall` | 2 |
|
||||
|
||||
合计 336,与注入前实测(09 §2.5)逐符号完全吻合。
|
||||
|
||||
## 3. 桥接蹦床原理
|
||||
|
||||
每个桥接函数 3 指令 12 字节,与系统 `__stubs` 条目**字节同构**,从同一 GOT 槽取址尾调用:
|
||||
|
||||
```
|
||||
adrp x16, GOT@page ; 与系统 stub 相同的页基址
|
||||
ldr x16, [x16, #off] ; 取同一 GOT 槽(dyld 已填真实函数地址)
|
||||
br x16 ; 尾调用,ABI 透明,变参/errno 原样透传
|
||||
```
|
||||
|
||||
关键差异:桥接函数**不登记进间接符号表**。因此静态扫描器遍历 `__stubs`→间接符号表还原"这个分支目标对应哪个导入符号"时,`IG_*` 无法被归为 `_write/_fopen/...`,调用点不再被判为对应系统符号。`_write` 等仍是导入符号(GOT 槽、桥接自身引用),第 2/3 层未动——与 09 §1 推断的 V4.6.6 判定口径(调用点直接分支关系,非符号存在性)一致。
|
||||
|
||||
尾调用正确性:`b IG_sym`(tail call)改写后,`IG_sym` 末尾 `br x16` 跳真实实现,返回地址仍是原调用者,ABI 透明;`bl IG_sym` 同理,桥接返回后回到调用点。变参 `open`/`syscall` 因纯尾调用、参数寄存器/栈原样透传,字节同构蹦床即足够(不需签名精确的 C 桥接)。
|
||||
|
||||
## 4. 段注入与偏移修正(最易错处)
|
||||
|
||||
在 `__DATA` 与 `__LINKEDIT` 之间插入 `__IGUARD`:
|
||||
|
||||
1. 文件在 `__LINKEDIT` fileoff(0x3458000)处插入一页段数据;
|
||||
2. header 区(0..16384,含 load commands)在 `__LINKEDIT` 命令前插入 72 字节 `LC_SEGMENT_64`,header 区总长保持 16384(原 load commands 结束于 15088,余量充足);
|
||||
3. `ncmds += 1`,`sizeofcmds += 72`;
|
||||
4. `__LINKEDIT` 段命令 vmaddr/fileoff `+= PAGE`;
|
||||
5. **所有指向 __LINKEDIT 的偏移 `+= PAGE`**:chained_fixups、exports_trie、symtab(symoff/stroff)、dysymtab(indirectsym)、function_starts、data_in_code、code_signature——漏一个即加载失败或签名区错位。命令本身也因插入右移 72 字节。
|
||||
|
||||
验证:`otool -l` exit 0 解析干净;段序 `__PAGEZERO,__TEXT,__DATA,__IGUARD,__LINKEDIT` 正确;`codesign -v` PASSED。
|
||||
|
||||
## 5. 工具与产物
|
||||
|
||||
- `tools/macho_guard/machox.py`:Mach-O 解析(`Macho` 类、`linkedit_pointers()`)。
|
||||
- `tools/macho_guard/macho_guard.py`:注入+改写+重签。CLI:`inject`(仅注入校验)、`harden`(注入→改写→重签一条龙)。因读取未信任二进制,须 `python3 -I` 运行。
|
||||
- 自测扫描脚本复现 V4.6.6 判定(扫 `__text` 全部 `bl/b → __stubs`,经间接符号表映射到 12 个命中符号)。
|
||||
- 加固后 IPA、逐点 CSV 等产物当前在会话 scratchpad,未入库(113M 二进制不宜提交);需长期留存可按需拷入 `test-results/`。
|
||||
|
||||
## 6. 复现命令
|
||||
|
||||
```bash
|
||||
cd tools/macho_guard
|
||||
python3 -I macho_guard.py harden <原始二进制> <输出二进制>
|
||||
# [1/3] 注入 __IGUARD;[2/3] 改写 336 处;[3/3] ad-hoc 重签 exit=0
|
||||
# 复扫期望 336 → 0
|
||||
```
|
||||
|
||||
## 7. 多 Mach-O 整包批处理(2026-11-10 自测通过)
|
||||
|
||||
单二进制验证后,把改写器推广到**整个 `.app` 包**。工程化要点:
|
||||
|
||||
- **base 泛化**:主程序 `__TEXT` vmaddr=0x1_0000_0000(`__PAGEZERO` 在前),framework/dylib vmaddr=0(无 `__PAGEZERO`)。原 `inject`/`find_stub_got_slots` 硬编码的 `BASE=0x100000000` 与 header 区 `16384` 均改为按 `__TEXT` 段实测值与首节文件偏移动态计算(`_text_mapping` / `_first_section_fileoff`)。扫描逻辑本就纯在 vmaddr 空间匹配,天然 base 无关。
|
||||
- **fat 容器**:`AliyunPlayer`/`alivcffmpeg`/`AliyunMediaDownloader` 为 `cafebabe` fat 壳包单 arm64 切片。用 `lipo -thin arm64` 抽出 → 加固 thin → `lipo -replace arm64` 回填,保持 fat 结构与原签名壳。
|
||||
- **逐级签名**:改写后自底向上 `codesign -f -s -` 各 `.framework`,再签主 `.app` bundle。
|
||||
- **注入前体检**:`batch.py` 先扫全包,报告每个 Mach-O 的命中数、注入余量(首节偏移−load command 末尾)、`cryptid`。本包 30 个 framework + 主二进制共命中,余量全部 >8KB(所需 72B),`cryptid` 全 0——无一受阻。
|
||||
|
||||
真实目标 `appstore.ipa` 整包结果(43 个 Mach-O/切片):
|
||||
|
||||
| 范围 | 命中 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 主二进制 readoor31OtherPay | 336 | → 0 |
|
||||
| 30 个 framework(含 3 个 fat) | 542 | → 0 |
|
||||
| **全包合计** | **878** | **→ 0** |
|
||||
|
||||
命中最多:AliyunPlayer 103、TTNetworkManager 56、ATAuthSDK_D 39、WCDBSwift 27。全包 `_dlsym` 312 居首(媒体/网络 SDK 动态加载)。改写后:整包复扫 0 命中;fat 容器仍 `cafebabe`+arm64;主二进制与各 framework `codesign -v` 全 PASSED;`otool -l` 干净;重打包成 IPA 再解包复扫仍 0——独立复现。
|
||||
|
||||
命令:
|
||||
```bash
|
||||
cd tools/macho_guard
|
||||
python3 -I batch.py <App.app> # 全包命中/余量体检
|
||||
python3 -I macho_guard.py harden-bundle <App.app> # 整包加固 + 逐级重签
|
||||
```
|
||||
|
||||
## 8. 下一步(未完成项,如实列出)
|
||||
|
||||
1. **送检 V4.6.6**:验证 09 §1 核心假设。过 → 收工;仍命中 → 09 §3 阶梯 A(dlsym 表 + 名字加密)。这是唯一能证实"桥接即过"的步骤,尚未做。
|
||||
2. **真机功能回归**:讯飞语音、书籍下载/解压(ZipZap/ZIPFoundation/SSZipArchive)、AliyunPlayer 播放、GCDWebServer——878 处改写后未验证运行时行为。改写只动调用目标(桥接 ABI 透明尾调用),风险低但需实测确认。
|
||||
3. **正式签名**:ad-hoc 仅够静态扫描;真机安装/提审需开发者身份 + entitlements + Provisioning 保留(整包重签需 `--entitlements` 逐包传递)。
|
||||
4. **arm64e / __auth_stubs**:本包全为 arm64(常规 `__stubs`+`__got`)。若后续样本含 arm64e 切片,需处理认证指针桩(`__auth_stubs`/`__auth_got`)——当前未覆盖。
|
||||
5. **运行时防护正交项**(05 计划):GOT 完整性校验、反调试——静态改写不覆盖,Frida 等运行时 Hook 仍需单独处理。
|
||||
@@ -0,0 +1,90 @@
|
||||
# 11 · 运行时防 HOOK Defender C 模块
|
||||
|
||||
日期:2026-11-10。状态:**模块实现 + iphoneos 交叉编译 + 宿主正向自测通过**。按 docs/05 §5.C 设计原则落地;真机接入与业务回归未做。
|
||||
|
||||
关联:报告威胁与运行时防护设计见 [05](05_READOOR_SECURITY_REMEDIATION_PLAN.md) §4/§5.C;与静态改写器([10](10_MACHO_GUARD_SELFTEST.md))正交——改写器改变自研规则下的直接分支形态,本模块防运行时 HOOK 导致的信息泄露,两层都要。
|
||||
|
||||
> 后续已将宿主测试固化为 `tests/test_defender_host.py` 和 `tests/fixtures/defender_host.c`,覆盖正常环境、符号不可用、提供方异常、环境变量、镜像特征及真实 GOT 槽重绑定,并交叉编译三个模块。本轮 7 项通过,日志随 [13](13_REPRODUCIBLE_BASELINE.md) 归档。inline Hook 真机正向测试仍未完成。
|
||||
|
||||
## 1. 定位
|
||||
|
||||
报告描述的"HOOK 关键系统函数 → 信息泄露"是**运行时威胁**,静态改写(`macho_guard`,桥接仍走同一 GOT 槽、ABI 透明)**防不住**。本模块是独立的运行时完整性探针,纯 C、无 Swift/OC 依赖,可直接编入任意 iOS target。
|
||||
|
||||
遵循 docs/05 §5.C 原则:**探针与处置分离**——只采集证据经回调上报,返回 `clear/detected/unavailable`(unavailable 不等于安全),**绝不自行 `exit`**,是否限制功能由上层策略决定(观察模式优先)。
|
||||
|
||||
## 2. 覆盖的 HOOK 形态
|
||||
|
||||
| 探针 | reason | 检测手段 | 对应攻击 |
|
||||
| --- | --- | --- | --- |
|
||||
| 符号提供方 | 100 `SYMBOL_PROVENANCE` | `dlsym`→`dladdr`,宿主镜像须系统路径 | dyld interpose / 注入 dylib 抢占符号定义 |
|
||||
| inline hook | 101 `INLINE_HOOK` | 关键函数序言首指令为无条件 B,或 LDR-literal+BR x16/x17 蹦床 | Frida Interceptor / Dobby inline patch |
|
||||
| **GOT 重绑定** | 102 `GOT_REBIND` | 运行时遍历自有镜像非惰性 `__got` 槽(fishhook 同款 loader 走法,用于**校验**),当前值去 PAC 后≠trusted 且提供方非系统 | fishhook 类 GOT/符号指针改写 |
|
||||
| 注入镜像 | 200 `INJECTED_IMAGE` | 已加载镜像名匹配 frida/substrate/cycript/dobby… 特征 | 越狱注入框架加载 |
|
||||
| Bundle 外镜像 | 201 `FOREIGN_IMAGE` | 非系统且不在 `.app` 内的镜像(弱信号) | 未知 dylib 载入 |
|
||||
| DYLD 插入 | 202 `DYLD_INSERT` | `DYLD_INSERT_LIBRARIES` **逐条**解析(非整串前缀,对应 05 §4 P1),条目在 Bundle 外即报 | `DYLD_INSERT_LIBRARIES` 注入 |
|
||||
| Frida 线程 | 203 `FRIDA_THREAD` | `task_threads`+`THREAD_EXTENDED_INFO` 线程名匹配 gum-js-loop/gmain/pool-frida… | Frida 运行时驻留 |
|
||||
| Frida 端口 | 204 `FRIDA_PORT` | 非阻塞 connect 127.0.0.1:27042(默认关,弱信号) | Frida 默认监听 |
|
||||
|
||||
全部基于公开 API:`<dlfcn.h>`、`<mach-o/dyld.h>`、`<mach-o/loader.h>`/`<nlist.h>`、`task_threads`/`thread_info`、BSD socket。
|
||||
|
||||
## 3. 文件与接口
|
||||
|
||||
```
|
||||
defender/
|
||||
include/IGDefender.h 结果模型(IGStatus/IGReason/IGFinding/IGFindingSink)+ ig_defender_scan
|
||||
anti_hook/IGAntiHook.{h,c} ig_anti_hook_check(names,count,sink,ctx) / _default
|
||||
anti_frida/IGAntiInject.{h,c} ig_anti_inject_check(bundle,sink,ctx) / ig_anti_frida_check(port,sink,ctx)
|
||||
IGDefender.c ig_defender_scan 聚合
|
||||
```
|
||||
|
||||
结果模型(`IGFinding`):`status` + `reason` + `subject`(符号/镜像/线程名)+ `evidence`(地址/提供方/端口人读文本)。探针对每条 DETECTED/UNAVAILABLE 调 `sink` 一次,CLEAR 不上报。
|
||||
|
||||
接入(观察模式,启动/回前台/关键操作前):
|
||||
```c
|
||||
static int sink(const IGFinding *f, void *ctx) {
|
||||
// 上报打点;按 f->reason 组合决定策略,勿在此直接 exit
|
||||
return 0;
|
||||
}
|
||||
int hits = ig_defender_scan(bundle_path, /*probe_port=*/0, sink, ctx);
|
||||
```
|
||||
|
||||
## 4. 验证证据
|
||||
|
||||
**iphoneos arm64 交叉编译**(可编入 App 的证明):三个 `.c` 以 `-arch arm64 -miphoneos-version-min=15.0 -O2 -Wall -Wextra` 全部 OK,`ar` 打包 `libIGDefender.a`(arm64),导出 `_ig_anti_hook_check / _ig_anti_hook_check_default / _ig_anti_inject_check / _ig_anti_frida_check / _ig_defender_scan`。
|
||||
|
||||
**宿主 arm64 行为自测**:
|
||||
|
||||
| 场景 | 期望 | 实测 |
|
||||
| --- | --- | --- |
|
||||
| 干净环境 anti_hook(12 符号 provenance+inline+GOT) | 0 命中 | 0(无误报) |
|
||||
| 干净环境注入扫描 | 0 | 0 |
|
||||
| 正向:`DYLD_INSERT_LIBRARIES=/tmp/evil:/var/x/hook` | 逐条报 DYLD_INSERT | 2 条 DYLD_INSERT(+1 FOREIGN,均正确) |
|
||||
| 正向:`dlopen` 名含 frida 的 dylib | INJECTED_IMAGE | 命中,证据含匹配特征 |
|
||||
| 正向:fishhook 式篡改 `getpid` 的 `__got` 槽指向本程序函数 | GOT_REBIND | DETECTED reason=102,证据含槽址/当前值/非系统提供方/期望值 |
|
||||
| Frida 线程扫描(无 frida) | 0 | 0 |
|
||||
|
||||
GOT 重绑定——即用户点名的"GOT 完整性校验"——以真实篡改正向验证抓得到,且篡改前零误报。
|
||||
|
||||
## 5. 边界(如实声明)
|
||||
|
||||
1. **架构**:仅 arm64/x86_64(LP64)。**arm64e `__auth_got`** 槽为认证指针,比较前 `ptrauth_strip`;若工具链无 ptrauth 则对认证槽判 unavailable,不强行比较。本包 appstore.ipa 全 arm64,无此问题。
|
||||
2. **惰性槽**:只对非惰性 `__got`(`S_NON_LAZY_SYMBOL_POINTERS`)判 rebind;`__la_symbol_ptr` 首次调用前可能仍指 helper,不误判,由 provenance/inline 层兜底。
|
||||
3. **inline hook 正向未测**:序言检测仅验证了 12 个真实系统函数的零误报路径;正向 patch 需改写共享缓存代码页(真机受保护),宿主不可行,留真机验证。检测逻辑本身保守(仅 B / LDR+BR 蹦床),低误报。
|
||||
4. **特征可规避**:镜像名/线程名/端口均为可改写特征,命中是强/弱证据,未命中不等于干净——故 05 §5.C 要求组合判定,本模块只给证据不下结论。
|
||||
5. **只检测不处置**:绝不 exit;策略层须区分构建缺陷/误报/真实攻击,支付/权益仍由服务端校验。
|
||||
6. **真机接入与回归未做**:启动链接入、冷启/回前台/多 Scene、正常 SDK 合法 swizzling 的误报面均未在真机验证。
|
||||
|
||||
## 6. 复现
|
||||
|
||||
```bash
|
||||
# 在 iOSGuard 根目录运行,隔离编译宿主测试并执行正反例,另做 iphoneos/arm64 交叉编译。
|
||||
python3 -m unittest discover -s tests -p 'test_defender_host.py' -v
|
||||
```
|
||||
|
||||
## 7. 下一步
|
||||
|
||||
1. **真机接入**:编入 readoor31(遵守其 AGENTS.md / Skill),启动链调用 `ig_defender_scan`,观察模式跑正常业务,量化误报面(合法 swizzling、调试配置)。
|
||||
2. **inline-hook 正向测**:真机用 Frida/Dobby 实挂关键函数,确认 reason=101 命中。
|
||||
3. **策略层**:把 reason 组合映射到受限操作(而非 exit),与 05 §4 指出的 `RDSecurityGuard` 立即 exit 缺陷一并整改。
|
||||
4. **arm64e 支持**:若后续样本含 arm64e 切片,补 `__auth_got` 认证槽校验。
|
||||
5. 与静态层串联:`macho_guard`(静态改写,厂商复测待完成)+ 本模块(防 HOOK)+ 可选 Plan A(dlsym+名字加密,消静态调用关系)。
|
||||
@@ -0,0 +1,83 @@
|
||||
# 12 · 内联原语 + 混淆直发系统调用 + 带校验的符号解析
|
||||
|
||||
日期:2026-11-10。状态:**优先级 1、2 实现 + iphoneos 交叉编译 + 宿主正向/反向自测通过**。优先级 3(LLVM/OLLVM/Hikari 混淆、控制流平坦化、字符串/段加密)**不在本轮**。
|
||||
|
||||
关联:威胁与运行时防护原则见 [05](05_READOOR_SECURITY_REMEDIATION_PLAN.md) §5.C;运行时探针(provenance/inline/GOT/注入)见 [11](11_RUNTIME_ANTIHOOK_MODULE.md)——本轮复用其 `ig_verify_function` 做「调用前校验」。静态过检见 [10](10_MACHO_GUARD_SELFTEST.md)。本模块与前两者正交:改写器过扫描、探针抓 HOOK、本模块让**核心逻辑自身**不给攻击者可挂的符号点。
|
||||
|
||||
## 1. 定位
|
||||
|
||||
用户落地方案四维度中的前两级:
|
||||
|
||||
- **优先级 1 — 核心逻辑自包含**:关键校验/鉴权/取数据不调用被监控的 libc/系统函数,改用强制内联原语 + 直发 `svc #0x80`,使 `__got`/`__la_symbol_ptr` 里**根本没有**这些符号条目可供 Fishhook 重绑、也没有 libSystem 函数入口可供 inline hook。
|
||||
- **优先级 2 — 隐藏意图 + 结果验真**:确需 `dlopen/dlsym` 时,库名/符号名编译期 XOR 编码、栈上解密即用即清;解析结果**放行前**过 provenance + 序言校验,把被挟持的实现挡在调用前。
|
||||
|
||||
方案 §4「导入表/指针完整性自检」已由 [11](11_RUNTIME_ANTIHOOK_MODULE.md) 的 GOT/provenance 探针覆盖,本轮不重复。
|
||||
|
||||
## 2. 交付物
|
||||
|
||||
```
|
||||
defender/
|
||||
primitives/IGInline.h 纯头,IG_AINLINE 原语:ig_strlen/memcmp/memcpy/memset/strcmp/strncmp/strstr
|
||||
syscall/IGSyscall.{h,c} 混淆直发 svc:ig_syscall6 + getpid/write/read/open/close/exit/is_debugged
|
||||
resolve/IGResolve.{h,c} 加密名 dlopen/dlsym + 放行前校验 + ig_getenv(_NSGetEnviron)
|
||||
anti_hook/IGAntiHook.{h,c} 新增公开 ig_verify_function(addr,name,sink,ctx)(复用 provenance+序言逻辑)
|
||||
```
|
||||
|
||||
### 2.1 内联原语(IGInline.h)
|
||||
`IG_AINLINE = static inline __attribute__((always_inline))`。使用处直接展开为离散指令,不生成 `bl`、不产生导入表项,从导入表抹除 strcmp/memcmp/memcpy/strstr/strlen 等特征。**定位是「隐藏特征」非「更安全实现」**——不做常量时间比较,防时序侧信道需另行处理。
|
||||
|
||||
### 2.2 混淆直发系统调用(IGSyscall)
|
||||
- **ABI(本会话真机/宿主实测)**:调用号入 `x16`,arm64 BSD 调用**不加** `0x2000000`(那是 x86_64 的 class 位);参数 `x0..x5`;`svc #0x80`;返回 `x0`,出错时 carry 置位、`x0=errno`。封装对出错统一返回 `-errno`。
|
||||
- **号混淆**:调用号不以 `movz x16,#n` 立即数出现。调用方传 `IG_SC(n)=n^0x5a`,运行期与 `volatile long ig_sc_key` 异或还原后入 `x16`。反汇编 `ig_sys_getpid` 实证:`eor x16, <mem>, #0x4e`(`0x4e=20^0x5a`),真实号 20 不出现;`ig_syscall6` 连立即数都没有(`eor x16, x9(mem), x0`)。还原真实号需运行期取 `ig_sc_key`。
|
||||
- **调试器检测** `ig_sys_is_debugged()`:直发 `sysctl({CTL_KERN,KERN_PROC,KERN_PROC_PID,pid})` 读 `kinfo_proc` 内 `extern_proc.p_flag & P_TRACED(0x800)`。偏移 `0x20` 由本机 `offsetof(struct kinfo_proc,kp_proc)==0` + `offsetof(struct extern_proc,p_flag)==32` 实测确定(非猜测,见 scratchpad/off.c)。不经 libc sysctl,规避对其 hook。**按 05 决定不含非公开 ptrace(PT_DENY_ATTACH)**,仅做公开 API 检测,处置交策略层。
|
||||
|
||||
### 2.3 加密名 + 带校验解析(IGResolve)
|
||||
- 库名/符号名编译期 XOR(`IG_ENC_KEY=0x3C`),运行期 `ig_decrypt` 栈上解密、`ig_wipe`(volatile 防 DCE)即用即清,明文不驻留 `__cstring`。
|
||||
- `ig_dlsym_verified`:解析后调 `ig_verify_function`,provenance(提供方须系统路径)+ 序言(非 inline-hook 蹦床)双过才返回地址,否则返回 NULL(视作被挟持拒用)。
|
||||
- `ig_getenv`:经 `_NSGetEnviron()` 手工遍历,规避 getenv 符号/hook。
|
||||
|
||||
## 3. 验证证据
|
||||
|
||||
全部 arm64。iphoneos:五个 `.c` 以 `-O2 -Wall -Wextra` 编译 OK,`ar` 成 `libIGDefender.a`,导出 `ig_syscall6 / ig_sys_{getpid,write,read,open,close,exit,is_debugged} / ig_decrypt / ig_wipe / ig_dlsym_verified / ig_dlopen_hidden / ig_getenv / ig_verify_function` 及 [11] 原有符号。
|
||||
|
||||
宿主 arm64 行为自测:
|
||||
|
||||
| 场景 | 期望 | 实测 |
|
||||
| --- | --- | --- |
|
||||
| `ig_sys_getpid` vs libc getpid | 相等 | 相等 |
|
||||
| `ig_sys_write(1,…)` 直发 | 写出、返回字节数 | OK(27/27) |
|
||||
| `ig_sys_open`/`read`/`close` 正常文件 | 成功 | fd=3、读 8B、close=0 |
|
||||
| `ig_sys_open` 不存在路径 | 返回 `-errno` | -2(-ENOENT) |
|
||||
| `ig_sys_is_debugged` 普通运行 | 0 | 0 |
|
||||
| `ig_sys_is_debugged` lldb 下 | 1 | 1(P_TRACED 命中) |
|
||||
| 反汇编 `ig_sys_getpid` 查立即数 | 不含真实号 20 | 仅见 `#0x4e`(编码值),真实号运行期还原 |
|
||||
| `ig_decrypt` XOR 往返 | 还原明文 | "getpid" 一致 |
|
||||
| `ig_dlsym_verified` 干净 libc 符号 | 非 NULL | getpid/dlsym/fopen 均解析 |
|
||||
| `ig_dlsym_verified` 自身二进制符号(非系统提供方) | **NULL(拒用)** | **REJECTED**(provenance 挡住) |
|
||||
| `ig_getenv(PATH)` / 缺失变量 | 命中值 / NULL | 正确 |
|
||||
|
||||
## 4. 边界(如实声明)
|
||||
|
||||
1. **仅 arm64**。直发 svc 绕过 libSystem,跨 iOS 版本调用号/ABI 稳定性由调用方负责;Apple 审核可能关注直发 svc,非 App Store 主线,用于确需防 hook 的关键路径。
|
||||
2. **混淆非加密**:svc 号掩码、字符串 XOR 密钥均在二进制内,决心足够的逆向者可还原——目标是**抬高静态分析成本**,不是密码学强度。与 svc 号混淆、[10] 桥接同理。
|
||||
3. **dlopen/dlsym 仍被调用**:仅隐藏其**参数**并对**结果验真**;若需连调用点也抹除,走 Export Trie 手工遍历(IGResolve 预留方向,当前以 dlsym 为主路径)。
|
||||
4. **原语是隐藏特征非更安全实现**:不做常量时间比较。
|
||||
5. **is_debugged 只检测不处置**:返回三态(1/0/-1),是否限制由策略层决定;不含非公开反调试手段。
|
||||
6. **真机接入与业务回归未做**:关键路径替换为 `ig_sys_*`/`ig_dlsym_verified` 后的功能正确性(讯飞语音、下载解包、AliyunPlayer、GCDWebServer)需真机验证。
|
||||
|
||||
## 5. 复现
|
||||
|
||||
```bash
|
||||
cd defender
|
||||
for f in anti_hook/IGAntiHook.c anti_frida/IGAntiInject.c IGDefender.c syscall/IGSyscall.c resolve/IGResolve.c; do
|
||||
xcrun --sdk iphoneos clang -arch arm64 -miphoneos-version-min=15.0 -O2 -Wall -Wextra -I . -I include -c "$f" -o "/tmp/$(basename ${f%.c}).o"; done
|
||||
xcrun --sdk iphoneos ar rcs /tmp/libIGDefender.a /tmp/*.o
|
||||
# 宿主自测:scratchpad sctest.c(svc)、rtest.c(resolve)、ntest.c(拒用负例)、off.c(p_flag 偏移)
|
||||
```
|
||||
|
||||
## 6. 下一步
|
||||
|
||||
1. **真机接入**:把关键校验/取数路径改用 `ig_sys_*` + `ig_dlsym_verified`,跑正常业务量化功能/性能影响。
|
||||
2. **调用点进一步隐藏**:对最敏感路径以 Export Trie 遍历替换 dlsym 调用点。
|
||||
3. 与 [11] 串联:启动链先 `ig_defender_scan`(观察模式),核心逻辑用本轮原语/直发/验真解析;策略层按 reason 组合限制功能(而非 exit)。
|
||||
4. 优先级 3(控制流平坦化 / 字符串段加密 / 商用壳)为后续独立评估项,不在本轮。
|
||||
@@ -0,0 +1,91 @@
|
||||
# 13 · 基线固化与可复现验证
|
||||
|
||||
日期:2026-11-10。本轮完成基线、自动化测试与静态证据归档,没有修改原 readoor 工程或副本业务代码,也未执行真机测试或向外部检测平台送检。
|
||||
|
||||
## 1. 本轮结果
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 输入 | 根目录 `appstore.ipa`,v2.199.0 / build 2.199.0.3 / `com.ecnup.aSCLdl2` |
|
||||
| 主可执行文件 | `readoor31OtherPay` |
|
||||
| 输入 SHA-256 | `ddb89e30c2259b45d3f09dbc825e70c4e84c682a3c23510ceb3aa6f93d891771` |
|
||||
| 自研直接分支扫描 | 43 个 Mach-O,31 个发生改写,878→0 |
|
||||
| 逐指令校验 | 878 个目标分支保留 BL/B 类型,桥接指向原 GOT 槽;其余 `__text` 指令保持一致 |
|
||||
| UUID / 结构 | 前后 UUID 一致,已记录每个文件及切片;LINKEDIT 偏移检查及 `otool -l` 解析通过 |
|
||||
| 签名 | 嵌套 bundle / dylib 从内向外 ad-hoc 签名,逐个 `codesign --verify --strict` 通过 |
|
||||
| 重打包验证 | 新 IPA 解包后重新扫描为 0,Mach-O 哈希与打包前一致 |
|
||||
| 自动化测试 | 28 项通过,未跳过:静态库重定向 15 项、Mach-O 6 项、运行时宿主/交叉编译 7 项 |
|
||||
| 原始输入 | 归档前后哈希一致 |
|
||||
|
||||
当前输入**不是原漏洞报告的同一个包**。报告为 v2.197.2 / `com.ecnup.azZVz02`,其对应 IPA 尚未确认取得。本轮只证明当前 v2.199.0 同版本前后比较成立,不得表述为原报告已通过。
|
||||
|
||||
核对最初复制时保存的原工程指纹:讯飞库和 `Podfile.lock` 一致,原工程 `project.pbxproj` 已有 SJTU OAuth 业务引用差异。本轮没有写入或回退原工程;差异及观测哈希记录在结果索引中。当前验证以冻结的 IPA 为准,不把持续开发中的原工程当作静止基线。
|
||||
|
||||
## 2. 复现入口
|
||||
|
||||
在工程根目录运行(macOS、Xcode、Python 3.11;无需安装 Python 第三方依赖):
|
||||
|
||||
```bash
|
||||
python3 tools/macho_guard/verify_baseline.py appstore.ipa \
|
||||
--output test-results/verification/new-run
|
||||
```
|
||||
|
||||
输出目录必须不存在,避免覆盖既有证据。工具会复制输入、冻结相关源码、运行冻结源码的全部测试、解包扫描、仅改写命中文件、逐级签名、逐指令校验及重新打包复扫。遇到命令失败、加密输入、未覆盖架构、空间不足或不一致时中止,已创建目录内记录 `status=failed`,不能作为通过证据。
|
||||
|
||||
复现指相同源码和输入下得到一致的调用点统计及检查结论;ZIP 时间戳、签名和运行地址可能变化,不要求每次输出 IPA 逐字节一致。
|
||||
|
||||
## 3. 证据位置
|
||||
|
||||
本次有效归档:`test-results/verification/20261110-step1-final/`。先前 `20261110-appstore-step1/` 是初次运行,仅保留作为过程记录;引用本轮结论以 `step1-final` 为准。
|
||||
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
| `manifest.json` | 输入版本/哈希、工具哈希、环境、统计及未完成的验收项 |
|
||||
| `source-snapshot/`、`source-files.json` | 当次改写器、静态库工具、Defender、测试及 fixture 的源码快照和哈希;不依赖未提交的 Git 状态 |
|
||||
| `baseline/input.ipa`、`baseline/unpacked/` | 同一个原始输入及解包内容 |
|
||||
| `guarded/guarded.ipa`、`guarded/unpacked/` | 加固输出及打包前内容,供后续静态复测准备使用 |
|
||||
| `before-binaries.json`、`after-binaries.json` | 每个 Mach-O 的 SHA-256、切片大小、UUID、段结构、各符号命中数 |
|
||||
| `before-callsites.csv`、`after-callsites.csv` | 逐调用点地址、分支类型及符号;加固后为空清单(保留表头) |
|
||||
| `rewrites.json` | 每个被改写文件的改写数及符号明细 |
|
||||
| `before-files.json`、`after-files.json` | 完整 Payload 文件哈希清单,符号链接单独记录 |
|
||||
| `repacked-binaries.json`、`repacked-callsites.csv` | 新 IPA 重新解包后的验证记录 |
|
||||
| `commands.log` | 实际执行命令、输出及退出码,包括 28 项测试、签名和结构检查 |
|
||||
| `evidence-hashes.json` | 全部归档文件的校验清单,不含自身 |
|
||||
|
||||
大文件位于 Git 忽略的 `test-results/`,已保存在本地,不会自动随源码提交。迁移或长期保存应复制整个有效归档目录。小型结果索引保存在 `docs/evidence/20261110-step1-summary.json`。
|
||||
|
||||
校验归档完整性(工程根目录):
|
||||
|
||||
```bash
|
||||
python3 - <<'PY'
|
||||
import hashlib, json, os
|
||||
from pathlib import Path
|
||||
root = Path('test-results/verification/20261110-step1-final')
|
||||
for record in json.loads((root / 'evidence-hashes.json').read_text()):
|
||||
path = root / record['path']
|
||||
if 'symlink' in record:
|
||||
assert path.is_symlink() and os.readlink(path) == record['symlink'], path
|
||||
else:
|
||||
h = hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
for block in iter(lambda: f.read(1024 * 1024), b''):
|
||||
h.update(block)
|
||||
assert path.stat().st_size == record['size'] and h.hexdigest() == record['sha256'], path
|
||||
print('归档校验通过')
|
||||
PY
|
||||
```
|
||||
|
||||
## 4. 新增的测试与拒绝条件
|
||||
|
||||
Mach-O 测试由 Apple 链接器生成 iOS arm64 样本,覆盖真实分支改写、原 GOT 地址保留、UUID、重复注入、输入覆盖、架构不支持、截断、加密、header 空间不足及 ZIP 路径逃逸。修正了 LINKEDIT 字段所在命令位于新插入命令前方时,不应统一将字段位置右移 72 字节的问题。
|
||||
|
||||
运行时测试只在独立宿主进程中运行:正常环境零告警、缺失符号上报 unavailable、本地函数提供方异常、两个环境变量条目分别上报、加载无害的特征名测试 dylib、真实 GOT 槽改指测试函数后命中 reason=102。另对三个 Defender 模块做 iphoneos/arm64 交叉编译。没有修改系统函数代码,也没有进行 inline Hook 真机验证。
|
||||
|
||||
## 5. 尚未完成的验收
|
||||
|
||||
1. V4.6.6 外部复测:自研扫描规则来自报告示例的推断,878→0 不等于厂商扫描清零。
|
||||
2. 开发者身份、entitlements、Provisioning 下的真机安装与业务回归:当前 ad-hoc 结果只用于本地静态验证。
|
||||
3. Defender 在 App 启动、回前台的实际调用与正常 SDK 误报检查,以及受控 inline Hook 正向验证。
|
||||
4. 原报告对应包及同版本前后厂商复测对照。
|
||||
|
||||
后续进入第二步:在 `readoor-test` 的 `readoor31` 上核实接入并制作真机观察包,继续使用 ZipZap;不切回已知打包失败的旧 `readoor` target。
|
||||
@@ -0,0 +1,123 @@
|
||||
# 14 · ZipZap 三层防护试点与验收记录
|
||||
|
||||
日期:2026-11-10。范围为 iOSGuard 和工程内 `readoor-test` 副本;原工程 `/Users/shenlei/Work/ReadBook/readoor` 未写入。沿用 `readoor31` target 和 ZipZap,不切回构建失败的旧 target。
|
||||
|
||||
后续观察构建、45 项当前测试和独立业务包状态见 [观察包业务回归](15_OBSERVATION_BUSINESS_REGRESSION.md);下文 44 项是第二步冻结证据,不覆盖业务回归。
|
||||
|
||||
## 1. 本次完成范围
|
||||
|
||||
| 层次 | 已实现 | 验证边界 |
|
||||
| --- | --- | --- |
|
||||
| 直接调用关系 | 使用同次 Release Link Map,把 ZipZap 两处 BL 改指向已链接的调度入口 | 精确核对调用者/入口符号地址、改写次数、分支范围,其他指令字节不变 |
|
||||
| 桥接后的目标追踪 | 符号名编码、首次运行时解析、校验、缓存、间接调用 | 最终 Release 为 `br x3` / `br x1`;不是原来的 GOT 转接;不能据此认定静态分析无法恢复目标 |
|
||||
| 运行时 Hook | 接入 Defender;保留提供方、GOT、序言探针,新增缓存指针和初始代码前缀检查 | 宿主真实 GOT 改指、真机独立诊断私有缓存篡改拒绝等通过;受控真机 inline Hook 与完整业务回归仍待完成 |
|
||||
|
||||
仅覆盖两个调用点:
|
||||
|
||||
```text
|
||||
-[ZZFileChannelOutput writeData:error:] → IG_dispatch_write → 校验后的 write 地址
|
||||
-[ZZFileChannelOutput close] → IG_dispatch_close → 校验后的 close 地址
|
||||
```
|
||||
|
||||
这是一轮试点,尚未推广至讯飞、AliyunPlayer 或全部报告函数。没有在同一产物上叠加旧的整包 GOT 桥接改写。副本中的 ZipZap 已恢复原始静态库,避免先重定向成 `IG_write/IG_close` 后又重复改写;其之前状态保存在 `test-results/step2/before/`。
|
||||
|
||||
## 2. 实现位置与顺序
|
||||
|
||||
- `tools/macho_guard/redirect_to_runtime.py`:链接后定点改写与有界追踪。
|
||||
- `tools/macho_guard/profiles/zipzap.json`:调用者、原符号、目标入口及预期次数。
|
||||
- `defender/dispatch/IGDispatch.{c,h}`:固定 C 签名入口、`pthread_once`、线程重入防护、原子缓存。
|
||||
- `defender/resolve/IGResolve.{c,h}`:解析结果区分 CLEAR / DETECTED / UNAVAILABLE,拒绝无效或截断的符号名。
|
||||
- `defender/anti_hook/IGAntiHook.{c,h}`:提供方、GOT、arm64 序言检查;代码读取使用 `vm_read_overwrite`,读失败不冒充正常。
|
||||
- `defender/IGDefender.c`:聚合调度完整性检查。
|
||||
- 副本的 `Base/Security/IGDefender/`:同步上述模块,通过 `scripts/add_igdefender.rb` 加入现有 target。
|
||||
|
||||
执行顺序为:先编译并链接运行时入口 → 保存同次 Link Map → 在可执行文件副本上改写指定分支 → 从内到外签名 → 打包与复核。实际签名发布时,必须在改写后使用匹配的开发者身份、profile 和 entitlements;下一次 Xcode 构建会生成新的未改写文件,需重新执行改写。当前尚未自动接入每次 Archive。
|
||||
|
||||
`dlsym/dlopen` 等解析器启动依赖保留原调用,不能把启动依赖再重定向回依赖自身的解析器。新增函数必须逐个适配 ABI、错误返回和所有权语义,不能把可变参数、结构体返回或 C++ 调用一律转换为通用 `void *` 函数。
|
||||
|
||||
## 3. 运行语义与处置
|
||||
|
||||
首次解析地址必须通过提供方和序言检查;初始化后保存地址及前 16 字节。每次 `write/close` 前复核缓存、提供方、序言和代码前缀。正常调用恢复进入时的 `errno`,保留系统函数返回值;不重试 `EINTR`,不补齐短写,不重复 `close`。
|
||||
|
||||
调度入口本身拒绝不可信调用:篡改返回 `-1/EACCES`;校验不可用返回 `-1/ENOSYS`;解析重入返回 `-1/EDEADLK`。**这部分不受 Swift 观察模式控制**,可能使解包写入或关闭失败,必须真机覆盖 ZipZap 下载、解包、取消和错误路径后再发布。
|
||||
|
||||
Swift 策略单独保留 `unavailableReasons`,观察模式记录,强制模式拒绝不可用或强信号对应的已接入新支付入口。`RDOrderViewController.payOrder()` 新增 `allowsSensitiveOperation(.beforePayment)`;已有 Apple 待处理交易的验证/补单沿现有分支继续,避免阻断交易收尾。其余支付、VIP、登录和激活入口尚未逐一接入。`applyDecision` 的日志本身不会限制所有入口。
|
||||
|
||||
启动重复调用共用一次评估,回前台与选定支付入口重新扫描;前台观察者只注册一次,评估状态统一到主线程。扫描目前同步执行,尚未完成启动、支付前扫描及高频文件写入的真机耗时测量。
|
||||
|
||||
## 4. Release 与静态证据
|
||||
|
||||
有效归档:`test-results/step2/zipzap-runtime-final-v3/`。`test-results/step2/zipzap-runtime-final/` 是 Link Map 编码问题导致的失败记录,不作通过依据;`-v2` 为之前的通过记录,本轮以 `-v3` 为准。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 构建 | `readoor31` / Release / iphoneos arm64,通过;OtherPay 同步接线但未单独构建 |
|
||||
| 本次产物版本 | `2.156.0` / `2.156.0.1` / `com.ecnup.aSCLdl2` |
|
||||
| 自动化测试 | 44 项通过,无跳过,执行冻结源码 |
|
||||
| 本次整包直接分支规则 | 558→556,仅定点减少 2 处 |
|
||||
| write 调用点 | `0x100c1f604` → `_IG_dispatch_write` `0x100485924` |
|
||||
| close 调用点 | `0x100c1f800` → `_IG_dispatch_close` `0x100485a5c` |
|
||||
| 调度对象导入 | 无 `_write` / `_close` / `_memcmp` |
|
||||
| Release 测试后门 | 最终 App 无 `ig_dispatch_test_*` 符号 |
|
||||
| 静态追踪 | 两处原目标 stub 路径消失;两个调度入口存在未解析间接分支 |
|
||||
| 结构/打包 | 原构建文件不变、UUID 不变、嵌套 ad-hoc 签名及严格验证、重打包后扫描和哈希一致 |
|
||||
|
||||
测试包括:文件调用语义/errno、短写/EAGAIN、EINTR 不重试、并发、构造阶段调用、初始化失败、解析重入、缓存篡改拒绝、解析失败、arm64 序言指令分类、真实宿主 GOT 改指、Swift 观察/强制策略,以及改写工具的拒绝路径。arm64 指令分类测试不等于真机实际修改系统代码后的检测。
|
||||
|
||||
主要证据:`manifest.json`、`redirect-report.json`(逐调用点及前后追踪)、三个 `.asm`、`IGDispatch-imports.txt`、`source-snapshot/`、`source-files.json`、`commands.log`、`build-release.log`、`guarded.ipa`、`evidence-hashes.json`。大文件由 Git 忽略,需单独备份。
|
||||
|
||||
第一步 `test-results/verification/20261110-step1-final/` 的 v2.199.0 / OtherPay / 878→0 归档保持独立,不与本次新构建的 558→556 混用。原漏洞报告为 v2.197.2 / `com.ecnup.azZVz02`,本轮仍不是原报告同一二进制。
|
||||
|
||||
## 5. 复现命令
|
||||
|
||||
在 iOSGuard 根目录,先构建:
|
||||
|
||||
```bash
|
||||
xcodebuild build -workspace readoor-test/readoor.xcworkspace \
|
||||
-scheme readoor31 -configuration Release -sdk iphoneos \
|
||||
-destination 'generic/platform=iOS' -derivedDataPath test-results/DerivedData \
|
||||
-jobs 4 CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
|
||||
COMPILER_INDEX_STORE_ENABLE=NO LD_GENERATE_MAP_FILE=YES
|
||||
```
|
||||
|
||||
保存构建日志后验证(输出目录必须不存在):
|
||||
|
||||
```bash
|
||||
python3 tools/macho_guard/verify_runtime_pilot.py \
|
||||
--app test-results/DerivedData/Build/Products/Release-iphoneos/readoor31.app \
|
||||
--link-map test-results/DerivedData/Build/Intermediates.noindex/readoor.build/Release-iphoneos/readoor31.build/readoor31-LinkMap-normal-arm64.txt \
|
||||
--dispatch-object test-results/DerivedData/Build/Intermediates.noindex/readoor.build/Release-iphoneos/readoor31.build/Objects-normal/arm64/IGDispatch.o \
|
||||
--build-log test-results/step2/build-release.log \
|
||||
--output test-results/step2/new-runtime-run
|
||||
```
|
||||
|
||||
构建日志、Link Map、对象文件必须来自同一次构建;更换日志路径时同步参数。Link Map 符号地址与实际二进制不一致会拒绝,不能用旧 Map 套新包。
|
||||
|
||||
## 6. 仍能被恢复或绕过的路径
|
||||
|
||||
1. 入口名仍提示用途;编码名可以解码;`dlsym/dladdr` 仍可识别。本轮提高简单调用图追踪成本,没有实现不可静态分析。
|
||||
2. 自研追踪只对本地 BL/B、有界深度、报告的 12 类系统 stub 和经典 GOT 桥接做检查,不解析所有寄存器数据流、TLS、初始化回调或符号解码。未解析间接调用不构成安全证明。
|
||||
3. 提供方路径白名单不是签名身份验证;`dlsym/dladdr/vm_read_overwrite` 自身也可能被攻击者干扰。现有 GOT 检查仍允许部分系统内转发,不能覆盖全部重绑定方式。
|
||||
4. 初始代码快照可能在攻击后建立;同进程攻击者可同时修改缓存、期望值或校验函数。前缀之后的改写及校验与调用之间的竞态仍存在。
|
||||
5. 当前序言只覆盖部分 arm64 蹦床,不能识别所有 Hook,也可能把合法的系统转发判成异常;arm64e/PAC 及不同系统版本需要独立验证。
|
||||
6. 未完成完整 App 业务回归、受控真机 inline Hook、所有正常 SDK 误报与性能统计、原报告同版本及 V4.6.6 厂商复测,不能宣称报告问题全部解决。
|
||||
|
||||
## 7. 回滚与后续验收
|
||||
|
||||
`test-results/step2/before-state.json` 记录改动前哈希,`before/` 保存工程、安全入口、ZipZap 和既有 Defender 文件。回滚应恢复相互匹配的工程配置与整套模块,并移除本轮新增源引用;不要只恢复一个静态库或仅删除调度模块。订单控制器仅撤销本轮 `payOrder()` 安全门禁插入,保留其他既有修改。
|
||||
|
||||
只需取消链接后改写时,使用归档 `baseline/Payload/readoor31.app` 或重新构建未改写 App;仍需按分发方式重新签名。默认观察模式仅控制 Swift 业务门禁,不是调度层回滚开关。
|
||||
|
||||
独立诊断真机验证已完成,见下一节。下一验收顺序:合法签名的 App 观察包执行下载/解包及支付收尾回归 → 受控真机提供方/GOT/inline Hook 正向验证与性能测量 → 固定同版本输入向 V4.6.6 复测。通过后再按 ABI 分类推广到其他调用者。
|
||||
|
||||
## 8. 独立诊断真机结果
|
||||
|
||||
设备:iPhone 16 Plus,设备工具报告 iOS `27.2`。使用现有通配开发 profile 签名,测试专用 Bundle ID 为 `cn.touchv.iosguard.dispatchpilot.20261110`;安装前确认不存在同名应用,测试后已卸载。没有安装覆盖现有 readoor。
|
||||
|
||||
有效记录:`test-results/step2/device-dispatch-v5/`。`console.log` 包含明确的 8 个逐项 PASS 与最终 PASS,`launch.json` 记录 exitCode=0;Defender 正常环境扫描 `detected=0 / unavailable=0`。通过项为:errno/返回值和文件语义、短写/EAGAIN、EINTR 不重试、8 线程并发、解析重入、解析失败、序言指令分类、私有缓存改指后拒绝调用。构造阶段调用由共用 fixture 一并执行。
|
||||
|
||||
该程序直接执行共用测试 fixture,再退出诊断进程;没有业务 UI,也不执行真实支付或网络请求。早期使用界面启动回调的诊断尝试未取得逐项结果,不计为通过;`v5` 改为直接执行测试并使用系统日志确认。短写测试的大缓冲区改为堆分配,避免依赖真机线程栈大小。
|
||||
|
||||
源码入口为 `tests/fixtures/dispatch_device.m` 和 `tools/macho_guard/build_dispatch_device.py`。构建脚本只接受专用 Bundle ID 前缀和匹配的有效通配开发 profile,不修改开发者门户;安装、运行与卸载单独执行。诊断程序使用 `IG_DISPATCH_TESTING` 允许改自身测试缓存,**不作为业务 App 发布包**。其冻结源码以该诊断目录的 `source-snapshot/` 为准;Release 静态归档独立保存同次构建与宿主测试输入。
|
||||
|
||||
此结果不包含实际修改系统函数代码的 inline Hook,也未在完整 App 中执行 ZipZap 解包。44 项自动化测试与 8 项真机诊断分开统计,不合并宣称整包验收通过。
|
||||
@@ -0,0 +1,88 @@
|
||||
# 15 · 观察包业务回归
|
||||
|
||||
日期:2026-11-10。用户授权使用提供的测试账号,打开首页任意资源;凭证不写入源码、文档或测试日志,不自动提交真实支付。
|
||||
|
||||
## 当前进度
|
||||
|
||||
2026-11-11 续测:设备恢复连接,独立观察包已安装并启动;用户完成协议确认、图片验证码及真实账号登录。首页 `[pdf]MW书籍测试读` 的详情及前后台恢复用例通过。首页 `【epub】会员免费书籍` 可进入 EPUB 内容(显示封面/正文和 `1/69`),前后台恢复和冷启动检查通过。业务回归结果为**部分通过**,受保护路径尚未验收。
|
||||
|
||||
PDF 试读进入旧阅读器并显示“已下载 100%”后发生 `NSRangeException`:`RBCoreCurlTurningViewController.pageViewController:viewControllerAfterViewController:` 访问索引 2,数组范围为 0…1。未改写同构建基线也复现相同异常和回调,说明该故障并非两处分支改写独有;不据此排除所有加固兼容风险。此次未修改旧阅读器业务代码。
|
||||
|
||||
对照基线使用同 Bundle ID/签名/源码构建,保留观察包登录和数据容器,仅撤销 ZipZap 两处分支改写;两包 `__text` 的差异恰为这两条指令所在 8 字节,见 `baseline-comparison-20261111.json`。两份崩溃报告为 `trial-crash-20261111.ips` 和 `pdf-baseline-crash-20261111.ips`,应用标识均已核对为观察包;摘要在 `pdf-ab-comparison-20261111.json`。对照后已恢复加固观察包。自动化用例启动或截图完成不代表阅读内容已成功渲染。
|
||||
|
||||
此前 `readoor31` Release 观察构建、45 项宿主/工具测试、独立 Runner 构建通过。观察包完成两处改写、开发签名及嵌套严格验证,IPA 内二进制哈希一致。2026-11-10 安装曾受 CoreDevice 4016/设备离线阻塞,原日志保留;2026-11-11 已解除。宿主/工具测试与业务测试不合并计算。
|
||||
|
||||
`security-final-20261111.jsonl` 共 14 条快照,覆盖本轮启动/前台事件(包含加固包与对照阶段),检测及不可用原因均为空;扫描耗时约 4.26–29.87 ms,中位数 14.21 ms。这只是单台设备的小样本,不是性能基准。四个 ZipZap 计数的最大值均为零,故当前业务没有证明命中其受保护文件输出。本轮未扩大保护范围,也未执行支付、异常网络/取消、实际 inline Hook 或厂商复测。
|
||||
|
||||
## 观察包
|
||||
|
||||
- Bundle ID:`cn.touchv.iosguard.observe.20261110`,显示名:`教育汇·观察`。
|
||||
- 来源:工程内 `readoor-test` 副本,源码版本 `2.156.0 / 2.156.0.1`;原工程不修改。
|
||||
- 使用真实登录及网络请求,不启用 `--UITesting` 或项目内假 token 注入。
|
||||
- 独立数据容器和 Keychain,移除五组 URL scheme,避免与原 App 争用回调。
|
||||
- 独立 Bundle ID 下的 Apple 登录、关联域、共享 Keychain、外部支付回调和绑定 Bundle ID 的第三方 SDK 授权需要另行验证。
|
||||
- Swift 安全策略保持观察模式,C 调度入口仍会拒绝篡改、不可验证及解析重入。
|
||||
|
||||
## 可观测性
|
||||
|
||||
只有定义 `IG_OBSERVATION` 的构建包含只读原子计数:`write_attempted/write_dispatched/close_attempted/close_dispatched`。`dispatched` 表示已调用系统函数,不能解释为 I/O 成功。新增宿主测试验证系统错误仍计入 dispatched、校验拒绝不计入 dispatched,以及普通构建不导出观察接口。
|
||||
|
||||
专用 Bundle ID 在既有安全评估事件后写入 `Documents/IGObservation/security.jsonl`,包含事件、模式、扫描耗时、检测/不可用原因编号和调用计数,不包含用户资料、凭证、资源 URL 或原始地址。计数为进程内累计,冷启动重置。记录是事件快照;完成资源操作后需触发前后台评估再读取。
|
||||
|
||||
## 已确认的业务调用链
|
||||
|
||||
当前两个保护点为 ZipZap 的 `ZZFileChannelOutput.writeData:error:` 和 `close`。新版 PDF/单词书下载解压链为:
|
||||
|
||||
```text
|
||||
RDWordBookHandler → RDPDFDownloadAPIService.downloadAndUnzip → SSZipArchive.unzipFile
|
||||
```
|
||||
|
||||
源码:`readoor-test/readoor/3.0/Features/ReadView/PDF/Network/RDPDFDownloadAPIService.swift` 和 `readoor-test/readoor/3.0/Features/ReadView/MemorizeWords/Handler/RDWordBookHandler.swift`。旧版 `STSCourseCardLearnHandler.m` 的 ZipZap 调用从 NSData 读取首个条目,不能据此认为执行了受保护的文件输出。
|
||||
|
||||
本轮实际 EPUB 的源码解包链为 `BookView/EPUB/Core/Classes/newEpub/epub/EpubParser.extractEpub → STSFileManagerStorage.unzipFileAtPath`。`STSStorage.framework` 的导入和依赖均指向 `SSZipArchive.framework`;已保存 `stsstorage-unzip-import-20261111.txt`。这属于源码及二进制依赖证据,尚未逐调用点采集运行时命中。
|
||||
|
||||
包内 `SSZipArchive.framework/SSZipArchive` 为 `MH_DYLIB`,导入 `fopen/fread/fwrite/fclose`。当前定点工具要求入口已链接在同一 Mach-O,不能直接把跨镜像分支写到主程序里的调度入口。扩大保护前需补独立 Framework 内的入口/绑定方案及签名验证,或在可重建 SDK 中编入入口,再按固定 ABI 验证;不能只增加主程序规则并声称已覆盖此 SDK。
|
||||
|
||||
因此首页资源运行正常且计数为零时,只能记录业务链未命中 ZipZap 文件输出。下一轮应按实际资源类型确定 SSZipArchive/minizip 调用者、固定 ABI 和预期调用次数,建立基线,再定点扩大保护和对照回归。
|
||||
|
||||
## 工具与证据
|
||||
|
||||
- `tools/business_regression/prepare_observation_app.py`:校验通配开发 profile、证书和有效期;复制、改写、独立化、签名、打包和生成哈希。`--baseline` 仍核对 Link Map 和预期调用点,但丢弃分支改写,用于同构建对照。
|
||||
- `tools/business_regression/create_ui_runner.rb`:生成独立 UI 测试工程,不修改业务工程。
|
||||
- `tests/business_regression/IGBusinessRegressionTests.swift`:启动、首页资源、试读、EPUB、前后台、冷启动及 PDF 复现用例。当前截图遮盖输入框,文本树删除输入值;初次登录诊断原始 xcresult 已删除,只保留已脱敏附件。
|
||||
- 证据目录:`test-results/step3/`;构建目录:`test-results/ObservationDerivedData/`。
|
||||
- 安装包:`test-results/step3/observation-package/observation.ipa`;签名 App 在同目录 `Payload/readoor31.app`。
|
||||
- 包内 `manifest.json`、`redirect-report.json`、`source-snapshot/`、`commands.log` 和 `evidence-hashes.json` 保留打包当时快照;其中业务 `not_run` 不追写,实际业务结果另见 `docs/evidence/20261111-step3-business-summary.json`。
|
||||
- `build-observation.log`、`build-ui-runner.log`、`host-tests.log`;安装失败和设备详情日志保留连接问题证据。
|
||||
|
||||
观察构建在既有标志上增加 `OTHER_CFLAGS='$(inherited) -DIG_OBSERVATION=1'` 和 `OTHER_SWIFT_FLAGS='$(inherited) -D COCOAPODS -D TARGETTYPE_7 -D IG_OBSERVATION -Xcc -DIG_OBSERVATION=1'`,使用 Release、iphoneos 和同次 Link Map。打包脚本的身份/profile 参数来自本机合法开发签名配置,输出目录必须不存在。
|
||||
|
||||
有效 UI 结果包:`home-resource-20261111.xcresult`、`epub-guard-20261111.xcresult`、`cold-restart-20261111.xcresult`。`trial-resource-20261111.xcresult` 只证明试读入口截图完成,其后发生崩溃,不记为阅读通过。`pdf-baseline-20261111.xcresult` 为同构建对照的实际失败记录。每项对应日志和导出附件在同级目录,最终驱动源码及哈希在 `business-run-20261111/`。
|
||||
|
||||
用户 2026-11-11 明确暂缓 PDF 越界修复、完整业务回归及报告复测。本轮改用首页 `31单词书(稳操胜券)-勿动` 建立 SSZipArchive 运行时命中证据;ZipZap 原试点仍需能命中文件输出的业务样例。协议确认及验证码均由用户完成。
|
||||
|
||||
## 回滚与验收边界
|
||||
|
||||
本轮改动前文件及哈希在 `test-results/step3/before/`。只取消观察能力时移除观察编译宏即可;完整恢复时逐个恢复备份对应文件,保留其他改动。观察包可单独卸载。前两轮冻结证据不修改,原报告同版本和厂商 V4.6.6 复测仍待完成。
|
||||
|
||||
## 单词书解包观察(2026-11-11)
|
||||
|
||||
仅在 `IG_OBSERVATION` 编译时,在 `RDPDFDownloadAPIService.unzip` 紧邻真实 `SSZipArchive.unzipFile` 调用前后记录 `unzip_begin/unzip_end`;单词书正式目录命中记录 `wordbook_cache_hit`。写入独立观察包 `Documents/IGObservation/archive.jsonl`,以随机 call_id 配对,结果包含 success 和耗时,不记录路径、下载地址、用户标识或凭证。串行锁保护并发写入,记录失败不改变原业务返回值。普通构建不包含这些记录。
|
||||
|
||||
该记录证明 SDK 边界被调用及其返回结果,不能用于证明 SDK 内部 fopen/fwrite 已被保护。此轮代码、Release 构建和新签名包在 `test-results/step4-wordbook/`,不覆盖此前冻结证据。关闭观察宏即可移除此项能力。
|
||||
|
||||
### 单词书实测结果
|
||||
|
||||
`read-v2.xcresult` 与 `reentry.xcresult` 两项真机用例通过:从详情的“稳操胜券”课件卡片进入,单词书显示已学 0 词、未学 7502 词,前后台恢复、返回重进均正常。未点击学习/复习或完成学习任务。
|
||||
|
||||
`archive-final.jsonl` 记录 1 对真实 `unzip_begin/unzip_end`,SDK 返回 success=true,耗时 12015.24 ms。首次进入时 style/dict 已命中缓存;SDK 边界事件未携带资源类型,因此不将该次调用标成已确认的具体包类型,也不声称覆盖了样式、词库的首次解压。重进时 style/dict/sound 均命中缓存,没有新增解压。未清理用户缓存,未修改服务端资源配置。SDK 成功返回及后续缓存发布可观测,未逐文件校验解压内容。
|
||||
|
||||
两次新增前台安全快照均无检测/不可用项,扫描约 17.28/15.07 ms;ZipZap 四项计数均为零。本轮只增加观察能力,没有扩大 SDK 内部函数的保护。下一步需为动态 `SSZipArchive.framework` 制定并验证 Framework 内入口/绑定或可重建 SDK 的保护方案,再对同一单词书进行改写前后对照;不得把本次调用证据当作 fopen/fwrite 保护验收。
|
||||
|
||||
Release 构建、Runner 构建、两处既有分支改写、开发签名及严格验证通过,新包 599 个文件哈希核对通过。过程中的失败保留:`detail.xcresult` 被营销弹窗阻挡,`read.xcresult` 因假定存在“开始阅读”按钮失败;已据实际页面调整驱动。`detail-v2.xcresult` 只证明详情壳可达,其截图尚在骨架加载,不单独记为完整详情通过。
|
||||
|
||||
最终证据和驱动快照归档到 `test-results/step4-wordbook/business-run/`(39 个文件及哈希清单);摘要为 `docs/evidence/20261111-wordbook-ssziparchive-summary.json`。新包为 `test-results/step4-wordbook/observation-package/observation.ipa`,可执行文件 SHA256 为 `e43f8990acefd09754db275504a15359a87bc05ea2eb5044c3839c67dede731c`。PDF 修复、完整业务回归、报告复测继续按用户要求暂缓。
|
||||
|
||||
## 后续 SDK 保护试点
|
||||
|
||||
2026-11-11 已继续实现 SSZipArchive 动态绑定保护,新增保护 Framework,覆盖 fopen/fread/fwrite/fclose 四个导入。以相同 Release 主程序进行指定词书样式包解压对照,两包输出 9 文件 / 1,890,776 字节,聚合摘要一致;保护包四个入口实际命中 10 / 388 / 466 / 10 次,均放行且无拒绝。该结果不追写本页此前冻结的业务归档,独立记录见 [SSZipArchive 动态 Framework 保护试点](16_SSZIPARCHIVE_FRAMEWORK_GUARD_PILOT.md),证据在 `test-results/step5-ssziparchive/`。PDF 修复、完整回归和报告复测仍暂缓。
|
||||
@@ -0,0 +1,63 @@
|
||||
# SSZipArchive 动态 Framework 保护试点
|
||||
|
||||
日期:2026-11-11。范围:工程内 `readoor-test` 副本的独立观察包,以及已审核 SSZipArchive 的四个文件函数导入。PDF 越界修复、完整业务回归和检测报告复测继续暂缓。
|
||||
|
||||
## 实施机制
|
||||
|
||||
```text
|
||||
SSZipArchive 原函数调用 → SDK 内原 stub/GOT
|
||||
→ dyld 绑定至 IGArchiveGuard.framework 的 ig_a0…ig_a3
|
||||
→ 校验系统提供方、代码前缀、缓存地址和 SDK GOT
|
||||
→ 间接调用 fopen / fread / fwrite / fclose
|
||||
```
|
||||
|
||||
这里由 dyld 处理镜像间绑定,不把 SDK 的 BL 指令写成主程序地址。SDK 的 `__text` 保持不变,变化在绑定表、符号表、加载命令和重新生成的签名中。不同签名不能用整文件相等代替运行代码相同:最终两包主程序及保护库排除签名后相同,SDK 的 `__text` 相同,见 `package-v2-comparison.json`。
|
||||
|
||||
`tools/macho_guard/redirect_framework_imports.py` 同步更新 `LC_DYLD_CHAINED_FIXUPS` 的符号名称/库序号及 `LC_SYMTAB` 的名称/库序号,再在已验证的零填充中增加 `LC_LOAD_DYLIB`。导入索引、指针链、SDK 段地址及机器码不移动。映射为 `_fopen → _ig_a0`、`_fread → _ig_a1`、`_fwrite → _ig_a2`、`_fclose → _ig_a3`;不是运行中全进程 interpose。
|
||||
|
||||
当前只接受 thin arm64、two-level 动态库、无压缩且格式为 `DYLD_CHAINED_IMPORT` 的绑定。四个函数必须各有唯一且来自 libSystem 的非 weak 导入;缺失、重复、名称重叠、头部空间不足、格式或摘要变化均拒绝输出。已审核 SDK SHA256:`485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a`。不支持 arm64e/PAC、其他 chained 格式或任意 SDK 无条件处理。
|
||||
|
||||
## 运行时与错误语义
|
||||
|
||||
`defender/dispatch/IGArchiveGuard.{c,h}` 固定四种函数签名,以线程安全 once 解析和缓存地址,复用 `IGResolve` 和 `IGAntiHook` 的提供方/序言检查。每次转发校验对应缓存及 16 字节代码基线,同时核对 SDK 四个非惰性 GOT 槽是否仍指向保护入口。缺槽、重复镜像、不可读等标记不可验证。普通转发保留原返回值、系统错误、FILE*、元素计数和 errno,不增加重试。
|
||||
|
||||
异常时拒绝:`fopen` 返回 NULL,`fread/fwrite` 返回 0,`fclose` 返回 EOF;errno 分别使用 EACCES(异常)、ENOSYS(不可验证)、EDEADLK(解析重入)。拒绝路径不能移植地设置 FILE 内部 ferror 标志,拒绝 fclose 也可能保留未关闭流。因此该异常状态不能被称为完整 stdio 兼容;业务错误传播、取消和恢复仍需覆盖。保护入口拒绝机制不受 Swift observe 开关控制。
|
||||
|
||||
导出的 `ig_archive_check()` 返回 0/1/-1(正常/检测异常/不可验证),仅观察构建导出只读计数 `ig_archive_counter()`。业务库不含地址覆盖和测试豁免;`IG_ARCHIVE_TESTING` 只用于宿主 ABI fixture。主程序在现有安全事件和 SDK 边界读取库状态及计数,记录到独立观察日志,不替换既有 Defender 的原因码和业务策略。普通构建不包含此观察记录;本轮未把新 SDK 状态接入生产强制业务门禁。
|
||||
|
||||
## 对照方法
|
||||
|
||||
新观察参数 `--IGArchiveReplayStyle` 只在 `IG_OBSERVATION` 且 Bundle ID 为 `cn.touchv.iosguard.observe.*` 时生效。进入指定词书时,将同一样式包重新下载并解压到现有临时目录;正式目录已发布时仍沿原 publish 分支保留正式目录。它不伪造账号、不跳过鉴权、不改服务器数据;无参数时沿原缓存逻辑。
|
||||
|
||||
服务在成功解压后记录文件数、总字节及聚合 SHA256,不记录路径、URL、账号、文件名。两包使用同一来源的 Release 主程序和 Link Map;两包均保留既有 ZipZap 两处改写。基线嵌入相同保护库,但 SDK 不依赖它,保留原系统绑定;保护包增加 SDK 依赖和四处导入重定向。聚合摘要只用于两次新解压的对照,不代表远程资源签名校验或可信发布。
|
||||
|
||||
阶段中曾尝试备份后通过设备文件服务重置样式缓存,返回 CoreDevice 7000/ActionError 3。此后观察包 Documents 出现重新初始化;现有证据不能区分发生在安装还是目录重置阶段,故停止该清理方式。仅样式缓存此前已有 9 个文件备份,未建立全观察容器备份,不声称所有观察数据已恢复原状。随后真实账号仍可打开词书,页面显示已学 0、未学 7502,词库和音频重新取得;最终有效对照使用不清目录的样式重放。设备操作始终指定独立观察 Bundle ID,未针对原业务 App。原始日志保留,不将该失败尝试当成成功的定点清理。
|
||||
|
||||
## 当前验证
|
||||
|
||||
- `readoor31` Release 及独立 UI Runner 构建通过;两包嵌套签名严格验证通过,各 615 个文件哈希核对通过。
|
||||
- 59 项宿主/工具测试通过,其中本轮 14 项:真实 SDK 格式和拒绝路径、stdio 语义、并发、重入、缓存篡改拒绝、普通构建排除测试/观察接口,以及 Apple Silicon 上真实动态 SDK chained binding/GOT 篡改检测、拒绝与恢复。测试 fixture 的可写 GOT 操作只存在于测试源码,未编入业务库。
|
||||
- 最终 Release 的四个入口均保留间接分支,未发现对原四个系统函数的直接/GOT 导入链;见 `guard-v2-static-traces.json`、`guard-v2-disassembly.txt` 和 `guard-v2-imports.txt`。
|
||||
- `baseline-v2-wordbook.xcresult` 与 `guard-v2-wordbook.xcresult` 均通过:首页指定资源 → 稳操胜券课件 → 样式下载解压 → 词书页面 → 前后台恢复;显示已学 0 / 未学 7502。
|
||||
- 基线样式解压约 38.53 ms,保护包约 43.02 ms(增加约 4.48 ms)。单次、单机、不同运行时刻的小样本,不推导总体性能或稳定性指标;记录区间包含开始事件的观察开销,未单独扣除观测成本,不包括网络下载耗时和自动化动画等待。
|
||||
- 保护包实际 dispatched:fopen 10、fread 388、fwrite 466、fclose 10;与 attempted 一致,rejected 全为零,库完整性状态为 0。四入口共 874 次调用。基线日志 `archive_guard_loaded=false`,保护包为 true。
|
||||
- 两包输出均为 9 个文件 / 1,890,776 字节,聚合 SHA256 一致:`7043dfcd54c6ce47154feb48b8ff2a19834c5f8cd4c28dabaa012fc96537ed79`。这份对照针对本轮新解压的内容,不据此声称此前缓存备份与远程资源完全一致。
|
||||
- 保护解压阶段两次既有 Defender 快照无检测/不可用项;SDK 完整性状态单独记录。ZipZap 计数仍为零,不混作 SDK 命中。
|
||||
|
||||
`guard-v2-cache-v2.xcresult` 验证无重放参数的正常缓存及返回重进、前后台恢复通过;最新进程 9 条库观察事件均为状态 0,style/dict/sound 命中缓存,没有解压调用,四个函数计数均零(冷启动重置)。此前 `guard-v2-cache.xcresult` 因营销弹窗在自动化等待期间消失而失败,尚未进入资源;失败日志保留。最终保护阶段既有 Defender 共 5 次快照,检测/不可用项均为零;观察状态不等于攻击测试。
|
||||
|
||||
## 打包与回滚
|
||||
|
||||
在既有 `tools/business_regression/prepare_observation_app.py` 命令上追加 `--archive-guard`,构建嵌入库、改写 SDK,再按从内到外签名和生成 IPA;对照追加 `--archive-baseline`。不能同时加主程序 `--baseline`,避免对照同时改变 ZipZap。输出必须新目录,原 SDK 不写回工程。
|
||||
|
||||
最终包位于 `test-results/step5-ssziparchive/{guard-v2-package,baseline-v2-package}/`。取消本轮 SDK 保护可安装已签名基线包或用相同源构建取消 `--archive-guard`;不要在已签名 App 中只删除保护库。取消观察能力时移除宏和专用运行参数,普通构建中观察代码被剔除。备份在 `test-results/step5-ssziparchive/before/`,恢复时仅逐个撤销本轮修改并保留已有工作。
|
||||
|
||||
SDK 更新必须重新审查摘要及格式后才更新允许的输入,随后构建、绑定改写和签名步骤可自动执行;此试点不自动信任新版本。
|
||||
|
||||
## 验收边界与下一步
|
||||
|
||||
当前只覆盖该 SDK 的四个导入,其他 I/O、其他动态库、内部绕过这些导入的路径不在范围。入口名、导入依赖、解析器、地址缓存和混淆常量仍可被静态分析;同进程攻击者可能同时修改校验代码和基线、直接绕过入口。代码前缀检查只覆盖部分常见蹦床,不代表所有 inline Hook 均能拦截。
|
||||
|
||||
本轮真机证明正常业务可进入保护路径、输出与同构建基线一致;GOT 篡改正向测试在宿主完成,iPhone 上受控 GOT/实际系统代码 inline Hook、失败/取消和大包性能尚未完成。下一阶段应先补这些验证,再推广库与 ABI 范围;不能把此试点等同于原报告复测通过。
|
||||
|
||||
最终摘要:`docs/evidence/20261111-ssziparchive-framework-summary.json`。源码、测试、日志和关键包记录冻结到 `test-results/step5-ssziparchive/final-evidence/`,哈希清单不含自身。
|
||||
@@ -0,0 +1,68 @@
|
||||
# 17 · 真机 HOOK 正向验证(step11)
|
||||
|
||||
日期:2026-11-12。状态:**已完成,11/11 用例通过**。补齐 [11](11_RUNTIME_ANTIHOOK_MODULE.md) §5.3、[14](14_ZIPZAP_RUNTIME_DISPATCH_PILOT.md) §6、[16](16_SSZIPARCHIVE_FRAMEWORK_GUARD_PILOT.md) 验收边界中反复挂账的"受控真机正向验证":此前所有真机证据只有干净环境零误报,攻击形态能否命中从未在真机证明。同轮新增两个探针并接入聚合:**调试器跟踪**(reason=300,复用 docs/12 的 `ig_sys_is_debugged`)与 **ObjC 方法 IMP 基线**(reason=110,docs/05 P1 点名的 swizzle 检测空洞),随 `ig_defender_scan` 在真机逐例执行。
|
||||
|
||||
设备:iPhone 16 Plus(iPhone17,4),iOS 27.2,非越狱,开发签名(TouchLinked_dev 通配 profile,专用 Bundle ID `cn.touchv.iosguard.hookpilot.20261112`,测试后已卸载)。
|
||||
|
||||
## 1. 验证方式
|
||||
|
||||
独立诊断进程 `tests/fixtures/hook_device.m`(模式沿用 step2 `dispatch_device.m`),在**自身进程内**构造攻击形态后运行真实探针链。构建器 `tools/macho_guard/build_hook_device.py`,执行器 `tools/macho_guard/run_hook_device.py`(安装→两相位→卸载→证据哈希)。攻击构造(可写 GOT、装载模拟 dylib、特征线程名、方法替换)只存在于诊断源码,绝不编入业务库。
|
||||
|
||||
两相位:
|
||||
|
||||
- **相位 A(干净启动)**:10 个用例,覆盖 5 类攻击形态 + 基线 + 恢复检查。
|
||||
- **相位 B(DYLD_INSERT_LIBRARIES 启动)**:宿主以 `devicectl -e` 注入环境变量启动,**dyld 在非越狱设备上真实装载** Documents 下的模拟 dylib——这是越狱外可行的真实注入路径(等同 Frida gadget 的加载形态)。
|
||||
|
||||
## 2. 用例与结果(`20261112-v1`,全部 PASS)
|
||||
|
||||
| 用例 | 攻击形态 | 期望 | 实测 |
|
||||
| --- | --- | --- | --- |
|
||||
| baseline_clean | 无(聚合含新调试器探针) | 0 DETECTED | PASS(零误报;直发 sysctl 真机 clear) |
|
||||
| got_rebind | fishhook 同款:`vm_protect(VM_PROT_COPY)` 改写自身 `__got` 的 getpid 槽 → 本进程函数 | reason=102 | PASS,证据含槽址/当前值/提供方 |
|
||||
| got_restore_clean | 恢复原始指针 | 0 DETECTED | PASS(恢复有效、无粘滞) |
|
||||
| prologue_b_branch | 导出符号首指令 `b .+64`(经 dlsym→dladdr→vm_read_overwrite 完整链) | reason=100+101 | PASS |
|
||||
| prologue_ldr_br | `ldr x16,#8; br x16` 蹦床 | reason=100+101 | PASS |
|
||||
| frida_thread | 子线程 `pthread_setname_np("gum-js-loop")` | reason=203 | PASS |
|
||||
| frida_thread_gone | join 后重扫(2s 轮询容忍内核回收延迟) | 0 DETECTED | PASS |
|
||||
| injected_image | Documents 下 dlopen 特征名 `libfrida-sim.dylib` | reason=200 | PASS |
|
||||
| foreign_image | Documents 下 dlopen 无特征名 `libiosutil-sim.dylib` | reason=201(弱信号) | PASS |
|
||||
| objc_imp_baseline | 运行期类采集基线后 `class_replaceMethod` 换实现 | reason=110 | PASS |
|
||||
| dyld_insert(相位 B) | `DYLD_INSERT_LIBRARIES` 指向 Documents dylib,dyld 真实装载 | reason=202(+200) | PASS,**202 与 200 双命中** |
|
||||
|
||||
探针行为澄清(本轮实证):命中注入特征名(200)的镜像**不再重复上报** Bundle 外(201);200 与 201 是互斥的两种形态,分别用两个用例验证。
|
||||
|
||||
## 3. 性能小样本
|
||||
|
||||
真机整包聚合扫描(anti_hook 12 符号 + ObjC 基线 + 注入 + 线程 + 调试器探针)5 次:avg 0.55 ms / min 0.53 ms。单机单次小样本,不推导总体性能结论;此前观察包业务内 17~30ms 的量级主要来自 Swift 策略层与观察日志开销,C 探针本身远低于该值。
|
||||
|
||||
## 3.5 同轮新增的探针模块
|
||||
|
||||
- `defender/anti_debug/IGAntiDebug.{h,c}`:把 docs/12 已实测的 `ig_sys_is_debugged()`(直发 sysctl 查 P_TRACED)接入 `ig_defender_scan` 聚合,reason=300(1→DETECTED / -1→UNAVAILABLE)。此前该能力存在但策略层无从消费。
|
||||
- `defender/anti_hook/IGObjCBaseline.{h,c}`:ObjC 关键方法 IMP 基线探针,reason=110。策略层用 `ig_objc_baseline_capture()` 登记关键方法(类名+选择子,≤64 条),check 时 `method_getImplementation` 与基线比较:IMP 换人(swizzle/replace/exchange)或 IMP 不变但代码前缀变化(函数体改写)即 DETECTED;类/方法不可解析 UNAVAILABLE;未 capture 时 no-op。填补 docs/05 §4 P1 指出的"IMP 基线检测"空洞。
|
||||
- 原因码补充:107 显式标注为 Swift 观察层 archive-dispatch 保留;新增 110(ObjC IMP)与 300(调试器跟踪)。
|
||||
- 两个设备构建器(dispatch/hook)模块清单同步更新(+IGObjCBaseline/IGAntiDebug/IGSyscall,链接 +lobjc)。
|
||||
|
||||
宿主测试新增 3 项(`tests/test_defender_host.py`):调试器探针干净环境、ObjC 基线干净路径、ObjC 基线 replace 正向;全套件回归通过。
|
||||
|
||||
## 4. 复现
|
||||
|
||||
```bash
|
||||
python3 tools/macho_guard/build_hook_device.py \
|
||||
--profile <TouchLinked_dev.mobileprovision> --identity <SHA1> \
|
||||
--bundle-id cn.touchv.iosguard.hookpilot.<date> \
|
||||
--output test-results/step11-device-hook/build-<date>
|
||||
python3 tools/macho_guard/run_hook_device.py \
|
||||
--device <UDID> --app test-results/step11-device-hook/build-<date>/IGHookPilot.app \
|
||||
--bundle-id cn.touchv.iosguard.hookpilot.<date> \
|
||||
--output test-results/step11-device-hook/<date>-v1
|
||||
```
|
||||
|
||||
输出目录必须不存在;证据:`device-verification.json`(用例/结论/边界)、`console-clean.log`、`console-insert.log`、`launch-*.json`、`install/uninstall.json`、`evidence-hashes.json`;构建侧 `build-*/manifest.json` 含源码快照哈希。宿主侧另有同一 fixture 的 9 用例冒烟(/tmp,未归档);既有 59 项宿主/工具测试重跑通过,无回归。
|
||||
|
||||
## 5. 边界(如实声明)
|
||||
|
||||
1. **inline-hook 仍非"真实系统函数 patch"**:非越狱无法改写共享缓存代码页。本用例针对受控导出符号的**真实代码字节**验证"解析→读取→分类"全链,序言分类逻辑与真实 patch 场景相同;对系统函数的实际 inline Hook 检测仍需越狱设备(后续可选)。
|
||||
2. **特征可规避**:镜像名/线程名改写即绕过 200/203;本验证证明"命中抓得住",未命中不等于干净(组合判定原则不变)。
|
||||
3. **诊断进程 ≠ 业务 App**:独立进程、无业务代码;业务 App 内的攻击面(ObjC 方法、业务函数)不受本轮覆盖——ObjC IMP/swizzle 检测仍是空洞,见 README 差距清单。
|
||||
4. `frida_thread_gone` 依赖内核线程回收延迟(2s 轮询窗口);极端缓慢环境下可能仍残留,属环境噪声。
|
||||
5. 相位 B 的 dylib 路径来自相位 A 回显(Documents 容器路径),两次运行间重装会变化,不可硬编码。
|
||||
@@ -0,0 +1,165 @@
|
||||
# 18 · readoor 接入 iOSGuard Defender 方案
|
||||
|
||||
> 目标:把 iOSGuard 的「检测 → 分级 → 数据依赖毒化」闭环接到 readoor 业务工程。
|
||||
> 边界:**纯客户端**,不引入服务端;分发渠道=**App Store 上架**,故处置**只用数据污染 + 功能静默降级,不随机崩溃**。
|
||||
> 本文件只在 iOSGuard 侧产出「可集成产物 + 接入步骤」,**不修改 readoor 代码**。真正落地到 readoor 时须走 readoor 的 Skill 流程 + xcodebuild。
|
||||
|
||||
---
|
||||
|
||||
## 0. TL;DR —— 接入只有「两处调用」
|
||||
|
||||
1. **启动链 / 回前台 / 关键操作前** 调一次策略扫描:
|
||||
|
||||
```swift
|
||||
ig_policy_scan_and_mark(bundlePath, 0, observerSink, nil)
|
||||
```
|
||||
命中高置信越狱/Hook 组合时,它**不 exit、不弹窗**,只在内部把毒化态置脏。
|
||||
|
||||
2. **epub 解密前**,对密钥字节过一遍毒化掩码:
|
||||
|
||||
```swift
|
||||
ig_poison_apply(keyIn, keyOut, keyLen) // 健康:原样;毒化:逐字节异或掩码
|
||||
```
|
||||
健康设备 `keyOut == keyIn`,解密正常;毒化设备 key 被打乱,`sfc_SimpleDeCrypt` 解出乱码,书读不了——**没有可 patch 的 `if` 分支**。
|
||||
|
||||
其余都是工程接线(静态库 + bridging header + Header Search Paths)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 产物(iOSGuard 侧已就绪)
|
||||
|
||||
用构建脚本一键产出可集成件:
|
||||
|
||||
```sh
|
||||
sh tools/build_defender_lib.sh /path/to/out
|
||||
```
|
||||
|
||||
产物结构:
|
||||
|
||||
```
|
||||
out/
|
||||
├── lib/
|
||||
│ └── libIGDefender.a # arm64 iphoneos 静态库(-O2),只采集 + 毒化,无网络、无 UI、无 exit
|
||||
└── include/
|
||||
├── IGGuard.h # 统一公共头(umbrella)—— bridging 只 import 这一个
|
||||
├── IGDefender.h # IGStatus/IGReason/IGFinding/IGFindingSink + ig_defender_scan
|
||||
├── poison/IGPoison.h # ig_poison_init / ig_poison_mark / ig_poison_apply
|
||||
├── policy/IGPolicy.h # ig_policy_scan_and_mark / ig_policy_sink / IGPolicyState
|
||||
└── … # 其余子模块头,保持相对目录供 umbrella 引用
|
||||
```
|
||||
|
||||
脚本已校验:单一 `-Iout/include` 即可编译 `IGGuard.h`(自洽),且导出符号包含
|
||||
`ig_policy_scan_and_mark / ig_poison_apply / ig_poison_init / ig_defender_scan`。
|
||||
|
||||
> 产物是**纯 C**,不依赖 Foundation/UIKit,无动态加载,无第三方。App Store 合规面只有:静态库里有直发 `svc`(反 libc hook)与越狱特征文件路径常量——均为被动只读探测,不触发拒审项(无私有 API 符号、无越狱必备 entitlement)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 工程接线(Xcode / readoor31 target)
|
||||
|
||||
> 以下是 readoor 侧要做的配置,列出以便一次到位;**本仓不替 readoor 改**。
|
||||
|
||||
1. **放置产物**:把 `libIGDefender.a` 与 `include/` 纳入 readoor 工程(建议 `readoor/3.0/Base/Security/IGDefender/`)。
|
||||
2. **Link**:target → Build Phases → Link Binary With Libraries 加入 `libIGDefender.a`;因含 ObjC runtime 读取,Other Linker Flags 补 `-lobjc`。
|
||||
3. **Header Search Paths**:加 `$(SRCROOT)/…/IGDefender/include`(非 recursive 即可,umbrella 内部按相对目录引用)。
|
||||
4. **Bridging Header**:在 readoor 既有 bridging header 里加一行
|
||||
```objc
|
||||
#import "IGGuard.h"
|
||||
```
|
||||
之后 Swift 侧即可直接调用 `ig_policy_scan_and_mark` / `ig_poison_apply` 等 C 符号。
|
||||
5. **构建验证**(readoor 默认命令):
|
||||
```sh
|
||||
xcodebuild build -workspace readoor.xcworkspace -scheme readoor31 \
|
||||
-sdk iphoneos -derivedDataPath /private/tmp/readoor-derived
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 接入点一:处置触发(替换 `RDSecurityGuard.forceExit()`)
|
||||
|
||||
**现状**:`readoor/3.0/Base/Security/RDSecurityGuard.swift` 的 `evaluate(event:)` 在 highRisk 时走 `forceExit() → exit(0)`。
|
||||
`exit/_exit/abort` 都是**单点、显式、可被 hook** 的控制流,Shadow/Liberty 一个断点就废掉。
|
||||
|
||||
**改法**:把 `exit(0)` 这条路换成策略扫描 + 毒化(**不 exit**)。在原来调用 `evaluate` 的事件点
|
||||
(launch / foreground / beforeLogin / beforePayment / beforeVipPurchase / beforeActivation)改为:
|
||||
|
||||
```swift
|
||||
// RDSecurityGuard 内部,原 forceExit() 调用点替换为:
|
||||
let bundlePath = Bundle.main.bundlePath
|
||||
_ = bundlePath.withCString { cBundle in
|
||||
ig_policy_scan_and_mark(cBundle, 0) { finding, _ -> Int32 in
|
||||
// observer:仅打点,不含敏感信息(不打 Token/手机号/用户ID/订单号)
|
||||
// 可转发到 RDOSLogManager 记 reason/status 计数,用于灰度观测误报面
|
||||
return 0
|
||||
} as IGFindingSink, nil)
|
||||
}
|
||||
// 返回后不做任何可见动作:命中与否对 UI 完全透明。
|
||||
// 真正的「拒服务」在接入点二随解密自然发生。
|
||||
```
|
||||
|
||||
要点:
|
||||
- **一次扫描即判**:`ig_policy_scan_and_mark` 内部 reset → `ig_defender_scan` → 按档位组合判定 → 命中则 `ig_poison_mark`。
|
||||
- **检测与处置解耦**:这里**只置脏**,书打不开发生在接入点二,时空分离,攻击者难把「检测」和「后果」对上。
|
||||
- **observer 打点合规**:遵守 readoor AGENTS — 日志不输出 Token / 手机号 / 用户 ID / 订单号 / 支付结果 / 完整请求参数,只记 `reason` 枚举与计数。
|
||||
- **保留 Swift 既有探针**:`RDJailbreakDetector`(public API:canOpenURL / FileManager)可留作**观察打点**,但判定权交给 C 侧 svc 直发(绕过 bypass 对 libc/公开 API 的 hook)。即 Swift 层量化误报面,C 层定罪。
|
||||
|
||||
---
|
||||
|
||||
## 4. 接入点二:数据依赖毒化(epub 解密)
|
||||
|
||||
**现状**:`readoor/3.0/Features/ReadView/Epub/RDEncryptedEpubResourceProvider.swift`
|
||||
`decrypt(path:key:)` 调 `StsSimpleCrypt.sfc_SimpleDeCrypt(path, pass: key)`;
|
||||
`bookKey = doubled("startiasoft" + bookIdentifier)`,imageKey 走 MD5。
|
||||
|
||||
**改法**:在把 key 交给 `sfc_SimpleDeCrypt` **之前**,对 key 字节过 `ig_poison_apply`:
|
||||
|
||||
```swift
|
||||
// decrypt(path:key:) 内,调用 sfc_SimpleDeCrypt 之前:
|
||||
func poisonedKey(_ key: String) -> String {
|
||||
var inBuf = Array(key.utf8)
|
||||
var outBuf = [UInt8](repeating: 0, count: inBuf.count)
|
||||
ig_poison_apply(&inBuf, &outBuf, inBuf.count)
|
||||
return String(decoding: outBuf, as: UTF8.self) // 若 key 是二进制,改用 Data 承载,勿走 UTF8
|
||||
}
|
||||
// let realKey = poisonedKey(key); StsSimpleCrypt.sfc_SimpleDeCrypt(path, pass: realKey)
|
||||
```
|
||||
|
||||
语义:
|
||||
- **健康设备**:`ig_poison_mask() == 0` → `ig_poison_apply` 是**恒等变换**,`outBuf == inBuf`,解密与现状完全一致,零影响。
|
||||
- **毒化设备**:mask ≠ 0 → key 每字节被 `(mask >> ((i&7)*8)) & 0xFF` 异或打乱 → `sfc_SimpleDeCrypt` 解出乱码 → 书页/图片无法渲染。
|
||||
- **无分支可 patch**:这里没有 `if(越狱)`,毒化靠数据流(mask)天然传播;要绕得逆向整条密钥推导并还原 mask=0 的恒等性,成本从「分钟级断点」抬到「天级逆向」。
|
||||
|
||||
> 若 key 实际是二进制(非可打印字符串),**不要**经 `String(UTF8)` 往返(会丢字节)。改成对承载 key 的 `Data`/`[UInt8]` 原地 `ig_poison_apply`,再按 `sfc_SimpleDeCrypt` 需要的类型传入。
|
||||
|
||||
---
|
||||
|
||||
## 5. 误报底线(上线前提)
|
||||
|
||||
毒化**隐蔽且不可逆**:误伤非越狱正常用户=「书打不开」的差评 + 难排查退款。故策略层(`IGPolicy.c`)已内建底线,接入时**不要放宽**:
|
||||
|
||||
| 档位 | reason | 触发规则 |
|
||||
|---|---|---|
|
||||
| **STRONG**(单条即判) | 400 越狱文件 / 401 沙盒逃逸 / 102 GOT 重绑 / 101 inline hook / 200 注入镜像 / 300 调试器 | `strong_count ≥ 1` |
|
||||
| **MEDIUM**(需组合) | 100 符号提供方 / 110 ObjC IMP / 203 frida 线程 | `≥2 个不同 MEDIUM`,或与任一 STRONG 同现 |
|
||||
| **WEAK**(永不毒化) | 201 Bundle 外镜像 / 204 frida 端口 | 仅观察打点 |
|
||||
|
||||
- `IG_UNAVAILABLE`(架构/平台不支持、数据缺失)与 `IG_CLEAR` **一律忽略**,绝不当攻击。
|
||||
- 110 ObjC IMP 合法 swizzling 会误报,故**不单条定罪**,归 MEDIUM。
|
||||
- **灰度上线**:先让 §3 的 observer 只打点、**接入点二先不接**(或 `ig_poison_apply` 旁路),用线上 `reason` 分布确认「非越狱设备零 STRONG、MEDIUM 不成对」后,再开毒化。
|
||||
|
||||
---
|
||||
|
||||
## 6. 能力边界(务必对齐预期)
|
||||
|
||||
- **纯客户端无法根治 bypass**:Shadow/Liberty 等能把越狱检测 hook 成「干净」。本方案**不锚定「客户端准确判越狱」**,而是:① svc 直发抬高 hook 成本;② 数据污染比 exit 强一个量级;③ 检测-处置解耦 + 延迟分散后果,让「绕过一次」≠「永久绕过」。目标是把破解成本从分钟级抬到天级,不是不可破。
|
||||
- **App Store 合规**:处置只有数据污染 + 静默降级,**不随机崩溃**,不触发拒审。
|
||||
|
||||
---
|
||||
|
||||
## 7. 后续硬化 TODO(接入后迭代,不阻塞首版)
|
||||
|
||||
1. 越狱路径字符串 `IG_ENC` 混淆(避免 `strings` 直接捞出 `/var/jb`、`Cydia` 等常量)。
|
||||
2. `IGPoison` 三副本分散存储(TLS/heap,别全在 BSS 相邻)。
|
||||
3. OLLVM/VMP 覆盖 `ig_poison_mark / ig_poison_mask / ig_poison_apply` 与策略分级表。
|
||||
4. 毒化基线魔数运行期派生(别硬编码 `0xA5C3F10E7B2D4968`)。
|
||||
5. 越狱探针真机正向验证:在越狱设备实测命中 400/401,且非越狱设备零 STRONG。
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"status": "passed_local_checks",
|
||||
"created_utc": "2026-11-10T07:29:55.370792+00:00",
|
||||
"scope": "自研直接分支规则与静态结构;不代表 V4.6.6/真机验收",
|
||||
"app": {
|
||||
"CFBundleIdentifier": "com.ecnup.aSCLdl2",
|
||||
"CFBundleShortVersionString": "2.199.0",
|
||||
"CFBundleVersion": "2.199.0.3",
|
||||
"CFBundleExecutable": "readoor31OtherPay"
|
||||
},
|
||||
"input": {
|
||||
"path": "/Users/shenlei/Work/ReadBook/iOSGuard/appstore.ipa",
|
||||
"size": 128271168,
|
||||
"sha256": "ddb89e30c2259b45d3f09dbc825e70c4e84c682a3c23510ceb3aa6f93d891771"
|
||||
},
|
||||
"original_report": {
|
||||
"version": "2.197.2",
|
||||
"bundle_id": "com.ecnup.azZVz02",
|
||||
"exact_report_binary_available": false,
|
||||
"note": "当前输入单独建基线,不视为原漏洞报告二进制"
|
||||
},
|
||||
"environment": {
|
||||
"platform": "macOS-26.7.1-arm64-arm-64bit",
|
||||
"python": "3.11.3 (v3.11.3:f3909b8bc8, Apr 4 2023, 20:12:10) [Clang 13.0.0 (clang-1300.0.29.30)]",
|
||||
"xcode": "Xcode 27.1\nBuild version 27A9275",
|
||||
"clang": "Apple clang version 21.0.0 (clang-2100.3.34.2)\nTarget: arm64-apple-darwin25.6.0\nThread model: posix\nInstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin"
|
||||
},
|
||||
"tools": {
|
||||
"tools/macho_guard/batch.py": "aa9cb201a32c35367ab2d7cefb02f1c51676b4d8fbf19eeeef110f472db51d59",
|
||||
"tools/macho_guard/macho_guard.py": "cb33515f0a76686727450e99378a6a144aeaeaee8146713ff9c46a012940b108",
|
||||
"tools/macho_guard/machox.py": "616dff961618cb52e9000b55dda21da75edaeaf1c2a2a822265273b1ef2d8522",
|
||||
"tools/macho_guard/verify_baseline.py": "4fa9e85e8bc7a7860e69acf1a055a5eee7448091b525a65e9c6d6d7beb0179c1"
|
||||
},
|
||||
"automated_tests": "passed; 详见 commands.log",
|
||||
"before_total": 878,
|
||||
"after_total": 0,
|
||||
"macho_files": 43,
|
||||
"changed_macho_files": 31,
|
||||
"instruction_and_bridge_validation": "passed",
|
||||
"guarded_ipa": {
|
||||
"path": "guarded/guarded.ipa",
|
||||
"sha256": "74c878fb64008e56dbdc10cea470e34113ee5e84abb8e105e7a52d4919327cb6"
|
||||
},
|
||||
"vendor_retest": "not_run",
|
||||
"device_regression": "not_run",
|
||||
"signing": "ad-hoc,仅用于本地静态验证",
|
||||
"archive": "test-results/verification/20261110-step1-final",
|
||||
"before_symbol_counts": {
|
||||
"_close": 138,
|
||||
"_dlopen": 2,
|
||||
"_dlsym": 312,
|
||||
"_exit": 99,
|
||||
"_fopen": 163,
|
||||
"_fork": 1,
|
||||
"_getpid": 34,
|
||||
"_open": 42,
|
||||
"_read": 24,
|
||||
"_syscall": 2,
|
||||
"_unlink": 22,
|
||||
"_write": 39
|
||||
},
|
||||
"test_counts": {
|
||||
"total": 28,
|
||||
"static_sdk": 15,
|
||||
"macho": 6,
|
||||
"defender": 7,
|
||||
"skipped": 0
|
||||
},
|
||||
"archive_integrity_verified": true,
|
||||
"evidence_hash_index_sha256": "ab1ef4f8e4a3c87d97798c18fe4a57e0086124780a1eb1792349e4b6c5057f08",
|
||||
"original_source_observation": {
|
||||
"note": "本轮未写入原工程;历史指纹存在 pbxproj 业务引用差异,保留现状,不将原工程视为静止基线。当前验证以冻结 IPA 为准。",
|
||||
"files": [
|
||||
{
|
||||
"path": "readoor.xcodeproj/project.pbxproj",
|
||||
"initial_sha256": "686e9eaf12b4b533d6a8c6dac0ca0aaa3996ffa3080fad70ae04433b1c8caa08",
|
||||
"observed_sha256": "b4a013c87bd0888c36fc0f7da8d73066a6010693d59c6525760f6879696a4c8d",
|
||||
"matches_initial": false,
|
||||
"mtime_utc": "2026-11-10T06:21:19.967065+00:00"
|
||||
},
|
||||
{
|
||||
"path": "readoor/BookShelf/Classes/Factorys/XunFei/iflyMSC.framework/iflyMSC",
|
||||
"initial_sha256": "b368fa4866d274da0c6e89607e9d5b95b4a59d49c183eb68c947ac2b50ff3c2c",
|
||||
"observed_sha256": "b368fa4866d274da0c6e89607e9d5b95b4a59d49c183eb68c947ac2b50ff3c2c",
|
||||
"matches_initial": true,
|
||||
"mtime_utc": "2026-11-09T02:35:30.281591+00:00"
|
||||
},
|
||||
{
|
||||
"path": "Podfile.lock",
|
||||
"initial_sha256": "6f8c57990b2a277236145d2e84fb9634e3049f544da70346cbc7a536b0f929ec",
|
||||
"observed_sha256": "6f8c57990b2a277236145d2e84fb9634e3049f544da70346cbc7a536b0f929ec",
|
||||
"matches_initial": true,
|
||||
"mtime_utc": "2026-11-09T02:39:06.704381+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"status": "passed_local_checks",
|
||||
"app": {
|
||||
"CFBundleIdentifier": "com.ecnup.aSCLdl2",
|
||||
"CFBundleShortVersionString": "2.156.0",
|
||||
"CFBundleVersion": "2.156.0.1",
|
||||
"CFBundleExecutable": "readoor31"
|
||||
},
|
||||
"device_regression": "not_run",
|
||||
"vendor_retest": "not_run",
|
||||
"signing": "ad-hoc, static checks only",
|
||||
"tests": "passed (详见 commands.log)",
|
||||
"environment": "Xcode 27.1\nBuild version 27A9275",
|
||||
"total_redirected": 2,
|
||||
"before_total": 558,
|
||||
"after_total": 556,
|
||||
"input_sha256": "f730cb5f0a22fd20e5032c7cf808a195732a7d7107a5fd7498671c83c63d02f7",
|
||||
"output_sha256": "3bf610eac5f5d6e3b21c80418afc9b3faa12dfc59e04a485b670dbc5e8f58bf9",
|
||||
"ipa_sha256": "85ae4b064d8416a19f0cc60568cac151b3afc73dcc5fd30dabc91221424c22ef",
|
||||
"static_tracking_limitations": [
|
||||
"保留本地调度函数名,名称仍提示用途",
|
||||
"目标函数名编码可由静态分析还原",
|
||||
"解析器仍依赖 dlsym/dladdr;不代表调用关系完全不可恢复",
|
||||
"其他调用者的系统导入/GOT 保留,本次只覆盖指定调用点"
|
||||
],
|
||||
"archive": "test-results/step2/zipzap-runtime-final-v3",
|
||||
"test_counts": {
|
||||
"automated": 44,
|
||||
"isolated_device": 8,
|
||||
"skipped": 0
|
||||
},
|
||||
"isolated_device": {
|
||||
"status": "passed_isolated_diagnostic_only",
|
||||
"archive": "test-results/step2/device-dispatch-v5",
|
||||
"device": {
|
||||
"model": "iPhone 16 Plus",
|
||||
"os_version": "27.2"
|
||||
},
|
||||
"baseline_detected": 0,
|
||||
"baseline_unavailable": 0,
|
||||
"cleanup": "uninstalled diagnostic app; existing business apps untouched"
|
||||
},
|
||||
"business_app_regression": "not_run",
|
||||
"actual_inline_hook": "not_run",
|
||||
"archive_integrity_verified": true,
|
||||
"step1_archive_integrity_verified": true,
|
||||
"static_evidence_hash_index_sha256": "81645f9bb7f4e95c99a810569386a97de290346190016eafa90b659dc5632eb9",
|
||||
"device_evidence_hash_index_sha256": "7045c25b3a284b67fa5b39813958b4b9f2056d7514da20a212f8aef798328e21",
|
||||
"original_source_observation": [
|
||||
{
|
||||
"path": "readoor.xcodeproj/project.pbxproj",
|
||||
"matches_step1_observation": true,
|
||||
"observed_sha256": "b4a013c87bd0888c36fc0f7da8d73066a6010693d59c6525760f6879696a4c8d"
|
||||
},
|
||||
{
|
||||
"path": "readoor/BookShelf/Classes/Factorys/XunFei/iflyMSC.framework/iflyMSC",
|
||||
"matches_step1_observation": true,
|
||||
"observed_sha256": "b368fa4866d274da0c6e89607e9d5b95b4a59d49c183eb68c947ac2b50ff3c2c"
|
||||
},
|
||||
{
|
||||
"path": "Podfile.lock",
|
||||
"matches_step1_observation": true,
|
||||
"observed_sha256": "6f8c57990b2a277236145d2e84fb9634e3049f544da70346cbc7a536b0f929ec"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"date": "2026-11-10",
|
||||
"stage": "observation_business_regression",
|
||||
"release_build": "passed",
|
||||
"host_tests": 45,
|
||||
"host_tests_result": "passed",
|
||||
"ui_runner_build": "passed",
|
||||
"package_signature": "verified",
|
||||
"package_hash_inventory_files": 594,
|
||||
"business_regression": "not_run",
|
||||
"blocker": "physical_device_offline_coredevice_4016",
|
||||
"bundle_id": "cn.touchv.iosguard.observe.20261110",
|
||||
"protected_zipzap_calls": 2,
|
||||
"protection_expanded": false,
|
||||
"actual_modern_unzip": "SSZipArchive",
|
||||
"credentials_saved": false
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"date": "2026-11-11",
|
||||
"resource": "31单词书(稳操胜券)-勿动",
|
||||
"bundle_id": "cn.touchv.iosguard.observe.20261110",
|
||||
"source_version": "2.156.0",
|
||||
"status": "framework_binding_pilot_and_same_build_wordbook_comparison_passed",
|
||||
"protection_scope": [
|
||||
"SSZipArchive: fopen",
|
||||
"SSZipArchive: fread",
|
||||
"SSZipArchive: fwrite",
|
||||
"SSZipArchive: fclose"
|
||||
],
|
||||
"host_tool_tests": {
|
||||
"total": 59,
|
||||
"this_round": 14,
|
||||
"passed": true,
|
||||
"real_dyld_binding_and_got_tamper_test": "Apple Silicon macOS host; not iPhone attack validation"
|
||||
},
|
||||
"business_checks": {
|
||||
"same_build_baseline_style_replay": "passed",
|
||||
"guarded_style_replay": "passed",
|
||||
"no_replay_normal_cache_and_reentry": "passed",
|
||||
"foreground_recovery": "passed",
|
||||
"learned_words": 0,
|
||||
"unlearned_words": 7502
|
||||
},
|
||||
"comparison": {
|
||||
"baseline_event": {
|
||||
"archive_guard_loaded": false,
|
||||
"call_id": "E69F522F-50ED-43F8-AE03-8898BF80EBB8",
|
||||
"elapsed_ms": 38.530333345988765,
|
||||
"event": "unzip_end",
|
||||
"output_bytes": 1890776,
|
||||
"output_files": 9,
|
||||
"output_fingerprint_available": true,
|
||||
"output_sha256": "7043dfcd54c6ce47154feb48b8ff2a19834c5f8cd4c28dabaa012fc96537ed79",
|
||||
"sdk": "SSZipArchive",
|
||||
"success": true,
|
||||
"time": 1794363370.44353
|
||||
},
|
||||
"guard_event": {
|
||||
"archive_guard_counters": {
|
||||
"fclose_attempted": 10,
|
||||
"fclose_dispatched": 10,
|
||||
"fclose_rejected": 0,
|
||||
"fopen_attempted": 10,
|
||||
"fopen_dispatched": 10,
|
||||
"fopen_rejected": 0,
|
||||
"fread_attempted": 388,
|
||||
"fread_dispatched": 388,
|
||||
"fread_rejected": 0,
|
||||
"fwrite_attempted": 466,
|
||||
"fwrite_dispatched": 466,
|
||||
"fwrite_rejected": 0
|
||||
},
|
||||
"archive_guard_loaded": true,
|
||||
"archive_guard_status": 0,
|
||||
"call_id": "E5F4CD08-4809-4FED-AF68-CF01D407E112",
|
||||
"elapsed_ms": 43.01520832814276,
|
||||
"event": "unzip_end",
|
||||
"output_bytes": 1890776,
|
||||
"output_files": 9,
|
||||
"output_fingerprint_available": true,
|
||||
"output_sha256": "7043dfcd54c6ce47154feb48b8ff2a19834c5f8cd4c28dabaa012fc96537ed79",
|
||||
"sdk": "SSZipArchive",
|
||||
"success": true,
|
||||
"time": 1794363764.835278
|
||||
},
|
||||
"output_digest_equal": true,
|
||||
"elapsed_delta_ms": 4.484874982153997,
|
||||
"timing_scope": "单次单机样式解压记录区间,含开始事件观察开销,不含网络及自动化等待,非性能基准"
|
||||
},
|
||||
"normal_cache": {
|
||||
"events": 9,
|
||||
"cache_hit_types": [
|
||||
"dict",
|
||||
"sound",
|
||||
"style"
|
||||
],
|
||||
"unzip_count": 0,
|
||||
"guard_statuses": [
|
||||
0
|
||||
],
|
||||
"counter_maxima": {
|
||||
"fclose_attempted": 0,
|
||||
"fclose_dispatched": 0,
|
||||
"fclose_rejected": 0,
|
||||
"fopen_attempted": 0,
|
||||
"fopen_dispatched": 0,
|
||||
"fopen_rejected": 0,
|
||||
"fread_attempted": 0,
|
||||
"fread_dispatched": 0,
|
||||
"fread_rejected": 0,
|
||||
"fwrite_attempted": 0,
|
||||
"fwrite_dispatched": 0,
|
||||
"fwrite_rejected": 0
|
||||
}
|
||||
},
|
||||
"existing_defender_during_guard": {
|
||||
"events": 5,
|
||||
"detected_events": 0,
|
||||
"unavailable_events": 0,
|
||||
"zipzap_counter_maxima": {
|
||||
"write_attempted": 0,
|
||||
"write_dispatched": 0,
|
||||
"close_attempted": 0,
|
||||
"close_dispatched": 0
|
||||
}
|
||||
},
|
||||
"original_vendor_sdk_unchanged": true,
|
||||
"observation_container_incident": {
|
||||
"target": "independent observation bundle only",
|
||||
"style_backup_files": 9,
|
||||
"reset_attempt_result": "CoreDevice7000/ActionError3",
|
||||
"observed": "Documents reinitialized after install/reset sequence; exact trigger not isolated; full container restoration not established",
|
||||
"subsequent_method": "no directory clearing; observation-only style replay",
|
||||
"login_and_resource_after_incident": "wordbook UI passed with 0 learned / 7502 unlearned"
|
||||
},
|
||||
"automation_failure_record": "guard-v2-cache.xcresult: popup disappeared while XCTest waited; no resource entered; subsequent guard-v2-cache-v2.xcresult passed",
|
||||
"uncovered": [
|
||||
"iPhone 受控 GOT 篡改",
|
||||
"实际系统代码 inline Hook",
|
||||
"SDK 下载取消及失败传播",
|
||||
"大包/长时间性能",
|
||||
"arm64e/PAC 和其他 chained 格式",
|
||||
"其他 SDK 或非四目标的 I/O",
|
||||
"生产强制业务门禁",
|
||||
"完整业务回归及原报告同版本复测"
|
||||
],
|
||||
"deferred_by_user": [
|
||||
"PDF 越界修复",
|
||||
"完整业务回归",
|
||||
"报告复测"
|
||||
],
|
||||
"guard_package": "test-results/step5-ssziparchive/guard-v2-package",
|
||||
"baseline_package": "test-results/step5-ssziparchive/baseline-v2-package",
|
||||
"evidence_directory": "test-results/step5-ssziparchive/final-evidence"
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"date": "2026-11-11",
|
||||
"timezone": "Asia/Tokyo",
|
||||
"status": "business_regression_partially_passed",
|
||||
"bundle_id": "cn.touchv.iosguard.observe.20261110",
|
||||
"source_version": "2.156.0",
|
||||
"user_completed_real_login": true,
|
||||
"fake_login": false,
|
||||
"functional_checks": {
|
||||
"home_resource_detail_and_foreground": "passed",
|
||||
"epub_content_and_foreground": "passed",
|
||||
"cold_restart": "passed"
|
||||
},
|
||||
"pdf_trial": "failed_existing_array_bounds_exception_reproduced_in_same_build_baseline",
|
||||
"pdf_exception": "NSRangeException: index 2 beyond bounds [0 .. 1]",
|
||||
"guard_restored_after_baseline": true,
|
||||
"zipzap_protected_path_business_coverage": "not_hit",
|
||||
"protection_expanded": false,
|
||||
"observation": {
|
||||
"events": 14,
|
||||
"detected_event_count": 0,
|
||||
"unavailable_event_count": 0,
|
||||
"scan_ms_min": 4.2584583279676735,
|
||||
"scan_ms_median": 14.205458341166377,
|
||||
"scan_ms_max": 29.871833336073905,
|
||||
"counter_maxima": {
|
||||
"write_attempted": 0,
|
||||
"write_dispatched": 0,
|
||||
"close_attempted": 0,
|
||||
"close_dispatched": 0
|
||||
},
|
||||
"scope": "单机小样本,含加固与基线阶段的启动/前台事件,非性能基准"
|
||||
},
|
||||
"uncovered": [
|
||||
"ZipZap 文件输出实际业务命中",
|
||||
"PDF 正常阅读/翻页",
|
||||
"下载取消及失败路径",
|
||||
"支付及第三方 Bundle ID 绑定能力",
|
||||
"实际 inline Hook",
|
||||
"原报告同版本厂商复测"
|
||||
],
|
||||
"credentials_in_driver_source": false,
|
||||
"evidence_directory": "test-results/step3/business-run-20261111"
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"date": "2026-11-11",
|
||||
"resource": "31单词书(稳操胜券)-勿动",
|
||||
"bundle_id": "cn.touchv.iosguard.observe.20261110",
|
||||
"source_version": "2.156.0",
|
||||
"status": "ssziparchive_boundary_invocation_and_wordbook_smoke_passed",
|
||||
"checks": {
|
||||
"home_to_detail": "passed",
|
||||
"wordbook_ready": "passed",
|
||||
"learned_words": 0,
|
||||
"unlearned_words": 7502,
|
||||
"background_foreground": "passed",
|
||||
"reentry": "passed",
|
||||
"reentry_cache_types": [
|
||||
"style",
|
||||
"dict",
|
||||
"sound"
|
||||
]
|
||||
},
|
||||
"archive": {
|
||||
"begin_count": 1,
|
||||
"end_count": 1,
|
||||
"successful_count": 1,
|
||||
"elapsed_ms": [
|
||||
12015.23712501512
|
||||
],
|
||||
"initial_cached_types": [
|
||||
"style",
|
||||
"dict"
|
||||
],
|
||||
"fresh_style_dict_extraction": "not_covered",
|
||||
"initial_unzip_resource_type": "not_recorded_at_sdk_boundary"
|
||||
},
|
||||
"security": {
|
||||
"new_events": 2,
|
||||
"detected_events": 0,
|
||||
"unavailable_events": 0,
|
||||
"counter_maxima": {
|
||||
"write_attempted": 0,
|
||||
"write_dispatched": 0,
|
||||
"close_attempted": 0,
|
||||
"close_dispatched": 0
|
||||
}
|
||||
},
|
||||
"protection_expanded": false,
|
||||
"sdk_internal_libc_protection_verified": false,
|
||||
"deferred_by_user": [
|
||||
"PDF 数组越界修复",
|
||||
"完整业务回归",
|
||||
"报告复测"
|
||||
],
|
||||
"driver_adjustments": [
|
||||
"detail.xcresult: 首页营销弹窗导致不可点击",
|
||||
"detail-v2.xcresult: 进入详情壳;截图尚在骨架加载",
|
||||
"read.xcresult: 该商品无开始阅读按钮,入口为稳操胜券课件卡片",
|
||||
"read-v2.xcresult: 课件卡片进入、就绪及前后台通过",
|
||||
"reentry.xcresult: 返回重进、缓存及前后台通过"
|
||||
],
|
||||
"evidence_directory": "test-results/step4-wordbook/business-run",
|
||||
"limitations": [
|
||||
"SDK 调用成功是 SDK 返回值,未逐文件校验输出内容",
|
||||
"未进入学习/复习或完成学习任务",
|
||||
"未做故障注入及 SDK 内部 fopen/fwrite 调度加固"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 访问真实观察包;不使用 --UITesting,不注入 token,不调用购买接口。
|
||||
final class IGBusinessRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.iosguard.observe.20261110"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
// 截图遮盖输入框,文本树移除输入值,避免登录排查留存凭证。
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
func testInspectLaunch() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
capture(app, "observation-launch")
|
||||
}
|
||||
|
||||
func testInspectCurrentPage() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
capture(app, "observation-current")
|
||||
}
|
||||
|
||||
func testAllowWifiAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
|
||||
let wifi = springboard.buttons["仅限无线局域网"]
|
||||
if wifi.waitForExistence(timeout: 5) { wifi.tap() }
|
||||
app.activate()
|
||||
_ = app.images["splash"].waitForNonExistence(timeout: 20)
|
||||
capture(app, "after-network-permission")
|
||||
}
|
||||
|
||||
func testHomeResourceAndForeground() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
XCTAssertTrue(home.waitForExistence(timeout: 30), "需先完成真实登录与启动流程")
|
||||
// 实际首页资源由 TableCell 内自绘卡片承载,使用已观察到的资源标题。
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
capture(app, "home-before-resource")
|
||||
resource.tap()
|
||||
let detail = app.otherElements["detail_page_anchor"]
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 20), "首个首页卡片未进入商品详情")
|
||||
capture(app, "resource-detail")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(detail.waitForExistence(timeout: 10))
|
||||
capture(app, "resource-after-foreground")
|
||||
}
|
||||
|
||||
func testTrialResourceAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
// 入口可能先展示课件/规格选择,先留存真实页面再决定下一步。
|
||||
capture(app, "after-trial-entry")
|
||||
}
|
||||
|
||||
func testColdRestartAndInspect() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30))
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
capture(app, "after-cold-restart")
|
||||
}
|
||||
|
||||
func testPDFTrialAndPageTurn() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["[pdf]MW书籍测试读"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 15))
|
||||
trial.tap()
|
||||
XCTAssertTrue(app.buttons["titlebar return phone"].waitForExistence(timeout: 20))
|
||||
_ = app.progressIndicators["进度"].waitForNonExistence(timeout: 30)
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5))
|
||||
capture(app, "pdf-before-page-turn")
|
||||
app.swipeLeft()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 5), "PDF 翻页后进程退出")
|
||||
capture(app, "pdf-after-page-turn")
|
||||
}
|
||||
|
||||
func testEPUBResourceAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let resource = app.staticTexts["【epub】会员免费书籍"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "epub-detail")
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let trial = app.buttons["试读"].firstMatch
|
||||
if read.exists { read.tap() }
|
||||
else {
|
||||
XCTAssertTrue(trial.waitForExistence(timeout: 10), "本账号没有可用阅读入口")
|
||||
trial.tap()
|
||||
}
|
||||
capture(app, "epub-entry")
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 30), "尚未出现 EPUB 内容视图")
|
||||
capture(app, "epub-content")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(app.webViews.firstMatch.waitForExistence(timeout: 15))
|
||||
capture(app, "epub-after-foreground")
|
||||
}
|
||||
func testWordbookOpenAndInspect() {
|
||||
openWordbook(replayStyle: true)
|
||||
}
|
||||
|
||||
private func openWordbook(replayStyle: Bool) {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.launchArguments = replayStyle ? ["--IGArchiveReplayStyle"] : []
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 30))
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForExistence(timeout: 5) { popupClose.tap() }
|
||||
capture(app, "wordbook-home")
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 20))
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
capture(app, "wordbook-detail")
|
||||
}
|
||||
|
||||
func testWordbookReadAndForeground() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let read = app.buttons["开始阅读"].firstMatch
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 20), "需先打开指定单词书详情")
|
||||
capture(app, "wordbook-loaded-detail")
|
||||
if read.exists { read.tap() } else { section.tap() }
|
||||
capture(app, "wordbook-after-read-entry")
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 120), "单词书未准备完成")
|
||||
XCTAssertTrue(ready.isHittable, "单词书就绪内容不可见")
|
||||
capture(app, "wordbook-ready")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-after-foreground")
|
||||
}
|
||||
|
||||
func testWordbookReentryAndCache() {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
let back = app.buttons["mw backBar img"].firstMatch
|
||||
XCTAssertTrue(back.waitForExistence(timeout: 10))
|
||||
back.tap()
|
||||
let section = app.staticTexts["稳操胜券"].firstMatch
|
||||
XCTAssertTrue(section.waitForExistence(timeout: 15))
|
||||
section.tap()
|
||||
let ready = app.staticTexts["今日学习单词了吗?"].firstMatch
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 60))
|
||||
XCTAssertTrue(ready.isHittable)
|
||||
capture(app, "wordbook-reentry-cache")
|
||||
XCUIDevice.shared.press(.home)
|
||||
XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10))
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
|
||||
XCTAssertTrue(ready.waitForExistence(timeout: 15))
|
||||
capture(app, "wordbook-reentry-foreground")
|
||||
}
|
||||
|
||||
func testWordbookFreshExtraction() {
|
||||
testWordbookOpenAndInspect()
|
||||
testWordbookReadAndForeground()
|
||||
}
|
||||
|
||||
func testWordbookCachedEntryAndReentry() {
|
||||
// 由单独无参数启动步骤进入首页,避免将短暂营销弹窗的自动消失误记为业务失败。
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
app.activate()
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: 20))
|
||||
let resource = app.staticTexts["31单词书(稳操胜券)-勿动"].firstMatch
|
||||
XCTAssertTrue(resource.waitForExistence(timeout: 15))
|
||||
XCTAssertTrue(resource.isHittable)
|
||||
resource.tap()
|
||||
XCTAssertTrue(app.otherElements["detail_page_anchor"].waitForExistence(timeout: 20))
|
||||
testWordbookReadAndForeground()
|
||||
testWordbookReentryAndCache()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
import XCTest
|
||||
import UIKit
|
||||
|
||||
/// 反 Hook 门禁按钮级回归(强制模式 dev 包 cn.touchv.a4YX061)。
|
||||
///
|
||||
/// 相位(按方法名字典序执行):
|
||||
/// A1 干净启动勘察;A2 登出到登录页(个人中心 退出登录);
|
||||
/// B1 注入启动·密码登录门禁;B2 注入启动·第三方登录门禁;
|
||||
/// C1 干净启动·密码登录放行(DEBUG 预填测试账号真实登录);
|
||||
/// D1 注入启动·VIP 购买门禁(会员页);E1 注入启动·激活码门禁(我的页探测入口)。
|
||||
///
|
||||
/// 注入:编排器(run_gate_regression.sh)以 devicectl `-e DYLD_INSERT_LIBRARIES`
|
||||
/// 调试启动通道预先注入启动(空壳 libfrida-sim.dylib),注入相位测试仅 activate()
|
||||
/// attach 到该进程——v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT 经
|
||||
/// SpringBoard 启动链被剥离,门禁不触发。各相位以 -only-testing 分批执行(v6 序,
|
||||
/// XCUITest↔devicectl 切换仅 2 次):干净批 A1/A2(游客态)→ 注入批 B1/B2(游客)
|
||||
/// → 干净批 C1(放行证明)→ 注入批 D1/E1(登录态,未登成则游客守卫跳过)。
|
||||
/// v5e 教训:devicectl `--console` 通道在连续会话后整体卡死(零输出+进程即死),
|
||||
/// 注入启动不用 console,注入生效由测试内门禁 toast 端到端自证。
|
||||
/// 教训(B2 首版崩溃):营销弹窗自动消失瞬间盲点「rd pop close」会落到其下方的
|
||||
/// 首页搜索按钮,触发路由重复注册 assertion 崩溃(业务既有 bug)——先等自然消失再点,
|
||||
/// 且点击前复核存在与可点性。
|
||||
/// 凭证不入日志:截图遮盖输入框、文本树脱敏(沿用业务观察 Runner 做法)。
|
||||
final class IGGateRegressionTests: XCTestCase {
|
||||
private let bundleID = "cn.touchv.a4YX061"
|
||||
private var injectLib: String? { ProcessInfo.processInfo.environment["INJECT_LIB"] }
|
||||
private let blockLoginToast = "当前环境暂时无法登录,请稍后重试"
|
||||
private let blockVipToast = "当前环境暂时无法购买,请稍后重试"
|
||||
private let blockActivationToast = "当前环境暂时无法激活,请稍后重试"
|
||||
|
||||
override func setUpWithError() throws { continueAfterFailure = false }
|
||||
|
||||
// MARK: - 工具
|
||||
|
||||
/// 脱敏截图(遮盖输入框)+ 脱敏文本树,全部 keepAlways 留证。
|
||||
private func capture(_ app: XCUIApplication, _ name: String) {
|
||||
let source = app.screenshot().image
|
||||
let fields = app.textFields.allElementsBoundByIndex + app.secureTextFields.allElementsBoundByIndex
|
||||
let screenshotImage = UIGraphicsImageRenderer(size: source.size).image { context in
|
||||
source.draw(at: .zero)
|
||||
UIColor.lightGray.setFill()
|
||||
let sx = source.size.width / app.frame.width
|
||||
let sy = source.size.height / app.frame.height
|
||||
for field in fields {
|
||||
let frame = field.frame
|
||||
context.fill(CGRect(x: frame.minX * sx, y: frame.minY * sy,
|
||||
width: frame.width * sx, height: frame.height * sy))
|
||||
}
|
||||
}
|
||||
let screenshot = XCTAttachment(image: screenshotImage)
|
||||
screenshot.name = name
|
||||
screenshot.lifetime = .keepAlways
|
||||
add(screenshot)
|
||||
let redactedTree = app.debugDescription.components(separatedBy: "\n").map { line in
|
||||
guard line.contains("TextField"), let value = line.range(of: ", value:") else { return line }
|
||||
return String(line[..<value.lowerBound]) + ", value: [redacted]"
|
||||
}.joined(separator: "\n")
|
||||
let tree = XCTAttachment(string: redactedTree)
|
||||
tree.name = name + "-accessibility"
|
||||
tree.lifetime = .keepAlways
|
||||
add(tree)
|
||||
}
|
||||
|
||||
private func step(_ message: String) {
|
||||
NSLog("[GateRegression] %@", message)
|
||||
}
|
||||
|
||||
private func launchApp(_ app: XCUIApplication, injected: Bool) throws {
|
||||
if injected {
|
||||
// v4 教训:XCUITest launchEnvironment 的 DYLD_INSERT_LIBRARIES 经 SpringBoard
|
||||
// 启动链被剥离(B1 门禁 toast 不出现)——注入进程由编排器以 devicectl
|
||||
// `-e` 调试启动通道预先启动,测试只 attach(activate 不重启,注入保持)。
|
||||
guard app.state == .runningForeground || app.state == .runningBackground else {
|
||||
try skipAndCapture("注入进程未运行(编排器须先 devicectl 注入启动本 App)")
|
||||
}
|
||||
app.activate()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 30), "注入进程未进前台")
|
||||
return
|
||||
}
|
||||
app.terminate()
|
||||
app.launch()
|
||||
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 40), "应用未进入前台")
|
||||
}
|
||||
|
||||
private func skipAndCapture(_ reason: String) throws -> Never {
|
||||
step("SKIP: \(reason)")
|
||||
throw XCTSkip(reason)
|
||||
}
|
||||
|
||||
/// 等待登录页或首页锚点,返回 "login" / "home" / "unknown"。
|
||||
private func waitLoginOrHome(_ app: XCUIApplication, timeout: TimeInterval = 25) -> String {
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: timeout) { return "login" }
|
||||
if app.otherElements["home_page_anchor"].waitForExistence(timeout: 10) { return "home" }
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
/// 关闭可能遮挡的营销弹窗:先等自然消失(约 6 秒),仍在且可点才点关闭。
|
||||
/// 不盲点:弹窗消失瞬间点击会落到其下方控件(首版曾误触首页搜索引发路由崩溃)。
|
||||
private func dismissPopups(_ app: XCUIApplication) {
|
||||
let popupClose = app.buttons["rd pop close"]
|
||||
if popupClose.waitForNonExistence(timeout: 6) { return }
|
||||
if popupClose.exists && popupClose.isHittable {
|
||||
popupClose.tap()
|
||||
_ = popupClose.waitForNonExistence(timeout: 3)
|
||||
}
|
||||
}
|
||||
|
||||
/// 勾选登录协议(v3 登录页树:勾选框暴露 identifier login_agreement_checkbox)。
|
||||
private func selectAgreementIfNeeded(_ app: XCUIApplication) {
|
||||
let agreement = app.otherElements["login_agreement_view"]
|
||||
_ = agreement.waitForExistence(timeout: 10)
|
||||
let checkbox = app.buttons["login_agreement_checkbox"].firstMatch
|
||||
if checkbox.exists {
|
||||
if checkbox.isHittable { checkbox.tap() }
|
||||
step("已点击协议勾选框")
|
||||
} else {
|
||||
let fallback = agreement.buttons.firstMatch
|
||||
if fallback.exists, fallback.isHittable {
|
||||
fallback.tap()
|
||||
step("勾选框无 identifier,已点协议视图内按钮")
|
||||
} else {
|
||||
step("协议勾选框未暴露,跳过勾选")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 断言门禁 toast 出现并等其消失。
|
||||
private func assertToast(_ app: XCUIApplication, text: String, label: String) {
|
||||
let toast = app.staticTexts[text].firstMatch
|
||||
XCTAssertTrue(toast.waitForExistence(timeout: 6), "\(label):未出现门禁 toast「\(text)」")
|
||||
capture(app, label + "-toast")
|
||||
_ = toast.waitForNonExistence(timeout: 8)
|
||||
}
|
||||
|
||||
/// 首页就绪并稳定(弹窗处理完成)。
|
||||
private func waitHomeStable(_ app: XCUIApplication, timeout: TimeInterval = 30) throws {
|
||||
XCTAssertTrue(app.otherElements["home_page_anchor"].waitForExistence(timeout: timeout), "未进入首页")
|
||||
dismissPopups(app)
|
||||
}
|
||||
|
||||
/// 游客态从首页导航到登录页:「我的」页「登录/注册」按钮(v2 勘察树确认)。
|
||||
/// 返回 false 表示入口不可达(多为已登录态),由调用方决定跳过或走既有会话判定。
|
||||
/// v3 教训:启动偶发落在无 tab bar 的推广落地页(AllTypes 书城页)——
|
||||
/// 先等待/返回自救,仍无 tab 则重启一次重抽落地页。
|
||||
private func navigateToLoginFromHome(_ app: XCUIApplication, allowRelaunch: Bool = true) -> Bool {
|
||||
func attempt() -> Bool {
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
if !mineTab.waitForExistence(timeout: 12) {
|
||||
// 落地页自救:点导航返回键(若在二级页)后再等 tab。
|
||||
let back = app.buttons["nav black goback"].firstMatch
|
||||
if back.exists, back.isHittable {
|
||||
back.tap()
|
||||
step("落地页无 tab,已点返回")
|
||||
}
|
||||
if !mineTab.waitForExistence(timeout: 12) { return false }
|
||||
}
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
dismissPopups(app)
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
guard guestEntry.waitForExistence(timeout: 8), guestEntry.isHittable else { return false }
|
||||
guestEntry.tap()
|
||||
return app.otherElements["login_page_anchor"].waitForExistence(timeout: 20)
|
||||
}
|
||||
if attempt() { return true }
|
||||
guard allowRelaunch else { return false }
|
||||
step("首轮导航失败,重启重抽落地页")
|
||||
app.terminate()
|
||||
app.launch()
|
||||
guard app.wait(for: .runningForeground, timeout: 40) else { return false }
|
||||
_ = app.otherElements["home_page_anchor"].waitForExistence(timeout: 25)
|
||||
dismissPopups(app)
|
||||
return attempt()
|
||||
}
|
||||
|
||||
// MARK: - A 勘察与登出
|
||||
|
||||
func testA1InspectCleanState() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A1 干净启动勘察开始,INJECT_LIB=\(injectLib ?? "未传入")")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
step("A1 启动状态=\(state)")
|
||||
if state == "home" { dismissPopups(app) }
|
||||
capture(app, "a1-clean-\(state)")
|
||||
}
|
||||
|
||||
func testA2LogoutIfNeeded() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("A2 确保登录页可达(游客直进;登录态经设置页登出)")
|
||||
try launchApp(app, injected: false)
|
||||
let state = waitLoginOrHome(app)
|
||||
if state == "login" {
|
||||
step("A2 已在登录页")
|
||||
capture(app, "a2-already-login")
|
||||
return
|
||||
}
|
||||
guard state == "home" else { try skipAndCapture("A2 首页不可达(状态 \(state))") }
|
||||
dismissPopups(app)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
_ = app.otherElements["personal_center_page_anchor"].waitForExistence(timeout: 10)
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "a2-mine-page")
|
||||
// 游客态(v2 树:登录/注册按钮)直接进登录页,B 阶段即可测登录门禁。
|
||||
let guestEntry = app.buttons["登录/注册"].firstMatch
|
||||
if guestEntry.exists, guestEntry.isHittable {
|
||||
guestEntry.tap()
|
||||
XCTAssertTrue(app.otherElements["login_page_anchor"].waitForExistence(timeout: 20), "游客点「登录/注册」未进入登录页")
|
||||
step("A2 游客态进入登录页")
|
||||
capture(app, "a2-guest-login-page")
|
||||
return
|
||||
}
|
||||
// 登录态:右上角设置图标(v2 树:personalCenter setting)→ 设置页底部「退出登录」。
|
||||
let settingIcon = app.buttons["personalCenter setting"].firstMatch
|
||||
XCTAssertTrue(settingIcon.exists && settingIcon.isHittable, "未找到设置入口(见 a2 勘察树)")
|
||||
settingIcon.tap()
|
||||
sleep(2)
|
||||
capture(app, "a2-settings-page")
|
||||
// 退出登录在设置列表尾部,滚动查找(cell 标签为文本)。
|
||||
var confirmedLogout = false
|
||||
for _ in 0..<4 where !confirmedLogout {
|
||||
let logoutBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
let logoutText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS '退出登录'")).firstMatch
|
||||
if logoutBtn.exists { logoutBtn.tap(); confirmedLogout = true }
|
||||
else if logoutText.exists { logoutText.tap(); confirmedLogout = true }
|
||||
else { app.swipeUp() }
|
||||
}
|
||||
XCTAssertTrue(confirmedLogout, "设置页未找到退出登录入口(见 a2-settings-page 树)")
|
||||
sleep(1)
|
||||
capture(app, "a2-logout-confirm")
|
||||
// 确认弹窗(自定义两键弹窗,右侧确认键常见文案逐个尝试)。
|
||||
for confirm in ["确定", "退出", "确认", "退出登录"] {
|
||||
let button = app.buttons[confirm].firstMatch
|
||||
if button.waitForExistence(timeout: 2) && button.isHittable {
|
||||
button.tap()
|
||||
step("A2 确认退出(「\(confirm)」)")
|
||||
break
|
||||
}
|
||||
}
|
||||
let back = waitLoginOrHome(app, timeout: 30)
|
||||
step("A2 登出后状态=\(back)")
|
||||
capture(app, "a2-after-logout-\(back)")
|
||||
XCTAssertEqual(back, "login", "登出后未回到登录页")
|
||||
}
|
||||
|
||||
// MARK: - B 拦截相位(注入启动·登录入口)
|
||||
|
||||
func testB1BlockPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B1 注入启动·密码登录门禁")
|
||||
try launchApp(app, injected: true)
|
||||
// 注入相位严禁 clean 重启(activate 之外的 launch 会丢 DYLD 注入),
|
||||
// navigate 不带 relaunch 自救;导航失败即跳过留证。
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
capture(app, "b1-inject-\(state)")
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B1 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
capture(app, "b1-login-page")
|
||||
// 门禁在输入校验之前:空输入点击提交也必须先命中门禁 toast。
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
submit.tap()
|
||||
assertToast(app, text: blockLoginToast, label: "b1-block-password-login")
|
||||
// 门禁 toast 之外不应出现协议弹窗(出现说明执行越过了门禁)。
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
XCTAssertFalse(agreementAlert.waitForExistence(timeout: 2), "点击越过了门禁(出现协议弹窗)")
|
||||
capture(app, "b1-block-after")
|
||||
}
|
||||
|
||||
func testB2BlockOtherLogins() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("B2 注入启动·第三方登录门禁(微信/QQ/Apple/Weread)")
|
||||
try launchApp(app, injected: true)
|
||||
var state = waitLoginOrHome(app)
|
||||
if state == "home", navigateToLoginFromHome(app, allowRelaunch: false) { state = "login" }
|
||||
guard state == "login" else {
|
||||
try skipAndCapture("B2 登录页不可达(状态 \(state),游客入口缺失)")
|
||||
}
|
||||
selectAgreementIfNeeded(app)
|
||||
capture(app, "b2-login-page")
|
||||
// v3 登录页树:第三方按钮为纯图片,label 即图片名(rd login wechat/qq/apple/wjOauth2)。
|
||||
var tapped = 0
|
||||
for label in ["rd login wechat", "rd login qq", "rd login apple", "rd login wjOauth2"] {
|
||||
let entry = app.buttons[label].firstMatch
|
||||
guard entry.waitForExistence(timeout: 3), entry.isHittable else { continue }
|
||||
entry.tap()
|
||||
tapped += 1
|
||||
step("B2 点击第三方入口「\(label)」")
|
||||
assertToast(app, text: blockLoginToast, label: "b2-block-\(label)")
|
||||
}
|
||||
if tapped == 0 {
|
||||
capture(app, "b2-no-third-party-buttons")
|
||||
try skipAndCapture("登录页未暴露可识别的第三方登录按钮(见 b2-login-page 树)")
|
||||
}
|
||||
step("B2 完成,拦截入口数=\(tapped)")
|
||||
}
|
||||
|
||||
// MARK: - C 放行相位(干净启动·真实登录)
|
||||
|
||||
func testC1AllowPasswordLogin() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("C1 干净启动·密码登录放行")
|
||||
try launchApp(app, injected: false)
|
||||
let bootState = waitLoginOrHome(app)
|
||||
var loginReached = bootState == "login"
|
||||
if !loginReached, bootState == "home" {
|
||||
// 游客态(home ≠ 已登录)也从「我的」页进入登录页做真实登录。
|
||||
loginReached = navigateToLoginFromHome(app)
|
||||
}
|
||||
if !loginReached {
|
||||
step("C1 登录页不可达且我的页无「登录/注册」(已登录态),放行以启动期零拦截与既有会话为证")
|
||||
capture(app, "c1-already-home")
|
||||
return
|
||||
}
|
||||
capture(app, "c1-login-page")
|
||||
selectAgreementIfNeeded(app)
|
||||
let submit = app.buttons["login_submit_button"]
|
||||
XCTAssertTrue(submit.waitForExistence(timeout: 10), "未找到登录提交按钮")
|
||||
if !submit.isEnabled {
|
||||
// 提交钮不可用才尝试补输入(v5d 教训:验证码框存在不代表必填,
|
||||
// 盲填占位值反而制造服务端拒绝)。先补图形验证码占位值,再退化到账号框刷新。
|
||||
let captcha = app.textFields.containing(NSPredicate(format: "placeholderValue CONTAINS '验证码'")).firstMatch
|
||||
if captcha.exists {
|
||||
captcha.tap()
|
||||
captcha.typeText("1111")
|
||||
step("C1 提交钮不可用,已补图形验证码占位值 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
if !submit.isEnabled {
|
||||
let account = app.textFields["login_phone_input"].firstMatch
|
||||
if account.exists { account.tap(); account.typeText("1") }
|
||||
step("C1 仍不可用,已触发账号输入刷新 isEnabled=\(submit.isEnabled)")
|
||||
}
|
||||
}
|
||||
capture(app, "c1-before-submit")
|
||||
submit.tap()
|
||||
// 放行判定(v6 修订):核心断言 = 门禁 toast 不出现(门禁放行)。
|
||||
// 业务进展尽力而为留证:DEBUG 预填账号的图形验证码无法自动识别,服务端
|
||||
// 拒绝时停留登录页属业务侧限制而非门禁问题(v5e 留证:干净提交后门禁
|
||||
// toast 与协议弹窗均未出现)。登录态若未建立,D1/E1 以游客守卫跳过。
|
||||
let gateToast = app.staticTexts[blockLoginToast].firstMatch
|
||||
XCTAssertFalse(gateToast.waitForExistence(timeout: 6), "干净环境出现门禁 toast(误拦截)")
|
||||
let home = app.otherElements["home_page_anchor"]
|
||||
let agreementAlert = app.alerts["请先阅读并同意协议"]
|
||||
let progress = home.waitForExistence(timeout: 45)
|
||||
|| agreementAlert.waitForExistence(timeout: 5)
|
||||
step("C1 门禁放行成立;业务进展标记=\(progress)(验证码服务端拒绝属业务侧限制)")
|
||||
capture(app, "c1-after-login-attempt")
|
||||
}
|
||||
|
||||
// MARK: - D/E 拦截相位(注入启动·VIP 与激活入口)
|
||||
|
||||
func testD1BlockVipPurchase() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("D1 注入启动·VIP 购买门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let vipTab = app.tabBars.buttons["会员"].firstMatch
|
||||
XCTAssertTrue(vipTab.waitForExistence(timeout: 10), "未找到「会员」页签")
|
||||
vipTab.tap()
|
||||
// v3 树:会员页用户区游客显示「游客」——登录态缺失时购买被业务游客检查
|
||||
// 拦在 sendPayVip 门禁之前,skip 留证而不误判门禁失效。
|
||||
_ = app.staticTexts["游客"].waitForExistence(timeout: 5)
|
||||
if app.staticTexts["游客"].firstMatch.exists {
|
||||
capture(app, "d1-guest-state")
|
||||
try skipAndCapture("会员页为游客态(C1 未建立登录态),VIP 门禁需登录后重跑")
|
||||
}
|
||||
// v2 树:购买按钮为富文本 label(如「立即购买 · ¥6.00 100.00」),已会员时为「立即续费 …」。
|
||||
let buyPred = NSPredicate(format: "label BEGINSWITH '立即购买' OR label BEGINSWITH '立即续费'")
|
||||
let buyBtn = app.buttons.containing(buyPred).firstMatch
|
||||
XCTAssertTrue(buyBtn.waitForExistence(timeout: 15), "会员页未出现购买按钮(见 d1 勘察树)")
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "d1-vip-page")
|
||||
// 先勾选 VIP 协议(未勾选时点购买先弹协议提示,越不过门禁汇合点)。
|
||||
let checkbox = app.buttons["rd vip checkbox unselect"].firstMatch
|
||||
if checkbox.exists, checkbox.isHittable {
|
||||
checkbox.tap()
|
||||
step("D1 已勾选 VIP 协议")
|
||||
} else {
|
||||
capture(app, "d1-checkbox-missing")
|
||||
}
|
||||
buyBtn.tap()
|
||||
step("D1 点击购买按钮「\(buyBtn.label)」")
|
||||
assertToast(app, text: blockVipToast, label: "d1-block-vip")
|
||||
}
|
||||
|
||||
func testE1BlockActivation() throws {
|
||||
let app = XCUIApplication(bundleIdentifier: bundleID)
|
||||
step("E1 注入启动·激活码门禁")
|
||||
try launchApp(app, injected: true)
|
||||
try waitHomeStable(app, timeout: 90)
|
||||
let mineTab = app.tabBars.buttons["我的"].firstMatch
|
||||
XCTAssertTrue(mineTab.waitForExistence(timeout: 10), "未找到「我的」页签")
|
||||
mineTab.tap()
|
||||
sleep(2)
|
||||
dismissPopups(app)
|
||||
capture(app, "e1-mine-page")
|
||||
// 激活入口探测(标签以勘察树为准)。
|
||||
var activationEntered = false
|
||||
for keyword in ["激活码", "激活"] {
|
||||
let entryBtn = app.buttons.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
let entryText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", keyword)).firstMatch
|
||||
if entryBtn.exists { entryBtn.tap(); activationEntered = true; step("E1 点击「\(keyword)」按钮入口"); break }
|
||||
if entryText.exists { entryText.tap(); activationEntered = true; step("E1 点击「\(keyword)」文本入口"); break }
|
||||
}
|
||||
guard activationEntered else {
|
||||
capture(app, "e1-no-activation-entry")
|
||||
try skipAndCapture("「我的」页未找到激活入口,需按勘察树修正导航")
|
||||
}
|
||||
sleep(2)
|
||||
// v3 教训:游客点「激活码」被带到登录页(激活需登录态)——先判定落点。
|
||||
if app.otherElements["login_page_anchor"].waitForExistence(timeout: 5) {
|
||||
capture(app, "e1-guest-to-login")
|
||||
try skipAndCapture("激活入口要求登录态(C1 未建立登录会话),激活门禁需登录后重跑")
|
||||
}
|
||||
capture(app, "e1-activation-page")
|
||||
// 激活码输入(被拦截环境填占位值即可,请求不会发出)。
|
||||
let codeField = (app.textFields.firstMatch.exists ? app.textFields : app.secureTextFields).firstMatch
|
||||
if codeField.exists {
|
||||
codeField.tap()
|
||||
codeField.typeText("1")
|
||||
}
|
||||
var activated = false
|
||||
for label in ["立即激活", "激活", "确定"] {
|
||||
let button = app.buttons[label].firstMatch
|
||||
if button.exists, button.isHittable { button.tap(); activated = true; step("E1 点击激活按钮「\(label)」"); break }
|
||||
}
|
||||
XCTAssertTrue(activated, "激活页未找到激活按钮(见 e1-activation-page 树)")
|
||||
assertToast(app, text: blockActivationToast, label: "e1-block-activation")
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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");
|
||||
uint64_t (*counter)(unsigned) = dlsym(sdk,"ig_archive_counter");
|
||||
assert(io && check && counter && check() == 0);
|
||||
assert(!io(argv[2],"abcdef",6));
|
||||
for (unsigned i=0;i<4;i++) assert(counter(i*3)>0 && counter(i*3)==counter(i*3+1) && !counter(i*3+2));
|
||||
const struct mach_header_64 *header = NULL;
|
||||
intptr_t slide = 0;
|
||||
for (uint32_t i=0;i<_dyld_image_count();i++) {
|
||||
const char *name = _dyld_get_image_name(i);
|
||||
if (name && strstr(name,"/SSZipArchive.framework/SSZipArchive")) {
|
||||
header=(const void *)_dyld_get_image_header(i); slide=_dyld_get_image_vmaddr_slide(i); break;
|
||||
}
|
||||
}
|
||||
assert(header);
|
||||
const struct symtab_command *symtab=NULL;
|
||||
const struct dysymtab_command *dysymtab=NULL;
|
||||
uintptr_t base=0;
|
||||
const uint8_t *command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SYMTAB) symtab=(const void *)lc;
|
||||
if (lc->cmd==LC_DYSYMTAB) dysymtab=(const void *)lc;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
if (!strcmp(seg->segname,SEG_LINKEDIT)) base=slide+seg->vmaddr-seg->fileoff;
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(base && symtab && dysymtab);
|
||||
const struct nlist_64 *symbols=(const void *)(base+symtab->symoff);
|
||||
const char *strings=(const void *)(base+symtab->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dysymtab->indirectsymoff);
|
||||
uintptr_t *slot=NULL;
|
||||
command=(const void *)(header+1);
|
||||
for (uint32_t i=0;i<header->ncmds;i++) {
|
||||
const struct load_command *lc=(const void *)command;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)lc;
|
||||
const struct section_64 *sections=(const void *)(seg+1);
|
||||
for (uint32_t j=0;j<seg->nsects;j++) {
|
||||
const struct section_64 *s=sections+j;
|
||||
if ((s->flags&SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
command+=lc->cmdsize;
|
||||
}
|
||||
assert(slot);
|
||||
uintptr_t original=*slot;
|
||||
vm_address_t page=(uintptr_t)slot & ~((uintptr_t)vm_page_size-1);
|
||||
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");
|
||||
assert(close_entry && !close_entry("unused","rb") && errno==EACCES);
|
||||
*slot=original;
|
||||
assert(check()==0);
|
||||
assert(!io(argv[2],"ghijkl",6)); unlink(argv[2]);
|
||||
puts("真实 chained binding 转发、GOT 篡改检测及拒绝、恢复均通过");
|
||||
return 0;
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
#include "dispatch/IGArchiveGuard.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static unsigned fake_calls;
|
||||
static FILE *fake_open(const char *a, const char *b) { (void)a; (void)b; fake_calls++; return NULL; }
|
||||
static void semantics(void) {
|
||||
char path[] = "/tmp/ig-archive-XXXXXX";
|
||||
int fd = mkstemp(path); assert(fd >= 0); close(fd);
|
||||
errno = EDOM;
|
||||
FILE *out = ig_a0(path, "wb"); assert(out && errno == EDOM);
|
||||
assert(ig_a2("abcdef", 2, 3, out) == 3);
|
||||
assert(ig_a2("", 0, 4, out) == 0);
|
||||
assert(ig_a3(out) == 0);
|
||||
FILE *in = ig_a0(path, "rb"); assert(in);
|
||||
char buffer[16] = {0};
|
||||
assert(ig_a1(buffer, 2, 4, in) == 3);
|
||||
assert(!memcmp(buffer, "abcdef", 6) && feof(in) && !ferror(in));
|
||||
assert(ig_a1(buffer, 1, 1, in) == 0);
|
||||
assert(ig_a3(in) == 0); unlink(path);
|
||||
errno = 0; assert(!ig_a0(path, "rb") && errno == ENOENT);
|
||||
FILE *system = tmpfile(); assert(system);
|
||||
assert(ig_a2("abc", 1, 3, system) == 3);
|
||||
rewind(system); assert(ig_a1(buffer, 1, 3, system) == 3); assert(ig_a3(system) == 0);
|
||||
assert(ig_archive_check() == 0);
|
||||
}
|
||||
static void *thread_run(void *ctx) { (void)ctx; semantics(); return NULL; }
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "semantics")) semantics();
|
||||
else if (!strcmp(argv[1], "threads")) {
|
||||
pthread_t t[6];
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_create(t+i,NULL,thread_run,NULL));
|
||||
for (unsigned i=0;i<6;i++) assert(!pthread_join(t[i],NULL));
|
||||
} else if (!strcmp(argv[1], "tamper")) {
|
||||
ig_archive_test_override(0, (void *)fake_open);
|
||||
assert(ig_a0("unused", "rb") == NULL && errno == EACCES && !fake_calls);
|
||||
errno = EDOM; assert(ig_archive_check() == 1 && errno == EDOM);
|
||||
assert(ig_archive_counter(0) == 1 && ig_archive_counter(1) == 0 && ig_archive_counter(2) == 1);
|
||||
} else if (!strcmp(argv[1], "reentry")) {
|
||||
ig_archive_test_reentry(1);
|
||||
assert(!ig_a0("unused", "rb") && errno == EDEADLK);
|
||||
assert(ig_archive_check() == -1);
|
||||
ig_archive_test_reentry(0); semantics();
|
||||
} else if (!strcmp(argv[1], "rejection")) {
|
||||
FILE *f = tmpfile(); assert(f);
|
||||
char b;
|
||||
for (unsigned i=1;i<4;i++) ig_archive_test_override(i, (void *)fake_open);
|
||||
assert(ig_a1(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a2(&b,1,1,f)==0 && errno==EACCES);
|
||||
assert(ig_a3(f)==EOF && errno==EACCES);
|
||||
assert(!fake_calls); fclose(f);
|
||||
} else assert(0);
|
||||
return 0;
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
/* 动态 SDK fixture:必须通过真实的四个导入完成一次 stdio 往返。 */
|
||||
int archive_fixture_io(const char *path, const char *bytes, size_t count) {
|
||||
FILE *file = fopen(path, "wb");
|
||||
if (!file) return 1;
|
||||
size_t written = fwrite(bytes, 1, count, file);
|
||||
if (fclose(file) || written != count) return 2;
|
||||
file = fopen(path, "rb");
|
||||
if (!file) return 3;
|
||||
char buffer[64] = {0};
|
||||
size_t read = fread(buffer, 1, sizeof(buffer), file);
|
||||
int closed = fclose(file);
|
||||
return closed || read != count || memcmp(bytes, buffer, count) ? 4 : 0;
|
||||
}
|
||||
Vendored
+159
@@ -0,0 +1,159 @@
|
||||
/* 仅宿主测试进程内操作;不修改系统函数代码。 */
|
||||
#include "IGDefender.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include "anti_hook/IGObjCBaseline.h"
|
||||
#include "anti_debug/IGAntiDebug.h"
|
||||
#include "anti_frida/IGAntiInject.h"
|
||||
#include <dlfcn.h>
|
||||
#include <objc/objc.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach-o/dyld.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <mach-o/nlist.h>
|
||||
|
||||
typedef struct { int reasons[256]; int detected; int unavailable; } Findings;
|
||||
static int collect(const IGFinding *f, void *context) {
|
||||
Findings *out = context;
|
||||
if (f->reason >= 0 && f->reason < 256) out->reasons[f->reason]++;
|
||||
if (f->status == IG_DETECTED) out->detected++;
|
||||
if (f->status == IG_UNAVAILABLE) out->unavailable++;
|
||||
printf("status=%d reason=%d subject=%s evidence=%s\n",
|
||||
f->status, f->reason, f->subject, f->evidence);
|
||||
return 0;
|
||||
}
|
||||
static int fake_getpid(void) { return 123; }
|
||||
/* 函数地址表达式确保本测试镜像包含 getpid 的 GOT 引用。 */
|
||||
__attribute__((noinline)) static void *getpid_address(void) { return (void *)getpid; }
|
||||
|
||||
/* ---- ObjC IMP 基线 fixture:运行期创建类,两条实现可互换 ---- */
|
||||
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 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;
|
||||
}
|
||||
objc_registerClassPair(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static void **getpid_slot(void) {
|
||||
const struct mach_header_64 *h = (const void *)_dyld_get_image_header(0);
|
||||
intptr_t slide = _dyld_get_image_vmaddr_slide(0);
|
||||
const struct segment_command_64 *le = NULL;
|
||||
const struct symtab_command *sy = NULL;
|
||||
const struct dysymtab_command *dy = NULL;
|
||||
const unsigned char *p = (const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64 && !strcmp(((const struct segment_command_64 *)p)->segname,"__LINKEDIT")) le=(const void *)p;
|
||||
if (lc->cmd==LC_SYMTAB) sy=(const void *)p;
|
||||
if (lc->cmd==LC_DYSYMTAB) dy=(const void *)p;
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
if (!le || !sy || !dy) return NULL;
|
||||
uintptr_t base=slide+le->vmaddr-le->fileoff;
|
||||
const struct nlist_64 *symbols=(const void *)(base+sy->symoff);
|
||||
const char *strings=(const void *)(base+sy->stroff);
|
||||
const uint32_t *indirect=(const void *)(base+dy->indirectsymoff);
|
||||
p=(const void *)(h+1);
|
||||
for (unsigned i=0; i<h->ncmds; i++) {
|
||||
const struct load_command *lc=(const void *)p;
|
||||
if (lc->cmd==LC_SEGMENT_64) {
|
||||
const struct segment_command_64 *seg=(const void *)p;
|
||||
const struct section_64 *s=(const void *)(seg+1);
|
||||
for (unsigned j=0; j<seg->nsects; j++) {
|
||||
if ((s[j].flags & SECTION_TYPE)!=S_NON_LAZY_SYMBOL_POINTERS) continue;
|
||||
for (unsigned k=0; k<s[j].size/sizeof(void *); k++) {
|
||||
uint32_t n=indirect[s[j].reserved1+k];
|
||||
if (n & (INDIRECT_SYMBOL_LOCAL|INDIRECT_SYMBOL_ABS)) continue;
|
||||
if (!strcmp(strings+symbols[n].n_un.n_strx,"_getpid"))
|
||||
return (void **)(slide+s[j].addr)+k;
|
||||
}
|
||||
}
|
||||
}
|
||||
p+=lc->cmdsize;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc<2) return 2;
|
||||
Findings f={0};
|
||||
if (!strcmp(argv[1],"clean")) {
|
||||
int hits=ig_defender_scan(NULL,0,collect,&f);
|
||||
return hits!=f.detected || f.detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"unresolved")) {
|
||||
const char *names[]={"IG_fixture_symbol_that_does_not_exist_123"};
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
return hits || f.unavailable!=1 || f.reasons[IG_REASON_SYMBOL_UNRESOLVED]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"verify")) {
|
||||
if (ig_verify_function(NULL,"null",collect,&f)!=IG_UNAVAILABLE) return 3;
|
||||
if (ig_verify_function(getpid_address(),"getpid",collect,&f)!=IG_CLEAR) return 4;
|
||||
return ig_verify_function((void *)fake_getpid,"local_fixture",collect,&f)!=IG_DETECTED
|
||||
|| f.reasons[IG_REASON_SYMBOL_PROVENANCE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"env")) {
|
||||
setenv("DYLD_INSERT_LIBRARIES","/tmp/ig_fixture_a:/tmp/ig_fixture_b",1);
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
unsetenv("DYLD_INSERT_LIBRARIES");
|
||||
return f.reasons[IG_REASON_DYLD_INSERT]!=2;
|
||||
}
|
||||
if (!strcmp(argv[1],"image")) {
|
||||
if (argc<3 || !dlopen(argv[2],RTLD_NOW)) return 5;
|
||||
ig_anti_inject_check(NULL,collect,&f);
|
||||
return f.reasons[IG_REASON_INJECTED_IMAGE]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"got")) {
|
||||
const char *names[]={"getpid"};
|
||||
if (!getpid_address() || ig_anti_hook_check(names,1,collect,&f)!=0) return 6;
|
||||
void **slot=getpid_slot();
|
||||
if (!slot) { fprintf(stderr,"未找到测试 GOT 槽\n"); return 7; }
|
||||
void *original=*slot;
|
||||
vm_size_t size=getpagesize();
|
||||
vm_address_t page=(uintptr_t)slot & ~(size-1);
|
||||
if (vm_protect(mach_task_self(),page,size,0,VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) return 8;
|
||||
*slot=(void *)fake_getpid;
|
||||
int hits=ig_anti_hook_check(names,1,collect,&f);
|
||||
*slot=original;
|
||||
return hits!=1 || f.reasons[IG_REASON_GOT_REBIND]!=1;
|
||||
}
|
||||
if (!strcmp(argv[1],"debugger")) {
|
||||
/* 正常(无调试器)环境:clear 且 sysctl 可判定。
|
||||
* 正向(P_TRACED 命中)由 lldb 场景验证,docs/12 已实测。 */
|
||||
ig_anti_debug_check(collect,&f);
|
||||
return f.detected || f.unavailable;
|
||||
}
|
||||
if (!strcmp(argv[1],"objc-clean")) {
|
||||
if (!make_fixture_class()) return 9;
|
||||
const IGObjCWatch watch[] = { { "IGFixtureHookTarget", "value" } };
|
||||
if (ig_objc_baseline_capture(watch,1)!=1) return 10;
|
||||
/* 未登记的方法在 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);
|
||||
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)。 */
|
||||
class_replaceMethod(c, sel_registerName("value"), (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 2;
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
/* 独立诊断进程:只在自身进程测试,不连接业务、不改系统代码。 */
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "IGDefender.h"
|
||||
#include <stdio.h>
|
||||
|
||||
int ig_dispatch_fixture_main(int argc, char **argv);
|
||||
static int findings, unavailable;
|
||||
static int collect(const IGFinding *f, void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->status==IG_DETECTED) findings++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
NSLog(@"IG_DEVICE_FINDING status=%d reason=%d subject=%s evidence=%s",
|
||||
f->status,f->reason,f->subject,f->evidence);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
(void)argc;(void)argv;
|
||||
@autoreleasepool {
|
||||
NSLog(@"IG_DEVICE_MAIN");
|
||||
const char *modes[]={"semantics","short-write","eintr","threads","reentry","resolver","prologue","tamper"};
|
||||
int hits=ig_defender_scan(NSBundle.mainBundle.bundlePath.UTF8String,0,collect,NULL);
|
||||
NSLog(@"IG_DEVICE_BASELINE detected=%d unavailable=%d hits=%d",findings,unavailable,hits);
|
||||
for (unsigned i=0;i<sizeof(modes)/sizeof(modes[0]);i++) {
|
||||
char *args[]={"dispatch-device",(char *)modes[i],NULL};
|
||||
int rc=ig_dispatch_fixture_main(2,args);
|
||||
NSLog(@"IG_DEVICE_CASE %s %s",modes[i],rc==0 ? "PASS" : "FAIL");
|
||||
if (rc) return rc;
|
||||
}
|
||||
NSLog(@"IG_DEVICE_SUITE PASS cases=8 baseline_detected=%d baseline_unavailable=%d",findings,unavailable);
|
||||
/* 诊断进程退出便于 console 收集退出码;不编入业务 App。 */
|
||||
return findings || unavailable ? 3 : 0;
|
||||
}
|
||||
}
|
||||
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
#include "dispatch/IGDispatch.h"
|
||||
#include "resolve/IGResolve.h"
|
||||
#include "anti_hook/IGAntiHook.h"
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int early_ok;
|
||||
__attribute__((constructor)) static void early(void) {
|
||||
#ifdef IG_EXPECT_INIT_FAILURE
|
||||
early_ok=1;
|
||||
#else
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
early_ok=fd>=0 && IG_dispatch_write(fd,"early",5)==5 && IG_dispatch_close(fd)==0;
|
||||
#endif
|
||||
}
|
||||
void *ig_fixture_missing_resolve(void *handle, const char *name) { (void)handle; (void)name; return NULL; }
|
||||
static int reasons[256], unavailable;
|
||||
static int collect(const IGFinding *f,void *ctx) {
|
||||
(void)ctx;
|
||||
if (f->reason>=0 && f->reason<256) reasons[f->reason]++;
|
||||
if (f->status==IG_UNAVAILABLE) unavailable++;
|
||||
return 0;
|
||||
}
|
||||
static int fake_close(int fd) { (void)fd; abort(); }
|
||||
static void *writer(void *ctx) {
|
||||
(void)ctx;
|
||||
int fd=open("/dev/null",O_WRONLY);
|
||||
assert(fd>=0);
|
||||
for (int i=0;i<100;i++) assert(IG_dispatch_write(fd,"abc",3)==3);
|
||||
assert(IG_dispatch_close(fd)==0);
|
||||
return NULL;
|
||||
}
|
||||
static void signal_handler(int sig) { (void)sig; }
|
||||
static pthread_t main_thread;
|
||||
static void *interruptor(void *ctx) { (void)ctx; usleep(30000); pthread_kill(main_thread,SIGUSR1); return NULL; }
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
assert(argc==2 && early_ok);
|
||||
if (!strcmp(argv[1],"observation")) {
|
||||
#ifdef IG_OBSERVATION
|
||||
IGDispatchObservation before=ig_dispatch_observation();
|
||||
errno=0; assert(IG_dispatch_write(-1,"x",1)==-1 && errno==EBADF);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
IGDispatchObservation after=ig_dispatch_observation();
|
||||
assert(after.write_attempted==before.write_attempted+1);
|
||||
assert(after.write_dispatched==before.write_dispatched+1);
|
||||
assert(after.close_attempted==before.close_attempted+1);
|
||||
assert(after.close_dispatched==before.close_dispatched+1);
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
IGDispatchObservation rejected=ig_dispatch_observation();
|
||||
assert(rejected.close_attempted==after.close_attempted+1);
|
||||
assert(rejected.close_dispatched==after.close_dispatched);
|
||||
#else
|
||||
return 2;
|
||||
#endif
|
||||
} 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);
|
||||
} 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);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EBADF);
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
errno=EDOM; assert(IG_dispatch_write(p[1],"abc",3)==3 && errno==EDOM);
|
||||
char b[4]={0}; assert(read(p[0],b,3)==3 && !memcmp(b,"abc",3));
|
||||
assert(IG_dispatch_close(p[1])==0 && IG_dispatch_close(p[0])==0);
|
||||
} else if (!strcmp(argv[1],"short-write")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
const size_t count=1024*1024;
|
||||
char *bytes=calloc(count,1);assert(bytes);
|
||||
ssize_t n=IG_dispatch_write(p[1],bytes,count);
|
||||
assert(n>0 && n<(ssize_t)count);
|
||||
while (IG_dispatch_write(p[1],bytes,count)>0) {}
|
||||
assert(errno==EAGAIN);
|
||||
IG_dispatch_close(p[1]); IG_dispatch_close(p[0]);
|
||||
free(bytes);
|
||||
} else if (!strcmp(argv[1],"eintr")) {
|
||||
int p[2]; assert(pipe(p)==0);
|
||||
assert(fcntl(p[1],F_SETFL,O_NONBLOCK)==0);
|
||||
char bytes[4096]={0}; while (write(p[1],bytes,sizeof(bytes))>0) {}
|
||||
assert(errno==EAGAIN && fcntl(p[1],F_SETFL,0)==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);
|
||||
assert(IG_dispatch_write(p[1],bytes,sizeof(bytes))==-1 && errno==EINTR);
|
||||
pthread_join(thread,NULL);IG_dispatch_close(p[1]);IG_dispatch_close(p[0]);
|
||||
} else if (!strcmp(argv[1],"threads")) {
|
||||
pthread_t threads[8];
|
||||
for (unsigned i=0;i<8;i++) assert(pthread_create(&threads[i],NULL,writer,NULL)==0);
|
||||
for (unsigned i=0;i<8;i++) pthread_join(threads[i],NULL);
|
||||
} else if (!strcmp(argv[1],"tamper")) {
|
||||
ig_dispatch_test_override(1,(void *)fake_close);
|
||||
errno=0; assert(IG_dispatch_close(-1)==-1 && errno==EACCES);
|
||||
assert(ig_dispatch_check(collect,NULL)==1 && reasons[IG_REASON_DISPATCH_TAMPER]==1);
|
||||
} else if (!strcmp(argv[1],"reentry")) {
|
||||
ig_dispatch_test_reentry(1);
|
||||
assert(IG_dispatch_close(-1)==-1 && errno==EDEADLK);
|
||||
ig_dispatch_test_reentry(0);
|
||||
} else if (!strcmp(argv[1],"resolver")) {
|
||||
unsigned char encoded[300];memset(encoded,'x',sizeof(encoded));char out[4];
|
||||
assert(!ig_decrypt(encoded,1,out,0));assert(!ig_decrypt(NULL,1,out,sizeof(out)));
|
||||
assert(!ig_decrypt(encoded,4,out,sizeof(out)) && out[0]==0);
|
||||
encoded[0]=IG_ENC_KEY;assert(!ig_decrypt(encoded,1,out,sizeof(out)));
|
||||
assert(ig_resolve_verified(NULL,encoded,300,NULL,NULL).status==IG_UNAVAILABLE);
|
||||
const char *name="IG_missing_symbol_774444";
|
||||
for (unsigned i=0;i<strlen(name);i++) encoded[i]=name[i]^IG_ENC_KEY;
|
||||
assert(ig_resolve_verified(NULL,encoded,strlen(name),collect,NULL).status==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_SYMBOL_UNRESOLVED]==1);
|
||||
assert(ig_verify_function((void *)1,"invalid",collect,NULL)==IG_UNAVAILABLE);
|
||||
assert(reasons[IG_REASON_VERIFICATION_UNAVAILABLE]==1);
|
||||
} 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(0x58000050,0xd61f0220));
|
||||
assert(!ig_arm64_suspicious_prologue(0x18000050,0xd61f0200));
|
||||
assert(!ig_arm64_suspicious_prologue(0xd503245f,0xd65f03c0));
|
||||
} else return 2;
|
||||
return 0;
|
||||
}
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern FILE *sdk_open(const char *path, const char *mode);
|
||||
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
extern int sdk_fclose(FILE *);
|
||||
extern size_t sdk_fread(void *, size_t, size_t, FILE *);
|
||||
extern size_t sdk_fwrite(const void *, size_t, size_t, FILE *);
|
||||
extern ssize_t sdk_read(int, void *, size_t);
|
||||
extern ssize_t sdk_write(int, const void *, size_t);
|
||||
extern int sdk_close(int);
|
||||
#define fclose sdk_fclose
|
||||
#define fread sdk_fread
|
||||
#define fwrite sdk_fwrite
|
||||
|
||||
static void exercise_posix(void) {
|
||||
int descriptors[2];
|
||||
char buffer[4096] = {0};
|
||||
assert(pipe(descriptors) == 0);
|
||||
assert(sdk_write(descriptors[1], "X", 1) == 1);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 1);
|
||||
assert(buffer[0] == 'X');
|
||||
assert(sdk_write(descriptors[1], buffer, 0) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, 0) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
assert(sdk_read(descriptors[0], buffer, sizeof(buffer)) == 0);
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(-1) == -1 && errno == EBADF);
|
||||
assert(sdk_read(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
assert(sdk_write(-1, buffer, 1) == -1 && errno == EBADF);
|
||||
|
||||
assert(pipe(descriptors) == 0);
|
||||
int flags = fcntl(descriptors[1], F_GETFL);
|
||||
assert(flags >= 0 && fcntl(descriptors[1], F_SETFL, flags | O_NONBLOCK) == 0);
|
||||
ssize_t result = 0;
|
||||
for (int i = 0; i < 1024; ++i) {
|
||||
result = sdk_write(descriptors[1], buffer, sizeof(buffer));
|
||||
if (result < 0) break;
|
||||
}
|
||||
assert(result == -1 && (errno == EAGAIN || errno == EWOULDBLOCK));
|
||||
assert(sdk_close(descriptors[0]) == 0);
|
||||
assert(sdk_close(descriptors[1]) == 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void exercise(const char *path) {
|
||||
FILE *file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
const unsigned char payload[] = {0, 1, 255, 10};
|
||||
assert(fwrite(payload, 1, sizeof(payload), file) == sizeof(payload));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "ab");
|
||||
assert(file != NULL);
|
||||
assert(fwrite("X", 1, 1, file) == 1);
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
unsigned char result[8] = {0};
|
||||
assert(fread(result, 1, sizeof(result), file) == 5);
|
||||
assert(memcmp(result, payload, sizeof(payload)) == 0);
|
||||
assert(result[4] == 'X');
|
||||
assert(feof(file));
|
||||
assert(fclose(file) == 0);
|
||||
|
||||
file = sdk_open(path, "wb");
|
||||
assert(file != NULL);
|
||||
assert(fclose(file) == 0);
|
||||
file = sdk_open(path, "rb");
|
||||
assert(file != NULL);
|
||||
assert(fgetc(file) == EOF);
|
||||
assert(fclose(file) == 0);
|
||||
assert(unlink(path) == 0);
|
||||
|
||||
FILE *system_result = fopen(path, "rb");
|
||||
int system_error = errno;
|
||||
assert(system_result == NULL);
|
||||
errno = 0;
|
||||
FILE *bridge_result = sdk_open(path, "rb");
|
||||
int bridge_error = errno;
|
||||
assert(bridge_result == NULL);
|
||||
assert(bridge_error == system_error && bridge_error == ENOENT);
|
||||
}
|
||||
|
||||
static void *thread_test(void *path) {
|
||||
for (int i = 0; i < 20; ++i) exercise(path);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
#ifdef IG_TEST_ALL_BRIDGES
|
||||
exercise_posix();
|
||||
#endif
|
||||
pthread_t threads[4];
|
||||
char paths[4][4096];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
int length = snprintf(paths[i], sizeof(paths[i]), "%s/文件-%d.bin", argv[1], i);
|
||||
assert(length > 0 && (size_t)length < sizeof(paths[i]));
|
||||
assert(pthread_create(&threads[i], NULL, thread_test, paths[i]) == 0);
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) assert(pthread_join(threads[i], NULL) == 0);
|
||||
puts("file semantics: passed");
|
||||
return 0;
|
||||
}
|
||||
Vendored
+393
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
/*
|
||||
* hook_sim_dylib.c — 空壳模拟 dylib(step11 诊断专用)。
|
||||
*
|
||||
* 唯一用途:被诊断进程 dlopen / 被 DYLD_INSERT_LIBRARIES 加载,构成
|
||||
* 「注入镜像 / Bundle 外镜像 / 插入库」探针的受控证据源。不实现任何业务功能,
|
||||
* 不导出会被业务引用的符号。仅用于诊断 App,绝不编入业务库。
|
||||
*/
|
||||
#include <stddef.h>
|
||||
|
||||
__attribute__((visibility("default")))
|
||||
int ig_frida_sim_marker(void) { return 0x46726461; /* "Frda" */ }
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/* 无 SDK 头依赖的 iOS 链接样本:两个外部调用和一个本地改写目标。 */
|
||||
extern int getpid(void);
|
||||
extern long write(int, const void *, unsigned long);
|
||||
int fixture_calls(void) { return getpid() + (int)write(-1, "x", 1); }
|
||||
int fixture_redirect(void) { return 123; }
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
FILE *sdk_open(const char *path, const char *mode) { return fopen(path, mode); }
|
||||
int sdk_fclose(FILE *stream) { return fclose(stream); }
|
||||
size_t sdk_fread(void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fread(buffer, size, count, stream);
|
||||
}
|
||||
size_t sdk_fwrite(const void *buffer, size_t size, size_t count, FILE *stream) {
|
||||
return fwrite(buffer, size, count, stream);
|
||||
}
|
||||
ssize_t sdk_read(int fd, void *buffer, size_t count) { return read(fd, buffer, count); }
|
||||
ssize_t sdk_write(int fd, const void *buffer, size_t count) { return write(fd, buffer, count); }
|
||||
int sdk_close(int fd) { return close(fd); }
|
||||
@@ -0,0 +1,125 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
|
||||
from redirect_framework_imports import rewrite, DEPENDENCY
|
||||
from machox import Macho, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
SDK = ROOT/'readoor-test/readoor/BookShelf/Classes/Factorys/SSZipArchive/SSZipArchive.framework/SSZipArchive'
|
||||
SHA = '485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
|
||||
|
||||
|
||||
@unittest.skipUnless(SDK.exists(), '需要已审核 SDK 副本')
|
||||
class FrameworkRewriteTests(unittest.TestCase):
|
||||
def setUp(self): self.data = SDK.read_bytes()
|
||||
def rejected(self, data):
|
||||
with self.assertRaises((ValueError, struct.error)):
|
||||
rewrite(data, hashlib.sha256(data).hexdigest())
|
||||
def test_real_sdk(self):
|
||||
data, report = rewrite(self.data, SHA)
|
||||
self.assertEqual(len(data), len(self.data))
|
||||
self.assertEqual(len(report['changes']), 8)
|
||||
self.assertTrue(report['machine_code_unchanged'])
|
||||
self.assertIn(DEPENDENCY.encode(), data[:32768])
|
||||
m = Macho(data)
|
||||
self.assertEqual(m.ncmds, Macho(self.data).ncmds+1)
|
||||
self.assertEqual(data[32768:212992], self.data[32768:212992])
|
||||
def test_wrong_hash(self):
|
||||
with self.assertRaises(ValueError): rewrite(self.data, '0'*64)
|
||||
def test_repeat_rejected(self):
|
||||
data, _ = rewrite(self.data, SHA); self.rejected(data)
|
||||
def test_no_padding(self):
|
||||
data = bytearray(self.data); data[32+Macho(data).sizeofcmds] = 1; self.rejected(data)
|
||||
def test_unsupported_import_format(self):
|
||||
data = bytearray(self.data); m = Macho(data)
|
||||
off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',data,off+8)[0]
|
||||
struct.pack_into('<I',data,fixoff+20,3); self.rejected(data)
|
||||
def test_wrong_provider_and_weak(self):
|
||||
m = Macho(self.data); off = next(o for c,_,o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS)
|
||||
fixoff = struct.unpack_from('<I',self.data,off+8)[0]
|
||||
imports = struct.unpack_from('<I',self.data,fixoff+8)[0]
|
||||
for mask in (0x100, 1):
|
||||
with self.subTest(mask=mask):
|
||||
data = bytearray(self.data); pos = fixoff+imports+43*4
|
||||
word = struct.unpack_from('<I',data,pos)[0]
|
||||
struct.pack_into('<I',data,pos,word^mask); self.rejected(data)
|
||||
def test_truncated(self): self.rejected(self.data[:3000])
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin', '需要 Apple 工具链')
|
||||
class ArchiveABITests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory(); cls.exe = Path(cls.tmp.name)/'archive-host'
|
||||
cls.env = dict(os.environ); cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
cls.sources = [str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')]
|
||||
command = ['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_ARCHIVE_TESTING','-DIG_OBSERVATION','-I',str(ROOT/'defender'),
|
||||
'-I',str(ROOT/'defender/include'),str(ROOT/'tests/fixtures/archive_host.c'),
|
||||
*cls.sources,'-o',str(cls.exe)]
|
||||
r = subprocess.run(command,capture_output=True,text=True,env=cls.env)
|
||||
if r.returncode: raise RuntimeError(r.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls): cls.tmp.cleanup()
|
||||
def run_mode(self,mode):
|
||||
r = subprocess.run([self.exe,mode],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
def test_stdio_semantics(self): self.run_mode('semantics')
|
||||
def test_concurrent_initialization(self): self.run_mode('threads')
|
||||
def test_tamper_refuses_before_call(self): self.run_mode('tamper')
|
||||
def test_reentry(self): self.run_mode('reentry')
|
||||
def test_read_write_close_reject(self): self.run_mode('rejection')
|
||||
def test_release_has_no_test_or_observation_api(self):
|
||||
output = Path(self.tmp.name)/'release.dylib'
|
||||
r = subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-fvisibility=hidden','-dynamiclib',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),*self.sources,
|
||||
'-o',str(output)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
nm = subprocess.run(['xcrun','nm','-g',output],capture_output=True,text=True,check=True).stdout
|
||||
self.assertNotIn('ig_archive_test_',nm); self.assertNotIn('_ig_archive_counter',nm)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and platform.machine() == 'arm64', '需要 Apple Silicon')
|
||||
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'
|
||||
sdk = root/'SSZipArchive.framework/SSZipArchive'
|
||||
guard.parent.mkdir(); sdk.parent.mkdir()
|
||||
common = ['xcrun','--sdk','macosx','clang','-arch','arm64','-mmacosx-version-min=13.0','-O2']
|
||||
env = dict(os.environ); env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
def command(args):
|
||||
r = subprocess.run(args,capture_output=True,text=True,env=env,timeout=40)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
return r
|
||||
command(common+['-dynamiclib','-DIG_OBSERVATION','-fvisibility=hidden',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
*(str(ROOT/'defender'/s) for s in
|
||||
('dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c')),
|
||||
'-Wl,-install_name,'+DEPENDENCY,'-o',str(guard)])
|
||||
command(common+['-dynamiclib',str(ROOT/'tests/fixtures/archive_sdk.c'),
|
||||
'-Wl,-install_name,@rpath/SSZipArchive.framework/SSZipArchive',
|
||||
'-Wl,-headerpad,0x4000','-Wl,-rpath,@loader_path/..','-o',str(sdk)])
|
||||
data = sdk.read_bytes(); changed, _ = rewrite(data,hashlib.sha256(data).hexdigest())
|
||||
sdk.write_bytes(changed)
|
||||
command(['codesign','--force','--sign','-',str(guard)])
|
||||
command(['codesign','--force','--sign','-',str(sdk)])
|
||||
exe = root/'binding-test'
|
||||
command(common+[str(ROOT/'tests/fixtures/archive_binding_host.c'),'-o',str(exe)])
|
||||
result = command([str(exe),str(sdk),str(root/'stdio.bin')])
|
||||
self.assertIn('均通过',result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""宿主探针正反例与 iOS 编译验证;不替代真机 inline Hook 测试。"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCES = ['IGDefender.c','anti_hook/IGAntiHook.c','anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c','anti_debug/IGAntiDebug.c',
|
||||
'syscall/IGSyscall.c','resolve/IGResolve.c','dispatch/IGDispatch.c']
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin' and shutil.which('xcrun'), '需要 Xcode/macOS')
|
||||
class DefenderTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.folder = Path(cls.tmp.name)
|
||||
cls.exe = cls.folder/'defender-host'
|
||||
cls.env = dict(os.environ)
|
||||
cls.env.pop('DYLD_INSERT_LIBRARIES', None)
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
str(ROOT/'tests/fixtures/defender_host.c'),
|
||||
*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-lobjc','-o',str(cls.exe)])
|
||||
fixture = cls.folder/'empty.c'
|
||||
fixture.write_text('int ig_fixture_marker(void) { return 1; }\n')
|
||||
cls.image = cls.folder/'fixture_frida.dylib'
|
||||
cls.compile(['xcrun','--sdk','macosx','clang','-dynamiclib',str(fixture),'-o',str(cls.image)])
|
||||
|
||||
@classmethod
|
||||
def compile(cls, args):
|
||||
p = subprocess.run(args,capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:
|
||||
raise RuntimeError(p.stdout+p.stderr)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def check_mode(self, mode, *args):
|
||||
p = subprocess.run([str(self.exe),mode,*map(str,args)],
|
||||
capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(p.returncode,0,p.stdout+p.stderr)
|
||||
# 保留各探针证据到 unittest 日志。
|
||||
print(mode+': '+p.stdout.strip(), flush=True)
|
||||
|
||||
def test_clean(self): self.check_mode('clean')
|
||||
def test_unavailable(self): self.check_mode('unresolved')
|
||||
def test_function_provenance(self): self.check_mode('verify')
|
||||
def test_environment_entries(self): self.check_mode('env')
|
||||
def test_loaded_image(self): self.check_mode('image',self.image)
|
||||
def test_got_rebinding(self): self.check_mode('got')
|
||||
def test_debugger_clean(self): self.check_mode('debugger')
|
||||
def test_objc_baseline_clean(self): self.check_mode('objc-clean')
|
||||
def test_objc_baseline_swap(self): self.check_mode('objc-swap')
|
||||
|
||||
def test_iphoneos_cross_compile(self):
|
||||
for i, source in enumerate(SOURCES):
|
||||
self.compile(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2',
|
||||
'-I',str(ROOT/'defender/include'),'-I',str(ROOT/'defender'),
|
||||
'-c',str(ROOT/'defender'/source),'-o',str(self.folder/f'{i}.o')])
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,70 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SOURCES=['dispatch/IGDispatch.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
|
||||
|
||||
@unittest.skipUnless(sys.platform=='darwin','需要 Apple 工具链')
|
||||
class DispatchTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp=tempfile.TemporaryDirectory()
|
||||
cls.exe=Path(cls.tmp.name)/'dispatch-test'
|
||||
cls.env=dict(os.environ);cls.env.pop('DYLD_INSERT_LIBRARIES',None)
|
||||
p=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(cls.exe)],capture_output=True,text=True,env=cls.env)
|
||||
if p.returncode:raise RuntimeError(p.stderr)
|
||||
@classmethod
|
||||
def tearDownClass(cls):cls.tmp.cleanup()
|
||||
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_semantics(self):self.run_mode('semantics')
|
||||
def test_short_write(self):self.run_mode('short-write')
|
||||
def test_eintr(self):self.run_mode('eintr')
|
||||
def test_concurrency(self):self.run_mode('threads')
|
||||
def test_tamper_rejected(self):self.run_mode('tamper')
|
||||
def test_reentry(self):self.run_mode('reentry')
|
||||
def test_resolver_errors(self):self.run_mode('resolver')
|
||||
def test_prologue_patterns(self):self.run_mode('prologue')
|
||||
def test_observation_counters_and_release_exclusion(self):
|
||||
exe=Path(self.tmp.name)/'observation'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Wall','-Wextra','-Werror',
|
||||
'-DIG_DISPATCH_TESTING','-DIG_OBSERVATION',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),*(str(ROOT/'defender'/p) for p in SOURCES),
|
||||
'-o',str(exe)],capture_output=True,text=True,env=self.env)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'observation'],capture_output=True,text=True,env=self.env,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
r=subprocess.run(['xcrun','nm',str(self.exe)],capture_output=True,text=True,check=True)
|
||||
self.assertNotIn('_ig_dispatch_observation',r.stdout)
|
||||
def test_ios_compile(self):
|
||||
for i,p in enumerate(SOURCES):
|
||||
r=subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-O2','-I',str(ROOT/'defender/include'),
|
||||
'-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)
|
||||
def test_initialization_failure(self):
|
||||
obj=Path(self.tmp.name)/'missing-resolver.o'
|
||||
exe=Path(self.tmp.name)/'init-failure'
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-Ddlsym=ig_fixture_missing_resolve',
|
||||
'-I',str(ROOT/'defender/include'),
|
||||
'-c',str(ROOT/'defender/resolve/IGResolve.c'),'-o',str(obj)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run(['xcrun','--sdk','macosx','clang','-O2','-DIG_DISPATCH_TESTING','-DIG_EXPECT_INIT_FAILURE',
|
||||
'-I',str(ROOT/'defender'),'-I',str(ROOT/'defender/include'),
|
||||
str(ROOT/'tests/fixtures/dispatch_host.c'),str(ROOT/'defender/dispatch/IGDispatch.c'),
|
||||
str(ROOT/'defender/anti_hook/IGAntiHook.c'),str(obj),'-o',str(exe)],capture_output=True,text=True)
|
||||
self.assertEqual(r.returncode,0,r.stderr)
|
||||
r=subprocess.run([str(exe),'init-failure'],capture_output=True,text=True,timeout=30)
|
||||
self.assertEqual(r.returncode,0,r.stdout+r.stderr)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,168 @@
|
||||
"""用真实 Apple 链接器生成样本,验证注入、指令及拒绝路径。"""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
|
||||
import batch
|
||||
import macho_guard as guard
|
||||
from machox import Macho
|
||||
from verify_baseline import inspect_binary, validate_zip
|
||||
from redirect_to_runtime import patch, trace_calls
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('xcrun'), '需要 Xcode')
|
||||
class MachoTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.src = Path(cls.tmp.name)/'fixture.dylib'
|
||||
cls.linkmap = Path(cls.tmp.name)/'fixture.map'
|
||||
subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
|
||||
'-miphoneos-version-min=15.0','-dynamiclib',
|
||||
'-Wl,-headerpad,0x1000',
|
||||
'-Wl,-map,'+str(cls.linkmap),
|
||||
str(ROOT/'tests/fixtures/macho_calls.c'),'-o',str(cls.src)],
|
||||
check=True, capture_output=True)
|
||||
cls.original = cls.src.read_bytes()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_rewrite_preserves_got_and_branch_targets(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst = Path(td)/'guarded'
|
||||
before, sites = inspect_binary(self.src)
|
||||
self.assertEqual({s['symbol'] for s in sites}, {'_getpid','_write'})
|
||||
count, n, _, va = guard.harden_thin(self.src, dst)
|
||||
after, remaining = inspect_binary(dst)
|
||||
self.assertEqual(sum(count.values()),len(sites))
|
||||
self.assertEqual(remaining, [])
|
||||
m = Macho(dst.read_bytes())
|
||||
self.assertEqual(m.segs['__IGUARD']['initprot'],5)
|
||||
self.assertEqual(guard.find_stub_got_slots(m),
|
||||
guard.find_stub_got_slots(Macho(self.original)))
|
||||
view = batch.Slice(dst.read_bytes(),0)
|
||||
old_view = batch.Slice(self.original,0)
|
||||
addr, length, off = view.text
|
||||
old_off = old_view.text[2]
|
||||
changes = []
|
||||
for i in range(0,length,4):
|
||||
old, = struct.unpack_from('<I',self.original,old_off+i)
|
||||
new, = struct.unpack_from('<I',m.d,off+i)
|
||||
if old==new:
|
||||
continue
|
||||
changes.append(i)
|
||||
self.assertEqual(old & 0xfc000000,new & 0xfc000000)
|
||||
imm = new & 0x3ffffff
|
||||
if imm & (1<<25): imm -= 1<<26
|
||||
self.assertTrue(va <= addr+i+imm*4 < va+n*12)
|
||||
self.assertEqual(len(changes),len(sites))
|
||||
self.assertEqual(self.src.read_bytes(),self.original)
|
||||
self.assertEqual(before['slices'][0]['uuid'],after['slices'][0]['uuid'])
|
||||
|
||||
def test_reject_duplicate_injection_and_input_overwrite(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst = Path(td)/'out'
|
||||
guard.inject(self.src,dst)
|
||||
with self.assertRaisesRegex(ValueError,'重复'):
|
||||
guard.inject(dst,Path(td)/'again')
|
||||
with self.assertRaisesRegex(ValueError,'覆盖'):
|
||||
guard.inject(self.src,self.src)
|
||||
|
||||
def test_reject_unsupported_architecture_and_truncation(self):
|
||||
for offset, value in [(4,0x01000007),(8,2)]:
|
||||
data = bytearray(self.original)
|
||||
struct.pack_into('<I',data,offset,value)
|
||||
with self.assertRaises(ValueError): Macho(data)
|
||||
for size in (0,4,31,64,len(self.original)-1):
|
||||
with self.subTest(size=size), self.assertRaises(ValueError):
|
||||
Macho(self.original[:size])
|
||||
|
||||
def test_reject_encrypted_image(self):
|
||||
data = bytearray(self.original)
|
||||
m = Macho(data)
|
||||
# 在已有 padding 中追加 encryption_info_command_64。
|
||||
end = 32+m.sizeofcmds
|
||||
data[end:end+24] = struct.pack('<6I',0x2c,24,0,0,1,0)
|
||||
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+24)
|
||||
with self.assertRaisesRegex(ValueError,'加密'): Macho(data)
|
||||
|
||||
def test_reject_insufficient_header_space(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
data = bytearray(self.original)
|
||||
m = Macho(data)
|
||||
# 保留现有命令,用合法空命令填满 padding,只剩不足 72B。
|
||||
end = 32+m.sizeofcmds
|
||||
first = guard._first_section_fileoff(m)
|
||||
size = (first-end)//8*8
|
||||
struct.pack_into('<II',data,end,0x7777,size)
|
||||
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+size)
|
||||
src,dst = Path(td)/'src',Path(td)/'dst'
|
||||
src.write_bytes(data)
|
||||
with self.assertRaisesRegex(AssertionError,'空间不足'):
|
||||
guard.inject(src,dst)
|
||||
self.assertFalse(dst.exists())
|
||||
|
||||
def test_targeted_rewrite_and_trace(self):
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst=Path(td)/'patched'
|
||||
report=patch(self.src,dst,self.linkmap,profile)
|
||||
self.assertEqual(report['total'],1)
|
||||
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
|
||||
self.assertNotIn('_getpid',{r.get('symbol') for r in rows})
|
||||
self.assertIn('_write',{r.get('symbol') for r in rows})
|
||||
with self.assertRaises(ValueError):patch(self.src,dst,self.linkmap,profile)
|
||||
|
||||
def test_targeted_reject_stale_map(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
lm=Path(td)/'bad.map'
|
||||
lm.write_text('0x1 0x4 [1] _fixture_calls\n0x2 0x4 [1] _fixture_redirect\n')
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
with self.assertRaisesRegex(ValueError,'不匹配'):
|
||||
patch(self.src,Path(td)/'out',lm,profile)
|
||||
|
||||
def test_map_with_non_utf8_sdk_symbol(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
lm=Path(td)/'sdk.map'
|
||||
lm.write_bytes(b'0x1 0x4 [1] sdk_\xf0\xff\n'+self.linkmap.read_bytes())
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=1)]}
|
||||
report=patch(self.src,Path(td)/'out',lm,profile)
|
||||
self.assertEqual(report['total'],1)
|
||||
|
||||
def test_targeted_reject_wrong_count(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
|
||||
destination='_fixture_redirect',expected_count=2)]}
|
||||
with self.assertRaises(ValueError):patch(self.src,Path(td)/'out',self.linkmap,profile)
|
||||
|
||||
def test_trace_recovers_injected_got_bridge(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
dst=Path(td)/'bridge'
|
||||
guard.harden_thin(self.src,dst)
|
||||
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
|
||||
self.assertEqual({r.get('symbol') for r in rows if r['kind']=='got_bridge'},
|
||||
{'_getpid','_write'})
|
||||
|
||||
|
||||
class ArchiveTests(unittest.TestCase):
|
||||
def test_reject_zip_escape(self):
|
||||
import zipfile
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = Path(td)/'bad.ipa'
|
||||
with zipfile.ZipFile(path,'w') as z: z.writestr('../escape','bad')
|
||||
with self.assertRaises(ValueError): validate_zip(path)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""用真实策略源码做宿主测试,覆盖观察/强制模式和 unavailable。"""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
POLICY=ROOT/'readoor-test/readoor/3.0/Base/Security/RDSecurityPolicy.swift'
|
||||
|
||||
@unittest.skipUnless(POLICY.exists(),'需要 App 副本中的策略源码')
|
||||
class SecurityPolicyTests(unittest.TestCase):
|
||||
def test_decisions(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
main=Path(td)/'main.swift';exe=Path(td)/'policy'
|
||||
main.write_text('''
|
||||
import Foundation
|
||||
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
|
||||
}
|
||||
let legacy=RDSecurityRiskContext(debuggerDetected:false,injectedDylibDetected:false,jailbreakDetected:false)
|
||||
let policy=RDSecurityPolicy.shared
|
||||
let clean=policy.evaluate(findings:[],legacy:legacy)
|
||||
assert(clean.action == .none && !clean.shouldRestrict(in:.enforce))
|
||||
let unknown=policy.evaluate(findings:[RDDefenderFinding(status:2,reason:104)],legacy:legacy)
|
||||
assert(unknown.action == .monitor && unknown.unavailableReasons == [104])
|
||||
assert(!unknown.shouldRestrict(in:.observe) && unknown.shouldRestrict(in:.enforce))
|
||||
let tamper=policy.evaluate(findings:[RDDefenderFinding(status:1,reason:105)],legacy:legacy)
|
||||
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))
|
||||
''')
|
||||
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)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,188 @@
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("redirect_symbols", ROOT / "tools/static_sdk_redirect/redirect_symbols.py")
|
||||
redirect = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(redirect)
|
||||
|
||||
|
||||
def object_bytes(name=b"_fopen", ntype=1):
|
||||
strings = b"\0" + name + b"\0"
|
||||
header = struct.pack("<8I", 0xFEEDFACF, redirect.CPU_ARM64, 0, 1, 1, 24, 0, 0)
|
||||
command = struct.pack("<6I", 2, 24, 56, 1, 72, len(strings))
|
||||
symbol = struct.pack("<IBBHQ", 1, ntype, 0, 0, 0)
|
||||
return header + command + symbol + strings
|
||||
|
||||
|
||||
def llvm_object(payload):
|
||||
segment = bytearray(152)
|
||||
struct.pack_into("<II", segment, 0, 0x19, 152)
|
||||
struct.pack_into("<I", segment, 64, 1)
|
||||
segment[72:88] = b"__bitcode".ljust(16, b"\0")
|
||||
segment[88:104] = b"__LLVM".ljust(16, b"\0")
|
||||
struct.pack_into("<QI", segment, 112, len(payload), 208)
|
||||
strings = b"\0_fopen\0"
|
||||
header = struct.pack("<8I", 0xFEEDFACF, redirect.CPU_ARM64, 0, 1, 2, 176, 0, 0)
|
||||
command = struct.pack("<6I", 2, 24, 216, 1, 232, len(strings))
|
||||
symbol = struct.pack("<IBBHQ", 1, 1, 0, 0, 0)
|
||||
return header + segment + command + payload.ljust(8, b"\0") + symbol + strings
|
||||
|
||||
|
||||
class FormatTests(unittest.TestCase):
|
||||
def test_invalid_mappings(self):
|
||||
invalid = [{}, [], {"fopen": "_IG_fopen"}, {"_a": "_a"},
|
||||
{"_a": "_b", "_b": "_c"}, {"_a": "_x", "_b": "_x"},
|
||||
{"_a": 3}, {"_a": "_x\u0000"}]
|
||||
for mapping in invalid:
|
||||
with self.subTest(mapping=mapping), self.assertRaises(ValueError):
|
||||
redirect.validate_mapping(mapping)
|
||||
|
||||
def test_duplicate_json_key(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "mapping.json"
|
||||
path.write_text('{"_a":"_x", "_a":"_y"}')
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.load_mapping(path)
|
||||
|
||||
def test_custom_mapping(self):
|
||||
result, count = redirect.redirect_object(object_bytes(b"_my_function"),
|
||||
{"_my_function": "_custom_bridge"})
|
||||
self.assertEqual(count, 1)
|
||||
self.assertIn(b"_custom_bridge\0", result)
|
||||
|
||||
def test_relocation_index_unchanged(self):
|
||||
original = object_bytes()
|
||||
result, count = redirect.redirect_object(original)
|
||||
self.assertEqual(count, 1)
|
||||
self.assertEqual(result[:52], original[:52])
|
||||
self.assertEqual(result[60:72], original[60:72])
|
||||
index = struct.unpack_from("<I", result, 56)[0]
|
||||
self.assertEqual(result[72 + index:].split(b"\0")[0], b"_IG_fopen")
|
||||
|
||||
def test_unrelated_symbol_unchanged(self):
|
||||
data = object_bytes(b"_fclose")
|
||||
self.assertEqual(redirect.redirect_object(data), (data, 0))
|
||||
|
||||
def test_reject_defined_source(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(object_bytes(ntype=0x0F))
|
||||
|
||||
def test_reject_existing_destination(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(object_bytes(b"_IG_fopen"))
|
||||
|
||||
def test_reject_truncation(self):
|
||||
data = object_bytes()
|
||||
for size in (0, 4, 31, 40, 60, len(data) - 1):
|
||||
with self.subTest(size=size), self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data[:size])
|
||||
|
||||
def test_archive_padding(self):
|
||||
data = object_bytes()
|
||||
self.assertEqual(redirect.redirect_object(data + b"\n" * 4)[1], 1)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data + b"ABCD")
|
||||
|
||||
def test_reject_malformed_archive(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_archive(b"!<arch>\ntruncated")
|
||||
|
||||
def test_preserve_empty_bitcode_marker(self):
|
||||
data = llvm_object(b"\0")
|
||||
result, count = redirect.redirect_object(data)
|
||||
self.assertEqual(count, 1)
|
||||
self.assertEqual(result[208:216], data[208:216])
|
||||
|
||||
def test_reject_real_bitcode(self):
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(llvm_object(b"BC\xc0\xde"))
|
||||
|
||||
def test_reject_dylib(self):
|
||||
data = bytearray(object_bytes())
|
||||
struct.pack_into("<I", data, 12, 6)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.redirect_object(data)
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.system() == "Darwin" and platform.machine() == "arm64", "需要 ARM64 Mac + Xcode")
|
||||
class NativeTests(unittest.TestCase):
|
||||
def test_multiple_symbols_and_cli(self):
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-multi-") as folder:
|
||||
root = Path(folder)
|
||||
obj, library, output = root / "sdk.o", root / "sdk.a", root / "protected.a"
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-c", str(ROOT / "tests/fixtures/sdk_io.c"),
|
||||
"-o", str(obj)], check=True)
|
||||
subprocess.run(["xcrun", "ar", "rcs", str(library), str(obj)], check=True)
|
||||
mapping = redirect.load_mapping(ROOT / "tools/static_sdk_redirect/mappings/stdio.json")
|
||||
mapping.update(redirect.load_mapping(ROOT / "tools/static_sdk_redirect/mappings/posix_io.json"))
|
||||
config = root / "mapping.json"
|
||||
config.write_text(json.dumps(mapping))
|
||||
command = [sys.executable, str(ROOT / "tools/static_sdk_redirect/redirect_symbols.py"),
|
||||
str(library), str(output), "--mapping", str(config), "--require-all"]
|
||||
report = json.loads(subprocess.check_output(command, text=True))
|
||||
self.assertEqual(report["references_redirected"], 7)
|
||||
self.assertEqual(report["symbol_counts"], {name: 1 for name in mapping})
|
||||
self.assertEqual(report["unmatched_symbols"], [])
|
||||
symbols = {s.strip() for s in subprocess.check_output(["xcrun", "nm", "-u", str(output)], text=True).splitlines()}
|
||||
self.assertTrue(set(mapping.values()) <= symbols)
|
||||
self.assertFalse(set(mapping) & symbols)
|
||||
for name, archive, extra in (("baseline", library, []),
|
||||
("redirected", output, [str(ROOT / "defender/call_bridge/IGFileBridge.c")])):
|
||||
binary = root / name
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-Wall", "-Wextra", "-Werror", "-DIG_TEST_ALL_BRIDGES",
|
||||
str(ROOT / "tests/fixtures/file_semantics.c"), str(archive), *extra,
|
||||
"-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary), str(root)], check=True)
|
||||
missing = {**mapping, "_absent": "_IG_absent"}
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, root / "strict.a", missing, require_all=True)
|
||||
self.assertFalse((root / "strict.a").exists())
|
||||
partial = redirect.run(library, root / "partial.a", missing)
|
||||
self.assertEqual(partial["unmatched_symbols"], ["_absent"])
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, root / "none.a", {"_absent": "_IG_absent"})
|
||||
self.assertFalse((root / "none.a").exists())
|
||||
legacy = json.loads(subprocess.check_output([sys.executable,
|
||||
str(ROOT / "tools/static_sdk_redirect/redirect_fopen.py"),
|
||||
str(library), str(root / "legacy.a")], text=True))
|
||||
self.assertEqual(legacy["references_redirected"], 1)
|
||||
|
||||
def test_link_and_file_semantics(self):
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-test-") as folder:
|
||||
root = Path(folder)
|
||||
source = root / "sdk.c"
|
||||
source.write_text('#include <stdio.h>\nFILE *sdk_open(const char *p, const char *m) { return fopen(p,m); }\n')
|
||||
obj, library, output = root / "sdk.o", root / "sdk.a", root / "protected.a"
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-c", str(source), "-o", str(obj)], check=True)
|
||||
subprocess.run(["xcrun", "ar", "rcs", str(library), str(obj)], check=True)
|
||||
original = library.read_bytes()
|
||||
report = redirect.run(library, output)
|
||||
self.assertEqual(report["references_redirected"], 1)
|
||||
self.assertEqual(library.read_bytes(), original)
|
||||
symbols = subprocess.check_output(["xcrun", "nm", "-u", str(output)], text=True).splitlines()
|
||||
self.assertIn("_IG_fopen", [s.strip() for s in symbols])
|
||||
self.assertNotIn("_fopen", [s.strip() for s in symbols])
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(library, output)
|
||||
with self.assertRaises(ValueError):
|
||||
redirect.run(output, root / "twice.a")
|
||||
# 同一行为测试分别链接原始归档和改写后的归档。
|
||||
for name, archive, extra in (("baseline", library, []),
|
||||
("redirected", output, [str(ROOT / "defender/call_bridge/IGFileBridge.c")])):
|
||||
binary = root / name
|
||||
subprocess.run(["xcrun", "clang", "-O2", "-Wall", "-Wextra", "-Werror",
|
||||
str(ROOT / "tests/fixtures/file_semantics.c"), str(archive),
|
||||
*extra, "-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary), str(root)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# build_defender_lib.sh — 把 defender/ 全部 C 源交叉编译并打包成可集成静态库。
|
||||
#
|
||||
# 产物(默认输出到 dist/):
|
||||
# dist/lib/libIGDefender.a arm64 iphoneos 静态库
|
||||
# dist/include/IGGuard.h 统一公共头(umbrella)
|
||||
# dist/include/... 随附的全部公共头(保持相对目录,供 IGGuard.h 相对引用)
|
||||
#
|
||||
# 用法:
|
||||
# sh tools/build_defender_lib.sh [输出目录]
|
||||
# sh tools/build_defender_lib.sh # → ./dist
|
||||
# sh tools/build_defender_lib.sh /path/to/out # → 指定目录
|
||||
#
|
||||
# 接入方式见 docs/18_READOOR_DEFENDER_INTEGRATION.md。
|
||||
set -eu
|
||||
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
OUT=${1:-"$ROOT/dist"}
|
||||
SDK=iphoneos
|
||||
ARCH=arm64
|
||||
MINVER=15.0
|
||||
CFLAGS="-arch $ARCH -miphoneos-version-min=$MINVER -O2 -Wall -Wextra -I$ROOT/defender -I$ROOT/defender/include"
|
||||
|
||||
OBJDIR=$(mktemp -d)
|
||||
trap 'rm -rf "$OBJDIR"' EXIT
|
||||
|
||||
echo "[1/4] 交叉编译 ($SDK/$ARCH)…"
|
||||
find "$ROOT/defender" -name '*.c' | while read -r f; do
|
||||
o="$OBJDIR/$(echo "$f" | sed "s|$ROOT/||; s|/|_|g").o"
|
||||
xcrun -sdk "$SDK" clang $CFLAGS -c "$f" -o "$o"
|
||||
done
|
||||
|
||||
echo "[2/4] 打包 libIGDefender.a…"
|
||||
mkdir -p "$OUT/lib" "$OUT/include"
|
||||
xcrun -sdk "$SDK" ar rcs "$OUT/lib/libIGDefender.a" "$OBJDIR"/*.o
|
||||
xcrun -sdk "$SDK" ranlib "$OUT/lib/libIGDefender.a"
|
||||
|
||||
echo "[3/4] 拷贝公共头…"
|
||||
# 单一 HEADER_SEARCH_PATH=<out>/include 即自洽:
|
||||
# - defender/include/ 下的头(IGGuard.h / IGDefender.h …)平移到 include 根
|
||||
# - 其余子目录头(poison/ policy/ syscall/ …)保持相对目录,供 umbrella 相对引用
|
||||
( cd "$ROOT/defender" && \
|
||||
find . -name '*.h' | sed 's|^\./||' | sort -u | while read -r h; do
|
||||
case "$h" in
|
||||
include/*) dst="${h#include/}" ;; # include/ 下平移到根
|
||||
*) dst="$h" ;;
|
||||
esac
|
||||
mkdir -p "$OUT/include/$(dirname "$dst")"
|
||||
cp "$ROOT/defender/$h" "$OUT/include/$dst"
|
||||
done )
|
||||
|
||||
echo "[4/4] 校验导出符号…"
|
||||
xcrun -sdk "$SDK" nm "$OUT/lib/libIGDefender.a" 2>/dev/null \
|
||||
| grep -E ' T _ig_(policy_scan_and_mark|poison_apply|poison_init|defender_scan)' | sort -u || true
|
||||
|
||||
echo "完成:$OUT/lib/libIGDefender.a ($(lipo -archs "$OUT/lib/libIGDefender.a"))"
|
||||
echo "公共头:$OUT/include/IGGuard.h"
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env ruby
|
||||
# 为门禁按钮级回归生成独立 XCUITest Runner,不修改 readoor 工程。
|
||||
# 与 create_ui_runner.rb 同构;目标 App 为强制模式 dev 包(cn.touchv.a4YX061),
|
||||
# 测试源为 IGGateRegressionTests.swift。诊断专用 Bundle ID,测试后卸载。
|
||||
require 'xcodeproj'
|
||||
require 'fileutils'
|
||||
root = File.expand_path('../..', __dir__)
|
||||
output = ARGV.fetch(0)
|
||||
abort('输出目录必须不存在') if File.exist?(output)
|
||||
FileUtils.mkdir_p(output)
|
||||
project = Xcodeproj::Project.new(File.join(output, 'IGGateRegression.xcodeproj'))
|
||||
target = project.new_target(:ui_test_bundle, 'IGGateRegression', :ios, '15.0')
|
||||
ref = project.main_group.new_file(File.join(root, 'tests/business_regression/IGGateRegressionTests.swift'))
|
||||
target.add_file_references([ref])
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings.merge!({
|
||||
'PRODUCT_BUNDLE_IDENTIFIER' => 'cn.touchv.iosguard.gateregression',
|
||||
'GENERATE_INFOPLIST_FILE' => 'YES', 'SWIFT_VERSION' => '5.0',
|
||||
'CODE_SIGN_STYLE' => 'Manual', 'DEVELOPMENT_TEAM' => 'MG4Z7FU83W',
|
||||
'CODE_SIGN_IDENTITY' => '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8',
|
||||
'PROVISIONING_PROFILE_SPECIFIER' => 'e0f18495-668f-4fb1-87e1-4e048fb48d11',
|
||||
'TARGETED_DEVICE_FAMILY' => '1,2'
|
||||
})
|
||||
end
|
||||
project.save
|
||||
scheme = Xcodeproj::XCScheme.new
|
||||
scheme.add_build_target(target)
|
||||
scheme.add_test_target(target)
|
||||
scheme.save_as(project.path, 'IGGateRegression', true)
|
||||
puts project.path
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env ruby
|
||||
# 为已安装的独立观察包生成独立 XCTest Runner,不修改 readoor 工程。
|
||||
require 'xcodeproj'
|
||||
require 'fileutils'
|
||||
root = File.expand_path('../..', __dir__)
|
||||
output = ARGV.fetch(0)
|
||||
abort('输出目录必须不存在') if File.exist?(output)
|
||||
FileUtils.mkdir_p(output)
|
||||
project = Xcodeproj::Project.new(File.join(output, 'IGBusinessRegression.xcodeproj'))
|
||||
target = project.new_target(:ui_test_bundle, 'IGBusinessRegression', :ios, '15.0')
|
||||
ref = project.main_group.new_file(File.join(root, 'tests/business_regression/IGBusinessRegressionTests.swift'))
|
||||
target.add_file_references([ref])
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings.merge!({
|
||||
'PRODUCT_BUNDLE_IDENTIFIER' => 'cn.touchv.iosguard.businessuitests',
|
||||
'GENERATE_INFOPLIST_FILE' => 'YES', 'SWIFT_VERSION' => '5.0',
|
||||
'CODE_SIGN_STYLE' => 'Manual', 'DEVELOPMENT_TEAM' => 'MG4Z7FU83W',
|
||||
'CODE_SIGN_IDENTITY' => '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8',
|
||||
'PROVISIONING_PROFILE_SPECIFIER' => 'e0f18495-668f-4fb1-87e1-4e048fb48d11',
|
||||
'TARGETED_DEVICE_FAMILY' => '1,2'
|
||||
})
|
||||
end
|
||||
project.save
|
||||
scheme = Xcodeproj::XCScheme.new
|
||||
scheme.add_build_target(target)
|
||||
scheme.add_test_target(target)
|
||||
scheme.save_as(project.path, 'IGBusinessRegression', true)
|
||||
puts project.path
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""定点加固并签名独立业务观察包;保留真实网络,禁用与原 App 冲突的 URL scheme。"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0,str(ROOT/'tools/macho_guard'))
|
||||
from redirect_to_runtime import patch,sha,trace_calls
|
||||
from verify_baseline import inventory,save
|
||||
from redirect_framework_imports import patch as patch_framework
|
||||
|
||||
ARCHIVE_SHA='485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
|
||||
|
||||
def prepare_archive(guarded,output,command,baseline):
|
||||
sdk=guarded/'Frameworks/SSZipArchive.framework/SSZipArchive'
|
||||
if sha(sdk)!=ARCHIVE_SHA:raise ValueError('SSZipArchive 版本变化,须重新审核绑定规则')
|
||||
folder=guarded/'Frameworks/IGArchiveGuard.framework'
|
||||
if folder.exists():raise ValueError('保护 Framework 已存在')
|
||||
folder.mkdir()
|
||||
(folder/'Info.plist').write_bytes(plistlib.dumps(dict(
|
||||
CFBundleExecutable='IGArchiveGuard',CFBundleIdentifier='cn.touchv.iosguard.archiveguard',
|
||||
CFBundleName='IGArchiveGuard',CFBundlePackageType='FMWK',CFBundleVersion='1',
|
||||
CFBundleShortVersionString='1.0',MinimumOSVersion='15.0',CFBundleSupportedPlatforms=['iPhoneOS'])))
|
||||
sources=['dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
|
||||
command(['xcrun','--sdk','iphoneos','clang','-arch','arm64','-miphoneos-version-min=15.0',
|
||||
'-O2','-Wall','-Wextra','-Werror','-fvisibility=hidden','-DIG_OBSERVATION',
|
||||
'-I',ROOT/'defender','-I',ROOT/'defender/include','-dynamiclib',
|
||||
*(ROOT/'defender'/p for p in sources),
|
||||
'-Wl,-install_name,@rpath/IGArchiveGuard.framework/IGArchiveGuard',
|
||||
'-Wl,-map,'+str(output/'archive-guard-link.map'),
|
||||
*(f'-Wl,-exported_symbol,_{n}' for n in
|
||||
['ig_a0','ig_a1','ig_a2','ig_a3','ig_archive_check','ig_archive_counter']),
|
||||
'-o',folder/'IGArchiveGuard'])
|
||||
symbols=command(['xcrun','nm','-g',folder/'IGArchiveGuard'])
|
||||
if 'ig_archive_test_' in symbols:raise ValueError('业务保护 Framework 含测试接口')
|
||||
# 基线仍执行完整格式审核,但不保留 SDK 改写;两包主程序完全相同。
|
||||
temp=output/'ssziparchive-rewritten'
|
||||
report=patch_framework(sdk,temp,ARCHIVE_SHA)
|
||||
if baseline:temp.unlink()
|
||||
else:shutil.move(temp,sdk)
|
||||
report.update(baseline=baseline,applied=not baseline)
|
||||
save(output/'archive-redirect-report.json',report)
|
||||
(output/'archive-guard-exports.txt').write_text(symbols)
|
||||
|
||||
def prepare(app,linkmap,profile,identity,output,baseline=False,archive_guard=False,archive_baseline=False):
|
||||
if archive_baseline and not archive_guard:raise ValueError('archive-baseline 需要 archive-guard')
|
||||
if archive_guard and baseline:raise ValueError('SDK 对照不能同时改变主程序基线')
|
||||
if output.exists():raise ValueError('输出目录必须不存在')
|
||||
p=subprocess.run(['openssl','smime','-inform','der','-verify','-noverify','-in',str(profile)],capture_output=True,check=True)
|
||||
provision=plistlib.loads(p.stdout);prefix=provision['ApplicationIdentifierPrefix'][0]
|
||||
ent=provision['Entitlements']
|
||||
if ent['application-identifier']!=prefix+'.*' or not ent.get('get-task-allow'):raise ValueError('需要通配开发 profile')
|
||||
if provision['ExpirationDate']<=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None):raise ValueError('profile 已过期')
|
||||
if identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in provision['DeveloperCertificates']}:raise ValueError('签名身份不匹配')
|
||||
bundle='cn.touchv.iosguard.observe.20261110'
|
||||
output.mkdir(parents=True)
|
||||
def command(args):
|
||||
r=subprocess.run(list(map(str,args)),capture_output=True,text=True)
|
||||
with (output/'commands.log').open('a') as log:log.write(json.dumps(list(map(str,args)))+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
|
||||
if r.returncode:raise RuntimeError('命令失败,详见 commands.log')
|
||||
return r.stdout
|
||||
guarded=output/'Payload'/app.name
|
||||
command(['ditto',app,guarded])
|
||||
info=plistlib.loads((guarded/'Info.plist').read_bytes());exe=guarded/info['CFBundleExecutable']
|
||||
symbols=subprocess.run(['xcrun','nm',exe],capture_output=True,text=True,check=True).stdout
|
||||
if '_ig_dispatch_observation' not in symbols:raise ValueError('输入不是观察构建')
|
||||
if 'ig_dispatch_test_' in symbols:raise ValueError('业务包不得包含测试覆盖地址接口')
|
||||
rules=json.loads((ROOT/'tools/macho_guard/profiles/zipzap.json').read_text())
|
||||
patched=output/'patched-binary';report=patch(exe,patched,linkmap,rules)
|
||||
report['trace_before']=trace_calls(exe,linkmap,[r['caller'] for r in rules['rules']])
|
||||
if baseline:
|
||||
# 仍验证同次 Link Map 和预期调用点,但基线不保留任何分支改写。
|
||||
patched.unlink()
|
||||
report=dict(input_sha256=sha(exe),output_sha256=sha(exe),total=0,changes=[],
|
||||
validated_guard_changes=report['changes'],trace_before=report['trace_before'],
|
||||
trace_after=report['trace_before'],baseline=True)
|
||||
else:
|
||||
report['trace_after']=trace_calls(patched,linkmap,[r['caller'] for r in rules['rules']])
|
||||
if any(r.get('symbol') in ('_write','_close') for r in report['trace_after']):raise ValueError('原目标直接/GOT 路径仍存在')
|
||||
shutil.move(patched,exe)
|
||||
original_bundle=info['CFBundleIdentifier'];info['CFBundleIdentifier']=bundle
|
||||
info['CFBundleDisplayName']='教育汇·观察'
|
||||
removed={k:info.pop(k) for k in ('CFBundleURLTypes',) if k in info}
|
||||
(guarded/'Info.plist').write_bytes(plistlib.dumps(info))
|
||||
shutil.copy2(profile,guarded/'embedded.mobileprovision')
|
||||
allowed={k:v for k,v in ent.items() if k not in ('application-identifier','keychain-access-groups')}
|
||||
allowed.update({'application-identifier':prefix+'.'+bundle,'keychain-access-groups':[prefix+'.'+bundle]})
|
||||
(output/'entitlements.plist').write_bytes(plistlib.dumps(allowed))
|
||||
if archive_guard:prepare_archive(guarded,output,command,archive_baseline)
|
||||
# 独立 sandbox 不复用原 keychain/关联域/Apple 登录权限;相关功能单独验收。
|
||||
nested={p for p in guarded.rglob('*') if not p.is_symlink() and p.suffix in ('.framework','.dylib')}
|
||||
if any(guarded.rglob('*.appex')):raise ValueError('含扩展时需分别匹配 profile,拒绝自动套通配签名')
|
||||
for p in sorted(nested,key=lambda p:(-len(p.parts),str(p))):command(['codesign','--force','--sign',identity,p])
|
||||
command(['codesign','--force','--sign',identity,'--entitlements',output/'entitlements.plist',guarded])
|
||||
for p in sorted(nested|{guarded}):command(['codesign','--verify','--strict','--verbose=2',p])
|
||||
shutil.copy2(linkmap,output/'link.map')
|
||||
report['signed_output_sha256']=sha(exe);save(output/'redirect-report.json',report)
|
||||
snapshot=output/'source-snapshot'
|
||||
for folder in ('defender','tools/macho_guard','tools/business_regression','tests/business_regression','readoor-test/readoor/3.0/Base/Security','readoor-test/readoor/3.0/Features/ReadView/PDF/Network','readoor-test/readoor/3.0/Features/ReadView/MemorizeWords/Handler'):
|
||||
for src in (ROOT/folder).rglob('*'):
|
||||
if src.is_file() and src.suffix in ('.c','.h','.swift','.py','.rb') and '__pycache__' not in src.parts:
|
||||
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
|
||||
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded.parent,output/'observation.ipa'])
|
||||
save(output/'manifest.json',dict(status='ready_for_device_regression',bundle_id=bundle,original_bundle_id=original_bundle,
|
||||
source_version=info.get('CFBundleShortVersionString'),redirected=report['total'],signing='development',
|
||||
fake_login=False,mode='observe',baseline=baseline,archive_guard=archive_guard,
|
||||
archive_baseline=archive_baseline,device_business_regression='not_run',
|
||||
limitations=['独立 Bundle ID;不覆盖既有 App','未接入原 App Apple 登录、关联域、共享 Keychain 和 URL 回调',
|
||||
'检测观察模式不关闭 C 调度拒绝机制'],removed_url_scheme_count=len(removed.get('CFBundleURLTypes',[])),
|
||||
executable_sha256=sha(exe),ipa_sha256=sha(output/'observation.ipa')))
|
||||
save(output/'evidence-hashes.json',inventory(output))
|
||||
print(guarded)
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('app','link-map','profile','output'):p.add_argument('--'+name,type=Path,required=True)
|
||||
p.add_argument('--identity',required=True)
|
||||
p.add_argument('--baseline',action='store_true',help='不保留分支改写,用同构建和独立 Bundle ID 做对照')
|
||||
p.add_argument('--archive-guard',action='store_true',help='嵌入并定点改写 SSZipArchive 文件函数绑定')
|
||||
p.add_argument('--archive-baseline',action='store_true',help='嵌入相同保护库但保留 SDK 原绑定,用于同构建对照')
|
||||
a=p.parse_args();prepare(a.app.resolve(),a.link_map.resolve(),a.profile.resolve(),a.identity,a.output.resolve(),a.baseline,a.archive_guard,a.archive_baseline)
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
#!/bin/bash
|
||||
# 门禁按钮级回归编排(dev 包 cn.touchv.a4YX061,iPhone 16 Plus)。
|
||||
#
|
||||
# v6 要点(v5d/v5e 教训):
|
||||
# 1. XCUITest launchEnvironment 的 DYLD_INSERT 被 SpringBoard 剥离——注入相位必须
|
||||
# devicectl `-e` 调试启动通道预先启动,测试仅 activate() attach。
|
||||
# 2. devicectl `--console` 通道在连续会话后不可靠(console 零输出、进程即死、命令卡
|
||||
# 超时;v5e 相位 2/4 三次重试全失败,且连无注入的干净 console 启动也卡死)——
|
||||
# v6 改为无 console 启动:注入生效的证明 = 进程存活 + 测试内门禁 toast 端到端
|
||||
# 命中(toast 只可能由 Defender 证据触发,链条自证)。console 仅在进程死亡时作
|
||||
# 诊断回退。
|
||||
# 3. 相位重排,XCUITest↔devicectl 切换从 4 次降到 2 次:
|
||||
# ① 干净批 A1 勘察 + A2 确保游客态·登录页 → ② 注入批(游客)B1+B2
|
||||
# ③ 干净批 C1 放行证明(真实登录尝试,断言只要求无门禁 toast)→ ④ 注入批(登录
|
||||
# 态,若 C1 未登成则 D1/E1 以游客守卫跳过留证)D1+E1
|
||||
#
|
||||
# 用法:run_gate_regression.sh <runner目录> <输出目录>
|
||||
set -uo pipefail
|
||||
|
||||
UDID=00008140-000960811493001C
|
||||
BUNDLE=cn.touchv.a4YX061
|
||||
DYLIB=/private/var/mobile/Containers/Data/Application/ED2D2D55-FBA5-4106-BEFD-87A7D40A42B9/Documents/libfrida-sim.dylib
|
||||
|
||||
RUNNER=${1:?用法: run_gate_regression.sh <runner目录> <输出目录>}
|
||||
OUT=${2:?用法: run_gate_regression.sh <runner目录> <输出目录>}
|
||||
mkdir -p "$OUT"
|
||||
# 子 shell 会 cd 进 runner,全部转绝对路径避免相对路径错位(v5 首跑教训)
|
||||
OUT=$(cd "$OUT" && pwd)
|
||||
RUNNER=$(cd "$RUNNER" && pwd)
|
||||
|
||||
launch_injected() { # $1=相位名:终止现进程→devicectl 无 console 注入启动→
|
||||
# 轮询进程存活确认(debug 通道坏时进程即死,v5e 教训),最多 3 次重试;
|
||||
# 死亡时追加一次 --console 诊断启动留取 Defender 决策行/报错。成功后等 UI 稳定。
|
||||
local phase=$1 alive=1
|
||||
for attempt in 1 2 3; do
|
||||
xcrun devicectl device process terminate --device "$UDID" "$BUNDLE" >/dev/null 2>&1
|
||||
sleep 2
|
||||
xcrun devicectl device process launch --device "$UDID" \
|
||||
-e "{\"DYLD_INSERT_LIBRARIES\":\"$DYLIB\"}" "$BUNDLE" \
|
||||
> "$OUT/launch-$phase-$attempt.log" 2>&1
|
||||
local launched_rc=$? alive_now=0
|
||||
for _ in $(seq 1 10); do # 30s 内确认进程存活
|
||||
sleep 3
|
||||
if [ "$(xcrun devicectl device info processes --device "$UDID" 2>/dev/null | grep -c "$BUNDLE")" -ge 1 ]; then
|
||||
alive_now=1; break
|
||||
fi
|
||||
done
|
||||
if [ "$alive_now" = 1 ]; then
|
||||
echo "注入进程存活(第 $attempt 次尝试,rc=$launched_rc)——注入生效由测试内门禁 toast 端到端自证"
|
||||
sleep 90 # 冷启动到首页稳定(A1 实测 ~158s 首页,90s 后 D1/E1 各自再等首页锚点)
|
||||
alive=0; return 0
|
||||
fi
|
||||
echo "第 $attempt 次注入启动进程死亡,重试"
|
||||
done
|
||||
# 诊断回退:console 模式抓一次输出(若 debug 通道可用可拿到 Defender 决策行)
|
||||
xcrun devicectl device process launch --device "$UDID" --console --timeout 60 \
|
||||
-e "{\"DYLD_INSERT_LIBRARIES\":\"$DYLIB\"}" "$BUNDLE" \
|
||||
> "$OUT/console-diag-$phase.log" 2>&1 &
|
||||
echo "$!" > "$OUT/console-diag-$phase.pid"
|
||||
echo "警告:$phase 三次注入启动进程均死亡;已发起 console 诊断启动(见 console-diag-$phase.log)"
|
||||
return 1
|
||||
}
|
||||
|
||||
run_tests() { # $1=结果包名, 其余=-only-testing 参数
|
||||
local result=$1; shift
|
||||
rm -rf "$OUT/$result" # xcodebuild 拒绝覆盖已存在结果包
|
||||
(cd "$RUNNER" && xcodebuild test-without-building \
|
||||
-project IGGateRegression.xcodeproj -scheme IGGateRegression \
|
||||
-destination "id=$UDID" -resultBundlePath "$OUT/$result" "$@" \
|
||||
> "$OUT/xcodebuild-$result.log" 2>&1)
|
||||
echo "EXIT_$result=$?"
|
||||
}
|
||||
|
||||
echo "== 相位1 干净批:A1 勘察 + A2 确保游客态(登录页)"
|
||||
run_tests results-clean1.xcresult \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testA1InspectCleanState \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testA2LogoutIfNeeded
|
||||
|
||||
echo "== 相位2 注入批(游客态):B1 密码 + B2 第三方"
|
||||
launch_injected b12 || true
|
||||
run_tests results-inject-guest.xcresult \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testB1BlockPasswordLogin \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testB2BlockOtherLogins
|
||||
|
||||
echo "== 相位3 干净批:C1 放行证明(真实登录尝试)"
|
||||
run_tests results-clean2.xcresult \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testC1AllowPasswordLogin
|
||||
|
||||
echo "== 相位4 注入批(登录态):D1 VIP + E1 激活"
|
||||
launch_injected de1 || true
|
||||
run_tests results-inject-login.xcresult \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testD1BlockVipPurchase \
|
||||
-only-testing:IGGateRegression/IGGateRegressionTests/testE1BlockActivation
|
||||
|
||||
# 收尾:先终止应用(让 console 诊断会话自然收口),再清残留进程
|
||||
xcrun devicectl device process terminate --device "$UDID" "$BUNDLE" >/dev/null 2>&1
|
||||
for pidf in "$OUT"/console-diag-*.pid; do kill "$(cat "$pidf")" 2>/dev/null; done
|
||||
|
||||
echo "== 完成。诊断 console 中的 Defender 决策行(若有):"
|
||||
grep -h "Defender\|证据" "$OUT"/console-diag-*.log 2>/dev/null | tail -8
|
||||
@@ -0,0 +1,165 @@
|
||||
"""批处理:遍历 .app 包内所有 Mach-O(thin / fat 单 arm64 切片),
|
||||
对每个 arm64 切片运行自研直接分支规则(扫 __text 全部 bl/b → __stubs,
|
||||
经间接符号表映射到 12 个命中符号),统计命中数与注入余量。
|
||||
|
||||
scan 模式只读不改;harden 模式见 macho_guard.harden_bundle。
|
||||
"""
|
||||
import struct, sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
SYMBOLS = ["_fopen","_dlopen","_dlsym","_write","_read","_open",
|
||||
"_close","_exit","_fork","_syscall","_unlink","_getpid"]
|
||||
WANT = set(SYMBOLS)
|
||||
|
||||
FAT_MAGIC = 0xBEBAFECA # fat_header magic, big-endian on disk (cafebabe 按大端读)
|
||||
FAT_MAGIC_LE = 0xCAFEBABE
|
||||
MH64 = 0xFEEDFACF
|
||||
LC_SEGMENT_64=0x19; LC_SYMTAB=0x2; LC_DYSYMTAB=0xb
|
||||
LC_ENCRYPTION_INFO_64=0x2C
|
||||
|
||||
def arm64_slices(data):
|
||||
"""返回 [(slice_offset, slice_size)];thin 返回单个 (0,len),fat 挑 arm64(非 arm64e)。"""
|
||||
magic,=struct.unpack_from(">I",data,0)
|
||||
if magic==FAT_MAGIC_LE: # fat:字段大端
|
||||
nfat,=struct.unpack_from(">I",data,4)
|
||||
out=[]
|
||||
for i in range(nfat):
|
||||
cputype,cpusub,off,size,align=struct.unpack_from(">IIIII",data,8+i*20)
|
||||
# CPU_TYPE_ARM64=0x0100000C;cpusub 低 24 位:0=ARM64_ALL,1=ARM64E(2)
|
||||
if cputype==0x0100000C and (cpusub & 0x00FFFFFF) in (0,1):
|
||||
out.append((off,size))
|
||||
return out
|
||||
m,=struct.unpack_from("<I",data,0)
|
||||
if m==MH64:
|
||||
cpu, sub=struct.unpack_from("<II",data,4)
|
||||
return [(0,len(data))] if cpu==0x0100000c and (sub & 0xffffff) in (0,1) else []
|
||||
return [] # 非 arm64 Mach-O
|
||||
|
||||
class Slice:
|
||||
"""一个 thin arm64 Mach-O 切片的只读分析视图(偏移均相对 base)。"""
|
||||
def __init__(self, data, base):
|
||||
self.d=data; self.base=base
|
||||
magic,=struct.unpack_from("<I",data,base)
|
||||
assert magic==MH64
|
||||
self.ncmds,=struct.unpack_from("<I",data,base+16)
|
||||
self.text=self.stubs=self.symtab=self.dysym=None
|
||||
self.cryptid=0; self.first_sect_foff=None; self.sizeofcmds=0
|
||||
self.text_vmaddr=0
|
||||
off=base+32
|
||||
self.sizeofcmds,=struct.unpack_from("<I",data,base+20)
|
||||
for _ in range(self.ncmds):
|
||||
cmd,cmdsize=struct.unpack_from("<II",data,off)
|
||||
if cmd==LC_SEGMENT_64:
|
||||
segname=data[off+8:off+24].split(b"\0")[0].decode()
|
||||
vmaddr,=struct.unpack_from("<Q",data,off+24)
|
||||
nsects,=struct.unpack_from("<I",data,off+64)
|
||||
if segname=="__TEXT": self.text_vmaddr=vmaddr
|
||||
so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=data[so:so+16].split(b"\0")[0].decode()
|
||||
addr,size=struct.unpack_from("<QQ",data,so+32)
|
||||
foff,=struct.unpack_from("<I",data,so+48)
|
||||
r1,r2=struct.unpack_from("<II",data,so+68)
|
||||
if foff>0 and (self.first_sect_foff is None or foff<self.first_sect_foff):
|
||||
self.first_sect_foff=foff
|
||||
if sn=="__text": self.text=(addr,size,foff)
|
||||
if sn=="__stubs": self.stubs=(addr,size,foff,r1,r2)
|
||||
so+=80
|
||||
elif cmd==LC_SYMTAB: self.symtab=struct.unpack_from("<IIII",data,off+8)
|
||||
elif cmd==LC_DYSYMTAB: self.dysym=struct.unpack_from("<"+"I"*18,data,off+8)
|
||||
elif cmd==LC_ENCRYPTION_INFO_64: self.cryptid=struct.unpack_from("<I",data,off+16)[0]
|
||||
off+=cmdsize
|
||||
|
||||
def foff(self, slice_rel):
|
||||
"""切片内相对偏移 → 文件绝对偏移。"""
|
||||
return self.base+slice_rel
|
||||
|
||||
def stub_symbol_map(self):
|
||||
"""{stub_vmaddr: symbol_name} 仅限 WANT 中符号。"""
|
||||
if not (self.stubs and self.symtab and self.dysym): return {}
|
||||
symoff,nsyms,stroff,strsize=self.symtab
|
||||
indoff=self.dysym[12]
|
||||
saddr,ssize,sfoff,sr1,sr2=self.stubs
|
||||
out={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",self.d,self.base+indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",self.d,self.base+symoff+idx*16)
|
||||
end=self.d.index(b"\0",self.base+stroff+strx)
|
||||
name=self.d[self.base+stroff+strx:end].decode()
|
||||
if name in WANT: out[saddr+i*sr2]=name
|
||||
return out
|
||||
|
||||
def scan(self):
|
||||
"""Counter{符号:命中数}。__text 内所有 bl/b 目标落到 WANT stub 的计数。"""
|
||||
from collections import Counter
|
||||
cnt=Counter()
|
||||
if not self.text: return cnt
|
||||
stub_sym=self.stub_symbol_map()
|
||||
if not stub_sym: return cnt
|
||||
taddr,tsize,tfoff=self.text
|
||||
for i in range(0,tsize,4):
|
||||
w,=struct.unpack_from("<I",self.d,self.base+tfoff+i)
|
||||
opc=w&0xFC000000
|
||||
if opc in (0x94000000,0x14000000):
|
||||
imm=w&0x3FFFFFF
|
||||
if imm&(1<<25): imm-=1<<26
|
||||
nm=stub_sym.get(taddr+i+imm*4)
|
||||
if nm: cnt[nm]+=1
|
||||
return cnt
|
||||
|
||||
def inject_headroom(self):
|
||||
"""注入一条 72 字节 LC_SEGMENT_64 所需余量:首节 foff - (header+sizeofcmds)。"""
|
||||
if self.first_sect_foff is None: return None
|
||||
return self.first_sect_foff-(32+self.sizeofcmds)
|
||||
|
||||
def iter_macho_files(app_dir):
|
||||
for root,_,files in os.walk(app_dir):
|
||||
for fn in files:
|
||||
p=os.path.join(root,fn)
|
||||
if os.path.islink(p): continue
|
||||
try:
|
||||
with open(p,"rb") as f: head=f.read(8)
|
||||
except Exception: continue
|
||||
if len(head)<4: continue
|
||||
m_le,=struct.unpack_from("<I",head,0)
|
||||
m_be,=struct.unpack_from(">I",head,0)
|
||||
if m_le==MH64 or m_be==FAT_MAGIC_LE:
|
||||
yield p
|
||||
|
||||
def scan_bundle(app_dir):
|
||||
rows=[] # (relpath, is_fat, total, cnt, headroom, cryptid)
|
||||
for p in sorted(iter_macho_files(app_dir)):
|
||||
data=open(p,"rb").read()
|
||||
slices=arm64_slices(data)
|
||||
is_fat = struct.unpack_from(">I",data,0)[0]==FAT_MAGIC_LE
|
||||
for (soff,ssize) in slices:
|
||||
s=Slice(data,soff)
|
||||
cnt=s.scan()
|
||||
rows.append((os.path.relpath(p,app_dir),is_fat,sum(cnt.values()),
|
||||
dict(cnt),s.inject_headroom(),s.cryptid))
|
||||
return rows
|
||||
|
||||
if __name__=="__main__":
|
||||
app=sys.argv[1]
|
||||
rows=scan_bundle(app)
|
||||
hit=[r for r in rows if r[2]>0]
|
||||
from collections import Counter
|
||||
grand=Counter()
|
||||
print(f"Mach-O 文件/切片总数: {len(rows)};命中(>0): {len(hit)}")
|
||||
print(f"{'命中':>5} {'余量':>6} {'enc':>3} 文件")
|
||||
for rel,fat,tot,cnt,room,crypt in sorted(rows,key=lambda r:-r[2]):
|
||||
if tot==0: continue
|
||||
for k,v in cnt.items(): grand[k]+=v
|
||||
tag=" FAT" if fat else ""
|
||||
print(f"{tot:>5} {str(room):>6} {crypt:>3} {rel}{tag}")
|
||||
print(f"\n命中总计: {sum(grand.values())}")
|
||||
for k,v in sorted(grand.items(),key=lambda x:-x[1]):
|
||||
print(f" {k:10} {v}")
|
||||
nz=[r for r in rows if r[2]>0 and (r[4] is None or r[4]<72)]
|
||||
if nz:
|
||||
print("\n注入余量不足(<72B)或未知的命中文件:")
|
||||
for rel,fat,tot,cnt,room,crypt in nz: print(f" room={room} {rel}")
|
||||
enc=[r for r in rows if r[2]>0 and r[5]!=0]
|
||||
if enc:
|
||||
print("\n加密(cryptid≠0)的命中文件:")
|
||||
for rel,fat,tot,cnt,room,crypt in enc: print(f" cryptid={crypt} {rel}")
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""构建独立诊断 App;只支持匹配的 wildcard 开发 profile,不安装、不更新开发者门户。"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def build(profile,identity,bundle,output):
|
||||
output=output.resolve()
|
||||
if output.exists():raise ValueError('输出目录必须不存在')
|
||||
r=subprocess.run(['openssl','smime','-inform','der','-verify','-noverify','-in',str(profile)],capture_output=True,check=True)
|
||||
data=plistlib.loads(r.stdout);ent=data['Entitlements'];team=data['TeamIdentifier'][0]
|
||||
prefix=data['ApplicationIdentifierPrefix'][0]
|
||||
if ent['application-identifier']!=prefix+'.*' or not ent.get('get-task-allow'):
|
||||
raise ValueError('需要通配开发 profile,避免复用现有业务 Bundle ID')
|
||||
if data['ExpirationDate']<=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None):raise ValueError('profile 已过期')
|
||||
if identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in data['DeveloperCertificates']}:
|
||||
raise ValueError('identity 不属于指定 profile')
|
||||
if not bundle.startswith('cn.touchv.iosguard.dispatchpilot.'):
|
||||
raise ValueError('诊断 Bundle ID 必须使用专用前缀')
|
||||
output.mkdir(parents=True)
|
||||
def command(args):
|
||||
r=subprocess.run(list(map(str,args)),capture_output=True,text=True)
|
||||
with (output/'build.log').open('a') as f:f.write(json.dumps(list(map(str,args)))+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
|
||||
if r.returncode:raise RuntimeError('命令失败,详见 build.log')
|
||||
source=output/'source-snapshot'
|
||||
inputs=[*list((ROOT/'defender').rglob('*.c')),*list((ROOT/'defender').rglob('*.h')),
|
||||
ROOT/'tests/fixtures/dispatch_host.c',ROOT/'tests/fixtures/dispatch_device.m',Path(__file__)]
|
||||
hashes={}
|
||||
for p in inputs:
|
||||
dest=source/p.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(p,dest)
|
||||
hashes[str(p.relative_to(ROOT))]=hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
app=output/'IGDispatchPilot.app';app.mkdir()
|
||||
info=dict(CFBundleExecutable='IGDispatchPilot',CFBundleIdentifier=bundle,CFBundleName='IGDispatchPilot',
|
||||
CFBundleDisplayName='IG Dispatch Test',CFBundlePackageType='APPL',CFBundleVersion='1',
|
||||
CFBundleShortVersionString='1.0',MinimumOSVersion='15.0',LSRequiresIPhoneOS=True,
|
||||
UIDeviceFamily=[1,2],UILaunchScreen={})
|
||||
(app/'Info.plist').write_bytes(plistlib.dumps(info))
|
||||
common=['xcrun','--sdk','iphoneos','clang','-arch','arm64','-miphoneos-version-min=15.0',
|
||||
'-O2','-DIG_DISPATCH_TESTING','-I',source/'defender','-I',source/'defender/include']
|
||||
command(common+['-Dmain=ig_dispatch_fixture_main','-c',source/'tests/fixtures/dispatch_host.c','-o',output/'fixture.o'])
|
||||
modules=['IGDefender.c','dispatch/IGDispatch.c','resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c','anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c','anti_debug/IGAntiDebug.c','syscall/IGSyscall.c']
|
||||
objects=[output/'fixture.o']
|
||||
for i,module in enumerate(modules):
|
||||
obj=output/f'{i}.o';command(common+['-c',source/'defender'/module,'-o',obj]);objects.append(obj)
|
||||
command(common+['-fobjc-arc',source/'tests/fixtures/dispatch_device.m',*objects,'-framework','UIKit','-framework','Foundation','-lobjc','-o',app/'IGDispatchPilot'])
|
||||
shutil.copy2(profile,app/'embedded.mobileprovision')
|
||||
allowed={k:v for k,v in ent.items() if k not in ('application-identifier','keychain-access-groups')}
|
||||
allowed.update({'application-identifier':prefix+'.'+bundle,'keychain-access-groups':[prefix+'.'+bundle]})
|
||||
(output/'entitlements.plist').write_bytes(plistlib.dumps(allowed))
|
||||
command(['codesign','--force','--sign',identity,'--entitlements',output/'entitlements.plist',app])
|
||||
command(['codesign','--verify','--strict','--verbose=2',app])
|
||||
(output/'manifest.json').write_text(json.dumps(dict(bundle_id=bundle,team=team,profile_name=data['Name'],
|
||||
source_hashes=hashes,signing='development',device_validation='not_run'),ensure_ascii=False,indent=2)+'\n')
|
||||
print(app)
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--profile',type=Path,required=True);p.add_argument('--identity',required=True)
|
||||
p.add_argument('--bundle-id',required=True);p.add_argument('--output',type=Path,required=True)
|
||||
a=p.parse_args();build(a.profile,a.identity,a.bundle_id,a.output)
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""构建真机 HOOK 正向验证诊断 App(step11)。
|
||||
|
||||
只支持匹配的 wildcard 开发 profile,专用 Bundle ID 前缀避免复用业务标识;
|
||||
构建后不安装、不更新开发者门户。诊断 App 附带空壳模拟 dylib(libfrida-sim.dylib),
|
||||
运行时拷贝到容器外构成注入证据。攻击构造只存在于诊断源码,业务库不含。
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BUNDLE_PREFIX = 'cn.touchv.iosguard.hookpilot.'
|
||||
|
||||
|
||||
def command(args, log: Path, label: str):
|
||||
r = subprocess.run(list(map(str, args)), capture_output=True, text=True)
|
||||
with log.open('a') as f:
|
||||
f.write(f'== {label} ==\n' + json.dumps(list(map(str, args))) + '\n'
|
||||
+ r.stdout + r.stderr + f'\nexit={r.returncode}\n')
|
||||
if r.returncode:
|
||||
raise RuntimeError(f'{label} 失败,详见 build.log')
|
||||
return r
|
||||
|
||||
|
||||
def build(profile, identity, bundle, output):
|
||||
output = output.resolve()
|
||||
if output.exists():
|
||||
raise ValueError('输出目录必须不存在')
|
||||
r = subprocess.run(['openssl', 'smime', '-inform', 'der', '-verify', '-noverify',
|
||||
'-in', str(profile)], capture_output=True, check=True)
|
||||
data = plistlib.loads(r.stdout)
|
||||
ent = data['Entitlements']
|
||||
team = data['TeamIdentifier'][0]
|
||||
prefix = data['ApplicationIdentifierPrefix'][0]
|
||||
if ent['application-identifier'] != prefix + '.*' or not ent.get('get-task-allow'):
|
||||
raise ValueError('需要通配开发 profile,避免复用现有业务 Bundle ID')
|
||||
if data['ExpirationDate'] <= datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None):
|
||||
raise ValueError('profile 已过期')
|
||||
if identity.upper() not in {hashlib.sha1(c).hexdigest().upper()
|
||||
for c in data['DeveloperCertificates']}:
|
||||
raise ValueError('identity 不属于指定 profile')
|
||||
if not bundle.startswith(BUNDLE_PREFIX):
|
||||
raise ValueError(f'诊断 Bundle ID 必须使用专用前缀 {BUNDLE_PREFIX}')
|
||||
output.mkdir(parents=True)
|
||||
blog = output / 'build.log'
|
||||
|
||||
source = output / 'source-snapshot'
|
||||
inputs = [*list((ROOT / 'defender').rglob('*.c')),
|
||||
*list((ROOT / 'defender').rglob('*.h')),
|
||||
ROOT / 'tests/fixtures/hook_device.m',
|
||||
ROOT / 'tests/fixtures/hook_sim_dylib.c',
|
||||
Path(__file__)]
|
||||
hashes = {}
|
||||
for p in inputs:
|
||||
dest = source / p.relative_to(ROOT)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(p, dest)
|
||||
hashes[str(p.relative_to(ROOT))] = hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
app = output / 'IGHookPilot.app'
|
||||
app.mkdir()
|
||||
info = dict(CFBundleExecutable='IGHookPilot', CFBundleIdentifier=bundle,
|
||||
CFBundleName='IGHookPilot', CFBundleDisplayName='IG Hook Test',
|
||||
CFBundlePackageType='APPL', CFBundleVersion='1',
|
||||
CFBundleShortVersionString='1.0', MinimumOSVersion='15.0',
|
||||
LSRequiresIPhoneOS=True, UIDeviceFamily=[1, 2], UILaunchScreen={})
|
||||
(app / 'Info.plist').write_bytes(plistlib.dumps(info))
|
||||
|
||||
common = ['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
|
||||
'-miphoneos-version-min=15.0', '-O2',
|
||||
'-I', source / 'defender', '-I', source / 'defender/include']
|
||||
modules = ['IGDefender.c', 'dispatch/IGDispatch.c', 'resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c', 'anti_debug/IGAntiDebug.c',
|
||||
'syscall/IGSyscall.c']
|
||||
objects = []
|
||||
for i, module in enumerate(modules):
|
||||
obj = output / f'{i}.o'
|
||||
command(common + ['-c', source / 'defender' / module, '-o', obj], blog, f'compile {module}')
|
||||
objects.append(obj)
|
||||
# 主诊断:export_dynamic 使 dlsym(RTLD_DEFAULT) 能解析主程序导出的蹦床符号。
|
||||
command(common + ['-fobjc-arc', source / 'tests/fixtures/hook_device.m', *objects,
|
||||
'-framework', 'UIKit', '-framework', 'Foundation',
|
||||
'-lobjc', '-Wl,-export_dynamic', '-o', app / 'IGHookPilot'],
|
||||
blog, 'link app')
|
||||
# 模拟注入 dylib:空壳、开发签名、随包作为资源分发。
|
||||
sim = app / 'libfrida-sim.dylib'
|
||||
command(common + ['-dynamiclib', source / 'tests/fixtures/hook_sim_dylib.c',
|
||||
'-o', sim], blog, 'build sim dylib')
|
||||
command(['codesign', '--force', '--sign', identity, sim], blog, 'sign sim dylib')
|
||||
|
||||
shutil.copy2(profile, app / 'embedded.mobileprovision')
|
||||
allowed = {k: v for k, v in ent.items()
|
||||
if k not in ('application-identifier', 'keychain-access-groups')}
|
||||
allowed.update({'application-identifier': prefix + '.' + bundle,
|
||||
'keychain-access-groups': [prefix + '.' + bundle]})
|
||||
(output / 'entitlements.plist').write_bytes(plistlib.dumps(allowed))
|
||||
command(['codesign', '--force', '--sign', identity,
|
||||
'--entitlements', output / 'entitlements.plist', app], blog, 'sign app')
|
||||
command(['codesign', '--verify', '--strict', '--verbose=2', app], blog, 'verify app')
|
||||
|
||||
(output / 'manifest.json').write_text(json.dumps(
|
||||
dict(bundle_id=bundle, team=team, profile_name=data['Name'],
|
||||
source_hashes=hashes, signing='development',
|
||||
device_validation='not_run'), ensure_ascii=False, indent=2) + '\n')
|
||||
print(app)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--profile', type=Path, required=True)
|
||||
p.add_argument('--identity', required=True)
|
||||
p.add_argument('--bundle-id', required=True)
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
build(a.profile, a.identity, a.bundle_id, a.output)
|
||||
@@ -0,0 +1,294 @@
|
||||
"""macho_guard 注入器:向未加密 thin arm64 可执行文件注入 __IGUARD 桥接段。
|
||||
|
||||
桥接函数与系统 stub 字节同构(adrp x16,GOT@page; ldr x16,[x16,off]; br x16),
|
||||
从同一 GOT 槽取址尾调用,但不登记进间接符号表——因此调用点改写为 bl IG_* 后,
|
||||
静态扫描器无法再把调用点标记为对应系统符号。
|
||||
|
||||
本阶段(step 1)只注入段并校验结构;调用点改写在 rewrite 子命令中进行。
|
||||
"""
|
||||
import struct, sys, subprocess, os
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from machox import Macho, LC_SEGMENT_64, LC_CODE_SIGNATURE
|
||||
|
||||
PAGE = 0x4000 # iOS arm64 16KB 页
|
||||
|
||||
# 报告命中的 12 个符号
|
||||
SYMBOLS = ["_fopen","_dlopen","_dlsym","_write","_read","_open",
|
||||
"_close","_exit","_fork","_syscall","_unlink","_getpid"]
|
||||
|
||||
def _text_mapping(m: Macho):
|
||||
"""返回 (__TEXT vmaddr, __TEXT fileoff),用于 vmaddr→fileoff 换算。
|
||||
主程序 __TEXT vmaddr=0x1_0000_0000/fileoff=0;framework/dylib vmaddr=0/fileoff=0。"""
|
||||
t=m.segs["__TEXT"]
|
||||
return t["vmaddr"], t["fileoff"]
|
||||
|
||||
def _first_section_fileoff(m: Macho):
|
||||
"""首个非零 section 文件偏移=load command 区可用上界(主程序 0x4000)。"""
|
||||
best=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd!=LC_SEGMENT_64: continue
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64); so=off+72
|
||||
for _ in range(nsects):
|
||||
foff,=struct.unpack_from("<I",m.d,so+48)
|
||||
if foff>0 and (best is None or foff<best): best=foff
|
||||
so+=80
|
||||
return best
|
||||
|
||||
def enc_adrp(rd, page_delta):
|
||||
"""adrp rd, #page_delta(已右移12的页差由调用方给未移的字节差)."""
|
||||
imm = page_delta >> 12
|
||||
immlo = imm & 3; immhi = (imm >> 2) & 0x7FFFF
|
||||
return 0x90000000 | (immlo<<29) | (immhi<<5) | rd
|
||||
|
||||
def enc_ldr_uimm(rt, rn, byte_off):
|
||||
"""ldr xt,[xn,#byte_off] 64位无符号偏移."""
|
||||
assert byte_off % 8 == 0
|
||||
imm12 = byte_off // 8
|
||||
return 0xF9400000 | (imm12<<10) | (rn<<5) | rt
|
||||
|
||||
def enc_br(rn):
|
||||
return 0xD61F0000 | (rn<<5)
|
||||
|
||||
def find_stub_got_slots(m: Macho):
|
||||
"""解析间接符号表,得到 {符号名: GOT槽vmaddr}(通过 stub 反解)。"""
|
||||
# 定位 __stubs、symtab、dysymtab
|
||||
import machox as X
|
||||
stubs=symtab=dysym=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd==LC_SEGMENT_64:
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64)
|
||||
so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=m.d[so:so+16].split(b"\0")[0].decode()
|
||||
if sn=="__stubs":
|
||||
addr,size=struct.unpack_from("<QQ",m.d,so+32)
|
||||
r1,r2=struct.unpack_from("<II",m.d,so+68)
|
||||
stubs=(addr,size,r1,r2)
|
||||
so+=80
|
||||
elif cmd==X.LC_SYMTAB: symtab=struct.unpack_from("<IIII",m.d,off+8)
|
||||
elif cmd==X.LC_DYSYMTAB: dysym=struct.unpack_from("<"+"I"*18,m.d,off+8)
|
||||
symoff,nsyms,stroff,strsize=symtab
|
||||
indoff=dysym[12]
|
||||
saddr,ssize,sr1,sr2=stubs
|
||||
tvm,tfo=_text_mapping(m) # vmaddr→fileoff: fo = va - tvm + tfo
|
||||
out={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",m.d,indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",m.d,symoff+idx*16)
|
||||
name=m.d[stroff+strx:m.d.index(b"\0",stroff+strx)].decode()
|
||||
if name in SYMBOLS:
|
||||
stub_va=saddr+i*sr2; fo=stub_va-tvm+tfo
|
||||
w0,w1=struct.unpack_from("<II",m.d,fo)
|
||||
immlo=(w0>>29)&3; immhi=(w0>>5)&0x7FFFF
|
||||
imm=(immhi<<2)|immlo
|
||||
if imm&(1<<20): imm-=1<<21
|
||||
page=(stub_va & ~0xFFF)+(imm<<12)
|
||||
imm12=(w1>>10)&0xFFF
|
||||
out[name]=page+imm12*8
|
||||
return out
|
||||
|
||||
def build_bridge(got_slots, ig_vmaddr):
|
||||
"""生成桥接段字节与 {符号:IG函数vmaddr}。每函数 3 指令 12 字节。"""
|
||||
code=bytearray(); addrs={}
|
||||
order=[s for s in SYMBOLS if s in got_slots]
|
||||
for i,sym in enumerate(order):
|
||||
fn_va=ig_vmaddr+i*12
|
||||
slot=got_slots[sym]
|
||||
page_delta=(slot & ~0xFFF)-(fn_va & ~0xFFF)
|
||||
off=slot & 0xFFF
|
||||
code+=struct.pack("<III",enc_adrp(16,page_delta),
|
||||
enc_ldr_uimm(16,16,off),enc_br(16))
|
||||
addrs[sym]=fn_va
|
||||
return bytes(code),addrs
|
||||
|
||||
def inject(path, out_path):
|
||||
if os.path.realpath(path)==os.path.realpath(out_path):
|
||||
raise ValueError("注入输出不得覆盖输入")
|
||||
m=Macho(Path(path).read_bytes())
|
||||
if "__IGUARD" in m.segs:
|
||||
raise ValueError("已存在 __IGUARD,拒绝重复注入")
|
||||
le=m.segs["__LINKEDIT"]
|
||||
ig_fileoff=le["fileoff"]; ig_vmaddr=le["vmaddr"]
|
||||
got=find_stub_got_slots(m)
|
||||
missing=[s for s in SYMBOLS if s not in got]
|
||||
bridge,addrs=build_bridge(got,ig_vmaddr)
|
||||
seg_filesize=PAGE # 一页足够
|
||||
hdr_region=_first_section_fileoff(m) # load command 区上界(主程序 0x4000,framework 各异)
|
||||
assert ig_fileoff>hdr_region, "插入点须在 header 区之后"
|
||||
# 1) 段数据:桥接 + 补零到一页
|
||||
segdata=bytearray(bridge)+b"\0"*(seg_filesize-len(bridge))
|
||||
# 2) 文件插入:在 __LINKEDIT fileoff 处插入一页
|
||||
d=m.d
|
||||
body=bytearray(d)
|
||||
body[ig_fileoff:ig_fileoff]=segdata # 插入
|
||||
# 3) 构造 __IGUARD 段命令(0 section, RX)
|
||||
segcmd=struct.pack("<II16sQQQQiiII",LC_SEGMENT_64,72,b"__IGUARD",
|
||||
ig_vmaddr,PAGE,ig_fileoff,seg_filesize,5,5,0,0)
|
||||
# 4) 在 __LINKEDIT 命令前插入该段命令,保持 header 区总长不变
|
||||
le_cmdoff=m.segs["__LINKEDIT"]["off"]
|
||||
# header 区(0..hdr_region)未受段数据插入影响(插入点 ig_fileoff>hdr_region),直接在其中插命令
|
||||
hdr=bytearray(body[:hdr_region])
|
||||
newhdr=hdr[:le_cmdoff]+segcmd+hdr[le_cmdoff:m.hdr_size+m.sizeofcmds]
|
||||
pad=hdr_region-len(newhdr)
|
||||
assert pad>=0, f"load command 空间不足: 需要 {len(newhdr)} > {hdr_region}"
|
||||
newhdr+=b"\0"*pad
|
||||
body[:hdr_region]=newhdr
|
||||
# 5) 修 header ncmds/sizeofcmds
|
||||
struct.pack_into("<II",body,16,m.ncmds+1,m.sizeofcmds+72)
|
||||
# 6) 修 __LINKEDIT 段命令:命令已右移 72 字节
|
||||
le_newoff=le_cmdoff+72
|
||||
struct.pack_into("<Q",body,le_newoff+24,le["vmaddr"]+PAGE) # vmaddr
|
||||
struct.pack_into("<Q",body,le_newoff+40,le["fileoff"]+PAGE) # fileoff
|
||||
# 7) 修所有指向 __LINKEDIT 的偏移 += PAGE(命令偏移也右移 72)
|
||||
for lab,fo,v in m.linkedit_pointers():
|
||||
struct.pack_into("<I",body,fo+(72 if fo>=le_cmdoff else 0),v+PAGE)
|
||||
Path(out_path).write_bytes(body)
|
||||
return addrs, missing, ig_vmaddr
|
||||
|
||||
def rewrite_callsites(path, out_path, bridge_addrs):
|
||||
"""把 __text 里所有 bl/b -> 命中符号 stub 的调用点改写为 bl/b -> IG_*。
|
||||
返回 {符号: 改写数}。调用点文件偏移在 ig 插入点之前,不受注入影响。"""
|
||||
m=Macho(Path(path).read_bytes())
|
||||
got=find_stub_got_slots(m) # 复用:也给出每个符号的 stub
|
||||
# 需要 stub_va: 重新建 符号->stub_va
|
||||
import machox as X
|
||||
stubs=symtab=dysym=text=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd==LC_SEGMENT_64:
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64); so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=m.d[so:so+16].split(b"\0")[0].decode()
|
||||
addr,size=struct.unpack_from("<QQ",m.d,so+32)
|
||||
foff,=struct.unpack_from("<I",m.d,so+48)
|
||||
r1,r2=struct.unpack_from("<II",m.d,so+68)
|
||||
if sn=="__stubs": stubs=(addr,size,foff,r1,r2)
|
||||
if sn=="__text": text=(addr,size,foff)
|
||||
so+=80
|
||||
elif cmd==X.LC_SYMTAB: symtab=struct.unpack_from("<IIII",m.d,off+8)
|
||||
elif cmd==X.LC_DYSYMTAB: dysym=struct.unpack_from("<"+"I"*18,m.d,off+8)
|
||||
symoff,nsyms,stroff,strsize=symtab; indoff=dysym[12]
|
||||
saddr,ssize,sfoff,sr1,sr2=stubs
|
||||
stub_sym={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",m.d,indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",m.d,symoff+idx*16)
|
||||
name=m.d[stroff+strx:m.d.index(b"\0",stroff+strx)].decode()
|
||||
if name in bridge_addrs: stub_sym[saddr+i*sr2]=name
|
||||
taddr,tsize,tfoff=text
|
||||
d=bytearray(Path(path).read_bytes())
|
||||
from collections import Counter
|
||||
cnt=Counter()
|
||||
for i in range(0,tsize,4):
|
||||
w,=struct.unpack_from("<I",d,tfoff+i)
|
||||
opc=w&0xFC000000
|
||||
if opc in (0x94000000,0x14000000):
|
||||
imm=w&0x3FFFFFF
|
||||
if imm&(1<<25): imm-=1<<26
|
||||
tgt=taddr+i+imm*4
|
||||
sym=stub_sym.get(tgt)
|
||||
if sym:
|
||||
site=taddr+i; dest=bridge_addrs[sym]; delta=dest-site
|
||||
assert -(1<<27)<=delta<(1<<27) and delta%4==0, f"越界 {site:#x}->{dest:#x}"
|
||||
neww=opc | ((delta>>2)&0x3FFFFFF)
|
||||
struct.pack_into("<I",d,tfoff+i,neww)
|
||||
cnt[sym]+=1
|
||||
Path(out_path).write_bytes(d)
|
||||
return dict(cnt)
|
||||
|
||||
def codesign_adhoc(path):
|
||||
r=subprocess.run(["codesign","-f","-s","-",path],capture_output=True,text=True)
|
||||
return r.returncode,r.stderr.strip()
|
||||
|
||||
# ---- 批处理:fat 感知的单文件处理 + 整包遍历 ----
|
||||
import tempfile, shutil
|
||||
|
||||
def harden_thin(src, dst):
|
||||
"""thin arm64:注入 __IGUARD + 改写调用点(不签名)。返回 (改写计数dict, 桥接数, missing)。"""
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
cnt=rewrite_callsites(dst,dst,addrs)
|
||||
return cnt, len(addrs), missing, igva
|
||||
|
||||
def _fat_arm64_arch(path):
|
||||
"""fat 容器里 arm64 切片的 lipo arch 名(arm64 或 arm64 的子型)。返回首个匹配。"""
|
||||
r=subprocess.run(["lipo","-archs",path],capture_output=True,text=True)
|
||||
archs=r.stdout.split()
|
||||
for a in archs:
|
||||
if a=="arm64": return a
|
||||
for a in archs:
|
||||
if a.startswith("arm64") and a!="arm64e": return a
|
||||
return None
|
||||
|
||||
def harden_macho_file(path, verbose=True):
|
||||
"""就地加固一个 Mach-O 文件(thin 或含单 arm64 切片的 fat)。签名在上层统一做。
|
||||
返回 (改写总数, 细目dict) 或 None(无命中/跳过)。"""
|
||||
data=Path(path).read_bytes()
|
||||
is_fat = struct.unpack_from(">I",data,0)[0]==0xCAFEBABE
|
||||
if is_fat:
|
||||
arch=_fat_arm64_arch(path)
|
||||
if not arch: return None
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
thin=os.path.join(td,"thin"); hard=os.path.join(td,"hard")
|
||||
subprocess.run(["lipo",path,"-thin",arch,"-output",thin],check=True)
|
||||
# 加密检查
|
||||
mm=Macho(Path(thin).read_bytes())
|
||||
cnt,nbr,missing,igva=harden_thin(thin,hard)
|
||||
if sum(cnt.values())==0: return None
|
||||
# 替换回 fat
|
||||
subprocess.run(["lipo",path,"-replace",arch,hard,"-output",path],check=True)
|
||||
return sum(cnt.values()), dict(cnt)
|
||||
else:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
hard=os.path.join(td,"hard")
|
||||
cnt,nbr,missing,igva=harden_thin(path,hard)
|
||||
if sum(cnt.values())==0: return None
|
||||
shutil.copymode(path,hard); shutil.move(hard,path)
|
||||
return sum(cnt.values()), dict(cnt)
|
||||
|
||||
def _sign_targets(app_dir):
|
||||
"""返回自底向上的签名目标:各 .framework/.app 包 + 主可执行文件。"""
|
||||
fws=[]
|
||||
fwdir=os.path.join(app_dir,"Frameworks")
|
||||
if os.path.isdir(fwdir):
|
||||
for n in sorted(os.listdir(fwdir)):
|
||||
p=os.path.join(fwdir,n)
|
||||
if p.endswith((".framework",".dylib")): fws.append(p)
|
||||
return fws
|
||||
|
||||
def harden_bundle(app_dir, resign=True):
|
||||
"""遍历 .app 内全部 Mach-O,逐个加固有命中者;可选统一重签。"""
|
||||
import batch
|
||||
results=[] # (relpath, total, cnt)
|
||||
for p in sorted(batch.iter_macho_files(app_dir)):
|
||||
r=harden_macho_file(p)
|
||||
if r:
|
||||
results.append((os.path.relpath(p,app_dir),r[0],r[1]))
|
||||
print(f" [改写] {r[0]:>4} 处 {os.path.relpath(p,app_dir)}")
|
||||
if resign:
|
||||
# 先签 Frameworks(含被改写的),再签主 app
|
||||
for fw in _sign_targets(app_dir):
|
||||
subprocess.run(["codesign","-f","-s","-",fw],capture_output=True)
|
||||
rc,err=codesign_adhoc(app_dir) # 签主 app bundle
|
||||
print(f" [重签] 主 app exit={rc} {err}")
|
||||
return results
|
||||
|
||||
if __name__=="__main__":
|
||||
mode=sys.argv[1]
|
||||
if mode=="inject":
|
||||
src,dst=sys.argv[2],sys.argv[3]
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
print(f"注入完成 -> {dst} __IGUARD={igva:#x} 桥接 {len(addrs)} 个")
|
||||
if missing: print("缺失:",missing)
|
||||
elif mode=="harden":
|
||||
src,dst=sys.argv[2],sys.argv[3]
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
print(f"[1/3] 注入 __IGUARD @{igva:#x},桥接 {len(addrs)} 个" + (f" 缺失={missing}" if missing else ""))
|
||||
cnt=rewrite_callsites(dst,dst,addrs)
|
||||
print(f"[2/3] 改写调用点 共 {sum(cnt.values())} 处: "+", ".join(f"{k}={v}" for k,v in sorted(cnt.items(),key=lambda x:-x[1])))
|
||||
rc,err=codesign_adhoc(dst)
|
||||
print(f"[3/3] ad-hoc 重签 exit={rc} {err}")
|
||||
elif mode=="harden-bundle":
|
||||
app=sys.argv[2]
|
||||
print(f"遍历加固 .app: {app}")
|
||||
res=harden_bundle(app, resign=(len(sys.argv)<4 or sys.argv[3]!="--no-sign"))
|
||||
print(f"共加固 {len(res)} 个 Mach-O,改写 {sum(t for _,t,_ in res)} 处")
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Mach-O thin arm64 结构分析/改写基础库(macho_guard)。
|
||||
只处理单切片 arm64、未加密(cryptid 0)可执行文件。"""
|
||||
import struct
|
||||
|
||||
LC_SEGMENT_64=0x19; LC_SYMTAB=0x2; LC_DYSYMTAB=0xb
|
||||
LC_DYLD_INFO=0x22; LC_DYLD_INFO_ONLY=0x80000022
|
||||
LC_FUNCTION_STARTS=0x26; LC_DATA_IN_CODE=0x29
|
||||
LC_CODE_SIGNATURE=0x1d; LC_DYLD_CHAINED_FIXUPS=0x80000034; LC_DYLD_EXPORTS_TRIE=0x80000033
|
||||
LC_SEGMENT_SPLIT_INFO=0x1e
|
||||
|
||||
class Macho:
|
||||
def __init__(self, data: bytearray):
|
||||
self.d=bytearray(data)
|
||||
if len(self.d) < 32:
|
||||
raise ValueError("Mach-O header 截断")
|
||||
magic,=struct.unpack_from("<I",self.d,0)
|
||||
if magic!=0xFEEDFACF:
|
||||
raise ValueError(f"需要 thin mach-o 64: {magic:#x}")
|
||||
(self.cputype,self.cpusub,self.filetype,self.ncmds,
|
||||
self.sizeofcmds,self.flags)=struct.unpack_from("<iiIIII",self.d,4)
|
||||
if self.cputype != 0x0100000c or (self.cpusub & 0xffffff) not in (0, 1):
|
||||
raise ValueError("仅支持 arm64/arm64v8,暂不支持 arm64e 或其它架构")
|
||||
if self.filetype not in (2, 6, 8):
|
||||
raise ValueError("仅支持已链接 executable/dylib/bundle")
|
||||
if self.sizeofcmds > len(self.d)-32 or self.ncmds > self.sizeofcmds//8:
|
||||
raise ValueError("load command 区截断")
|
||||
self.hdr_size=32
|
||||
self._parse()
|
||||
def _parse(self):
|
||||
self.cmds=[]; self.segs={}; off=self.hdr_size
|
||||
for _ in range(self.ncmds):
|
||||
if off+8 > self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("load command header 截断")
|
||||
cmd,cmdsize=struct.unpack_from("<II",self.d,off)
|
||||
if cmdsize < 8 or cmdsize % 8 or off+cmdsize > self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("非法 load command 长度")
|
||||
self.cmds.append((cmd,cmdsize,off))
|
||||
if cmd==LC_SEGMENT_64:
|
||||
if cmdsize < 72:
|
||||
raise ValueError("segment command 截断")
|
||||
segname=self.d[off+8:off+24].split(b"\0")[0].decode()
|
||||
vmaddr,vmsize,fileoff,filesize=struct.unpack_from("<QQQQ",self.d,off+24)
|
||||
maxprot,initprot,nsects,fl=struct.unpack_from("<iiII",self.d,off+56)
|
||||
if 72+nsects*80 != cmdsize or fileoff+filesize > len(self.d):
|
||||
raise ValueError("segment/section 越界")
|
||||
if segname in self.segs:
|
||||
raise ValueError("重复 segment")
|
||||
self.segs[segname]=dict(off=off,vmaddr=vmaddr,vmsize=vmsize,
|
||||
fileoff=fileoff,filesize=filesize,nsects=nsects,
|
||||
maxprot=maxprot,initprot=initprot)
|
||||
elif cmd==0x2c:
|
||||
if cmdsize < 24 or struct.unpack_from("<I",self.d,off+16)[0] != 0:
|
||||
raise ValueError("加密 Mach-O 不支持改写或扫描")
|
||||
off+=cmdsize
|
||||
if off != self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("load command 总长不一致")
|
||||
def linkedit_pointers(self):
|
||||
"""返回所有指向 __LINKEDIT 的 (命令名, 字段偏移绝对值, 当前值) 列表。"""
|
||||
res=[]
|
||||
for cmd,cmdsize,off in self.cmds:
|
||||
def add(fieldoff,label):
|
||||
v,=struct.unpack_from("<I",self.d,off+fieldoff)
|
||||
if v: res.append((label,off+fieldoff,v))
|
||||
if cmd in (LC_DYLD_INFO,LC_DYLD_INFO_ONLY):
|
||||
for i,lab in enumerate(["rebase","bind","weak_bind","lazy_bind","export"]):
|
||||
add(8+i*8,"dyld_info."+lab) # each has off(4)+size(4)
|
||||
elif cmd==LC_SYMTAB:
|
||||
add(8,"symtab.symoff"); add(16,"symtab.stroff")
|
||||
elif cmd==LC_DYSYMTAB:
|
||||
for fo,lab in [(32,"toc"),(40,"modtab"),(48,"extrefsym"),
|
||||
(56,"indirectsym"),(64,"extrel"),(72,"locrel")]:
|
||||
add(fo,"dysymtab."+lab)
|
||||
elif cmd in (LC_FUNCTION_STARTS,LC_DATA_IN_CODE,LC_CODE_SIGNATURE,
|
||||
LC_DYLD_CHAINED_FIXUPS,LC_DYLD_EXPORTS_TRIE,LC_SEGMENT_SPLIT_INFO):
|
||||
add(8,{LC_FUNCTION_STARTS:"function_starts",LC_DATA_IN_CODE:"data_in_code",
|
||||
LC_CODE_SIGNATURE:"code_signature",LC_DYLD_CHAINED_FIXUPS:"chained_fixups",
|
||||
LC_DYLD_EXPORTS_TRIE:"exports_trie",LC_SEGMENT_SPLIT_INFO:"split_info"}[cmd])
|
||||
return res
|
||||
|
||||
if __name__=="__main__":
|
||||
import sys
|
||||
m=Macho(bytearray(open(sys.argv[1],"rb").read()))
|
||||
print(f"cputype={m.cputype:#x} ncmds={m.ncmds} sizeofcmds={m.sizeofcmds}")
|
||||
print("padding for new LC =", min(s['fileoff'] for s in m.segs.values() if s['fileoff']>0 and s['nsects']>0) - (m.hdr_size+m.sizeofcmds))
|
||||
for name,s in m.segs.items():
|
||||
print(f" {name:14} vmaddr={s['vmaddr']:#012x} vmsize={s['vmsize']:#x} fileoff={s['fileoff']:#x} filesize={s['filesize']:#x} prot={s['initprot']}")
|
||||
print("--- __LINKEDIT 指针 ---")
|
||||
le=m.segs["__LINKEDIT"]
|
||||
for lab,fo,v in m.linkedit_pointers():
|
||||
inside = le['fileoff']<=v<le['fileoff']+le['filesize']
|
||||
print(f" {lab:24} @{fo:#x} = {v:#x} {'(in LINKEDIT)' if inside else '!!OUTSIDE'}")
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"rules": [
|
||||
{"caller": "-[ZZFileChannelOutput writeData:error:]", "symbol": "_write", "destination": "_IG_dispatch_write", "expected_count": 1},
|
||||
{"caller": "-[ZZFileChannelOutput close]", "symbol": "_close", "destination": "_IG_dispatch_close", "expected_count": 1}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""严格限定的 arm64 chained-import 试点;新文件输出,不改 SDK 机器码。"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
DEPENDENCY = '@rpath/IGArchiveGuard.framework/IGArchiveGuard'
|
||||
MAPPING = {'_fopen': '_ig_a0', '_fread': '_ig_a1', '_fwrite': '_ig_a2', '_fclose': '_ig_a3'}
|
||||
LOADS = (0xc, 0x80000018, 0x8000001f, 0x80000023, 0x20)
|
||||
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def rewrite(data, expected_sha256):
|
||||
require(hashlib.sha256(data).hexdigest() == expected_sha256, 'SDK 哈希不匹配,须重新审核版本')
|
||||
m = Macho(data)
|
||||
require(m.filetype == 6 and m.flags & 0x80, '需要 two-level MH_DYLIB')
|
||||
require(not any(c in (0x22, 0x80000022) for c, _, _ in m.cmds), '不支持混合传统 dyld 绑定')
|
||||
deps = []
|
||||
sections = []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
n = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= n < size, '依赖名偏移无效')
|
||||
end = m.d.index(0, off + n, off + size)
|
||||
deps.append(bytes(m.d[off + n:end]).decode())
|
||||
if cmd == LC_SEGMENT_64:
|
||||
count = struct.unpack_from('<I', m.d, off + 64)[0]
|
||||
for i in range(count):
|
||||
s = off + 72 + 80 * i
|
||||
length, fileoff = struct.unpack_from('<QI', m.d, s + 40)
|
||||
flags = struct.unpack_from('<I', m.d, s + 64)[0]
|
||||
if length and flags & 0xff not in (1, 0xc, 0x12):
|
||||
require(fileoff > 0 and fileoff + length <= len(data), 'section 文件范围无效')
|
||||
sections.append((fileoff, length))
|
||||
require(DEPENDENCY not in deps and len(deps) < 0x7e, '依赖冲突或 ordinal 超范围')
|
||||
old_ordinal = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
ordinal = len(deps) + 1
|
||||
commands = [o for c, _, o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS]
|
||||
require(len(commands) == 1, '需要唯一 chained fixups')
|
||||
fixoff, fixsize = struct.unpack_from('<II', m.d, commands[0] + 8)
|
||||
require(28 <= fixsize and fixoff + fixsize <= len(data), 'fixups 越界')
|
||||
version, starts, imports, symbols, count, fmt, compression = struct.unpack_from('<7I', m.d, fixoff)
|
||||
require(version == 0 and fmt == 1 and compression == 0, '仅支持无压缩 DYLD_CHAINED_IMPORT')
|
||||
require(28 <= starts < imports <= symbols < fixsize and imports + count * 4 <= symbols,
|
||||
'fixups 结构不支持')
|
||||
# 两套字符串池均先审查,拒绝别名字符串重叠和重复条目。
|
||||
changes = []
|
||||
allowed = set()
|
||||
def write(off, value):
|
||||
require(off >= 0 and off + len(value) <= len(m.d), '写入越界')
|
||||
m.d[off:off + len(value)] = value
|
||||
allowed.update(range(off, off + len(value)))
|
||||
def rename_pool(entries, pool_start, pool_end, kind):
|
||||
selected = {}
|
||||
intervals = []
|
||||
for entry, strx, ordinal_value in entries:
|
||||
start = pool_start + strx
|
||||
require(pool_start <= start < pool_end, '字符串索引越界')
|
||||
end = m.d.index(0, start, pool_end)
|
||||
name = bytes(m.d[start:end]).decode('utf-8')
|
||||
require(name not in MAPPING.values(), '已改写或目标冲突')
|
||||
intervals.append((start, end + 1, name))
|
||||
if name in MAPPING:
|
||||
require(name not in selected and ordinal_value == old_ordinal,
|
||||
'重复导入或提供方不匹配')
|
||||
selected[name] = (entry, start, end)
|
||||
require(set(selected) == set(MAPPING), '缺少预期四个文件函数')
|
||||
for name, (entry, start, end) in selected.items():
|
||||
require(all(other == name or finish <= start or begin >= end + 1
|
||||
for begin, finish, other in intervals), '共享后缀字符串,拒绝原地改名')
|
||||
encoded = MAPPING[name].encode()
|
||||
require(len(encoded) <= end - start, '新名称超出原字符串空间')
|
||||
write(start, encoded + bytes(end - start + 1 - len(encoded)))
|
||||
if kind == 'chained':
|
||||
word = struct.unpack_from('<I', m.d, entry)[0]
|
||||
require(not word & 0x100, '不支持 weak 目标导入')
|
||||
write(entry, struct.pack('<I', (word & ~255) | ordinal))
|
||||
else:
|
||||
desc = struct.unpack_from('<H', m.d, entry + 6)[0]
|
||||
require(not desc & 0x40, '不支持 weak 符号')
|
||||
write(entry + 6, struct.pack('<H', (desc & 255) | (ordinal << 8)))
|
||||
changes.append({'table': kind, 'source': name, 'destination': MAPPING[name],
|
||||
'old_ordinal': old_ordinal, 'ordinal': ordinal})
|
||||
entries = []
|
||||
for i in range(count):
|
||||
pos = fixoff + imports + 4 * i
|
||||
word = struct.unpack_from('<I', m.d, pos)[0]
|
||||
entries.append((pos, word >> 9, word & 255))
|
||||
rename_pool(entries, fixoff + symbols, fixoff + fixsize, 'chained')
|
||||
tabs = [o for c, _, o in m.cmds if c == LC_SYMTAB]
|
||||
require(len(tabs) == 1, '需要唯一符号表')
|
||||
symoff, nsyms, stroff, strsize = struct.unpack_from('<4I', m.d, tabs[0] + 8)
|
||||
require(symoff + nsyms * 16 <= len(data) and stroff + strsize <= len(data), '符号表越界')
|
||||
entries = []
|
||||
for i in range(nsyms):
|
||||
pos = symoff + i * 16
|
||||
strx, typ, sect, desc, value = struct.unpack_from('<IBBHQ', m.d, pos)
|
||||
entries.append((pos, strx, desc >> 8 if typ == 1 and sect == 0 and value == 0 else -1))
|
||||
rename_pool(entries, stroff, stroff + strsize, 'nlist')
|
||||
name = DEPENDENCY.encode() + b'\0'
|
||||
size = (24 + len(name) + 7) & ~7
|
||||
end = 32 + m.sizeofcmds
|
||||
require(end + size <= min(o for o, _ in sections), 'header padding 不足')
|
||||
require(not any(m.d[end:end + size]), 'header padding 非零')
|
||||
command = struct.pack('<6I', 0xc, size, 24, 0, 0x10000, 0x10000) + name
|
||||
write(end, command + bytes(size - len(command)))
|
||||
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + size))
|
||||
result = bytes(m.d)
|
||||
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), '非预期字节变化')
|
||||
require(all(data[o:o+n] == result[o:o+n] for o, n in sections), 'section 内容变化')
|
||||
Macho(result)
|
||||
return result, {'input_sha256': hashlib.sha256(data).hexdigest(),
|
||||
'output_sha256': hashlib.sha256(result).hexdigest(), 'dependency': DEPENDENCY,
|
||||
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': 4}
|
||||
|
||||
|
||||
def patch(source, destination, expected_sha256):
|
||||
source, destination = Path(source), Path(destination)
|
||||
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
|
||||
output, report = rewrite(source.read_bytes(), expected_sha256)
|
||||
destination.write_bytes(output)
|
||||
destination.chmod(source.stat().st_mode)
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source', type=Path)
|
||||
p.add_argument('destination', type=Path)
|
||||
p.add_argument('--expected-sha256', required=True)
|
||||
p.add_argument('--report', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256), indent=2) + '\n')
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""使用同次 Link Map 精确改写选定调用者;目标函数必须已编入同一 arm64 二进制。"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
|
||||
from machox import Macho, LC_SYMTAB
|
||||
from batch import Slice
|
||||
|
||||
|
||||
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def link_symbols(path):
|
||||
result={}
|
||||
# Apple Link Map 可包含来自 SDK 的非 UTF-8 字节;受保护规则仍使用 ASCII 精确名称。
|
||||
for line in Path(path).read_text(errors='replace').splitlines():
|
||||
if line.startswith('# Dead Stripped Symbols:'): break
|
||||
m=re.match(r'^(0x[0-9A-Fa-f]+)\s+(0x[0-9A-Fa-f]+)\s+\[\s*\d+\]\s+(.+)$',line)
|
||||
if m:
|
||||
name=m[3]
|
||||
value=(int(m[1],16),int(m[2],16))
|
||||
if name in result and result[name]!=value: result[name]=None
|
||||
else: result[name]=value
|
||||
return {k:v for k,v in result.items() if v is not None}
|
||||
|
||||
|
||||
def defined_symbols(m):
|
||||
result={}
|
||||
for cmd,_,off in m.cmds:
|
||||
if cmd!=LC_SYMTAB: continue
|
||||
symoff,nsyms,stroff,size=struct.unpack_from('<4I',m.d,off+8)
|
||||
for i in range(nsyms):
|
||||
idx,typ,sect,desc,value=struct.unpack_from('<IBBHQ',m.d,symoff+i*16)
|
||||
if typ & 0xe0 or (typ & 0x0e)!=0x0e or idx>=size: continue
|
||||
end=m.d.index(0,stroff+idx,stroff+size)
|
||||
name=m.d[stroff+idx:end].decode(errors='replace')
|
||||
if name in result and result[name]!=value: result[name]=None
|
||||
else: result[name]=value
|
||||
return {k:v for k,v in result.items() if v is not None}
|
||||
|
||||
|
||||
def target(word,site):
|
||||
imm=word & 0x3ffffff
|
||||
if imm & (1<<25): imm-=1<<26
|
||||
return site+imm*4
|
||||
|
||||
|
||||
def patch(src,dst,linkmap,profile):
|
||||
src,dst,linkmap=Path(src),Path(dst),Path(linkmap)
|
||||
if src.resolve()==dst.resolve() or dst.exists(): raise ValueError('输出必须为新文件')
|
||||
data=src.read_bytes();m=Macho(data);v=Slice(data,0)
|
||||
if not v.text or not v.stubs: raise ValueError('缺少 __text/__stubs')
|
||||
lm=link_symbols(linkmap);symbols=defined_symbols(m);stubs=v.stub_symbol_map()
|
||||
textva,textsize,textoff=v.text
|
||||
result=bytearray(data);changes=[]
|
||||
for rule in profile['rules']:
|
||||
caller,dest=rule['caller'],rule['destination']
|
||||
if caller not in lm or dest not in lm: raise ValueError(f'Link Map 缺少 {caller}/{dest}')
|
||||
start,size=lm[caller];destination,dsize=lm[dest]
|
||||
if symbols.get(caller)!=start or symbols.get(dest)!=destination:
|
||||
raise ValueError('Link Map 与二进制的定义符号不匹配,拒绝陈旧映射')
|
||||
if not textva<=start<start+size<=textva+textsize or not textva<=destination<destination+dsize<=textva+textsize:
|
||||
raise ValueError('调用者或目标不在 __text 范围')
|
||||
count=0
|
||||
for site in range(start,start+size,4):
|
||||
off=textoff+site-textva;word,=struct.unpack_from('<I',data,off)
|
||||
op=word & 0xfc000000
|
||||
if op not in (0x94000000,0x14000000) or stubs.get(target(word,site))!=rule['symbol']:continue
|
||||
delta=destination-site
|
||||
if delta%4 or not -(1<<27)<=delta<(1<<27):raise ValueError('分支目标超范围')
|
||||
new=op | ((delta>>2)&0x3ffffff)
|
||||
struct.pack_into('<I',result,off,new)
|
||||
changes.append(dict(caller=caller,symbol=rule['symbol'],site=hex(site),file_offset=off,
|
||||
original_word=hex(word),new_word=hex(new),destination=dest,
|
||||
destination_address=hex(destination),branch='bl' if op==0x94000000 else 'b'))
|
||||
count+=1
|
||||
if count!=rule['expected_count']:raise ValueError(f'{caller}: 期望 {rule["expected_count"]} 处,实际 {count}')
|
||||
if len({r['site'] for r in changes})!=len(changes):raise ValueError('规则重复改写同一调用点')
|
||||
allowed={r['file_offset']+i for r in changes for i in range(4)}
|
||||
if any(a!=b and i not in allowed for i,(a,b) in enumerate(zip(data,result))):raise ValueError('非目标字节变化')
|
||||
for r in changes:
|
||||
word,=struct.unpack_from('<I',result,r['file_offset'])
|
||||
if target(word,int(r['site'],16))!=int(r['destination_address'],16):raise ValueError('改写后目标不一致')
|
||||
dst.parent.mkdir(parents=True,exist_ok=True);dst.write_bytes(result);shutil.copymode(src,dst)
|
||||
return dict(input_sha256=sha(src),output_sha256=sha(dst),linkmap_sha256=sha(linkmap),
|
||||
total=len(changes),changes=changes,
|
||||
residual_tracking=['保留本地调度函数名,名称仍提示用途','目标函数名编码可由静态分析还原',
|
||||
'解析器仍依赖 dlsym/dladdr;不代表调用关系完全不可恢复',
|
||||
'其他调用者的系统导入/GOT 保留,本次只覆盖指定调用点'])
|
||||
|
||||
|
||||
def trace_calls(path,linkmap,roots,max_depth=8):
|
||||
"""有界跟踪本地 BL/B 与经典 GOT 桥接,保留未解析间接分支,不把未知当作安全。"""
|
||||
data=Path(path).read_bytes();m=Macho(data);v=Slice(data,0)
|
||||
functions=link_symbols(linkmap);stubs=v.stub_symbol_map()
|
||||
by_address={addr:(name,size) for name,(addr,size) in functions.items()}
|
||||
textva,textsize,textoff=v.text
|
||||
# 反解当前标准 stub/GOT 关系,检测仍沿用原 GOT 的旧桥接。
|
||||
from macho_guard import find_stub_got_slots
|
||||
slots={addr:name for name,addr in find_stub_got_slots(m).items()}
|
||||
rows=[]
|
||||
def bridge_symbol(address):
|
||||
for seg in m.segs.values():
|
||||
if seg['vmaddr']<=address<=seg['vmaddr']+seg['filesize']-12:
|
||||
off=seg['fileoff']+address-seg['vmaddr']
|
||||
w,w1,w2=struct.unpack_from('<III',data,off)
|
||||
if (w & 0x9f00001f)!=0x90000010 or (w1 & 0xffc003ff)!=0xf9400210 or w2!=0xd61f0200:return None
|
||||
imm=((w>>5)&0x7ffff)*4+((w>>29)&3)
|
||||
if imm & (1<<20):imm-=1<<21
|
||||
return slots.get((address & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8)
|
||||
return None
|
||||
def visit(addr,size,chain,seen,depth):
|
||||
if not textva<=addr<addr+size<=textva+textsize:return
|
||||
for site in range(addr,addr+size,4):
|
||||
off=textoff+site-textva;w,=struct.unpack_from('<I',data,off)
|
||||
op=w & 0xfc000000
|
||||
if op in (0x94000000,0x14000000):
|
||||
dest=target(w,site)
|
||||
if dest in stubs: rows.append(dict(chain=chain,symbol=stubs[dest],kind='direct_stub',site=hex(site)))
|
||||
elif bridge_symbol(dest):rows.append(dict(chain=chain+[f'bridge@{dest:#x}'],symbol=bridge_symbol(dest),kind='got_bridge',site=hex(site)))
|
||||
elif dest in by_address and dest not in seen:
|
||||
name,n=by_address[dest]
|
||||
if depth<max_depth:visit(dest,n,chain+[name],seen|{dest},depth+1)
|
||||
else:rows.append(dict(chain=chain+[name],kind='depth_limit'))
|
||||
elif not addr<=dest<addr+size and dest not in seen:
|
||||
rows.append(dict(chain=chain,kind='local_target_unresolved',site=hex(site),target=hex(dest)))
|
||||
if (w & 0xfffffc1f) in (0xd61f0000,0xd63f0000):
|
||||
rows.append(dict(chain=chain,kind='indirect_unresolved',site=hex(site)))
|
||||
if off+12<=len(data) and (w & 0x9f00001f)==0x90000010:
|
||||
w1,w2=struct.unpack_from('<II',data,off+4)
|
||||
if (w1 & 0xffc003ff)==0xf9400210 and w2==0xd61f0200:
|
||||
imm=((w>>5)&0x7ffff)*4+((w>>29)&3)
|
||||
if imm & (1<<20):imm-=1<<21
|
||||
slot=(site & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8
|
||||
if slot in slots:rows.append(dict(chain=chain,symbol=slots[slot],kind='got_bridge',site=hex(site)))
|
||||
for root in roots:
|
||||
addr,size=functions[root];visit(addr,size,[root],{addr},0)
|
||||
return rows
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source',type=Path);p.add_argument('output',type=Path)
|
||||
p.add_argument('--link-map',type=Path,required=True);p.add_argument('--profile',type=Path,required=True)
|
||||
p.add_argument('--report',type=Path,required=True)
|
||||
args=p.parse_args();profile=json.loads(args.profile.read_text())
|
||||
report=patch(args.source,args.output,args.link_map,profile)
|
||||
roots=[r['caller'] for r in profile['rules']]
|
||||
report['trace_before']=trace_calls(args.source,args.link_map,roots)
|
||||
report['trace_after']=trace_calls(args.output,args.link_map,roots)
|
||||
args.report.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(f'已改写 {report["total"]} 处;残余追踪路径详见报告')
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""安装并运行 step11 HOOK 正向验证诊断 App,收集/解析结果。
|
||||
|
||||
两相位:
|
||||
A 干净启动(受控攻击形态:GOT/蹦床/线程名/注入 dylib,见 hook_device.m)
|
||||
B 以 DYLD_INSERT_LIBRARIES 启动(真实 dyld 注入,使用相位 A 回显的 dylib 路径)
|
||||
结束即卸载诊断 App;全部证据与哈希写入输出目录(必须不存在)。
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
CASE_RE = re.compile(r'IG_HOOK_CASE (\S+) (PASS|FAIL)(?: detail=(.*))?$')
|
||||
SUITE_RE = re.compile(r'IG_HOOK_SUITE (PASS|FAIL)')
|
||||
TIMING_RE = re.compile(r'IG_HOOK_TIMING (.+)$')
|
||||
DYLIB_RE = re.compile(r'IG_HOOK_DYLIB_PATH (\S+)$')
|
||||
INSERT_RE = re.compile(r'IG_HOOK_INSERT_SUMMARY (.+)$')
|
||||
|
||||
|
||||
def run(args, log: Path, label: str, timeout: int = 240):
|
||||
r = subprocess.run(list(map(str, args)), capture_output=True, text=True, timeout=timeout)
|
||||
log.write_text(r.stdout + r.stderr)
|
||||
return r
|
||||
|
||||
|
||||
def parse_console(path: Path):
|
||||
cases, timing, insert_summary = [], None, None
|
||||
for line in path.read_text(errors='replace').splitlines():
|
||||
m = CASE_RE.search(line)
|
||||
if m:
|
||||
cases.append(dict(name=m.group(1), result=m.group(2), detail=m.group(3) or ''))
|
||||
continue
|
||||
m = TIMING_RE.search(line)
|
||||
if m:
|
||||
timing = m.group(1)
|
||||
continue
|
||||
m = INSERT_RE.search(line)
|
||||
if m:
|
||||
insert_summary = m.group(1)
|
||||
return cases, timing, insert_summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--device', required=True)
|
||||
p.add_argument('--app', type=Path, required=True)
|
||||
p.add_argument('--bundle-id', required=True)
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if out.exists():
|
||||
raise ValueError('输出目录必须不存在')
|
||||
out.mkdir(parents=True)
|
||||
base = ['xcrun', 'devicectl'] # --device 为子命令级参数,逐条拼接
|
||||
|
||||
r = run(base + ['device', 'info', 'details', '--device', a.device], out / 'device-details.log', 'device info')
|
||||
(out / 'device-details.json').write_text(r.stdout)
|
||||
|
||||
run(base + ['device', 'install', 'app', '--device', a.device, '--timeout', '60',
|
||||
'--json-output', out / 'install.json', a.app],
|
||||
out / 'install.log', 'install')
|
||||
|
||||
# 相位 A:干净启动,收集受控攻击形态结果与可注入 dylib 路径。
|
||||
run(base + ['device', 'process', 'launch', '--device', a.device, '--console', '--timeout', '90',
|
||||
'--json-output', out / 'launch-clean.json', a.bundle_id],
|
||||
out / 'console-clean.log', 'launch clean')
|
||||
cases, timing, _ = parse_console(out / 'console-clean.log')
|
||||
dylib = None
|
||||
for line in (out / 'console-clean.log').read_text(errors='replace').splitlines():
|
||||
m = DYLIB_RE.search(line)
|
||||
if m and m.group(1) != 'none':
|
||||
dylib = m.group(1)
|
||||
break
|
||||
|
||||
# 相位 B:DYLD_INSERT_LIBRARIES 真实注入(复用相位 A 验证可装载的路径)。
|
||||
if dylib:
|
||||
r = run(base + ['device', 'process', 'launch', '--device', a.device, '--console', '--timeout', '90',
|
||||
'-e', json.dumps({'DYLD_INSERT_LIBRARIES': dylib}),
|
||||
'--json-output', out / 'launch-insert.json', a.bundle_id],
|
||||
out / 'console-insert.log', 'launch insert')
|
||||
b_cases, _, insert_summary = parse_console(out / 'console-insert.log')
|
||||
cases += b_cases
|
||||
else:
|
||||
insert_summary = 'skipped:相位 A 未能装载模拟 dylib'
|
||||
(out / 'console-insert.log').write_text(insert_summary + '\n')
|
||||
|
||||
run(base + ['device', 'uninstall', 'app', '--device', a.device, '--timeout', '60',
|
||||
'--json-output', out / 'uninstall.json', a.bundle_id],
|
||||
out / 'uninstall.log', 'uninstall')
|
||||
|
||||
failed = [c for c in cases if c['result'] != 'PASS']
|
||||
verification = dict(
|
||||
device=a.device, bundle_id=a.bundle_id, app=str(a.app),
|
||||
cases=cases, case_count=len(cases),
|
||||
passed=len(cases) - len(failed), failed=len(failed),
|
||||
suite='PASS' if cases and not failed else 'FAIL',
|
||||
scan_timing=timing, insert_summary=insert_summary, injected_dylib=dylib,
|
||||
limitations=[
|
||||
'inline-hook 用例针对受控导出符号的真实字节,不是对系统函数的实际 patch',
|
||||
'特征名/线程名/端口可被攻击者改名规避,未命中不等于干净',
|
||||
'本诊断为独立进程,不等同于业务 App 内的完整验收',
|
||||
])
|
||||
(out / 'device-verification.json').write_text(
|
||||
json.dumps(verification, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
hashes = {}
|
||||
for f in sorted(out.rglob('*')):
|
||||
if f.is_file() and f.name != 'evidence-hashes.json':
|
||||
hashes[str(f.relative_to(out))] = hashlib.sha256(f.read_bytes()).hexdigest()
|
||||
(out / 'evidence-hashes.json').write_text(
|
||||
json.dumps(hashes, ensure_ascii=False, indent=2) + '\n')
|
||||
print(json.dumps({k: verification[k] for k in
|
||||
('suite', 'passed', 'failed', 'case_count', 'scan_timing')},
|
||||
ensure_ascii=False))
|
||||
raise SystemExit(0 if verification['suite'] == 'PASS' else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,302 @@
|
||||
#!/usr/bin/env python3
|
||||
"""同一 IPA 加固前后证据归档。仅作本地规则/结构验证,不代表厂商复测或真机验收。"""
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import plistlib
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import batch
|
||||
from machox import Macho
|
||||
import macho_guard
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def digest(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, 'rb') as f:
|
||||
for block in iter(lambda: f.read(1024*1024), b''):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def save(path, data):
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n')
|
||||
|
||||
|
||||
def validate_zip(path):
|
||||
"""ditto 解包前检查路径与符号链接,避免归档逃逸;拒绝重复条目。"""
|
||||
with zipfile.ZipFile(path) as z:
|
||||
seen = set()
|
||||
for info in z.infolist():
|
||||
p = Path(info.filename)
|
||||
if p.is_absolute() or '..' in p.parts or info.filename in seen:
|
||||
raise ValueError(f'不安全或重复的 ZIP 路径: {info.filename}')
|
||||
seen.add(info.filename)
|
||||
if stat.S_ISLNK(info.external_attr >> 16):
|
||||
target = z.read(info).decode()
|
||||
resolved = os.path.normpath(str(p.parent / target))
|
||||
if Path(target).is_absolute() or resolved == '..' or resolved.startswith('../'):
|
||||
raise ValueError(f'ZIP 符号链接逃逸: {p}')
|
||||
bad = z.testzip()
|
||||
if bad:
|
||||
raise ValueError(f'ZIP CRC 失败: {bad}')
|
||||
|
||||
|
||||
def inventory(folder):
|
||||
result = []
|
||||
for path in sorted(folder.rglob('*')):
|
||||
rel = str(path.relative_to(folder))
|
||||
if path.is_symlink():
|
||||
result.append(dict(path=rel, symlink=os.readlink(path)))
|
||||
elif path.is_file():
|
||||
result.append(dict(path=rel, size=path.stat().st_size, sha256=digest(path)))
|
||||
return result
|
||||
|
||||
|
||||
def inspect_binary(path):
|
||||
data = path.read_bytes()
|
||||
slices = batch.arm64_slices(data)
|
||||
if not slices:
|
||||
raise ValueError(f'发现未覆盖的 Mach-O 架构: {path}')
|
||||
if data[:4] == b'\xca\xfe\xba\xbe' and struct.unpack_from('>I',data,4)[0] != len(slices):
|
||||
raise ValueError(f'fat 包含未覆盖的架构,拒绝按全覆盖验收: {path}')
|
||||
results, sites = [], []
|
||||
for base, size in slices:
|
||||
if base+size > len(data):
|
||||
raise ValueError(f'fat 切片越界: {path}')
|
||||
m = Macho(data[base:base+size])
|
||||
le = m.segs['__LINKEDIT']
|
||||
for label, _, offset in m.linkedit_pointers():
|
||||
if not le['fileoff'] <= offset < le['fileoff']+le['filesize']:
|
||||
raise ValueError(f'{path}: {label} 不在 __LINKEDIT')
|
||||
view = batch.Slice(data[base:base+size], 0)
|
||||
uuid = None
|
||||
for cmd, cmdsize, off in m.cmds:
|
||||
if cmd == 0x1b:
|
||||
import uuid as uuid_module
|
||||
uuid = str(uuid_module.UUID(bytes=bytes(m.d[off+8:off+24])))
|
||||
cnt = view.scan()
|
||||
results.append(dict(offset=base, size=size, uuid=uuid,
|
||||
cputype=m.cputype, cpusubtype=m.cpusub,
|
||||
cryptid=view.cryptid, counts=dict(cnt), total=sum(cnt.values()),
|
||||
header_headroom=view.inject_headroom(),
|
||||
segments=m.segs))
|
||||
if view.text:
|
||||
va, length, fileoff = view.text
|
||||
stubs = view.stub_symbol_map()
|
||||
for i in range(0, length, 4):
|
||||
w, = struct.unpack_from('<I', m.d, fileoff+i)
|
||||
op = w & 0xfc000000
|
||||
if op not in (0x94000000, 0x14000000):
|
||||
continue
|
||||
imm = w & 0x3ffffff
|
||||
if imm & (1 << 25):
|
||||
imm -= 1 << 26
|
||||
target = va+i+imm*4
|
||||
if target in stubs:
|
||||
sites.append(dict(slice_offset=base, site=hex(va+i),
|
||||
target=hex(target), branch='bl' if op==0x94000000 else 'b',
|
||||
symbol=stubs[target]))
|
||||
return dict(sha256=digest(path), size=len(data), slices=results), sites
|
||||
|
||||
|
||||
def verify_rewrite(original, guarded):
|
||||
"""逐条检查 __text 差异,并反解桥接目的 GOT;不能只以复扫零命中验收。"""
|
||||
before, after = original.read_bytes(), guarded.read_bytes()
|
||||
old_slices, new_slices = batch.arm64_slices(before), batch.arm64_slices(after)
|
||||
if len(old_slices) != len(new_slices):
|
||||
raise ValueError('改写前后切片数量变化')
|
||||
changes = 0
|
||||
for (off, size), (noff, nsize) in zip(old_slices,new_slices):
|
||||
old, new = before[off:off+size], after[noff:noff+nsize]
|
||||
ov, nv = batch.Slice(old,0), batch.Slice(new,0)
|
||||
om, nm = Macho(old), Macho(new)
|
||||
if ov.text != nv.text:
|
||||
raise ValueError('__text 映射发生变化')
|
||||
stubs = ov.stub_symbol_map()
|
||||
if not ov.text:
|
||||
continue
|
||||
slots = macho_guard.find_stub_got_slots(om) if stubs else {}
|
||||
va, length, fileoff = ov.text
|
||||
ig = nm.segs.get('__IGUARD')
|
||||
for i in range(0,length,4):
|
||||
a, = struct.unpack_from('<I',old,fileoff+i)
|
||||
b, = struct.unpack_from('<I',new,fileoff+i)
|
||||
op = a & 0xfc000000
|
||||
def branch_target(w):
|
||||
imm = w & 0x3ffffff
|
||||
if imm & (1<<25): imm -= 1<<26
|
||||
return va+i+imm*4
|
||||
sym = stubs.get(branch_target(a)) if op in (0x94000000,0x14000000) else None
|
||||
if not sym:
|
||||
if a != b:
|
||||
raise ValueError('非目标指令发生变化')
|
||||
continue
|
||||
if (b & 0xfc000000) != op or not ig:
|
||||
raise ValueError('分支类型变化或缺少桥接段')
|
||||
target = branch_target(b)
|
||||
if not ig['vmaddr'] <= target <= ig['vmaddr']+ig['filesize']-12:
|
||||
raise ValueError('调用目标未落入 __IGUARD')
|
||||
boff = ig['fileoff']+target-ig['vmaddr']
|
||||
w0,w1,w2 = struct.unpack_from('<III',new,boff)
|
||||
if w0 & 0x9f00001f != 0x90000010 or w1 & 0xffc003ff != 0xf9400210 or w2 != 0xd61f0200:
|
||||
raise ValueError('桥接不是 ADRP/LDR/BR x16')
|
||||
imm = ((w0>>5)&0x7ffff)*4+((w0>>29)&3)
|
||||
if imm & (1<<20): imm -= 1<<21
|
||||
got = (target & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8
|
||||
if got != slots[sym]:
|
||||
raise ValueError(f'桥接 GOT 目标错误: {sym}')
|
||||
changes += 1
|
||||
return changes
|
||||
|
||||
|
||||
def scan(app, output, label):
|
||||
binaries, sites = {}, []
|
||||
for path in sorted(map(Path, batch.iter_macho_files(str(app)))):
|
||||
rel = str(path.relative_to(app))
|
||||
binaries[rel], found = inspect_binary(path)
|
||||
sites.extend(dict(path=rel, **site) for site in found)
|
||||
if not binaries:
|
||||
raise ValueError('未发现支持的 Mach-O,拒绝将空扫描判为通过')
|
||||
save(output / f'{label}-binaries.json', binaries)
|
||||
with (output / f'{label}-callsites.csv').open('w') as f:
|
||||
w = csv.DictWriter(f, fieldnames=['path','slice_offset','site','target','branch','symbol'])
|
||||
w.writeheader()
|
||||
w.writerows(sites)
|
||||
return binaries, len(sites)
|
||||
|
||||
|
||||
def run(ipa, output):
|
||||
ipa, output = ipa.resolve(), output.resolve()
|
||||
if output.exists():
|
||||
raise ValueError('输出目录必须不存在,避免覆盖既有证据')
|
||||
validate_zip(ipa)
|
||||
output.mkdir(parents=True)
|
||||
manifest = dict(schema_version=1, status='running',
|
||||
created_utc=datetime.now(timezone.utc).isoformat(),
|
||||
scope='自研直接分支规则与静态结构;不代表 V4.6.6/真机验收',
|
||||
vendor_retest='not_run', device_regression='not_run',
|
||||
signing='ad-hoc,仅用于本地静态验证',
|
||||
input=dict(path=str(ipa), size=ipa.stat().st_size, sha256=digest(ipa)),
|
||||
environment=dict(platform=platform.platform(), python=sys.version),
|
||||
tools={str(p.relative_to(ROOT)):digest(p) for p in
|
||||
sorted((ROOT/'tools/macho_guard').glob('*.py'))})
|
||||
def command(args):
|
||||
p = subprocess.run(list(map(str,args)), capture_output=True, text=True)
|
||||
with (output/'commands.log').open('a') as log:
|
||||
log.write(json.dumps(list(map(str,args)), ensure_ascii=False)+'\n')
|
||||
log.write(p.stdout+p.stderr+f'\nexit={p.returncode}\n')
|
||||
if p.returncode:
|
||||
raise RuntimeError(f'命令失败({p.returncode}): {args[0]},详见 commands.log')
|
||||
return p.stdout.strip()
|
||||
try:
|
||||
manifest['environment']['xcode'] = command(['xcodebuild','-version'])
|
||||
manifest['environment']['clang'] = command(['xcrun','clang','--version'])
|
||||
# 仓库未提交的实现也随证据冻结,避免只有 HEAD 无法还原当时源码。
|
||||
snapshot = output/'source-snapshot'
|
||||
for folder in ('tools/macho_guard','tools/static_sdk_redirect','tests','defender'):
|
||||
for p in sorted((ROOT/folder).rglob('*')):
|
||||
if p.is_file() and '__pycache__' not in p.parts and p.suffix in ('.py','.c','.h','.json'):
|
||||
dest = snapshot/p.relative_to(ROOT)
|
||||
dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
shutil.copy2(p,dest)
|
||||
save(output/'source-files.json', inventory(snapshot))
|
||||
# 对冻结源码运行全部测试;日志永久保存,失败中止。
|
||||
command([sys.executable,'-m','unittest','discover','-s',snapshot/'tests','-v'])
|
||||
manifest['automated_tests'] = 'passed; 详见 commands.log'
|
||||
baseline = output/'baseline'
|
||||
baseline.mkdir()
|
||||
shutil.copy2(ipa, baseline/'input.ipa')
|
||||
if digest(baseline/'input.ipa') != manifest['input']['sha256']:
|
||||
raise ValueError('输入在复制过程中发生变化')
|
||||
command(['ditto','-x','-k',baseline/'input.ipa',baseline/'unpacked'])
|
||||
apps = list((baseline/'unpacked/Payload').glob('*.app'))
|
||||
if len(apps) != 1:
|
||||
raise ValueError('需要恰好一个顶层 .app')
|
||||
app = apps[0]
|
||||
with (app/'Info.plist').open('rb') as f:
|
||||
info = plistlib.load(f)
|
||||
manifest['app'] = {k:info.get(k) for k in
|
||||
('CFBundleIdentifier','CFBundleShortVersionString','CFBundleVersion','CFBundleExecutable')}
|
||||
manifest['original_report'] = dict(version='2.197.2', bundle_id='com.ecnup.azZVz02',
|
||||
exact_report_binary_available=False,
|
||||
note='当前输入单独建基线,不视为原漏洞报告二进制')
|
||||
before, before_total = scan(app, output, 'before')
|
||||
save(output/'before-files.json', inventory(baseline/'unpacked'))
|
||||
guarded = output/'guarded'
|
||||
guarded.mkdir()
|
||||
command(['ditto', baseline/'unpacked', guarded/'unpacked'])
|
||||
guarded_app = guarded/'unpacked/Payload'/app.name
|
||||
rewrites = []
|
||||
for rel, binary in before.items():
|
||||
hits = sum(s['total'] for s in binary['slices'])
|
||||
if not hits:
|
||||
continue
|
||||
for s in binary['slices']:
|
||||
if s['header_headroom'] is None or s['header_headroom'] < 72:
|
||||
raise ValueError(f'注入余量不足: {rel}')
|
||||
result = macho_guard.harden_macho_file(str(guarded_app/rel))
|
||||
if not result or result[0] != hits:
|
||||
raise ValueError(f'改写计数不一致: {rel}')
|
||||
rewrites.append(dict(path=rel, total=result[0], counts=result[1]))
|
||||
save(output/'rewrites.json', rewrites)
|
||||
# 对所有嵌套 bundle 和裸 dylib 从内向外签名;每次失败均中止。
|
||||
targets = {p for p in guarded_app.rglob('*') if
|
||||
not p.is_symlink() and (p.suffix in ('.framework','.app','.appex','.xpc','.dylib'))}
|
||||
targets.add(guarded_app)
|
||||
for target in sorted(targets, key=lambda p:(-len(p.parts),str(p))):
|
||||
command(['codesign','--force','--sign','-',target])
|
||||
for target in sorted(targets):
|
||||
command(['codesign','--verify','--strict','--verbose=2',target])
|
||||
after, after_total = scan(guarded_app, output, 'after')
|
||||
if before.keys() != after.keys() or after_total != 0:
|
||||
raise ValueError('Mach-O 清单变化或改写后仍有命中')
|
||||
for rel in before:
|
||||
command(['xcrun','otool','-l',guarded_app/rel])
|
||||
expected = sum(s['total'] for s in before[rel]['slices'])
|
||||
if verify_rewrite(app/rel,guarded_app/rel) != expected:
|
||||
raise ValueError(f'逐指令改写校验数量不一致: {rel}')
|
||||
for a,b in zip(before[rel]['slices'],after[rel]['slices']):
|
||||
if a['uuid'] != b['uuid']:
|
||||
raise ValueError(f'UUID 意外变化: {rel}')
|
||||
save(output/'after-files.json', inventory(guarded/'unpacked'))
|
||||
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded/'unpacked/Payload',guarded/'guarded.ipa'])
|
||||
command(['ditto','-x','-k',guarded/'guarded.ipa',output/'repacked-check'])
|
||||
repacked, total = scan(output/'repacked-check/Payload'/app.name, output, 'repacked')
|
||||
if repacked != after or total:
|
||||
raise ValueError('重新打包解包后扫描/二进制哈希不一致')
|
||||
if digest(ipa) != manifest['input']['sha256']:
|
||||
raise ValueError('原始输入哈希发生变化')
|
||||
manifest.update(status='passed_local_checks', before_total=before_total, after_total=after_total,
|
||||
macho_files=len(before), changed_macho_files=len(rewrites),
|
||||
instruction_and_bridge_validation='passed',
|
||||
guarded_ipa=dict(path='guarded/guarded.ipa',sha256=digest(guarded/'guarded.ipa')))
|
||||
# 重解包副本验证后可删除,前后两个完整 Payload 与 IPA 留存。
|
||||
shutil.rmtree(output/'repacked-check')
|
||||
except Exception as exc:
|
||||
manifest.update(status='failed', error=str(exc))
|
||||
raise
|
||||
finally:
|
||||
save(output/'manifest.json', manifest)
|
||||
save(output/'evidence-hashes.json', inventory(output))
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('ipa', type=Path)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
run(args.ipa, args.output)
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ZipZap 两函数的构建后转接、增强追踪、签名和证据固化;无真机/厂商通过声明。"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from redirect_to_runtime import patch,trace_calls,sha
|
||||
from verify_baseline import inventory,save,scan
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def run(app,linkmap,build_log,dispatch_object,output):
|
||||
app,linkmap,output=app.resolve(),linkmap.resolve(),output.resolve()
|
||||
if output.exists():raise ValueError('输出目录必须不存在')
|
||||
with (app/'Info.plist').open('rb') as f:info=plistlib.load(f)
|
||||
output.mkdir(parents=True)
|
||||
result=dict(status='running',app={k:info.get(k) for k in
|
||||
('CFBundleIdentifier','CFBundleShortVersionString','CFBundleVersion','CFBundleExecutable')},
|
||||
device_regression='not_run',vendor_retest='not_run',signing='ad-hoc, static checks only')
|
||||
def command(args):
|
||||
r=subprocess.run(list(map(str,args)),capture_output=True,text=True)
|
||||
with (output/'commands.log').open('a') as log:
|
||||
log.write(json.dumps(list(map(str,args)),ensure_ascii=False)+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
|
||||
if r.returncode:raise RuntimeError(f'{args[0]} 失败,详见 commands.log')
|
||||
return r.stdout
|
||||
try:
|
||||
# 冻结本次执行所需源码及 App 策略测试输入,保留原工程已有工作。
|
||||
snapshot=output/'source-snapshot'
|
||||
for folder in ('defender','tools/macho_guard','tools/static_sdk_redirect','tests'):
|
||||
for src in (ROOT/folder).rglob('*'):
|
||||
if src.is_file() and src.suffix in ('.c','.h','.m','.py','.json') and '__pycache__' not in src.parts:
|
||||
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
|
||||
sources=[ROOT/'readoor-test/readoor.xcodeproj/project.pbxproj',
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security').rglob('*.swift')),
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security/IGDefender').rglob('*.c')),
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security/IGDefender').rglob('*.h')),
|
||||
ROOT/'readoor-test/scripts/add_igdefender.rb',
|
||||
ROOT/'readoor-test/readoor/3.0/Features/PurchaseOrOrder/Controllers/RDOrderViewController.swift']
|
||||
for src in sources:
|
||||
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
|
||||
save(output/'source-files.json',inventory(snapshot))
|
||||
command([sys.executable,'-m','unittest','discover','-s',snapshot/'tests','-v'])
|
||||
result['tests']='passed (详见 commands.log)'
|
||||
result['environment']=command(['xcodebuild','-version']).strip()
|
||||
shutil.copy2(build_log,output/'build-release.log');shutil.copy2(linkmap,output/'link.map')
|
||||
shutil.copy2(dispatch_object,output/'IGDispatch.o')
|
||||
imports=command(['xcrun','nm','-u',output/'IGDispatch.o'])
|
||||
(output/'IGDispatch-imports.txt').write_text(imports)
|
||||
if {'_write','_close','_memcmp'} & set(imports.split()):
|
||||
raise ValueError('调度对象仍直接导入受保护目标或前缀比较函数')
|
||||
baseline=output/'baseline/Payload'/app.name
|
||||
guarded=output/'guarded/Payload'/app.name
|
||||
command(['ditto',app,baseline]);command(['ditto',app,guarded])
|
||||
executable=info['CFBundleExecutable'];original=baseline/executable;binary=guarded/executable
|
||||
profile=json.loads((ROOT/'tools/macho_guard/profiles/zipzap.json').read_text())
|
||||
roots=[r['caller'] for r in profile['rules']]
|
||||
new_binary=output/'patched-binary'
|
||||
report=patch(original,new_binary,linkmap,profile)
|
||||
report['trace_before']=trace_calls(original,linkmap,roots)
|
||||
report['trace_after']=trace_calls(new_binary,linkmap,roots)
|
||||
# 新调度可以间接调用,不能仍沿直接桩或经典 GOT 桥接到原 write/close。
|
||||
remaining=[r for r in report['trace_after'] if r.get('symbol') in ('_write','_close')]
|
||||
if remaining:raise ValueError('试点路径仍存在可恢复的原目标直接/GOT 桥接')
|
||||
if not any(r['kind']=='indirect_unresolved' for r in report['trace_after']):
|
||||
raise ValueError('未观察到预期的运行时间接调用')
|
||||
shutil.move(new_binary,binary)
|
||||
before,bt=scan(baseline,output,'before')
|
||||
targets={p for p in guarded.rglob('*') if not p.is_symlink() and p.suffix in ('.framework','.app','.appex','.xpc','.dylib')}
|
||||
targets.add(guarded)
|
||||
for p in sorted(targets,key=lambda p:(-len(p.parts),str(p))):command(['codesign','--force','--sign','-',p])
|
||||
for p in sorted(targets):command(['codesign','--verify','--strict','--verbose=2',p])
|
||||
after,at=scan(guarded,output,'after')
|
||||
if bt-at!=report['total']:raise ValueError('整包直接调用减少数与试点不一致')
|
||||
if before.keys()!=after.keys():raise ValueError('二进制清单变化')
|
||||
if [s['uuid'] for s in before[executable]['slices']]!=[s['uuid'] for s in after[executable]['slices']]:
|
||||
raise ValueError('UUID 变化')
|
||||
command(['xcrun','otool','-l',binary])
|
||||
for symbol in ('IG_dispatch_write','IG_dispatch_close','ig_resolve_verified'):
|
||||
text=command(['xcrun','llvm-objdump','--no-show-raw-insn',
|
||||
'--disassemble-symbols=_'+symbol,binary])
|
||||
(output/(symbol+'.asm')).write_text(text)
|
||||
symbols=command(['xcrun','nm',binary])
|
||||
if 'ig_dispatch_test_' in symbols:raise ValueError('发布产物残留测试接口')
|
||||
report['signed_output_sha256']=sha(binary)
|
||||
save(output/'redirect-report.json',report)
|
||||
save(output/'before-files.json',inventory(baseline.parent.parent))
|
||||
save(output/'after-files.json',inventory(guarded.parent.parent))
|
||||
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded.parent,output/'guarded.ipa'])
|
||||
command(['ditto','-x','-k',output/'guarded.ipa',output/'repack'])
|
||||
repacked,total=scan(output/'repack/Payload'/app.name,output,'repacked')
|
||||
if repacked!=after or total!=at:raise ValueError('重打包验证失败')
|
||||
shutil.rmtree(output/'repack')
|
||||
if sha(app/executable)!=report['input_sha256']:raise ValueError('输入构建产物意外变化')
|
||||
result.update(status='passed_local_checks',total_redirected=report['total'],before_total=bt,
|
||||
after_total=at,input_sha256=report['input_sha256'],
|
||||
output_sha256=report['signed_output_sha256'],ipa_sha256=sha(output/'guarded.ipa'),
|
||||
static_tracking_limitations=report['residual_tracking'])
|
||||
except Exception as exc:
|
||||
result.update(status='failed',error=str(exc));raise
|
||||
finally:save(output/'manifest.json',result)
|
||||
save(output/'evidence-hashes.json',inventory(output))
|
||||
print(json.dumps(result,ensure_ascii=False,indent=2))
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--app',type=Path,required=True);p.add_argument('--link-map',type=Path,required=True)
|
||||
p.add_argument('--build-log',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
|
||||
p.add_argument('--dispatch-object',type=Path,required=True)
|
||||
a=p.parse_args();run(a.app,a.link_map,a.build_log,a.dispatch_object,a.output)
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"_read": "_IG_read",
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"_fopen": "_IG_fopen",
|
||||
"_fclose": "_IG_fclose",
|
||||
"_fread": "_IG_fread",
|
||||
"_fwrite": "_IG_fwrite"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""兼容原 fopen PoC 命令;通用入口见 redirect_symbols.py。"""
|
||||
|
||||
from redirect_symbols import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(legacy_fopen=True)
|
||||
@@ -0,0 +1,241 @@
|
||||
#!/usr/bin/env python3
|
||||
"""由 JSON 映射驱动的 ARM64 Mach-O 静态归档外部 C 符号重定向工具。
|
||||
|
||||
只生成新文件;拒绝未知格式、目标符号冲突、动态库和实际 LLVM bitcode。
|
||||
允许并保留 __LLVM 内单字节零值的 bitcode/cmdline 占位标记。
|
||||
不改机器码或重定位索引,不自动生成 ABI 转发函数,不提供 IPA 加固保证。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ARCHIVE_MAGIC = b"!<arch>\n"
|
||||
DEFAULT_MAPPING = {"_fopen": "_IG_fopen"}
|
||||
CPU_ARM64 = 0x0100000C
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def bounds(data, offset, length):
|
||||
require(0 <= offset <= len(data) and 0 <= length <= len(data) - offset,
|
||||
"数据范围越界")
|
||||
|
||||
|
||||
def validate_mapping(mapping):
|
||||
require(isinstance(mapping, dict) and bool(mapping), "映射必须是非空 JSON 对象")
|
||||
for source, target in mapping.items():
|
||||
for name in (source, target):
|
||||
require(isinstance(name, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", name),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(len(set(mapping.values())) == len(mapping), "多个源符号不能共用一个目标")
|
||||
require(not set(mapping).intersection(mapping.values()), "不允许自映射、映射链或循环")
|
||||
return {source.encode("ascii"): target.encode("ascii") for source, target in mapping.items()}
|
||||
|
||||
|
||||
def load_mapping(path):
|
||||
def unique_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, f"JSON 映射存在重复键:{key}")
|
||||
result[key] = value
|
||||
return result
|
||||
mapping = json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique_pairs)
|
||||
validate_mapping(mapping)
|
||||
return mapping
|
||||
|
||||
|
||||
def redirect_object(data, mapping=None):
|
||||
rewritten, counts = _redirect_object(data, validate_mapping(DEFAULT_MAPPING if mapping is None else mapping))
|
||||
return rewritten, sum(counts.values())
|
||||
|
||||
|
||||
def _redirect_object(data, mapping):
|
||||
"""保持 nlist 索引及重定位不变,仅追加字符串、更新字符串偏移。"""
|
||||
bounds(data, 0, 32)
|
||||
magic, cpu, subtype, kind, count, size, _, _ = struct.unpack_from("<8I", data)
|
||||
require(magic == 0xFEEDFACF and cpu == CPU_ARM64 and subtype == 0,
|
||||
"仅支持 little-endian arm64(不含 arm64e)Mach-O 对象")
|
||||
require(kind == 1, "成员必须是 MH_OBJECT,不能处理可执行文件或动态库")
|
||||
bounds(data, 32, size)
|
||||
cursor = 32
|
||||
symtab = None
|
||||
for _ in range(count):
|
||||
require(cursor + 8 <= 32 + size, "load command 头越界")
|
||||
cmd, cmdsize = struct.unpack_from("<II", data, cursor)
|
||||
require(cmdsize >= 8 and cmdsize % 8 == 0 and cursor + cmdsize <= 32 + size,
|
||||
"load command 长度无效")
|
||||
require(cmd != 0x1D, "不支持含代码签名的对象")
|
||||
if cmd == 0x19:
|
||||
require(cmdsize >= 72, "segment command 太短")
|
||||
sections = struct.unpack_from("<I", data, cursor + 64)[0]
|
||||
require(72 + sections * 80 == cmdsize, "section 数量不匹配")
|
||||
for index in range(sections):
|
||||
pos = cursor + 72 + index * 80
|
||||
section_name = data[pos:pos + 16].rstrip(b"\0")
|
||||
segment = data[pos + 16:pos + 32].rstrip(b"\0")
|
||||
if segment == b"__LLVM":
|
||||
section_size = struct.unpack_from("<Q", data, pos + 40)[0]
|
||||
section_offset = struct.unpack_from("<I", data, pos + 48)[0]
|
||||
bounds(data, section_offset, section_size)
|
||||
require(section_name in (b"__bitcode", b"__cmdline") and section_size == 1
|
||||
and data[section_offset:section_offset + 1] == b"\0",
|
||||
"实际 LLVM bitcode 或未知 LLVM section 不在本 PoC 支持范围")
|
||||
if cmd == 2:
|
||||
require(symtab is None and cmdsize == 24, "LC_SYMTAB 重复或长度无效")
|
||||
symtab = cursor
|
||||
cursor += cmdsize
|
||||
require(cursor == 32 + size, "load command 总长度不匹配")
|
||||
require(symtab is not None, "对象缺少 LC_SYMTAB")
|
||||
symoff, nsyms, stroff, strsize = struct.unpack_from("<4I", data, symtab + 8)
|
||||
bounds(data, symoff, nsyms * 16)
|
||||
bounds(data, stroff, strsize)
|
||||
require(symoff >= cursor and stroff >= symoff + nsyms * 16,
|
||||
"不支持重叠或乱序的符号表/字符串表")
|
||||
# Apple 静态归档可能在对象尾部加入换行填充,也接受零填充。
|
||||
tail = data[stroff + strsize:]
|
||||
require(len(tail) <= 7 and (not tail or set(tail) <= {0} or set(tail) <= {10}),
|
||||
"字符串表后存在未知数据")
|
||||
strings = data[stroff:stroff + strsize]
|
||||
changed = []
|
||||
for index in range(nsyms):
|
||||
pos = symoff + index * 16
|
||||
strx, ntype, section, _, value = struct.unpack_from("<IBBHQ", data, pos)
|
||||
require(strx < strsize, "符号字符串索引越界")
|
||||
end = strings.find(b"\0", strx)
|
||||
require(end != -1, "符号名缺少终止符")
|
||||
name = strings[strx:end]
|
||||
require(name not in mapping.values(), f"归档已包含目标符号 {name!r},拒绝重复处理或冲突")
|
||||
if name in mapping:
|
||||
require(ntype == 1 and section == 0 and value == 0,
|
||||
f"{name!r} 必须是普通外部未定义符号,不能重写定义/common/debug 符号")
|
||||
changed.append((pos, name))
|
||||
if not changed:
|
||||
return data, Counter()
|
||||
output = bytearray(data[:stroff + strsize])
|
||||
offsets = {}
|
||||
counts = Counter()
|
||||
for pos, name in changed:
|
||||
if name not in offsets:
|
||||
offsets[name] = len(output) - stroff
|
||||
output.extend(mapping[name] + b"\0")
|
||||
struct.pack_into("<I", output, pos, offsets[name])
|
||||
counts[name.decode("ascii")] += 1
|
||||
# 保持对象长度为 8 字节对齐,填充也属于字符串表。
|
||||
output.extend(b"\0" * (-len(output) % 8))
|
||||
struct.pack_into("<I", output, symtab + 20, len(output) - stroff)
|
||||
return bytes(output), counts
|
||||
|
||||
|
||||
def redirect_archive(data, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
encoded_mapping = validate_mapping(mapping)
|
||||
require(data.startswith(ARCHIVE_MAGIC), "输入不是普通 ar 归档")
|
||||
output = bytearray(ARCHIVE_MAGIC)
|
||||
cursor = len(ARCHIVE_MAGIC)
|
||||
records = []
|
||||
members = 0
|
||||
totals = Counter({source: 0 for source in mapping})
|
||||
while cursor < len(data):
|
||||
bounds(data, cursor, 60)
|
||||
header = data[cursor:cursor + 60]
|
||||
require(header[58:60] == b"`\n", "ar 成员头无效")
|
||||
length = int(header[48:58].strip())
|
||||
bounds(data, cursor + 60, length)
|
||||
payload = data[cursor + 60:cursor + 60 + length]
|
||||
name = header[:16].rstrip(b" ")
|
||||
prefix = b""
|
||||
if name.startswith(b"#1/"):
|
||||
name_length = int(name[3:])
|
||||
require(0 < name_length <= len(payload), "BSD 扩展成员名长度无效")
|
||||
prefix, payload = payload[:name_length], payload[name_length:]
|
||||
name = prefix.rstrip(b"\0")
|
||||
else:
|
||||
require(not name.startswith(b"/"), "暂不支持 GNU 长名称或 GNU 索引格式")
|
||||
name = name.rstrip(b"/")
|
||||
require(bool(name), "空成员名")
|
||||
cursor += 60 + length
|
||||
if length % 2:
|
||||
bounds(data, cursor, 1)
|
||||
require(data[cursor:cursor + 1] == b"\n", "ar 填充无效")
|
||||
cursor += 1
|
||||
if name in (b"__.SYMDEF", b"__.SYMDEF SORTED", b"__.SYMDEF_64", b"__.SYMDEF_64 SORTED"):
|
||||
continue # 修改后必须由 ranlib 重建索引。
|
||||
try:
|
||||
rewritten, counts = _redirect_object(payload, encoded_mapping)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"成员 {os.fsdecode(name)}:{error}") from error
|
||||
members += 1
|
||||
if counts:
|
||||
totals.update(counts)
|
||||
records.append({"member_index": members, "member": os.fsdecode(name),
|
||||
"references": sum(counts.values()), "symbols": dict(counts)})
|
||||
combined = prefix + rewritten
|
||||
require(len(str(len(combined))) <= 10, "成员过大")
|
||||
output.extend(header[:48] + str(len(combined)).encode().ljust(10) + header[58:60])
|
||||
output.extend(combined)
|
||||
if len(combined) % 2:
|
||||
output.extend(b"\n")
|
||||
require(bool(records), "没有找到映射中的可重定向引用")
|
||||
unmatched = [source for source in mapping if not totals[source]]
|
||||
require(not require_all or not unmatched, f"要求全部命中,但缺少符号:{', '.join(unmatched)}")
|
||||
return bytes(output), {"members_checked": members, "changed_members": records,
|
||||
"references_redirected": sum(totals.values()),
|
||||
"symbol_counts": dict(totals), "unmatched_symbols": unmatched}
|
||||
|
||||
|
||||
def run(source, destination, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
validate_mapping(mapping)
|
||||
source, destination = source.resolve(), destination.absolute()
|
||||
require(source != destination.resolve(), "不能覆盖输入")
|
||||
require(not destination.exists() and not destination.is_symlink(), "输出已存在,拒绝覆盖")
|
||||
original = source.read_bytes()
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-", dir=destination.parent) as folder:
|
||||
thin = Path(folder) / "input.a"
|
||||
if original.startswith(ARCHIVE_MAGIC):
|
||||
thin.write_bytes(original)
|
||||
else:
|
||||
require(original[:4] in (b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"),
|
||||
"仅接受 BSD 静态归档或包含该归档的 fat 文件")
|
||||
subprocess.run(["xcrun", "lipo", str(source), "-thin", "arm64", "-output", str(thin)], check=True)
|
||||
archive, report = redirect_archive(thin.read_bytes(), mapping, require_all)
|
||||
candidate = Path(folder) / "redirected.a"
|
||||
candidate.write_bytes(archive)
|
||||
subprocess.run(["xcrun", "ranlib", str(candidate)], check=True)
|
||||
report.update({"source": str(source), "output": str(destination), "architecture": "arm64",
|
||||
"source_sha256": hashlib.sha256(original).hexdigest(),
|
||||
"output_sha256": hashlib.sha256(candidate.read_bytes()).hexdigest(),
|
||||
"mapping": dict(mapping)})
|
||||
# 同目录硬链接原子发布,目标已存在时失败,避免竞争覆盖。
|
||||
os.link(candidate, destination)
|
||||
return report
|
||||
|
||||
|
||||
def main(legacy_fopen=False):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("output", type=Path, help="不存在的新 .a 路径;父目录须存在")
|
||||
if not legacy_fopen:
|
||||
parser.add_argument("--mapping", type=Path, required=True, help="精确的 Mach-O C 符号映射 JSON")
|
||||
parser.add_argument("--require-all", action="store_true", help="每个源符号均须命中,否则不输出")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
mapping = DEFAULT_MAPPING if legacy_fopen else load_mapping(args.mapping)
|
||||
print(json.dumps(run(args.input, args.output, mapping, args.require_all), ensure_ascii=False, indent=2))
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
parser.exit(1, f"重定向失败:{error}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user