harden(defender): docs/18 §7 抗静态分析硬化(符号隐藏/串混淆/副本分散/基线派生)

针对「纯客户端抗静态分析」的最高性价比项落地,守在 tests/test_static_hardening.py(6 条,gate 于 iphoneos SDK):

- 符号隐藏 + strip(§7.0 新增):IGVisibility.h 定 IG_INTERNAL=hidden,全库
  -fvisibility=hidden;仅四入口 ig_defender_scan/ig_poison_init/ig_poison_apply/
  ig_policy_scan_and_mark 标 IG_PUBLIC 保持导出,其余 ig_* 变 private external,
  链接后 strip -x 彻底消失——攻击者 nm 不再能按名定位 ig_poison_mark/mask 去 NOP。
- §7.1 串混淆:gen_jb_paths.py(唯一真源)生成 IGJailbreakPaths.inc /
  IGInjectSignatures.inc(XOR keystream,两表不共享 key),运行期解码进栈、用完擦除;
  decode 内 volatile key 屏障阻止 -O2 把常量折叠回 __const 明文。strings 已捞不到
  /var/jb、Cydia、substrate、gum-js-loop 等。--check 守 .inc 与清单同步。
- §7.2 副本分散:g_h0/h1/h2 置于不相邻命名段 __DATA,__ig_p0/p1/p2,加 __ig_pd 诱饵
  (mask 不读);刻意不用 TLS(会破坏跨线程毒化一致性)。
- §7.4 基线派生:删硬编码 0xA5C3F10E7B2D4968,改 ig_poison_baseline() 由拆分种子经
  volatile 屏障派生;otool -tV 已无旧魔数立即数。
- §7.3 OLLVM/VMP:仅留 build 的 IG_OBFUSCATOR hook,stock clang 无能力,需另备工具链(未完成)。
- §7.5 越狱设备正向验证仍阻塞(无设备)。

