23 KiB
iOSGuard 八大核心子系统详细设计与实现方案
本文档为 iOSGuard 企业级加固系统的八大核心子系统技术白皮书。每个子系统均提供:设计目标、核心数据结构与接口、底层算法与实现流程、汇编与代码原型、技术陷阱与规避策略。
目录
- 子系统 1:Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)
- 子系统 2:Class-Dump 彻底防御与动态重映射 (Metadata Protector)
- 子系统 3:原生代码虚拟化 (VMP) 引擎 (Code Virtualization)
- 子系统 4:全维度内核级主动防御对抗矩阵 (Defender Core)
- 子系统 5:双符号表体系与 dSYM 崩溃逆向还原 (Dual-Symbol & Crash Restorer)
- 子系统 6:资产保护与无感透明解密 (Virtual File System & Assets Protector)
- 子系统 7:跨平台自动化重签名流水线 (Cross-Platform Signer Engine)
- 子系统 8:IPA 相似度预检中心 (App Store 4.3 预检器)
1. Mach-O 深度重构与二进制引擎 (Mach-O Rewriter)
1.1 设计目标
在无源码条件下解析 IPA 中的主 Mach-O 与 Dynamic Frameworks,完成:
- 安全注入
LC_LOAD_DYLIB加载加固守护动态库libDefender.dylib; - 新增私有加密段
__PROTECT(存放抽取函数、加密元数据、白盒查找表); - 严格遵循 ARM64
0x4000(16KB)页面对齐规范,保证重签名后 AMFI 校验通过。
1.2 核心数据结构
#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 底层算法与平移逻辑
flowchart TD
A["读取 mach_header_64 & load_commands"] --> B{"计算 Header Padding\n首个Section偏移 - (header + sizeofcmds)"}
B -- "Padding >= sizeof(dylib_command)" --> C["直接就地追加 LC_LOAD_DYLIB\n递增 ncmds & sizeofcmds"]
B -- "Padding 不足" --> D["执行全局段平移 (Segment Shift)\n平移增量 Delta = 0x4000 (16KB)"]
D --> E["更新所有 Segment fileoff >= Delta\n更新 Section.offset, Rebase, Binding, Export Trie"]
C --> F["追加 __PROTECT Segment (0x4000对齐)"]
E --> F
F --> G["重设 LC_CODE_SIGNATURE 指向文件末尾"]
代码实现原型:Header 扩容与 LC_LOAD_DYLIB 注入
bool InjectDylib(std::vector<uint8_t>& binary, const std::string& dylib_path) {
auto* header = reinterpret_cast<mach_header_64*>(binary.data());
if (header->magic != MH_MAGIC_64) return false;
// 1. 计算对齐后的 dylib_command 大小
uint32_t cmd_size = sizeof(dylib_command) + dylib_path.length() + 1;
cmd_size = (cmd_size + 7) & ~7; // 8 字节对齐
// 2. 检测 Header Padding
uint8_t* cmds_start = binary.data() + sizeof(mach_header_64);
uint8_t* cmds_end = cmds_start + header->sizeofcmds;
// 查找第一个 Section 的起始文件偏移 (通常在 __TEXT 段)
uint32_t first_section_offset = UINT32_MAX;
uint8_t* cur_cmd = cmds_start;
for (uint32_t i = 0; i < header->ncmds; i++) {
auto* sc = reinterpret_cast<segment_command_64*>(cur_cmd);
if (sc->cmd == LC_SEGMENT_64) {
auto* sec = reinterpret_cast<section_64*>(cur_cmd + sizeof(segment_command_64));
for (uint32_t j = 0; j < sc->nsects; j++) {
if (sec[j].offset > 0 && sec[j].offset < first_section_offset) {
first_section_offset = sec[j].offset;
}
}
}
cur_cmd += sc->cmdsize;
}
uint32_t available_padding = first_section_offset - (sizeof(mach_header_64) + header->sizeofcmds);
if (available_padding >= cmd_size) {
// 直接原地写入
auto* new_cmd = reinterpret_cast<dylib_command*>(cmds_end);
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;
} else {
// 触发全局段平移 ShiftSegment(binary, 0x4000);
return ShiftAndInjectDylib(binary, dylib_path, cmd_size);
}
}
1.4 避坑要点
- 0x4000 严格对齐:ARM64 架构下,
__TEXT、__DATA以及新增的__PROTECT段的vmaddr和fileoff必须是0x4000(16KB)的整倍数,否则 dyld 报错file system page size mismatch。 - Linkedit 偏移调整:
LC_CODE_SIGNATURE、LC_SYMTAB必须保持位于文件末尾。新增段时应插入在__LINKEDIT之前。
2. Class-Dump 彻底防御与动态重映射 (Metadata Protector)
2.1 设计目标
消除 Mach-O 静态暴露的所有 Objective-C 类名、分类、选择器和属性元数据,使 class-dump、dscli、Hopper、IDA 彻底无法还原符号;同时通过运行时受控动态注册,确保 objc_msgSend 与 KVC 正常运作。
2.2 Objective-C 64位运行时结构体解构
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
uint64_t imp; // 函数指针
};
2.3 加固与还原流程
[编译加固期 (Mach-O 离线重写)]
1. 扫描 __DATA,__objc_classlist 提取所有 class_ro_t 信息
2. 序列化 {ClassName, [Selector, ImpOffset, Type]} 结构为二进制数据
3. 使用 ChaCha20-Poly1305 加密存入 __PROTECT,__meta 节
4. 清空 __TEXT,__objc_methname (填 '\0'),将 class_ro_t->baseMethods 置空
│
▼
[运行时阶段 (libDefender 早期构造器 __mod_init_func)]
1. 读取 __PROTECT 段并使用内嵌白盒秘钥解密元数据
2. 遍历类对象,调用 objc_allocateClassPair / class_addMethod 动态注回
3. 拦截 NSClassFromString 与 sel_registerName 桥接映射
运行时动态重映射 Hook 原型
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
void RestoreObjcMetadata(const uint8_t *decrypted_meta, size_t size) {
size_t offset = 0;
while (offset < size) {
// 读取类名长度和字符串
uint16_t name_len = *(uint16_t*)(decrypted_meta + offset);
offset += 2;
char class_name[256] = {0};
memcpy(class_name, decrypted_meta + offset, name_len);
offset += name_len;
Class cls = objc_getClass(class_name);
// 读取方法数量
uint32_t method_count = *(uint32_t*)(decrypted_meta + offset);
offset += 4;
for (uint32_t i = 0; i < method_count; i++) {
uint16_t sel_len = *(uint16_t*)(decrypted_meta + offset);
offset += 2;
char sel_name[256] = {0};
memcpy(sel_name, decrypted_meta + offset, sel_len);
offset += sel_len;
uint64_t imp_addr = *(uint64_t*)(decrypted_meta + offset);
offset += 8;
SEL sel = sel_registerName(sel_name);
class_addMethod(cls, sel, (IMP)imp_addr, "v@:");
}
}
}
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 跳转循环实现原型
#include <stdint.h>
#include <stdlib.h>
typedef struct {
uint64_t r[31]; // 对应 ARM64 x0 - x30
uint64_t sp; // 虚拟栈指针
uint64_t flags; // 标志位 NZCV
uint64_t ret_val; // 返回值
} VMContext;
uint64_t VMP_Execute(const uint8_t *bytecode, uint64_t arg0, uint64_t arg1) {
VMContext ctx;
ctx.r[0] = arg0;
ctx.r[1] = arg1;
ctx.sp = (uint64_t)malloc(4096) + 4096; // 分配独立虚拟栈
const uint8_t *pc = bytecode;
// 静态直接线程标签跳转表 (极致性能且无条件分支预测惩罚)
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() goto *dispatch_table[*pc]
DISPATCH();
op_mov_imm: {
uint8_t dst = pc[1];
uint8_t imm = pc[3];
ctx.r[dst] = imm;
pc += 4;
DISPATCH();
}
op_add: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
ctx.r[dst] += ctx.r[src];
pc += 4;
DISPATCH();
}
op_xor: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
ctx.r[dst] ^= ctx.r[src];
pc += 4;
DISPATCH();
}
op_load64: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
ctx.r[dst] = *(uint64_t*)(ctx.r[src]);
pc += 4;
DISPATCH();
}
op_store64: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
*(uint64_t*)(ctx.r[dst]) = ctx.r[src];
pc += 4;
DISPATCH();
}
op_cmp: {
uint8_t dst = pc[1];
uint8_t src = pc[2];
ctx.flags = (ctx.r[dst] == ctx.r[src]) ? 1 : 0; // 模拟 Z 标志
pc += 4;
DISPATCH();
}
op_jz: {
int8_t offset = (int8_t)pc[3];
if (ctx.flags == 1) {
pc += offset * 4;
} else {
pc += 4;
}
DISPATCH();
}
op_ret: {
uint64_t result = ctx.r[0];
free((void*)(ctx.sp - 4096));
return result;
}
}
4. 全维度内核级主动防御对抗矩阵 (Defender Core)
4.1 内联汇编 SVC 0x80 反调试 (Anti-Debug)
不使用 libc 导出的 ptrace,使用裸汇编直接触发 XNU 系统调用 26 号中断(SYS_ptrace):
__attribute__((always_inline)) static inline void anti_debug_svc_ptrace() {
#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
}
4.2 硬件断点 (DR0-DR7) 探测
攻击者在 LLDB 或调试器中下硬件断点时,会写入 ARM64 调试寄存器。通过 thread_get_state 轮询检查:
#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):
#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:
__DWARF,__debug_info:树状结构的 DIE(Debugging Information Entries),包含DW_TAG_subprogram(函数)和属性DW_AT_name、DW_AT_linkage_name。__DWARF,__debug_str:字符串常量池(以\0分隔)。DIE 中的DW_FORM_strp属性存储指向该池的文件偏移。__DWARF,__debug_line:行号状态机字节码,映射机器指令地址与源码行号。
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 重构伪代码原型
def restore_dsym(dsym_path, mapping_dict, output_path):
# 1. 打开 DWARF 调试文件
with open(dsym_path, "r+b") as f:
macho = MachO(f)
debug_str_section = macho.get_section("__DWARF", "__debug_str")
debug_info_section = macho.get_section("__DWARF", "__debug_info")
# 2. 扫描并替换符号
str_data = bytearray(debug_str_section.data)
for obfuscated, original in mapping_dict.items():
obf_bytes = obfuscated.encode('utf-8')
orig_bytes = original.encode('utf-8')
# 若等长替换直接原位覆写
if len(orig_bytes) <= len(obf_bytes):
padded_orig = orig_bytes.ljust(len(obf_bytes), b'\x00')
str_data = str_data.replace(obf_bytes, padded_orig)
else:
# 不等长则需调整 .debug_str 长度并修复 DIE 偏移
str_data = append_and_fix_die_offsets(debug_info_section, str_data, obf_bytes, orig_bytes)
debug_str_section.write(str_data)
macho.save(output_path)
6. 资产保护与无感透明解密 (Virtual File System & Assets Protector)
6.1 PNG 免解密 Hash 扰动(应对 2.3.1 / 4.3 静态排查)
在不破坏图片展示的前提下修改图片 MD5/SHA256。PNG 格式由固定 8 字节签名加上多个 Chunk 组成。规范允许插入合规私有辅助 Chunk(如 tEXt):
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。
#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
#include <stdint.h>
#define CSMAGIC_CODEDIRECTORY 0xfade0c02
#define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
#define CSMAGIC_ENTITLEMENTS 0xfade7171
#define CSMAGIC_DER_ENTITLEMENTS 0xfade7172
struct BlobIndex {
uint32_t type; // 0: CodeDirectory, 5: Entitlements, 7: DER Entitlements, 0x10000: CMS Signature
uint32_t offset; // 指向 Blob 距离 SuperBlob 起始处的偏移
};
struct SuperBlob {
uint32_t magic; // CSMAGIC_EMBEDDED_SIGNATURE
uint32_t length; // 整个 SuperBlob 大小
uint32_t count; // 包含的 Blob 数量
BlobIndex index[];
};
struct CodeDirectory {
uint32_t magic; // CSMAGIC_CODEDIRECTORY
uint32_t length; // 本结构体大小
uint32_t version; // 0x20400
uint32_t flags; // 0
uint32_t hashOffset; // 哈希数组距头部的偏移
uint32_t identOffset; // Bundle Identifier 字符串偏移
uint32_t nSpecialSlots; // 负数槽位数量 (Info.plist, Requirements, CodeResources)
uint32_t nCodeSlots; // 页面正数槽位数量
uint32_t codeLimit; // 签名覆盖的文件大小 (排除签名本身)
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 签名流水线完整算法时序
- 解析描述文件 (
embedded.mobileprovision):- 提取
Entitlements(XML 格式); - 通过 ASN.1 编码生成二进制的 DER Entitlements(iOS 15+ 强制要求)。
- 提取
- Inside-Out 递归遍历:
Payload/App.app/Frameworks/*.dylibPayload/App.app/Frameworks/*.frameworkPayload/App.app/PlugIns/*.appex
- 计算 Mach-O 16KB 分页哈希:
- 循环计算二进制文件每个 16384 字节区块的 SHA256,填入
CodeDirectory.hashOffset数组。
- 循环计算二进制文件每个 16384 字节区块的 SHA256,填入
- 生成 CMS (PKCS#7) 签名:
- 对
CodeDirectory整体计算 SHA256,生成 CDHash; - 使用证书私钥通过 OpenSSL 调用
PKCS7_sign签名 CDHash。
- 对
- 组装 SuperBlob 并写回:
- 将
CodeDirectory、Requirements、Entitlements、DER Entitlements、CMS Signature封包写入 Mach-O 尾部,更新LC_CODE_SIGNATURE。
- 将
- 输出
_CodeSignature/CodeResources:- 扫描 Bundle 内部全部资源文件生成 XML Plist 资源哈希字典。
8. IPA 相似度预检中心 (App Store 4.3 预检器)
8.1 算法模型设计
App Store 4.3 审核主要基于机器码静态散列相似度、符号集重合度与媒体资源指纹。iOSGuard 采用三维综合加权评估模型:
\text{RiskScore} = w_1 \cdot \text{Sim}_{\text{Code}} + w_2 \cdot \text{Sim}_{\text{Symbol}} + w_3 \cdot \text{Sim}_{\text{Asset}}
其中权重推荐值:w_1 = 0.45, w_2 = 0.35, $w_3 = 0.20$。
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{"RiskScore 判定"}
F -- "< 35%" --> G["安全 (可通过审核)"]
F -- "35% ~ 50%" --> H["中度风险 (建议调整符号库)"]
F -- "> 50%" --> I["极高风险 (4.3拒审高发,阻断发布)"]
8.2 核心算法实现:基于 SSDEEP 的机器码片段比对
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 系数计算
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