Files
iOSGuard/tools/macho_guard/build_dispatch_device.py
shenleiandClaude Opus 4.8 599e1da5ce 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>
2026-11-12 22:16:47 +09:00

70 lines
4.5 KiB
Python

#!/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)