Files
iOSGuard/tools/macho_guard/build_poison_device.py
T
shenleiandClaude Opus 4.8 b76d7cdc21 harden(defender): docs/18 §7 抗静态分析硬化(符号隐藏/串混淆/副本分散/基线派生)
针对「纯客户端抗静态分析」的最高性价比项落地,守在 tests/test_static_hardening.py(6 条,gate 于 iphoneos SDK):

- 符号隐藏 + strip(§7.0 新增):IGVisibility.h 定 IG_INTERNAL=hidden,全库
  -fvisibility=hidden;仅四入口 ig_defender_scan/ig_poison_init/ig_poison_apply/
  ig_policy_scan_and_mark 标 IG_PUBLIC 保持导出,其余 ig_* 变 private external,
  链接后 strip -x 彻底消失——攻击者 nm 不再能按名定位 ig_poison_mark/mask 去 NOP。
- §7.1 串混淆:gen_jb_paths.py(唯一真源)生成 IGJailbreakPaths.inc /
  IGInjectSignatures.inc(XOR keystream,两表不共享 key),运行期解码进栈、用完擦除;
  decode 内 volatile key 屏障阻止 -O2 把常量折叠回 __const 明文。strings 已捞不到
  /var/jb、Cydia、substrate、gum-js-loop 等。--check 守 .inc 与清单同步。
- §7.2 副本分散:g_h0/h1/h2 置于不相邻命名段 __DATA,__ig_p0/p1/p2,加 __ig_pd 诱饵
  (mask 不读);刻意不用 TLS(会破坏跨线程毒化一致性)。
- §7.4 基线派生:删硬编码 0xA5C3F10E7B2D4968,改 ig_poison_baseline() 由拆分种子经
  volatile 屏障派生;otool -tV 已无旧魔数立即数。
- §7.3 OLLVM/VMP:仅留 build 的 IG_OBFUSCATOR hook,stock clang 无能力,需另备工具链(未完成)。
- §7.5 越狱设备正向验证仍阻塞(无设备)。

构建/快照同步:build_defender_lib.sh 加 -fvisibility=hidden + gen --check + IG_OBFUSCATOR
hook;build_poison_device.py 快照纳入 *.inc。全量 69 测试通过;poison_device.m 全模块
iphoneos 交叉编译通过(arm64)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-13 10:47:35 +09:00

120 lines
5.7 KiB
Python
Executable File
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
"""构建处置链真机验证诊断 App(step12,见 docs/19)。
验证 poison/policy/anti_jailbreak 这条「检测→分级→数据毒化」链在真机的行为。
只支持匹配的 wildcard 开发 profile,专用 Bundle ID 前缀避免复用业务标识;
构建后不安装、不更新开发者门户。诊断进程只被动探测,不含注入/攻击构造 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.poisonpilot.'
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')),
*list((ROOT / 'defender').rglob('*.inc')), # §7.1 混淆表(.inc),否则快照编译缺头
ROOT / 'tests/fixtures/poison_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 / 'IGPoisonPilot.app'
app.mkdir()
info = dict(CFBundleExecutable='IGPoisonPilot', CFBundleIdentifier=bundle,
CFBundleName='IGPoisonPilot', CFBundleDisplayName='IG Poison 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']
# 处置链 + 其依赖的聚合扫描全套模块(ig_policy_scan_and_mark → ig_defender_scan)。
modules = ['poison/IGPoison.c', 'policy/IGPolicy.c',
'anti_jailbreak/IGAntiJailbreak.c', 'syscall/IGSyscall.c',
'IGDefender.c', 'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c',
'anti_frida/IGAntiInject.c', 'anti_debug/IGAntiDebug.c',
'resolve/IGResolve.c', 'dispatch/IGDispatch.c',
'dispatch/IGArchiveGuard.c', 'call_bridge/IGFileBridge.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)
command(common + ['-fobjc-arc', source / 'tests/fixtures/poison_device.m', *objects,
'-framework', 'UIKit', '-framework', 'Foundation',
'-lobjc', '-o', app / 'IGPoisonPilot'],
blog, 'link app')
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)