fix(defender): ObjC 方法基线改用构建期签名清单,修复误报 110 导致的延迟闪退

- 构建期生成随包签名的 IGMethods.bin(仅主程序),运行时按镜像 UUID、
  入口偏移与函数边界内指令摘要校验;导出审计复核清单与最终镜像一致
- 系统函数、调度与解包保护的代码前缀按 LC_FUNCTION_STARTS 限定在函数边界内
- 边界内识别 B / LDR+BR / ADRP+ADD+BR / MOVK+BR 蹦床并确认目标归属,避免系统尾调用误报
- 登记前 IMP 已落入匿名内存判为改写;清单读取改走 IG_dispatch_open
- 函数边界长度按入口缓存;镜像未重新链接时复用基线;Debug 附加调试器时不按入口摘要判定改写
- 补充宿主测试;删除已过时的 README 与 docs 历史文档,保留 THIRD_PARTY_NOTICES
This commit is contained in:
shenlei
2026-11-25 10:57:21 +09:00
parent a340075c1d
commit 01fd5acdab
46 changed files with 771 additions and 4640 deletions
@@ -368,6 +368,13 @@ def audit_ipa(
f'变体符号 {invalid_images}'
)
from objc_method_baseline import NAME, generate
expected = unpacked / 'expected-method-baseline.bin'
report['objc_method_count'] = generate(app, main_bin, expected)
sealed = app / NAME
if not sealed.is_file() or sealed.read_bytes() != expected.read_bytes():
raise ValueError('导出的 IPA 方法基线缺失或与最终镜像不一致')
hygiene = _check_static_hygiene(app, main_bin, info)
report['static_hygiene'] = hygiene
if not hygiene['passed']:
@@ -543,6 +543,29 @@ def restore_route2_off(app_dir, main_bin, audit_dir, app_repo, dsym_folder=None)
return removed_guard, restored
def write_method_baseline(app_dir, main_bin, audit_dir):
"""生成随包签名的 ObjC 方法基线;镜像未重新链接时复用上次结果。
链接器按内容生成 UUID,签名不改变 UUID,因此 UUID 未变即代码未变。
"""
import objc_method_baseline as baseline
output = app_dir / baseline.NAME
lines = [hashlib.sha256(Path(baseline.__file__).read_bytes()).hexdigest()]
for image in baseline.input_images(app_dir, main_bin):
lines.append(f'{image.relative_to(app_dir)} {baseline.image_uuid(image).hex()}')
key = '\n'.join(lines)
stamp = audit_dir / 'objc-method-baseline.stamp'
if output.is_file() and stamp.is_file():
digest = hashlib.sha256(output.read_bytes()).hexdigest()
if stamp.read_text(encoding='utf-8') == f'{key}\n{digest}':
print('[objc-baseline] images unchanged, reuse existing baseline')
return
count = baseline.generate(app_dir, main_bin, output)
audit_dir.mkdir(parents=True, exist_ok=True)
stamp.write_text(f'{key}\n{hashlib.sha256(output.read_bytes()).hexdigest()}', encoding='utf-8')
print(f'[objc-baseline] {count} methods')
def main():
off_reason = None
if os.environ.get('IG_DISABLE_ROUTE2_ARCHIVE') == '1':
@@ -554,7 +577,8 @@ def main():
config = os.environ.get('CONFIGURATION', '')
platform = os.environ.get('PLATFORM_NAME', '')
if config != 'Release' or platform != 'iphoneos':
if platform not in ('iphoneos', 'iphonesimulator') or (
platform == 'iphonesimulator' and 'arm64' not in os.environ.get('ARCHS', '').split()):
print(f'[IGRoute2] frameworks phase skipped: CONFIGURATION={config} PLATFORM_NAME={platform}')
return 0
@@ -567,6 +591,10 @@ def main():
audit_dir = target_temp_dir / 'ig-route2-audit'
app_repo = resolve_app_repo(TOOLCHAIN_ROOT)
if config != 'Release' or platform != 'iphoneos':
write_method_baseline(app_dir, main_bin, audit_dir)
return 0
if off_reason:
removed_guard, restored = restore_route2_off(
app_dir, main_bin, audit_dir, app_repo, dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH')
@@ -575,6 +603,7 @@ def main():
f'[IGRoute2] frameworks phase off ({off_reason}): '
f'removed_guard={removed_guard}, restored={len(restored)}'
)
write_method_baseline(app_dir, main_bin, audit_dir)
return 0
defender_dir = resolve_defender_dir(TOOLCHAIN_ROOT, app_repo)
@@ -587,6 +616,7 @@ def main():
dsym_folder=os.environ.get('DWARF_DSYM_FOLDER_PATH'),
debug_info_format=os.environ.get('DEBUG_INFORMATION_FORMAT', ''),
)
write_method_baseline(app_dir, main_bin, audit_dir)
print(
f'[IGRoute2] frameworks audit OK for {app_dir.name}: '
f'binaries={summary["binaries"]}, rewritten={summary["frameworks_rewritten"]}, '
+1 -1
View File
@@ -1330,7 +1330,7 @@ def verify_patched_main(binary_path, linkmap_path):
if sites:
attributed = list(attribute(Path(binary_path), Path(linkmap_path)))
details = [
f"{s.get('symbol')} in {s.get('caller', '?')} ({s.get('object', '?')}) @ 0x{s['site']:x}"
f"{s.get('symbol')} in {s.get('caller', '?')} ({s.get('object', '?')}) @ {s['site']}"
for s in attributed[:20]
]
raise RuntimeError(
+162
View File
@@ -0,0 +1,162 @@
"""从最终链接的 arm64 镜像生成随应用签名的 ObjC 方法基线。"""
import hashlib
import os
from pathlib import Path
import re
import struct
import subprocess
import sys
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'macho_guard'))
from batch import Slice
from machox import Macho
NAME = 'IGMethods.bin'
MAGIC = b'IGMB0001'
ROW = struct.Struct('<32s16sQI32s4x')
METHOD = re.compile(r'^\s*(0x[0-9a-fA-F]+)\s+([+-])\[([^ (]+)(?:\([^)]*\))? ([^\]]+)\]$')
def _is_top_level_swift_objc_class(name):
raw = name.encode('utf-8')
if not raw.startswith(b'_TtC'):
return False
idx = 4
for _ in range(2):
start = idx
while idx < len(raw) and 48 <= raw[idx] <= 57:
idx += 1
if idx == start:
return False
length = int(raw[start:idx])
if length <= 0 or idx + length > len(raw):
return False
idx += length
return idx == len(raw)
def image_records(binary):
data = binary.read_bytes()
if data[:4] in (bytes.fromhex('cafebabe'), bytes.fromhex('cafebabf')):
with tempfile.TemporaryDirectory() as tmp:
thin = Path(tmp) / 'arm64'
subprocess.run(['xcrun', 'lipo', str(binary), '-thin', 'arm64', '-output', str(thin)], check=True)
data = thin.read_bytes()
image = Macho(data)
uuid, = [data[o + 8:o + 24] for cmd, _, o in image.cmds if cmd == 0x1b]
layout = Slice(data, 0)
listing = subprocess.check_output(
['xcrun', 'dyld_info', '-arch', 'arm64', '-function_starts', '-objc', str(binary)],
text=True,
)
start_listing, marker, objc_listing = listing.partition(' -objc:')
if not marker or ' -function_starts:' not in start_listing:
raise ValueError(f'无法解析 dyld_info 输出: {binary.name}')
starts = sorted({int(a, 16) for a in re.findall(r'^\s*(0x[0-9a-fA-F]+)\s', start_listing, re.M)})
methods = [m.groups() for line in objc_listing.splitlines() if (m := METHOD.match(line))]
# 同一镜像内,任一已知方法入口也构成前一方法的上界。
start_set = set(starts)
boundaries = sorted(start_set.union(int(addr, 16) for addr, _, _, _ in methods))
lengths = {a: min(32, b - a) for a, b in zip(boundaries, boundaries[1:]) if a in start_set}
records = []
swift_names = sorted({cls for _, _, cls, _ in methods if _is_top_level_swift_objc_class(cls)})
runtime_names = {}
if swift_names:
demangled = subprocess.run(['xcrun', 'swift-demangle', '--compact'],
input='\n'.join(swift_names) + '\n', text=True,
check=True, stdout=subprocess.PIPE).stdout.splitlines()
if len(demangled) != len(swift_names):
raise ValueError(f'Swift 类名解析失败: {binary.name}')
runtime_names = dict(zip(swift_names, demangled))
text, text_size, offset = layout.text or (0, 0, 0)
for address, kind, cls, selector in methods:
cls = runtime_names.get(cls, cls)
addr = int(address, 16)
# 方法元数据给出了入口,缺少完整边界时只读取首条指令。
length = lengths.get(addr, 4)
pos = offset + addr - text
if pos < 0 or pos + length > len(data) or addr % 4 or length % 4 or not (text <= addr and addr + length <= text + text_size):
length = 0
key = hashlib.sha256(f'{kind}{cls} {selector}'.encode()).digest()
digest = hashlib.sha256(data[pos:pos + length]).digest() if length else bytes(32)
records.append((key, uuid, addr - layout.text_vmaddr if length else 0, length, digest))
return uuid, records
def input_images(app, main):
"""只记录主程序(Debug 还包括承载代码的 *.debug.dylib)。
受监控的方法都在主镜像中;Framework 的方法从不登记,收录它们只会增加包体与构建耗时,
并可能与主镜像同名方法冲突。新增监控方法须位于主镜像,否则运行时记为校验不可用。
"""
return [main, *sorted(app.glob('*.debug.dylib'))]
def image_uuid(binary):
"""只读取 Mach-O 头部取 arm64 切片的 LC_UUID,用于判断镜像是否重新链接。"""
with open(binary, 'rb') as f:
head = f.read(4096)
base = 0
if head[:4] in (bytes.fromhex('cafebabe'), bytes.fromhex('cafebabf')):
wide = head[3] == 0xbf
step = 32 if wide else 20
count, = struct.unpack_from('>I', head, 4)
for i in range(count):
cpu, sub = struct.unpack_from('>II', head, 8 + i * step)
if cpu == 0x0100000c and (sub & 0x00ffffff) == 0:
base, = struct.unpack_from('>Q' if wide else '>I', head, 16 + i * step)
break
else:
raise ValueError(f'缺少 arm64 切片: {binary}')
f.seek(base)
magic, _, _, _, ncmds, sizeofcmds = struct.unpack('<IiiIII', f.read(24))
if magic != 0xfeedfacf:
raise ValueError(f'不是 64 位 Mach-O: {binary}')
f.seek(base + 32)
cmds = f.read(sizeofcmds)
off = 0
for _ in range(ncmds):
cmd, size = struct.unpack_from('<II', cmds, off)
if cmd == 0x1b:
return cmds[off + 8:off + 24]
if size < 8:
break
off += size
raise ValueError(f'缺少 LC_UUID: {binary}')
def generate(app, main, output):
images = input_images(app, main)
records = {}
for binary in images:
uuid, rows = image_records(binary)
if binary == main:
main_uuid = uuid
for row in rows:
key = row[0]
if key in records and records[key] != row:
# 同一方法存在多个分类实现;缺少唯一预期时保留为不可判定。
records[key] = (key, bytes(16), 0, 0, b'')
else:
records[key] = row
if not any(row[3] for row in records.values()):
raise ValueError('产物缺少可校验的 Objective-C 方法元数据')
with tempfile.NamedTemporaryFile(dir=output.parent, delete=False) as f:
temp = Path(f.name)
try:
f.write(MAGIC + main_uuid)
for key in sorted(records):
f.write(ROW.pack(*records[key]))
f.flush()
os.chmod(temp, 0o644)
os.replace(temp, output)
finally:
if temp.exists():
temp.unlink()
return len(records)
if __name__ == '__main__':
app, main = map(Path, sys.argv[1:])
print(f'[objc-baseline] {generate(app, main, app / NAME)} methods')