在 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>
129 lines
9.1 KiB
Python
129 lines
9.1 KiB
Python
#!/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)
|