feat(defender): 可集成静态库 + readoor 接入方案(检测→分级→数据毒化闭环)
在 iOSGuard 侧产出可集成产物与接入文档,不修改 readoor 代码。 - defender/: anti_hook/anti_frida/anti_debug/anti_jailbreak 探针 + syscall 直发、 policy 分级层、poison 数据依赖毒化、dispatch/resolve/call_bridge 等子模块 - poison: 三副本冗余、无分支掩码;健康恒等、毒化破坏 key(替代 if-exit 处置) - policy: STRONG/MEDIUM/WEAK 分级,守误报底线,仅 DETECTED 参与、组合命中才毒化 - anti_jailbreak: IGSyscall 直发 svc 检测越狱文件(400)/沙盒逃逸(401),绕 libc hook - tools/build_defender_lib.sh: 一键交叉编译打包 libIGDefender.a(arm64) + umbrella 头 - docs/18_READOOR_DEFENDER_INTEGRATION.md: 精确到文件/bridging/替换点/代码片段 - docs/05-17 + evidence + tests + macho_guard/static_sdk_redirect 工具链 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
ff0aee7f47
commit
599e1da5ce
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"_read": "_IG_read",
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"_fopen": "_IG_fopen",
|
||||
"_fclose": "_IG_fclose",
|
||||
"_fread": "_IG_fread",
|
||||
"_fwrite": "_IG_fwrite"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"_write": "_IG_write",
|
||||
"_close": "_IG_close"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""兼容原 fopen PoC 命令;通用入口见 redirect_symbols.py。"""
|
||||
|
||||
from redirect_symbols import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(legacy_fopen=True)
|
||||
@@ -0,0 +1,241 @@
|
||||
#!/usr/bin/env python3
|
||||
"""由 JSON 映射驱动的 ARM64 Mach-O 静态归档外部 C 符号重定向工具。
|
||||
|
||||
只生成新文件;拒绝未知格式、目标符号冲突、动态库和实际 LLVM bitcode。
|
||||
允许并保留 __LLVM 内单字节零值的 bitcode/cmdline 占位标记。
|
||||
不改机器码或重定位索引,不自动生成 ABI 转发函数,不提供 IPA 加固保证。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ARCHIVE_MAGIC = b"!<arch>\n"
|
||||
DEFAULT_MAPPING = {"_fopen": "_IG_fopen"}
|
||||
CPU_ARM64 = 0x0100000C
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def bounds(data, offset, length):
|
||||
require(0 <= offset <= len(data) and 0 <= length <= len(data) - offset,
|
||||
"数据范围越界")
|
||||
|
||||
|
||||
def validate_mapping(mapping):
|
||||
require(isinstance(mapping, dict) and bool(mapping), "映射必须是非空 JSON 对象")
|
||||
for source, target in mapping.items():
|
||||
for name in (source, target):
|
||||
require(isinstance(name, str) and re.fullmatch(r"_[A-Za-z_][A-Za-z0-9_]*", name),
|
||||
"映射须使用带下划线前缀的精确 Mach-O C 符号名")
|
||||
require(len(set(mapping.values())) == len(mapping), "多个源符号不能共用一个目标")
|
||||
require(not set(mapping).intersection(mapping.values()), "不允许自映射、映射链或循环")
|
||||
return {source.encode("ascii"): target.encode("ascii") for source, target in mapping.items()}
|
||||
|
||||
|
||||
def load_mapping(path):
|
||||
def unique_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, f"JSON 映射存在重复键:{key}")
|
||||
result[key] = value
|
||||
return result
|
||||
mapping = json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique_pairs)
|
||||
validate_mapping(mapping)
|
||||
return mapping
|
||||
|
||||
|
||||
def redirect_object(data, mapping=None):
|
||||
rewritten, counts = _redirect_object(data, validate_mapping(DEFAULT_MAPPING if mapping is None else mapping))
|
||||
return rewritten, sum(counts.values())
|
||||
|
||||
|
||||
def _redirect_object(data, mapping):
|
||||
"""保持 nlist 索引及重定位不变,仅追加字符串、更新字符串偏移。"""
|
||||
bounds(data, 0, 32)
|
||||
magic, cpu, subtype, kind, count, size, _, _ = struct.unpack_from("<8I", data)
|
||||
require(magic == 0xFEEDFACF and cpu == CPU_ARM64 and subtype == 0,
|
||||
"仅支持 little-endian arm64(不含 arm64e)Mach-O 对象")
|
||||
require(kind == 1, "成员必须是 MH_OBJECT,不能处理可执行文件或动态库")
|
||||
bounds(data, 32, size)
|
||||
cursor = 32
|
||||
symtab = None
|
||||
for _ in range(count):
|
||||
require(cursor + 8 <= 32 + size, "load command 头越界")
|
||||
cmd, cmdsize = struct.unpack_from("<II", data, cursor)
|
||||
require(cmdsize >= 8 and cmdsize % 8 == 0 and cursor + cmdsize <= 32 + size,
|
||||
"load command 长度无效")
|
||||
require(cmd != 0x1D, "不支持含代码签名的对象")
|
||||
if cmd == 0x19:
|
||||
require(cmdsize >= 72, "segment command 太短")
|
||||
sections = struct.unpack_from("<I", data, cursor + 64)[0]
|
||||
require(72 + sections * 80 == cmdsize, "section 数量不匹配")
|
||||
for index in range(sections):
|
||||
pos = cursor + 72 + index * 80
|
||||
section_name = data[pos:pos + 16].rstrip(b"\0")
|
||||
segment = data[pos + 16:pos + 32].rstrip(b"\0")
|
||||
if segment == b"__LLVM":
|
||||
section_size = struct.unpack_from("<Q", data, pos + 40)[0]
|
||||
section_offset = struct.unpack_from("<I", data, pos + 48)[0]
|
||||
bounds(data, section_offset, section_size)
|
||||
require(section_name in (b"__bitcode", b"__cmdline") and section_size == 1
|
||||
and data[section_offset:section_offset + 1] == b"\0",
|
||||
"实际 LLVM bitcode 或未知 LLVM section 不在本 PoC 支持范围")
|
||||
if cmd == 2:
|
||||
require(symtab is None and cmdsize == 24, "LC_SYMTAB 重复或长度无效")
|
||||
symtab = cursor
|
||||
cursor += cmdsize
|
||||
require(cursor == 32 + size, "load command 总长度不匹配")
|
||||
require(symtab is not None, "对象缺少 LC_SYMTAB")
|
||||
symoff, nsyms, stroff, strsize = struct.unpack_from("<4I", data, symtab + 8)
|
||||
bounds(data, symoff, nsyms * 16)
|
||||
bounds(data, stroff, strsize)
|
||||
require(symoff >= cursor and stroff >= symoff + nsyms * 16,
|
||||
"不支持重叠或乱序的符号表/字符串表")
|
||||
# Apple 静态归档可能在对象尾部加入换行填充,也接受零填充。
|
||||
tail = data[stroff + strsize:]
|
||||
require(len(tail) <= 7 and (not tail or set(tail) <= {0} or set(tail) <= {10}),
|
||||
"字符串表后存在未知数据")
|
||||
strings = data[stroff:stroff + strsize]
|
||||
changed = []
|
||||
for index in range(nsyms):
|
||||
pos = symoff + index * 16
|
||||
strx, ntype, section, _, value = struct.unpack_from("<IBBHQ", data, pos)
|
||||
require(strx < strsize, "符号字符串索引越界")
|
||||
end = strings.find(b"\0", strx)
|
||||
require(end != -1, "符号名缺少终止符")
|
||||
name = strings[strx:end]
|
||||
require(name not in mapping.values(), f"归档已包含目标符号 {name!r},拒绝重复处理或冲突")
|
||||
if name in mapping:
|
||||
require(ntype == 1 and section == 0 and value == 0,
|
||||
f"{name!r} 必须是普通外部未定义符号,不能重写定义/common/debug 符号")
|
||||
changed.append((pos, name))
|
||||
if not changed:
|
||||
return data, Counter()
|
||||
output = bytearray(data[:stroff + strsize])
|
||||
offsets = {}
|
||||
counts = Counter()
|
||||
for pos, name in changed:
|
||||
if name not in offsets:
|
||||
offsets[name] = len(output) - stroff
|
||||
output.extend(mapping[name] + b"\0")
|
||||
struct.pack_into("<I", output, pos, offsets[name])
|
||||
counts[name.decode("ascii")] += 1
|
||||
# 保持对象长度为 8 字节对齐,填充也属于字符串表。
|
||||
output.extend(b"\0" * (-len(output) % 8))
|
||||
struct.pack_into("<I", output, symtab + 20, len(output) - stroff)
|
||||
return bytes(output), counts
|
||||
|
||||
|
||||
def redirect_archive(data, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
encoded_mapping = validate_mapping(mapping)
|
||||
require(data.startswith(ARCHIVE_MAGIC), "输入不是普通 ar 归档")
|
||||
output = bytearray(ARCHIVE_MAGIC)
|
||||
cursor = len(ARCHIVE_MAGIC)
|
||||
records = []
|
||||
members = 0
|
||||
totals = Counter({source: 0 for source in mapping})
|
||||
while cursor < len(data):
|
||||
bounds(data, cursor, 60)
|
||||
header = data[cursor:cursor + 60]
|
||||
require(header[58:60] == b"`\n", "ar 成员头无效")
|
||||
length = int(header[48:58].strip())
|
||||
bounds(data, cursor + 60, length)
|
||||
payload = data[cursor + 60:cursor + 60 + length]
|
||||
name = header[:16].rstrip(b" ")
|
||||
prefix = b""
|
||||
if name.startswith(b"#1/"):
|
||||
name_length = int(name[3:])
|
||||
require(0 < name_length <= len(payload), "BSD 扩展成员名长度无效")
|
||||
prefix, payload = payload[:name_length], payload[name_length:]
|
||||
name = prefix.rstrip(b"\0")
|
||||
else:
|
||||
require(not name.startswith(b"/"), "暂不支持 GNU 长名称或 GNU 索引格式")
|
||||
name = name.rstrip(b"/")
|
||||
require(bool(name), "空成员名")
|
||||
cursor += 60 + length
|
||||
if length % 2:
|
||||
bounds(data, cursor, 1)
|
||||
require(data[cursor:cursor + 1] == b"\n", "ar 填充无效")
|
||||
cursor += 1
|
||||
if name in (b"__.SYMDEF", b"__.SYMDEF SORTED", b"__.SYMDEF_64", b"__.SYMDEF_64 SORTED"):
|
||||
continue # 修改后必须由 ranlib 重建索引。
|
||||
try:
|
||||
rewritten, counts = _redirect_object(payload, encoded_mapping)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"成员 {os.fsdecode(name)}:{error}") from error
|
||||
members += 1
|
||||
if counts:
|
||||
totals.update(counts)
|
||||
records.append({"member_index": members, "member": os.fsdecode(name),
|
||||
"references": sum(counts.values()), "symbols": dict(counts)})
|
||||
combined = prefix + rewritten
|
||||
require(len(str(len(combined))) <= 10, "成员过大")
|
||||
output.extend(header[:48] + str(len(combined)).encode().ljust(10) + header[58:60])
|
||||
output.extend(combined)
|
||||
if len(combined) % 2:
|
||||
output.extend(b"\n")
|
||||
require(bool(records), "没有找到映射中的可重定向引用")
|
||||
unmatched = [source for source in mapping if not totals[source]]
|
||||
require(not require_all or not unmatched, f"要求全部命中,但缺少符号:{', '.join(unmatched)}")
|
||||
return bytes(output), {"members_checked": members, "changed_members": records,
|
||||
"references_redirected": sum(totals.values()),
|
||||
"symbol_counts": dict(totals), "unmatched_symbols": unmatched}
|
||||
|
||||
|
||||
def run(source, destination, mapping=None, require_all=False):
|
||||
mapping = DEFAULT_MAPPING if mapping is None else mapping
|
||||
validate_mapping(mapping)
|
||||
source, destination = source.resolve(), destination.absolute()
|
||||
require(source != destination.resolve(), "不能覆盖输入")
|
||||
require(not destination.exists() and not destination.is_symlink(), "输出已存在,拒绝覆盖")
|
||||
original = source.read_bytes()
|
||||
with tempfile.TemporaryDirectory(prefix="iosguard-", dir=destination.parent) as folder:
|
||||
thin = Path(folder) / "input.a"
|
||||
if original.startswith(ARCHIVE_MAGIC):
|
||||
thin.write_bytes(original)
|
||||
else:
|
||||
require(original[:4] in (b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"),
|
||||
"仅接受 BSD 静态归档或包含该归档的 fat 文件")
|
||||
subprocess.run(["xcrun", "lipo", str(source), "-thin", "arm64", "-output", str(thin)], check=True)
|
||||
archive, report = redirect_archive(thin.read_bytes(), mapping, require_all)
|
||||
candidate = Path(folder) / "redirected.a"
|
||||
candidate.write_bytes(archive)
|
||||
subprocess.run(["xcrun", "ranlib", str(candidate)], check=True)
|
||||
report.update({"source": str(source), "output": str(destination), "architecture": "arm64",
|
||||
"source_sha256": hashlib.sha256(original).hexdigest(),
|
||||
"output_sha256": hashlib.sha256(candidate.read_bytes()).hexdigest(),
|
||||
"mapping": dict(mapping)})
|
||||
# 同目录硬链接原子发布,目标已存在时失败,避免竞争覆盖。
|
||||
os.link(candidate, destination)
|
||||
return report
|
||||
|
||||
|
||||
def main(legacy_fopen=False):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("output", type=Path, help="不存在的新 .a 路径;父目录须存在")
|
||||
if not legacy_fopen:
|
||||
parser.add_argument("--mapping", type=Path, required=True, help="精确的 Mach-O C 符号映射 JSON")
|
||||
parser.add_argument("--require-all", action="store_true", help="每个源符号均须命中,否则不输出")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
mapping = DEFAULT_MAPPING if legacy_fopen else load_mapping(args.mapping)
|
||||
print(json.dumps(run(args.input, args.output, mapping, args.require_all), ensure_ascii=False, indent=2))
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
parser.exit(1, f"重定向失败:{error}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user