Files
iOSGuard/tools/macho_guard/build_hook_device.py
T
shenlei 704ee66834 feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固
- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测
- llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言)
- tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化)
- tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
2026-11-24 15:00:07 +09:00

123 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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', '-DIG_OBSERVATION=1',
'-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)