#!/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/RDCoreIO.framework' if folder.exists():raise ValueError('保护 Framework 已存在') folder.mkdir() (folder/'Info.plist').write_bytes(plistlib.dumps(dict( CFBundleExecutable='RDCoreIO',CFBundleIdentifier='cn.touchv.readoor.coreio', CFBundleName='RDCoreIO',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', '-DIG_ARCHIVE_INTERNAL_RESOLVE=1', '-I',ROOT/'defender','-I',ROOT/'defender/include','-dynamiclib', *(ROOT/'defender'/p for p in sources), '-Wl,-install_name,@rpath/RDCoreIO.framework/RDCoreIO', '-Wl,-map,'+str(output/'archive-guard-link.map'), *(f'-Wl,-exported_symbol,_{n}' for n in ['rd_a0','rd_a1','rd_a2','rd_a3','rd_io_chk','ig_archive_counter']), '-o',folder/'RDCoreIO']) symbols=command(['xcrun','nm','-g',folder/'RDCoreIO']) 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)