Files
kdm-re/tools/unicorn_diff/udiff/t2.py
T

491 lines
21 KiB
Python

"""Strict recorded syscall replay; no host I/O and no default-success stubs."""
from __future__ import annotations
import json
import struct
from dataclasses import dataclass
from pathlib import Path
from unicorn import Uc, UC_HOOK_CODE
from unicorn.x86_const import UC_X86_REG_EAX, UC_X86_REG_ESP
from .image import CODE_SCRATCH, PeImage
@dataclass(frozen=True, slots=True)
class FixtureError(Exception):
detail: str
def __str__(self) -> str:
return f"fixture error: {self.detail}"
@dataclass(frozen=True, slots=True)
class MemoryEffect:
"""Pointer argument; compare outgoing bytes, then inject incoming bytes."""
argument: int
before: bytes
after: bytes
@dataclass(frozen=True, slots=True)
class IoEvent:
service: str
arguments: tuple[int, ...]
result: int
memory: tuple[MemoryEffect, ...] = ()
def __post_init__(self) -> None:
if not self.service or not 0 <= self.result <= 0xFFFFFFFF:
raise FixtureError(detail="event needs a service and a uint32 result")
if any(not 0 <= arg <= 0xFFFFFFFF for arg in self.arguments):
raise FixtureError(detail="arguments must be uint32 words")
pointers = [effect.argument for effect in self.memory]
if len(set(pointers)) != len(pointers):
raise FixtureError(detail="duplicate pointer argument")
for effect in self.memory:
if not 0 <= effect.argument < len(self.arguments):
raise FixtureError(detail="pointer argument outside call frame")
if self.arguments[effect.argument] != 0:
raise FixtureError(detail="recorded pointers must be normalized to zero")
if not effect.before and not effect.after:
raise FixtureError(detail="pointer effect must check or write bytes")
@dataclass(frozen=True, slots=True)
class RecordedIoFixture:
name: str
provenance: str
events: tuple[IoEvent, ...]
expected_eax: int
expected_output: bytes
def __post_init__(self) -> None:
if not self.name or not self.provenance or not self.events:
raise FixtureError(detail="empty name, provenance, or event stream")
if not 0 <= self.expected_eax <= 0xFFFFFFFF:
raise FixtureError(detail="expected EAX must be uint32")
@classmethod
def load(cls, path: Path) -> RecordedIoFixture:
"""Parse normalized recorded calls and independent golden observations."""
data = json.loads(path.read_text(encoding="utf-8"))
if data["schema_version"] != 1:
raise FixtureError(detail="unsupported recorded-I/O schema")
events = tuple(
IoEvent(
service=row["service"],
arguments=tuple(row["arguments"]),
result=row["result"],
memory=tuple(
MemoryEffect(
argument=effect["argument"],
before=bytes.fromhex(effect["before_hex"]),
after=bytes.fromhex(effect["after_hex"]),
)
for effect in row.get("memory", [])
),
)
for row in data["events"]
)
return cls(
name=data["name"], provenance=data["provenance"], events=events,
expected_eax=data["expected"]["eax"],
expected_output=bytes.fromhex(data["expected"]["output_hex"]),
)
@dataclass(frozen=True, slots=True)
class StubBinding:
"""Recovered x86 ABI, with optional IAT patch relative to the PE image."""
service: str
address: int
argument_count: int
callee_cleanup: bool
iat_rva: int | None = None
def _install_returns(emulator: Uc, bindings: tuple[StubBinding, ...]) -> None:
"""Only the declared x86 ABI decides stack cleanup."""
addresses = [binding.address for binding in bindings]
if len(set(addresses)) != len(addresses):
raise FixtureError(detail="duplicate stub address")
for binding in bindings:
if not 0 <= binding.argument_count <= 16383:
raise FixtureError(detail="invalid x86 argument count")
if not CODE_SCRATCH <= binding.address < CODE_SCRATCH + 0xE00:
raise FixtureError(detail="stub address outside reserved scratch code")
cleanup = binding.argument_count * 4 if binding.callee_cleanup else 0
instruction = b"\xc2" + struct.pack("<H", cleanup) if cleanup else b"\xc3"
emulator.mem_write(binding.address, instruction)
def _arguments(cpu: Uc, binding: StubBinding) -> tuple[int, ...]:
esp = cpu.reg_read(UC_X86_REG_ESP)
return struct.unpack(
f"<{binding.argument_count}I",
cpu.mem_read(esp + 4, binding.argument_count * 4),
) if binding.argument_count else ()
class StubbedSyscallMode:
"""Stateful replay cursor, reset for each emulator, never shared host state.
Each call must match the next recorded service, scalar arguments, and
outgoing memory. Recorded bytes are written to actual guest buffers.
Exhausted, missing, or reordered calls are errors, including zero calls.
Thread events are a prescribed schedule of observations, not OS threads.
"""
def __init__(
self, fixture: RecordedIoFixture, bindings: tuple[StubBinding, ...],
) -> None:
self.fixture = fixture
self.bindings = {binding.address: binding for binding in bindings}
if len(self.bindings) != len(bindings):
raise FixtureError(detail="duplicate stub address")
services = {binding.service for binding in bindings}
if not {event.service for event in fixture.events} <= services:
raise FixtureError(detail="recorded service has no explicit binding")
for binding in bindings:
if not 0 <= binding.argument_count <= 16383:
raise FixtureError(detail="invalid x86 argument count")
self.consumed = 0
self.calls: list[IoEvent] = []
# (guest address, length) of every recorded out-parameter access, so the
# runner can enforce declared ownership on stub-side host writes.
self.memory_accesses: list[tuple[int, int]] = []
def install(self, emulator: Uc) -> None:
"""Install into mapped scratch memory; unsupported calls still fault."""
self.consumed = 0
self.calls.clear()
self.memory_accesses.clear()
_install_returns(emulator, tuple(self.bindings.values()))
emulator.hook_add(UC_HOOK_CODE, self._on_code)
def _on_code(self, cpu: Uc, address: int, size: int, user_data: None) -> None:
# Callback signature is fixed by Unicorn.
if address not in self.bindings:
return
binding = self.bindings[address]
if self.consumed == len(self.fixture.events):
raise FixtureError(detail=f"unexpected extra call to {binding.service}")
event = self.fixture.events[self.consumed]
if event.service != binding.service:
raise FixtureError(detail=f"expected {event.service}, got {binding.service}")
arguments = list(_arguments(cpu, binding))
if len(arguments) != len(event.arguments):
raise FixtureError(detail=f"{binding.service}: argument count mismatch")
pointers = {effect.argument: arguments[effect.argument] for effect in event.memory}
for index in pointers:
arguments[index] = 0
if tuple(arguments) != event.arguments:
raise FixtureError(detail=f"{binding.service}: arguments {arguments} != {event.arguments}")
observed = []
for effect in event.memory:
pointer = pointers[effect.argument]
self.memory_accesses.append((pointer, max(len(effect.before), len(effect.after))))
before = bytes(cpu.mem_read(pointer, len(effect.before)))
if before != effect.before:
raise FixtureError(detail=f"{binding.service}: outgoing buffer mismatch")
if effect.after:
cpu.mem_write(pointer, effect.after)
observed.append(MemoryEffect(
effect.argument, before, bytes(cpu.mem_read(pointer, len(effect.after))),
))
cpu.reg_write(UC_X86_REG_EAX, event.result)
self.calls.append(IoEvent(
binding.service, tuple(arguments), event.result, tuple(observed),
))
self.consumed += 1
def finish(self) -> None:
"""Required after a clean function return; no unused fixture is evidence."""
if self.consumed != len(self.fixture.events):
raise FixtureError(detail=f"consumed {self.consumed}/{len(self.fixture.events)} events")
@dataclass(frozen=True, slots=True)
class ImportEnvironment:
"""One deterministic thread/process. Values are fixture inputs, never host state."""
heap_create_result: int = 0x51000000
heaps: tuple[int, ...] = ()
process_id: int = 0x1234
thread_id: int = 0x5678
tick_count: int = 0x10203040
file_time: int = 0x01D0123456789ABC
performance_counter: int = 0x123456789
pointer_cookie: int = 0x13579BDF
# Exact supported ABI surface. Unknown imports are deliberately not success stubs.
_WIN32_ARGUMENTS = {
"HeapCreate": 3, "HeapDestroy": 1, "GetProcessHeap": 0,
"HeapAlloc": 3, "HeapFree": 3,
"TlsAlloc": 0, "TlsFree": 1, "TlsGetValue": 1, "TlsSetValue": 2,
"FlsAlloc": 1, "FlsFree": 1, "FlsGetValue": 1, "FlsSetValue": 2,
"InitializeCriticalSectionAndSpinCount": 2, "InitializeCriticalSection": 1,
"EnterCriticalSection": 1, "LeaveCriticalSection": 1, "DeleteCriticalSection": 1,
"GetCurrentProcessId": 0, "GetCurrentThreadId": 0, "GetTickCount": 0,
"GetSystemTimeAsFileTime": 1, "QueryPerformanceCounter": 1,
"EncodePointer": 1, "DecodePointer": 1,
}
_CRT_ARGUMENTS = {"malloc": 1, "free": 1}
HEAP_BASE = 0x00800000
HEAP_SIZE = 0x00100000
def bind_imports(image: PeImage, services: tuple[str, ...]) -> tuple[StubBinding, ...]:
"""Bind a recovered PE IAT to the supported model; never infer an unknown ABI."""
slots = {slot.service: slot.rva for slot in image.imports()}
bindings = []
for index, service in enumerate(services):
library, name = service.rsplit(".", 1)
match library:
case "kernel32.dll":
signatures = _WIN32_ARGUMENTS
cleanup = True
case "msvcrt.dll":
signatures = _CRT_ARGUMENTS
cleanup = False
case _:
raise FixtureError(detail=f"unsupported import library {library}")
if name not in signatures or service not in slots:
raise FixtureError(detail=f"unsupported or absent import {service}")
bindings.append(StubBinding(
service, CODE_SCRATCH + 0x100 + index * 0x10,
signatures[name], cleanup, slots[service],
))
return tuple(bindings)
class DeterministicImports:
"""Mutable guest-only heap, TLS/FLS, and recursive lock state for one run.
Allocation addresses, handles and syscall values are fixed. No OS call is
made. Invalid lifecycle operations and unsupported callbacks fail closed.
Calls record actual arguments, results, and out-buffer bytes.
"""
def __init__(
self, bindings: tuple[StubBinding, ...],
environment: ImportEnvironment = ImportEnvironment(),
pointer_regions: tuple[tuple[int, int, int], ...] = (),
) -> None:
self.bindings = {binding.address: binding for binding in bindings}
if len(self.bindings) != len(bindings):
raise FixtureError(detail="duplicate stub address")
for binding in bindings:
library, name = binding.service.rsplit(".", 1)
expected = (_WIN32_ARGUMENTS if library == "kernel32.dll" else
_CRT_ARGUMENTS if library == "msvcrt.dll" else {})
if (name not in expected or expected[name] != binding.argument_count
or binding.callee_cleanup != (library == "kernel32.dll")):
raise FixtureError(detail=f"unsupported import ABI {binding.service}")
self.environment = environment
# (guest address, extent, canonical address), for lock identity across PEs.
self.pointer_regions = pointer_regions
self.calls: list[IoEvent] = []
# (guest address, length) of every stub-side out-parameter access, so the
# runner can enforce declared ownership on bytes a host mem_write touches
# without tripping a Unicorn hook.
self.memory_accesses: list[tuple[int, int]] = []
def install(self, emulator: Uc) -> None:
self.calls.clear()
self.memory_accesses.clear()
self.heaps = {0x50000000, *self.environment.heaps}
self.allocations: dict[int, tuple[int, int]] = {}
self.cursor = HEAP_BASE
self.slots: dict[str, dict[int, int]] = {"Tls": {}, "Fls": {}}
self.locks: dict[int, int] = {}
emulator.mem_map(HEAP_BASE, HEAP_SIZE)
_install_returns(emulator, tuple(self.bindings.values()))
emulator.hook_add(UC_HOOK_CODE, self._on_code)
def _allocate(self, cpu: Uc, heap: int, size: int, zero: bool) -> int:
if heap not in self.heaps:
raise FixtureError(detail=f"unknown heap {heap:#x}")
extent = (max(size, 1) + 15) & ~15
if self.cursor + extent > HEAP_BASE + HEAP_SIZE:
return 0
pointer = self.cursor
self.cursor += extent
self.allocations[pointer] = (heap, size)
cpu.mem_write(pointer, bytes([0 if zero else 0xCD]) * extent)
return pointer
def _free(self, heap: int, pointer: int) -> int:
if heap not in self.heaps:
raise FixtureError(detail=f"unknown heap {heap:#x}")
if pointer not in self.allocations or self.allocations[pointer][0] != heap:
raise FixtureError(detail=f"invalid free {pointer:#x} on heap {heap:#x}")
del self.allocations[pointer]
return 1
def _on_code(self, cpu: Uc, address: int, size: int, user_data: None) -> None:
if address not in self.bindings:
return
binding = self.bindings[address]
arguments = list(_arguments(cpu, binding))
name = binding.service.rsplit(".", 1)[1]
result = 0
memory: tuple[MemoryEffect, ...] = ()
env = self.environment
match name:
case "HeapCreate":
if arguments != [0, 0x1000, 0]:
raise FixtureError(detail="HeapCreate model supports flags=0, initial=4096, max=0")
result = env.heap_create_result
if result:
if result in self.heaps:
raise FixtureError(detail="fixture heap handle already exists")
self.heaps.add(result)
case "HeapDestroy":
heap = arguments[0]
if heap not in self.heaps:
raise FixtureError(detail=f"destroy unknown heap {heap:#x}")
self.heaps.remove(heap)
self.allocations = {
pointer: allocation for pointer, allocation in self.allocations.items()
if allocation[0] != heap
}
result = 1
case "GetProcessHeap":
result = 0x50000000
case "HeapAlloc":
heap, flags, length = arguments
if flags & ~8:
raise FixtureError(detail="unsupported HeapAlloc flags")
result = self._allocate(cpu, heap, length, bool(flags & 8))
case "malloc":
result = self._allocate(cpu, 0x50000000, arguments[0], False)
case "HeapFree":
heap, flags, pointer = arguments
if flags:
raise FixtureError(detail="unsupported HeapFree flags")
result = self._free(heap, pointer)
case "free":
if arguments[0]:
self._free(0x50000000, arguments[0])
case "TlsAlloc" | "FlsAlloc":
if arguments and arguments[0]:
raise FixtureError(detail="FLS callbacks require a recorded fixture")
slots = self.slots[name[:3]]
result = next((index for index in range(128) if index not in slots), 0xFFFFFFFF)
if result != 0xFFFFFFFF:
slots[result] = 0
case "TlsFree" | "FlsFree" | "TlsGetValue" | "FlsGetValue" | "TlsSetValue" | "FlsSetValue":
slots = self.slots[name[:3]]
index = arguments[0]
if index not in slots:
raise FixtureError(detail=f"unallocated {name[:3]} index {index}")
match name[3:]:
case "Free":
del slots[index]
result = 1
case "GetValue":
result = slots[index]
case "SetValue":
slots[index] = arguments[1]
result = 1
case "InitializeCriticalSection" | "InitializeCriticalSectionAndSpinCount":
pointer = arguments[0]
if pointer in self.locks:
raise FixtureError(detail="lock initialized twice")
self.locks[pointer] = 0
result = 1 if name.endswith("SpinCount") else 0
case "EnterCriticalSection" | "LeaveCriticalSection" | "DeleteCriticalSection":
pointer = arguments[0]
if pointer not in self.locks:
raise FixtureError(detail="uninitialized lock")
match name:
case "EnterCriticalSection":
self.locks[pointer] += 1
case "LeaveCriticalSection":
if self.locks[pointer] == 0:
raise FixtureError(detail="release of unheld lock")
self.locks[pointer] -= 1
case "DeleteCriticalSection":
if self.locks[pointer]:
raise FixtureError(detail="delete of held lock")
del self.locks[pointer]
case "GetCurrentProcessId":
result = env.process_id
case "GetCurrentThreadId":
result = env.thread_id
case "GetTickCount":
result = env.tick_count
case "GetSystemTimeAsFileTime" | "QueryPerformanceCounter":
pointer = arguments[0]
self.memory_accesses.append((pointer, 8))
before = bytes(cpu.mem_read(pointer, 8))
value = env.file_time if name == "GetSystemTimeAsFileTime" else env.performance_counter
after = struct.pack("<Q", value)
cpu.mem_write(pointer, after)
arguments[0] = 0
memory = (MemoryEffect(0, before, after),)
result = int(name == "QueryPerformanceCounter")
case "EncodePointer" | "DecodePointer":
result = arguments[0] ^ env.pointer_cookie
case _:
raise FixtureError(detail=f"unsupported import {binding.service}")
if "CriticalSection" in name:
pointer = arguments[0]
for start, extent, canonical in self.pointer_regions:
if start <= pointer < start + extent:
arguments[0] = canonical + pointer - start
break
else:
if not 0x00400000 <= pointer < 0x00500000:
raise FixtureError(detail="lock pointer needs a canonical region")
cpu.reg_write(UC_X86_REG_EAX, result)
self.calls.append(IoEvent(binding.service, tuple(arguments), result, memory))
def finish(self) -> None:
"""Caller effects, including live resources, are compared by the differential."""
class InjectedImage(PeImage):
"""Optional mode for existing UnicornRunner, without modifying its default."""
def __init__(self, path: Path, mode: StubbedSyscallMode | DeterministicImports) -> None:
super().__init__(path)
self.mode = mode
def new_emulator(self) -> Uc:
emulator = super().new_emulator()
# Unbound imports must fault, not accidentally execute import-name bytes.
for slot in self.imports():
emulator.mem_write(self.va(slot.rva), bytes(4))
self.mode.install(emulator)
for binding in self.mode.bindings.values():
if binding.iat_rva is not None:
emulator.mem_write(self.va(binding.iat_rva), struct.pack("<I", binding.address))
return emulator
def bound_import_rvas(self) -> tuple[int, ...]:
return tuple(
binding.iat_rva for binding in self.mode.bindings.values()
if binding.iat_rva is not None
)
def finish_run(self) -> tuple[IoEvent, ...]:
self.mode.finish()
return tuple(self.mode.calls)
def stub_memory_accesses(self) -> tuple[tuple[int, int], ...]:
return tuple(self.mode.memory_accesses)
def external_outputs(self, emulator: Uc) -> tuple[tuple[str, bytes], ...]:
match self.mode:
case DeterministicImports():
return tuple(
(f"heap:{pointer:#x}", bytes(emulator.mem_read(pointer, size)))
for pointer, (_, size) in sorted(self.mode.allocations.items())
)
case StubbedSyscallMode():
return ()