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:
shenlei
2026-11-24 15:00:07 +09:00
parent 1094cc2760
commit 704ee66834
106 changed files with 27487 additions and 286 deletions
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Xcode Release arm64 C/ObjC compiler wrapper (3-stage LLVM bitcode -> opt -> native Mach-O)."""
import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile
SCRIPT_DIR = Path(__file__).resolve().parent
TOOLS_DIR = SCRIPT_DIR.parent
TOOLCHAIN_ROOT = TOOLS_DIR.parent
sys.path.insert(0, str(SCRIPT_DIR))
sys.path.insert(0, str(TOOLS_DIR / 'llvm_obf'))
from ig_toolchain_resolver import ( # noqa: E402
detect_sdk_info,
detect_stock_tool,
detect_xcode_info,
discover_active_app_repo,
file_sha256,
resolve_effective_policy,
resolve_opt,
)
SOURCE_EXTENSIONS = {'.c', '.m', '.mm', '.cc', '.cpp', '.cxx', '.c++'}
def resolve_default_policy(profile='default'):
names = [f'ig_llvm_policy_{profile}.json'] if profile and profile != 'default' else []
names.append('ig_llvm_policy.json')
for name in names:
for cand in (
TOOLCHAIN_ROOT / 'config' / name,
TOOLCHAIN_ROOT / 'llvm_obf' / name,
):
if cand.is_file():
return str(cand)
return ''
def expand_response_files(args):
expanded = []
for arg in args:
if arg.startswith('@') and len(arg) > 1:
resp = Path(arg[1:])
if resp.is_file():
text = resp.read_text(encoding='utf-8', errors='replace')
expanded.extend(shlex.split(text))
continue
expanded.append(arg)
return expanded
def parse_control_token(expanded_args):
"""Extract control tuple from `-DIG_OBF_CTL_<mode>__<filter>__<route2>__<all_off>__<seed>__<stamp>[__<profile>]=1`."""
ctl = {
'mode': 'full',
'filter': 'all',
'route2': 'on',
'all_off': '0',
'seed': 'm0_seed_20261119_v1',
'stamp': 'default',
'policy_profile': 'default',
}
prefix = '-DIG_OBF_CTL_'
for arg in expanded_args:
if arg.startswith(prefix):
body = arg[len(prefix):]
if '=' in body:
body = body.split('=', 1)[0]
parts = body.split('__')
if len(parts) >= 7:
ctl['mode'] = parts[0] or ctl['mode']
ctl['filter'] = parts[1] or ctl['filter']
ctl['route2'] = parts[2] or ctl['route2']
ctl['all_off'] = parts[3] or ctl['all_off']
ctl['seed'] = parts[4] or ctl['seed']
ctl['stamp'] = parts[5] or ctl['stamp']
ctl['policy_profile'] = '__'.join(parts[6:]) or ctl['policy_profile']
elif len(parts) >= 6:
ctl['mode'] = parts[0] or ctl['mode']
ctl['filter'] = parts[1] or ctl['filter']
ctl['route2'] = parts[2] or ctl['route2']
ctl['all_off'] = parts[3] or ctl['all_off']
ctl['seed'] = parts[4] or ctl['seed']
ctl['stamp'] = '__'.join(parts[5:]) or ctl['stamp']
elif len(parts) >= 1 and parts[0]:
ctl['mode'] = parts[0]
# Env overrides take precedence if explicitly set
if os.environ.get('IG_DISABLE_LLVM_OBF') == '1':
ctl['mode'] = 'off'
if os.environ.get('IG_ALL_GUARD_OFF') == '1':
ctl['all_off'] = '1'
ctl['mode'] = 'off'
if os.environ.get('IG_OBF_MODE'):
ctl['mode'] = os.environ['IG_OBF_MODE']
if os.environ.get('IG_LLVM_PASS_FILTER'):
ctl['filter'] = os.environ['IG_LLVM_PASS_FILTER']
if os.environ.get('IG_RELEASE_SEED'):
ctl['seed'] = os.environ['IG_RELEASE_SEED']
if os.environ.get('IG_POLICY_PROFILE'):
ctl['policy_profile'] = os.environ['IG_POLICY_PROFILE']
if ctl['all_off'] == '1':
ctl['mode'] = 'off'
return ctl
def parse_compile_metadata(raw_args, expanded_args):
has_c = '-c' in expanded_args
out_path = None
top_out_idx = None
for idx, arg in enumerate(raw_args):
if arg == '-o' and idx + 1 < len(raw_args):
top_out_idx = idx + 1
out_path = raw_args[idx + 1]
if out_path is None:
for idx, arg in enumerate(expanded_args):
if arg == '-o' and idx + 1 < len(expanded_args):
out_path = expanded_args[idx + 1]
lang = None
isysroot = None
target = None
arch = None
min_ver_flag = None
opt_flag = None
debug_flags = []
extra_codegen = []
source_path = None
i = 0
skip_next_flags = {
'-o', '-I', '-isystem', '-iquote', '-F', '-iframework', '-include',
'-include-pch', '-MT', '-MF', '-MQ', '-D', '-U', '-x', '-target',
'-arch', '-isysroot', '-ivfsoverlay', '-index-store-path',
'-index-unit-output-path', '--serialize-diagnostics', '-dependency-info',
'-pch-output-dir', '-fmodule-map-file', '-Xclang', '-Xpreprocessor',
'-idirafter', '-iprefix', '-iwithprefix', '-iwithprefixbefore', '-B',
}
while i < len(expanded_args):
a = expanded_args[i]
nxt = expanded_args[i + 1] if i + 1 < len(expanded_args) else None
if a == '-x' and nxt is not None:
lang = nxt
i += 2
continue
if a == '-target' and nxt is not None:
target = nxt
i += 2
continue
if a.startswith('--target='):
target = a.split('=', 1)[1]
i += 1
continue
if a == '-arch' and nxt is not None:
arch = nxt
i += 2
continue
if a == '-isysroot' and nxt is not None:
isysroot = nxt
i += 2
continue
if a.startswith('-miphoneos-version-min=') or a.startswith('-mllvm'):
if a.startswith('-miphoneos-version-min='):
min_ver_flag = a
elif nxt is not None:
i += 2
continue
i += 1
continue
if a in ('-O0', '-O1', '-O2', '-O3', '-Os', '-Oz', '-Ofast'):
opt_flag = a
i += 1
continue
if a.startswith('-g') and not a.startswith('-gmodules') and a != '-g0':
debug_flags.append(a)
i += 1
continue
if a in ('-fPIC', '-fpic', '-fno-common', '-fstrict-aliasing', '-fno-strict-aliasing') or (
a.startswith('-fvisibility=')
or a.startswith('-fstack-protector')
or a.startswith('-ffile-prefix-map=')
or a.startswith('-fdebug-prefix-map=')
or a.startswith('-fembed-bitcode')
):
extra_codegen.append(a)
i += 1
continue
if a in skip_next_flags and nxt is not None:
i += 2
continue
if not a.startswith('-'):
if Path(a).suffix.lower() in SOURCE_EXTENSIONS:
source_path = a
i += 1
return {
'has_c': has_c,
'out_path': out_path,
'top_out_idx': top_out_idx,
'lang': lang,
'isysroot': isysroot,
'target': target,
'arch': arch,
'min_ver_flag': min_ver_flag,
'opt_flag': opt_flag or '-Os',
'debug_flags': debug_flags,
'extra_codegen': extra_codegen,
'source_path': source_path,
}
def should_passthrough(meta, expanded_args, ctl, policy):
if ctl['all_off'] == '1' or ctl['mode'] == 'off':
return True, f"mode={ctl['mode']} all_off={ctl['all_off']}"
if os.environ.get('PLATFORM_NAME') and os.environ.get('PLATFORM_NAME') != 'iphoneos':
return True, f"platform={os.environ.get('PLATFORM_NAME')}"
if os.environ.get('CONFIGURATION') and os.environ.get('CONFIGURATION') != 'Release':
return True, f"config={os.environ.get('CONFIGURATION')}"
if not meta['has_c'] or not meta['out_path']:
return True, 'not single -c object compile'
if any(f in expanded_args for f in ('-E', '-M', '-MM', '-fsyntax-only', '--analyze', '-emit-llvm', '-S')):
return True, 'preprocess/syntax/emit-llvm/asm mode'
if meta['lang'] and (meta['lang'].endswith('-header') or meta['lang'] in ('ir', 'assembler', 'assembler-with-cpp')):
return True, f"lang={meta['lang']}"
out_suf = Path(meta['out_path']).suffix.lower()
if out_suf in ('.pch', '.gch', '.pcm'):
return True, f'precompiled header output {out_suf}'
if meta['arch'] and meta['arch'] != 'arm64':
return True, f"non-arm64 arch {meta['arch']}"
if meta['target'] and 'arm64' not in meta['target']:
return True, f"non-arm64 target {meta['target']}"
if meta['isysroot'] and 'iPhoneSimulator' in meta['isysroot']:
return True, 'simulator sdk'
src = meta['source_path'] or ''
if not src:
return True, 'no C/ObjC/C++ source path'
for ex in policy.get('exempt_path_substrings', []):
if ex in src:
return True, f'exempt path ({ex})'
return False, ''
def build_stage3_flags(meta):
flags = []
if meta['target']:
flags.extend(['-target', meta['target']])
else:
flags.extend(['-arch', meta['arch'] or 'arm64'])
if meta['min_ver_flag']:
flags.append(meta['min_ver_flag'])
if meta['isysroot']:
flags.extend(['-isysroot', meta['isysroot']])
if meta['target'] and meta['min_ver_flag'] and 'ios' not in meta['target']:
flags.append(meta['min_ver_flag'])
flags.append(meta['opt_flag'])
flags.extend(meta['debug_flags'])
flags.extend(meta['extra_codegen'])
flags.extend(['-Xclang', '-disable-llvm-passes', '-fno-builtin', '-Wno-override-module', '-x', 'ir', '-c'])
return flags
def infer_obj_cache_dir(out_path):
env_dir = os.environ.get('IG_OBF_OBJ_CACHE_DIR')
if env_dir:
return Path(env_dir)
for parent in out_path.parents:
if parent.name in ('Intermediates.noindex', 'Build'):
return parent / 'ig-obf-obj-cache'
return out_path.parent / '.ig-obf-obj-cache'
def run_wrapper(argv=None, cxx=False):
raw_args = list(sys.argv[1:] if argv is None else argv)
tool_name = 'clang++' if cxx else 'clang'
real_cc = detect_stock_tool(tool_name)
expanded_args = expand_response_files(raw_args)
ctl = parse_control_token(expanded_args)
policy_path = os.environ.get('IG_LLVM_POLICY_PATH') or resolve_default_policy(ctl.get('policy_profile', 'default'))
policy = {}
if policy_path and Path(policy_path).is_file():
policy = json.loads(Path(policy_path).read_text(encoding='utf-8'))
meta = parse_compile_metadata(raw_args, expanded_args)
passthrough, _ = should_passthrough(meta, expanded_args, ctl, policy)
if passthrough:
if meta.get('out_path'):
stale_audit = Path(str(meta['out_path']) + '.ig-audit.json')
if stale_audit.exists():
try:
stale_audit.unlink()
except OSError:
pass
os.execv(real_cc, [real_cc, *raw_args])
return 0
require_obf = os.environ.get('IG_REQUIRE_LLVM_OBF') == '1' or ctl['mode'] in ('full', 'str', 'noop')
tc = resolve_opt(require_obf=require_obf)
opt_path = tc.get('opt_path')
if not opt_path:
sys.stderr.write(f"[IGCC] WARNING: {tc.get('warning', 'opt unavailable')}; falling back to stock {tool_name}\n")
os.execv(real_cc, [real_cc, *raw_args])
return 0
out_path = Path(meta['out_path'])
out_path.parent.mkdir(parents=True, exist_ok=True)
audit_sidecar = Path(str(out_path) + '.ig-audit.json')
app_repo = discover_active_app_repo([meta.get('source_path') or ''])
eff_policy_path, _eff_policy = resolve_effective_policy(policy_path, app_repo, infer_obj_cache_dir(out_path))
stage3_prefix = build_stage3_flags(meta)
xc_build = tc['xcode']['xcode_build']
sdk_info = detect_sdk_info(meta['isysroot']) if meta['isysroot'] else {'sdk_version': ''}
wrapper_sha = file_sha256(__file__)
policy_sha = file_sha256(eff_policy_path) if eff_policy_path and Path(eff_policy_path).is_file() else 'none'
with tempfile.TemporaryDirectory(prefix='.ig-cc-', dir=out_path.parent) as td:
work = Path(td)
bc_path = work / 'stage1.bc'
obf_bc_path = work / 'stage2.obf.bc'
# Stage 1: stock clang -> bitcode (preserving .pch, .d, .dia generation!)
s1_args = list(raw_args)
if meta['top_out_idx'] is not None:
s1_args[meta['top_out_idx']] = str(bc_path)
else:
s1_args.extend(['-o', str(bc_path)])
s1_args.append('-emit-llvm')
p1 = subprocess.run([real_cc, *s1_args])
if p1.returncode != 0:
return p1.returncode
bc_sha = file_sha256(bc_path)
key_hash = hashlib.sha256(
json.dumps(
{
'kind': 'cc_v1',
'bc_sha256': bc_sha,
'xcode_build': xc_build,
'sdk_version': sdk_info.get('sdk_version', ''),
'opt_sha256': tc['opt_sha256'],
'wrapper_sha256': wrapper_sha,
'policy_sha256': policy_sha,
'mode': ctl['mode'],
'filter': ctl['filter'],
'seed': ctl['seed'],
'stamp': ctl['stamp'],
'stage3': stage3_prefix,
},
sort_keys=True,
).encode('utf-8')
).hexdigest()[:24]
cache_dir = infer_obj_cache_dir(out_path) / key_hash[:2]
cached_obj = cache_dir / f'{key_hash}.o'
cached_audit = cache_dir / f'{key_hash}.audit.json'
if cached_obj.is_file() and cached_audit.is_file():
shutil.copy2(cached_obj, out_path)
shutil.copy2(cached_audit, audit_sidecar)
return 0
# Stage 2: standalone opt
opt_cmd = [
opt_path,
'-passes=ig-obfuscate',
f'--ig-policy={eff_policy_path}',
f"--ig-mode={ctl['mode']}",
f"--ig-pass-filter={ctl['filter']}",
f"--ig-seed={ctl['seed']}",
f"--ig-source-path={meta['source_path'] or ''}",
f'--ig-audit-out={audit_sidecar}',
str(bc_path),
'-o',
str(obf_bc_path),
]
p2 = subprocess.run(opt_cmd)
if p2.returncode != 0:
return p2.returncode
# Stage 3: stock clang pure backend lowering (no duplicate middle-end IR passes)
s3_cmd = [real_cc, *stage3_prefix, str(obf_bc_path), '-o', str(out_path)]
p3 = subprocess.run(s3_cmd)
if p3.returncode != 0:
return p3.returncode
# Atomic cache save (.o + .audit.json sidecar)
try:
cache_dir.mkdir(parents=True, exist_ok=True)
tmp_o = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.o'
tmp_a = cache_dir / f'.tmp-{key_hash}-{os.getpid()}.audit.json'
shutil.copy2(out_path, tmp_o)
shutil.copy2(audit_sidecar, tmp_a)
tmp_o.replace(cached_obj)
tmp_a.replace(cached_audit)
except OSError:
pass
return 0
if __name__ == '__main__':
raise SystemExit(run_wrapper(cxx=False))