feat: 集成 LLVM IR 混淆体系、Route 2 全量合规与系统调用调度加固
- defender: 扩展 IGDispatch/IGArchiveGuard/IGAntiHook/IGObjCBaseline/IGResolve,支持 Route 2 静态库桥接 (IGThreadID.c) 与防重签名检测 - llvm_passes: 新增 IGObfuscator LLVM IR 插件源码(控制流平坦化、字符串加密、间接跳转/调用、不透明常量/字段、MBA、函数外提、基本块拆分、反 Hook 序言) - tools & config: 新增 Xcode 归档编译/链接包装器、LLVM 自愈工具链 (ig_toolchain_resolver)、IPA 审计门禁、崩溃符号还原及最新 ig_llvm_policy.json(文件级匹配 + 3.0 全业务 Handler 平坦化) - tests & docs: 补齐 M0~M3、Pass 单测及系统调用调度/Route 2/LLVM 方案文档;.gitignore 忽略 *.bc 与 .obfuscate_extraction_cache.json
This commit is contained in:
Executable
+280
@@ -0,0 +1,280 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Symbolicate modern JSON (.ips) and classic text (.crash) Apple crash reports with UUID enforcement."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FRAME_LINE_RE = re.compile(
|
||||
r'^(\d+)\s+(\S+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)(?:\s*\+\s*(\d+))?(.*)$'
|
||||
)
|
||||
BIN_IMAGE_RE = re.compile(
|
||||
r'^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+(\S+)\s+(\S+)\s+<([0-9a-fA-F-]+)>\s+(.+)$'
|
||||
)
|
||||
|
||||
|
||||
def norm_uuid(u):
|
||||
return str(u).replace('-', '').upper()
|
||||
|
||||
|
||||
def index_dsyms(dsym_root):
|
||||
"""Map normalized UUID -> {'arch': ..., 'dwarf': Path, 'dsym': Path}."""
|
||||
mapping = {}
|
||||
root = Path(dsym_root)
|
||||
candidates = []
|
||||
if root.is_dir() and root.suffix == '.dSYM':
|
||||
candidates.append(root)
|
||||
elif root.is_dir():
|
||||
candidates.extend(sorted(root.glob('*.dSYM')))
|
||||
else:
|
||||
raise FileNotFoundError(f'dSYM path not found: {root}')
|
||||
|
||||
for dsym in candidates:
|
||||
dwarf_dir = dsym / 'Contents' / 'Resources' / 'DWARF'
|
||||
if not dwarf_dir.is_dir():
|
||||
continue
|
||||
out = subprocess.check_output(['xcrun', 'dwarfdump', '--uuid', str(dsym)], text=True)
|
||||
for line in out.splitlines():
|
||||
m = re.match(r'^UUID:\s*([0-9A-Fa-f-]+)\s+\(([^)]+)\)\s+(.+)$', line.strip())
|
||||
if m:
|
||||
uid = norm_uuid(m.group(1))
|
||||
arch = m.group(2)
|
||||
dwarf_path = Path(m.group(3).strip())
|
||||
mapping[uid] = {'arch': arch, 'dwarf': dwarf_path, 'dsym': dsym}
|
||||
return mapping
|
||||
|
||||
|
||||
def _unwrap_v2_mappings(raw) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
if isinstance(raw.get('mappings'), dict) and (
|
||||
'schema_version' in raw or raw.get('kind') in ('symbol_map', 'method_map')
|
||||
):
|
||||
return raw['mappings']
|
||||
return raw
|
||||
|
||||
|
||||
def load_reverse_maps(symbol_map_path=None, method_map_path=None):
|
||||
cls_rev = {}
|
||||
sel_rev = {}
|
||||
if symbol_map_path and Path(symbol_map_path).is_file():
|
||||
raw = _unwrap_v2_mappings(json.loads(Path(symbol_map_path).read_text(encoding='utf-8')))
|
||||
for orig, obf in raw.items():
|
||||
if isinstance(obf, str):
|
||||
cls_rev[obf] = orig
|
||||
elif isinstance(obf, dict) and isinstance(obf.get('obfuscated'), str):
|
||||
cls_rev[obf['obfuscated']] = orig
|
||||
if method_map_path and Path(method_map_path).is_file():
|
||||
raw = _unwrap_v2_mappings(json.loads(Path(method_map_path).read_text(encoding='utf-8')))
|
||||
for orig, obf in raw.items():
|
||||
if isinstance(obf, str):
|
||||
sel_rev[obf] = orig
|
||||
if ':' in orig:
|
||||
orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig)
|
||||
for idx, orig_part in enumerate(orig_parts, start=1):
|
||||
sel_rev.setdefault(f'{obf}_{idx}:', orig_part)
|
||||
if orig_parts:
|
||||
sel_rev.setdefault(f'{obf}_1', orig_parts[0][:-1])
|
||||
elif isinstance(obf, list):
|
||||
for item in obf:
|
||||
if isinstance(item, str):
|
||||
sel_rev[item] = orig
|
||||
elif isinstance(obf, dict):
|
||||
full_obf = obf.get('obfuscated')
|
||||
tok = obf.get('token')
|
||||
parts = obf.get('parts')
|
||||
if isinstance(full_obf, str) and full_obf:
|
||||
sel_rev[full_obf] = orig
|
||||
if obf.get('kind') == 'objc_selector' and isinstance(parts, list) and ':' in orig:
|
||||
orig_parts = re.findall(r'[A-Za-z_][A-Za-z0-9_]*:', orig)
|
||||
if len(orig_parts) == len(parts):
|
||||
for obf_part, orig_part in zip(parts, orig_parts):
|
||||
norm_obf = obf_part if obf_part.endswith(':') else f'{obf_part}:'
|
||||
sel_rev.setdefault(norm_obf, orig_part)
|
||||
if isinstance(tok, str) and tok and orig_parts:
|
||||
sel_rev.setdefault(tok, orig_parts[0][:-1])
|
||||
elif isinstance(tok, str) and tok:
|
||||
sel_rev[tok] = orig
|
||||
return cls_rev, sel_rev
|
||||
|
||||
|
||||
def deobfuscate_symbol_text(text, cls_rev, sel_rev):
|
||||
out = text
|
||||
combined = {}
|
||||
combined.update(cls_rev)
|
||||
combined.update(sel_rev)
|
||||
for obf, orig in sorted(combined.items(), key=lambda kv: -len(kv[0])):
|
||||
if not obf or obf not in out:
|
||||
continue
|
||||
if ':' in obf:
|
||||
out = out.replace(obf, orig)
|
||||
else:
|
||||
out = re.sub(r'(?<![A-Za-z0-9_])' + re.escape(obf) + r'(?![A-Za-z0-9_])', orig, out)
|
||||
return out
|
||||
|
||||
|
||||
def atos_lookup(dwarf_path, load_addr_hex, addr_hex, arch='arm64'):
|
||||
out = subprocess.check_output(
|
||||
['xcrun', 'atos', '-arch', arch, '-o', str(dwarf_path), '-l', load_addr_hex, '-inlineFrames', addr_hex],
|
||||
text=True,
|
||||
).strip()
|
||||
return [line.strip() for line in out.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def parse_ips(text):
|
||||
lines = [l for l in text.splitlines() if l.strip()]
|
||||
if not lines:
|
||||
raise ValueError('Empty .ips report')
|
||||
header = json.loads(lines[0])
|
||||
body = json.loads('\n'.join(lines[1:])) if len(lines) > 1 else header
|
||||
return header, body
|
||||
|
||||
|
||||
def symbolicate_ips(text, dsym_index, cls_rev, sel_rev):
|
||||
_, body = parse_ips(text)
|
||||
used_images = body.get('usedImages') or []
|
||||
results = []
|
||||
for t_idx, thread in enumerate(body.get('threads') or []):
|
||||
if not thread.get('triggered') and len(body.get('threads') or []) > 1 and t_idx != 0:
|
||||
continue
|
||||
frames_out = []
|
||||
for f_idx, frame in enumerate(thread.get('frames') or []):
|
||||
img_idx = frame.get('imageIndex')
|
||||
img_off = frame.get('imageOffset')
|
||||
if img_idx is None or img_off is None or img_idx >= len(used_images):
|
||||
continue
|
||||
img = used_images[img_idx]
|
||||
uid = norm_uuid(img.get('uuid', ''))
|
||||
base = img.get('base', 0)
|
||||
name = img.get('name', img.get('path', f'img_{img_idx}'))
|
||||
addr_hex = hex(base + img_off)
|
||||
base_hex = hex(base)
|
||||
dsym_entry = dsym_index.get(uid)
|
||||
if not dsym_entry:
|
||||
# Require UUID match for app/embedded bundle binaries
|
||||
img_path = img.get('path', '')
|
||||
if '.app/' in img_path:
|
||||
raise RuntimeError(
|
||||
f'UUID mismatch or missing dSYM for bundle image {name} (uuid={img.get("uuid")})'
|
||||
)
|
||||
frames_out.append({
|
||||
'frame_index': f_idx,
|
||||
'image': name,
|
||||
'uuid': img.get('uuid'),
|
||||
'address': addr_hex,
|
||||
'status': 'system_or_unindexed',
|
||||
'inline_frames': [],
|
||||
})
|
||||
continue
|
||||
raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img.get('arch', 'arm64'))
|
||||
restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms]
|
||||
frames_out.append({
|
||||
'frame_index': f_idx,
|
||||
'image': name,
|
||||
'uuid': img.get('uuid'),
|
||||
'dsym': str(dsym_entry['dsym']),
|
||||
'load_address': base_hex,
|
||||
'address': addr_hex,
|
||||
'status': 'symbolicated',
|
||||
'raw_atos': raw_syms,
|
||||
'restored_frames': restored,
|
||||
})
|
||||
results.append({'thread_index': t_idx, 'triggered': bool(thread.get('triggered')), 'frames': frames_out})
|
||||
return {'format': 'ips_json', 'threads': results}
|
||||
|
||||
|
||||
def symbolicate_crash(text, dsym_index, cls_rev, sel_rev):
|
||||
images_by_name = {}
|
||||
in_bin_images = False
|
||||
for line in text.splitlines():
|
||||
if line.strip().startswith('Binary Images:'):
|
||||
in_bin_images = True
|
||||
continue
|
||||
if in_bin_images:
|
||||
m = BIN_IMAGE_RE.match(line)
|
||||
if m:
|
||||
start_hex, _, name, arch, uid_str, path = m.groups()
|
||||
images_by_name[name] = {
|
||||
'base_hex': start_hex,
|
||||
'name': name,
|
||||
'arch': arch,
|
||||
'uuid': uid_str,
|
||||
'uuid_norm': norm_uuid(uid_str),
|
||||
'path': path.strip(),
|
||||
}
|
||||
|
||||
frames_out = []
|
||||
for line in text.splitlines():
|
||||
m = FRAME_LINE_RE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
f_idx, img_name, addr_hex, base_or_sym, _, _ = m.groups()
|
||||
img = images_by_name.get(img_name)
|
||||
if not img:
|
||||
continue
|
||||
uid = img['uuid_norm']
|
||||
base_hex = img['base_hex']
|
||||
dsym_entry = dsym_index.get(uid)
|
||||
if not dsym_entry:
|
||||
if '.app/' in img['path']:
|
||||
raise RuntimeError(
|
||||
f'UUID mismatch or missing dSYM for bundle image {img_name} (uuid={img["uuid"]})'
|
||||
)
|
||||
frames_out.append({
|
||||
'frame_index': int(f_idx),
|
||||
'image': img_name,
|
||||
'uuid': img['uuid'],
|
||||
'address': addr_hex,
|
||||
'status': 'system_or_unindexed',
|
||||
'restored_frames': [],
|
||||
})
|
||||
continue
|
||||
raw_syms = atos_lookup(dsym_entry['dwarf'], base_hex, addr_hex, arch=img['arch'])
|
||||
restored = [deobfuscate_symbol_text(s, cls_rev, sel_rev) for s in raw_syms]
|
||||
frames_out.append({
|
||||
'frame_index': int(f_idx),
|
||||
'image': img_name,
|
||||
'uuid': img['uuid'],
|
||||
'dsym': str(dsym_entry['dsym']),
|
||||
'load_address': base_hex,
|
||||
'address': addr_hex,
|
||||
'status': 'symbolicated',
|
||||
'raw_atos': raw_syms,
|
||||
'restored_frames': restored,
|
||||
})
|
||||
return {'format': 'crash_text', 'images_parsed': len(images_by_name), 'frames': frames_out}
|
||||
|
||||
|
||||
def restore_report(report_path, dsym_dir, symbol_map=None, method_map=None):
|
||||
text = Path(report_path).read_text(encoding='utf-8', errors='replace')
|
||||
dsym_index = index_dsyms(dsym_dir)
|
||||
cls_rev, sel_rev = load_reverse_maps(symbol_map, method_map)
|
||||
|
||||
first_nonempty = next((l.strip() for l in text.splitlines() if l.strip()), '')
|
||||
if first_nonempty.startswith('{'):
|
||||
return symbolicate_ips(text, dsym_index, cls_rev, sel_rev)
|
||||
return symbolicate_crash(text, dsym_index, cls_rev, sel_rev)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--report', required=True, type=Path)
|
||||
p.add_argument('--dsym-dir', required=True, type=Path)
|
||||
p.add_argument('--symbol-map', type=Path)
|
||||
p.add_argument('--method-map', type=Path)
|
||||
p.add_argument('--out', type=Path)
|
||||
args = p.parse_args()
|
||||
|
||||
res = restore_report(args.report, args.dsym_dir, args.symbol_map, args.method_map)
|
||||
text = json.dumps(res, ensure_ascii=False, indent=2) + '\n'
|
||||
if args.out:
|
||||
args.out.write_text(text, encoding='utf-8')
|
||||
else:
|
||||
sys.stdout.write(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user