327 lines
15 KiB
Python
327 lines
15 KiB
Python
"""Read-only relocation of a reviewed native ABI onto a new client image.
|
||
|
||
A version number never grants compatibility. Match complete function bodies,
|
||
their pointer/call relationships and RTTI tables. Every result stays unverified
|
||
until that exact build and account have a confirmed first-send receipt.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import mmap
|
||
import os
|
||
from pathlib import Path
|
||
import re
|
||
import struct
|
||
from threading import RLock
|
||
|
||
from wecom_native_signatures import REVISION, SIGNATURES, SIGNATURE_VARIANTS
|
||
|
||
MAX_IMAGE_BYTES = 512 * 1024 * 1024
|
||
EXECUTE, READ, WRITE = 0x20000000, 0x40000000, 0x80000000
|
||
_CACHE = {}
|
||
_LOCK = RLock()
|
||
|
||
|
||
class AdaptationUnavailable(ValueError):
|
||
pass
|
||
|
||
|
||
class PEImage:
|
||
"""Bounded PE32 reader. Never maps executable pages or loads client code."""
|
||
def __init__(self, data):
|
||
self.data = data
|
||
self.sections = []
|
||
if len(data) < 256 or len(data) > MAX_IMAGE_BYTES or data[:2] != b"MZ":
|
||
raise AdaptationUnavailable("客户端 PE 文件无效")
|
||
pe = self.u32(0x3c)
|
||
if not 64 <= pe <= len(data) - 24 or data[pe:pe + 4] != b"PE\0\0":
|
||
raise AdaptationUnavailable("客户端 PE 头无效")
|
||
machine, count = struct.unpack_from("<HH", data, pe + 4)
|
||
optional_size = struct.unpack_from("<H", data, pe + 20)[0]
|
||
optional = pe + 24
|
||
if (machine != 0x14c or not 1 <= count <= 96 or optional_size < 96
|
||
or optional + optional_size + count * 40 > len(data)
|
||
or struct.unpack_from("<H", data, optional)[0] != 0x10b):
|
||
raise AdaptationUnavailable("自动接口适配目前要求 x86 PE32 客户端")
|
||
self.base = self.u32(optional + 28)
|
||
self.size = self.u32(optional + 56)
|
||
if self.base != 0x400000 or not 4096 <= self.size <= MAX_IMAGE_BYTES:
|
||
raise AdaptationUnavailable("客户端映像布局不符合已验证的调用方式")
|
||
for index in range(count):
|
||
at = optional + optional_size + index * 40
|
||
virtual_size, rva, raw_size, raw = struct.unpack_from("<4I", data, at + 8)
|
||
flags = self.u32(at + 36) & 0xe0000000
|
||
span = max(virtual_size, raw_size)
|
||
if (not span or rva + span > self.size or raw + raw_size > len(data)
|
||
or any(rva < s[0] + s[1] and s[0] < rva + span for s in self.sections)
|
||
or any(raw_size and s[3] and raw < s[2] + s[3] and s[2] < raw + raw_size
|
||
for s in self.sections)):
|
||
raise AdaptationUnavailable("客户端节区范围无效或重叠")
|
||
self.sections.append((rva, span, raw, raw_size, flags))
|
||
|
||
def u32(self, offset):
|
||
if not 0 <= offset <= len(self.data) - 4:
|
||
raise AdaptationUnavailable("客户端地址超出文件范围")
|
||
return struct.unpack_from("<I", self.data, offset)[0]
|
||
|
||
def section(self, address, size=1):
|
||
for section in self.sections:
|
||
rva, span, _, _, _ = section
|
||
if self.base + rva <= address and address + size <= self.base + rva + span:
|
||
return section
|
||
raise AdaptationUnavailable("接口地址不在客户端映像内")
|
||
|
||
def offset(self, address, size=1):
|
||
rva, _, raw, raw_size, _ = self.section(address, size)
|
||
delta = address - self.base - rva
|
||
if delta + size > raw_size:
|
||
raise AdaptationUnavailable("接口地址不在文件数据内")
|
||
return raw + delta
|
||
|
||
def bytes_at(self, address, size):
|
||
at = self.offset(address, size)
|
||
return self.data[at:at + size]
|
||
|
||
def find(self, needle, *, code=False, limit=64):
|
||
hits = []
|
||
for rva, _, raw, size, flags in self.sections:
|
||
if bool(flags & EXECUTE) != code or not flags & READ:
|
||
continue
|
||
position = raw
|
||
while position < raw + size:
|
||
position = self.data.find(needle, position, raw + size)
|
||
if position < 0:
|
||
break
|
||
hits.append(self.base + rva + position - raw)
|
||
if len(hits) > limit:
|
||
raise AdaptationUnavailable("接口特征匹配过多,无法唯一定位")
|
||
position += 1
|
||
return hits
|
||
|
||
def vtable(self, type_name, object_offset):
|
||
descriptors = self.find(type_name.encode("ascii") + b"\0")
|
||
if len(descriptors) != 1:
|
||
raise AdaptationUnavailable("客户端类型信息缺失或不唯一:" + type_name)
|
||
descriptor = descriptors[0] - 8
|
||
tables = set()
|
||
for reference in self.find(struct.pack("<I", descriptor)):
|
||
locator = reference - 12
|
||
try:
|
||
fields = struct.unpack("<5I", self.bytes_at(locator, 20))
|
||
if fields[:3] != (0, object_offset, 0):
|
||
continue
|
||
self.section(fields[4], 16)
|
||
for table_ref in self.find(struct.pack("<I", locator)):
|
||
table = table_ref + 4
|
||
if table % 4 or self.section(table, 24)[4] & (EXECUTE | WRITE):
|
||
continue
|
||
functions = struct.unpack("<6I", self.bytes_at(table, 24))
|
||
if all(self.section(fn)[4] & EXECUTE for fn in functions):
|
||
tables.add(table)
|
||
except AdaptationUnavailable:
|
||
continue
|
||
if len(tables) != 1:
|
||
raise AdaptationUnavailable("客户端虚函数表无法唯一定位:" + type_name)
|
||
return tables.pop()
|
||
|
||
|
||
def _pattern(signature):
|
||
raw = bytes.fromhex(signature["hex"])
|
||
masked = set()
|
||
for at, _, _, _ in signature["captures"]:
|
||
masked.update(range(at, at + 4))
|
||
return re.compile(b"".join(b"." if i in masked else re.escape(bytes([value]))
|
||
for i, value in enumerate(raw)), re.DOTALL)
|
||
|
||
|
||
_CONTRACTS = {
|
||
name: tuple((signature, _pattern(signature)) for signature in
|
||
(baseline, *SIGNATURE_VARIANTS.get(name, ())))
|
||
for name, baseline in SIGNATURES.items()
|
||
}
|
||
|
||
|
||
def _match(image, name, address, bindings):
|
||
# Each variant is a reviewed complete body, not additional wildcard bytes.
|
||
# Even indistinguishable contracts are rejected instead of selecting one.
|
||
matches = []
|
||
failures = []
|
||
for signature, pattern in _CONTRACTS[name]:
|
||
try:
|
||
matches.append(_match_contract(image, name, address, bindings, signature, pattern))
|
||
except AdaptationUnavailable as exc:
|
||
failures.append(str(exc))
|
||
if len(matches) == 1:
|
||
return matches[0]
|
||
if len(matches) > 1:
|
||
raise AdaptationUnavailable("接口函数签名不唯一:" + name)
|
||
raise AdaptationUnavailable(";".join(dict.fromkeys(failures)))
|
||
|
||
|
||
def _match_contract(image, name, address, bindings, signature, pattern):
|
||
size = len(bytes.fromhex(signature["hex"]))
|
||
if not image.section(address, size)[4] & EXECUTE:
|
||
raise AdaptationUnavailable("接口函数不在代码节区:" + name)
|
||
raw = image.bytes_at(address, size)
|
||
if not pattern.fullmatch(raw):
|
||
raise AdaptationUnavailable("接口调用方式已变化:" + name)
|
||
updated = dict(bindings)
|
||
original = signature["address"]
|
||
if original in updated and updated[original] != address:
|
||
raise AdaptationUnavailable("接口调用关系冲突:" + name)
|
||
updated[original] = address
|
||
relocations = []
|
||
for at, kind, old_target, flags in signature["captures"]:
|
||
value = struct.unpack_from("<I", raw, at)[0]
|
||
if kind == "rel":
|
||
value = address + at + 4 + struct.unpack_from("<i", raw, at)[0]
|
||
else:
|
||
relocations.append(at)
|
||
if image.section(value)[4] != flags:
|
||
raise AdaptationUnavailable("接口指针类型已变化:" + name)
|
||
if old_target in updated and updated[old_target] != value:
|
||
raise AdaptationUnavailable("接口指针关系已变化:" + name)
|
||
updated[old_target] = value
|
||
return updated, (address, raw, tuple(relocations))
|
||
|
||
|
||
def _candidates(image, name, *, limit=64):
|
||
hits = set()
|
||
for rva, _, raw, size, flags in image.sections:
|
||
if not flags & EXECUTE:
|
||
continue
|
||
for _, pattern in _CONTRACTS[name]:
|
||
for match in pattern.finditer(image.data, raw, raw + size):
|
||
hits.add(image.base + rva + match.start() - raw)
|
||
if len(hits) > limit:
|
||
raise AdaptationUnavailable("接口函数匹配过多:" + name)
|
||
return sorted(hits)
|
||
|
||
|
||
def analyze_image(image, version, digest):
|
||
"""Resolve all addresses with one consistent relationship map."""
|
||
from wecom_native_builds import NativeBuild, normalize_version
|
||
version = normalize_version(version)
|
||
if not version:
|
||
raise AdaptationUnavailable("新客户端缺少可核对的版本号")
|
||
message_table = image.vtable(".?AVMessageServiceImpl@logic@wework@@", 12)
|
||
login_table = image.vtable(".?AVLoginServiceImpl@logic@wework@@", 12)
|
||
manager_table = image.vtable(".?AVServiceManagerImpl@logic@wework@@", 0)
|
||
send = struct.unpack("<I", image.bytes_at(message_table + 20, 4))[0]
|
||
bindings, check = _match(image, "send", send, {})
|
||
checks = [check]
|
||
for name in ("release", "promise_make"):
|
||
bindings, check = _match(image, name, bindings[SIGNATURES[name]["address"]], bindings)
|
||
checks.append(check)
|
||
# Factory and singleton getter are independent roots. Only one complete
|
||
# graph is accepted, even when generic singleton code has multiple hits.
|
||
for names in (("factory", "factory_impl", "message_ctor"),
|
||
("manager_get", "manager_make", "manager_ctor")):
|
||
alternatives = []
|
||
failures = []
|
||
for candidate in _candidates(image, names[0]):
|
||
try:
|
||
current = dict(bindings)
|
||
candidate_checks = []
|
||
address = candidate
|
||
for name in names:
|
||
if name != names[0]:
|
||
address = current[SIGNATURES[name]["address"]]
|
||
current, check = _match(image, name, address, current)
|
||
candidate_checks.append(check)
|
||
if names[0] == "manager_get":
|
||
# The constructor must reference this ServiceManager RTTI table.
|
||
reference_table = 0xbe324d0
|
||
if current.get(reference_table) != manager_table:
|
||
raise AdaptationUnavailable("服务管理器类型不匹配")
|
||
alternatives.append((current, candidate_checks))
|
||
except (AdaptationUnavailable, KeyError) as exc:
|
||
failures.append((len(candidate_checks), str(exc)))
|
||
continue
|
||
if len(alternatives) != 1:
|
||
detail = ""
|
||
if not alternatives and failures:
|
||
# Report the deepest failed node; generic singleton candidates
|
||
# often fail earlier and should not hide the useful diagnosis.
|
||
deepest = max(depth for depth, _ in failures)
|
||
reasons = dict.fromkeys(reason for depth, reason in failures if depth == deepest)
|
||
detail = "(" + ";".join(list(reasons)[:3]) + ")"
|
||
elif len(alternatives) > 1:
|
||
detail = f"(发现 {len(alternatives)} 组完整匹配)"
|
||
else:
|
||
detail = "(入口函数无完整匹配)"
|
||
raise AdaptationUnavailable("接口关系无法唯一匹配:" + names[0] + detail)
|
||
bindings, candidate_checks = alternatives[0]
|
||
checks.extend(candidate_checks)
|
||
root = bindings.get(0xfe3c444)
|
||
if root is None or image.section(root, 12)[4] != READ | WRITE:
|
||
raise AdaptationUnavailable("服务根指针未通过校验")
|
||
# Include type tables in live image validation, not only function prologues.
|
||
for table in (message_table, login_table, manager_table):
|
||
checks.append((table, image.bytes_at(table, 24), tuple(range(0, 24, 4))))
|
||
return NativeBuild(
|
||
version, digest, root, message_table, login_table,
|
||
bindings[SIGNATURES["factory"]["address"]], send,
|
||
bindings[SIGNATURES["release"]["address"]],
|
||
"send_with_options", 16, False, REVISION,
|
||
automatic=True, live_checks=tuple(checks),
|
||
)
|
||
|
||
|
||
def cached_build(digest):
|
||
with _LOCK:
|
||
return _CACHE.get(str(digest or "").lower())
|
||
|
||
|
||
def resolve_build(path, digest):
|
||
"""Cache only immutable layouts keyed by the complete executable digest.
|
||
|
||
No persisted JSON, version-range match or previous receipt can register an
|
||
adapter. NativeClient still hashes the current image and validates its live
|
||
code, account and service pointers before opening a write handle.
|
||
"""
|
||
from wecom_native_builds import build_for_hash
|
||
known = build_for_hash(digest)
|
||
if known is not None:
|
||
return known
|
||
from wxwork_protocol_probe import file_version
|
||
path = Path(path)
|
||
version = file_version(path)
|
||
with _LOCK:
|
||
known = _CACHE.get(digest)
|
||
if known is not None:
|
||
return known
|
||
with path.open("rb") as handle:
|
||
before = os.fstat(handle.fileno())
|
||
if not 256 <= before.st_size <= MAX_IMAGE_BYTES:
|
||
raise AdaptationUnavailable("客户端文件大小不在自动分析范围内")
|
||
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
|
||
if hashlib.sha256(data).hexdigest() != digest:
|
||
raise AdaptationUnavailable("客户端在适配期间已变化,请重新检测")
|
||
profile = analyze_image(PEImage(data), version, digest)
|
||
# A concurrent updater must not register a mixture of images.
|
||
if hashlib.sha256(data).hexdigest() != digest:
|
||
raise AdaptationUnavailable("客户端在适配期间已变化,请重新检测")
|
||
after = os.fstat(handle.fileno())
|
||
with path.open("rb") as current:
|
||
latest = os.fstat(current.fileno())
|
||
identity = lambda st: (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)
|
||
if identity(before) != identity(after) or identity(before) != identity(latest):
|
||
raise AdaptationUnavailable("客户端在适配期间已变化,请重新检测")
|
||
if len(_CACHE) >= 16:
|
||
_CACHE.pop(next(iter(_CACHE)))
|
||
_CACHE[digest] = profile
|
||
return profile
|
||
|
||
|
||
def validate_live_layout(profile, base, read):
|
||
"""Compare relocated full bodies against the running image, read-only."""
|
||
delta = base - 0x400000
|
||
for address, raw, offsets in profile.live_checks:
|
||
expected = bytearray(raw)
|
||
for at in offsets:
|
||
value = struct.unpack_from("<I", raw, at)[0]
|
||
struct.pack_into("<I", expected, at, (value + delta) & 0xffffffff)
|
||
if read(address + delta, len(expected)) != expected:
|
||
raise AdaptationUnavailable("运行中的客户端接口与文件不一致,请重启企业微信后重新检测")
|