Files
iOSGuard/docs/04_DETAILED_SUBSYSTEMS_DESIGN.md

891 lines
38 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# iOSGuard 八大核心子系统详细设计与实现方案
本文档为 **iOSGuard** 企业级加固系统的八大核心子系统技术白皮书。每个子系统均提供:**设计目标、核心数据结构与接口、底层算法与实现流程、汇编与代码原型、技术陷阱与规避策略**。
---
## 目录
1. [子系统 1:Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)](#1-mach-o-深度重构与二进制引擎-mach-o-rewriter)
2. [子系统 2:Class-Dump 彻底防御与动态重映射 (Metadata Protector)](#2-class-dump-彻底防御与动态重映射-metadata-protector)
3. [子系统 3:原生代码虚拟化 (VMP) 引擎 (Code Virtualization)](#3-原生代码虚拟化-vmp-引擎-code-virtualization)
4. [子系统 4:全维度内核级主动防御对抗矩阵 (Defender Core)](#4-全维度内核级主动防御对抗矩阵-defender-core)
5. [子系统 5:双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)](#5-双符号表体系与-dsym-崩溃逆向还原-dual-symbol--crash-restorer)
6. [子系统 6:资产保护与无感透明解密 (Virtual File System & Assets Protector)](#6-资产保护与无感透明解密-virtual-file-system--assets-protector)
7. [子系统 7:跨平台自动化重签名流水线 (Cross-Platform Signer Engine)](#7-跨平台自动化重签名流水线-cross-platform-signer-engine)
8. [子系统 8:IPA 相似度预检中心 (App Store 4.3 预检器)](#8-ipa-相似度预检中心-app-store-43-预检器)
---
## 1. Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)
### 1.1 设计目标
在无源码条件下解析 IPA 中的主 Mach-O 与 Dynamic Frameworks,完成:
1. 安全注入 `LC_LOAD_DYLIB` 加载加固守护动态库 `libDefender.dylib`;
2. 新增私有加密段 `__PROTECT`(存放抽取函数、加密元数据、白盒查找表);
3. 严格遵循 ARM64 `0x4000`(16KB)页面对齐规范,保证重签名后 AMFI 校验通过。
### 1.2 核心数据结构
```cpp
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <vector>
#include <string>
struct MachOBinary {
mach_header_64 header;
std::vector<uint8_t> raw_data;
std::vector<load_command*> load_commands;
segment_command_64* text_segment;
segment_command_64* linkedit_segment;
linkedit_data_command* code_signature_cmd;
uint32_t header_padding_size;
};
```
### 1.3 底层算法与 M1 注入逻辑
```mermaid
flowchart TD
A["读取并校验 Mach-O 边界\nbinary.size >= sizeof(mach_header_64)"] --> B["遍历与校验 load_commands\n边界检查: cmdsize >= 8 且在 cmds_end 范围内"]
B --> C["遍历 LC_SEGMENT_64 与 sections\n统计真实存在的第一节最小 offset (found_valid_section)"]
C --> D{"有效性安全检查\nfound_valid_section && first_section_offset >= header_and_cmds && <= binary.size"}
D -- "检查不通过" --> D1["退出拒绝处理 (防御非法头部/下溢/越界)"]
D -- "通过" --> E{"检测可用 Padding 空间\navailable_padding = first_section_offset - header_and_cmds"}
E -- "available_padding >= cmd_size" --> F["M1 MVP 路径: 原地追加 LC_LOAD_DYLIB\n更新 ncmds & sizeofcmds 并写入 @rpath 路径"]
E -- "available_padding 不足" --> G["M1 策略: 直接拒绝,报错退出\n(段平移与 Fixup 重构隔离至 M2 研发)"]
```
#### 代码实现原型:严格边界防御的 LC_LOAD_DYLIB 原地注入
```cpp
bool InjectDylib(std::vector<uint8_t>& binary, const std::string& dylib_path) {
// 1. 基础头部尺寸校验
if (binary.size() < sizeof(mach_header_64)) return false;
auto* header = reinterpret_cast<mach_header_64*>(binary.data());
if (header->magic != MH_MAGIC_64) return false;
// 2. sizeofcmds 边界校验
uint32_t header_and_cmds = sizeof(mach_header_64) + header->sizeofcmds;
if (binary.size() < header_and_cmds) return false;
// 3. 计算对齐后的 dylib_command 大小 (8 字节对齐)
uint32_t cmd_size = sizeof(dylib_command) + dylib_path.length() + 1;
cmd_size = (cmd_size + 7) & ~7;
uint8_t* cmds_start = binary.data() + sizeof(mach_header_64);
uint8_t* cmds_end = cmds_start + header->sizeofcmds;
// 4. 遍历所有 Load Commands 并严格检查边界,查找首个 Section 偏移
uint32_t first_section_offset = UINT32_MAX;
bool found_valid_section = false;
uint8_t* cur_cmd = cmds_start;
for (uint32_t i = 0; i < header->ncmds; i++) {
if (cur_cmd + sizeof(load_command) > cmds_end) return false;
auto* lc = reinterpret_cast<load_command*>(cur_cmd);
if (lc->cmdsize < sizeof(load_command) || cur_cmd + lc->cmdsize > cmds_end) {
return false; // 非法 cmdsize
}
if (lc->cmd == LC_SEGMENT_64) {
if (cur_cmd + sizeof(segment_command_64) > cmds_end) return false;
auto* sc = reinterpret_cast<segment_command_64*>(cur_cmd);
if (cur_cmd + sizeof(segment_command_64) + sc->nsects * sizeof(section_64) > cmds_end) {
return false; // Section 数组超出 load commands 边界
}
auto* sec = reinterpret_cast<section_64*>(cur_cmd + sizeof(segment_command_64));
for (uint32_t j = 0; j < sc->nsects; j++) {
// 仅统计实际存在于文件内的有效非零偏移 Section
if (sec[j].offset > 0 && sec[j].size > 0) {
if (sec[j].offset < first_section_offset) {
first_section_offset = sec[j].offset;
found_valid_section = true;
}
}
}
}
cur_cmd += lc->cmdsize;
}
// 5. 严格防御:无 Section、偏移异常或首节偏移超出文件长度时直接拒绝,彻底杜绝下溢
if (!found_valid_section || first_section_offset < header_and_cmds || first_section_offset > binary.size()) {
return false;
}
uint32_t available_padding = first_section_offset - header_and_cmds;
// 6. M1 策略:Padding 空间充足时原地写入,不足时直接拒绝处理
if (available_padding < cmd_size || header_and_cmds + cmd_size > binary.size()) {
// 空间不足,在 M1 阶段明确拒绝,不隐式调用段平移
return false;
}
// 原地写入 LC_LOAD_DYLIB
auto* new_cmd = reinterpret_cast<dylib_command*>(cmds_start + header->sizeofcmds);
memset(new_cmd, 0, cmd_size);
new_cmd->cmd = LC_LOAD_DYLIB;
new_cmd->cmdsize = cmd_size;
new_cmd->dylib.name.offset = sizeof(dylib_command);
new_cmd->dylib.timestamp = 2;
new_cmd->dylib.current_version = 0x10000;
new_cmd->dylib.compatibility_version = 0x10000;
memcpy(reinterpret_cast<char*>(new_cmd) + sizeof(dylib_command), dylib_path.c_str(), dylib_path.length() + 1);
header->ncmds += 1;
header->sizeofcmds += cmd_size;
return true;
}
```
### 1.4 M1 运行环境与 @rpath 依赖解析
在 M1 真机验收中,注入的 `libDefender.dylib` 必须满足动态链接器解析路径:
1. **注入路径规范**:推荐使用 `@rpath/libDefender.dylib`;
2. **实际物理嵌入**:IPA 解包后,必须将 `libDefender.dylib` 拷贝至 `Payload/App.app/Frameworks/libDefender.dylib`;
3. **LC_RPATH 校验**:主二进制必须包含 `LC_RPATH` 指向 `@executable_path/Frameworks`,若不存在需在注入时同步检测并补齐。
---
## 2. Class-Dump 彻底防御与动态重映射 (Metadata Protector)
### 2.1 设计目标
消除 Mach-O 静态暴露的所有 Objective-C 类名、分类、选择器和属性元数据,使 `class-dump`、`dscli`、Hopper、IDA 彻底无法还原符号;同时通过运行时受控动态注册,确保 `objc_msgSend` 与 KVC 正常运作。
### 2.2 Objective-C 64位运行时结构体解构
```c
struct objc_class_64 {
uint64_t isa;
uint64_t superclass;
uint64_t cache;
uint64_t vtable;
uint64_t data; // 指向 class_rw_t 或 class_ro_t
};
struct class_ro_t_64 {
uint32_t flags;
uint32_t instanceStart;
uint32_t instanceSize;
uint32_t reserved;
uint64_t ivarLayout;
uint64_t name; // 指向 __objc_classname 字符串
uint64_t baseMethods; // 指向 method_list_t
uint64_t baseProtocols;
uint64_t ivars;
uint64_t weakIvarLayout;
uint64_t baseProperties;
};
struct method_t_64 {
uint64_t name; // 指向 __objc_methname
uint64_t types; // 指向 __objc_methtype (真实类型编码,如 "@16@0:8")
uint64_t imp; // 函数虚拟地址 (相对Mach-O vmaddr基地址)
};
// iOS 14+ 广泛采用的小方法列表 (Relative Method List)
struct method_list_t_relative {
uint32_t entsizeAndFlags; // 包含 0x80000000 相对寻址标记
uint32_t count;
// 相对偏移结构体: 每个字段为相对于字段自身地址的 int32_t 偏移
struct method_relative_t {
int32_t name_offset;
int32_t types_offset;
int32_t imp_offset;
} methods[];
};
```
### 2.3 加固与还原流程
```
[编译加固期 (Mach-O 离线重写)]
1. 扫描 __DATA,__objc_classlist 提取 class_ro_t 与元类 (Meta-Class)
2. 序列化 {ClassName, [is_meta, Selector, ImpVMAddr, TypeEncoding]} 为私有二进制
3. 使用 ChaCha20-Poly1305 加密存入 __PROTECT,__meta 节
4. 清空非白名单的 __TEXT,__objc_methname (填 '\0'),将 class_ro_t->baseMethods 置空
│
▼
[运行时阶段 (libDefender 早期构造器 __mod_init_func)]
1. 获取目标 Mach-O 的 ASLR 偏移 (Slide = _dyld_get_image_vmaddr_slide(index))
2. 解密元数据,准确按类型注回:
- 实例方法注回目标类 cls
- 类方法注回元类 object_getClass(cls)
3. 使用真实 TypeEncoding 与 (ImpVMAddr + Slide) 动态注册
4. 对 +load、KVC 敏感类与系统协议建立白名单豁免机制
```
#### 运行时动态重映射 Hook 原型 (严格流同步与边界防御版)
```objc
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <mach-o/dyld.h>
void RestoreObjcMetadata(const uint8_t *decrypted_meta, size_t size, intptr_t slide) {
if (!decrypted_meta || size == 0) return;
size_t offset = 0;
while (offset + 2 <= size) {
// 1. 安全读取类名长度与字符串
uint16_t name_len = *(uint16_t*)(decrypted_meta + offset);
offset += 2;
if (name_len == 0 || name_len >= 256 || offset + name_len > size) {
break; // 数据流受损,安全终止
}
char class_name[256] = {0};
memcpy(class_name, decrypted_meta + offset, name_len);
offset += name_len;
// 查找目标类 (即便类不存在,游标也必须完整跳过后续方法体,绝不可直接 continue 导致流失步)
Class cls = objc_getClass(class_name);
Class meta_cls = cls ? object_getClass(cls) : nil;
// 2. 读取方法数量
if (offset + 4 > size) break;
uint32_t method_count = *(uint32_t*)(decrypted_meta + offset);
offset += 4;
for (uint32_t i = 0; i < method_count; i++) {
if (offset + 1 > size) break;
uint8_t is_meta = *(uint8_t*)(decrypted_meta + offset++);
// 读取 Selector 名字
if (offset + 2 > size) break;
uint16_t sel_len = *(uint16_t*)(decrypted_meta + offset);
offset += 2;
if (sel_len >= 256 || offset + sel_len > size) break;
char sel_name[256] = {0};
memcpy(sel_name, decrypted_meta + offset, sel_len);
offset += sel_len;
// 读取真实类型编码 (如 "@16@0:8" 或 "i24@0:8@16")
if (offset + 2 > size) break;
uint16_t type_len = *(uint16_t*)(decrypted_meta + offset);
offset += 2;
if (type_len >= 128 || offset + type_len > size) break;
char type_encoding[128] = {0};
memcpy(type_encoding, decrypted_meta + offset, type_len);
offset += type_len;
// 读取静态 VM 地址并结合 ASLR Slide 计算真实函数入口
if (offset + 8 > size) break;
uint64_t imp_vmaddr = *(uint64_t*)(decrypted_meta + offset);
offset += 8;
// 仅在类存在时执行注回;即使类缺失,游标也已完整解析完当前方法,下一记录依然对齐
if (cls) {
IMP real_imp = (IMP)(imp_vmaddr + slide);
SEL sel = sel_registerName(sel_name);
Class target_cls = is_meta ? meta_cls : cls;
class_addMethod(target_cls, sel, real_imp, type_encoding);
}
}
}
}
```
### 2.4 语义保持、分类顺序与共享 Selector 防线
> [!IMPORTANT]
> **Objective-C 进阶语义约束**:
> 1. **分类 (Category) 覆盖顺序保持**:在 Objective-C 运行时中,分类的方法会被追加到类方法列表前端(优先命中)。元数据序列化时,必须保证**主类记录在前、分类记录在后**,运行时按序注回,以维持既有的分类覆盖优先级。
> 2. **共享与系统 Selector 保护**:若某个 Selector 仍被系统 Framework(如 `UITableViewDelegate` 回调)、KVO 或未加固模块显式调用,**其 `__TEXT,__objc_methname` 字符串绝不可盲目抹除**,必须建立静态交叉引用扫描(Xref),只抹除非暴露、纯内部调用的私有 Selector。
> 3. **`+load` 时序限制**:`+load` 在 dyld 加载镜像时由 `libobjc` 的 `prepare_load_methods` 内部直接读取并调用,早于 C++ 动态库构造器。因此**带有 `+load` 的类方法必须保留在静态结构中或采用动态桥接白名单**,不可盲目抹除。
> 4. **JSON 反序列化与 KVC**:`YYModel` / `MJExtension` 依赖 `class_copyPropertyList` 和 `class_copyIvarList`。加固系统必须建立基于类的排除规则,对 Model 数据模型对象豁免元数据抹除。
---
## 3. 原生代码虚拟化 (VMP) 引擎 (Code Virtualization)
### 3.1 设计目标
针对高敏感函数(如充值校验、密钥派生、核心通信协议),将其 ARM64 指令编译或抽取为私有字节码,通过纯解释型虚拟机(Interpreter-based VM)执行。**绝对不使用 `mprotect(PROT_EXEC)`,100% 遵从苹果 AMFI 与 W^X 规范**。
### 3.2 私有指令集 (Custom ISA) 规范设计
指令格式采用 4 字节定长指令:`[Opcode 8bit] [Dest_Reg 8bit] [Src_Reg 8bit] [Immediate / Offset 8bit]`。
| Opcode | 汇编助记符 | 描述 | 操作数含义 |
| :--- | :--- | :--- | :--- |
| `0x11` | `VM_MOV_IMM` | 将立即数写入虚拟寄存器 | `dst = imm` |
| `0x12` | `VM_MOV_REG` | 寄存器传值 | `dst = src` |
| `0x21` | `VM_ADD` | 虚拟寄存器加法 | `dst = dst + src` |
| `0x22` | `VM_SUB` | 虚拟寄存器减法 | `dst = dst - src` |
| `0x25` | `VM_XOR` | 异或运算 | `dst = dst ^ src` |
| `0x31` | `VM_LOAD64` | 内存加载 64 位值 | `dst = *(uint64_t*)(src + imm)` |
| `0x32` | `VM_STORE64`| 写入内存 64 位值 | `*(uint64_t*)(dst + imm) = src` |
| `0x41` | `VM_CMP` | 比较并更新标志位 | `flags = cmp(dst, src)` |
| `0x51` | `VM_JMP` | 无条件跳转 | `pc += imm` |
| `0x52` | `VM_JZ` | 为零跳转 | `if (flags.Z) pc += imm` |
| `0x61` | `VM_CALL` | 调用原生 C 函数 | 调度真实函数指针 |
| `0xFF` | `VM_RET` | 退出虚拟机并还原上下文 | 返回上层原生栈 |
### 3.3 解释器 Direct-Threaded 跳转循环实现原型 (含完整安全与异常边界)
```c
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
// 执行结果结构体,区分正常返回值与执行错误
typedef struct {
bool success;
uint64_t ret_val;
uint32_t error_code; // 0: 正常, 1: 未知操作码, 2: 非法内存越界, 3: 指令跳转越界
} VMResult;
typedef struct {
uint64_t r[31]; // ARM64 x0 - x30 通用虚拟寄存器
uint64_t sp; // 当前栈指针
uint64_t sp_base; // 虚拟栈底边界 (安全检查)
uint64_t sp_top; // 虚拟栈顶边界 (安全检查)
uint64_t flags; // 标志位 NZCV
} VMContext;
// 校验地址是否落在合法的虚拟栈或有效数据内存区内
static inline bool is_vm_memory_accessible(const VMContext *ctx, uint64_t addr, size_t size) {
if (addr < 4096) return false; // 严防空指针及低地址零页异常 (如 0x1)
if (addr >= ctx->sp_base && addr + size <= ctx->sp_top) return true;
return false; // 原型阶段严格限制在虚拟栈内存空间,后续扩展堆区白名单
}
VMResult VMP_Execute(const uint8_t *bytecode, size_t bytecode_len, uint64_t arg0, uint64_t arg1) {
VMResult result = {false, 0, 0};
if (!bytecode || bytecode_len < 4) {
result.error_code = 1;
return result;
}
VMContext ctx = {0};
ctx.r[0] = arg0;
ctx.r[1] = arg1;
size_t stack_size = 4096;
void *stack_mem = malloc(stack_size);
if (!stack_mem) {
result.error_code = 2;
return result;
}
ctx.sp_base = (uint64_t)stack_mem;
ctx.sp_top = ctx.sp_base + stack_size;
ctx.sp = ctx.sp_top; // 栈自顶向下生长
const uint8_t *pc = bytecode;
const uint8_t *pc_end = bytecode + bytecode_len;
static const void *dispatch_table[256] = {
[0x11] = &&op_mov_imm,
[0x12] = &&op_mov_reg,
[0x21] = &&op_add,
[0x25] = &&op_xor,
[0x31] = &&op_load64,
[0x32] = &&op_store64,
[0x41] = &&op_cmp,
[0x52] = &&op_jz,
[0xFF] = &&op_ret
};
#define DISPATCH() \
do { \
if (pc + 4 > pc_end) { \
result.error_code = 1; \
goto vm_exit; \
} \
void *target = (void*)dispatch_table[*pc]; \
if (!target) { \
result.error_code = 1; /* 未知操作码,明确报错,绝不伪装正常返回 */ \
goto vm_exit; \
} \
goto *target; \
} while(0)
DISPATCH();
op_mov_imm: {
uint8_t dst = pc[1];
uint8_t imm = pc[3];
if (dst < 31) ctx.r[dst] = imm;
pc += 4;
DISPATCH();
}
op_mov_reg: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
if (dst < 31 && src < 31) ctx.r[dst] = ctx.r[src];
pc += 4;
DISPATCH();
}
op_add: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
if (dst < 31 && src < 31) ctx.r[dst] += ctx.r[src];
pc += 4;
DISPATCH();
}
op_xor: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
if (dst < 31 && src < 31) ctx.r[dst] ^= ctx.r[src];
pc += 4;
DISPATCH();
}
op_load64: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
int8_t imm = (int8_t)pc[3]; // 正确计入 ISA 规范中定义的 imm 偏移
if (dst < 31 && src < 31) {
uint64_t target_addr = ctx.r[src] + imm;
if (!is_vm_memory_accessible(&ctx, target_addr, 8)) {
result.error_code = 2; // 内存越界/非法指针,明确捕获异常
goto vm_exit;
}
ctx.r[dst] = *(uint64_t*)target_addr;
}
pc += 4;
DISPATCH();
}
op_store64: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
int8_t imm = (int8_t)pc[3]; // 正确计入 ISA 规范中定义的 imm 偏移
if (dst < 31 && src < 31) {
uint64_t target_addr = ctx.r[dst] + imm;
if (!is_vm_memory_accessible(&ctx, target_addr, 8)) {
result.error_code = 2; // 内存越界/非法指针,明确捕获异常
goto vm_exit;
}
*(uint64_t*)target_addr = ctx.r[src];
}
pc += 4;
DISPATCH();
}
op_cmp: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
if (dst < 31 && src < 31) {
ctx.flags = (ctx.r[dst] == ctx.r[src]) ? 1 : 0;
}
pc += 4;
DISPATCH();
}
op_jz: {
int8_t offset = (int8_t)pc[3];
if (ctx.flags == 1) {
const uint8_t *next_pc = pc + offset * 4;
if (next_pc >= bytecode && next_pc + 4 <= pc_end) {
pc = next_pc;
} else {
result.error_code = 3; // 跳转目标越界,明确报错
goto vm_exit;
}
} else {
pc += 4;
}
DISPATCH();
}
op_ret: {
result.success = true;
result.ret_val = ctx.r[0];
result.error_code = 0;
goto vm_exit;
}
vm_exit:
free(stack_mem);
return result;
}
```
### 3.4 虚拟化适用范围与验收边界
> [!NOTE]
> **VMP 研发边界与验收范围**:
> 当前原型用于验证自定义字节码指令调度与寄存器映射机制。通用 C/C++/Swift 函数若包含浮点/SIMD(NEON `Q0~Q31`)、C++ 异常栈解退(`eh_frame`)、动态栈分配(`alloca`)或变长参数(`va_list`),需要完备的编译器后端支持。
> **工程策略**:VMP 首期仅用于保护加固关键的算法、鉴权校验与密钥派生纯整型逻辑函数,不作为通用全量函数虚拟化方案。
---
## 4. 全维度内核级主动防御对抗矩阵 (Defender Core)
### 4.1 反调试机制与 App Store §2.5.1 公开 API 边界
> [!CAUTION]
> **iPhoneOS SDK 真实接口与提审红线**:
> 在 iOS 官方 SDK(`iPhoneOS.platform`)中,**苹果并未提供公开的 `<sys/ptrace.h>` 头文件**。
> `ptrace` 在 iOS 底层 `libSystem.dylib` 中被视作私有未公开符号。无论是直接调用、还是通过 `dlsym(RTLD_DEFAULT, "ptrace")` 动态查找并混淆符号名,均属于调用非公开 API,直接违反 **App Store Review Guideline §2.5.1**。
>
> **方案修正与合规边界**:
> 1. **提审产物必须物理排除**:通过预编译宏 `#ifndef APPSTORE_RELEASE`,在生成提审包时**将 `PT_DENY_ATTACH`、`dlsym("ptrace")` 以及裸汇编 `svc #0x80` 源码彻底编译排除**,绝不残留任何私有符号或未文档化系统调用路径;
> 2. **提审版反调试方案**:仅使用苹果公开文档许可的标准接口,即通过 `sysctl` 检查进程 `P_TRACED` 标志位;
> 3. **内核级软中断定位**:裸汇编 `svc #0x80` 与 `PT_DENY_ATTACH` 仅供**企业内部分发 (Enterprise) / Ad-Hoc / 内部反作弊测试**使用,收回此前“可直接提审”和“完全合规”的不严谨表述。
```c
#include <sys/types.h>
#include <sys/sysctl.h>
#include <unistd.h>
#include <stdbool.h>
// 1. App Store 提审合规反调试:仅依赖公开 documented sysctl API
bool is_debugger_attached_appstore_compliant(void) {
int name[4];
struct kinfo_proc info;
size_t info_size = sizeof(info);
info.kp_proc.p_flag = 0;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_PID;
name[3] = getpid();
if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
return false;
}
// 检查进程标志位中的 P_TRACED
return ((info.kp_proc.p_flag & P_TRACED) != 0);
}
// 2. 企业版/内测专用反调试:裸汇编软中断 (提审构建时由预处理器物理排除)
#ifndef APPSTORE_RELEASE
__attribute__((always_inline)) static inline void anti_debug_enterprise_svc(void) {
#if defined(__arm64__) || defined(__aarch64__)
__asm__ volatile(
"mov x0, #31\n" // PT_DENY_ATTACH (0x1f)
"mov x1, #0\n"
"mov x2, #0\n"
"mov x3, #0\n"
"mov x16, #26\n" // SYS_ptrace = 26
"svc #0x80\n" // 仅用于企业签/反作弊对抗环境
:
:
: "x0", "x1", "x2", "x3", "x16"
);
#endif
}
#endif
```
### 4.2 硬件断点 (DR0-DR7) 探测
攻击者在 LLDB 或调试器中下硬件断点时,会写入 ARM64 调试寄存器。通过 `thread_get_state` 轮询检查:
```c
#include <mach/mach.h>
#include <stdbool.h>
bool check_hardware_breakpoints() {
mach_port_t this_thread = mach_thread_self();
arm_debug_state64_t state;
mach_msg_type_number_t count = ARM_DEBUG_STATE64_COUNT;
kern_return_t kr = thread_get_state(this_thread, ARM_DEBUG_STATE64,
(thread_state_t)&state, &count);
mach_port_deallocate(mach_task_self(), this_thread);
if (kr == KERN_SUCCESS) {
for (int i = 0; i < 16; i++) {
// bvr 为断点地址寄存器,bcr 为控制寄存器 (bit 0 为启用位)
if (state.__bcr[i] & 1) {
return true; // 发现硬件执行断点!
}
if (state.__wcr[i] & 1) {
return true; // 发现硬件观察点 (Watchpoint)!
}
}
}
return false;
}
```
### 4.3 关键函数头 Inline Hook 探测 (Anti-Dobby / Anti-Substrate)
Dobby / CydiaSubstrate 对 ARM64 函数 Hook 时,会在前 16 字节写入跳板指令(如 `LDR X16, #8; BR X16` 机器码 `0x58000050, 0xd61f0200`):
```c
#include <stdint.h>
#include <stdbool.h>
bool is_function_inline_hooked(void *func_ptr) {
uint32_t *instructions = (uint32_t *)func_ptr;
// 检查是否为 LDR X16, [PC, #8] (0x58000050) 紧跟 BR X16 (0xd61f0200)
if (instructions[0] == 0x58000050 && instructions[1] == 0xd61f0200) {
return true;
}
// 检查直接 B / BL 跳转 (0x14000000 掩码)
if ((instructions[0] & 0xFC000000) == 0x14000000) {
return true;
}
return false;
}
```
---
## 5. 双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)
### 5.1 设计目标
解决代码混淆后 Bugly、Sentry 堆栈崩溃无法定位代码行号的问题。
加固期生成 `mapping.db`,离线重写 Release 产生的 `App.app.dSYM`,将 DWARF 调试符号批量恢复为原始符号。
### 5.2 DWARF 调试格式解析与重写流程
Mach-O dSYM 文件包含三个关键调试 Section:
1. `__DWARF,__debug_info`:树状结构的 DIE(Debugging Information Entries),包含 `DW_TAG_subprogram`(函数)和属性 `DW_AT_name`、`DW_AT_linkage_name`。
2. `__DWARF,__debug_str`:字符串常量池(以 `\0` 分隔)。DIE 中的 `DW_FORM_strp` 属性存储指向该池的文件偏移。
3. `__DWARF,__debug_line`:行号状态机字节码,映射机器指令地址与源码行号。
```mermaid
flowchart LR
A["读取原始 dSYM DWARF"] --> B["解析 __debug_str 字符串池"]
B --> C["查询 mapping.sqlite\nObfuscated -> Original"]
C --> D{"新字符串长度 <= 原始混淆名?"}
D -- 是 --> E["就地改写字符串并补 \\0 填充"]
D -- 否 --> F["重建 __debug_str 并在末尾追加\n更新 __debug_info 中对应 DW_FORM_strp 偏移"]
E --> G["输出 Restored.dSYM (上传至 Sentry/Bugly)"]
F --> G
```
#### DWARF 定点引用解析与重构伪代码 (杜绝全局子串误替)
```python
def restore_dsym_targeted(dsym_path, mapping_dict, output_path):
# 严禁在 __debug_str 中执行全文 replace!
# 必须通过 __debug_info 树定位具体 DIE 的 DW_FORM_strp 偏移进行定点更新
with open(dsym_path, "r+b") as f:
macho = MachO(f)
debug_str = bytearray(macho.get_section("__DWARF", "__debug_str").data)
debug_info = macho.get_section("__DWARF", "__debug_info").data
# 1. 遍历 .debug_info 中的 Compilation Units 与 DIE 树
die_offsets = parse_dwarf_die_string_offsets(debug_info) # 提取 (die_id, attr_type, str_offset)
# 2. 定点校验与改写
for str_offset in die_offsets:
# 读取当前位置以 \0 结尾的完整原始字符串
end_idx = debug_str.find(b'\x00', str_offset)
if end_idx == -1: continue
current_sym = debug_str[str_offset:end_idx].decode('utf-8', errors='ignore')
# 精确匹配(非子串模糊替换)
if current_sym in mapping_dict:
restored_sym = mapping_dict[current_sym].encode('utf-8')
orig_len = end_idx - str_offset
if len(restored_sym) <= orig_len:
# 原位填充并截断,严格保证不越界污染相邻字符串
debug_str[str_offset:str_offset + len(restored_sym)] = restored_sym
debug_str[str_offset + len(restored_sym):end_idx] = b'\x00' * (orig_len - len(restored_sym))
else:
# 超长符号追加至表尾,并同步校准该 DIE 的 DW_FORM_strp 指针值
new_offset = append_debug_str(debug_str, restored_sym)
update_die_strp_offset(debug_info, str_offset, new_offset)
macho.get_section("__DWARF", "__debug_str").write(debug_str)
macho.save(output_path)
```
### 5.3 崩溃符号化适用边界与限制说明
> [!IMPORTANT]
> **dSYM 还原的适用边界与客观约束**:
> 1. **符号混淆场景**:仅在函数体指令未发生偏移(仅改名)且通过 DIE 引用定点恢复时,堆栈可获得良好还原。但需注意:编译器内联优化(Inlining)或尾调用消除可能使部分行号产生轻微漂移,收回“100% 精确还原”的绝对表述;同时必须严格校验新产物与原始构建的 `LC_UUID` 严格匹配。
> 2. **代码虚拟化 (VMP) / 函数抽取场景**:一旦函数体被抽离为私有字节码或替换为跳板(Trampoline),原机器指令在二进制中已不复存在。崩溃发生时,系统捕获的堆栈顶帧将必然是 `VMP_Execute`。
> * **解决路径**:对此类函数,无法仅靠静态 dSYM 还原;必须在 `VMPContext` 中维护虚拟 PC,并在崩溃捕获回调中输出虚拟栈帧,结合离线的 `vmp_pc_mapping.json` 完成混合回溯还原。
---
## 6. 资产保护与无感透明解密 (Virtual File System & Assets Protector)
### 6.1 PNG 免解密 Hash 扰动(应对 2.3.1 / 4.3 静态排查)
在不破坏图片展示的前提下修改图片 MD5/SHA256。PNG 格式由固定 8 字节签名加上多个 Chunk 组成。规范允许插入合规私有辅助 Chunk(如 `tEXt`):
```cpp
void PerturbPNGHash(std::vector<uint8_t>& png_data) {
// PNG Header: 89 50 4E 47 0D 0A 1A 0A
std::string key = "Comment";
std::string value = GenerateRandomUUID(); // 随机特征串
// 构造 tEXt Chunk: [Length 4B] [ChunkType 4B "tEXt"] [Data] [CRC 4B]
std::vector<uint8_t> chunk;
uint32_t data_len = key.length() + 1 + value.length();
AppendBigEndian(chunk, data_len);
chunk.insert(chunk.end(), {'t', 'E', 'X', 't'});
chunk.insert(chunk.end(), key.begin(), key.end());
chunk.push_back(0); // 分隔符
chunk.insert(chunk.end(), value.begin(), value.end());
uint32_t crc = CalculateCRC32(chunk.data() + 4, data_len + 4);
AppendBigEndian(chunk, crc);
// 插入在 IHDR Chunk (偏移 8 + 25 字节) 之后
png_data.insert(png_data.begin() + 33, chunk.begin(), chunk.end());
}
```
### 6.2 深度加密与底层 POSIX 透明内存解密
* 加密格式:`[Magic 4B: 'G','U','A','D'] [Nonce 12B] [Tag 16B] [Ciphertext]`
* 拦截 API:使用 `fishhook` 拦截 `fopen`、`open`、`stat`。
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static FILE *(*orig_fopen)(const char *path, const char *mode);
FILE *hook_fopen(const char *path, const char *mode) {
FILE *fp = orig_fopen(path, mode);
if (!fp) return NULL;
// 读取前 4 字节判断是否为加密资产
char magic[4];
if (fread(magic, 1, 4, fp) == 4 && memcmp(magic, "GUAD", 4) == 0) {
// 读取密文长度并在内存解密
fseek(fp, 0, SEEK_END);
long sz = ftell(fp) - 32;
fseek(fp, 32, SEEK_SET);
uint8_t *decrypted_buf = malloc(sz);
// 执行 ChaCha20-Poly1305 解密 ...
// 创建内存文件句柄 (fmemopen) 使得上层读取无感
FILE *mem_fp = fmemopen(decrypted_buf, sz, mode);
fclose(fp);
return mem_fp;
}
fseek(fp, 0, SEEK_SET); // 非加固资源重置指针
return fp;
}
```
---
## 7. 跨平台自动化重签名流水线 (Cross-Platform Signer Engine)
### 7.1 签名核心数据结构:Apple SuperBlob 与 CodeDirectory
```cpp
#include <stdint.h>
#define CSMAGIC_CODEDIRECTORY 0xfade0c02
#define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
#define CSMAGIC_REQUIREMENTS 0xfade0c01
#define CSMAGIC_BLOBWRAPPER 0xfade0b01
#define CSMAGIC_ENTITLEMENTS 0xfade7171
#define CSMAGIC_DER_ENTITLEMENTS 0xfade7172
// 1. SuperBlob 索引类型 (BlobIndex.type,均为正数或标准常量)
#define CSSLOT_CODEDIRECTORY 0 // 0x0: 主 CodeDirectory
#define CSSLOT_REQUIREMENTS 2 // 0x2: Requirements 规则
#define CSSLOT_ENTITLEMENTS 5 // 0x5: XML Entitlements
#define CSSLOT_DER_ENTITLEMENTS 7 // 0x7: DER-encoded Entitlements
#define CSSLOT_SIGNATURESLOT 0x10000 // 0x10000: CMS 签名块 (BlobWrapper)
// 2. CodeDirectory 负数特殊散列槽位 (Special Slots,相对于 hashOffset 的负索引)
#define CD_SLOT_INFOPLIST -1 // Info.plist SHA256
#define CD_SLOT_REQUIREMENTS -2 // Requirements SHA256
#define CD_SLOT_RESOURCEDIR -3 // _CodeSignature/CodeResources SHA256 (关键依赖)
#define CD_SLOT_APPLICATION -4 // 预留
#define CD_SLOT_ENTITLEMENTS -5 // XML Entitlements SHA256
#define CD_SLOT_DER_ENTITLEMENTS -7 // DER Entitlements SHA256
struct BlobIndex {
uint32_t type; // 必须为上述正数常量: 0, 2, 5, 7, 0x10000
uint32_t offset; // 指向 Blob 距离 SuperBlob 起始处的字节偏移
};
struct SuperBlob {
uint32_t magic; // CSMAGIC_EMBEDDED_SIGNATURE
uint32_t length; // 整个 SuperBlob 大小 (包含所有子 Blob)
uint32_t count; // 包含的子 Blob 数量
BlobIndex index[];
};
struct CodeDirectory {
uint32_t magic; // CSMAGIC_CODEDIRECTORY
uint32_t length; // CodeDirectory 自身结构及前后哈希数组大小
uint32_t version; // 0x20400 (支持 SHA256 及负数槽)
uint32_t flags; // 0
uint32_t hashOffset; // 代码正数哈希数组起始偏移 (负数特殊槽位于其左侧)
uint32_t identOffset; // Bundle ID 字符串距头部的偏移
uint32_t nSpecialSlots; // 负数槽位数量 (通常为 7)
uint32_t nCodeSlots; // 页面正数槽位数量 (ceil(codeLimit / 16384))
uint32_t codeLimit; // 签名覆盖的文件大小 (即 SuperBlob 起始偏移)
uint8_t hashSize; // 32 (SHA256)
uint8_t hashType; // 2 (CS_HASHTYPE_SHA256)
uint8_t platform; // 0
uint8_t pageSize; // 14 (表示 1 << 14 = 16384 = 16KB)
uint32_t spare2;
};
```
### 7.2 严格合规的重签名流水线算法时序 (包含 LC_CODE_SIGNATURE 预占位)
> [!CAUTION]
> **两大签名底层陷阱**:
> 1. **`LC_CODE_SIGNATURE` 命令属于 Page 0**:`load_commands` 位于二进制头部,属于 Page 0(0 ~ 16KB 范围)。如果在计算代码页哈希之后再更新 `LC_CODE_SIGNATURE` 的 `dataoff` 和 `datasize`,会导致 Page 0 哈希瞬间失效!因此**必须预先在 Header 中完成 `LC_CODE_SIGNATURE` 的位置与大小占位**,再执行分页代码哈希!
> 2. **CMS 签名的真实入参**:苹果规范中,CMS `signedData` 签名封装的是**完整的 `CodeDirectory` 序列化二进制字节数据**(作为 SignedContent 或 Authenticated Attributes),绝非仅对 32 字节的 CDHash 做简单签名。
```mermaid
sequenceDiagram
autonumber
participant Runner as 签名调度器
participant Prov as Mobileprovision 与 Entitlements 协调
participant Dylibs as Frameworks/PlugIns (内部组件)
participant Res as CodeResources 资源清单
participant MachO as 主可执行文件 Header
participant CMS as OpenSSL 签名核
Runner->>Prov: 解析 embedded.mobileprovision 提取授权范围
Runner->>Prov: 协调并生成目标所需 Entitlements (XML + DER 编码)
Runner->>Dylibs: 先行签名内部 Frameworks/*.dylib 与 *.framework
Runner->>Dylibs: 先行签名 PlugIns/*.appex (独立 Entitlements 与 BundleID)
Runner->>Res: 扫描 Bundle 全部文件生成 _CodeSignature/CodeResources
Runner->>MachO: 预先计算 SuperBlob 大小,在 Mach-O Header 预设 LC_CODE_SIGNATURE (dataoff=codeLimit, datasize=blob_size)
Runner->>MachO: 将 CodeResources 哈希填入 CodeDirectory Slot -3
Runner->>MachO: 将 Info.plist、Entitlements 哈希填入 Slot -1, -2, -5, -7
Runner->>MachO: 计算 0..codeLimit 范围内的每 16KB 代码页 SHA256,填入 Slot 0..N
Runner->>CMS: 传入完整的 CodeDirectory 序列化字节,由 OpenSSL 使用私钥生成 CMS PKCS#7 签名
Runner->>MachO: 组装 SuperBlob (包含 0, 2, 5, 7, 0x10000 槽位),写入 dataoff
Runner->>Runner: 重新打包压缩为 .ipa
```
---
## 8. IPA 相似度预检中心 (App Store 4.3 预检器)
### 8.1 算法模型设计与免责边界
App Store 4.3 审核(Design: Spam)属于苹果人工审核与机审结合的行为规范策略,旨在遏制重复马甲包与克隆 App。**任何静态相似度工具均无法保证 100% 过审**。
iOSGuard 的相似度模型定位于**企业内部风控与差异化基准度量工具**:
$$\text{InternalRiskScore} = 0.45 \cdot \text{Sim}_{\text{Code}} + 0.35 \cdot \text{Sim}_{\text{Symbol}} + 0.20 \cdot \text{Sim}_{\text{Asset}}$$
```mermaid
graph TD
A["待测 IPA vs 基线母包 IPA"] --> B["Mach-O __text 提取\nSSDEEP (CTPH) 模糊哈希"]
A --> C["符号表导出\nJaccard 集合交并比计算"]
A --> D["图片媒体提取\n感知哈希 (pHash) 汉明距离计算"]
B --> E["加权综合评分算法"]
C --> E
D --> E
E --> F{"内部风控基准评分"}
F -- "< 35%" --> G["内部低相似度 (特征分化充分)"]
F -- "35% ~ 50%" --> H["内部中度相似 (建议调换混淆特征库)"]
F -- "> 50%" --> I["内部高相似度风险 (建议阻断提审)"]
```
### 8.2 核心算法实现:基于 SSDEEP 的机器码片段比对
```python
import ssdeep
def calculate_macho_code_similarity(macho_path_a, macho_path_b):
# 提取 __TEXT, __text 机器指令二进制段
bytes_a = extract_text_section(macho_path_a)
bytes_b = extract_text_section(macho_path_b)
# 计算 CTPH 模糊哈希
hash_a = ssdeep.hash(bytes_a)
hash_b = ssdeep.hash(bytes_b)
# 计算相似度 (0 ~ 100)
score = ssdeep.compare(hash_a, hash_b)
return score
```
### 8.3 符号表 Jaccard 系数计算
```python
def calculate_symbol_similarity(symbols_a: set, symbols_b: set) -> float:
intersection = len(symbols_a.intersection(symbols_b))
union = len(symbols_a.union(symbols_b))
if union == 0:
return 0.0
return (intersection / union) * 100.0
```