feat(defender): 可集成静态库 + readoor 接入方案(检测→分级→数据毒化闭环)

在 iOSGuard 侧产出可集成产物与接入文档,不修改 readoor 代码。

- defender/: anti_hook/anti_frida/anti_debug/anti_jailbreak 探针 + syscall 直发、
  policy 分级层、poison 数据依赖毒化、dispatch/resolve/call_bridge 等子模块
- poison: 三副本冗余、无分支掩码;健康恒等、毒化破坏 key(替代 if-exit 处置)
- policy: STRONG/MEDIUM/WEAK 分级,守误报底线,仅 DETECTED 参与、组合命中才毒化
- anti_jailbreak: IGSyscall 直发 svc 检测越狱文件(400)/沙盒逃逸(401),绕 libc hook
- tools/build_defender_lib.sh: 一键交叉编译打包 libIGDefender.a(arm64) + umbrella 头
- docs/18_READOOR_DEFENDER_INTEGRATION.md: 精确到文件/bridging/替换点/代码片段
- docs/05-17 + evidence + tests + macho_guard/static_sdk_redirect 工具链

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-11-12 22:16:47 +09:00
co-authored by Claude Opus 4.8
parent ff0aee7f47
commit 599e1da5ce
91 changed files with 8751 additions and 0 deletions
@@ -0,0 +1,30 @@
#!/usr/bin/env ruby
# 为门禁按钮级回归生成独立 XCUITest Runner,不修改 readoor 工程。
# 与 create_ui_runner.rb 同构;目标 App 为强制模式 dev 包(cn.touchv.a4YX061),
# 测试源为 IGGateRegressionTests.swift。诊断专用 Bundle ID,测试后卸载。
require 'xcodeproj'
require 'fileutils'
root = File.expand_path('../..', __dir__)
output = ARGV.fetch(0)
abort('输出目录必须不存在') if File.exist?(output)
FileUtils.mkdir_p(output)
project = Xcodeproj::Project.new(File.join(output, 'IGGateRegression.xcodeproj'))
target = project.new_target(:ui_test_bundle, 'IGGateRegression', :ios, '15.0')
ref = project.main_group.new_file(File.join(root, 'tests/business_regression/IGGateRegressionTests.swift'))
target.add_file_references([ref])
target.build_configurations.each do |config|
config.build_settings.merge!({
'PRODUCT_BUNDLE_IDENTIFIER' => 'cn.touchv.iosguard.gateregression',
'GENERATE_INFOPLIST_FILE' => 'YES', 'SWIFT_VERSION' => '5.0',
'CODE_SIGN_STYLE' => 'Manual', 'DEVELOPMENT_TEAM' => 'MG4Z7FU83W',
'CODE_SIGN_IDENTITY' => '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8',
'PROVISIONING_PROFILE_SPECIFIER' => 'e0f18495-668f-4fb1-87e1-4e048fb48d11',
'TARGETED_DEVICE_FAMILY' => '1,2'
})
end
project.save
scheme = Xcodeproj::XCScheme.new
scheme.add_build_target(target)
scheme.add_test_target(target)
scheme.save_as(project.path, 'IGGateRegression', true)
puts project.path
@@ -0,0 +1,28 @@
#!/usr/bin/env ruby
# 为已安装的独立观察包生成独立 XCTest Runner,不修改 readoor 工程。
require 'xcodeproj'
require 'fileutils'
root = File.expand_path('../..', __dir__)
output = ARGV.fetch(0)
abort('输出目录必须不存在') if File.exist?(output)
FileUtils.mkdir_p(output)
project = Xcodeproj::Project.new(File.join(output, 'IGBusinessRegression.xcodeproj'))
target = project.new_target(:ui_test_bundle, 'IGBusinessRegression', :ios, '15.0')
ref = project.main_group.new_file(File.join(root, 'tests/business_regression/IGBusinessRegressionTests.swift'))
target.add_file_references([ref])
target.build_configurations.each do |config|
config.build_settings.merge!({
'PRODUCT_BUNDLE_IDENTIFIER' => 'cn.touchv.iosguard.businessuitests',
'GENERATE_INFOPLIST_FILE' => 'YES', 'SWIFT_VERSION' => '5.0',
'CODE_SIGN_STYLE' => 'Manual', 'DEVELOPMENT_TEAM' => 'MG4Z7FU83W',
'CODE_SIGN_IDENTITY' => '784502FA7C65D2D524D6D20DAFD2F0A83E01B6C8',
'PROVISIONING_PROFILE_SPECIFIER' => 'e0f18495-668f-4fb1-87e1-4e048fb48d11',
'TARGETED_DEVICE_FAMILY' => '1,2'
})
end
project.save
scheme = Xcodeproj::XCScheme.new
scheme.add_build_target(target)
scheme.add_test_target(target)
scheme.save_as(project.path, 'IGBusinessRegression', true)
puts project.path
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""定点加固并签名独立业务观察包;保留真实网络,禁用与原 App 冲突的 URL scheme。"""
import argparse
import datetime
import hashlib
import json
from pathlib import Path
import plistlib
import shutil
import subprocess
import sys
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'tools/macho_guard'))
from redirect_to_runtime import patch,sha,trace_calls
from verify_baseline import inventory,save
from redirect_framework_imports import patch as patch_framework
ARCHIVE_SHA='485c0c95b4701a4e51625e16b6c2a9781c1a8a6f6c9b9cbe392709ecfc95191a'
def prepare_archive(guarded,output,command,baseline):
sdk=guarded/'Frameworks/SSZipArchive.framework/SSZipArchive'
if sha(sdk)!=ARCHIVE_SHA:raise ValueError('SSZipArchive 版本变化,须重新审核绑定规则')
folder=guarded/'Frameworks/IGArchiveGuard.framework'
if folder.exists():raise ValueError('保护 Framework 已存在')
folder.mkdir()
(folder/'Info.plist').write_bytes(plistlib.dumps(dict(
CFBundleExecutable='IGArchiveGuard',CFBundleIdentifier='cn.touchv.iosguard.archiveguard',
CFBundleName='IGArchiveGuard',CFBundlePackageType='FMWK',CFBundleVersion='1',
CFBundleShortVersionString='1.0',MinimumOSVersion='15.0',CFBundleSupportedPlatforms=['iPhoneOS'])))
sources=['dispatch/IGArchiveGuard.c','resolve/IGResolve.c','anti_hook/IGAntiHook.c']
command(['xcrun','--sdk','iphoneos','clang','-arch','arm64','-miphoneos-version-min=15.0',
'-O2','-Wall','-Wextra','-Werror','-fvisibility=hidden','-DIG_OBSERVATION',
'-I',ROOT/'defender','-I',ROOT/'defender/include','-dynamiclib',
*(ROOT/'defender'/p for p in sources),
'-Wl,-install_name,@rpath/IGArchiveGuard.framework/IGArchiveGuard',
'-Wl,-map,'+str(output/'archive-guard-link.map'),
*(f'-Wl,-exported_symbol,_{n}' for n in
['ig_a0','ig_a1','ig_a2','ig_a3','ig_archive_check','ig_archive_counter']),
'-o',folder/'IGArchiveGuard'])
symbols=command(['xcrun','nm','-g',folder/'IGArchiveGuard'])
if 'ig_archive_test_' in symbols:raise ValueError('业务保护 Framework 含测试接口')
# 基线仍执行完整格式审核,但不保留 SDK 改写;两包主程序完全相同。
temp=output/'ssziparchive-rewritten'
report=patch_framework(sdk,temp,ARCHIVE_SHA)
if baseline:temp.unlink()
else:shutil.move(temp,sdk)
report.update(baseline=baseline,applied=not baseline)
save(output/'archive-redirect-report.json',report)
(output/'archive-guard-exports.txt').write_text(symbols)
def prepare(app,linkmap,profile,identity,output,baseline=False,archive_guard=False,archive_baseline=False):
if archive_baseline and not archive_guard:raise ValueError('archive-baseline 需要 archive-guard')
if archive_guard and baseline:raise ValueError('SDK 对照不能同时改变主程序基线')
if output.exists():raise ValueError('输出目录必须不存在')
p=subprocess.run(['openssl','smime','-inform','der','-verify','-noverify','-in',str(profile)],capture_output=True,check=True)
provision=plistlib.loads(p.stdout);prefix=provision['ApplicationIdentifierPrefix'][0]
ent=provision['Entitlements']
if ent['application-identifier']!=prefix+'.*' or not ent.get('get-task-allow'):raise ValueError('需要通配开发 profile')
if provision['ExpirationDate']<=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None):raise ValueError('profile 已过期')
if identity.upper() not in {hashlib.sha1(c).hexdigest().upper() for c in provision['DeveloperCertificates']}:raise ValueError('签名身份不匹配')
bundle='cn.touchv.iosguard.observe.20261110'
output.mkdir(parents=True)
def command(args):
r=subprocess.run(list(map(str,args)),capture_output=True,text=True)
with (output/'commands.log').open('a') as log:log.write(json.dumps(list(map(str,args)))+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
if r.returncode:raise RuntimeError('命令失败,详见 commands.log')
return r.stdout
guarded=output/'Payload'/app.name
command(['ditto',app,guarded])
info=plistlib.loads((guarded/'Info.plist').read_bytes());exe=guarded/info['CFBundleExecutable']
symbols=subprocess.run(['xcrun','nm',exe],capture_output=True,text=True,check=True).stdout
if '_ig_dispatch_observation' not in symbols:raise ValueError('输入不是观察构建')
if 'ig_dispatch_test_' in symbols:raise ValueError('业务包不得包含测试覆盖地址接口')
rules=json.loads((ROOT/'tools/macho_guard/profiles/zipzap.json').read_text())
patched=output/'patched-binary';report=patch(exe,patched,linkmap,rules)
report['trace_before']=trace_calls(exe,linkmap,[r['caller'] for r in rules['rules']])
if baseline:
# 仍验证同次 Link Map 和预期调用点,但基线不保留任何分支改写。
patched.unlink()
report=dict(input_sha256=sha(exe),output_sha256=sha(exe),total=0,changes=[],
validated_guard_changes=report['changes'],trace_before=report['trace_before'],
trace_after=report['trace_before'],baseline=True)
else:
report['trace_after']=trace_calls(patched,linkmap,[r['caller'] for r in rules['rules']])
if any(r.get('symbol') in ('_write','_close') for r in report['trace_after']):raise ValueError('原目标直接/GOT 路径仍存在')
shutil.move(patched,exe)
original_bundle=info['CFBundleIdentifier'];info['CFBundleIdentifier']=bundle
info['CFBundleDisplayName']='教育汇·观察'
removed={k:info.pop(k) for k in ('CFBundleURLTypes',) if k in info}
(guarded/'Info.plist').write_bytes(plistlib.dumps(info))
shutil.copy2(profile,guarded/'embedded.mobileprovision')
allowed={k:v for k,v in ent.items() if k not in ('application-identifier','keychain-access-groups')}
allowed.update({'application-identifier':prefix+'.'+bundle,'keychain-access-groups':[prefix+'.'+bundle]})
(output/'entitlements.plist').write_bytes(plistlib.dumps(allowed))
if archive_guard:prepare_archive(guarded,output,command,archive_baseline)
# 独立 sandbox 不复用原 keychain/关联域/Apple 登录权限;相关功能单独验收。
nested={p for p in guarded.rglob('*') if not p.is_symlink() and p.suffix in ('.framework','.dylib')}
if any(guarded.rglob('*.appex')):raise ValueError('含扩展时需分别匹配 profile,拒绝自动套通配签名')
for p in sorted(nested,key=lambda p:(-len(p.parts),str(p))):command(['codesign','--force','--sign',identity,p])
command(['codesign','--force','--sign',identity,'--entitlements',output/'entitlements.plist',guarded])
for p in sorted(nested|{guarded}):command(['codesign','--verify','--strict','--verbose=2',p])
shutil.copy2(linkmap,output/'link.map')
report['signed_output_sha256']=sha(exe);save(output/'redirect-report.json',report)
snapshot=output/'source-snapshot'
for folder in ('defender','tools/macho_guard','tools/business_regression','tests/business_regression','readoor-test/readoor/3.0/Base/Security','readoor-test/readoor/3.0/Features/ReadView/PDF/Network','readoor-test/readoor/3.0/Features/ReadView/MemorizeWords/Handler'):
for src in (ROOT/folder).rglob('*'):
if src.is_file() and src.suffix in ('.c','.h','.swift','.py','.rb') and '__pycache__' not in src.parts:
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded.parent,output/'observation.ipa'])
save(output/'manifest.json',dict(status='ready_for_device_regression',bundle_id=bundle,original_bundle_id=original_bundle,
source_version=info.get('CFBundleShortVersionString'),redirected=report['total'],signing='development',
fake_login=False,mode='observe',baseline=baseline,archive_guard=archive_guard,
archive_baseline=archive_baseline,device_business_regression='not_run',
limitations=['独立 Bundle ID;不覆盖既有 App','未接入原 App Apple 登录、关联域、共享 Keychain 和 URL 回调',
'检测观察模式不关闭 C 调度拒绝机制'],removed_url_scheme_count=len(removed.get('CFBundleURLTypes',[])),
executable_sha256=sha(exe),ipa_sha256=sha(output/'observation.ipa')))
save(output/'evidence-hashes.json',inventory(output))
print(guarded)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for name in ('app','link-map','profile','output'):p.add_argument('--'+name,type=Path,required=True)
p.add_argument('--identity',required=True)
p.add_argument('--baseline',action='store_true',help='不保留分支改写,用同构建和独立 Bundle ID 做对照')
p.add_argument('--archive-guard',action='store_true',help='嵌入并定点改写 SSZipArchive 文件函数绑定')
p.add_argument('--archive-baseline',action='store_true',help='嵌入相同保护库但保留 SDK 原绑定,用于同构建对照')
a=p.parse_args();prepare(a.app.resolve(),a.link_map.resolve(),a.profile.resolve(),a.identity,a.output.resolve(),a.baseline,a.archive_guard,a.archive_baseline)
+100
View File
@@ -0,0 +1,100 @@
#!/bin/bash
# 门禁按钮级回归编排(dev 包 cn.touchv.a4YX061,iPhone 16 Plus)。
#
# v6 要点(v5d/v5e 教训):
# 1. XCUITest launchEnvironment 的 DYLD_INSERT 被 SpringBoard 剥离——注入相位必须
# devicectl `-e` 调试启动通道预先启动,测试仅 activate() attach。
# 2. devicectl `--console` 通道在连续会话后不可靠(console 零输出、进程即死、命令卡
# 超时;v5e 相位 2/4 三次重试全失败,且连无注入的干净 console 启动也卡死)——
# v6 改为无 console 启动:注入生效的证明 = 进程存活 + 测试内门禁 toast 端到端
# 命中(toast 只可能由 Defender 证据触发,链条自证)。console 仅在进程死亡时作
# 诊断回退。
# 3. 相位重排,XCUITest↔devicectl 切换从 4 次降到 2 次:
# ① 干净批 A1 勘察 + A2 确保游客态·登录页 → ② 注入批(游客)B1+B2
# ③ 干净批 C1 放行证明(真实登录尝试,断言只要求无门禁 toast)→ ④ 注入批(登录
# 态,若 C1 未登成则 D1/E1 以游客守卫跳过留证)D1+E1
#
# 用法:run_gate_regression.sh <runner目录> <输出目录>
set -uo pipefail
UDID=00008140-000960811493001C
BUNDLE=cn.touchv.a4YX061
DYLIB=/private/var/mobile/Containers/Data/Application/ED2D2D55-FBA5-4106-BEFD-87A7D40A42B9/Documents/libfrida-sim.dylib
RUNNER=${1:?用法: run_gate_regression.sh <runner目录> <输出目录>}
OUT=${2:?用法: run_gate_regression.sh <runner目录> <输出目录>}
mkdir -p "$OUT"
# 子 shell 会 cd 进 runner,全部转绝对路径避免相对路径错位(v5 首跑教训)
OUT=$(cd "$OUT" && pwd)
RUNNER=$(cd "$RUNNER" && pwd)
launch_injected() { # $1=相位名:终止现进程→devicectl 无 console 注入启动→
# 轮询进程存活确认(debug 通道坏时进程即死,v5e 教训),最多 3 次重试;
# 死亡时追加一次 --console 诊断启动留取 Defender 决策行/报错。成功后等 UI 稳定。
local phase=$1 alive=1
for attempt in 1 2 3; do
xcrun devicectl device process terminate --device "$UDID" "$BUNDLE" >/dev/null 2>&1
sleep 2
xcrun devicectl device process launch --device "$UDID" \
-e "{\"DYLD_INSERT_LIBRARIES\":\"$DYLIB\"}" "$BUNDLE" \
> "$OUT/launch-$phase-$attempt.log" 2>&1
local launched_rc=$? alive_now=0
for _ in $(seq 1 10); do # 30s 内确认进程存活
sleep 3
if [ "$(xcrun devicectl device info processes --device "$UDID" 2>/dev/null | grep -c "$BUNDLE")" -ge 1 ]; then
alive_now=1; break
fi
done
if [ "$alive_now" = 1 ]; then
echo "注入进程存活(第 $attempt 次尝试,rc=$launched_rc)——注入生效由测试内门禁 toast 端到端自证"
sleep 90 # 冷启动到首页稳定(A1 实测 ~158s 首页,90s 后 D1/E1 各自再等首页锚点)
alive=0; return 0
fi
echo "第 $attempt 次注入启动进程死亡,重试"
done
# 诊断回退:console 模式抓一次输出(若 debug 通道可用可拿到 Defender 决策行)
xcrun devicectl device process launch --device "$UDID" --console --timeout 60 \
-e "{\"DYLD_INSERT_LIBRARIES\":\"$DYLIB\"}" "$BUNDLE" \
> "$OUT/console-diag-$phase.log" 2>&1 &
echo "$!" > "$OUT/console-diag-$phase.pid"
echo "警告:$phase 三次注入启动进程均死亡;已发起 console 诊断启动(见 console-diag-$phase.log)"
return 1
}
run_tests() { # $1=结果包名, 其余=-only-testing 参数
local result=$1; shift
rm -rf "$OUT/$result" # xcodebuild 拒绝覆盖已存在结果包
(cd "$RUNNER" && xcodebuild test-without-building \
-project IGGateRegression.xcodeproj -scheme IGGateRegression \
-destination "id=$UDID" -resultBundlePath "$OUT/$result" "$@" \
> "$OUT/xcodebuild-$result.log" 2>&1)
echo "EXIT_$result=$?"
}
echo "== 相位1 干净批:A1 勘察 + A2 确保游客态(登录页)"
run_tests results-clean1.xcresult \
-only-testing:IGGateRegression/IGGateRegressionTests/testA1InspectCleanState \
-only-testing:IGGateRegression/IGGateRegressionTests/testA2LogoutIfNeeded
echo "== 相位2 注入批(游客态):B1 密码 + B2 第三方"
launch_injected b12 || true
run_tests results-inject-guest.xcresult \
-only-testing:IGGateRegression/IGGateRegressionTests/testB1BlockPasswordLogin \
-only-testing:IGGateRegression/IGGateRegressionTests/testB2BlockOtherLogins
echo "== 相位3 干净批:C1 放行证明(真实登录尝试)"
run_tests results-clean2.xcresult \
-only-testing:IGGateRegression/IGGateRegressionTests/testC1AllowPasswordLogin
echo "== 相位4 注入批(登录态):D1 VIP + E1 激活"
launch_injected de1 || true
run_tests results-inject-login.xcresult \
-only-testing:IGGateRegression/IGGateRegressionTests/testD1BlockVipPurchase \
-only-testing:IGGateRegression/IGGateRegressionTests/testE1BlockActivation
# 收尾:先终止应用(让 console 诊断会话自然收口),再清残留进程
xcrun devicectl device process terminate --device "$UDID" "$BUNDLE" >/dev/null 2>&1
for pidf in "$OUT"/console-diag-*.pid; do kill "$(cat "$pidf")" 2>/dev/null; done
echo "== 完成。诊断 console 中的 Defender 决策行(若有):"
grep -h "Defender\|证据" "$OUT"/console-diag-*.log 2>/dev/null | tail -8