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:
@@ -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')
|
||||
Reference in New Issue
Block a user