"""静态硬化回归(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;缺则跳过。 """ import json from pathlib import Path import re 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}') def test_no_diagnostic_strings_in_release(self): """Release 构建(无 DEBUG/IG_OBSERVATION)不得残留探针 subject/evidence 明文诊断串。""" with tempfile.TemporaryDirectory() as td: ar_dir = Path(td) subprocess.run(['xcrun', '--sdk', 'iphoneos', 'ar', 'x', str(self.lib)], cwd=ar_dir, check=True) cstrings = bytearray() for obj in sorted(ar_dir.glob('*.o')): out = subprocess.run( ['xcrun', '--sdk', 'iphoneos', 'otool', '-s', '__TEXT', '__cstring', str(obj)], capture_output=True, text=True, check=True, ).stdout for line in out.splitlines(): parts = line.split('\t') if len(parts) == 2: for hx in parts[1].strip().split(): try: cstrings.append(int(hx, 16)) except ValueError: pass raw = bytes(cstrings) diag_needles = [ b'cryptid==0', b'CS_VALID', b'get-task-allow', b'P_TRACED', b'DYLD_INSERT_LIBRARIES', b'dispatch-write', b'dispatch-target', b'archive-target', b'task_threads', '蹦床'.encode('utf-8'), '基线'.encode('utf-8'), '重签'.encode('utf-8'), '提供方'.encode('utf-8'), '弱信号'.encode('utf-8'), ] hits = [n.decode('utf-8', errors='replace') for n in diag_needles if n in raw] self.assertEqual(hits, [], f'Release libIGDefender.a __cstring 残留诊断明文串:{hits}') def test_m1_objc_hybrid_hardening_coverage(self): """M1:RDEpubCryptBridge 基线监控 >= 30 条,高敏 OC 扩展进入压平与串加密策略,核心 OC 类锁定 L1。""" bridge_src = (ROOT / 'readoor-test/readoor/3.0/Base/Security/RDEpubCryptBridge.m').read_text(encoding='utf-8') watch_count = len(re.findall(r'sel_getName\(@selector\(', bridge_src)) self.assertGreaterEqual(watch_count, 30, f'Expected >= 30 baseline watches, got {watch_count}') policy = json.loads((ROOT / 'config/ig_llvm_policy.json').read_text(encoding='utf-8')) expected_paths = [ 'BookShelf/Classes/Features/IAP/Extension/', 'BookShelf/Classes/Features/Login/Extension/', 'BookShelf/Classes/Extension/ControllersExtension/STSBaseViewController+STSReadOrPayExtension.m', 'BookView/EPUB/Core/Classes/STSBaseViewController+STSEpubViewLoginOrPayExtension.m', 'BookView/PDF/Core/Classes/Stage/STSBaseViewController+STSPDFViewLoginOrPayExtension.m', ] str_paths = {r.get('path_contains') for r in policy.get('string_encrypt_targets', [])} fla_paths = {r.get('path_contains') for r in policy.get('flatten_targets', [])} for p in expected_paths: self.assertIn(p, str_paths, f'Missing from string_encrypt_targets: {p}') self.assertIn(p, fla_paths, f'Missing from flatten_targets: {p}') build_py = (ROOT / 'tools/llvm_obf/build_obfuscated_ipa.py').read_text(encoding='utf-8') for cls_name in ( 'STSIAPHandler', 'STSIAPVerifyHandler', 'STSIAPKeyChainHandler', 'STSIAPVerifyTask', 'STSJailbreakDetectTool', ): self.assertIn(f"'{cls_name}'", build_py, f'Missing from unobfuscated_watch_classes: {cls_name}') if __name__ == '__main__': unittest.main()