Files
iOSGuard/tests/test_macho_guard.py
shenleiandClaude Opus 4.8 599e1da5ce feat(defender): 可集成静态库 + readoor 接入方案(检测→分级→数据毒化闭环)
在 iOSGuard 侧产出可集成产物与接入文档,不修改 readoor 代码。

- defender/: anti_hook/anti_frida/anti_debug/anti_jailbreak 探针 + syscall 直发、
  policy 分级层、poison 数据依赖毒化、dispatch/resolve/call_bridge 等子模块
- poison: 三副本冗余、无分支掩码;健康恒等、毒化破坏 key(替代 if-exit 处置)
- policy: STRONG/MEDIUM/WEAK 分级,守误报底线,仅 DETECTED 参与、组合命中才毒化
- anti_jailbreak: IGSyscall 直发 svc 检测越狱文件(400)/沙盒逃逸(401),绕 libc hook
- tools/build_defender_lib.sh: 一键交叉编译打包 libIGDefender.a(arm64) + umbrella 头
- docs/18_READOOR_DEFENDER_INTEGRATION.md: 精确到文件/bridging/替换点/代码片段
- docs/05-17 + evidence + tests + macho_guard/static_sdk_redirect 工具链

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-12 22:16:47 +09:00

169 lines
7.5 KiB
Python

