From 3503a24bd4fc74a8651d46edbfdc7d5f9ffeb90e Mon Sep 17 00:00:00 2001 From: shenlei Date: Thu, 12 Nov 2026 22:43:03 +0900 Subject: [PATCH] =?UTF-8?q?test(defender):=20=E5=A4=84=E7=BD=AE=E9=93=BE?= =?UTF-8?q?=E7=9C=9F=E6=9C=BA=E9=AA=8C=E8=AF=81=E8=AF=8A=E6=96=AD=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=20+=20=E6=9E=84=E5=BB=BA/=E6=89=A7=E8=A1=8C=E5=99=A8(?= =?UTF-8?q?step12)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补齐 docs/19 的真机 harness,交叉编译通过(iphoneos arm64),待设备执行。 - tests/fixtures/poison_device.m:真机诊断进程。D4–D7 环境无关不变量 (apply恒等/mark坏key/构造期mask=0/策略分级)输出 IG_POISON_CASE 作套件门槛; D1–D3 环境相关(聚合扫描/越狱文件400/沙盒逃逸401)输出 OBS + IG_POISON_ENV 环境判定,供 R/J 组对照判定。只被动探测,不自造越狱文件,每例 ig_poison_init 复位。 - tools/macho_guard/build_poison_device.py:照 hook 版,模块含 poison/policy/ anti_jailbreak,专用 Bundle 前缀 poisonpilot、通配开发 profile 校验、源码快照哈希。 - tools/macho_guard/run_poison_device.py:单相位安装→启动→卸载→证据哈希; --expect clean|jailbroken 自动校验 R 组 jailbroken=no / J 组命中 400/401。 - docs/19 §2/§3/§6 更新为“已建、交叉编译通过、待真机执行”。 全套 63 项宿主/工具测试通过。 Co-Authored-By: Claude Opus 4.8 --- ...9_DISPOSITION_CHAIN_DEVICE_VERIFICATION.md | 26 ++- tests/fixtures/poison_device.m | 176 ++++++++++++++++++ tools/macho_guard/build_poison_device.py | 118 ++++++++++++ tools/macho_guard/run_poison_device.py | 134 +++++++++++++ 4 files changed, 446 insertions(+), 8 deletions(-) create mode 100644 tests/fixtures/poison_device.m create mode 100755 tools/macho_guard/build_poison_device.py create mode 100755 tools/macho_guard/run_poison_device.py diff --git a/docs/19_DISPOSITION_CHAIN_DEVICE_VERIFICATION.md b/docs/19_DISPOSITION_CHAIN_DEVICE_VERIFICATION.md index 7860cb0..5ce23f2 100644 --- a/docs/19_DISPOSITION_CHAIN_DEVICE_VERIFICATION.md +++ b/docs/19_DISPOSITION_CHAIN_DEVICE_VERIFICATION.md @@ -26,7 +26,11 @@ ## 2. 诊断进程(复用 docs/17 harness 模式) -新增 fixture `tests/fixtures/poison_device.m`(**待建**,模式沿用 `hook_device.m`),在自身进程内按用例运行**真实探针链**,逐条 `NSLog` 证据 + 汇总 PASS/FAIL。构建/执行器复用 `tools/macho_guard/build_*_device.py` / `run_*_device.py` 的「安装→运行→卸载→证据哈希」骨架。 +诊断进程 `tests/fixtures/poison_device.m`(**已建**,模式沿用 `hook_device.m`),在自身进程内按用例运行**真实探针链**,逐条 `NSLog` 证据 + 汇总。构建/执行器为 `tools/macho_guard/build_poison_device.py` / `run_poison_device.py`,复用 docs/17 的「安装→运行→卸载→证据哈希」骨架;已交叉编译通过(iphoneos arm64,符号全解析),待真机执行。 + +输出分两类(见下表): +- **`IG_POISON_CASE`**:环境无关不变量(D4–D7),构成套件 PASS/FAIL 门槛,两组都必须过。 +- **`IG_POISON_OBS` / `IG_POISON_ENV`**:环境相关观察(D1–D3 + 越狱判定),不写死 PASS/FAIL;由 runner 的 `--expect clean|jailbroken` 按 R/J 组校验(R 应 `jailbroken=no`、J 应 `jailbroken=yes`)。 **关键:攻击/构造代码只存在于诊断源码,绝不编入业务库。** 越狱特征文件的「存在性」在 J 组由设备本身提供(真有 `/var/jb`、Cydia 等),诊断进程只做被动探测,不自己造越狱文件。 @@ -55,19 +59,25 @@ python3 tools/macho_guard/build_poison_device.py \ --bundle-id cn.touchv.iosguard.poisonpilot. \ --output test-results/step12-device-poison/build- -# R 组(非越狱真机) +# R 组(非越狱真机):--expect clean 自动校验 jailbroken=no python3 tools/macho_guard/run_poison_device.py \ - --device --app .../IGPoisonPilot.app \ + --device --expect clean \ + --app test-results/step12-device-poison/build-/IGPoisonPilot.app \ --bundle-id cn.touchv.iosguard.poisonpilot. \ --output test-results/step12-device-poison/-R -# J 组(越狱设备) +# J 组(越狱设备):--expect jailbroken 自动校验命中 400/401 python3 tools/macho_guard/run_poison_device.py \ - --device --app .../IGPoisonPilot.app \ + --device --expect jailbroken \ + --app test-results/step12-device-poison/build-/IGPoisonPilot.app \ --bundle-id cn.touchv.iosguard.poisonpilot. \ --output test-results/step12-device-poison/-J ``` +runner 退出码:D4–D7 不变量全过 **且** 环境判定与 `--expect` 一致 → 0,否则 1。证据: +`device-verification.json`(verdict/不变量用例/观察/环境判定/边界)、`console.log`(逐条 finding)、 +`install/launch/uninstall.json`、`evidence-hashes.json`;构建侧 `manifest.json` 含源码快照哈希。 + 证据产物(对齐 docs/17 口径):`device-verification.json`(用例/结论/边界)、`console-*.log`(逐条 finding)、`evidence-hashes.json`、构建侧 `manifest.json`(源码快照哈希)。 --- @@ -97,7 +107,7 @@ python3 tools/macho_guard/run_poison_device.py \ ## 6. 当前进度 - [x] 宿主闭环基线固化并绿灯:`tests/fixtures/poison_host.c` + `tests/test_poison_policy.py`(19/19:poison 7 + policy 8 + jailbreak 4)。 -- [ ] `poison_device.m` + `build/run_poison_device.py`(复用 docs/17 harness)。 -- [ ] R 组(非越狱真机)跑 D1–D7,达标 §4.1。 -- [ ] J 组(越狱设备)跑 D1–D7,达标 §4.2,分「裸越狱 / 带 bypass」两档记录。 +- [x] `poison_device.m` + `build_poison_device.py` + `run_poison_device.py`(复用 docs/17 harness);交叉编译通过(iphoneos arm64),待真机执行。 +- [ ] R 组(非越狱真机)跑 D1–D7,`--expect clean`,达标 §4.1。 +- [ ] J 组(越狱设备)跑 D1–D7,`--expect jailbroken`,达标 §4.2,分「裸越狱 / 带 bypass」两档记录。 - [ ] 达标后进入 docs/18 §5 灰度(observer 打点 → 开毒化)。 diff --git a/tests/fixtures/poison_device.m b/tests/fixtures/poison_device.m new file mode 100644 index 0000000..9dcaa6e --- /dev/null +++ b/tests/fixtures/poison_device.m @@ -0,0 +1,176 @@ +/* + * poison_device.m — 处置链真机验证诊断进程(step12,见 docs/19)。 + * + * 在真机自身进程内运行真实的「检测→分级→数据毒化」链,分两类用例: + * + * A. 环境无关不变量(两组设备都必须 PASS,构成套件门槛): + * D4 poison_identity 健康态 apply 恒等(out==key)——证不误伤解密 + * D5 poison_mark_corrupt mark 后 apply 坏 key(out!=key)——证毒化真的生效 + * D6 ctor_clean_start 进程启动未 mark 时 mask==0——证构造期初始化干净、无启动即毒化 + * D7 policy_grades 合成 finding 复核分级(弱/单MEDIUM不触发;双MEDIUM/单STRONG触发) + * + * B. 环境相关观察(不写死 PASS/FAIL,输出命中供人按 R/J 组判定,见 docs/19 §4): + * D1 baseline_scan ig_policy_scan_and_mark(bundle) 的返回/mask + * D2 jb_file 内置越狱特征表 access 直发命中数(reason=400) + * D3 jb_sandbox 默认沙盒逃逸探测(reason=401) + * 并据 D2/D3 是否命中输出环境判定 IG_POISON_ENV jailbroken=yes|no。 + * + * 边界:攻击/构造代码只存在于本诊断源码,绝不编入业务库;越狱特征文件的“存在性” + * 在 J 组由设备本身提供,诊断进程只做被动 access/open 探测,不自己造越狱文件。 + * 每例结束前调 ig_poison_init() 复位,避免跨例污染。 + */ +#import +#include "IGDefender.h" +#include "poison/IGPoison.h" +#include "policy/IGPolicy.h" +#include "anti_jailbreak/IGAntiJailbreak.h" + +#include + +/* ---------- 发现收集 ---------- */ +#define IG_MAXF 64 +static IGFinding g_f[IG_MAXF]; +static int g_nf; +static int g_detected; + +static int collect(const IGFinding *f, void *ctx) { + (void)ctx; + if (f->status == IG_DETECTED) { + if (g_nf < IG_MAXF) g_f[g_nf++] = *f; + g_detected++; + } + NSLog(@"IG_POISON_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_nf = 0; g_detected = 0; } +static int count_reason(int reason) { + int n = 0; + for (int i = 0; i < g_nf; ++i) if (g_f[i].reason == reason) n++; + return n; +} + +/* ---------- PASS/FAIL 汇总 ---------- */ +static int g_pass = 0, g_fail = 0; +static void mark_case(const char *name, int pass, const char *detail) { + if (pass) g_pass++; else g_fail++; + NSLog(@"IG_POISON_CASE %s %s detail=%s", name, pass ? "PASS" : "FAIL", detail ? detail : ""); +} +static void observe(const char *name, const char *detail) { + NSLog(@"IG_POISON_OBS %s %s", name, detail ? detail : ""); +} + +/* ---------- policy 合成输入 ---------- */ +static void feed(IGPolicyState *st, IGStatus status, int reason) { + IGFinding f; memset(&f, 0, sizeof(f)); + f.status = status; f.reason = reason; + ig_policy_sink(&f, st); +} +static int run_policy_weak(void) { + ig_poison_init(); + IGPolicyState st; ig_policy_reset(&st, NULL, NULL); + feed(&st, IG_DETECTED, IG_REASON_FOREIGN_IMAGE); + feed(&st, IG_DETECTED, IG_REASON_FRIDA_PORT); + return ig_policy_evaluate_and_mark(&st); +} +static int run_policy_single_medium(void) { + ig_poison_init(); + IGPolicyState st; ig_policy_reset(&st, NULL, NULL); + feed(&st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); + return ig_policy_evaluate_and_mark(&st); +} +static int run_policy_two_medium(void) { + ig_poison_init(); + IGPolicyState st; ig_policy_reset(&st, NULL, NULL); + feed(&st, IG_DETECTED, IG_REASON_OBJC_IMP_CHANGED); + feed(&st, IG_DETECTED, IG_REASON_SYMBOL_PROVENANCE); + return ig_policy_evaluate_and_mark(&st); +} +static int run_policy_single_strong(void) { + ig_poison_init(); + IGPolicyState st; ig_policy_reset(&st, NULL, NULL); + feed(&st, IG_DETECTED, IG_REASON_JAILBREAK_SANDBOX); + return ig_policy_evaluate_and_mark(&st); +} + +int main(int argc, char **argv) { + (void)argc; (void)argv; + @autoreleasepool { + const char *bundle = [[[NSBundle mainBundle] bundlePath] fileSystemRepresentation]; + + /* ===== D6 ctor_clean_start:进程启动早期、任何 mark 之前,mask 必须为 0 ===== + * 放最前,尽量贴近启动态(构造器已跑,但本进程尚未触发任何检测/mark)。 */ + { + uint64_t m = ig_poison_mask(); + char d[64]; snprintf(d, sizeof(d), "mask=0x%llx", (unsigned long long)m); + mark_case("ctor_clean_start", m == 0, d); + } + + /* ===== D4 poison_identity:健康态 apply 恒等 ===== */ + { + ig_poison_init(); + const uint8_t key[] = { 's','t','a','r','t','i','a','s','o','f','t',0x11,0x22 }; + size_t n = sizeof(key); uint8_t out[sizeof(key)]; + memset(out, 0xAB, n); + ig_poison_apply(key, out, n); + mark_case("poison_identity", memcmp(out, key, n) == 0, "healthy apply must be identity"); + } + + /* ===== D5 poison_mark_corrupt:mark 后 apply 坏 key ===== */ + { + ig_poison_init(); + const uint8_t key[] = { 's','t','a','r','t','i','a','s','o','f','t',0x11,0x22 }; + size_t n = sizeof(key); uint8_t out[sizeof(key)]; + ig_poison_mark(0xC0FFEE); + int nonzero = (ig_poison_mask() != 0); + ig_poison_apply(key, out, n); + int corrupted = (memcmp(out, key, n) != 0); + mark_case("poison_mark_corrupt", nonzero && corrupted, "marked apply must differ"); + ig_poison_init(); + } + + /* ===== D7 policy_grades:真机复核分级 ===== */ + { + int weak = run_policy_weak(); /* 期望 0 */ + int med1 = run_policy_single_medium(); /* 期望 0 */ + int med2 = run_policy_two_medium(); /* 期望 1 */ + int strong = run_policy_single_strong(); /* 期望 1 */ + int ok = (weak == 0 && med1 == 0 && med2 == 1 && strong == 1); + char d[96]; + snprintf(d, sizeof(d), "weak=%d single_medium=%d two_medium=%d single_strong=%d", + weak, med1, med2, strong); + mark_case("policy_grades", ok, d); + ig_poison_init(); + } + + /* ===== D2 jb_file(观察):内置越狱特征表直发 access ===== */ + reset_findings(); + ig_anti_jb_check(collect, NULL); + int hit400 = count_reason(IG_REASON_JAILBREAK_FILE); + int hit401_default = count_reason(IG_REASON_JAILBREAK_SANDBOX); + { + char d[96]; snprintf(d, sizeof(d), "reason400=%d reason401=%d", hit400, hit401_default); + observe("jb_file", d); + } + + /* ===== D1 baseline_scan(观察):聚合策略扫描的返回与 mask ===== */ + { + ig_poison_init(); + int triggered = ig_policy_scan_and_mark(bundle, 0, NULL, NULL); + uint64_t m = ig_poison_mask(); + char d[96]; snprintf(d, sizeof(d), "triggered=%d mask=0x%llx", + triggered, (unsigned long long)m); + observe("baseline_scan", d); + ig_poison_init(); + } + + /* ===== 环境判定:D2/D3 任一命中即视作越狱环境(J 组)===== */ + int jailbroken = (hit400 > 0) || (hit401_default > 0); + NSLog(@"IG_POISON_ENV jailbroken=%s reason400=%d reason401=%d", + jailbroken ? "yes" : "no", hit400, hit401_default); + + /* 套件判定只看环境无关不变量(D4–D7)。 */ + NSLog(@"IG_POISON_SUITE %s pass=%d fail=%d", g_fail ? "FAIL" : "PASS", g_pass, g_fail); + } + return 0; +} diff --git a/tools/macho_guard/build_poison_device.py b/tools/macho_guard/build_poison_device.py new file mode 100755 index 0000000..366e8d5 --- /dev/null +++ b/tools/macho_guard/build_poison_device.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""构建处置链真机验证诊断 App(step12,见 docs/19)。 + +验证 poison/policy/anti_jailbreak 这条「检测→分级→数据毒化」链在真机的行为。 +只支持匹配的 wildcard 开发 profile,专用 Bundle ID 前缀避免复用业务标识; +构建后不安装、不更新开发者门户。诊断进程只被动探测,不含注入/攻击构造 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.poisonpilot.' + + +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/poison_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 / 'IGPoisonPilot.app' + app.mkdir() + info = dict(CFBundleExecutable='IGPoisonPilot', CFBundleIdentifier=bundle, + CFBundleName='IGPoisonPilot', CFBundleDisplayName='IG Poison 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'] + # 处置链 + 其依赖的聚合扫描全套模块(ig_policy_scan_and_mark → ig_defender_scan)。 + modules = ['poison/IGPoison.c', 'policy/IGPolicy.c', + 'anti_jailbreak/IGAntiJailbreak.c', 'syscall/IGSyscall.c', + 'IGDefender.c', 'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c', + 'anti_frida/IGAntiInject.c', 'anti_debug/IGAntiDebug.c', + 'resolve/IGResolve.c', 'dispatch/IGDispatch.c', + 'dispatch/IGArchiveGuard.c', 'call_bridge/IGFileBridge.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) + command(common + ['-fobjc-arc', source / 'tests/fixtures/poison_device.m', *objects, + '-framework', 'UIKit', '-framework', 'Foundation', + '-lobjc', '-o', app / 'IGPoisonPilot'], + blog, 'link app') + + 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) diff --git a/tools/macho_guard/run_poison_device.py b/tools/macho_guard/run_poison_device.py new file mode 100755 index 0000000..1e9eaa8 --- /dev/null +++ b/tools/macho_guard/run_poison_device.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""安装并运行 step12 处置链真机验证诊断 App,收集/解析结果(见 docs/19)。 + +单相位启动(无需 DYLD 注入)。解析两类输出: + - IG_POISON_CASE:环境无关不变量(D4–D7),构成套件 PASS/FAIL 门槛。 + - IG_POISON_OBS / IG_POISON_ENV:环境相关观察(D1–D3 + 越狱判定),供人按 + R(非越狱)/J(越狱)组对照 docs/19 §4 验收门槛判定,不参与套件 PASS/FAIL。 +结束即卸载诊断 App;全部证据与哈希写入输出目录(必须不存在)。 + +退出码:套件不变量全过且环境判定与 --expect 一致 → 0;否则 1。 +--expect clean|jailbroken|any(默认 any):声明本次所在组的期望环境,便于自动校验 + “R 组必须 jailbroken=no、J 组必须 jailbroken=yes”。 +""" +import argparse +import hashlib +import json +import re +from pathlib import Path +import subprocess + +CASE_RE = re.compile(r'IG_POISON_CASE (\S+) (PASS|FAIL)(?: detail=(.*))?$') +OBS_RE = re.compile(r'IG_POISON_OBS (\S+) (.*)$') +SUITE_RE = re.compile(r'IG_POISON_SUITE (PASS|FAIL) pass=(\d+) fail=(\d+)') +ENV_RE = re.compile(r'IG_POISON_ENV jailbroken=(yes|no) reason400=(\d+) reason401=(\d+)') + + +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, observations, suite, env = [], [], 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 = OBS_RE.search(line) + if m: + observations.append(dict(name=m.group(1), detail=m.group(2))) + continue + m = SUITE_RE.search(line) + if m: + suite = dict(result=m.group(1), passed=int(m.group(2)), failed=int(m.group(3))) + continue + m = ENV_RE.search(line) + if m: + env = dict(jailbroken=(m.group(1) == 'yes'), + reason400=int(m.group(2)), reason401=int(m.group(3))) + return cases, observations, suite, env + + +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) + p.add_argument('--expect', choices=['clean', 'jailbroken', 'any'], default='any', + help='R 组传 clean,J 组传 jailbroken;默认 any 不校验环境') + a = p.parse_args() + out = a.output.resolve() + if out.exists(): + raise ValueError('输出目录必须不存在') + out.mkdir(parents=True) + base = ['xcrun', 'devicectl'] + + 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') + + run(base + ['device', 'process', 'launch', '--device', a.device, '--console', '--timeout', '90', + '--json-output', out / 'launch.json', a.bundle_id], + out / 'console.log', 'launch') + cases, observations, suite, env = parse_console(out / 'console.log') + + 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'] + invariants_ok = bool(cases) and not failed and suite and suite['result'] == 'PASS' + + env_ok = True + env_note = '未校验(--expect any)' + if a.expect != 'any': + if env is None: + env_ok = False + env_note = '未解析到 IG_POISON_ENV' + else: + want = (a.expect == 'jailbroken') + env_ok = (env['jailbroken'] == want) + env_note = (f"期望 {a.expect},实测 jailbroken=" + f"{'yes' if env['jailbroken'] else 'no'}" + f"(400={env['reason400']} 401={env['reason401']})") + + verdict = 'PASS' if (invariants_ok and env_ok) else 'FAIL' + verification = dict( + device=a.device, bundle_id=a.bundle_id, app=str(a.app), expect=a.expect, + verdict=verdict, + invariant_cases=cases, invariant_suite=suite, + invariants_ok=invariants_ok, + observations=observations, environment=env, + env_check=dict(ok=env_ok, note=env_note), + acceptance_ref='docs/19 §4', + limitations=[ + 'D1–D3 依赖真实环境:R 组应 jailbroken=no 且 baseline mask=0;J 组应命中 400/401', + 'bypass(Shadow/Liberty) 可规避:J 组若装 bypass 未命中不代表探针失效,需分裸越狱/带 bypass 两档记录', + '诊断为独立进程,业务密钥派生端到端效果需接入 readoor 后再验(docs/18 §4)', + ]) + (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(dict(verdict=verdict, invariants_ok=invariants_ok, + suite=suite, environment=env, env_check=env_note), + ensure_ascii=False)) + raise SystemExit(0 if verdict == 'PASS' else 1) + + +if __name__ == '__main__': + main()