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
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Attribute direct calls in a Mach-O to objects in its same-build Link Map."""
import argparse
from bisect import bisect_right
import csv
from pathlib import Path
import re
from machox import Macho
from redirect_to_runtime import defined_symbols
from verify_baseline import inspect_binary
def load_link_map(path):
objects, symbols = {}, []
section = ''
for line in path.read_text(errors='replace').splitlines():
if line in ('# Object files:', '# Sections:', '# Symbols:', '# Dead Stripped Symbols:'):
section = line
elif line.startswith('# '):
continue
elif section == '# Object files:':
match = re.fullmatch(r'\[\s*(\d+)\]\s+(.+)', line)
if match:
objects[int(match[1])] = match[2]
elif section == '# Symbols:':
match = re.fullmatch(r'(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+\[\s*(\d+)\]\s+(.+)', line)
if match and int(match[2], 16):
symbols.append((int(match[1], 16), int(match[2], 16), int(match[3]), match[4]))
if not objects or not symbols:
raise ValueError(f'Incomplete Link Map: {path}')
return objects, sorted(symbols)
def attribute(binary, link_map):
objects, entries = load_link_map(link_map)
defined = defined_symbols(Macho(binary.read_bytes()))
# Require matching named functions before trusting the object addresses.
common = [(address, defined[name]) for address, _, _, name in entries if name in defined]
if not common or any(mapped != actual for mapped, actual in common):
raise ValueError('Link Map symbols do not match executable')
_, calls = inspect_binary(binary)
starts = [entry[0] for entry in entries]
for call in calls:
site = int(call['site'], 16)
index = bisect_right(starts, site) - 1
if index >= 0:
address, size, obj, name = entries[index]
if site < address + size and (index == 0 or starts[index - 1] != address):
call.update(caller=name, object=objects.get(obj, ''))
yield call
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('binary', type=Path)
parser.add_argument('link_map', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
rows = list(attribute(args.binary, args.link_map))
with args.output.open('x', newline='') as stream:
writer = csv.DictWriter(stream, fieldnames=['slice_offset', 'site', 'target', 'branch', 'symbol', 'caller', 'object'])
writer.writeheader()
writer.writerows(rows)
+1 -1
View File
@@ -73,7 +73,7 @@ def build(profile, identity, bundle, output):
(app / 'Info.plist').write_bytes(plistlib.dumps(info))
common = ['xcrun', '--sdk', 'iphoneos', 'clang', '-arch', 'arm64',
'-miphoneos-version-min=15.0', '-O2',
'-miphoneos-version-min=15.0', '-O2', '-DIG_OBSERVATION=1',
'-I', source / 'defender', '-I', source / 'defender/include']
modules = ['IGDefender.c', 'dispatch/IGDispatch.c', 'resolve/IGResolve.c',
'anti_hook/IGAntiHook.c', 'anti_hook/IGObjCBaseline.c',
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Relink one captured release command with hash-verified SDK candidate inputs."""
import argparse
import hashlib
import json
from pathlib import Path
import shlex
import subprocess
from redirect_to_runtime import patch
def sha(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def relink(log, manifest_path, output, working_directory):
manifest = json.loads(manifest_path.read_text())
root = manifest_path.parent
verified = set()
for record in manifest['files']:
path = (root / record['path']).resolve()
verified.add(path)
if sha(path) != record['sha256']:
raise ValueError(f'SDK candidate changed: {path}')
required = [(root / item).resolve() for item in manifest['objects']]
required += [(root / rule['file']).resolve() for rule in manifest['replacements']]
required.append((root / manifest['patch_profile']).resolve())
if not set(required) <= verified:
raise ValueError('Candidate file missing from hash manifest')
commands = []
for line in log.read_text(errors='replace').splitlines():
if '/bin/clang++ ' in line:
argv = shlex.split(line)
if '-o' in argv and argv[argv.index('-o') + 1].endswith(
'.app/' + manifest['executable']):
commands.append(argv)
if len(commands) != 1:
raise ValueError('Need exactly one matching release link command')
argv = commands[0]
if any(arg.startswith(('-fprofile', '-fcoverage')) for arg in argv):
raise ValueError('Release link still enables coverage')
for rule in manifest['replacements']:
needle = rule['arguments']
positions = [i for i in range(len(argv) - len(needle) + 1)
if argv[i:i + len(needle)] == needle]
if len(positions) != 1:
raise ValueError(f'Link input missing or duplicated: {needle}')
i = positions[0]
argv[i:i + len(needle)] = [str((root / rule['file']).resolve())]
prepend = [str((root / item).resolve()) for item in manifest['objects']]
prepend += ['-F' + str((root / item).resolve()) for item in manifest['framework_search']]
argv[1:1] = prepend
if output.exists():
raise FileExistsError(output)
output.mkdir()
for key, name in [('-map', 'LinkMap.txt'), ('-object_path_lto', 'lto.o'),
('-dependency_info', 'dependency_info.dat')]:
if key not in argv and key == '-map':
argv[1:1] = ['-Xlinker', '-map', '-Xlinker', str(output / name)]
continue
i = argv.index(key)
if argv[i + 1] != '-Xlinker':
raise ValueError(f'Unexpected linker argument layout: {key}')
argv[i + 2] = str(output / name)
binary = output / manifest['executable']
argv[argv.index('-o') + 1] = str(output / 'unpatched')
(output / 'link-argv.json').write_text(json.dumps(argv, indent=2) + '\n')
with (output / 'link.log').open('w') as stream:
subprocess.run(argv, cwd=working_directory, stdout=stream,
stderr=subprocess.STDOUT, check=True)
profile = json.loads((root / manifest['patch_profile']).read_text())
report = patch(output / 'unpatched', binary, output / 'LinkMap.txt', profile)
(output / 'patch.json').write_text(json.dumps(report, indent=2) + '\n')
(output / 'inputs.json').write_text(json.dumps(manifest, indent=2) + '\n')
return binary
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
for name in ('build_log', 'manifest', 'output', 'working_directory'):
parser.add_argument(name, type=Path)
args = parser.parse_args()
print(relink(args.build_log.resolve(), args.manifest.resolve(),
args.output.resolve(), args.working_directory.resolve()))
+326
View File
@@ -0,0 +1,326 @@
#!/usr/bin/env python3
"""Package Route 2 hardened app bundle, build IGArchiveGuard, redirect all embedded frameworks, audit & sign."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import plistlib
import shutil
import subprocess
import sys
import tempfile
from batch import arm64_slices, iter_macho_files, Slice
from machox import Macho, LC_DYLD_CHAINED_FIXUPS
from redirect_framework_imports import (
DEPENDENCY,
detect_chained_target_mapping,
rewrite as rewrite_chained,
)
from redirect_legacy_imports import (
detect_legacy_target_mapping,
rewrite as rewrite_legacy,
)
from verify_baseline import inspect_binary, scan
EXTERNAL_SYMBOLS = ('_fopen', '_dlopen', '_dlsym')
SYSTEM_SYMBOLS = ('_write', '_read', '_open', '_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid')
FORBIDDEN_SYMBOLS = set(EXTERNAL_SYMBOLS) | set(SYSTEM_SYMBOLS)
EXPECTED_ARCHIVE_EXPORTS = {
'_rd_a0', '_rd_f', '_rd_a1', '_rd_a2', '_rd_a3', '_rd_a4',
'_rd_u00', '_rd_o', '_rdo', '_rd_r', '_rdr', '_rd_w0', '_rd_w',
'_rd_c0', '_rd_c', '_rd_p00', '_rd_p0', '_rd_e', '_rd_k',
'_rd_l00', '_rd_s0', '_rd_s',
'_rd_io_cfg', '_rd_io_chk', '_rd_io_ev',
}
def sha256(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def run_cmd(*args, env=None, cwd=None):
return subprocess.check_output(list(map(str, args)), env=env, cwd=cwd, text=True)
def build_archive_guard(defender_dir, framework_dir):
if framework_dir.exists():
shutil.rmtree(framework_dir)
framework_dir.mkdir(parents=True)
binary = framework_dir / 'RDCoreIO'
sources = [
defender_dir / 'dispatch/IGArchiveGuard.c',
defender_dir / 'resolve/IGResolve.c',
defender_dir / 'anti_hook/IGAntiHook.c',
]
subprocess.run([
'xcrun', '--sdk', 'iphoneos', 'clang',
'-arch', 'arm64', '-miphoneos-version-min=15.0', '-O2',
'-Wall', '-Wextra', '-Werror', '-fvisibility=hidden', '-dynamiclib',
'-DIG_ARCHIVE_INTERNAL_RESOLVE=1',
'-I', str(defender_dir), '-I', str(defender_dir / 'include'),
*map(str, sources),
'-Wl,-install_name,' + DEPENDENCY,
'-o', str(binary),
], check=True)
plist = {
'CFBundleExecutable': 'RDCoreIO',
'CFBundleIdentifier': 'cn.touchv.readoor.coreio',
'CFBundleName': 'RDCoreIO',
'CFBundlePackageType': 'FMWK',
'CFBundleShortVersionString': '1.0',
'CFBundleSupportedPlatforms': ['iPhoneOS'],
'CFBundleVersion': '1',
'MinimumOSVersion': '15.0',
}
with (framework_dir / 'Info.plist').open('wb') as stream:
plistlib.dump(plist, stream)
exports_out = run_cmd('xcrun', 'nm', '-gU', binary)
exported = {line.split()[-1] for line in exports_out.splitlines() if line.split()}
missing = EXPECTED_ARCHIVE_EXPORTS - exported
if missing:
raise ValueError(f'RDCoreIO missing expected exports: {sorted(missing)}')
leaked_ig = sorted(s for s in exported if s.startswith('_ig_'))
if leaked_ig:
raise ValueError(f'RDCoreIO leaked _ig_* exports: {leaked_ig}')
undef_out = run_cmd('xcrun', 'nm', '-u', binary)
undef = {line.split()[-1] for line in undef_out.splitlines() if line.split()}
forbidden_undef = undef & FORBIDDEN_SYMBOLS
if forbidden_undef:
raise ValueError(f'RDCoreIO has forbidden undefined imports: {sorted(forbidden_undef)}')
info, sites = inspect_binary(binary)
if sites:
raise ValueError(f'RDCoreIO has direct target calls: {sites}')
return dict(sha256=sha256(binary), exported_count=len(exported), inspect=info)
def thin_if_fat(binary_path):
raw = binary_path.read_bytes()
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
with tempfile.NamedTemporaryFile(dir=binary_path.parent, delete=False) as tf:
tmp = Path(tf.name)
try:
subprocess.run(['xcrun', 'lipo', str(binary_path), '-thin', 'arm64', '-output', str(tmp)], check=True)
shutil.copymode(binary_path, tmp)
tmp.replace(binary_path)
return True
finally:
if tmp.exists():
tmp.unlink()
return False
def process_framework(fw_dir):
name = fw_dir.stem
codesig = fw_dir / '_CodeSignature'
if codesig.exists():
shutil.rmtree(codesig)
binary = fw_dir / name
if not binary.is_file():
raise FileNotFoundError(binary)
thinned = thin_if_fat(binary)
raw = binary.read_bytes()
slices = arm64_slices(raw)
if len(slices) != 1 or slices[0][0] != 0:
raise ValueError(f'{name}: expected single thin arm64 Mach-O')
m = Macho(raw)
has_chained = any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds)
has_dyld_info = any(c in (0x22, 0x80000022) for c, _, _ in m.cmds)
include_stdio_rw = (name == 'SSZipArchive')
if has_chained:
mapping = detect_chained_target_mapping(raw, include_stdio_rw=include_stdio_rw)
mode = 'chained'
elif has_dyld_info:
mapping = detect_legacy_target_mapping(raw)
mode = 'legacy_dyld_info'
else:
mapping = {}
mode = 'none'
before_info, _ = inspect_binary(binary)
if mapping:
in_sha = hashlib.sha256(raw).hexdigest()
if mode == 'chained':
out_bytes, report = rewrite_chained(raw, in_sha, mapping)
else:
out_bytes, report = rewrite_legacy(raw, in_sha, mapping)
binary.write_bytes(out_bytes)
after_info, after_sites = inspect_binary(binary)
if after_sites:
raise ValueError(f'{name}: remaining direct calls after rewrite: {after_sites}')
return dict(
framework=name,
mode=mode,
thinned=thinned,
before_total=sum(s['total'] for s in before_info['slices']),
after_total=sum(s['total'] for s in after_info['slices']),
symbols_redirected=len(mapping),
mapping=mapping,
output_sha256=report['output_sha256'],
)
if sum(s['total'] for s in before_info['slices']) > 0:
raise ValueError(f'{name}: has direct calls but empty mapping: {before_info}')
return dict(
framework=name,
mode='clean_no_change' if not thinned else 'thinned_clean',
thinned=thinned,
before_total=0,
after_total=0,
symbols_redirected=0,
)
def regenerate_whitelist(app_repo, payload_dir, app_name):
script = app_repo / 'AutoPacking/obfuscation/generate_image_whitelist.py'
env = dict(os.environ)
env['TARGET_BUILD_DIR'] = str(payload_dir)
env['WRAPPER_NAME'] = app_name
env['EXECUTABLE_PATH'] = Path(app_name).stem
out = run_cmd(sys.executable, script, env=env, cwd=app_repo)
plist_path = payload_dir / app_name / 'RDKnownImages.plist'
data = plistlib.loads(plist_path.read_bytes())
return dict(stdout=out.strip(), entry_count=len(data['known_images']), digest=data['digest'])
def adhoc_sign_and_verify(app_dir):
frameworks = sorted((app_dir / 'Frameworks').glob('*.framework'))
for fw in frameworks:
subprocess.run(['codesign', '--force', '--sign', '-', str(fw)], check=True)
subprocess.run(['codesign', '--force', '--sign', '-', str(app_dir)], check=True)
verified = []
for target in [*frameworks, app_dir]:
subprocess.run(['codesign', '--verify', '--strict', str(target)], check=True)
verified.append(str(target.relative_to(app_dir.parent)))
return verified
def package(source_app, relinked_main, app_repo, output):
if output.exists():
raise FileExistsError(output)
output.mkdir(parents=True)
payload_dir = output / 'Payload'
payload_dir.mkdir()
app_dir = payload_dir / source_app.name
shutil.copytree(source_app, app_dir, symlinks=True)
app_sig = app_dir / '_CodeSignature'
if app_sig.exists():
shutil.rmtree(app_sig)
main_bin = app_dir / relinked_main.name
shutil.copy2(relinked_main, main_bin)
main_bin.chmod(0o755)
defender_dir = app_repo / 'readoor/3.0/Base/Security/IGDefender'
guard_report = build_archive_guard(defender_dir, app_dir / 'Frameworks/RDCoreIO.framework')
fw_reports = []
for fw_dir in sorted((app_dir / 'Frameworks').glob('*.framework')):
if fw_dir.name == 'RDCoreIO.framework':
continue
fw_reports.append(process_framework(fw_dir))
(output / 'framework-rewrites.json').write_text(json.dumps(fw_reports, indent=2) + '\n')
whitelist_report = regenerate_whitelist(app_repo, payload_dir, source_app.name)
binaries, callsite_total = scan(app_dir, output, 'route2')
combined_counts = {}
for rel, info in binaries.items():
for sl in info['slices']:
for sym, cnt in sl['counts'].items():
combined_counts[sym] = combined_counts.get(sym, 0) + cnt
external_call_total = sum(combined_counts.get(s, 0) for s in EXTERNAL_SYMBOLS)
system_call_total = sum(combined_counts.get(s, 0) for s in SYSTEM_SYMBOLS)
if len(binaries) != 44:
raise ValueError(f'Expected 44 Mach-O binaries, got {len(binaries)}')
if external_call_total != 0 or system_call_total != 0 or callsite_total != 0:
raise ValueError(
f'Non-zero residual callsites: external={external_call_total}, '
f'system={system_call_total}, total={callsite_total}, counts={combined_counts}'
)
variant_stubs = []
for mpath in sorted(map(Path, iter_macho_files(str(app_dir)))):
mdata = mpath.read_bytes()
for off, _ in arm64_slices(mdata):
sl = Slice(mdata, off)
if not (sl.stubs and sl.symtab and sl.dysym):
continue
import struct
symoff, _, stroff, _ = sl.symtab
indoff = sl.dysym[12]
_, ssize, _, sr1, sr2 = sl.stubs
for idx_pos in range(ssize // sr2):
symi, = struct.unpack_from('<I', mdata, off + indoff + (sr1 + idx_pos) * 4)
strx, = struct.unpack_from('<I', mdata, off + symoff + symi * 16)
sname = mdata[off + stroff + strx:mdata.index(b'\0', off + stroff + strx)].decode(errors='replace')
if sname == '_fopen$DARWIN_EXTSN' or any(sname.startswith(f + '$') for f in FORBIDDEN_SYMBOLS):
variant_stubs.append((str(mpath.relative_to(app_dir)), sname))
if variant_stubs:
raise ValueError(f'Found Darwin variant stubs of target symbols: {variant_stubs}')
main_undef_out = run_cmd('xcrun', 'nm', '-u', main_bin)
main_undef = {line.split()[-1] for line in main_undef_out.splitlines() if line.split()}
if '_fopen$DARWIN_EXTSN' in main_undef or any(any(u.startswith(f + '$') for f in FORBIDDEN_SYMBOLS) for u in main_undef):
raise ValueError(f'Main binary still imports Darwin variant of target symbol: {sorted(main_undef)}')
main_defined_out = run_cmd('xcrun', 'nm', '-U', main_bin)
main_defined = {line.split()[-1] for line in main_defined_out.splitlines() if line.split()}
expected_dispatch_exports = {
'_IG_dispatch_fopen', '_IG_dispatch_dlopen', '_IG_dispatch_dlsym',
'_IG_dispatch_write', '_IG_dispatch_read', '_IG_dispatch_open',
'_IG_dispatch_close', '_IG_dispatch_exit', '_IG_dispatch_fork',
'_IG_dispatch_unlink', '_IG_dispatch_getpid',
}
missing_dispatch = expected_dispatch_exports - main_defined
if missing_dispatch:
raise ValueError(f'Main binary missing IG_dispatch symbols: {sorted(missing_dispatch)}')
verified_bundles = adhoc_sign_and_verify(app_dir)
ipa_path = output / 'route2-adhoc.ipa'
subprocess.run(['ditto', '-c', '-k', '--keepParent', str(payload_dir), str(ipa_path)], check=True)
summary = dict(
binaries=len(binaries),
external_call_total=external_call_total,
system_call_total=system_call_total,
direct_calls=combined_counts,
main_binary_forbidden_undef=sorted(main_undef & FORBIDDEN_SYMBOLS),
ig_archive_guard=guard_report,
frameworks_rewritten=sum(1 for r in fw_reports if r['symbols_redirected'] > 0),
frameworks_thinned=sum(1 for r in fw_reports if r['thinned']),
whitelist=whitelist_report,
codesign_verified_count=len(verified_bundles),
ipa=str(ipa_path),
ipa_sha256=sha256(ipa_path),
)
(output / 'route2-summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
return summary
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source-app', type=Path, required=True)
parser.add_argument('--relinked-main', type=Path, required=True)
parser.add_argument('--app-repo', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
result = package(
args.source_app.resolve(),
args.relinked_main.resolve(),
args.app_repo.resolve(),
args.output.resolve(),
)
print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -0,0 +1,10 @@
{
"rules": [
{
"caller": "__isJailbreak",
"symbol": "_fopen",
"destination": "_IG_dispatch_fopen",
"expected_count": 6
}
]
}
@@ -0,0 +1,70 @@
{
"rules": [
{
"caller": "__isJailbreak",
"symbol": "_fopen",
"destination": "_IG_dispatch_fopen",
"expected_count": 6
},
{
"caller": "_SignalHandler",
"symbol": "_getpid",
"destination": "_IG_dispatch_getpid",
"expected_count": 1
},
{
"caller": "+[UMInternalUtil Value2]",
"symbol": "_getpid",
"destination": "_IG_dispatch_getpid",
"expected_count": 1
},
{
"caller": "__initializeAvailabilityCheck",
"symbol": "_fopen",
"destination": "_IG_dispatch_fopen",
"expected_count": 1
},
{
"caller": "__initializeAvailabilityCheck",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 10
},
{
"caller": "__ZZZL25swift_voucher_needs_adoptP9voucher_sENKUlvE_clEvENUlPvE_8__invokeES2_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
},
{
"caller": "__ZZZN5swift19_swift_tsan_acquireEPvENK3$_0clEvENUlS0_E_8__invokeES0_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
},
{
"caller": "__ZZZN5swift19_swift_tsan_releaseEPvENK3$_0clEvENUlS0_E_8__invokeES0_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
},
{
"caller": "__ZZZN5swift31swift_task_escalateBackdeploy56EPNS_9AsyncTaskENS_11JobPriorityEENK3$_0clEvENUlPvE_8__invokeES4_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
},
{
"caller": "__ZZZN5swift45swift_task_exitThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
},
{
"caller": "__ZZZN5swift46swift_task_enterThreadLocalContextBackdeploy56EPcENK3$_0clEvENUlPvE_8__invokeES2_",
"symbol": "_dlsym",
"destination": "_IG_dispatch_dlsym",
"expected_count": 1
}
]
}
+72 -12
View File
@@ -8,8 +8,29 @@ import struct
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
DEPENDENCY = '@rpath/IGArchiveGuard.framework/IGArchiveGuard'
MAPPING = {'_fopen': '_ig_a0', '_fread': '_ig_a1', '_fwrite': '_ig_a2', '_fclose': '_ig_a3'}
GUARD_FRAMEWORK_NAME = 'RDCoreIO'
DEPENDENCY = '@rpath/RDCoreIO.framework/RDCoreIO'
MAPPING = {'_fopen': '_rd_a0', '_fread': '_rd_a1', '_fwrite': '_rd_a2', '_fclose': '_rd_a3'}
ALLOWED_MAPPING = {
'_fopen': '_rd_a0',
'_fread': '_rd_a1',
'_fwrite': '_rd_a2',
'_fclose': '_rd_a3',
'_unlink': '_rd_a4',
'_open': '_rd_o',
'_read': '_rd_r',
'_write': '_rd_w0',
'_close': '_rd_c0',
'_getpid': '_rd_p00',
'_exit': '_rd_e',
'_fork': '_rd_k',
'_dlopen': '_rd_l00',
'_dlsym': '_rd_s0',
}
REPORT_TARGET_SYMBOLS = {
'_fopen', '_dlopen', '_dlsym', '_write', '_read', '_open',
'_close', '_exit', '_fork', '_syscall', '_unlink', '_getpid',
}
LOADS = (0xc, 0x80000018, 0x8000001f, 0x80000023, 0x20)
@@ -18,7 +39,45 @@ def require(value, message):
raise ValueError(message)
def rewrite(data, expected_sha256):
def detect_chained_target_mapping(data, include_stdio_rw=False):
m = Macho(data)
deps = []
for cmd, size, off in m.cmds:
if cmd in LOADS:
n = struct.unpack_from('<I', m.d, off + 8)[0]
require(24 <= n < size, '依赖名偏移无效')
end = m.d.index(0, off + n, off + size)
deps.append(bytes(m.d[off + n:end]).decode())
if '/usr/lib/libSystem.B.dylib' not in deps:
return {}
old_ordinal = deps.index('/usr/lib/libSystem.B.dylib') + 1
commands = [o for c, _, o in m.cmds if c == LC_DYLD_CHAINED_FIXUPS]
require(len(commands) == 1, '需要唯一 chained fixups')
fixoff, fixsize = struct.unpack_from('<II', m.d, commands[0] + 8)
version, starts, imports, symbols, count, fmt, compression = struct.unpack_from('<7I', m.d, fixoff)
require(version == 0 and fmt == 1 and compression == 0, '仅支持无压缩 DYLD_CHAINED_IMPORT')
wanted = set(REPORT_TARGET_SYMBOLS)
if include_stdio_rw:
wanted.update({'_fread', '_fwrite', '_fclose'})
found = {}
pool_start, pool_end = fixoff + symbols, fixoff + fixsize
for i in range(count):
word = struct.unpack_from('<I', m.d, fixoff + imports + 4 * i)[0]
if (word & 255) != old_ordinal:
continue
start = pool_start + (word >> 9)
end = m.d.index(0, start, pool_end)
name = bytes(m.d[start:end]).decode('utf-8')
if name in wanted:
require(name in ALLOWED_MAPPING, f'缺少框架保护映射: {name}')
found[name] = ALLOWED_MAPPING[name]
return found
def rewrite(data, expected_sha256, mapping=None):
mapping = MAPPING if mapping is None else mapping
require(bool(mapping) and all(k in ALLOWED_MAPPING and ALLOWED_MAPPING[k] == v for k, v in mapping.items()),
'映射必须是已实现的保护入口子集')
require(hashlib.sha256(data).hexdigest() == expected_sha256, 'SDK 哈希不匹配,须重新审核版本')
m = Macho(data)
require(m.filetype == 6 and m.flags & 0x80, '需要 two-level MH_DYLIB')
@@ -66,17 +125,17 @@ def rewrite(data, expected_sha256):
require(pool_start <= start < pool_end, '字符串索引越界')
end = m.d.index(0, start, pool_end)
name = bytes(m.d[start:end]).decode('utf-8')
require(name not in MAPPING.values(), '已改写或目标冲突')
require(name not in mapping.values(), '已改写或目标冲突')
intervals.append((start, end + 1, name))
if name in MAPPING:
if name in mapping:
require(name not in selected and ordinal_value == old_ordinal,
'重复导入或提供方不匹配')
selected[name] = (entry, start, end)
require(set(selected) == set(MAPPING), '缺少预期四个文件函数')
require(set(selected) == set(mapping), '缺少配置的文件函数')
for name, (entry, start, end) in selected.items():
require(all(other == name or finish <= start or begin >= end + 1
for begin, finish, other in intervals), '共享后缀字符串,拒绝原地改名')
encoded = MAPPING[name].encode()
encoded = mapping[name].encode()
require(len(encoded) <= end - start, '新名称超出原字符串空间')
write(start, encoded + bytes(end - start + 1 - len(encoded)))
if kind == 'chained':
@@ -87,7 +146,7 @@ def rewrite(data, expected_sha256):
desc = struct.unpack_from('<H', m.d, entry + 6)[0]
require(not desc & 0x40, '不支持 weak 符号')
write(entry + 6, struct.pack('<H', (desc & 255) | (ordinal << 8)))
changes.append({'table': kind, 'source': name, 'destination': MAPPING[name],
changes.append({'table': kind, 'source': name, 'destination': mapping[name],
'old_ordinal': old_ordinal, 'ordinal': ordinal})
entries = []
for i in range(count):
@@ -119,13 +178,13 @@ def rewrite(data, expected_sha256):
Macho(result)
return result, {'input_sha256': hashlib.sha256(data).hexdigest(),
'output_sha256': hashlib.sha256(result).hexdigest(), 'dependency': DEPENDENCY,
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': 4}
'changes': changes, 'machine_code_unchanged': True, 'total_symbols': len(mapping)}
def patch(source, destination, expected_sha256):
def patch(source, destination, expected_sha256, mapping=None):
source, destination = Path(source), Path(destination)
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
output, report = rewrite(source.read_bytes(), expected_sha256)
output, report = rewrite(source.read_bytes(), expected_sha256, mapping)
destination.write_bytes(output)
destination.chmod(source.stat().st_mode)
return report
@@ -137,5 +196,6 @@ if __name__ == '__main__':
p.add_argument('destination', type=Path)
p.add_argument('--expected-sha256', required=True)
p.add_argument('--report', type=Path, required=True)
p.add_argument('--mapping', type=Path, help='现有四入口中的显式子集 JSON')
a = p.parse_args()
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256), indent=2) + '\n')
a.report.write_text(json.dumps(patch(a.source, a.destination, a.expected_sha256, json.loads(a.mapping.read_text()) if a.mapping else None), indent=2) + '\n')
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Redirect a reviewed lazy fopen import without changing lazy-record offsets."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from machox import Macho
from redirect_framework_imports import DEPENDENCY, LOADS, require
SOURCE = b'_fopen'
DESTINATION = b'_rd_a0'
def uleb(data, pos, end):
start, value, shift = pos, 0, 0
while pos < end and shift < 64:
byte = data[pos]
pos += 1
value |= (byte & 127) << shift
if not byte & 128:
return value, pos, start
shift += 7
raise ValueError('Invalid LEB128')
def encode(value):
result = bytearray()
while value >= 128:
result.append((value & 127) | 128)
value >>= 7
result.append(value)
return bytes(result)
def rewrite(data, expected_sha):
require(hashlib.sha256(data).hexdigest() == expected_sha, 'Input hash changed')
m = Macho(data)
require(m.filetype == 6 and m.flags & 0x80, 'Expected two-level dylib')
deps, dyld, symtab, sections = [], [], [], []
for cmd, size, off in m.cmds:
if cmd in LOADS:
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
require(24 <= nameoff < size, 'Invalid dependency')
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
if cmd in (0x22, 0x80000022):
dyld.append(off)
if cmd == 2:
symtab.append(off)
if cmd == 0x80000034:
raise ValueError('Chained imports require the chained rewriter')
if cmd == 0x19:
for i in range(struct.unpack_from('<I', m.d, off + 64)[0]):
section = off + 72 + i * 80
length, fileoff = struct.unpack_from('<QI', m.d, section + 40)
flags = struct.unpack_from('<I', m.d, section + 64)[0] & 255
if length and flags not in (1, 0xc, 0x12):
require(fileoff > 0 and fileoff + length <= len(data), 'Invalid section')
sections.append((fileoff, length))
require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables')
require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict')
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
new = len(deps) + 1
fields = struct.unpack_from('<10I', m.d, dyld[0] + 8)
for i in (1, 2):
offset, size = fields[i * 2:i * 2 + 2]
require(SOURCE + b'\0' not in data[offset:offset + size],
'fopen also appears in regular or weak binding')
offset, size = fields[6:8]
require(offset + size <= len(data), 'Lazy stream outside file')
pos, end, records = offset, offset + size, []
record = {'symbols': [], 'ordinals': [], 'binds': 0}
while pos < end:
at = pos
opcode = data[pos] & 0xf0
imm = data[pos] & 15
pos += 1
if opcode == 0:
require(imm == 0, 'Invalid DONE opcode')
if record['symbols']:
records.append(record)
record = {'symbols': [], 'ordinals': [], 'binds': 0}
elif opcode == 0x10:
record['ordinals'].append((at, pos, imm, False))
elif opcode == 0x20:
value, pos, start = uleb(data, pos, end)
record['ordinals'].append((start, pos, value, True))
elif opcode == 0x40:
finish = data.index(0, pos, end)
record['symbols'].append((pos, finish, data[pos:finish], imm))
pos = finish + 1
elif opcode in (0x60, 0x70, 0x80):
_, pos, _ = uleb(data, pos, end)
elif opcode == 0x50:
pass
elif opcode == 0x90:
record['binds'] += 1
else:
raise ValueError(f'Unsupported lazy opcode {opcode:#x}')
require(not record['symbols'] and not record['ordinals'] and not record['binds'], 'Unterminated lazy record')
selected = [r for r in records if any(s[2] == SOURCE for s in r['symbols'])]
require(len(selected) == 1, 'Need exactly one fopen lazy record')
r = selected[0]
require(len(r['symbols']) == len(r['ordinals']) == r['binds'] == 1,
'Shared or multi-bind lazy record')
start, finish, name, flags = r['symbols'][0]
require(flags == 0 and len(DESTINATION) == finish - start, 'Unsupported symbol flags/length')
at, stop, ordinal, extended = r['ordinals'][0]
require(ordinal == old, 'Unexpected provider')
encoded = encode(new) if extended else bytes([0x10 | new]) if new < 16 else b''
require(len(encoded) == stop - at, 'Ordinal size would move lazy records')
allowed = set()
def write(at, content):
m.d[at:at + len(content)] = content
allowed.update(range(at, at + len(content)))
write(start, DESTINATION)
write(at, encoded)
so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8)
require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table')
matched = 0
intervals = []
for i in range(count):
entry = so + i * 16
index, typ, _, desc, _ = struct.unpack_from('<IBBHQ', data, entry)
if index >= stringsize:
raise ValueError('Symbol name outside pool')
nameend = data.index(0, strings + index, strings + stringsize)
intervals.append((strings + index, nameend + 1))
if data[strings + index:nameend] != SOURCE:
continue
require(typ == 1 and desc >> 8 == old, 'Unexpected nlist provider')
symbol_span = (strings + index, nameend + 1)
write(strings + index, DESTINATION)
write(entry + 6, struct.pack('<H', (desc & 255) | (new << 8)))
matched += 1
require(matched == 1, 'Need one undefined fopen symbol')
require(all(span == symbol_span or span[1] <= symbol_span[0] or span[0] >= symbol_span[1]
for span in intervals), 'Shared symbol-name suffix')
name = DEPENDENCY.encode() + b'\0'
length = (24 + len(name) + 7) & ~7
at = 32 + m.sizeofcmds
require(at + length <= min(s[0] for s in sections), 'Insufficient header padding')
require(not any(data[at:at + length]), 'Nonzero header padding')
command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name
write(at, command + bytes(length - len(command)))
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + length))
result = bytes(m.d)
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), 'Unexpected mutation')
require(all(data[o:o+n] == result[o:o+n] for o,n in sections), 'Section bytes changed')
return result, dict(input_sha256=expected_sha, output_sha256=hashlib.sha256(result).hexdigest(),
source=SOURCE.decode(), destination=DESTINATION.decode(),
old_ordinal=old, new_ordinal=new, lazy_offsets_preserved=True,
section_bytes_unchanged=True)
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('source', type=Path)
p.add_argument('output', type=Path)
p.add_argument('--sha256', required=True)
p.add_argument('--report', type=Path, required=True)
a = p.parse_args()
result, report = rewrite(a.source.read_bytes(), a.sha256)
with a.output.open('xb') as stream:
stream.write(result)
a.report.write_text(json.dumps(report, indent=2) + '\n')
@@ -0,0 +1,327 @@
#!/usr/bin/env python3
"""Redirect reviewed lazy imports in thin arm64 DYLD_INFO_ONLY frameworks without shifting lazy offsets."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from machox import Macho, LC_SEGMENT_64, LC_SYMTAB, LC_DYLD_CHAINED_FIXUPS
from redirect_framework_imports import DEPENDENCY, LOADS, REPORT_TARGET_SYMBOLS, require
EQUAL_LEN_MAPPING = {
'_fopen': '_rd_a0',
'_open': '_rd_o',
'_read': '_rd_r',
'_write': '_rd_w0',
'_close': '_rd_c0',
'_unlink': '_rd_u00',
'_getpid': '_rd_p00',
'_exit': '_rd_e',
'_fork': '_rd_k',
'_dlopen': '_rd_l00',
'_dlsym': '_rd_s0',
}
SHRINK1_MAPPING = {
'_fopen': '_rd_f',
'_open': '_rdo',
'_read': '_rdr',
'_write': '_rd_w',
'_close': '_rd_c',
'_unlink': '_rd_a4',
'_getpid': '_rd_p0',
'_dlsym': '_rd_s',
}
def uleb(data, pos, end):
start, value, shift = pos, 0, 0
while pos < end and shift < 64:
byte = data[pos]
pos += 1
value |= (byte & 127) << shift
if not byte & 128:
return value, pos, start
shift += 7
raise ValueError('Invalid LEB128')
def sleb_skip(data, pos, end):
while pos < end:
byte = data[pos]
pos += 1
if not byte & 128:
return pos
raise ValueError('Invalid SLEB128')
def encode_uleb(value):
result = bytearray()
while value >= 128:
result.append((value & 127) | 128)
value >>= 7
result.append(value)
return bytes(result)
def parse_bind_symbols(data, offset, size):
if not size:
return set()
require(offset + size <= len(data), 'Bind stream outside file')
pos, end, symbols = offset, offset + size, set()
while pos < end:
opcode = data[pos] & 0xf0
pos += 1
if opcode in (0x00, 0x10, 0x30, 0x50, 0x90, 0xb0):
pass
elif opcode in (0x20, 0x70, 0x80, 0xa0):
_, pos, _ = uleb(data, pos, end)
elif opcode == 0x60:
pos = sleb_skip(data, pos, end)
elif opcode == 0xc0:
_, pos, _ = uleb(data, pos, end)
_, pos, _ = uleb(data, pos, end)
elif opcode == 0x40:
finish = data.index(0, pos, end)
symbols.add(data[pos:finish])
pos = finish + 1
else:
raise ValueError(f'Unsupported bind opcode {opcode:#x}')
return symbols
def parse_lazy_records(data, offset, size):
require(offset + size <= len(data), 'Lazy stream outside file')
pos, end, records = offset, offset + size, []
record = {'symbols': [], 'ordinals': [], 'binds': 0}
while pos < end:
at = pos
opcode = data[pos] & 0xf0
imm = data[pos] & 15
pos += 1
if opcode == 0:
require(imm == 0, 'Invalid DONE opcode')
if record['symbols']:
records.append(record)
record = {'symbols': [], 'ordinals': [], 'binds': 0}
elif opcode == 0x10:
record['ordinals'].append((at, pos, imm, False))
elif opcode == 0x20:
value, pos, _ = uleb(data, pos, end)
record['ordinals'].append((at, pos, value, True))
elif opcode == 0x40:
finish = data.index(0, pos, end)
record['symbols'].append((pos, finish, data[pos:finish], imm))
pos = finish + 1
elif opcode in (0x70, 0x80, 0xa0):
_, pos, _ = uleb(data, pos, end)
elif opcode == 0x60:
pos = sleb_skip(data, pos, end)
elif opcode == 0xc0:
_, pos, _ = uleb(data, pos, end)
_, pos, _ = uleb(data, pos, end)
elif opcode in (0x50, 0x90, 0xb0):
if opcode == 0x90:
record['binds'] += 1
else:
raise ValueError(f'Unsupported lazy opcode {opcode:#x}')
require(not record['symbols'] and not record['ordinals'] and not record['binds'],
'Unterminated lazy record')
return records
def detect_legacy_target_mapping(data):
m = Macho(data)
deps = []
dyld_cmds = []
for cmd, size, off in m.cmds:
if cmd in LOADS:
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
require(24 <= nameoff < size, 'Invalid dependency')
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
if cmd in (0x22, 0x80000022):
dyld_cmds.append(off)
if '/usr/lib/libSystem.B.dylib' not in deps or not dyld_cmds:
return {}
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
new = len(deps) + 1
old_width = 1 if old < 16 else 2
new_width = 1 if new < 16 else 2
delta = new_width - old_width
require(delta in (0, 1), f'Unsupported ordinal width delta: {delta}')
table = EQUAL_LEN_MAPPING if delta == 0 else SHRINK1_MAPPING
fields = struct.unpack_from('<10I', m.d, dyld_cmds[0] + 8)
lo, ls = fields[6:8]
records = parse_lazy_records(data, lo, ls)
found = {}
for rec in records:
for _, _, sym_bytes, _ in rec['symbols']:
name = sym_bytes.decode('utf-8')
if name in REPORT_TARGET_SYMBOLS:
require(name in table, f'Missing legacy alias for {name} (width delta={delta})')
found[name] = table[name]
return found
def rewrite(data, expected_sha, mapping=None):
require(hashlib.sha256(data).hexdigest() == expected_sha, 'Input hash changed')
m = Macho(data)
require(m.filetype == 6 and m.flags & 0x80, 'Expected two-level dylib')
require(not any(c == LC_DYLD_CHAINED_FIXUPS for c, _, _ in m.cmds),
'Chained imports require redirect_framework_imports')
deps, dyld, symtab, sections = [], [], [], []
for cmd, size, off in m.cmds:
if cmd in LOADS:
nameoff = struct.unpack_from('<I', m.d, off + 8)[0]
require(24 <= nameoff < size, 'Invalid dependency')
deps.append(bytes(m.d[off + nameoff:m.d.index(0, off + nameoff, off + size)]).decode())
if cmd in (0x22, 0x80000022):
dyld.append(off)
if cmd == 2:
symtab.append(off)
if cmd == LC_SEGMENT_64:
for i in range(struct.unpack_from('<I', m.d, off + 64)[0]):
section = off + 72 + i * 80
length, fileoff = struct.unpack_from('<QI', m.d, section + 40)
flags = struct.unpack_from('<I', m.d, section + 64)[0] & 255
if length and flags not in (1, 0xc, 0x12):
require(fileoff > 0 and fileoff + length <= len(data), 'Invalid section')
sections.append((fileoff, length))
require(len(dyld) == len(symtab) == 1 and sections, 'Missing tables')
require(DEPENDENCY not in deps and len(deps) < 0x7e, 'Dependency conflict')
old = deps.index('/usr/lib/libSystem.B.dylib') + 1
new = len(deps) + 1
old_width = 1 if old < 16 else 2
new_width = 1 if new < 16 else 2
delta = new_width - old_width
allowed_table = EQUAL_LEN_MAPPING if delta == 0 else SHRINK1_MAPPING if delta == 1 else {}
require(bool(allowed_table), f'Unsupported ordinal width delta: {delta}')
if mapping is None:
mapping = detect_legacy_target_mapping(data)
require(bool(mapping) and all(k in allowed_table and allowed_table[k] == v for k, v in mapping.items()),
'Mapping must match allowed legacy wrapper table')
byte_mapping = {k.encode('ascii'): v.encode('ascii') for k, v in mapping.items()}
fields = struct.unpack_from('<10I', m.d, dyld[0] + 8)
for i in (1, 2):
offset, size = fields[i * 2:i * 2 + 2]
bind_syms = parse_bind_symbols(data, offset, size)
for src in byte_mapping:
require(src not in bind_syms,
f'{src.decode()} appears in regular or weak binding')
records = parse_lazy_records(data, fields[6], fields[7])
selected = []
for rec in records:
if any(s[2] in byte_mapping for s in rec['symbols']):
require(len(rec['symbols']) == len(rec['ordinals']) == rec['binds'] == 1,
'Shared or multi-bind lazy record')
selected.append(rec)
require({r['symbols'][0][2] for r in selected} == set(byte_mapping),
'Not all mapped symbols matched unique lazy records')
allowed = set()
def write(at, content):
require(at >= 0 and at + len(content) <= len(m.d), 'Write out of range')
m.d[at:at + len(content)] = content
allowed.update(range(at, at + len(content)))
new_ord_bytes = bytes([0x10 | new]) if new < 16 else b'\x20' + encode_uleb(new)
changes = []
for rec in selected:
start, finish, src_sym, flags = rec['symbols'][0]
dst_sym = byte_mapping[src_sym]
ord_start, ord_stop, ordinal, _ = rec['ordinals'][0]
require(flags == 0 and ordinal == old, 'Unexpected symbol flags or provider')
sym_opcode_pos = start - 1
require(data[sym_opcode_pos] == 0x40, 'Expected SET_SYMBOL_TRAILING_FLAGS_IMM(0) before symbol')
require(ord_stop == sym_opcode_pos, 'Expected ordinal opcode immediately before symbol opcode')
old_span = finish + 1 - ord_start
replacement = new_ord_bytes + b'\x40' + dst_sym + b'\0'
require(len(replacement) == old_span, 'Replacement size would shift lazy records')
write(ord_start, replacement)
changes.append(dict(table='lazy', source=src_sym.decode(), destination=dst_sym.decode(),
old_ordinal=old, new_ordinal=new))
so, count, strings, stringsize = struct.unpack_from('<4I', data, symtab[0] + 8)
require(so + count * 16 <= len(data) and strings + stringsize <= len(data), 'Invalid symbol table')
matched = {}
intervals = []
target_spans = []
for i in range(count):
entry = so + i * 16
index, typ, _, desc, value = struct.unpack_from('<IBBHQ', data, entry)
require(index < stringsize, 'Symbol name outside pool')
nameend = data.index(0, strings + index, strings + stringsize)
sym = data[strings + index:nameend]
intervals.append((strings + index, nameend + 1, sym))
require(sym not in byte_mapping.values(), 'Target symbol already exists in symbol table')
if sym in byte_mapping and typ == 1 and value == 0:
require((desc >> 8) == old and not (desc & 0x40), 'Unexpected nlist provider or weak symbol')
dst = byte_mapping[sym]
require(len(dst) <= len(sym), 'Destination longer than source in string pool')
span = (strings + index, nameend + 1, sym)
target_spans.append(span)
write(strings + index, dst + b'\0' * (len(sym) + 1 - len(dst)))
write(entry + 6, struct.pack('<H', (desc & 255) | (new << 8)))
matched[sym] = matched.get(sym, 0) + 1
changes.append(dict(table='nlist', source=sym.decode(), destination=dst.decode(),
old_ordinal=old, new_ordinal=new))
require(set(matched) == set(byte_mapping) and all(v == 1 for v in matched.values()),
'Missing or duplicate nlist symbol')
for b1, e1, n1 in target_spans:
require(all(n2 == n1 or e2 <= b1 or b2 >= e1 for b2, e2, n2 in intervals),
'Shared symbol-name suffix')
name = DEPENDENCY.encode() + b'\0'
length = (24 + len(name) + 7) & ~7
at = 32 + m.sizeofcmds
require(at + length <= min(s[0] for s in sections), 'Insufficient header padding')
require(not any(data[at:at + length]), 'Nonzero header padding')
command = struct.pack('<6I', 0xc, length, 24, 0, 0x10000, 0x10000) + name
write(at, command + bytes(length - len(command)))
write(16, struct.pack('<II', m.ncmds + 1, m.sizeofcmds + length))
result = bytes(m.d)
require(all(a == b or i in allowed for i, (a, b) in enumerate(zip(data, result))), 'Unexpected mutation')
require(all(data[o:o + n] == result[o:o + n] for o, n in sections), 'Section bytes changed')
Macho(result)
return result, dict(
input_sha256=expected_sha,
output_sha256=hashlib.sha256(result).hexdigest(),
dependency=DEPENDENCY,
old_ordinal=old,
new_ordinal=new,
ordinal_width_delta=delta,
lazy_offsets_preserved=True,
section_bytes_unchanged=True,
changes=changes,
total_symbols=len(mapping),
)
def patch(source, destination, expected_sha256, mapping=None):
source, destination = Path(source), Path(destination)
require(not destination.exists() and source.resolve() != destination.resolve(), '输出必须为新文件')
output, report = rewrite(source.read_bytes(), expected_sha256, mapping)
destination.write_bytes(output)
destination.chmod(source.stat().st_mode)
return report
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('source', type=Path)
p.add_argument('destination', type=Path)
p.add_argument('--expected-sha256', required=True)
p.add_argument('--report', type=Path, required=True)
p.add_argument('--mapping', type=Path)
a = p.parse_args()
result, report = rewrite(a.source.read_bytes(), a.expected_sha256,
json.loads(a.mapping.read_text()) if a.mapping else None)
with a.output.open('xb') if hasattr(a, 'output') else a.destination.open('xb') as stream:
stream.write(result)
a.destination.chmod(a.source.stat().st_mode)
a.report.write_text(json.dumps(report, indent=2) + '\n')
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""核对同次构建的 arm64 可执行文件中所列文件方法确实调用保护入口。
需要保留本地符号的验证构建;符号缺失直接失败,不将未知判为通过。
只验证所列方法的直接 BL/B 调用边,不代表全包系统调用整改完成。
"""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from machox import Macho
from batch import Slice
from redirect_to_runtime import defined_symbols, target
EXPECTED = {
'+[STSCommonUtil convertPcmToWav:wavFilePath:]': {'fopen': 1},
'-[GCDWebServerMultiPartFile dealloc]': {'unlink': 1},
'-[GCDWebServerMIMEStreamParser dealloc]': {'close': 1, 'unlink': 1},
'-[GCDWebServerMIMEStreamParser _parseData]': {'open': 1, 'write': 2, 'close': 1},
'-[GCDWebServerFileRequest dealloc]': {'unlink': 1},
'-[GCDWebServerFileRequest open:]': {'open': 1},
'-[GCDWebServerFileRequest writeData:error:]': {'write': 1},
'-[GCDWebServerFileRequest close:]': {'close': 1},
'-[GCDWebServerFileResponse open:]': {'open': 1, 'close': 1},
'-[GCDWebServerFileResponse readData:]': {'read': 1},
'-[GCDWebServerFileResponse close]': {'close': 1},
}
ZIPZAP = {
'-[ZZFileChannel newOutput:]': {'open': 1},
'-[ZZFileChannelOutput writeData:error:]': {'write': 1},
'-[ZZFileChannelOutput close]': {'close': 1},
}
def verify(path, include_zipzap=False):
expected = EXPECTED | ZIPZAP if include_zipzap else EXPECTED
data = Path(path).read_bytes()
macho = Macho(data)
view = Slice(data, 0)
if not view.text:
raise ValueError('缺少 __text')
start, size, offset = view.text
symbols = defined_symbols(macho)
boundaries = sorted({v for v in symbols.values() if start <= v < start + size} | {start + size})
stubs = view.stub_symbol_map()
all_protected = {name for wanted in expected.values() for name in wanted}
result = []
for method, wanted in expected.items():
if method not in symbols or not start <= symbols[method] < start + size:
raise ValueError(f'缺少可核验的业务方法符号:{method}')
address = symbols[method]
end = next(v for v in boundaries if v > address)
calls = []
for site in range(address, end, 4):
word, = struct.unpack_from('<I', data, offset + site - start)
if word & 0xfc000000 in (0x94000000, 0x14000000):
calls.append((site, target(word, site)))
for site, dest in calls:
if stubs.get(dest) in {'_' + n for n in all_protected}:
raise ValueError(f'{method} 仍直接调用 {stubs[dest]} @ {site:#x}')
for name, minimum in wanted.items():
guard = '_IG_dispatch_' + name
if guard not in symbols:
raise ValueError(f'保护入口未链接或符号缺失:{guard}')
sites = [hex(site) for site, dest in calls if dest == symbols[guard]]
if len(sites) < minimum:
raise ValueError(f'{method} 未实际调用 {guard}')
result.append(dict(caller=method, destination=guard, sites=sites))
return dict(status='passed_selected_call_edges', executable=str(Path(path).resolve()),
sha256=hashlib.sha256(data).hexdigest(), verified_edges=result,
scope='仅所列方法;不代表全包或真机验收')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('executable', type=Path)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--include-zipzap', action='store_true', help='同时核验 ZipZap 输出文件调用')
args = parser.parse_args()
report = verify(args.executable, args.include_zipzap)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(report, ensure_ascii=False, indent=2))
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Verify prior direct calls from one archive now reach a specified local guard."""
import argparse
from collections import Counter, defaultdict
import csv
import hashlib
import json
from pathlib import Path
import struct
from attribute_callsites import attribute, load_link_map
from batch import Slice
from machox import Macho
from redirect_to_runtime import defined_symbols, target
def verify(previous_calls, executable, link_map, archive, source, guard):
with previous_calls.open() as stream:
expected = Counter(row['caller'] for row in csv.DictReader(stream)
if row['symbol'] == source
and Path(row['object'].split('(')[0]).name == archive)
if not expected:
raise ValueError('No prior calls selected')
remaining = [r for r in attribute(executable, link_map)
if r['symbol'] == source
and Path(r.get('object', '').split('(')[0]).name == archive]
if remaining:
raise ValueError(f'{len(remaining)} direct calls remain')
data = executable.read_bytes()
symbols = defined_symbols(Macho(data))
if guard not in symbols:
raise ValueError('Guard symbol missing')
destination = symbols[guard]
view = Slice(data, 0)
if not view.text:
raise ValueError('Missing __text')
start, length, offset = view.text
objects, entries = load_link_map(link_map)
found = defaultdict(list)
for address, size, obj, name in entries:
owner = Path(objects.get(obj, '').split('(')[0]).name
if owner != archive or name not in expected:
continue
if not start <= address < address + size <= start + length:
raise ValueError('Selected method outside __text')
for site in range(address, address + size, 4):
word, = struct.unpack_from('<I', data, offset + site - start)
if word & 0xfc000000 in (0x94000000, 0x14000000) and target(word, site) == destination:
found[name].append(hex(site))
if Counter({k: len(v) for k, v in found.items()}) != expected:
raise ValueError('Guard calls do not match prior call counts')
return dict(executable_sha256=hashlib.sha256(data).hexdigest(), archive=archive,
source=source, guard=guard, verified_calls=sum(expected.values()),
callers=dict(found))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
for name in ('previous_calls', 'executable', 'link_map', 'output'):
parser.add_argument(name, type=Path)
parser.add_argument('--archive', required=True)
parser.add_argument('--source', required=True)
parser.add_argument('--guard', required=True)
args = parser.parse_args()
report = verify(args.previous_calls, args.executable, args.link_map,
args.archive, args.source, args.guard)
with args.output.open('x') as stream:
json.dump(report, stream, indent=2)
stream.write('\n')
print(f'Verified {report["verified_calls"]} redirected calls')