"""用真实 Apple 链接器生成样本,验证注入、指令及拒绝路径。"""
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/macho_guard'))
import batch
import macho_guard as guard
from machox import Macho
from verify_baseline import inspect_binary, validate_zip
from redirect_to_runtime import patch, trace_calls
@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('xcrun'), '需要 Xcode')
class MachoTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.src = Path(cls.tmp.name)/'fixture.dylib'
cls.linkmap = Path(cls.tmp.name)/'fixture.map'
subprocess.run(['xcrun','--sdk','iphoneos','clang','-arch','arm64',
'-miphoneos-version-min=15.0','-dynamiclib',
'-Wl,-headerpad,0x1000',
'-Wl,-map,'+str(cls.linkmap),
str(ROOT/'tests/fixtures/macho_calls.c'),'-o',str(cls.src)],
check=True, capture_output=True)
cls.original = cls.src.read_bytes()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def test_rewrite_preserves_got_and_branch_targets(self):
with tempfile.TemporaryDirectory() as td:
dst = Path(td)/'guarded'
before, sites = inspect_binary(self.src)
self.assertEqual({s['symbol'] for s in sites}, {'_getpid','_write'})
count, n, _, va = guard.harden_thin(self.src, dst)
after, remaining = inspect_binary(dst)
self.assertEqual(sum(count.values()),len(sites))
self.assertEqual(remaining, [])
m = Macho(dst.read_bytes())
self.assertEqual(m.segs['__IGUARD']['initprot'],5)
self.assertEqual(guard.find_stub_got_slots(m),
guard.find_stub_got_slots(Macho(self.original)))
view = batch.Slice(dst.read_bytes(),0)
old_view = batch.Slice(self.original,0)
addr, length, off = view.text
old_off = old_view.text[2]
changes = []
for i in range(0,length,4):
old, = struct.unpack_from('<I',self.original,old_off+i)
new, = struct.unpack_from('<I',m.d,off+i)
if old==new:
continue
changes.append(i)
self.assertEqual(old & 0xfc000000,new & 0xfc000000)
imm = new & 0x3ffffff
if imm & (1<<25): imm -= 1<<26
self.assertTrue(va <= addr+i+imm*4 < va+n*12)
self.assertEqual(len(changes),len(sites))
self.assertEqual(self.src.read_bytes(),self.original)
self.assertEqual(before['slices'][0]['uuid'],after['slices'][0]['uuid'])
def test_reject_duplicate_injection_and_input_overwrite(self):
with tempfile.TemporaryDirectory() as td:
dst = Path(td)/'out'
guard.inject(self.src,dst)
with self.assertRaisesRegex(ValueError,'重复'):
guard.inject(dst,Path(td)/'again')
with self.assertRaisesRegex(ValueError,'覆盖'):
guard.inject(self.src,self.src)
def test_reject_unsupported_architecture_and_truncation(self):
for offset, value in [(4,0x01000007),(8,2)]:
data = bytearray(self.original)
struct.pack_into('<I',data,offset,value)
with self.assertRaises(ValueError): Macho(data)
for size in (0,4,31,64,len(self.original)-1):
with self.subTest(size=size), self.assertRaises(ValueError):
Macho(self.original[:size])
def test_reject_encrypted_image(self):
data = bytearray(self.original)
m = Macho(data)
# 在已有 padding 中追加 encryption_info_command_64。
end = 32+m.sizeofcmds
data[end:end+24] = struct.pack('<6I',0x2c,24,0,0,1,0)
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+24)
with self.assertRaisesRegex(ValueError,'加密'): Macho(data)
def test_reject_insufficient_header_space(self):
with tempfile.TemporaryDirectory() as td:
data = bytearray(self.original)
m = Macho(data)
# 保留现有命令,用合法空命令填满 padding,只剩不足 72B。
end = 32+m.sizeofcmds
first = guard._first_section_fileoff(m)
size = (first-end)//8*8
struct.pack_into('<II',data,end,0x7777,size)
struct.pack_into('<II',data,16,m.ncmds+1,m.sizeofcmds+size)
src,dst = Path(td)/'src',Path(td)/'dst'
src.write_bytes(data)
with self.assertRaisesRegex(AssertionError,'空间不足'):
guard.inject(src,dst)
self.assertFalse(dst.exists())
def test_targeted_rewrite_and_trace(self):
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
destination='_fixture_redirect',expected_count=1)]}
with tempfile.TemporaryDirectory() as td:
dst=Path(td)/'patched'
report=patch(self.src,dst,self.linkmap,profile)
self.assertEqual(report['total'],1)
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
self.assertNotIn('_getpid',{r.get('symbol') for r in rows})
self.assertIn('_write',{r.get('symbol') for r in rows})
with self.assertRaises(ValueError):patch(self.src,dst,self.linkmap,profile)
def test_targeted_reject_stale_map(self):
with tempfile.TemporaryDirectory() as td:
lm=Path(td)/'bad.map'
lm.write_text('0x1 0x4 [1] _fixture_calls\n0x2 0x4 [1] _fixture_redirect\n')
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
destination='_fixture_redirect',expected_count=1)]}
with self.assertRaisesRegex(ValueError,'不匹配'):
patch(self.src,Path(td)/'out',lm,profile)
def test_map_with_non_utf8_sdk_symbol(self):
with tempfile.TemporaryDirectory() as td:
lm=Path(td)/'sdk.map'
lm.write_bytes(b'0x1 0x4 [1] sdk_\xf0\xff\n'+self.linkmap.read_bytes())
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
destination='_fixture_redirect',expected_count=1)]}
report=patch(self.src,Path(td)/'out',lm,profile)
self.assertEqual(report['total'],1)
def test_targeted_reject_wrong_count(self):
with tempfile.TemporaryDirectory() as td:
profile={'rules':[dict(caller='_fixture_calls',symbol='_getpid',
destination='_fixture_redirect',expected_count=2)]}
with self.assertRaises(ValueError):patch(self.src,Path(td)/'out',self.linkmap,profile)
def test_trace_recovers_injected_got_bridge(self):
with tempfile.TemporaryDirectory() as td:
dst=Path(td)/'bridge'
guard.harden_thin(self.src,dst)
rows=trace_calls(dst,self.linkmap,['_fixture_calls'])
self.assertEqual({r.get('symbol') for r in rows if r['kind']=='got_bridge'},
{'_getpid','_write'})
class ArchiveTests(unittest.TestCase):
def test_reject_zip_escape(self):
import zipfile
with tempfile.TemporaryDirectory() as td:
path = Path(td)/'bad.ipa'
with zipfile.ZipFile(path,'w') as z: z.writestr('../escape','bad')
with self.assertRaises(ValueError): validate_zip(path)
if __name__ == '__main__':
unittest.main()