Files
iOSGuard/tests/test_static_hardening.py
shenleiandClaude Opus 4.8 e3d2a48d56 harden(poison): 修命名段挂牌泄漏——毒化副本改匿名数组分散(对抗自验)
对「链接+strip 的宿主」做攻击者视角自验(nm/otool -l/-tV/strings),揪出上一版
§7.2 的反效果设计:三副本用自定义命名段 __DATA,__ig_p0/p1/p2/pd,而命名段原样留在
Mach-O load command、strip 也抹不掉——otool -l | grep __ig_p 一把定位毒化副本位置,
比匿名 BSS 更糟(等于在 header 上挂牌)。

修法:三真副本+诱饵散进一个匿名数组 g_state[12] 的非相邻下标(IG_LANE={2,7,11}、
IG_DECOY=5,其余陪衬槽),全进匿名 __bss/__data;每槽存 baseline^lane_k(i) 使各槽值
互不相同,消除「数组里几个相同的字=一组健康值」的静态 tell;mask 只读三真副本。
mask 语义不变(健康→0,毒化→非0,无分支),毒化语义测试全过。

回归守卫:tests/test_static_hardening.py 新增 test_no_telegraphing_sections,
守 .a 不再出现 __ig_/__poison 等泄漏性命名段。

另记录自验第二发现(已写进 docs/18 §7.0):四个 public 入口名 _ig_poison_* 的字样
本身泄露用途,strip -x 抹不掉,须 readoor Release 用完整 strip(style=all) 或接入层包中性名。

设备 poison_device.m 全模块 iphoneos 交叉编译 arm64 通过;全量 70 测试通过。

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

