Files
xieyi-weixin-/test_wecom_native_adaptation.py
T
2026-09-29 15:51:28 +08:00

363 lines
17 KiB
Python

"""Synthetic PE fixtures and integration tests; no real messages or process writes."""
from dataclasses import replace
import hashlib
import struct
import tempfile
from pathlib import Path
import unittest
from unittest import mock
import wecom_native_adaptation as adaptation
from wecom_native_adaptation import (
PEImage, analyze_image, AdaptationUnavailable, validate_live_layout,
)
from wecom_native_builds import build_for_hash, build_for_version
from wecom_native_signatures import SIGNATURES
from reply_transport import protocol_ready
def fixture():
data = bytearray(0x18200)
data[:2] = b"MZ"
struct.pack_into("<I", data, 0x3c, 0x80)
data[0x80:0x84] = b"PE\0\0"
struct.pack_into("<HH", data, 0x84, 0x14c, 3)
struct.pack_into("<H", data, 0x94, 224)
struct.pack_into("<H", data, 0x98, 0x10b)
struct.pack_into("<I", data, 0x98 + 28, 0x400000)
struct.pack_into("<I", data, 0x98 + 56, 0x28000)
roles = (0x60000000, 0x40000000, 0xc0000000)
starts = (0x1000, 0x10000, 0x20000)
cursors = {role: 0x400000 + rva for role, rva in zip(roles, starts)}
for index, (role, rva) in enumerate(zip(roles, starts)):
at = 0x98 + 224 + index * 40
struct.pack_into("<4I", data, at + 8, 0x8000, rva, 0x8000, 0x200 + index * 0x8000)
struct.pack_into("<I", data, at + 36, role)
def allocate(role, size):
address = cursors[role]
cursors[role] += (size + 15) // 16 * 16
return address
def offset(address):
for index, rva in enumerate(starts):
if 0x400000 + rva <= address < 0x408000 + rva:
return 0x200 + index * 0x8000 + address - 0x400000 - rva
raise AssertionError(hex(address))
def put(address, raw):
at = offset(address)
data[at:at + len(raw)] = raw
bindings = {}
addresses = {}
for name, sig in SIGNATURES.items():
address = allocate(0x60000000, len(bytes.fromhex(sig["hex"])))
bindings[sig["address"]] = address
addresses[name] = address
for sig in SIGNATURES.values():
for _, _, old, flags in sig["captures"]:
if old not in bindings:
bindings[old] = allocate(flags, 32)
for name, sig in SIGNATURES.items():
raw = bytearray.fromhex(sig["hex"])
address = addresses[name]
for at, kind, old, _ in sig["captures"]:
target = bindings[old]
struct.pack_into("<I", raw, at, (target - address - at - 4 if kind == "rel" else target) & 0xffffffff)
put(address, raw)
def table(type_name, object_offset, table_address=None):
td = allocate(0xc0000000, 8 + len(type_name) + 1)
put(td + 8, type_name.encode() + b"\0")
hierarchy = allocate(0x40000000, 16)
col = allocate(0x40000000, 20)
put(col, struct.pack("<5I", 0, object_offset, 0, td, hierarchy))
if table_address is None:
table_address = allocate(0x40000000, 32) + 4
# Captured tables have 32-byte allocations, with room before the table.
put(table_address - 4, struct.pack("<I", col))
put(table_address, struct.pack("<6I", *([addresses["release"]] * 5 + [addresses["send"]])))
return table_address
table(".?AVMessageServiceImpl@logic@wework@@", 12)
table(".?AVLoginServiceImpl@logic@wework@@", 12)
table(".?AVServiceManagerImpl@logic@wework@@", 0, bindings[0xbe324d0])
return data, addresses, offset, bindings
class RelocationTests(unittest.TestCase):
def setUp(self):
self.data, self.addresses, self.offset, self.bindings = fixture()
def analyze(self, version="8.1.99.1234"):
return analyze_image(PEImage(self.data), version, hashlib.sha256(self.data).hexdigest())
def test_unlisted_major_version_with_identical_abi_resolves_without_granting_send(self):
profile = self.analyze()
self.assertTrue(profile.automatic)
self.assertFalse(profile.verified)
self.assertEqual(profile.send, self.addresses["send"])
self.assertEqual(profile.factory, self.addresses["factory"])
self.assertEqual(profile.service_root, self.bindings[0xfe3c444])
self.assertEqual(len(profile.live_checks), 12)
self.assertEqual(profile.send_argument_bytes, 16)
def test_changed_stack_cleanup_is_rejected(self):
at = self.offset(self.addresses["send"])
size = len(bytes.fromhex(SIGNATURES["send"]["hex"]))
ending = self.data[at:at + size].rfind(b"\xc2\x10\0")
self.assertGreater(ending, 0)
self.data[at + ending + 1] = 12
with self.assertRaises(AdaptationUnavailable):
self.analyze()
def test_changed_object_layout_is_rejected(self):
at = self.offset(self.addresses["factory_impl"])
sig = bytes.fromhex(SIGNATURES["factory_impl"]["hex"])
field = sig.index(bytes.fromhex("c7405002000000"))
self.data[at + field + 2] = 0x54
with self.assertRaises(AdaptationUnavailable):
self.analyze()
def test_inconsistent_calls_to_release_are_rejected(self):
sig = SIGNATURES["send"]
refs = [at for at, kind, target, _ in sig["captures"]
if kind == "rel" and target == SIGNATURES["release"]["address"]]
self.assertEqual(len(refs), 2)
at = self.offset(self.addresses["send"]) + refs[1]
struct.pack_into("<i", self.data, at, struct.unpack_from("<i", self.data, at)[0] + 16)
with self.assertRaises(AdaptationUnavailable):
self.analyze()
def test_duplicate_complete_factory_is_rejected(self):
at = self.offset(self.addresses["factory"])
raw = bytearray(self.data[at:at + len(bytes.fromhex(SIGNATURES["factory"]["hex"]))])
target = 0x407000
for capture, kind, _, _ in SIGNATURES["factory"]["captures"]:
if kind == "rel":
displacement = struct.unpack_from("<i", raw, capture)[0]
struct.pack_into("<i", raw, capture, displacement + self.addresses["factory"] - target)
off = self.offset(target)
self.data[off:off + len(raw)] = raw
with self.assertRaises(AdaptationUnavailable):
self.analyze()
def test_non_code_function_and_x64_images_rejected(self):
struct.pack_into("<I", self.data, 0x98 + 224 + 36, 0x40000000)
with self.assertRaises(AdaptationUnavailable):
self.analyze()
struct.pack_into("<H", self.data, 0x84, 0x8664)
with self.assertRaises(AdaptationUnavailable):
PEImage(self.data)
def test_truncated_and_overlapping_sections_rejected(self):
for raw in (b"", b"MZ", self.data[:200]):
with self.subTest(length=len(raw)), self.assertRaises(AdaptationUnavailable):
PEImage(raw)
struct.pack_into("<I", self.data, 0x98 + 224 + 40 + 12, 0x1000)
with self.assertRaises(AdaptationUnavailable):
PEImage(self.data)
def test_live_aslr_rebase_is_checked_beyond_prologues(self):
profile = self.analyze()
delta = 0x18000000
chunks = {}
for address, raw, relocations in profile.live_checks:
relocated = bytearray(raw)
for at in relocations:
struct.pack_into("<I", relocated, at, struct.unpack_from("<I", raw, at)[0] + delta)
chunks[address + delta] = bytes(relocated)
read = lambda address, size: chunks[address][:size]
validate_live_layout(profile, 0x400000 + delta, read)
address = profile.send + delta
raw = bytearray(chunks[address]); raw[200] ^= 1
chunks[address] = bytes(raw)
with self.assertRaises(AdaptationUnavailable):
validate_live_layout(profile, 0x400000 + delta, read)
class ProbeTests(unittest.TestCase):
def setUp(self):
data, _, _, _ = fixture()
self.profile = analyze_image(PEImage(data), "5.0.11.6029", hashlib.sha256(data).hexdigest())
self.enterContext(mock.patch.dict(adaptation._CACHE, {self.profile.sha256: self.profile}, clear=True))
self.client = dict(pid=12, path="C:/fixture/WXWork.exe", version=self.profile.version, architecture="x86")
self.live = dict(pid=12, accountId="100", clientVersion=self.profile.version,
clientSha256=self.profile.sha256, autoAdapted=True)
self.enterContext(mock.patch("wxwork_protocol_probe.running_clients", return_value=[self.client]))
self.enterContext(mock.patch("wxwork_protocol_probe.inspect_binary", return_value={}))
self.enterContext(mock.patch("wxwork_protocol_probe.bundled_agent_info", return_value={}))
self.enterContext(mock.patch("wecom_native_builds.sha256_file", return_value=self.profile.sha256))
self.discovery = self.enterContext(mock.patch("wecom_native_sender.discover", return_value=self.live))
self.enterContext(mock.patch("wecom_environment.protocol_database_status", return_value={"ready": True}))
self.receipt = self.enterContext(mock.patch("wecom_native_evidence.local_send_receipt", return_value=None))
def probe(self):
from wxwork_protocol_probe import probe_installed_client
return probe_installed_client(initialize_database=False)
def test_new_build_progresses_to_validation_without_send(self):
report = self.probe()
self.assertTrue(report["autoAdapted"])
self.assertEqual(report["buildMatchMode"], "structural")
self.assertEqual(report["status"], "native_validation_required")
self.assertTrue(report["databaseReady"])
self.assertFalse(report["canSend"])
self.assertFalse(report["sendVerified"])
self.assertFalse(protocol_ready(report))
def test_exact_account_receipt_required_for_ready(self):
self.receipt.return_value = {"status": "confirmed"}
report = self.probe()
self.assertTrue(protocol_ready(report))
self.assertFalse(protocol_ready({**report, "clientSha256": "0" * 64}))
self.receipt.return_value = None
self.assertFalse(protocol_ready(report))
def test_new_executable_does_not_reuse_old_version_layout(self):
unknown = "f" * 64
with mock.patch("wecom_native_builds.sha256_file", return_value=unknown), \
mock.patch.object(adaptation, "resolve_build", side_effect=AdaptationUnavailable("send ABI changed")):
report = self.probe()
self.assertFalse(report["canSend"])
self.assertTrue(report["needsAdapterUpdate"])
self.assertIn("send ABI changed", report["message"])
self.discovery.assert_not_called()
def test_identity_change_after_database_check_cancels_readiness(self):
self.receipt.return_value = {"status": "confirmed"}
self.discovery.side_effect = [self.live, {**self.live, "accountId": "101"}]
report = self.probe()
self.assertFalse(report["canSend"])
self.assertFalse(report["loginVerified"])
def test_static_old_build_lookup_unchanged(self):
old = build_for_version("5.0.10.6023")
self.assertEqual(build_for_hash(old.sha256), old)
self.assertFalse(old.automatic)
self.assertTrue(old.verified)
class CacheAndVerificationTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.path = Path(self.temporary.name) / "WXWork.exe"
self.data, _, _, _ = fixture()
self.path.write_bytes(self.data)
self.digest = hashlib.sha256(self.data).hexdigest()
self.enterContext(mock.patch.dict(adaptation._CACHE, {}, clear=True))
self.version = self.enterContext(mock.patch("wxwork_protocol_probe.file_version", return_value="5.0.11.6029"))
def test_cache_is_exact_digest_bound_and_does_not_mark_verified(self):
first = adaptation.resolve_build(self.path, self.digest)
self.assertIs(build_for_hash(self.digest), first)
self.assertFalse(first.verified)
self.data[-1] ^= 1
self.path.write_bytes(self.data)
digest = hashlib.sha256(self.data).hexdigest()
self.assertIsNone(build_for_hash(digest))
second = adaptation.resolve_build(self.path, digest)
self.assertNotEqual(first.sha256, second.sha256)
self.assertFalse(second.verified)
def test_wrong_hash_does_not_register_layout(self):
with self.assertRaises(AdaptationUnavailable):
adaptation.resolve_build(self.path, "0" * 64)
self.assertEqual(adaptation._CACHE, {})
def test_image_changed_during_analysis_does_not_register_layout(self):
def changed(image, version, digest):
result = analyze_image(image, version, digest)
with self.path.open("r+b") as handle:
handle.seek(-1, 2)
handle.write(b"X")
return result
with mock.patch.object(adaptation, "analyze_image", side_effect=changed):
with self.assertRaises(AdaptationUnavailable):
adaptation.resolve_build(self.path, self.digest)
self.assertEqual(adaptation._CACHE, {})
def test_verification_key_distinguishes_same_version_build_and_revision(self):
from wecom_native_verification import verification_request_id
profile = adaptation.resolve_build(self.path, self.digest)
original = verification_request_id(profile, "100", "S:100_200")
other = verification_request_id(replace(profile, sha256="f" * 64), "100", "S:100_200")
revised = verification_request_id(replace(profile, adapter_revision="v2"), "100", "S:100_200")
self.assertEqual(len({original, other, revised}), 3)
self.assertTrue(original.endswith(":5.0.11.6029:100:S:100_200"))
def test_confirmation_for_replaced_build_stops_before_database_or_sender(self):
from wecom_native_verification import run_send_test
profile = adaptation.resolve_build(self.path, self.digest)
live = dict(pid=1, accountId="100", clientVersion=profile.version,
clientSha256=profile.sha256, nativeAdapter=profile.adapter_id)
with mock.patch("wecom_native_verification.discover", return_value=live), \
mock.patch("reply_database.LiveReplyDatabase._open_database") as database, \
mock.patch("wecom_native_verification.NativeSender") as sender:
status = run_send_test(["--protocol-send-test", "test", "--report",
str(self.path.parent / "report.json"),
"--expected-sha256", "f" * 64])
self.assertEqual(status, 2)
database.assert_not_called()
sender.assert_not_called()
class NativeHandleTests(unittest.TestCase):
def setUp(self):
from wecom_native_sender import NativeClient
data, _, _, _ = fixture()
self.profile = analyze_image(PEImage(data), "5.0.11.6029", hashlib.sha256(data).hexdigest())
self.kernel = mock.Mock()
self.kernel.CreateToolhelp32Snapshot.return_value = 1
self.kernel.OpenProcess.side_effect = [10, 20]
def first(snapshot, pointer):
module = pointer._obj
module.szModule = "WXWork.exe"
module.szExePath = "C:/fixture/WXWork.exe"
module.modBaseAddr = 0x400000
return True
self.kernel.Module32FirstW.side_effect = first
self.enterContext(mock.patch("wecom_native_sender.kernel", return_value=self.kernel))
self.enterContext(mock.patch("wecom_native_sender._client_file_digest", return_value=self.profile.sha256))
self.enterContext(mock.patch("wecom_native_sender.build_for_hash", return_value=self.profile))
self.validate = self.enterContext(mock.patch.object(NativeClient, "validate", return_value="100"))
self.authorized = self.enterContext(mock.patch("wecom_native_sender.send_authorized", return_value=False))
def test_unverified_automatic_build_cannot_open_write_handle(self):
from wecom_native_sender import NativeClient, NativeUnavailable
with self.assertRaises(NativeUnavailable):
NativeClient(1, write=True)
self.kernel.OpenProcess.assert_called_once_with(0x410, False, 1)
self.kernel.WriteProcessMemory.assert_not_called()
self.kernel.CreateRemoteThread.assert_not_called()
def test_wrong_expected_build_stops_before_process_access(self):
from wecom_native_sender import NativeClient, NativeUnavailable
with self.assertRaises(NativeUnavailable):
NativeClient(1, write=True, allow_unverified=True, expected_sha256="0" * 64)
self.kernel.OpenProcess.assert_not_called()
def test_live_validation_failure_cannot_open_write_handle(self):
from wecom_native_sender import NativeClient, NativeUnavailable
self.validate.side_effect = NativeUnavailable("live code changed")
self.authorized.return_value = True
with self.assertRaises(NativeUnavailable):
NativeClient(1, write=True)
self.kernel.OpenProcess.assert_called_once_with(0x410, False, 1)
def test_identity_change_while_obtaining_handle_closes_it(self):
from wecom_native_sender import NativeClient, NativeUnavailable
self.authorized.return_value = True
self.validate.side_effect = ["100", "101"]
with self.assertRaises(NativeUnavailable):
NativeClient(1, write=True)
self.kernel.CloseHandle.assert_any_call(20)
self.kernel.WriteProcessMemory.assert_not_called()
if __name__ == "__main__":
unittest.main()