构建/快照同步:build_defender_lib.sh 加 -fvisibility=hidden + gen --check + IG_OBFUSCATOR
hook;build_poison_device.py 快照纳入 *.inc。全量 69 测试通过;poison_device.m 全模块
iphoneos 交叉编译通过(arm64)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-11-13 10:47:35 +09:00
co-authored by Claude Opus 4.8
parent 60d868a351
commit b76d7cdc21
14 changed files with 531 additions and 70 deletions
+37 -17
View File
@@ -47,18 +47,26 @@ static const char *ig_local_getenv(const char *name) {
return NULL;
}
/* 已知注入 / 调试 / 越狱增强框架的镜像名子串(小写)。 */
static const char *const kInjectSignatures[] = {
"frida", "gadget", "cynject", "cycript", "libcycript",
"substrate", "substitute", "libsubstrate", "tweakinject",
"rocketbootstrap", "reveal", "flexloader", "libhooker",
"shadowhook", "dobby", "fishhook",
};
/*
* §7.1 IG_ENC:注入特征串与 frida 线程名不再明文驻留(避免 `strings` 捞出 frida/substrate/
* gum-js-loop 等,白送检测目标)。混淆表由 tools/gen_jb_paths.py 生成,运行期解码进栈。
*/
#include "IGInjectSignatures.inc"
/* 已知 frida 线程名。 */
static const char *const kFridaThreads[] = {
"gum-js-loop", "gmain", "gdbus", "pool-frida", "pool-spawner", "linjector",
};
/* 解码单条混淆串到 out(容量 cap,含结尾 0)。返回长度,失败返回 0。
* k0 取 volatile:阻止 -O2 把「常量 enc + 常量 key」整条折叠回明文存入 __const
* (否则 strings 又能捞出 frida/gum-js-loop)。强制运行期解码。 */
static size_t ig_inj_decode(const unsigned char *enc, size_t n, int idx,
char *out, size_t cap) {
volatile unsigned k0 = IG_INJ_XOR_K0;
if (n + 1 > cap) return 0;
for (size_t j = 0; j < n; ++j) {
unsigned ks = ((unsigned)k0 + (unsigned)idx * IG_INJ_XOR_K1 + j * IG_INJ_XOR_K2) & 0xFFu;
out[j] = (char)(enc[j] ^ ks);
}
out[n] = '\0';
return n;
}
static void ig_emit2(IGFindingSink sink, void *ctx, int *stop, int *hits,
IGStatus st, int reason, const char *subject, const char *evidence) {
@@ -94,6 +102,11 @@ static int ig_is_system_path2(const char *path) {
int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx) {
int hits = 0, stop = 0;
/* §7.1:特征串运行期解码进栈,循环内用解码副本;函数退出前擦除。 */
char injsig[IG_INJ_ENC_COUNT][24];
for (int s = 0; s < IG_INJ_ENC_COUNT; ++s)
ig_inj_decode(kIGInjEnc[s].b, kIGInjEnc[s].n, s, injsig[s], sizeof(injsig[s]));
/* 1+2. 镜像扫描。 */
uint32_t imgc = _dyld_image_count();
for (uint32_t i = 0; i < imgc && !stop; ++i) {
@@ -109,10 +122,10 @@ int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx)
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])) {
for (int s = 0; s < IG_INJ_ENC_COUNT; ++s) {
if (ig_strstr(low, injsig[s])) {
char ev[256];
snprintf(ev, sizeof(ev), "镜像=%s 命中特征=%s", name, kInjectSignatures[s]);
snprintf(ev, sizeof(ev), "镜像=%s 命中特征=%s", name, injsig[s]);
ig_emit2(sink, ctx, &stop, &hits, IG_DETECTED, IG_REASON_INJECTED_IMAGE, name, ev);
matched = 1;
break;
@@ -146,6 +159,7 @@ int ig_anti_inject_check(const char *bundle_path, IGFindingSink sink, void *ctx)
}
}
}
__builtin_memset(injsig, 0, sizeof(injsig));
return hits;
}
@@ -158,16 +172,21 @@ static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits)
"task_threads", "无法枚举线程");
return;
}
/* §7.1:frida 线程名运行期解码进栈,比对后擦除。 */
char thr[IG_THR_ENC_COUNT][24];
for (int t = 0; t < IG_THR_ENC_COUNT; ++t)
ig_inj_decode(kIGThrEnc[t].b, kIGThrEnc[t].n, t, thr[t], sizeof(thr[t]));
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) {
for (int t = 0; t < IG_THR_ENC_COUNT; ++t) {
if (ig_strcmp(info.pth_name, thr[t]) == 0) {
char ev[256];
snprintf(ev, sizeof(ev), "线程名=%s 命中 frida 特征", info.pth_name);
snprintf(ev, sizeof(ev), "线程名=%s 命中注入运行时特征", info.pth_name);
ig_emit2(sink, ctx, stop, hits, IG_DETECTED, IG_REASON_FRIDA_THREAD,
info.pth_name, ev);
break;
@@ -175,6 +194,7 @@ static void ig_scan_threads(IGFindingSink sink, void *ctx, int *stop, int *hits)
}
if (*stop) break;
}
__builtin_memset(thr, 0, sizeof(thr));
/* 回收端口。 */
for (mach_msg_type_number_t i = 0; i < count; ++i) {
mach_port_deallocate(mach_task_self(), threads[i]);
@@ -0,0 +1,34 @@
/* IGInjectSignatures.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */
/* 注入/Frida 特征串 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */
#define IG_INJ_XOR_K0 0x3cu
#define IG_INJ_XOR_K1 0x47u
#define IG_INJ_XOR_K2 0x1du
static const unsigned char kIGInjEnc0[] = { 0x5a, 0x2b, 0x1f, 0xf7, 0xd1 }; /* len=5 */
static const unsigned char kIGInjEnc1[] = { 0xe4, 0xc1, 0xd9, 0xbd, 0x92, 0x60 }; /* len=6 */
static const unsigned char kIGInjEnc2[] = { 0xa9, 0x9e, 0x6a, 0x4b, 0x5b, 0x38, 0x0c }; /* len=7 */
static const unsigned char kIGInjEnc3[] = { 0x72, 0x57, 0x28, 0x1a, 0xec, 0xd2, 0xcb }; /* len=7 */
static const unsigned char kIGInjEnc4[] = { 0x34, 0x1c, 0xf0, 0xcc, 0xb5, 0x8a, 0x74, 0x4a, 0x30, 0x29 }; /* len=10 */
static const unsigned char kIGInjEnc5[] = { 0xec, 0xc9, 0xbb, 0x85, 0x67, 0x42, 0x2c, 0x1e, 0xe2 }; /* len=9 */
static const unsigned char kIGInjEnc6[] = { 0x95, 0x76, 0x42, 0x4e, 0x2e, 0x1e, 0xe0, 0xc4, 0xba, 0x8e }; /* len=10 */
static const unsigned char kIGInjEnc7[] = { 0x41, 0x23, 0x05, 0xf7, 0xd4, 0xdc, 0xa8, 0x8c, 0x67, 0x53, 0x3b, 0x09 }; /* len=12 */
static const unsigned char kIGInjEnc8[] = { 0x00, 0xe6, 0xcb, 0xaa, 0x83, 0x6c, 0x4c, 0x55, 0x39, 0x1a, 0xe2 }; /* len=11 */
static const unsigned char kIGInjEnc9[] = { 0xc9, 0xb7, 0x96, 0x79, 0x4a, 0x38, 0x0b, 0xe9, 0xcc, 0xb4, 0xae, 0x8e, 0x65, 0x55, 0x21 }; /* len=15 */
static const unsigned char kIGInjEnc10[] = { 0x70, 0x7a, 0x4a, 0x3c, 0x17, 0xff }; /* len=6 */
static const unsigned char kIGInjEnc11[] = { 0x2f, 0x0a, 0xe6, 0xd8, 0xd1, 0xb5, 0x96, 0x70, 0x54, 0x3c }; /* len=10 */
static const unsigned char kIGInjEnc12[] = { 0xfc, 0xc4, 0xa8, 0x8f, 0x6b, 0x4e, 0x55, 0x3e, 0x0a }; /* len=9 */
static const unsigned char kIGInjEnc13[] = { 0xa4, 0x9c, 0x70, 0x4a, 0x24, 0x1f, 0xed, 0xcd, 0xd0, 0xb7 }; /* len=10 */
static const unsigned char kIGInjEnc14[] = { 0x7a, 0x54, 0x3a, 0x17, 0xeb }; /* len=5 */
static const unsigned char kIGInjEnc15[] = { 0x03, 0xeb, 0xec, 0xd4, 0xb1, 0x99, 0x7c, 0x5b }; /* len=8 */
static const struct { const unsigned char *b; unsigned char n; } kIGInjEnc[] = { { kIGInjEnc0, 5 }, { kIGInjEnc1, 6 }, { kIGInjEnc2, 7 }, { kIGInjEnc3, 7 }, { kIGInjEnc4, 10 }, { kIGInjEnc5, 9 }, { kIGInjEnc6, 10 }, { kIGInjEnc7, 12 }, { kIGInjEnc8, 11 }, { kIGInjEnc9, 15 }, { kIGInjEnc10, 6 }, { kIGInjEnc11, 10 }, { kIGInjEnc12, 9 }, { kIGInjEnc13, 10 }, { kIGInjEnc14, 5 }, { kIGInjEnc15, 8 } };
#define IG_INJ_ENC_COUNT 16
static const unsigned char kIGThrEnc0[] = { 0x5b, 0x2c, 0x1b, 0xbe, 0xda, 0xbe, 0xc7, 0x6b, 0x4b, 0x2e, 0x2e }; /* len=11 */
static const unsigned char kIGThrEnc1[] = { 0xe4, 0xcd, 0xdc, 0xb3, 0x99 }; /* len=5 */
static const unsigned char kIGThrEnc2[] = { 0xad, 0x83, 0x66, 0x54, 0x4d }; /* len=5 */
static const unsigned char kIGThrEnc3[] = { 0x61, 0x41, 0x24, 0x04, 0xa8, 0xc4, 0xcd, 0xb5, 0x9d, 0x77 }; /* len=10 */
static const unsigned char kIGThrEnc4[] = { 0x28, 0x1a, 0xfd, 0xc3, 0xe1, 0x9a, 0x76, 0x42, 0x37, 0x33, 0x1f, 0xe5 }; /* len=12 */
static const unsigned char kIGThrEnc5[] = { 0xf3, 0xd5, 0xb7, 0x9c, 0x76, 0x53, 0x39, 0x05, 0xf5 }; /* len=9 */
static const struct { const unsigned char *b; unsigned char n; } kIGThrEnc[] = { { kIGThrEnc0, 11 }, { kIGThrEnc1, 5 }, { kIGThrEnc2, 5 }, { kIGThrEnc3, 10 }, { kIGThrEnc4, 12 }, { kIGThrEnc5, 9 } };
#define IG_THR_ENC_COUNT 6
+36 -21
View File
@@ -17,23 +17,27 @@
/*
* 内置 iOS 越狱特征(强信号)。沙盒内正常 App 对这些路径 access 应得 -ENOENT/-EPERM;
* 能访问即越狱。rootless 越狱重点在 /var/jb。TODO:改为 IG_ENC XOR 混淆,勿明文驻留。
* 能访问即越狱。rootless 越狱重点在 /var/jb。
*
* §7.1 IG_ENC:路径不再明文驻留——由 tools/gen_jb_paths.py 生成的 XOR 混淆表引入,
* 运行期解码进栈缓冲、用完擦除,`strings` 捞不到 /var/jb、Cydia、substrate 等常量。
*/
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",
};
#include "IGJailbreakPaths.inc"
/* 解码单条混淆路径到 out(容量 cap,含结尾 0)。返回长度,失败返回 0。
* k0 取 volatile:阻止 -O2 把「常量 enc + 常量 key」整条折叠回明文存入 __const
* (否则混淆被优化器击穿,strings 又能捞出)。强制运行期解码。 */
static size_t ig_jb_decode(const unsigned char *enc, size_t n, int idx,
char *out, size_t cap) {
volatile unsigned k0 = IG_JB_XOR_K0;
if (n + 1 > cap) return 0;
for (size_t j = 0; j < n; ++j) {
unsigned ks = ((unsigned)k0 + (unsigned)idx * IG_JB_XOR_K1 + j * IG_JB_XOR_K2) & 0xFFu;
out[j] = (char)(enc[j] ^ ks);
}
out[n] = '\0';
return n;
}
static void ig_jb_emit(IGFindingSink sink, void *ctx, int *hits,
IGStatus st, int reason, const char *subject, const char *evidence) {
@@ -80,9 +84,20 @@ int ig_anti_jb_check_paths(const char *const *paths, size_t count,
}
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);
/* §7.1:把混淆表运行期解码进栈,构建 ptr 数组喂给通用入口,用完擦除,不留明文。 */
char storage[IG_JB_ENC_COUNT][128];
const char *ptrs[IG_JB_ENC_COUNT];
for (int i = 0; i < IG_JB_ENC_COUNT; ++i) {
ig_jb_decode(kIGJbEnc[i].b, kIGJbEnc[i].n, i, storage[i], sizeof(storage[i]));
ptrs[i] = storage[i];
}
char probe[128];
ig_jb_decode(kIGJbProbeEnc, IG_JB_PROBE_LEN, IG_JB_PROBE_IDX, probe, sizeof(probe));
int hits = ig_anti_jb_check_paths(ptrs, IG_JB_ENC_COUNT, probe, sink, ctx);
/* 擦除解码后的明文,缩短其在内存驻留窗口(动态分析仍可抓,但抬高被动 dump 成本)。 */
__builtin_memset(storage, 0, sizeof(storage));
__builtin_memset(probe, 0, sizeof(probe));
return hits;
}
@@ -0,0 +1,28 @@
/* IGJailbreakPaths.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */
/* 越狱路径 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */
#define IG_JB_XOR_K0 0x5au
#define IG_JB_XOR_K1 0x2fu
#define IG_JB_XOR_K2 0x13u
static const unsigned char kIGJbEnc0[] = { 0x75, 0x1b, 0xe1, 0xe1, 0x89, 0xd3, 0xae }; /* len=7 */
static const unsigned char kIGJbEnc1[] = { 0xa6, 0xdd, 0xdf, 0xb2, 0xb9, 0x81, 0x98, 0x6f, 0x55, 0x5d, 0x28, 0x34, 0x1e, 0xaf, 0xd0, 0xdf, 0xdd, 0xa5, 0xbe, 0xdc, 0x64, 0x68, 0x5b }; /* len=23 */
static const unsigned char kIGJbEnc2[] = { 0x97, 0x8a, 0xae, 0x81, 0x68, 0x7e, 0x49, 0x5c, 0x24, 0x0a, 0x19, 0xe7, 0xef, 0x80, 0x91, 0xbc, 0x84, 0x9e, 0x61, 0x0f, 0x55, 0x37, 0x2a }; /* len=23 */
static const unsigned char kIGJbEnc3[] = { 0xc8, 0xbb, 0x7d, 0x50, 0x5f, 0x2f, 0x3a, 0x0d, 0x0b, 0xfb, 0xca, 0xd6, 0xb8, 0xf1, 0xab, 0x61, 0x75, 0x58, 0x5c, 0x7e, 0x02, 0x06, 0xf9 }; /* len=23 */
static const unsigned char kIGJbEnc4[] = { 0x39, 0x5c, 0x4f, 0x3d, 0x4d, 0x06, 0xea, 0xf2, 0xc0, 0xee, 0xa7, 0x94, 0x92, 0x69 }; /* len=14 */
static const unsigned char kIGJbEnc5[] = { 0x6a, 0x2d, 0x18, 0x0c, 0xbe, 0xc6, 0xde, 0xa4, 0xf2, 0x83, 0x70, 0x7e }; /* len=12 */
static const unsigned char kIGJbEnc6[] = { 0x5b, 0xe5, 0xf3, 0xc3, 0xef, 0xb1, 0x87, 0x8a, 0x64 }; /* len=9 */
static const unsigned char kIGJbEnc7[] = { 0x8c, 0xd4, 0xa0, 0xb2, 0xc0, 0x71, 0x7d }; /* len=7 */
static const unsigned char kIGJbEnc8[] = { 0xfd, 0x80, 0x8c, 0x68, 0x31, 0x50, 0x34, 0x23 }; /* len=8 */
static const unsigned char kIGJbEnc9[] = { 0x2e, 0x64, 0x55, 0x53, 0x3b, 0x01, 0x07, 0xe3, 0xb6, 0xda, 0xde, 0xa0, 0xca, 0x94, 0x62, 0x7c, 0x1e, 0x25, 0x27, 0x1e }; /* len=20 */
static const unsigned char kIGJbEnc10[] = { 0x1f, 0x36, 0x25, 0x1b, 0x53, 0xe3, 0xcb, 0xd7, 0xe7, 0xa8, 0x9b, 0x63, 0x67, 0x53, 0x48, 0x2c, 0x14, 0x16 }; /* len=18 */
static const unsigned char kIGJbEnc11[] = { 0x70, 0x3e, 0xec, 0xfa, 0xd9, 0xdf, 0xa3, 0x9d, 0xd8, 0x47, 0x72, 0x52, 0x2a, 0x3a, 0x0c, 0x2f, 0xfa, 0xc0, 0xc6, 0xbc, 0xa9, 0x8f, 0x75, 0x71, 0x08, 0x77, 0x22, 0x02, 0x1a, 0xea, 0xfc, 0xff, 0xca, 0xb0, 0x96, 0x8c, 0x79, 0x7f, 0x45, 0x21, 0x79, 0x0e, 0x04, 0xfc, 0xca, 0xd4 }; /* len=46 */
static const unsigned char kIGJbEnc12[] = { 0xa1, 0xd4, 0xc7, 0xb5, 0xf5, 0x81, 0x69, 0x71, 0x09, 0x6d, 0x3b, 0x3a, 0x13, 0xee, 0xd1, 0xc5, 0xd4, 0xb4, 0x87, 0x83 }; /* len=20 */
static const struct { const unsigned char *b; unsigned char n; } kIGJbEnc[] = { { kIGJbEnc0, 7 }, { kIGJbEnc1, 23 }, { kIGJbEnc2, 23 }, { kIGJbEnc3, 23 }, { kIGJbEnc4, 14 }, { kIGJbEnc5, 12 }, { kIGJbEnc6, 9 }, { kIGJbEnc7, 7 }, { kIGJbEnc8, 8 }, { kIGJbEnc9, 20 }, { kIGJbEnc10, 18 }, { kIGJbEnc11, 46 }, { kIGJbEnc12, 20 } };
#define IG_JB_ENC_COUNT 13
/* 沙盒逃逸探测路径(idx 用一个与上表不冲突的独立下标)。 */
static const unsigned char kIGJbProbeEnc[] = { 0x8a, 0xc8, 0xb9, 0xb7, 0x87, 0x65, 0x63, 0x4f, 0x12, 0x7e, 0x0a, 0x11, 0xd6, 0xf6, 0xcd, 0x9d, 0xa5, 0x9a, 0x94, 0x6c, 0x44 }; /* len=21 */
#define IG_JB_PROBE_LEN 21
#define IG_JB_PROBE_IDX 0xa5
+3 -1
View File
@@ -13,6 +13,8 @@
#include <stdint.h>
#include <stddef.h>
#include "IGVisibility.h"
#ifdef __cplusplus
extern "C" {
#endif
@@ -69,7 +71,7 @@ typedef int (*IGFindingSink)(const IGFinding *finding, void *ctx);
* probe_port:非 0 时才做 frida 端口弱探测(典型 27042);0 表示跳过。
* 返回 DETECTED 证据总条数。本函数只采集不处置,绝不 exit。
*/
int ig_defender_scan(const char *bundle_path, int probe_port,
IG_PUBLIC int ig_defender_scan(const char *bundle_path, int probe_port,
IGFindingSink sink, void *ctx);
#ifdef __cplusplus
+33
View File
@@ -0,0 +1,33 @@
/*
* IGVisibility.h — 符号可见性控制(抗静态调用关系分析,§7 硬化)。
*
* 背景:静态库 .a 里所有全局函数默认都是导出符号(nm 显示 T),接入方链进 App 后,
* 若不 strip,_ig_poison_mark / _ig_poison_mask / _ig_policy_* 等**内部**符号名
* 会留在符号表,成为「nm 一把定位 → 找调用点 → NOP」的锚点。
*
* 策略:
* - 整个 defender 库用 -fvisibility=hidden 编译:默认所有符号隐藏(private extern)。
* - 只有接入方跨 bridging header 真正引用的入口用 IG_PUBLIC 显式导出:
* ig_defender_scan / ig_policy_scan_and_mark / ig_poison_init / ig_poison_apply。
* - 其余(mark/mask/sink/reset/evaluate/anti_jb_* 及各探针内部)保持 hidden,
* 最终 App 链接 + strip 后从符号表消失,nm 再也捞不到名字。
*
* 边界(如实声明):
* - 这不消除调用图的「边」(bl 仍在),只抹掉「节点的名字」——把定位成本从
* 「nm 一把」抬到「靠交叉引用 + 语义猜」。真正删边要靠内联(apply 揉进解密)
* 与间接化调用点,见 docs/18 §7。
* - 在 .a 阶段 hidden 符号仍可能以 private-extern 出现在**静态**符号表(nm 无 -g);
* 决定性的一步是最终镜像 strip。故接入方必须保持 Release 的 strip(见 docs/18 §7.0)。
*/
#ifndef IG_VISIBILITY_H
#define IG_VISIBILITY_H
#if defined(__GNUC__) || defined(__clang__)
#define IG_PUBLIC __attribute__((visibility("default")))
#define IG_INTERNAL __attribute__((visibility("hidden")))
#else
#define IG_PUBLIC
#define IG_INTERNAL
#endif
#endif /* IG_VISIBILITY_H */
+46 -18
View File
@@ -3,23 +3,46 @@
*
* 实现要点:
* - 三副本冗余、写法各异、均 volatile(防编译器把 (copy ^ BASELINE) 常量折叠回 0)。
* - 掩码由三副本与基线异或后按位或得出:健康时每副本==BASELINE → 全 0;毒化时非 0。
* - 掩码由三副本与基线异或后按位或得出:健康时每副本==基线 → 全 0;毒化时非 0。
* - 没有任何 `if (poisoned)` 控制流;处置是纯算术数据流。
*
* 后续硬化(本骨架未做,留 TODO):
* - 把三副本分散到不同存储域(TLS / 堆上结构 / 编码进业务数据的冗余位),而非都在 BSS。
* - mark / mask / apply 三个函数用 OLLVM(Fla+BCF) + 字符串/常量加密盖住(README 规划)。
* - 基线魔数不以明文入二进制:改为运行期由多来源派生,避免被静态定位后直接写回。
* §7 硬化(本次已落地):
* - §7.4 基线不再明文驻留:IG_POISON_BASELINE 宏删除,改 ig_poison_baseline() 运行期
* 由分片种子派生,volatile 屏障阻止折叠回单一 64bit 魔数写入常量区。
* - §7.2 三副本分散:g_h0/g_h1/g_h2 各置于独立命名 section(__DATA 内不相邻),
* 并维护一路诱饵 g_hd(init/mark 同步写、mask 不读),抬高「哪几路真正喂掩码」的辨识成本。
*
* §7 硬化(仍 TODO,需额外工具链,见 docs/18 §7.3):
* - mark / mask / apply 三个函数用 OLLVM(Fla+BCF) + 常量加密盖住;本库预留
* IG_OBFUSCATOR 编译钩子,默认构建不启用。
*/
#include "IGPoison.h"
/* 基线魔数:健康态三副本都等于它。TODO:改为运行期派生,勿明文驻留常量区。 */
#define IG_POISON_BASELINE 0xA5C3F10E7B2D4968ULL
/*
* §7.4 基线运行期派生:具体 bit 无语义要求(健康态三副本==基线即可,mask=copy^基线),
* 只要全程一致且非零。volatile 种子强制运行期求值,阻止整条链折叠回单一常量写入 __const。
*/
static uint64_t ig_poison_baseline(void) {
volatile uint64_t seed = 0x243F6A88ULL; /* 分片种子,非最终值 */
uint64_t x = (uint64_t)seed;
x ^= 0x85A308D3ULL;
x *= 0xFF51AFD7ED558CCDULL;
x ^= x >> 33;
x += 0x2545F4914F6CDD1DULL;
x ^= x >> 29;
return x | 1ULL; /* 保证非零 */
}
/* 三副本,volatile 防折叠。写法刻意不一致以抬高静态模式匹配成本。 */
static volatile uint64_t g_h0;
static volatile uint64_t g_h1;
static volatile uint64_t g_h2;
/*
* §7.2 三副本分散:各自独立 section,避免三者在 BSS 相邻被一眼框定为「一组健康值」。
* 仍是进程级全局(非 TLS)——毒化态必须跨线程一致:检测线程 mark 后,解密线程读到的
* 掩码必须同为非零,TLS 会让每线程各看各的、破坏处置闭环,故**刻意不用 TLS**。
*/
static volatile uint64_t g_h0 __attribute__((section("__DATA,__ig_p0")));
static volatile uint64_t g_h1 __attribute__((section("__DATA,__ig_p1")));
static volatile uint64_t g_h2 __attribute__((section("__DATA,__ig_p2")));
/* 诱饵副本:与真副本同步维护、写法相同,但 mask 永不读它。抬高静态辨识成本。 */
static volatile uint64_t g_hd __attribute__((section("__DATA,__ig_pd")));
/* 把 entropy 扩散成三个互不相同、且必非 0 的偏移量(保证任一副本都会偏离基线)。 */
static uint64_t ig_spread(uint64_t e, unsigned lane) {
@@ -31,9 +54,11 @@ static uint64_t ig_spread(uint64_t e, unsigned lane) {
}
void ig_poison_init(void) {
g_h0 = IG_POISON_BASELINE;
g_h1 = IG_POISON_BASELINE;
g_h2 = IG_POISON_BASELINE;
uint64_t b = ig_poison_baseline();
g_h0 = b;
g_h1 = b;
g_h2 = b;
g_hd = b; /* 诱饵同步,看起来与真副本无异 */
}
/* 构造期兜底初始化(若宿主未显式调用 ig_poison_init)。 */
@@ -44,15 +69,18 @@ void ig_poison_mark(uint64_t entropy) {
/* entropy 为 0 时仍强制非 0,避免“混入 0 = 不生效”。 */
uint64_t e = entropy ? entropy : 0xD1B54A32D192ED03ULL;
g_h0 ^= ig_spread(e, 0);
g_hd ^= ig_spread(e, 3); /* 诱饵也动,混淆“哪几路生效” */
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);
/* 健康:每项 ^基线 == 0 → 或起来为 0。毒化:至少一项非 0。无分支。
* 只读三路真副本,诱饵 g_hd 不参与——即便攻击者把 g_hd 写回基线也不影响掩码。 */
uint64_t b = ig_poison_baseline();
uint64_t m = (g_h0 ^ b)
| (g_h1 ^ b)
| (g_h2 ^ b);
return m;
}
+4 -2
View File
@@ -23,12 +23,14 @@
#include <stdint.h>
#include <stddef.h>
#include "IGVisibility.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 把多副本健康值置为基线。应在尽早的构造期调用一次(也有构造函数兜底)。 */
void ig_poison_init(void);
IG_PUBLIC void ig_poison_init(void);
/*
* 命中强信号组合时调用:把 entropy(必须非 0)混进所有健康值副本,使其偏离基线。
@@ -47,7 +49,7 @@ uint64_t ig_poison_mask(void);
* 健康时 out 与 in 逐字节相等(掩码 0,异或 0);毒化时每字节被掩码扰动。
* 业务用法:对解密 key 的字节调用本函数后再传给解密器——健康照常、毒化解出乱码。
*/
void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n);
IG_PUBLIC void ig_poison_apply(const uint8_t *in, uint8_t *out, size_t n);
#ifdef __cplusplus
}
+1 -1
View File
@@ -49,7 +49,7 @@ 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,
IG_PUBLIC int ig_policy_scan_and_mark(const char *bundle_path, int probe_port,
IGFindingSink observer, void *observer_ctx);
#ifdef __cplusplus
+13 -5
View File
@@ -158,11 +158,19 @@ func poisonedKey(_ key: String) -> String {
## 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。
> 状态截至 2026-11-13。回归守在 `tests/test_static_hardening.py`(6 条,gate 于 darwin+iphoneos SDK),防以下几条被后续改动悄悄打回。
**0. ✅ 符号隐藏 + strip(本轮新增,针对「抗静态分析」最高性价比项)。**
`defender/include/IGVisibility.h` 定义 `IG_INTERNAL=hidden`;全库 `-fvisibility=hidden`(见 `tools/build_defender_lib.sh`)。只有 readoor 实际调用的四入口标 `IG_PUBLIC`(`ig_defender_scan / ig_poison_init / ig_poison_apply / ig_policy_scan_and_mark`)保持导出,其余 `ig_*` 在 `.a` 里是 private external,链接进可执行文件后 `strip -x` 即彻底消失——攻击者 `nm` 不再能按名定位 `ig_poison_mark/mask` 去 NOP 调用点。
**readoor 侧务必保留 Release 的 `STRIP_INSTALLED_PRODUCT=YES`**,否则内部符号不消失;连那四个 public 入口也可全量 strip(无外部模块 import 它们,仅编译期静态链接用到)。
1. ✅ 越狱路径字符串 `IG_ENC` 混淆。`tools/gen_jb_paths.py`(唯一真源)生成 `IGJailbreakPaths.inc` / `IGInjectSignatures.inc`(XOR keystream,两表不共享 key);运行期解码进栈、用完 `memset` 擦除。`ig_jb_decode/ig_inj_decode` 内 `volatile` key 屏障,阻止 `-O2` 把「常量 enc+常量 key」折叠回 `__const` 明文。`strings` 已捞不到 `/var/jb`、`Cydia`、`substrate`、`gum-js-loop` 等。CI 用 `gen_jb_paths.py --check` 守 .inc 与清单同步。
2. ✅ `IGPoison` 三副本分散存储。`g_h0/g_h1/g_h2` 置于不相邻命名段 `__DATA,__ig_p0/__ig_p1/__ig_p2`,另加 `__ig_pd` 诱饵副本(init/mark 维护但 mask 不读)。**刻意不用 TLS**——会破坏跨线程毒化一致性。
3. ⚠️ OLLVM/VMP 覆盖 `ig_poison_mark / mask / apply` 与策略分级表。**仅留 hook 未落地**:`build_defender_lib.sh` 的 `IG_OBFUSCATOR` 环境变量在指向 OLLVM-clang 时对 `IGPoison.c`/`IGPolicy.c` 启 `-mllvm -fla -bcf -sub`;stock Xcode clang 无此能力,需另备 obfuscator-llvm/商业 VMP 工具链才算真正完成。
4. ✅ 毒化基线魔数运行期派生。删除硬编码 `0xA5C3F10E7B2D4968`,改 `ig_poison_baseline()` 由拆分种子经 `volatile` 屏障派生(阻止常量折叠回单一魔数);值本身不影响行为,只需进程内自洽。`otool -tV` 已无旧魔数立即数。
5. ⛔ 越狱探针真机正向验证:越狱设备实测命中 400/401,且非越狱设备零 STRONG。**仍阻塞**(无越狱设备)。D8 `svc_access_live` 已在非越狱 iPhone 证了 svc 直发探针活性,残留缺口=真越狱文件 400 + 沙盒逃逸 401 的正向命中。
> **尚未做、留到 readoor 接入时的「断边」深化**:把 `ig_poison_apply` 内联进 epub 解密函数(删掉 `bl ig_poison_apply` 这条调用边),以及调用点改间接跳转(`blr` + 运行期解析目标)——符号隐藏只去掉「按名定位」,这两项才去掉静态调用图里的边本身。
---
+130
View File
@@ -0,0 +1,130 @@
"""静态硬化回归(docs/18 §7):守住「抗静态分析」几条不被后续改动悄悄打回。
验收(对 iphoneos 产物):
1. §7.1 strings 捞不到越狱路径 / 注入特征串 / frida 线程名等明文常量。
2. 符号可见性:只有 IG_PUBLIC 四入口导出(T);内部 ig_* 不以外部符号导出,
且链接进可执行文件 strip 后彻底消失。
3. §7.4 旧基线魔数 0xA5C3F10E7B2D4968 不以明文/立即数出现在反汇编。
4. 混淆表 .inc 与 gen_jb_paths.py 清单一致(防手改 .inc 或漏重生成)。
需 Xcode + iphoneos SDK;缺则跳过。
"""
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
# strings 里绝不应出现的明文特征(越狱路径 + 注入/frida 特征 + 线程名)。
FORBIDDEN = [
'cydia', '/var/jb', '/bin/bash', 'tweakinject', 'sileo', 'mobilesubstrate',
'ig_jb_probe', 'gum-js-loop', 'pool-frida', 'pool-spawner', 'gmain', 'gdbus',
'linjector', 'cynject', 'cycript', 'libhooker', 'rocketbootstrap', 'flexloader',
'shadowhook', 'substitute', 'gadget', 'dobby', 'fishhook',
]
PUBLIC = {'_ig_defender_scan', '_ig_poison_init', '_ig_poison_apply', '_ig_policy_scan_and_mark'}
INTERNAL = ['_ig_poison_mark', '_ig_poison_mask', '_ig_policy_sink',
'_ig_policy_evaluate_and_mark', '_ig_anti_jb_check', '_ig_anti_inject_check']
OLD_MAGIC = ['a5c3f10e', '7b2d4968']
def have_sdk():
if sys.platform != 'darwin' or not shutil.which('xcrun'):
return False
r = subprocess.run(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'],
capture_output=True, text=True)
return r.returncode == 0 and r.stdout.strip() != ''
@unittest.skipUnless(have_sdk(), '需要 Xcode + iphoneos SDK')
class StaticHardeningTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.dist = Path(cls.tmp.name) / 'dist'
r = subprocess.run(['sh', str(ROOT / 'tools/build_defender_lib.sh'), str(cls.dist)],
capture_output=True, text=True)
if r.returncode:
raise RuntimeError(r.stdout + r.stderr)
cls.lib = cls.dist / 'lib/libIGDefender.a'
cls.inc = cls.dist / 'include'
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def _nm(self, path, *extra):
return subprocess.run(['xcrun', '--sdk', 'iphoneos', 'nm', *extra, str(path)],
capture_output=True, text=True).stdout
def test_no_plaintext_needles(self):
"""§7.1:strings 不含任何越狱/注入/frida 明文特征。"""
out = subprocess.run(['strings', '-a', str(self.lib)],
capture_output=True, text=True).stdout.lower()
hit = [w for w in FORBIDDEN if w in out]
self.assertEqual(hit, [], f'明文特征泄漏:{hit}')
def test_gen_table_in_sync(self):
"""混淆表 .inc 与清单一致。"""
r = subprocess.run([sys.executable, str(ROOT / 'tools/gen_jb_paths.py'), '--check'],
capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
def _defined_class(self):
"""解析 nm -m,返回 {symbol: 'private external'|'external'}(只取已定义符号)。
.a 阶段 nm -g 无法区分 private-extern(仍显示 T),须用 nm -m 看 N_PEXT 位。"""
cls = {}
for line in self._nm(self.lib, '-m').splitlines():
if '(undefined)' in line or ') ' not in line:
continue
sym = line.rsplit(' ', 1)[-1]
if 'private external' in line:
cls[sym] = 'private external'
elif 'external' in line:
cls[sym] = 'external'
return cls
def test_internal_symbols_private(self):
"""内部符号为 private external(-fvisibility=hidden 生效),最终 strip 即消失。"""
cls = self._defined_class()
for sym in INTERNAL:
if sym in cls: # 已定义者必须是 private external,不能是普通 external
self.assertEqual(cls[sym], 'private external', f'{sym} 未私有化:{cls[sym]}')
def test_public_entries_exported(self):
"""四个 IG_PUBLIC 入口为普通 external(保持导出,供接入方引用)。"""
cls = self._defined_class()
for sym in PUBLIC:
self.assertEqual(cls.get(sym), 'external', f'{sym} 非导出 external:{cls.get(sym)}')
def test_strip_removes_internal(self):
"""链接进可执行文件 + strip -x 后,内部 ig_* 名彻底消失。"""
w = Path(self.tmp.name)
src = w / 'main.c'
src.write_text('#include "IGGuard.h"\n'
'int main(){ ig_poison_init(); uint8_t k[4]={1,2,3,4},o[4];\n'
' ig_policy_scan_and_mark("/x",0,0,0); ig_poison_apply(k,o,4); return o[0]; }\n')
app = w / 'app'
r = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
'-miphoneos-version-min=15.0', '-O2', '-I', str(self.inc),
str(src), str(self.lib), '-lobjc', '-framework', 'Foundation',
'-o', str(app)], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'strip', '-x', str(app)], check=True)
out = self._nm(app)
for sym in INTERNAL:
self.assertNotIn(sym, out, f'strip 后仍残留 {sym}')
def test_baseline_magic_absent(self):
"""§7.4:旧基线魔数不以明文/立即数出现在反汇编。"""
dis = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'otool', '-tV', str(self.lib)],
capture_output=True, text=True).stdout.lower()
hit = [m for m in OLD_MAGIC if m in dis]
self.assertEqual(hit, [], f'旧基线魔数残留:{hit}')
if __name__ == '__main__':
unittest.main()
+28 -5
View File
@@ -19,7 +19,19 @@ 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"
# -fvisibility=hidden(§7 抗静态调用关系):默认隐藏所有符号,只有头里标 IG_PUBLIC 的
# 入口导出;内部的 ig_poison_mark/mask、ig_policy_* 等成为 private extern,接入方最终
# 链接 + strip 后从符号表消失,nm 再也捞不到名字。
CFLAGS="-arch $ARCH -miphoneos-version-min=$MINVER -O2 -Wall -Wextra -fvisibility=hidden -I$ROOT/defender -I$ROOT/defender/include"
# §7.3 OLLVM/VMP 钩子(默认不启用):设 IG_OBFUSCATOR=/path/to/ollvm-clang 时,用它编译
# 毒化/策略两个敏感 TU 并附加 Fla/BCF/Sub 混淆;未设则用 stock clang,不做混淆(如实)。
OBF_CC=${IG_OBFUSCATOR:-}
OBF_FILES="defender/poison/IGPoison.c defender/policy/IGPolicy.c"
OBF_FLAGS="-mllvm -fla -mllvm -bcf -mllvm -sub"
# 先让 §7.1 混淆表与路径清单保持同步(CI 口径:不一致即失败)。
python3 "$ROOT/tools/gen_jb_paths.py" --check
OBJDIR=$(mktemp -d)
trap 'rm -rf "$OBJDIR"' EXIT
@@ -27,7 +39,13 @@ 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"
rel=${f#"$ROOT/"}
if [ -n "$OBF_CC" ] && echo "$OBF_FILES" | grep -qw "$rel"; then
echo " [obf] $rel"
xcrun -sdk "$SDK" "$OBF_CC" $CFLAGS $OBF_FLAGS -c "$f" -o "$o"
else
xcrun -sdk "$SDK" clang $CFLAGS -c "$f" -o "$o"
fi
done
echo "[2/4] 打包 libIGDefender.a…"
@@ -49,9 +67,14 @@ echo "[3/4] 拷贝公共头…"
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 "[4/4] 校验可见性(§7):公共入口导出(T)、内部符号已私有化…"
echo " — 导出入口(应为 IG_PUBLIC 四个):"
xcrun -sdk "$SDK" nm -g "$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 " — 内部符号可见性(应标 private external,最终 strip 后消失):"
xcrun -sdk "$SDK" nm -m "$OUT/lib/libIGDefender.a" 2>/dev/null \
| grep -E '_ig_(poison_mark|poison_mask|policy_sink|policy_evaluate_and_mark|anti_jb_check)$' \
| sed 's/^/ /' | sort -u | head -20 || true
echo "完成:$OUT/lib/libIGDefender.a ($(lipo -archs "$OUT/lib/libIGDefender.a"))"
echo "公共头:$OUT/include/IGGuard.h"
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""gen_jb_paths.py — 生成越狱特征路径的 XOR 混淆表(docs/18 §7.1 IG_ENC)。
越狱路径常量(/var/jb、Cydia、substrate…)若明文入二进制,`strings` 一把捞出,
等于把检测目标白送。本脚本把每条路径按位置相关的 keystream 异或编码,产出
defender/anti_jailbreak/IGJailbreakPaths.inc;运行期由 IGAntiJailbreak.c 解码进
栈缓冲、用完擦除,二进制里不再驻留明文。
路径清单以本脚本为唯一真源;改清单后重跑本脚本重生成 .inc(可复现)。
python3 tools/gen_jb_paths.py # 写回 .inc
python3 tools/gen_jb_paths.py --check # 只校验 .inc 与当前清单一致(CI 用)
"""
import argparse
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
INC = ROOT / 'defender/anti_jailbreak/IGJailbreakPaths.inc'
INC_INJ = ROOT / 'defender/anti_frida/IGInjectSignatures.inc'
# keystream: enc[j] = plain[j] ^ ((K0 + idx*K1 + j*K2) & 0xFF)。解码端须完全一致。
K0, K1, K2 = 0x5A, 0x2F, 0x13
# anti_frida 用一组不同常量(defense in depth,两表不共享 keystream)。
IK0, IK1, IK2 = 0x3C, 0x47, 0x1D
# 已知注入/调试/越狱增强框架镜像名子串(小写,ig_strstr 子串匹配)。
INJECT = [
"frida", "gadget", "cynject", "cycript", "libcycript",
"substrate", "substitute", "libsubstrate", "tweakinject",
"rocketbootstrap", "reveal", "flexloader", "libhooker",
"shadowhook", "dobby", "fishhook",
]
# 已知 frida 线程名(精确匹配)。
THREADS = [
"gum-js-loop", "gmain", "gdbus", "pool-frida", "pool-spawner", "linjector",
]
# 内置 iOS 越狱特征(强信号)。rootless 越狱重点在 /var/jb。
PATHS = [
"/var/jb",
"/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",
]
# 沙盒外探测路径(能创建即沙盒逃逸)。
PROBE = "/private/.ig_jb_probe"
def encode(s: str, idx: int, k0=K0, k1=K1, k2=K2) -> list:
return [(ord(c) ^ ((k0 + idx * k1 + j * k2) & 0xFF)) & 0xFF for j, c in enumerate(s)]
def arr(name: str, data: list) -> str:
body = ', '.join('0x%02x' % b for b in data)
return f'static const unsigned char {name}[] = {{ {body} }};'
def render() -> str:
out = []
out.append('/* IGJailbreakPaths.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */')
out.append('/* 越狱路径 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */')
out.append(f'#define IG_JB_XOR_K0 0x{K0:02x}u')
out.append(f'#define IG_JB_XOR_K1 0x{K1:02x}u')
out.append(f'#define IG_JB_XOR_K2 0x{K2:02x}u')
out.append('')
for i, p in enumerate(PATHS):
out.append(arr(f'kIGJbEnc{i}', encode(p, i)) + f' /* len={len(p)} */')
out.append('')
rows = ', '.join(f'{{ kIGJbEnc{i}, {len(p)} }}' for i, p in enumerate(PATHS))
out.append('static const struct { const unsigned char *b; unsigned char n; } '
f'kIGJbEnc[] = {{ {rows} }};')
out.append(f'#define IG_JB_ENC_COUNT {len(PATHS)}')
out.append('')
out.append('/* 沙盒逃逸探测路径(idx 用一个与上表不冲突的独立下标)。 */')
probe_idx = 0xA5
out.append(arr('kIGJbProbeEnc', encode(PROBE, probe_idx)) + f' /* len={len(PROBE)} */')
out.append(f'#define IG_JB_PROBE_LEN {len(PROBE)}')
out.append(f'#define IG_JB_PROBE_IDX 0x{probe_idx:02x}')
out.append('')
return '\n'.join(out) + '\n'
def render_inject() -> str:
out = []
out.append('/* IGInjectSignatures.inc — 由 tools/gen_jb_paths.py 生成,请勿手改。 */')
out.append('/* 注入/Frida 特征串 XOR 混淆表(§7.1):enc[j]=plain[j]^((K0+idx*K1+j*K2)&0xFF)。 */')
out.append(f'#define IG_INJ_XOR_K0 0x{IK0:02x}u')
out.append(f'#define IG_INJ_XOR_K1 0x{IK1:02x}u')
out.append(f'#define IG_INJ_XOR_K2 0x{IK2:02x}u')
out.append('')
for i, s in enumerate(INJECT):
out.append(arr(f'kIGInjEnc{i}', encode(s, i, IK0, IK1, IK2)) + f' /* len={len(s)} */')
rows = ', '.join(f'{{ kIGInjEnc{i}, {len(s)} }}' for i, s in enumerate(INJECT))
out.append('static const struct { const unsigned char *b; unsigned char n; } '
f'kIGInjEnc[] = {{ {rows} }};')
out.append(f'#define IG_INJ_ENC_COUNT {len(INJECT)}')
out.append('')
for i, s in enumerate(THREADS):
out.append(arr(f'kIGThrEnc{i}', encode(s, i, IK0, IK1, IK2)) + f' /* len={len(s)} */')
rows = ', '.join(f'{{ kIGThrEnc{i}, {len(s)} }}' for i, s in enumerate(THREADS))
out.append('static const struct { const unsigned char *b; unsigned char n; } '
f'kIGThrEnc[] = {{ {rows} }};')
out.append(f'#define IG_THR_ENC_COUNT {len(THREADS)}')
out.append('')
return '\n'.join(out) + '\n'
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--check', action='store_true', help='只校验,不写回')
a = ap.parse_args()
outputs = [(INC, render(), f'{len(PATHS)} 条路径 + probe'),
(INC_INJ, render_inject(), f'{len(INJECT)} 注入特征 + {len(THREADS)} 线程名')]
if a.check:
for path, text, _ in outputs:
cur = path.read_text() if path.exists() else ''
if cur != text:
print(f'{path.name} 与当前清单不一致,请重跑 gen_jb_paths.py', file=sys.stderr)
sys.exit(1)
print('ok: 混淆表 .inc 与清单一致')
return
for path, text, note in outputs:
path.write_text(text)
print(f'已写 {path.relative_to(ROOT)}({note})')
if __name__ == '__main__':
main()
+1
View File
@@ -53,6 +53,7 @@ def build(profile, identity, bundle, output):
source = output / 'source-snapshot'
inputs = [*list((ROOT / 'defender').rglob('*.c')),
*list((ROOT / 'defender').rglob('*.h')),
*list((ROOT / 'defender').rglob('*.inc')), # §7.1 混淆表(.inc),否则快照编译缺头
ROOT / 'tests/fixtures/poison_device.m',
Path(__file__)]
hashes = {}