144 lines
6.9 KiB
Python
Raw Permalink 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.
"""静态硬化回归(docs/18 §7):守住「抗静态分析」几条不被后续改动悄悄打回。
验收(对 iphoneos 产物):
1. §7.1 strings 捞不到越狱路径 / 注入特征串 / frida 线程名等明文常量。
2. 符号可见性:只有 IG_PUBLIC 四入口导出(T);内部 ig_* 不以外部符号导出,
且链接进可执行文件 strip 后彻底消失。
3. §7.4 旧基线魔数 0xA5C3F10E7B2D4968 不以明文/立即数出现在反汇编。
4. 混淆表 .inc 与 gen_jb_paths.py 清单一致(防手改 .inc 或漏重生成)。
需 Xcode + iphoneos SDK;缺则跳过。
"""
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
# strings 里绝不应出现的明文特征(越狱路径 + 注入/frida 特征 + 线程名)。
FORBIDDEN = [
'cydia', '/var/jb', '/bin/bash', 'tweakinject', 'sileo', 'mobilesubstrate',
'ig_jb_probe', 'gum-js-loop', 'pool-frida', 'pool-spawner', 'gmain', 'gdbus',
'linjector', 'cynject', 'cycript', 'libhooker', 'rocketbootstrap', 'flexloader',
'shadowhook', 'substitute', 'gadget', 'dobby', 'fishhook',
]
PUBLIC = {'_ig_defender_scan', '_ig_poison_init', '_ig_poison_apply', '_ig_policy_scan_and_mark'}
INTERNAL = ['_ig_poison_mark', '_ig_poison_mask', '_ig_policy_sink',
'_ig_policy_evaluate_and_mark', '_ig_anti_jb_check', '_ig_anti_inject_check']
OLD_MAGIC = ['a5c3f10e', '7b2d4968']
def have_sdk():
if sys.platform != 'darwin' or not shutil.which('xcrun'):
return False
r = subprocess.run(['xcrun', '--sdk', 'iphoneos', '--show-sdk-path'],
capture_output=True, text=True)
return r.returncode == 0 and r.stdout.strip() != ''
@unittest.skipUnless(have_sdk(), '需要 Xcode + iphoneos SDK')
class StaticHardeningTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.dist = Path(cls.tmp.name) / 'dist'
r = subprocess.run(['sh', str(ROOT / 'tools/build_defender_lib.sh'), str(cls.dist)],
capture_output=True, text=True)
if r.returncode:
raise RuntimeError(r.stdout + r.stderr)
cls.lib = cls.dist / 'lib/libIGDefender.a'
cls.inc = cls.dist / 'include'
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def _nm(self, path, *extra):
return subprocess.run(['xcrun', '--sdk', 'iphoneos', 'nm', *extra, str(path)],
capture_output=True, text=True).stdout
def test_no_plaintext_needles(self):
"""§7.1:strings 不含任何越狱/注入/frida 明文特征。"""
out = subprocess.run(['strings', '-a', str(self.lib)],
capture_output=True, text=True).stdout.lower()
hit = [w for w in FORBIDDEN if w in out]
self.assertEqual(hit, [], f'明文特征泄漏:{hit}')
def test_gen_table_in_sync(self):
"""混淆表 .inc 与清单一致。"""
r = subprocess.run([sys.executable, str(ROOT / 'tools/gen_jb_paths.py'), '--check'],
capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
def _defined_class(self):
"""解析 nm -m,返回 {symbol: 'private external'|'external'}(只取已定义符号)。
.a 阶段 nm -g 无法区分 private-extern(仍显示 T),须用 nm -m 看 N_PEXT 位。"""
cls = {}
for line in self._nm(self.lib, '-m').splitlines():
if '(undefined)' in line or ') ' not in line:
continue
sym = line.rsplit(' ', 1)[-1]
if 'private external' in line:
cls[sym] = 'private external'
elif 'external' in line:
cls[sym] = 'external'
return cls
def test_internal_symbols_private(self):
"""内部符号为 private external(-fvisibility=hidden 生效),最终 strip 即消失。"""
cls = self._defined_class()
for sym in INTERNAL:
if sym in cls: # 已定义者必须是 private external,不能是普通 external
self.assertEqual(cls[sym], 'private external', f'{sym} 未私有化:{cls[sym]}')
def test_public_entries_exported(self):
"""四个 IG_PUBLIC 入口为普通 external(保持导出,供接入方引用)。"""
cls = self._defined_class()
for sym in PUBLIC:
self.assertEqual(cls.get(sym), 'external', f'{sym} 非导出 external:{cls.get(sym)}')
def test_strip_removes_internal(self):
"""链接进可执行文件 + strip -x 后,内部 ig_* 名彻底消失。"""
w = Path(self.tmp.name)
src = w / 'main.c'
src.write_text('#include "IGGuard.h"\n'
'int main(){ ig_poison_init(); uint8_t k[4]={1,2,3,4},o[4];\n'
' ig_policy_scan_and_mark("/x",0,0,0); ig_poison_apply(k,o,4); return o[0]; }\n')
app = w / 'app'
r = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
'-miphoneos-version-min=15.0', '-O2', '-I', str(self.inc),
str(src), str(self.lib), '-lobjc', '-framework', 'Foundation',
'-o', str(app)], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
subprocess.run(['xcrun', '--sdk', 'iphoneos', 'strip', '-x', str(app)], check=True)
out = self._nm(app)
for sym in INTERNAL:
self.assertNotIn(sym, out, f'strip 后仍残留 {sym}')
def test_baseline_magic_absent(self):
"""§7.4:旧基线魔数不以明文/立即数出现在反汇编。"""
dis = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'otool', '-tV', str(self.lib)],
capture_output=True, text=True).stdout.lower()
hit = [m for m in OLD_MAGIC if m in dis]
self.assertEqual(hit, [], f'旧基线魔数残留:{hit}')
def test_no_telegraphing_sections(self):
"""§7.2:不得用会「挂牌」的自定义命名 section。
命名 section(如旧实现的 __ig_p0/p1/p2/pd)会原样留在 Mach-O load command 里,
strip 也抹不掉,等于把毒化副本位置写进 header 供 otool -l 一把定位——比匿名 BSS 更糟。
毒化状态须存进匿名 __bss/__data。本测试守 .a 不出现 __ig_/__poison 等泄漏性节名。"""
out = subprocess.run(['xcrun', '--sdk', 'iphoneos', 'otool', '-l', str(self.lib)],
capture_output=True, text=True).stdout.lower()
leak = [ln.split('sectname', 1)[1].strip()
for ln in out.splitlines() if 'sectname' in ln
and ('__ig' in ln or '__poison' in ln or '__ig_p' in ln)]
self.assertEqual(leak, [], f'泄漏性命名 section(strip 抹不掉,会挂牌毒化副本位置):{leak}')
if __name__ == '__main__':
unittest.main()