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:
co-authored by
Claude Opus 4.8
parent
ff0aee7f47
commit
599e1da5ce
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# build_defender_lib.sh — 把 defender/ 全部 C 源交叉编译并打包成可集成静态库。
|
||||
#
|
||||
# 产物(默认输出到 dist/):
|
||||
# dist/lib/libIGDefender.a arm64 iphoneos 静态库
|
||||
# dist/include/IGGuard.h 统一公共头(umbrella)
|
||||
# dist/include/... 随附的全部公共头(保持相对目录,供 IGGuard.h 相对引用)
|
||||
#
|
||||
# 用法:
|
||||
# sh tools/build_defender_lib.sh [输出目录]
|
||||
# sh tools/build_defender_lib.sh # → ./dist
|
||||
# sh tools/build_defender_lib.sh /path/to/out # → 指定目录
|
||||
#
|
||||
# 接入方式见 docs/18_READOOR_DEFENDER_INTEGRATION.md。
|
||||
set -eu
|
||||
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
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"
|
||||
|
||||
OBJDIR=$(mktemp -d)
|
||||
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"
|
||||
done
|
||||
|
||||
echo "[2/4] 打包 libIGDefender.a…"
|
||||
mkdir -p "$OUT/lib" "$OUT/include"
|
||||
xcrun -sdk "$SDK" ar rcs "$OUT/lib/libIGDefender.a" "$OBJDIR"/*.o
|
||||
xcrun -sdk "$SDK" ranlib "$OUT/lib/libIGDefender.a"
|
||||
|
||||
echo "[3/4] 拷贝公共头…"
|
||||
# 单一 HEADER_SEARCH_PATH=<out>/include 即自洽:
|
||||
# - defender/include/ 下的头(IGGuard.h / IGDefender.h …)平移到 include 根
|
||||
# - 其余子目录头(poison/ policy/ syscall/ …)保持相对目录,供 umbrella 相对引用
|
||||
( cd "$ROOT/defender" && \
|
||||
find . -name '*.h' | sed 's|^\./||' | sort -u | while read -r h; do
|
||||
case "$h" in
|
||||
include/*) dst="${h#include/}" ;; # include/ 下平移到根
|
||||
*) dst="$h" ;;
|
||||
esac
|
||||
mkdir -p "$OUT/include/$(dirname "$dst")"
|
||||
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 "完成:$OUT/lib/libIGDefender.a ($(lipo -archs "$OUT/lib/libIGDefender.a"))"
|
||||
echo "公共头:$OUT/include/IGGuard.h"
|
||||
@@ -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
@@ -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
|
||||
@@ -0,0 +1,165 @@
|
||||
"""批处理:遍历 .app 包内所有 Mach-O(thin / fat 单 arm64 切片),
|
||||
对每个 arm64 切片运行自研直接分支规则(扫 __text 全部 bl/b → __stubs,
|
||||
经间接符号表映射到 12 个命中符号),统计命中数与注入余量。
|
||||
|
||||
scan 模式只读不改;harden 模式见 macho_guard.harden_bundle。
|
||||
"""
|
||||
import struct, sys, os
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
SYMBOLS = ["_fopen","_dlopen","_dlsym","_write","_read","_open",
|
||||
"_close","_exit","_fork","_syscall","_unlink","_getpid"]
|
||||
WANT = set(SYMBOLS)
|
||||
|
||||
FAT_MAGIC = 0xBEBAFECA # fat_header magic, big-endian on disk (cafebabe 按大端读)
|
||||
FAT_MAGIC_LE = 0xCAFEBABE
|
||||
MH64 = 0xFEEDFACF
|
||||
LC_SEGMENT_64=0x19; LC_SYMTAB=0x2; LC_DYSYMTAB=0xb
|
||||
LC_ENCRYPTION_INFO_64=0x2C
|
||||
|
||||
def arm64_slices(data):
|
||||
"""返回 [(slice_offset, slice_size)];thin 返回单个 (0,len),fat 挑 arm64(非 arm64e)。"""
|
||||
magic,=struct.unpack_from(">I",data,0)
|
||||
if magic==FAT_MAGIC_LE: # fat:字段大端
|
||||
nfat,=struct.unpack_from(">I",data,4)
|
||||
out=[]
|
||||
for i in range(nfat):
|
||||
cputype,cpusub,off,size,align=struct.unpack_from(">IIIII",data,8+i*20)
|
||||
# CPU_TYPE_ARM64=0x0100000C;cpusub 低 24 位:0=ARM64_ALL,1=ARM64E(2)
|
||||
if cputype==0x0100000C and (cpusub & 0x00FFFFFF) in (0,1):
|
||||
out.append((off,size))
|
||||
return out
|
||||
m,=struct.unpack_from("<I",data,0)
|
||||
if m==MH64:
|
||||
cpu, sub=struct.unpack_from("<II",data,4)
|
||||
return [(0,len(data))] if cpu==0x0100000c and (sub & 0xffffff) in (0,1) else []
|
||||
return [] # 非 arm64 Mach-O
|
||||
|
||||
class Slice:
|
||||
"""一个 thin arm64 Mach-O 切片的只读分析视图(偏移均相对 base)。"""
|
||||
def __init__(self, data, base):
|
||||
self.d=data; self.base=base
|
||||
magic,=struct.unpack_from("<I",data,base)
|
||||
assert magic==MH64
|
||||
self.ncmds,=struct.unpack_from("<I",data,base+16)
|
||||
self.text=self.stubs=self.symtab=self.dysym=None
|
||||
self.cryptid=0; self.first_sect_foff=None; self.sizeofcmds=0
|
||||
self.text_vmaddr=0
|
||||
off=base+32
|
||||
self.sizeofcmds,=struct.unpack_from("<I",data,base+20)
|
||||
for _ in range(self.ncmds):
|
||||
cmd,cmdsize=struct.unpack_from("<II",data,off)
|
||||
if cmd==LC_SEGMENT_64:
|
||||
segname=data[off+8:off+24].split(b"\0")[0].decode()
|
||||
vmaddr,=struct.unpack_from("<Q",data,off+24)
|
||||
nsects,=struct.unpack_from("<I",data,off+64)
|
||||
if segname=="__TEXT": self.text_vmaddr=vmaddr
|
||||
so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=data[so:so+16].split(b"\0")[0].decode()
|
||||
addr,size=struct.unpack_from("<QQ",data,so+32)
|
||||
foff,=struct.unpack_from("<I",data,so+48)
|
||||
r1,r2=struct.unpack_from("<II",data,so+68)
|
||||
if foff>0 and (self.first_sect_foff is None or foff<self.first_sect_foff):
|
||||
self.first_sect_foff=foff
|
||||
if sn=="__text": self.text=(addr,size,foff)
|
||||
if sn=="__stubs": self.stubs=(addr,size,foff,r1,r2)
|
||||
so+=80
|
||||
elif cmd==LC_SYMTAB: self.symtab=struct.unpack_from("<IIII",data,off+8)
|
||||
elif cmd==LC_DYSYMTAB: self.dysym=struct.unpack_from("<"+"I"*18,data,off+8)
|
||||
elif cmd==LC_ENCRYPTION_INFO_64: self.cryptid=struct.unpack_from("<I",data,off+16)[0]
|
||||
off+=cmdsize
|
||||
|
||||
def foff(self, slice_rel):
|
||||
"""切片内相对偏移 → 文件绝对偏移。"""
|
||||
return self.base+slice_rel
|
||||
|
||||
def stub_symbol_map(self):
|
||||
"""{stub_vmaddr: symbol_name} 仅限 WANT 中符号。"""
|
||||
if not (self.stubs and self.symtab and self.dysym): return {}
|
||||
symoff,nsyms,stroff,strsize=self.symtab
|
||||
indoff=self.dysym[12]
|
||||
saddr,ssize,sfoff,sr1,sr2=self.stubs
|
||||
out={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",self.d,self.base+indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",self.d,self.base+symoff+idx*16)
|
||||
end=self.d.index(b"\0",self.base+stroff+strx)
|
||||
name=self.d[self.base+stroff+strx:end].decode()
|
||||
if name in WANT: out[saddr+i*sr2]=name
|
||||
return out
|
||||
|
||||
def scan(self):
|
||||
"""Counter{符号:命中数}。__text 内所有 bl/b 目标落到 WANT stub 的计数。"""
|
||||
from collections import Counter
|
||||
cnt=Counter()
|
||||
if not self.text: return cnt
|
||||
stub_sym=self.stub_symbol_map()
|
||||
if not stub_sym: return cnt
|
||||
taddr,tsize,tfoff=self.text
|
||||
for i in range(0,tsize,4):
|
||||
w,=struct.unpack_from("<I",self.d,self.base+tfoff+i)
|
||||
opc=w&0xFC000000
|
||||
if opc in (0x94000000,0x14000000):
|
||||
imm=w&0x3FFFFFF
|
||||
if imm&(1<<25): imm-=1<<26
|
||||
nm=stub_sym.get(taddr+i+imm*4)
|
||||
if nm: cnt[nm]+=1
|
||||
return cnt
|
||||
|
||||
def inject_headroom(self):
|
||||
"""注入一条 72 字节 LC_SEGMENT_64 所需余量:首节 foff - (header+sizeofcmds)。"""
|
||||
if self.first_sect_foff is None: return None
|
||||
return self.first_sect_foff-(32+self.sizeofcmds)
|
||||
|
||||
def iter_macho_files(app_dir):
|
||||
for root,_,files in os.walk(app_dir):
|
||||
for fn in files:
|
||||
p=os.path.join(root,fn)
|
||||
if os.path.islink(p): continue
|
||||
try:
|
||||
with open(p,"rb") as f: head=f.read(8)
|
||||
except Exception: continue
|
||||
if len(head)<4: continue
|
||||
m_le,=struct.unpack_from("<I",head,0)
|
||||
m_be,=struct.unpack_from(">I",head,0)
|
||||
if m_le==MH64 or m_be==FAT_MAGIC_LE:
|
||||
yield p
|
||||
|
||||
def scan_bundle(app_dir):
|
||||
rows=[] # (relpath, is_fat, total, cnt, headroom, cryptid)
|
||||
for p in sorted(iter_macho_files(app_dir)):
|
||||
data=open(p,"rb").read()
|
||||
slices=arm64_slices(data)
|
||||
is_fat = struct.unpack_from(">I",data,0)[0]==FAT_MAGIC_LE
|
||||
for (soff,ssize) in slices:
|
||||
s=Slice(data,soff)
|
||||
cnt=s.scan()
|
||||
rows.append((os.path.relpath(p,app_dir),is_fat,sum(cnt.values()),
|
||||
dict(cnt),s.inject_headroom(),s.cryptid))
|
||||
return rows
|
||||
|
||||
if __name__=="__main__":
|
||||
app=sys.argv[1]
|
||||
rows=scan_bundle(app)
|
||||
hit=[r for r in rows if r[2]>0]
|
||||
from collections import Counter
|
||||
grand=Counter()
|
||||
print(f"Mach-O 文件/切片总数: {len(rows)};命中(>0): {len(hit)}")
|
||||
print(f"{'命中':>5} {'余量':>6} {'enc':>3} 文件")
|
||||
for rel,fat,tot,cnt,room,crypt in sorted(rows,key=lambda r:-r[2]):
|
||||
if tot==0: continue
|
||||
for k,v in cnt.items(): grand[k]+=v
|
||||
tag=" FAT" if fat else ""
|
||||
print(f"{tot:>5} {str(room):>6} {crypt:>3} {rel}{tag}")
|
||||
print(f"\n命中总计: {sum(grand.values())}")
|
||||
for k,v in sorted(grand.items(),key=lambda x:-x[1]):
|
||||
print(f" {k:10} {v}")
|
||||
nz=[r for r in rows if r[2]>0 and (r[4] is None or r[4]<72)]
|
||||
if nz:
|
||||
print("\n注入余量不足(<72B)或未知的命中文件:")
|
||||
for rel,fat,tot,cnt,room,crypt in nz: print(f" room={room} {rel}")
|
||||
enc=[r for r in rows if r[2]>0 and r[5]!=0]
|
||||
if enc:
|
||||
print("\n加密(cryptid≠0)的命中文件:")
|
||||
for rel,fat,tot,cnt,room,crypt in enc: print(f" cryptid={crypt} {rel}")
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""构建独立诊断 App;只支持匹配的 wildcard 开发 profile,不安装、不更新开发者门户。"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
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('cn.touchv.iosguard.dispatchpilot.'):
|
||||
raise ValueError('诊断 Bundle ID 必须使用专用前缀')
|
||||
output.mkdir(parents=True)
|
||||
def command(args):
|
||||
r=subprocess.run(list(map(str,args)),capture_output=True,text=True)
|
||||
with (output/'build.log').open('a') as f:f.write(json.dumps(list(map(str,args)))+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
|
||||
if r.returncode:raise RuntimeError('命令失败,详见 build.log')
|
||||
source=output/'source-snapshot'
|
||||
inputs=[*list((ROOT/'defender').rglob('*.c')),*list((ROOT/'defender').rglob('*.h')),
|
||||
ROOT/'tests/fixtures/dispatch_host.c',ROOT/'tests/fixtures/dispatch_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/'IGDispatchPilot.app';app.mkdir()
|
||||
info=dict(CFBundleExecutable='IGDispatchPilot',CFBundleIdentifier=bundle,CFBundleName='IGDispatchPilot',
|
||||
CFBundleDisplayName='IG Dispatch 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','-DIG_DISPATCH_TESTING','-I',source/'defender','-I',source/'defender/include']
|
||||
command(common+['-Dmain=ig_dispatch_fixture_main','-c',source/'tests/fixtures/dispatch_host.c','-o',output/'fixture.o'])
|
||||
modules=['IGDefender.c','dispatch/IGDispatch.c','resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c','anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c','anti_debug/IGAntiDebug.c','syscall/IGSyscall.c']
|
||||
objects=[output/'fixture.o']
|
||||
for i,module in enumerate(modules):
|
||||
obj=output/f'{i}.o';command(common+['-c',source/'defender'/module,'-o',obj]);objects.append(obj)
|
||||
command(common+['-fobjc-arc',source/'tests/fixtures/dispatch_device.m',*objects,'-framework','UIKit','-framework','Foundation','-lobjc','-o',app/'IGDispatchPilot'])
|
||||
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])
|
||||
command(['codesign','--verify','--strict','--verbose=2',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)
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""构建真机 HOOK 正向验证诊断 App(step11)。
|
||||
|
||||
只支持匹配的 wildcard 开发 profile,专用 Bundle ID 前缀避免复用业务标识;
|
||||
构建后不安装、不更新开发者门户。诊断 App 附带空壳模拟 dylib(libfrida-sim.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.hookpilot.'
|
||||
|
||||
|
||||
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/hook_device.m',
|
||||
ROOT / 'tests/fixtures/hook_sim_dylib.c',
|
||||
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 / 'IGHookPilot.app'
|
||||
app.mkdir()
|
||||
info = dict(CFBundleExecutable='IGHookPilot', CFBundleIdentifier=bundle,
|
||||
CFBundleName='IGHookPilot', CFBundleDisplayName='IG Hook 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']
|
||||
modules = ['IGDefender.c', 'dispatch/IGDispatch.c', 'resolve/IGResolve.c',
|
||||
'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c',
|
||||
'anti_frida/IGAntiInject.c', 'anti_debug/IGAntiDebug.c',
|
||||
'syscall/IGSyscall.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)
|
||||
# 主诊断:export_dynamic 使 dlsym(RTLD_DEFAULT) 能解析主程序导出的蹦床符号。
|
||||
command(common + ['-fobjc-arc', source / 'tests/fixtures/hook_device.m', *objects,
|
||||
'-framework', 'UIKit', '-framework', 'Foundation',
|
||||
'-lobjc', '-Wl,-export_dynamic', '-o', app / 'IGHookPilot'],
|
||||
blog, 'link app')
|
||||
# 模拟注入 dylib:空壳、开发签名、随包作为资源分发。
|
||||
sim = app / 'libfrida-sim.dylib'
|
||||
command(common + ['-dynamiclib', source / 'tests/fixtures/hook_sim_dylib.c',
|
||||
'-o', sim], blog, 'build sim dylib')
|
||||
command(['codesign', '--force', '--sign', identity, sim], blog, 'sign sim dylib')
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,294 @@
|
||||
"""macho_guard 注入器:向未加密 thin arm64 可执行文件注入 __IGUARD 桥接段。
|
||||
|
||||
桥接函数与系统 stub 字节同构(adrp x16,GOT@page; ldr x16,[x16,off]; br x16),
|
||||
从同一 GOT 槽取址尾调用,但不登记进间接符号表——因此调用点改写为 bl IG_* 后,
|
||||
静态扫描器无法再把调用点标记为对应系统符号。
|
||||
|
||||
本阶段(step 1)只注入段并校验结构;调用点改写在 rewrite 子命令中进行。
|
||||
"""
|
||||
import struct, sys, subprocess, os
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from machox import Macho, LC_SEGMENT_64, LC_CODE_SIGNATURE
|
||||
|
||||
PAGE = 0x4000 # iOS arm64 16KB 页
|
||||
|
||||
# 报告命中的 12 个符号
|
||||
SYMBOLS = ["_fopen","_dlopen","_dlsym","_write","_read","_open",
|
||||
"_close","_exit","_fork","_syscall","_unlink","_getpid"]
|
||||
|
||||
def _text_mapping(m: Macho):
|
||||
"""返回 (__TEXT vmaddr, __TEXT fileoff),用于 vmaddr→fileoff 换算。
|
||||
主程序 __TEXT vmaddr=0x1_0000_0000/fileoff=0;framework/dylib vmaddr=0/fileoff=0。"""
|
||||
t=m.segs["__TEXT"]
|
||||
return t["vmaddr"], t["fileoff"]
|
||||
|
||||
def _first_section_fileoff(m: Macho):
|
||||
"""首个非零 section 文件偏移=load command 区可用上界(主程序 0x4000)。"""
|
||||
best=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd!=LC_SEGMENT_64: continue
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64); so=off+72
|
||||
for _ in range(nsects):
|
||||
foff,=struct.unpack_from("<I",m.d,so+48)
|
||||
if foff>0 and (best is None or foff<best): best=foff
|
||||
so+=80
|
||||
return best
|
||||
|
||||
def enc_adrp(rd, page_delta):
|
||||
"""adrp rd, #page_delta(已右移12的页差由调用方给未移的字节差)."""
|
||||
imm = page_delta >> 12
|
||||
immlo = imm & 3; immhi = (imm >> 2) & 0x7FFFF
|
||||
return 0x90000000 | (immlo<<29) | (immhi<<5) | rd
|
||||
|
||||
def enc_ldr_uimm(rt, rn, byte_off):
|
||||
"""ldr xt,[xn,#byte_off] 64位无符号偏移."""
|
||||
assert byte_off % 8 == 0
|
||||
imm12 = byte_off // 8
|
||||
return 0xF9400000 | (imm12<<10) | (rn<<5) | rt
|
||||
|
||||
def enc_br(rn):
|
||||
return 0xD61F0000 | (rn<<5)
|
||||
|
||||
def find_stub_got_slots(m: Macho):
|
||||
"""解析间接符号表,得到 {符号名: GOT槽vmaddr}(通过 stub 反解)。"""
|
||||
# 定位 __stubs、symtab、dysymtab
|
||||
import machox as X
|
||||
stubs=symtab=dysym=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd==LC_SEGMENT_64:
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64)
|
||||
so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=m.d[so:so+16].split(b"\0")[0].decode()
|
||||
if sn=="__stubs":
|
||||
addr,size=struct.unpack_from("<QQ",m.d,so+32)
|
||||
r1,r2=struct.unpack_from("<II",m.d,so+68)
|
||||
stubs=(addr,size,r1,r2)
|
||||
so+=80
|
||||
elif cmd==X.LC_SYMTAB: symtab=struct.unpack_from("<IIII",m.d,off+8)
|
||||
elif cmd==X.LC_DYSYMTAB: dysym=struct.unpack_from("<"+"I"*18,m.d,off+8)
|
||||
symoff,nsyms,stroff,strsize=symtab
|
||||
indoff=dysym[12]
|
||||
saddr,ssize,sr1,sr2=stubs
|
||||
tvm,tfo=_text_mapping(m) # vmaddr→fileoff: fo = va - tvm + tfo
|
||||
out={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",m.d,indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",m.d,symoff+idx*16)
|
||||
name=m.d[stroff+strx:m.d.index(b"\0",stroff+strx)].decode()
|
||||
if name in SYMBOLS:
|
||||
stub_va=saddr+i*sr2; fo=stub_va-tvm+tfo
|
||||
w0,w1=struct.unpack_from("<II",m.d,fo)
|
||||
immlo=(w0>>29)&3; immhi=(w0>>5)&0x7FFFF
|
||||
imm=(immhi<<2)|immlo
|
||||
if imm&(1<<20): imm-=1<<21
|
||||
page=(stub_va & ~0xFFF)+(imm<<12)
|
||||
imm12=(w1>>10)&0xFFF
|
||||
out[name]=page+imm12*8
|
||||
return out
|
||||
|
||||
def build_bridge(got_slots, ig_vmaddr):
|
||||
"""生成桥接段字节与 {符号:IG函数vmaddr}。每函数 3 指令 12 字节。"""
|
||||
code=bytearray(); addrs={}
|
||||
order=[s for s in SYMBOLS if s in got_slots]
|
||||
for i,sym in enumerate(order):
|
||||
fn_va=ig_vmaddr+i*12
|
||||
slot=got_slots[sym]
|
||||
page_delta=(slot & ~0xFFF)-(fn_va & ~0xFFF)
|
||||
off=slot & 0xFFF
|
||||
code+=struct.pack("<III",enc_adrp(16,page_delta),
|
||||
enc_ldr_uimm(16,16,off),enc_br(16))
|
||||
addrs[sym]=fn_va
|
||||
return bytes(code),addrs
|
||||
|
||||
def inject(path, out_path):
|
||||
if os.path.realpath(path)==os.path.realpath(out_path):
|
||||
raise ValueError("注入输出不得覆盖输入")
|
||||
m=Macho(Path(path).read_bytes())
|
||||
if "__IGUARD" in m.segs:
|
||||
raise ValueError("已存在 __IGUARD,拒绝重复注入")
|
||||
le=m.segs["__LINKEDIT"]
|
||||
ig_fileoff=le["fileoff"]; ig_vmaddr=le["vmaddr"]
|
||||
got=find_stub_got_slots(m)
|
||||
missing=[s for s in SYMBOLS if s not in got]
|
||||
bridge,addrs=build_bridge(got,ig_vmaddr)
|
||||
seg_filesize=PAGE # 一页足够
|
||||
hdr_region=_first_section_fileoff(m) # load command 区上界(主程序 0x4000,framework 各异)
|
||||
assert ig_fileoff>hdr_region, "插入点须在 header 区之后"
|
||||
# 1) 段数据:桥接 + 补零到一页
|
||||
segdata=bytearray(bridge)+b"\0"*(seg_filesize-len(bridge))
|
||||
# 2) 文件插入:在 __LINKEDIT fileoff 处插入一页
|
||||
d=m.d
|
||||
body=bytearray(d)
|
||||
body[ig_fileoff:ig_fileoff]=segdata # 插入
|
||||
# 3) 构造 __IGUARD 段命令(0 section, RX)
|
||||
segcmd=struct.pack("<II16sQQQQiiII",LC_SEGMENT_64,72,b"__IGUARD",
|
||||
ig_vmaddr,PAGE,ig_fileoff,seg_filesize,5,5,0,0)
|
||||
# 4) 在 __LINKEDIT 命令前插入该段命令,保持 header 区总长不变
|
||||
le_cmdoff=m.segs["__LINKEDIT"]["off"]
|
||||
# header 区(0..hdr_region)未受段数据插入影响(插入点 ig_fileoff>hdr_region),直接在其中插命令
|
||||
hdr=bytearray(body[:hdr_region])
|
||||
newhdr=hdr[:le_cmdoff]+segcmd+hdr[le_cmdoff:m.hdr_size+m.sizeofcmds]
|
||||
pad=hdr_region-len(newhdr)
|
||||
assert pad>=0, f"load command 空间不足: 需要 {len(newhdr)} > {hdr_region}"
|
||||
newhdr+=b"\0"*pad
|
||||
body[:hdr_region]=newhdr
|
||||
# 5) 修 header ncmds/sizeofcmds
|
||||
struct.pack_into("<II",body,16,m.ncmds+1,m.sizeofcmds+72)
|
||||
# 6) 修 __LINKEDIT 段命令:命令已右移 72 字节
|
||||
le_newoff=le_cmdoff+72
|
||||
struct.pack_into("<Q",body,le_newoff+24,le["vmaddr"]+PAGE) # vmaddr
|
||||
struct.pack_into("<Q",body,le_newoff+40,le["fileoff"]+PAGE) # fileoff
|
||||
# 7) 修所有指向 __LINKEDIT 的偏移 += PAGE(命令偏移也右移 72)
|
||||
for lab,fo,v in m.linkedit_pointers():
|
||||
struct.pack_into("<I",body,fo+(72 if fo>=le_cmdoff else 0),v+PAGE)
|
||||
Path(out_path).write_bytes(body)
|
||||
return addrs, missing, ig_vmaddr
|
||||
|
||||
def rewrite_callsites(path, out_path, bridge_addrs):
|
||||
"""把 __text 里所有 bl/b -> 命中符号 stub 的调用点改写为 bl/b -> IG_*。
|
||||
返回 {符号: 改写数}。调用点文件偏移在 ig 插入点之前,不受注入影响。"""
|
||||
m=Macho(Path(path).read_bytes())
|
||||
got=find_stub_got_slots(m) # 复用:也给出每个符号的 stub
|
||||
# 需要 stub_va: 重新建 符号->stub_va
|
||||
import machox as X
|
||||
stubs=symtab=dysym=text=None
|
||||
for cmd,cmdsize,off in m.cmds:
|
||||
if cmd==LC_SEGMENT_64:
|
||||
nsects,=struct.unpack_from("<I",m.d,off+64); so=off+72
|
||||
for _ in range(nsects):
|
||||
sn=m.d[so:so+16].split(b"\0")[0].decode()
|
||||
addr,size=struct.unpack_from("<QQ",m.d,so+32)
|
||||
foff,=struct.unpack_from("<I",m.d,so+48)
|
||||
r1,r2=struct.unpack_from("<II",m.d,so+68)
|
||||
if sn=="__stubs": stubs=(addr,size,foff,r1,r2)
|
||||
if sn=="__text": text=(addr,size,foff)
|
||||
so+=80
|
||||
elif cmd==X.LC_SYMTAB: symtab=struct.unpack_from("<IIII",m.d,off+8)
|
||||
elif cmd==X.LC_DYSYMTAB: dysym=struct.unpack_from("<"+"I"*18,m.d,off+8)
|
||||
symoff,nsyms,stroff,strsize=symtab; indoff=dysym[12]
|
||||
saddr,ssize,sfoff,sr1,sr2=stubs
|
||||
stub_sym={}
|
||||
for i in range(ssize//sr2):
|
||||
idx,=struct.unpack_from("<I",m.d,indoff+(sr1+i)*4)
|
||||
strx,=struct.unpack_from("<I",m.d,symoff+idx*16)
|
||||
name=m.d[stroff+strx:m.d.index(b"\0",stroff+strx)].decode()
|
||||
if name in bridge_addrs: stub_sym[saddr+i*sr2]=name
|
||||
taddr,tsize,tfoff=text
|
||||
d=bytearray(Path(path).read_bytes())
|
||||
from collections import Counter
|
||||
cnt=Counter()
|
||||
for i in range(0,tsize,4):
|
||||
w,=struct.unpack_from("<I",d,tfoff+i)
|
||||
opc=w&0xFC000000
|
||||
if opc in (0x94000000,0x14000000):
|
||||
imm=w&0x3FFFFFF
|
||||
if imm&(1<<25): imm-=1<<26
|
||||
tgt=taddr+i+imm*4
|
||||
sym=stub_sym.get(tgt)
|
||||
if sym:
|
||||
site=taddr+i; dest=bridge_addrs[sym]; delta=dest-site
|
||||
assert -(1<<27)<=delta<(1<<27) and delta%4==0, f"越界 {site:#x}->{dest:#x}"
|
||||
neww=opc | ((delta>>2)&0x3FFFFFF)
|
||||
struct.pack_into("<I",d,tfoff+i,neww)
|
||||
cnt[sym]+=1
|
||||
Path(out_path).write_bytes(d)
|
||||
return dict(cnt)
|
||||
|
||||
def codesign_adhoc(path):
|
||||
r=subprocess.run(["codesign","-f","-s","-",path],capture_output=True,text=True)
|
||||
return r.returncode,r.stderr.strip()
|
||||
|
||||
# ---- 批处理:fat 感知的单文件处理 + 整包遍历 ----
|
||||
import tempfile, shutil
|
||||
|
||||
def harden_thin(src, dst):
|
||||
"""thin arm64:注入 __IGUARD + 改写调用点(不签名)。返回 (改写计数dict, 桥接数, missing)。"""
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
cnt=rewrite_callsites(dst,dst,addrs)
|
||||
return cnt, len(addrs), missing, igva
|
||||
|
||||
def _fat_arm64_arch(path):
|
||||
"""fat 容器里 arm64 切片的 lipo arch 名(arm64 或 arm64 的子型)。返回首个匹配。"""
|
||||
r=subprocess.run(["lipo","-archs",path],capture_output=True,text=True)
|
||||
archs=r.stdout.split()
|
||||
for a in archs:
|
||||
if a=="arm64": return a
|
||||
for a in archs:
|
||||
if a.startswith("arm64") and a!="arm64e": return a
|
||||
return None
|
||||
|
||||
def harden_macho_file(path, verbose=True):
|
||||
"""就地加固一个 Mach-O 文件(thin 或含单 arm64 切片的 fat)。签名在上层统一做。
|
||||
返回 (改写总数, 细目dict) 或 None(无命中/跳过)。"""
|
||||
data=Path(path).read_bytes()
|
||||
is_fat = struct.unpack_from(">I",data,0)[0]==0xCAFEBABE
|
||||
if is_fat:
|
||||
arch=_fat_arm64_arch(path)
|
||||
if not arch: return None
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
thin=os.path.join(td,"thin"); hard=os.path.join(td,"hard")
|
||||
subprocess.run(["lipo",path,"-thin",arch,"-output",thin],check=True)
|
||||
# 加密检查
|
||||
mm=Macho(Path(thin).read_bytes())
|
||||
cnt,nbr,missing,igva=harden_thin(thin,hard)
|
||||
if sum(cnt.values())==0: return None
|
||||
# 替换回 fat
|
||||
subprocess.run(["lipo",path,"-replace",arch,hard,"-output",path],check=True)
|
||||
return sum(cnt.values()), dict(cnt)
|
||||
else:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
hard=os.path.join(td,"hard")
|
||||
cnt,nbr,missing,igva=harden_thin(path,hard)
|
||||
if sum(cnt.values())==0: return None
|
||||
shutil.copymode(path,hard); shutil.move(hard,path)
|
||||
return sum(cnt.values()), dict(cnt)
|
||||
|
||||
def _sign_targets(app_dir):
|
||||
"""返回自底向上的签名目标:各 .framework/.app 包 + 主可执行文件。"""
|
||||
fws=[]
|
||||
fwdir=os.path.join(app_dir,"Frameworks")
|
||||
if os.path.isdir(fwdir):
|
||||
for n in sorted(os.listdir(fwdir)):
|
||||
p=os.path.join(fwdir,n)
|
||||
if p.endswith((".framework",".dylib")): fws.append(p)
|
||||
return fws
|
||||
|
||||
def harden_bundle(app_dir, resign=True):
|
||||
"""遍历 .app 内全部 Mach-O,逐个加固有命中者;可选统一重签。"""
|
||||
import batch
|
||||
results=[] # (relpath, total, cnt)
|
||||
for p in sorted(batch.iter_macho_files(app_dir)):
|
||||
r=harden_macho_file(p)
|
||||
if r:
|
||||
results.append((os.path.relpath(p,app_dir),r[0],r[1]))
|
||||
print(f" [改写] {r[0]:>4} 处 {os.path.relpath(p,app_dir)}")
|
||||
if resign:
|
||||
# 先签 Frameworks(含被改写的),再签主 app
|
||||
for fw in _sign_targets(app_dir):
|
||||
subprocess.run(["codesign","-f","-s","-",fw],capture_output=True)
|
||||
rc,err=codesign_adhoc(app_dir) # 签主 app bundle
|
||||
print(f" [重签] 主 app exit={rc} {err}")
|
||||
return results
|
||||
|
||||
if __name__=="__main__":
|
||||
mode=sys.argv[1]
|
||||
if mode=="inject":
|
||||
src,dst=sys.argv[2],sys.argv[3]
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
print(f"注入完成 -> {dst} __IGUARD={igva:#x} 桥接 {len(addrs)} 个")
|
||||
if missing: print("缺失:",missing)
|
||||
elif mode=="harden":
|
||||
src,dst=sys.argv[2],sys.argv[3]
|
||||
addrs,missing,igva=inject(src,dst)
|
||||
print(f"[1/3] 注入 __IGUARD @{igva:#x},桥接 {len(addrs)} 个" + (f" 缺失={missing}" if missing else ""))
|
||||
cnt=rewrite_callsites(dst,dst,addrs)
|
||||
print(f"[2/3] 改写调用点 共 {sum(cnt.values())} 处: "+", ".join(f"{k}={v}" for k,v in sorted(cnt.items(),key=lambda x:-x[1])))
|
||||
rc,err=codesign_adhoc(dst)
|
||||
print(f"[3/3] ad-hoc 重签 exit={rc} {err}")
|
||||
elif mode=="harden-bundle":
|
||||
app=sys.argv[2]
|
||||
print(f"遍历加固 .app: {app}")
|
||||
res=harden_bundle(app, resign=(len(sys.argv)<4 or sys.argv[3]!="--no-sign"))
|
||||
print(f"共加固 {len(res)} 个 Mach-O,改写 {sum(t for _,t,_ in res)} 处")
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Mach-O thin arm64 结构分析/改写基础库(macho_guard)。
|
||||
只处理单切片 arm64、未加密(cryptid 0)可执行文件。"""
|
||||
import struct
|
||||
|
||||
LC_SEGMENT_64=0x19; LC_SYMTAB=0x2; LC_DYSYMTAB=0xb
|
||||
LC_DYLD_INFO=0x22; LC_DYLD_INFO_ONLY=0x80000022
|
||||
LC_FUNCTION_STARTS=0x26; LC_DATA_IN_CODE=0x29
|
||||
LC_CODE_SIGNATURE=0x1d; LC_DYLD_CHAINED_FIXUPS=0x80000034; LC_DYLD_EXPORTS_TRIE=0x80000033
|
||||
LC_SEGMENT_SPLIT_INFO=0x1e
|
||||
|
||||
class Macho:
|
||||
def __init__(self, data: bytearray):
|
||||
self.d=bytearray(data)
|
||||
if len(self.d) < 32:
|
||||
raise ValueError("Mach-O header 截断")
|
||||
magic,=struct.unpack_from("<I",self.d,0)
|
||||
if magic!=0xFEEDFACF:
|
||||
raise ValueError(f"需要 thin mach-o 64: {magic:#x}")
|
||||
(self.cputype,self.cpusub,self.filetype,self.ncmds,
|
||||
self.sizeofcmds,self.flags)=struct.unpack_from("<iiIIII",self.d,4)
|
||||
if self.cputype != 0x0100000c or (self.cpusub & 0xffffff) not in (0, 1):
|
||||
raise ValueError("仅支持 arm64/arm64v8,暂不支持 arm64e 或其它架构")
|
||||
if self.filetype not in (2, 6, 8):
|
||||
raise ValueError("仅支持已链接 executable/dylib/bundle")
|
||||
if self.sizeofcmds > len(self.d)-32 or self.ncmds > self.sizeofcmds//8:
|
||||
raise ValueError("load command 区截断")
|
||||
self.hdr_size=32
|
||||
self._parse()
|
||||
def _parse(self):
|
||||
self.cmds=[]; self.segs={}; off=self.hdr_size
|
||||
for _ in range(self.ncmds):
|
||||
if off+8 > self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("load command header 截断")
|
||||
cmd,cmdsize=struct.unpack_from("<II",self.d,off)
|
||||
if cmdsize < 8 or cmdsize % 8 or off+cmdsize > self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("非法 load command 长度")
|
||||
self.cmds.append((cmd,cmdsize,off))
|
||||
if cmd==LC_SEGMENT_64:
|
||||
if cmdsize < 72:
|
||||
raise ValueError("segment command 截断")
|
||||
segname=self.d[off+8:off+24].split(b"\0")[0].decode()
|
||||
vmaddr,vmsize,fileoff,filesize=struct.unpack_from("<QQQQ",self.d,off+24)
|
||||
maxprot,initprot,nsects,fl=struct.unpack_from("<iiII",self.d,off+56)
|
||||
if 72+nsects*80 != cmdsize or fileoff+filesize > len(self.d):
|
||||
raise ValueError("segment/section 越界")
|
||||
if segname in self.segs:
|
||||
raise ValueError("重复 segment")
|
||||
self.segs[segname]=dict(off=off,vmaddr=vmaddr,vmsize=vmsize,
|
||||
fileoff=fileoff,filesize=filesize,nsects=nsects,
|
||||
maxprot=maxprot,initprot=initprot)
|
||||
elif cmd==0x2c:
|
||||
if cmdsize < 24 or struct.unpack_from("<I",self.d,off+16)[0] != 0:
|
||||
raise ValueError("加密 Mach-O 不支持改写或扫描")
|
||||
off+=cmdsize
|
||||
if off != self.hdr_size+self.sizeofcmds:
|
||||
raise ValueError("load command 总长不一致")
|
||||
def linkedit_pointers(self):
|
||||
"""返回所有指向 __LINKEDIT 的 (命令名, 字段偏移绝对值, 当前值) 列表。"""
|
||||
res=[]
|
||||
for cmd,cmdsize,off in self.cmds:
|
||||
def add(fieldoff,label):
|
||||
v,=struct.unpack_from("<I",self.d,off+fieldoff)
|
||||
if v: res.append((label,off+fieldoff,v))
|
||||
if cmd in (LC_DYLD_INFO,LC_DYLD_INFO_ONLY):
|
||||
for i,lab in enumerate(["rebase","bind","weak_bind","lazy_bind","export"]):
|
||||
add(8+i*8,"dyld_info."+lab) # each has off(4)+size(4)
|
||||
elif cmd==LC_SYMTAB:
|
||||
add(8,"symtab.symoff"); add(16,"symtab.stroff")
|
||||
elif cmd==LC_DYSYMTAB:
|
||||
for fo,lab in [(32,"toc"),(40,"modtab"),(48,"extrefsym"),
|
||||
(56,"indirectsym"),(64,"extrel"),(72,"locrel")]:
|
||||
add(fo,"dysymtab."+lab)
|
||||
elif cmd in (LC_FUNCTION_STARTS,LC_DATA_IN_CODE,LC_CODE_SIGNATURE,
|
||||
LC_DYLD_CHAINED_FIXUPS,LC_DYLD_EXPORTS_TRIE,LC_SEGMENT_SPLIT_INFO):
|
||||
add(8,{LC_FUNCTION_STARTS:"function_starts",LC_DATA_IN_CODE:"data_in_code",
|
||||
LC_CODE_SIGNATURE:"code_signature",LC_DYLD_CHAINED_FIXUPS:"chained_fixups",
|
||||
LC_DYLD_EXPORTS_TRIE:"exports_trie",LC_SEGMENT_SPLIT_INFO:"split_info"}[cmd])
|
||||
return res
|
||||
|
||||
if __name__=="__main__":
|
||||
import sys
|
||||
m=Macho(bytearray(open(sys.argv[1],"rb").read()))
|
||||
print(f"cputype={m.cputype:#x} ncmds={m.ncmds} sizeofcmds={m.sizeofcmds}")
|
||||
print("padding for new LC =", min(s['fileoff'] for s in m.segs.values() if s['fileoff']>0 and s['nsects']>0) - (m.hdr_size+m.sizeofcmds))
|
||||
for name,s in m.segs.items():
|
||||
print(f" {name:14} vmaddr={s['vmaddr']:#012x} vmsize={s['vmsize']:#x} fileoff={s['fileoff']:#x} filesize={s['filesize']:#x} prot={s['initprot']}")
|
||||
print("--- __LINKEDIT 指针 ---")
|
||||
le=m.segs["__LINKEDIT"]
|
||||
for lab,fo,v in m.linkedit_pointers():
|
||||
inside = le['fileoff']<=v<le['fileoff']+le['filesize']
|
||||
print(f" {lab:24} @{fo:#x} = {v:#x} {'(in LINKEDIT)' if inside else '!!OUTSIDE'}")
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"rules": [
|
||||
{"caller": "-[ZZFileChannelOutput writeData:error:]", "symbol": "_write", "destination": "_IG_dispatch_write", "expected_count": 1},
|
||||
{"caller": "-[ZZFileChannelOutput close]", "symbol": "_close", "destination": "_IG_dispatch_close", "expected_count": 1}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""严格限定的 arm64 chained-import 试点;新文件输出,不改 SDK 机器码。"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
|
||||
|
||||
DEPENDENCY = '@rpath/IGArchiveGuard.framework/IGArchiveGuard'
|
||||
MAPPING = {'_fopen': '_ig_a0', '_fread': '_ig_a1', '_fwrite': '_ig_a2', '_fclose': '_ig_a3'}
|
||||
LOADS = (0xc, 0x80000018, 0x8000001f, 0x80000023, 0x20)
|
||||
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def rewrite(data, expected_sha256):
|
||||
require(hashlib.sha256(data).hexdigest() == expected_sha256, 'SDK 哈希不匹配,须重新审核版本')
|
||||
m = Macho(data)
|
||||
require(m.filetype == 6 and m.flags & 0x80, '需要 two-level MH_DYLIB')
|
||||
require(not any(c in (0x22, 0x80000022) for c, _, _ in m.cmds), '不支持混合传统 dyld 绑定')
|
||||
deps = []
|
||||
sections = []
|
||||
for cmd, size, off in m.cmds:
|
||||
if cmd in LOADS:
|
||||
n = struct.unpack_from('<I', m.d, off + 8)[0]
|
||||
require(24 <= n < size, '依赖名偏移无效')
|
||||
end = m.d.index(0, off + n, off + size)
|
||||
deps.append(bytes(m.d[off + n:end]).decode())
|
||||
if cmd == LC_SEGMENT_64:
|
||||
count = struct.unpack_from('<I', m.d, off + 64)[0]
|
||||
for i in range(count):
|
||||
s = off + 72 + 80 * i
|
||||
length, fileoff = struct.unpack_from('<QI', m.d, s + 40)
|
||||
flags = struct.unpack_from('<I', m.d, s + 64)[0]
|
||||
if length and flags & 0xff not in (1, 0xc, 0x12):
|
||||
require(fileoff > 0 and fileoff + length <= len(data), 'section 文件范围无效')
|
||||
sections.append((fileoff, length))
|
||||
require(DEPENDENCY not in deps and len(deps) < 0x7e, '依赖冲突或 ordinal 超范围')
|
||||
old_ordinal = deps.index('/usr/lib/libSystem.B.dylib') + 1
|
||||
ordinal = len(deps) + 1
|
||||
commands = [o for c, _, o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS]
|
||||
require(len(commands) == 1, '需要唯一 chained fixups')
|
||||
fixoff, fixsize = struct.unpack_from('<II', m.d, commands[0] + 8)
|
||||
require(28 <= fixsize and fixoff + fixsize <= len(data), 'fixups 越界')
|
||||
version, starts, imports, symbols, count, fmt, compression = struct.unpack_from('<7I', m.d, fixoff)
|
||||
require(version == 0 and fmt == 1 and compression == 0, '仅支持无压缩 DYLD_CHAINED_IMPORT')
|
||||
require(28 <= starts < imports <= symbols < fixsize and imports + count * 4 <= symbols,
|
||||
'fixups 结构不支持')
|
||||
# 两套字符串池均先审查,拒绝别名字符串重叠和重复条目。
|
||||
changes = []
|
||||
allowed = set()
|
||||
def write(off, value):
|
||||
require(off >= 0 and off + len(value) <= len(m.d), '写入越界')
|
||||
m.d[off:off + len(value)] = value
|
||||
allowed.update(range(off, off + len(value)))
|
||||
def rename_pool(entries, pool_start, pool_end, kind):
|
||||
selected = {}
|
||||
intervals = []
|
||||
for entry, strx, ordinal_value in entries:
|
||||
start = pool_start + strx
|
||||
require(pool_start <= start < pool_end, '字符串索引越界')
|
||||
end = m.d.index(0, start, pool_end)
|
||||
name = bytes(m.d[start:end]).decode('utf-8')
|
||||
require(name not in MAPPING.values(), '已改写或目标冲突')
|
||||
intervals.append((start, end + 1, name))
|
||||
if name in MAPPING:
|
||||
require(name not in selected and ordinal_value == old_ordinal,
|
||||
'重复导入或提供方不匹配')
|
||||
selected[name] = (entry, start, end)
|
||||
require(set(selected) == set(MAPPING), '缺少预期四个文件函数')
|
||||
for name, (entry, start, end) in selected.items():
|
||||
require(all(other == name or finish <= start or begin >= end + 1
|
||||
for begin, finish, other in intervals), '共享后缀字符串,拒绝原地改名')
|
||||
encoded = MAPPING[name].encode()
|
||||
require(len(encoded) <= end - start, '新名称超出原字符串空间')
|
||||
write(start, encoded + bytes(end - start + 1 - len(encoded)))
|
||||
if kind == 'chained':
|
||||
word = struct.unpack_from('<I', m.d, entry)[0]
|
||||
require(not word & 0x100, '不支持 weak 目标导入')
|
||||
write(entry, struct.pack('<I', (word & ~255) | ordinal))
|
||||
else:
|
||||
desc = struct.unpack_from('<H', m.d, entry + 6)[0]
|
||||
require(not desc & 0x40, '不支持 weak 符号')
|
||||
write(entry + 6, struct.pack('<H', (desc & 255) | (ordinal << 8)))
|
||||
changes.append({'table': kind, 'source': name, 'destination': MAPPING[name],
|
||||
'old_ordinal': old_ordinal, 'ordinal': ordinal})
|
||||
entries = []
|
||||
for i in range(count):
|
||||
pos = fixoff + imports + 4 * i
|
||||
word = struct.unpack_from('<I', m.d, pos)[0]
|
||||
entries.append((pos, word >> 9, word & 255))
|
||||
rename_pool(entries, fixoff + symbols, fixoff + fixsize, 'chained')
|
||||
tabs = [o for c, _, o in m.cmds if c == LC_SYMTAB]
|
||||
require(len(tabs) == 1, '需要唯一符号表')
|
||||
symoff, nsyms, stroff, strsize = struct.unpack_from('<4I', m.d, tabs[0] + 8)
|
||||
require(symoff + nsyms * 16 <= len(data) and stroff + strsize <= len(data), '符号表越界')
|
||||
entries = []
|
||||
for i in range(nsyms):
|
||||
pos = symoff + i * 16
|
||||
strx, typ, sect, desc, value = struct.unpack_from('<IBBHQ', m.d, pos)
|
||||
entries.append((pos, strx, desc >> 8 if typ == 1 and sect == 0 and value == 0 else -1))
|
||||
rename_pool(entries, stroff, stroff + strsize, 'nlist')
|
||||
name = DEPENDENCY.encode() + b'\0'
|
||||
size = (24 + len(name) + 7) & ~7
|
||||
end = 32 + m.sizeofcmds
|
||||
require(end + size <= min(o for o, _ in sections), 'header padding 不足')
|
||||
require(not any(m.d[end:end + size]), 'header padding 非零')
|
||||
command = struct.pack('<6I', 0xc, size, 24, 0, 0x10000, 0x10000) + name
|
||||
write(end, command + bytes(size - len(command)))
|
||||
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + size))
|
||||
result = bytes(m.d)
|
||||
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), '非预期字节变化')
|
||||
require(all(data[o:o+n] == result[o:o+n] for o, n in sections), 'section 内容变化')
|
||||
Macho(result)
|
||||
return result, {'input_sha256': hashlib.sha256(data).hexdigest(),
|
||||
'output_sha256': hashlib.sha256(result).hexdigest(), 'dependency': DEPENDENCY,
|
||||
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': 4}
|
||||
|
||||
|
||||
def patch(source, destination, expected_sha256):
|
||||
source, destination = Path(source), Path(destination)
|
||||
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
|
||||
output, report = rewrite(source.read_bytes(), expected_sha256)
|
||||
destination.write_bytes(output)
|
||||
destination.chmod(source.stat().st_mode)
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source', type=Path)
|
||||
p.add_argument('destination', type=Path)
|
||||
p.add_argument('--expected-sha256', required=True)
|
||||
p.add_argument('--report', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256), indent=2) + '\n')
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""使用同次 Link Map 精确改写选定调用者;目标函数必须已编入同一 arm64 二进制。"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
|
||||
from machox import Macho, LC_SYMTAB
|
||||
from batch import Slice
|
||||
|
||||
|
||||
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def link_symbols(path):
|
||||
result={}
|
||||
# Apple Link Map 可包含来自 SDK 的非 UTF-8 字节;受保护规则仍使用 ASCII 精确名称。
|
||||
for line in Path(path).read_text(errors='replace').splitlines():
|
||||
if line.startswith('# Dead Stripped Symbols:'): break
|
||||
m=re.match(r'^(0x[0-9A-Fa-f]+)\s+(0x[0-9A-Fa-f]+)\s+\[\s*\d+\]\s+(.+)$',line)
|
||||
if m:
|
||||
name=m[3]
|
||||
value=(int(m[1],16),int(m[2],16))
|
||||
if name in result and result[name]!=value: result[name]=None
|
||||
else: result[name]=value
|
||||
return {k:v for k,v in result.items() if v is not None}
|
||||
|
||||
|
||||
def defined_symbols(m):
|
||||
result={}
|
||||
for cmd,_,off in m.cmds:
|
||||
if cmd!=LC_SYMTAB: continue
|
||||
symoff,nsyms,stroff,size=struct.unpack_from('<4I',m.d,off+8)
|
||||
for i in range(nsyms):
|
||||
idx,typ,sect,desc,value=struct.unpack_from('<IBBHQ',m.d,symoff+i*16)
|
||||
if typ & 0xe0 or (typ & 0x0e)!=0x0e or idx>=size: continue
|
||||
end=m.d.index(0,stroff+idx,stroff+size)
|
||||
name=m.d[stroff+idx:end].decode(errors='replace')
|
||||
if name in result and result[name]!=value: result[name]=None
|
||||
else: result[name]=value
|
||||
return {k:v for k,v in result.items() if v is not None}
|
||||
|
||||
|
||||
def target(word,site):
|
||||
imm=word & 0x3ffffff
|
||||
if imm & (1<<25): imm-=1<<26
|
||||
return site+imm*4
|
||||
|
||||
|
||||
def patch(src,dst,linkmap,profile):
|
||||
src,dst,linkmap=Path(src),Path(dst),Path(linkmap)
|
||||
if src.resolve()==dst.resolve() or dst.exists(): raise ValueError('输出必须为新文件')
|
||||
data=src.read_bytes();m=Macho(data);v=Slice(data,0)
|
||||
if not v.text or not v.stubs: raise ValueError('缺少 __text/__stubs')
|
||||
lm=link_symbols(linkmap);symbols=defined_symbols(m);stubs=v.stub_symbol_map()
|
||||
textva,textsize,textoff=v.text
|
||||
result=bytearray(data);changes=[]
|
||||
for rule in profile['rules']:
|
||||
caller,dest=rule['caller'],rule['destination']
|
||||
if caller not in lm or dest not in lm: raise ValueError(f'Link Map 缺少 {caller}/{dest}')
|
||||
start,size=lm[caller];destination,dsize=lm[dest]
|
||||
if symbols.get(caller)!=start or symbols.get(dest)!=destination:
|
||||
raise ValueError('Link Map 与二进制的定义符号不匹配,拒绝陈旧映射')
|
||||
if not textva<=start<start+size<=textva+textsize or not textva<=destination<destination+dsize<=textva+textsize:
|
||||
raise ValueError('调用者或目标不在 __text 范围')
|
||||
count=0
|
||||
for site in range(start,start+size,4):
|
||||
off=textoff+site-textva;word,=struct.unpack_from('<I',data,off)
|
||||
op=word & 0xfc000000
|
||||
if op not in (0x94000000,0x14000000) or stubs.get(target(word,site))!=rule['symbol']:continue
|
||||
delta=destination-site
|
||||
if delta%4 or not -(1<<27)<=delta<(1<<27):raise ValueError('分支目标超范围')
|
||||
new=op | ((delta>>2)&0x3ffffff)
|
||||
struct.pack_into('<I',result,off,new)
|
||||
changes.append(dict(caller=caller,symbol=rule['symbol'],site=hex(site),file_offset=off,
|
||||
original_word=hex(word),new_word=hex(new),destination=dest,
|
||||
destination_address=hex(destination),branch='bl' if op==0x94000000 else 'b'))
|
||||
count+=1
|
||||
if count!=rule['expected_count']:raise ValueError(f'{caller}: 期望 {rule["expected_count"]} 处,实际 {count}')
|
||||
if len({r['site'] for r in changes})!=len(changes):raise ValueError('规则重复改写同一调用点')
|
||||
allowed={r['file_offset']+i for r in changes for i in range(4)}
|
||||
if any(a!=b and i not in allowed for i,(a,b) in enumerate(zip(data,result))):raise ValueError('非目标字节变化')
|
||||
for r in changes:
|
||||
word,=struct.unpack_from('<I',result,r['file_offset'])
|
||||
if target(word,int(r['site'],16))!=int(r['destination_address'],16):raise ValueError('改写后目标不一致')
|
||||
dst.parent.mkdir(parents=True,exist_ok=True);dst.write_bytes(result);shutil.copymode(src,dst)
|
||||
return dict(input_sha256=sha(src),output_sha256=sha(dst),linkmap_sha256=sha(linkmap),
|
||||
total=len(changes),changes=changes,
|
||||
residual_tracking=['保留本地调度函数名,名称仍提示用途','目标函数名编码可由静态分析还原',
|
||||
'解析器仍依赖 dlsym/dladdr;不代表调用关系完全不可恢复',
|
||||
'其他调用者的系统导入/GOT 保留,本次只覆盖指定调用点'])
|
||||
|
||||
|
||||
def trace_calls(path,linkmap,roots,max_depth=8):
|
||||
"""有界跟踪本地 BL/B 与经典 GOT 桥接,保留未解析间接分支,不把未知当作安全。"""
|
||||
data=Path(path).read_bytes();m=Macho(data);v=Slice(data,0)
|
||||
functions=link_symbols(linkmap);stubs=v.stub_symbol_map()
|
||||
by_address={addr:(name,size) for name,(addr,size) in functions.items()}
|
||||
textva,textsize,textoff=v.text
|
||||
# 反解当前标准 stub/GOT 关系,检测仍沿用原 GOT 的旧桥接。
|
||||
from macho_guard import find_stub_got_slots
|
||||
slots={addr:name for name,addr in find_stub_got_slots(m).items()}
|
||||
rows=[]
|
||||
def bridge_symbol(address):
|
||||
for seg in m.segs.values():
|
||||
if seg['vmaddr']<=address<=seg['vmaddr']+seg['filesize']-12:
|
||||
off=seg['fileoff']+address-seg['vmaddr']
|
||||
w,w1,w2=struct.unpack_from('<III',data,off)
|
||||
if (w & 0x9f00001f)!=0x90000010 or (w1 & 0xffc003ff)!=0xf9400210 or w2!=0xd61f0200:return None
|
||||
imm=((w>>5)&0x7ffff)*4+((w>>29)&3)
|
||||
if imm & (1<<20):imm-=1<<21
|
||||
return slots.get((address & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8)
|
||||
return None
|
||||
def visit(addr,size,chain,seen,depth):
|
||||
if not textva<=addr<addr+size<=textva+textsize:return
|
||||
for site in range(addr,addr+size,4):
|
||||
off=textoff+site-textva;w,=struct.unpack_from('<I',data,off)
|
||||
op=w & 0xfc000000
|
||||
if op in (0x94000000,0x14000000):
|
||||
dest=target(w,site)
|
||||
if dest in stubs: rows.append(dict(chain=chain,symbol=stubs[dest],kind='direct_stub',site=hex(site)))
|
||||
elif bridge_symbol(dest):rows.append(dict(chain=chain+[f'bridge@{dest:#x}'],symbol=bridge_symbol(dest),kind='got_bridge',site=hex(site)))
|
||||
elif dest in by_address and dest not in seen:
|
||||
name,n=by_address[dest]
|
||||
if depth<max_depth:visit(dest,n,chain+[name],seen|{dest},depth+1)
|
||||
else:rows.append(dict(chain=chain+[name],kind='depth_limit'))
|
||||
elif not addr<=dest<addr+size and dest not in seen:
|
||||
rows.append(dict(chain=chain,kind='local_target_unresolved',site=hex(site),target=hex(dest)))
|
||||
if (w & 0xfffffc1f) in (0xd61f0000,0xd63f0000):
|
||||
rows.append(dict(chain=chain,kind='indirect_unresolved',site=hex(site)))
|
||||
if off+12<=len(data) and (w & 0x9f00001f)==0x90000010:
|
||||
w1,w2=struct.unpack_from('<II',data,off+4)
|
||||
if (w1 & 0xffc003ff)==0xf9400210 and w2==0xd61f0200:
|
||||
imm=((w>>5)&0x7ffff)*4+((w>>29)&3)
|
||||
if imm & (1<<20):imm-=1<<21
|
||||
slot=(site & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8
|
||||
if slot in slots:rows.append(dict(chain=chain,symbol=slots[slot],kind='got_bridge',site=hex(site)))
|
||||
for root in roots:
|
||||
addr,size=functions[root];visit(addr,size,[root],{addr},0)
|
||||
return rows
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('source',type=Path);p.add_argument('output',type=Path)
|
||||
p.add_argument('--link-map',type=Path,required=True);p.add_argument('--profile',type=Path,required=True)
|
||||
p.add_argument('--report',type=Path,required=True)
|
||||
args=p.parse_args();profile=json.loads(args.profile.read_text())
|
||||
report=patch(args.source,args.output,args.link_map,profile)
|
||||
roots=[r['caller'] for r in profile['rules']]
|
||||
report['trace_before']=trace_calls(args.source,args.link_map,roots)
|
||||
report['trace_after']=trace_calls(args.output,args.link_map,roots)
|
||||
args.report.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(f'已改写 {report["total"]} 处;残余追踪路径详见报告')
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""安装并运行 step11 HOOK 正向验证诊断 App,收集/解析结果。
|
||||
|
||||
两相位:
|
||||
A 干净启动(受控攻击形态:GOT/蹦床/线程名/注入 dylib,见 hook_device.m)
|
||||
B 以 DYLD_INSERT_LIBRARIES 启动(真实 dyld 注入,使用相位 A 回显的 dylib 路径)
|
||||
结束即卸载诊断 App;全部证据与哈希写入输出目录(必须不存在)。
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
CASE_RE = re.compile(r'IG_HOOK_CASE (\S+) (PASS|FAIL)(?: detail=(.*))?$')
|
||||
SUITE_RE = re.compile(r'IG_HOOK_SUITE (PASS|FAIL)')
|
||||
TIMING_RE = re.compile(r'IG_HOOK_TIMING (.+)$')
|
||||
DYLIB_RE = re.compile(r'IG_HOOK_DYLIB_PATH (\S+)$')
|
||||
INSERT_RE = re.compile(r'IG_HOOK_INSERT_SUMMARY (.+)$')
|
||||
|
||||
|
||||
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, timing, insert_summary = [], 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 = TIMING_RE.search(line)
|
||||
if m:
|
||||
timing = m.group(1)
|
||||
continue
|
||||
m = INSERT_RE.search(line)
|
||||
if m:
|
||||
insert_summary = m.group(1)
|
||||
return cases, timing, insert_summary
|
||||
|
||||
|
||||
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)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if out.exists():
|
||||
raise ValueError('输出目录必须不存在')
|
||||
out.mkdir(parents=True)
|
||||
base = ['xcrun', 'devicectl'] # --device 为子命令级参数,逐条拼接
|
||||
|
||||
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')
|
||||
|
||||
# 相位 A:干净启动,收集受控攻击形态结果与可注入 dylib 路径。
|
||||
run(base + ['device', 'process', 'launch', '--device', a.device, '--console', '--timeout', '90',
|
||||
'--json-output', out / 'launch-clean.json', a.bundle_id],
|
||||
out / 'console-clean.log', 'launch clean')
|
||||
cases, timing, _ = parse_console(out / 'console-clean.log')
|
||||
dylib = None
|
||||
for line in (out / 'console-clean.log').read_text(errors='replace').splitlines():
|
||||
m = DYLIB_RE.search(line)
|
||||
if m and m.group(1) != 'none':
|
||||
dylib = m.group(1)
|
||||
break
|
||||
|
||||
# 相位 B:DYLD_INSERT_LIBRARIES 真实注入(复用相位 A 验证可装载的路径)。
|
||||
if dylib:
|
||||
r = run(base + ['device', 'process', 'launch', '--device', a.device, '--console', '--timeout', '90',
|
||||
'-e', json.dumps({'DYLD_INSERT_LIBRARIES': dylib}),
|
||||
'--json-output', out / 'launch-insert.json', a.bundle_id],
|
||||
out / 'console-insert.log', 'launch insert')
|
||||
b_cases, _, insert_summary = parse_console(out / 'console-insert.log')
|
||||
cases += b_cases
|
||||
else:
|
||||
insert_summary = 'skipped:相位 A 未能装载模拟 dylib'
|
||||
(out / 'console-insert.log').write_text(insert_summary + '\n')
|
||||
|
||||
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']
|
||||
verification = dict(
|
||||
device=a.device, bundle_id=a.bundle_id, app=str(a.app),
|
||||
cases=cases, case_count=len(cases),
|
||||
passed=len(cases) - len(failed), failed=len(failed),
|
||||
suite='PASS' if cases and not failed else 'FAIL',
|
||||
scan_timing=timing, insert_summary=insert_summary, injected_dylib=dylib,
|
||||
limitations=[
|
||||
'inline-hook 用例针对受控导出符号的真实字节,不是对系统函数的实际 patch',
|
||||
'特征名/线程名/端口可被攻击者改名规避,未命中不等于干净',
|
||||
'本诊断为独立进程,不等同于业务 App 内的完整验收',
|
||||
])
|
||||
(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({k: verification[k] for k in
|
||||
('suite', 'passed', 'failed', 'case_count', 'scan_timing')},
|
||||
ensure_ascii=False))
|
||||
raise SystemExit(0 if verification['suite'] == 'PASS' else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,302 @@
|
||||
#!/usr/bin/env python3
|
||||
"""同一 IPA 加固前后证据归档。仅作本地规则/结构验证,不代表厂商复测或真机验收。"""
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import plistlib
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import batch
|
||||
from machox import Macho
|
||||
import macho_guard
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def digest(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, 'rb') as f:
|
||||
for block in iter(lambda: f.read(1024*1024), b''):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def save(path, data):
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n')
|
||||
|
||||
|
||||
def validate_zip(path):
|
||||
"""ditto 解包前检查路径与符号链接,避免归档逃逸;拒绝重复条目。"""
|
||||
with zipfile.ZipFile(path) as z:
|
||||
seen = set()
|
||||
for info in z.infolist():
|
||||
p = Path(info.filename)
|
||||
if p.is_absolute() or '..' in p.parts or info.filename in seen:
|
||||
raise ValueError(f'不安全或重复的 ZIP 路径: {info.filename}')
|
||||
seen.add(info.filename)
|
||||
if stat.S_ISLNK(info.external_attr >> 16):
|
||||
target = z.read(info).decode()
|
||||
resolved = os.path.normpath(str(p.parent / target))
|
||||
if Path(target).is_absolute() or resolved == '..' or resolved.startswith('../'):
|
||||
raise ValueError(f'ZIP 符号链接逃逸: {p}')
|
||||
bad = z.testzip()
|
||||
if bad:
|
||||
raise ValueError(f'ZIP CRC 失败: {bad}')
|
||||
|
||||
|
||||
def inventory(folder):
|
||||
result = []
|
||||
for path in sorted(folder.rglob('*')):
|
||||
rel = str(path.relative_to(folder))
|
||||
if path.is_symlink():
|
||||
result.append(dict(path=rel, symlink=os.readlink(path)))
|
||||
elif path.is_file():
|
||||
result.append(dict(path=rel, size=path.stat().st_size, sha256=digest(path)))
|
||||
return result
|
||||
|
||||
|
||||
def inspect_binary(path):
|
||||
data = path.read_bytes()
|
||||
slices = batch.arm64_slices(data)
|
||||
if not slices:
|
||||
raise ValueError(f'发现未覆盖的 Mach-O 架构: {path}')
|
||||
if data[:4] == b'\xca\xfe\xba\xbe' and struct.unpack_from('>I',data,4)[0] != len(slices):
|
||||
raise ValueError(f'fat 包含未覆盖的架构,拒绝按全覆盖验收: {path}')
|
||||
results, sites = [], []
|
||||
for base, size in slices:
|
||||
if base+size > len(data):
|
||||
raise ValueError(f'fat 切片越界: {path}')
|
||||
m = Macho(data[base:base+size])
|
||||
le = m.segs['__LINKEDIT']
|
||||
for label, _, offset in m.linkedit_pointers():
|
||||
if not le['fileoff'] <= offset < le['fileoff']+le['filesize']:
|
||||
raise ValueError(f'{path}: {label} 不在 __LINKEDIT')
|
||||
view = batch.Slice(data[base:base+size], 0)
|
||||
uuid = None
|
||||
for cmd, cmdsize, off in m.cmds:
|
||||
if cmd == 0x1b:
|
||||
import uuid as uuid_module
|
||||
uuid = str(uuid_module.UUID(bytes=bytes(m.d[off+8:off+24])))
|
||||
cnt = view.scan()
|
||||
results.append(dict(offset=base, size=size, uuid=uuid,
|
||||
cputype=m.cputype, cpusubtype=m.cpusub,
|
||||
cryptid=view.cryptid, counts=dict(cnt), total=sum(cnt.values()),
|
||||
header_headroom=view.inject_headroom(),
|
||||
segments=m.segs))
|
||||
if view.text:
|
||||
va, length, fileoff = view.text
|
||||
stubs = view.stub_symbol_map()
|
||||
for i in range(0, length, 4):
|
||||
w, = struct.unpack_from('<I', m.d, fileoff+i)
|
||||
op = w & 0xfc000000
|
||||
if op not in (0x94000000, 0x14000000):
|
||||
continue
|
||||
imm = w & 0x3ffffff
|
||||
if imm & (1 << 25):
|
||||
imm -= 1 << 26
|
||||
target = va+i+imm*4
|
||||
if target in stubs:
|
||||
sites.append(dict(slice_offset=base, site=hex(va+i),
|
||||
target=hex(target), branch='bl' if op==0x94000000 else 'b',
|
||||
symbol=stubs[target]))
|
||||
return dict(sha256=digest(path), size=len(data), slices=results), sites
|
||||
|
||||
|
||||
def verify_rewrite(original, guarded):
|
||||
"""逐条检查 __text 差异,并反解桥接目的 GOT;不能只以复扫零命中验收。"""
|
||||
before, after = original.read_bytes(), guarded.read_bytes()
|
||||
old_slices, new_slices = batch.arm64_slices(before), batch.arm64_slices(after)
|
||||
if len(old_slices) != len(new_slices):
|
||||
raise ValueError('改写前后切片数量变化')
|
||||
changes = 0
|
||||
for (off, size), (noff, nsize) in zip(old_slices,new_slices):
|
||||
old, new = before[off:off+size], after[noff:noff+nsize]
|
||||
ov, nv = batch.Slice(old,0), batch.Slice(new,0)
|
||||
om, nm = Macho(old), Macho(new)
|
||||
if ov.text != nv.text:
|
||||
raise ValueError('__text 映射发生变化')
|
||||
stubs = ov.stub_symbol_map()
|
||||
if not ov.text:
|
||||
continue
|
||||
slots = macho_guard.find_stub_got_slots(om) if stubs else {}
|
||||
va, length, fileoff = ov.text
|
||||
ig = nm.segs.get('__IGUARD')
|
||||
for i in range(0,length,4):
|
||||
a, = struct.unpack_from('<I',old,fileoff+i)
|
||||
b, = struct.unpack_from('<I',new,fileoff+i)
|
||||
op = a & 0xfc000000
|
||||
def branch_target(w):
|
||||
imm = w & 0x3ffffff
|
||||
if imm & (1<<25): imm -= 1<<26
|
||||
return va+i+imm*4
|
||||
sym = stubs.get(branch_target(a)) if op in (0x94000000,0x14000000) else None
|
||||
if not sym:
|
||||
if a != b:
|
||||
raise ValueError('非目标指令发生变化')
|
||||
continue
|
||||
if (b & 0xfc000000) != op or not ig:
|
||||
raise ValueError('分支类型变化或缺少桥接段')
|
||||
target = branch_target(b)
|
||||
if not ig['vmaddr'] <= target <= ig['vmaddr']+ig['filesize']-12:
|
||||
raise ValueError('调用目标未落入 __IGUARD')
|
||||
boff = ig['fileoff']+target-ig['vmaddr']
|
||||
w0,w1,w2 = struct.unpack_from('<III',new,boff)
|
||||
if w0 & 0x9f00001f != 0x90000010 or w1 & 0xffc003ff != 0xf9400210 or w2 != 0xd61f0200:
|
||||
raise ValueError('桥接不是 ADRP/LDR/BR x16')
|
||||
imm = ((w0>>5)&0x7ffff)*4+((w0>>29)&3)
|
||||
if imm & (1<<20): imm -= 1<<21
|
||||
got = (target & ~0xfff)+(imm<<12)+((w1>>10)&0xfff)*8
|
||||
if got != slots[sym]:
|
||||
raise ValueError(f'桥接 GOT 目标错误: {sym}')
|
||||
changes += 1
|
||||
return changes
|
||||
|
||||
|
||||
def scan(app, output, label):
|
||||
binaries, sites = {}, []
|
||||
for path in sorted(map(Path, batch.iter_macho_files(str(app)))):
|
||||
rel = str(path.relative_to(app))
|
||||
binaries[rel], found = inspect_binary(path)
|
||||
sites.extend(dict(path=rel, **site) for site in found)
|
||||
if not binaries:
|
||||
raise ValueError('未发现支持的 Mach-O,拒绝将空扫描判为通过')
|
||||
save(output / f'{label}-binaries.json', binaries)
|
||||
with (output / f'{label}-callsites.csv').open('w') as f:
|
||||
w = csv.DictWriter(f, fieldnames=['path','slice_offset','site','target','branch','symbol'])
|
||||
w.writeheader()
|
||||
w.writerows(sites)
|
||||
return binaries, len(sites)
|
||||
|
||||
|
||||
def run(ipa, output):
|
||||
ipa, output = ipa.resolve(), output.resolve()
|
||||
if output.exists():
|
||||
raise ValueError('输出目录必须不存在,避免覆盖既有证据')
|
||||
validate_zip(ipa)
|
||||
output.mkdir(parents=True)
|
||||
manifest = dict(schema_version=1, status='running',
|
||||
created_utc=datetime.now(timezone.utc).isoformat(),
|
||||
scope='自研直接分支规则与静态结构;不代表 V4.6.6/真机验收',
|
||||
vendor_retest='not_run', device_regression='not_run',
|
||||
signing='ad-hoc,仅用于本地静态验证',
|
||||
input=dict(path=str(ipa), size=ipa.stat().st_size, sha256=digest(ipa)),
|
||||
environment=dict(platform=platform.platform(), python=sys.version),
|
||||
tools={str(p.relative_to(ROOT)):digest(p) for p in
|
||||
sorted((ROOT/'tools/macho_guard').glob('*.py'))})
|
||||
def command(args):
|
||||
p = 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)), ensure_ascii=False)+'\n')
|
||||
log.write(p.stdout+p.stderr+f'\nexit={p.returncode}\n')
|
||||
if p.returncode:
|
||||
raise RuntimeError(f'命令失败({p.returncode}): {args[0]},详见 commands.log')
|
||||
return p.stdout.strip()
|
||||
try:
|
||||
manifest['environment']['xcode'] = command(['xcodebuild','-version'])
|
||||
manifest['environment']['clang'] = command(['xcrun','clang','--version'])
|
||||
# 仓库未提交的实现也随证据冻结,避免只有 HEAD 无法还原当时源码。
|
||||
snapshot = output/'source-snapshot'
|
||||
for folder in ('tools/macho_guard','tools/static_sdk_redirect','tests','defender'):
|
||||
for p in sorted((ROOT/folder).rglob('*')):
|
||||
if p.is_file() and '__pycache__' not in p.parts and p.suffix in ('.py','.c','.h','.json'):
|
||||
dest = snapshot/p.relative_to(ROOT)
|
||||
dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
shutil.copy2(p,dest)
|
||||
save(output/'source-files.json', inventory(snapshot))
|
||||
# 对冻结源码运行全部测试;日志永久保存,失败中止。
|
||||
command([sys.executable,'-m','unittest','discover','-s',snapshot/'tests','-v'])
|
||||
manifest['automated_tests'] = 'passed; 详见 commands.log'
|
||||
baseline = output/'baseline'
|
||||
baseline.mkdir()
|
||||
shutil.copy2(ipa, baseline/'input.ipa')
|
||||
if digest(baseline/'input.ipa') != manifest['input']['sha256']:
|
||||
raise ValueError('输入在复制过程中发生变化')
|
||||
command(['ditto','-x','-k',baseline/'input.ipa',baseline/'unpacked'])
|
||||
apps = list((baseline/'unpacked/Payload').glob('*.app'))
|
||||
if len(apps) != 1:
|
||||
raise ValueError('需要恰好一个顶层 .app')
|
||||
app = apps[0]
|
||||
with (app/'Info.plist').open('rb') as f:
|
||||
info = plistlib.load(f)
|
||||
manifest['app'] = {k:info.get(k) for k in
|
||||
('CFBundleIdentifier','CFBundleShortVersionString','CFBundleVersion','CFBundleExecutable')}
|
||||
manifest['original_report'] = dict(version='2.197.2', bundle_id='com.ecnup.azZVz02',
|
||||
exact_report_binary_available=False,
|
||||
note='当前输入单独建基线,不视为原漏洞报告二进制')
|
||||
before, before_total = scan(app, output, 'before')
|
||||
save(output/'before-files.json', inventory(baseline/'unpacked'))
|
||||
guarded = output/'guarded'
|
||||
guarded.mkdir()
|
||||
command(['ditto', baseline/'unpacked', guarded/'unpacked'])
|
||||
guarded_app = guarded/'unpacked/Payload'/app.name
|
||||
rewrites = []
|
||||
for rel, binary in before.items():
|
||||
hits = sum(s['total'] for s in binary['slices'])
|
||||
if not hits:
|
||||
continue
|
||||
for s in binary['slices']:
|
||||
if s['header_headroom'] is None or s['header_headroom'] < 72:
|
||||
raise ValueError(f'注入余量不足: {rel}')
|
||||
result = macho_guard.harden_macho_file(str(guarded_app/rel))
|
||||
if not result or result[0] != hits:
|
||||
raise ValueError(f'改写计数不一致: {rel}')
|
||||
rewrites.append(dict(path=rel, total=result[0], counts=result[1]))
|
||||
save(output/'rewrites.json', rewrites)
|
||||
# 对所有嵌套 bundle 和裸 dylib 从内向外签名;每次失败均中止。
|
||||
targets = {p for p in guarded_app.rglob('*') if
|
||||
not p.is_symlink() and (p.suffix in ('.framework','.app','.appex','.xpc','.dylib'))}
|
||||
targets.add(guarded_app)
|
||||
for target in sorted(targets, key=lambda p:(-len(p.parts),str(p))):
|
||||
command(['codesign','--force','--sign','-',target])
|
||||
for target in sorted(targets):
|
||||
command(['codesign','--verify','--strict','--verbose=2',target])
|
||||
after, after_total = scan(guarded_app, output, 'after')
|
||||
if before.keys() != after.keys() or after_total != 0:
|
||||
raise ValueError('Mach-O 清单变化或改写后仍有命中')
|
||||
for rel in before:
|
||||
command(['xcrun','otool','-l',guarded_app/rel])
|
||||
expected = sum(s['total'] for s in before[rel]['slices'])
|
||||
if verify_rewrite(app/rel,guarded_app/rel) != expected:
|
||||
raise ValueError(f'逐指令改写校验数量不一致: {rel}')
|
||||
for a,b in zip(before[rel]['slices'],after[rel]['slices']):
|
||||
if a['uuid'] != b['uuid']:
|
||||
raise ValueError(f'UUID 意外变化: {rel}')
|
||||
save(output/'after-files.json', inventory(guarded/'unpacked'))
|
||||
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded/'unpacked/Payload',guarded/'guarded.ipa'])
|
||||
command(['ditto','-x','-k',guarded/'guarded.ipa',output/'repacked-check'])
|
||||
repacked, total = scan(output/'repacked-check/Payload'/app.name, output, 'repacked')
|
||||
if repacked != after or total:
|
||||
raise ValueError('重新打包解包后扫描/二进制哈希不一致')
|
||||
if digest(ipa) != manifest['input']['sha256']:
|
||||
raise ValueError('原始输入哈希发生变化')
|
||||
manifest.update(status='passed_local_checks', before_total=before_total, after_total=after_total,
|
||||
macho_files=len(before), changed_macho_files=len(rewrites),
|
||||
instruction_and_bridge_validation='passed',
|
||||
guarded_ipa=dict(path='guarded/guarded.ipa',sha256=digest(guarded/'guarded.ipa')))
|
||||
# 重解包副本验证后可删除,前后两个完整 Payload 与 IPA 留存。
|
||||
shutil.rmtree(output/'repacked-check')
|
||||
except Exception as exc:
|
||||
manifest.update(status='failed', error=str(exc))
|
||||
raise
|
||||
finally:
|
||||
save(output/'manifest.json', manifest)
|
||||
save(output/'evidence-hashes.json', inventory(output))
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('ipa', type=Path)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
run(args.ipa, args.output)
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ZipZap 两函数的构建后转接、增强追踪、签名和证据固化;无真机/厂商通过声明。"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from redirect_to_runtime import patch,trace_calls,sha
|
||||
from verify_baseline import inventory,save,scan
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def run(app,linkmap,build_log,dispatch_object,output):
|
||||
app,linkmap,output=app.resolve(),linkmap.resolve(),output.resolve()
|
||||
if output.exists():raise ValueError('输出目录必须不存在')
|
||||
with (app/'Info.plist').open('rb') as f:info=plistlib.load(f)
|
||||
output.mkdir(parents=True)
|
||||
result=dict(status='running',app={k:info.get(k) for k in
|
||||
('CFBundleIdentifier','CFBundleShortVersionString','CFBundleVersion','CFBundleExecutable')},
|
||||
device_regression='not_run',vendor_retest='not_run',signing='ad-hoc, static checks only')
|
||||
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)),ensure_ascii=False)+'\n'+r.stdout+r.stderr+f'\nexit={r.returncode}\n')
|
||||
if r.returncode:raise RuntimeError(f'{args[0]} 失败,详见 commands.log')
|
||||
return r.stdout
|
||||
try:
|
||||
# 冻结本次执行所需源码及 App 策略测试输入,保留原工程已有工作。
|
||||
snapshot=output/'source-snapshot'
|
||||
for folder in ('defender','tools/macho_guard','tools/static_sdk_redirect','tests'):
|
||||
for src in (ROOT/folder).rglob('*'):
|
||||
if src.is_file() and src.suffix in ('.c','.h','.m','.py','.json') and '__pycache__' not in src.parts:
|
||||
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
|
||||
sources=[ROOT/'readoor-test/readoor.xcodeproj/project.pbxproj',
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security').rglob('*.swift')),
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security/IGDefender').rglob('*.c')),
|
||||
*list((ROOT/'readoor-test/readoor/3.0/Base/Security/IGDefender').rglob('*.h')),
|
||||
ROOT/'readoor-test/scripts/add_igdefender.rb',
|
||||
ROOT/'readoor-test/readoor/3.0/Features/PurchaseOrOrder/Controllers/RDOrderViewController.swift']
|
||||
for src in sources:
|
||||
dest=snapshot/src.relative_to(ROOT);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,dest)
|
||||
save(output/'source-files.json',inventory(snapshot))
|
||||
command([sys.executable,'-m','unittest','discover','-s',snapshot/'tests','-v'])
|
||||
result['tests']='passed (详见 commands.log)'
|
||||
result['environment']=command(['xcodebuild','-version']).strip()
|
||||
shutil.copy2(build_log,output/'build-release.log');shutil.copy2(linkmap,output/'link.map')
|
||||
shutil.copy2(dispatch_object,output/'IGDispatch.o')
|
||||
imports=command(['xcrun','nm','-u',output/'IGDispatch.o'])
|
||||
(output/'IGDispatch-imports.txt').write_text(imports)
|
||||
if {'_write','_close','_memcmp'} & set(imports.split()):
|
||||
raise ValueError('调度对象仍直接导入受保护目标或前缀比较函数')
|
||||
baseline=output/'baseline/Payload'/app.name
|
||||
guarded=output/'guarded/Payload'/app.name
|
||||
command(['ditto',app,baseline]);command(['ditto',app,guarded])
|
||||
executable=info['CFBundleExecutable'];original=baseline/executable;binary=guarded/executable
|
||||
profile=json.loads((ROOT/'tools/macho_guard/profiles/zipzap.json').read_text())
|
||||
roots=[r['caller'] for r in profile['rules']]
|
||||
new_binary=output/'patched-binary'
|
||||
report=patch(original,new_binary,linkmap,profile)
|
||||
report['trace_before']=trace_calls(original,linkmap,roots)
|
||||
report['trace_after']=trace_calls(new_binary,linkmap,roots)
|
||||
# 新调度可以间接调用,不能仍沿直接桩或经典 GOT 桥接到原 write/close。
|
||||
remaining=[r for r in report['trace_after'] if r.get('symbol') in ('_write','_close')]
|
||||
if remaining:raise ValueError('试点路径仍存在可恢复的原目标直接/GOT 桥接')
|
||||
if not any(r['kind']=='indirect_unresolved' for r in report['trace_after']):
|
||||
raise ValueError('未观察到预期的运行时间接调用')
|
||||
shutil.move(new_binary,binary)
|
||||
before,bt=scan(baseline,output,'before')
|
||||
targets={p for p in guarded.rglob('*') if not p.is_symlink() and p.suffix in ('.framework','.app','.appex','.xpc','.dylib')}
|
||||
targets.add(guarded)
|
||||
for p in sorted(targets,key=lambda p:(-len(p.parts),str(p))):command(['codesign','--force','--sign','-',p])
|
||||
for p in sorted(targets):command(['codesign','--verify','--strict','--verbose=2',p])
|
||||
after,at=scan(guarded,output,'after')
|
||||
if bt-at!=report['total']:raise ValueError('整包直接调用减少数与试点不一致')
|
||||
if before.keys()!=after.keys():raise ValueError('二进制清单变化')
|
||||
if [s['uuid'] for s in before[executable]['slices']]!=[s['uuid'] for s in after[executable]['slices']]:
|
||||
raise ValueError('UUID 变化')
|
||||
command(['xcrun','otool','-l',binary])
|
||||
for symbol in ('IG_dispatch_write','IG_dispatch_close','ig_resolve_verified'):
|
||||
text=command(['xcrun','llvm-objdump','--no-show-raw-insn',
|
||||
'--disassemble-symbols=_'+symbol,binary])
|
||||
(output/(symbol+'.asm')).write_text(text)
|
||||
symbols=command(['xcrun','nm',binary])
|
||||
if 'ig_dispatch_test_' in symbols:raise ValueError('发布产物残留测试接口')
|
||||
report['signed_output_sha256']=sha(binary)
|
||||
save(output/'redirect-report.json',report)
|
||||
save(output/'before-files.json',inventory(baseline.parent.parent))
|
||||
save(output/'after-files.json',inventory(guarded.parent.parent))
|
||||
command(['ditto','-c','-k','--sequesterRsrc','--keepParent',guarded.parent,output/'guarded.ipa'])
|
||||
command(['ditto','-x','-k',output/'guarded.ipa',output/'repack'])
|
||||
repacked,total=scan(output/'repack/Payload'/app.name,output,'repacked')
|
||||
if repacked!=after or total!=at:raise ValueError('重打包验证失败')
|
||||
shutil.rmtree(output/'repack')
|
||||
if sha(app/executable)!=report['input_sha256']:raise ValueError('输入构建产物意外变化')
|
||||
result.update(status='passed_local_checks',total_redirected=report['total'],before_total=bt,
|
||||
after_total=at,input_sha256=report['input_sha256'],
|
||||
output_sha256=report['signed_output_sha256'],ipa_sha256=sha(output/'guarded.ipa'),
|
||||
static_tracking_limitations=report['residual_tracking'])
|
||||
except Exception as exc:
|
||||
result.update(status='failed',error=str(exc));raise
|
||||
finally:save(output/'manifest.json',result)
|
||||
save(output/'evidence-hashes.json',inventory(output))
|
||||
print(json.dumps(result,ensure_ascii=False,indent=2))
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--app',type=Path,required=True);p.add_argument('--link-map',type=Path,required=True)
|
||||
p.add_argument('--build-log',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
|
||||
p.add_argument('--dispatch-object',type=Path,required=True)
|
||||
a=p.parse_args();run(a.app,a.link_map,a.build_log,a.dispatch_object,a.output)
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"_read": "_IG_read",
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"_fopen": "_IG_fopen",
|
||||
"_fclose": "_IG_fclose",
|
||||
"_fread": "_IG_fread",
|
||||
"_fwrite": "_IG_fwrite"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""兼容原 fopen PoC 命令;通用入口见 redirect_symbols.py。"""
|
||||
|
||||
from redirect_symbols import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(legacy_fopen=True)
|
||||
@@ -0,0 +1,241 @@
|
||||
#!/usr/bin/env python3
|
||||
"""由 JSON 映射驱动的 ARM64 Mach-O 静态归档外部 C 符号重定向工具。
|
||||
|
||||
只生成新文件;拒绝未知格式、目标符号冲突、动态库和实际 LLVM bitcode。
|
||||
允许并保留 __LLVM 内单字节零值的 bitcode/cmdline 占位标记。
|
||||
不改机器码或重定位索引,不自动生成 ABI 转发函数,不提供 IPA 加固保证。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ARCHIVE_MAGIC = b"!<arch>\n"
|
||||
DEFAULT_MAPPING = {"_fopen": "_IG_fopen"}
|
||||
CPU_ARM64 = 0x0100000C
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def bounds(data, offset, length):
|
||||
require(0 <= offset <= len(data) and 0 <= length <= len(data) - offset,
|
||||
"数据范围越界")
|
||||
|
||||
|
||||
def validate_mapping(mapping):
|
||||
require(isinstance(mapping, dict) and bool(mapping), "映射必须是非空 JSON 对象")
|
||||
for source, target in mapping.items():
|
||||
for name in (source, target):
|
||||
require(isinstance(name, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", name),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(len(set(mapping.values())) == len(mapping), "多个源符号不能共用一个目标")
|
||||
require(not set(mapping).intersection(mapping.values()), "不允许自映射、映射链或循环")
|
||||
return {source.encode("ascii"): target.encode("ascii") for source, target in mapping.items()}
|
||||
|
||||
|
||||
def load_mapping(path):
|
||||
def unique_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, f"JSON 映射存在重复键:{key}")
|
||||
result[key] = value
|
||||
return result
|
||||
mapping = json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique_pairs)
|
||||
validate_mapping(mapping)
|
||||
return mapping
|
||||
|
||||
|
||||
def redirect_object(data, mapping=None):
|
||||
rewritten, counts = _redirect_object(data, validate_mapping(DEFAULT_MAPPING if mapping is None else mapping))
|
||||
return rewritten, sum(counts.values())
|
||||
|
||||
|
||||
def _redirect_object(data, mapping):
|
||||
"""保持 nlist 索引及重定位不变,仅追加字符串、更新字符串偏移。"""
|
||||
bounds(data, 0, 32)
|
||||
magic, cpu, subtype, kind, count, size, _, _ = struct.unpack_from("<8I", data)
|
||||
require(magic == 0xFEEDFACF and cpu == CPU_ARM64 and subtype == 0,
|
||||
"仅支持 little-endian arm64(不含 arm64e)Mach-O 对象")
|
||||
require(kind == 1, "成员必须是 MH_OBJECT,不能处理可执行文件或动态库")
|
||||
bounds(data, 32, size)
|
||||
cursor = 32
|
||||
symtab = None
|
||||
for _ in range(count):
|
||||
require(cursor + 8 <= 32 + size, "load command 头越界")
|
||||
cmd, cmdsize = struct.unpack_from("<II", data, cursor)
|
||||
require(cmdsize >= 8 and cmdsize % 8 == 0 and cursor + cmdsize <= 32 + size,
|
||||
"load command 长度无效")
|
||||
require(cmd != 0x1D, "不支持含代码签名的对象")
|
||||
if cmd == 0x19:
|
||||
require(cmdsize >= 72, "segment command 太短")
|
||||
sections = struct.unpack_from("<I", data, cursor + 64)[0]
|
||||
require(72 + sections * 80 == cmdsize, "section 数量不匹配")
|
||||
for index in range(sections):
|
||||
pos = cursor + 72 + index * 80
|
||||
section_name = data[pos:pos + 16].rstrip(b"\0")
|
||||
segment = data[pos + 16:pos + 32].rstrip(b"\0")
|
||||
if segment == b"__LLVM":
|
||||
section_size = struct.unpack_from("<Q", data, pos + 40)[0]
|
||||
section_offset = struct.unpack_from("<I", data, pos + 48)[0]
|
||||
bounds(data, section_offset, section_size)
|
||||
require(section_name in (b"__bitcode", b"__cmdline") and section_size == 1
|
||||
and data[section_offset:section_offset + 1] == b"\0",
|
||||
"实际 LLVM bitcode 或未知 LLVM section 不在本 PoC 支持范围")
|
||||
if cmd == 2:
|
||||
require(symtab is None and cmdsize == 24, "LC_SYMTAB 重复或长度无效")
|
||||
symtab = cursor
|
||||
cursor += cmdsize
|
||||
require(cursor == 32 + size, "load command 总长度不匹配")
|
||||
require(symtab is not None, "对象缺少 LC_SYMTAB")
|
||||
symoff, nsyms, stroff, strsize = struct.unpack_from("<4I", data, symtab + 8)
|
||||
bounds(data, symoff, nsyms * 16)
|
||||
bounds(data, stroff, strsize)
|
||||
require(symoff >= cursor and stroff >= symoff + nsyms * 16,
|
||||
"不支持重叠或乱序的符号表/字符串表")
|
||||
# Apple 静态归档可能在对象尾部加入换行填充,也接受零填充。
|
||||
tail = data[stroff + strsize:]
|
||||
require(len(tail) <= 7 and (not tail or set(tail) <= {0} or set(tail) <= {10}),
|
||||
"字符串表后存在未知数据")
|
||||
strings = data[stroff:stroff + strsize]
|
||||
changed = []
|
||||
for index in range(nsyms):
|
||||
pos = symoff + index * 16
|
||||
strx, ntype, section, _, value = struct.unpack_from("<IBBHQ", data, pos)
|
||||
require(strx < strsize, "符号字符串索引越界")
|
||||
end = strings.find(b"\0", strx)
|
||||
require(end != -1, "符号名缺少终止符")
|
||||
name = strings[strx:end]
|
||||
require(name not in mapping.values(), f"归档已包含目标符号 {name!r},拒绝重复处理或冲突")
|
||||
if name in mapping:
|
||||
require(ntype == 1 and section == 0 and value == 0,
|
||||
f"{name!r} 必须是普通外部未定义符号,不能重写定义/common/debug 符号")
|
||||
changed.append((pos, name))
|
||||
if not changed:
|
||||
return data, Counter()
|
||||
output = bytearray(data[:stroff + strsize])
|
||||
offsets = {}
|
||||
counts = Counter()
|
||||
for pos, name in changed:
|
||||
if name not in offsets:
|
||||
offsets[name] = len(output) - stroff
|
||||
output.extend(mapping[name] + b"\0")
|
||||
struct.pack_into("<I", output, pos, offsets[name])
|
||||
counts[name.decode("ascii")] += 1
|
||||
# 保持对象长度为 8 字节对齐,填充也属于字符串表。
|
||||
output.extend(b"\0" * (-len(output) % 8))
|
||||
struct.pack_into("<I", output, symtab + 20, len(output) - stroff)
|
||||
return bytes(output), counts
|
||||
|
||||
|
||||
def redirect_archive(data, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
encoded_mapping = validate_mapping(mapping)
|
||||
require(data.startswith(ARCHIVE_MAGIC), "输入不是普通 ar 归档")
|
||||
output = bytearray(ARCHIVE_MAGIC)
|
||||
cursor = len(ARCHIVE_MAGIC)
|
||||
records = []
|
||||
members = 0
|
||||
totals = Counter({source: 0 for source in mapping})
|
||||
while cursor < len(data):
|
||||
bounds(data, cursor, 60)
|
||||
header = data[cursor:cursor + 60]
|
||||
require(header[58:60] == b"`\n", "ar 成员头无效")
|
||||
length = int(header[48:58].strip())
|
||||
bounds(data, cursor + 60, length)
|
||||
payload = data[cursor + 60:cursor + 60 + length]
|
||||
name = header[:16].rstrip(b" ")
|
||||
prefix = b""
|
||||
if name.startswith(b"#1/"):
|
||||
name_length = int(name[3:])
|
||||
require(0 < name_length <= len(payload), "BSD 扩展成员名长度无效")
|
||||
prefix, payload = payload[:name_length], payload[name_length:]
|
||||
name = prefix.rstrip(b"\0")
|
||||
else:
|
||||
require(not name.startswith(b"/"), "暂不支持 GNU 长名称或 GNU 索引格式")
|
||||
name = name.rstrip(b"/")
|
||||
require(bool(name), "空成员名")
|
||||
cursor += 60 + length
|
||||
if length % 2:
|
||||
bounds(data, cursor, 1)
|
||||
require(data[cursor:cursor + 1] == b"\n", "ar 填充无效")
|
||||
cursor += 1
|
||||
if name in (b"__.SYMDEF", b"__.SYMDEF SORTED", b"__.SYMDEF_64", b"__.SYMDEF_64 SORTED"):
|
||||
continue # 修改后必须由 ranlib 重建索引。
|
||||
try:
|
||||
rewritten, counts = _redirect_object(payload, encoded_mapping)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"成员 {os.fsdecode(name)}:{error}") from error
|
||||
members += 1
|
||||
if counts:
|
||||
totals.update(counts)
|
||||
records.append({"member_index": members, "member": os.fsdecode(name),
|
||||
"references": sum(counts.values()), "symbols": dict(counts)})
|
||||
combined = prefix + rewritten
|
||||
require(len(str(len(combined))) <= 10, "成员过大")
|
||||
output.extend(header[:48] + str(len(combined)).encode().ljust(10) + header[58:60])
|
||||
output.extend(combined)
|
||||
if len(combined) % 2:
|
||||
output.extend(b"\n")
|
||||
require(bool(records), "没有找到映射中的可重定向引用")
|
||||
unmatched = [source for source in mapping if not totals[source]]
|
||||
require(not require_all or not unmatched, f"要求全部命中,但缺少符号:{', '.join(unmatched)}")
|
||||
return bytes(output), {"members_checked": members, "changed_members": records,
|
||||
"references_redirected": sum(totals.values()),
|
||||
"symbol_counts": dict(totals), "unmatched_symbols": unmatched}
|
||||
|
||||
|
||||
def run(source, destination, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
validate_mapping(mapping)
|
||||
source, destination = source.resolve(), destination.absolute()
|
||||
require(source != destination.resolve(), "不能覆盖输入")
|
||||
require(not destination.exists() and not destination.is_symlink(), "输出已存在,拒绝覆盖")
|
||||
original = source.read_bytes()
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-", dir=destination.parent) as folder:
|
||||
thin = Path(folder) / "input.a"
|
||||
if original.startswith(ARCHIVE_MAGIC):
|
||||
thin.write_bytes(original)
|
||||
else:
|
||||
require(original[:4] in (b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"),
|
||||
"仅接受 BSD 静态归档或包含该归档的 fat 文件")
|
||||
subprocess.run(["xcrun", "lipo", str(source), "-thin", "arm64", "-output", str(thin)], check=True)
|
||||
archive, report = redirect_archive(thin.read_bytes(), mapping, require_all)
|
||||
candidate = Path(folder) / "redirected.a"
|
||||
candidate.write_bytes(archive)
|
||||
subprocess.run(["xcrun", "ranlib", str(candidate)], check=True)
|
||||
report.update({"source": str(source), "output": str(destination), "architecture": "arm64",
|
||||
"source_sha256": hashlib.sha256(original).hexdigest(),
|
||||
"output_sha256": hashlib.sha256(candidate.read_bytes()).hexdigest(),
|
||||
"mapping": dict(mapping)})
|
||||
# 同目录硬链接原子发布,目标已存在时失败,避免竞争覆盖。
|
||||
os.link(candidate, destination)
|
||||
return report
|
||||
|
||||
|
||||
def main(legacy_fopen=False):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("output", type=Path, help="不存在的新 .a 路径;父目录须存在")
|
||||
if not legacy_fopen:
|
||||
parser.add_argument("--mapping", type=Path, required=True, help="精确的 Mach-O C 符号映射 JSON")
|
||||
parser.add_argument("--require-all", action="store_true", help="每个源符号均须命中,否则不输出")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
mapping = DEFAULT_MAPPING if legacy_fopen else load_mapping(args.mapping)
|
||||
print(json.dumps(run(args.input, args.output, mapping, args.require_all), ensure_ascii=False, indent=2))
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
parser.exit(1, f"重定向失败:{error}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user