256 lines
11 KiB
Python
256 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
import struct
|
|
from dataclasses import dataclass
|
|
|
|
from capstone import CS_ARCH_X86, CS_GRP_JUMP, CS_MODE_32, Cs
|
|
from unicorn import Uc, UcError, UC_HOOK_CODE, UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, UC_MEM_READ
|
|
from unicorn.x86_const import (
|
|
UC_X86_REG_EAX,
|
|
UC_X86_REG_EBP,
|
|
UC_X86_REG_EBX,
|
|
UC_X86_REG_ECX,
|
|
UC_X86_REG_EDI,
|
|
UC_X86_REG_EDX,
|
|
UC_X86_REG_ESI,
|
|
UC_X86_REG_ESP,
|
|
UC_X86_REG_EIP,
|
|
)
|
|
|
|
from .abi import Buffer, CallSpec, ReturnKind, cleanup_is_callee
|
|
from .fp import capture_st0
|
|
from .image import CODE_SCRATCH, SCRATCH_BASE, SCRATCH_SIZE, STACK_BASE, STACK_SIZE, PeImage
|
|
from .result import GlobalDelta, RunResult
|
|
|
|
REGS = {
|
|
"eax": UC_X86_REG_EAX,
|
|
"ebx": UC_X86_REG_EBX,
|
|
"ecx": UC_X86_REG_ECX,
|
|
"edx": UC_X86_REG_EDX,
|
|
"esi": UC_X86_REG_ESI,
|
|
"edi": UC_X86_REG_EDI,
|
|
"ebp": UC_X86_REG_EBP,
|
|
}
|
|
RETURN_SENTINEL = CODE_SCRATCH + 0xF00
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class RunError(Exception):
|
|
detail: str
|
|
|
|
def __str__(self) -> str:
|
|
return f"emulation error: {self.detail}"
|
|
|
|
|
|
class UnicornRunner:
|
|
def __init__(self, image: PeImage, max_instructions: int = 1_000_000) -> None:
|
|
if max_instructions <= 0:
|
|
raise RunError(detail="instruction budget must be positive")
|
|
self.image = image
|
|
self.max_instructions = max_instructions
|
|
|
|
def run(self, spec: CallSpec) -> RunResult:
|
|
uc = self.image.new_emulator()
|
|
for region in spec.global_regions:
|
|
self.image.read(region.rva, len(region.data)) # check the whole range
|
|
uc.mem_write(self.image.va(region.rva), region.data)
|
|
# Read-only input constants (rdata fn-ptr tables, element counts) the
|
|
# function dereferences. Seeded before the baseline snapshot so they are
|
|
# inputs, never scored as deltas; the function never writes them (a
|
|
# written global must be a declared, owned GlobalRegion instead).
|
|
for address, data in spec.memory_seeds:
|
|
uc.mem_write(address, data)
|
|
# Snapshot AFTER IAT installation and input seeding. Host mem_write calls
|
|
# (including syscall out parameters) do not trigger Unicorn write hooks.
|
|
image_before = bytes(uc.mem_read(self.image.image_base, self.image.size))
|
|
by_tag: dict[str, tuple[int, Buffer]] = {}
|
|
cursor = SCRATCH_BASE
|
|
buffers = (
|
|
list(spec.buffers)
|
|
+ [r.buffer for r in spec.regs if r.buffer is not None]
|
|
+ [s.buffer for s in spec.stack_args if s.buffer is not None]
|
|
)
|
|
for buf in buffers:
|
|
if buf.tag in by_tag:
|
|
if by_tag[buf.tag][1] != buf:
|
|
raise RunError(detail=f"conflicting buffer tag {buf.tag}")
|
|
continue
|
|
size = max(len(buf.data), buf.out_size, 1)
|
|
if cursor + size > SCRATCH_BASE + SCRATCH_SIZE:
|
|
raise RunError(detail="scratch buffer capacity exceeded")
|
|
uc.mem_write(cursor, buf.data.ljust(size, b"\x00"))
|
|
by_tag[buf.tag] = (cursor, buf)
|
|
cursor += (size + 15) & ~15
|
|
for rv in spec.regs:
|
|
value = by_tag[rv.buffer.tag][0] if rv.buffer is not None else rv.immediate
|
|
if value is None:
|
|
raise RunError(detail=f"register {rv.reg} has no value")
|
|
uc.reg_write(REGS[rv.reg], value)
|
|
esp = STACK_BASE + STACK_SIZE - 0x100
|
|
for arg in reversed(spec.stack_args):
|
|
value = by_tag[arg.buffer.tag][0] if arg.buffer is not None else arg.immediate
|
|
if value is None:
|
|
raise RunError(detail="stack argument has no value")
|
|
esp -= 4
|
|
uc.mem_write(esp, struct.pack("<I", value & 0xFFFFFFFF))
|
|
esp -= 4
|
|
uc.mem_write(esp, struct.pack("<I", RETURN_SENTINEL))
|
|
uc.reg_write(UC_X86_REG_ESP, esp)
|
|
globals_before = [
|
|
(tag, rva, bytes(uc.mem_read(self.image.va(rva), size)))
|
|
for tag, rva, size in spec.globals_watched
|
|
]
|
|
steps = 0
|
|
written: set[int] = set()
|
|
owned = {
|
|
self.image.va(region.rva) + offset
|
|
for region in spec.global_regions for offset in range(len(region.data))
|
|
}
|
|
iat_bytes = {
|
|
self.image.va(rva) + offset
|
|
for rva in self.image.bound_import_rvas() for offset in range(4)
|
|
}
|
|
branches: list[tuple[int, bool]] = []
|
|
pending_branch: tuple[int, int] | None = None
|
|
decoder = Cs(CS_ARCH_X86, CS_MODE_32)
|
|
decoder.detail = True
|
|
branch_fallthrough: dict[int, int] = {}
|
|
for rva in spec.branch_sites:
|
|
address = self.image.va(rva)
|
|
ins = next(decoder.disasm(self.image.read(rva, 15), address), None)
|
|
if ins is None or not ins.group(CS_GRP_JUMP) or ins.mnemonic == "jmp":
|
|
raise RunError(detail=f"branch probe is not a conditional jump: {address:#x}")
|
|
branch_fallthrough[address] = address + ins.size
|
|
|
|
# Unicorn fixes these callback signatures.
|
|
def on_code(cpu: Uc, address: int, size: int, user_data: None) -> None:
|
|
nonlocal steps, pending_branch
|
|
steps += 1
|
|
if pending_branch is not None:
|
|
site, fallthrough = pending_branch
|
|
branches.append((site - self.image.image_base, address != fallthrough))
|
|
pending_branch = (
|
|
(address, branch_fallthrough[address]) if address in branch_fallthrough else None
|
|
)
|
|
|
|
def on_write(
|
|
cpu: Uc, access: int, address: int, size: int, value: int, user_data: None,
|
|
) -> None:
|
|
start = max(address, self.image.image_base)
|
|
end = min(address + size, self.image.image_base + self.image.size)
|
|
written.update(range(start, end))
|
|
|
|
def on_access(
|
|
cpu: Uc, access: int, address: int, size: int, value: int, user_data: None,
|
|
) -> None:
|
|
addresses = set(range(address, address + size))
|
|
allowed = owned | iat_bytes if access == UC_MEM_READ else owned
|
|
if not addresses <= allowed:
|
|
raise RunError(detail=f"unowned module access at {address:#x}+{size}")
|
|
|
|
hook = uc.hook_add(UC_HOOK_CODE, on_code)
|
|
write_hook = uc.hook_add(
|
|
UC_HOOK_MEM_WRITE, on_write, begin=self.image.image_base,
|
|
end=self.image.image_base + self.image.size - 1,
|
|
)
|
|
state_hook = uc.hook_add(
|
|
UC_HOOK_MEM_READ | UC_HOOK_MEM_WRITE, on_access,
|
|
begin=self.image.image_base, end=self.image.image_base + self.image.size - 1,
|
|
) if spec.capture_state else None
|
|
try:
|
|
# Stop before decoding the sentinel's blank scratch page.
|
|
uc.emu_start(self.image.va(spec.rva), RETURN_SENTINEL, count=self.max_instructions)
|
|
except UcError as error:
|
|
raise RunError(
|
|
detail=f"{error} at EIP={uc.reg_read(UC_X86_REG_EIP):#x} after {steps} instructions"
|
|
) from error
|
|
finally:
|
|
uc.hook_del(hook)
|
|
uc.hook_del(write_hook)
|
|
if state_hook is not None:
|
|
uc.hook_del(state_hook)
|
|
if uc.reg_read(UC_X86_REG_EIP) != RETURN_SENTINEL:
|
|
raise RunError(detail=f"did not return after {steps} instructions")
|
|
esp_after = uc.reg_read(UC_X86_REG_ESP)
|
|
expected = esp + 4 + (len(spec.stack_args) * 4 if cleanup_is_callee(spec.conv) else 0)
|
|
if esp_after != expected:
|
|
raise RunError(detail=f"stack cleanup mismatch: esp={esp_after:#x}, expected={expected:#x}")
|
|
import_calls = self.image.finish_run()
|
|
if spec.capture_state:
|
|
# Ownership is declared, not delta-observed: a stub (or the function)
|
|
# touching a module global absent from global_regions fails closed
|
|
# even when the bytes are unchanged. Host mem_write from an import
|
|
# stub bypasses the Unicorn access hook, so check its ranges here.
|
|
for address, length in self.image.stub_memory_accesses():
|
|
start = max(address, self.image.image_base)
|
|
end = min(address + length, self.image.image_base + self.image.size)
|
|
unowned = next((byte for byte in range(start, end) if byte not in owned), None)
|
|
if unowned is not None:
|
|
raise RunError(
|
|
detail=f"unowned stub-side module access at RVA {unowned - self.image.image_base:#x}"
|
|
)
|
|
image_after = bytes(uc.mem_read(self.image.image_base, self.image.size))
|
|
unexpected = next((
|
|
offset for offset, (before, after) in enumerate(zip(image_before, image_after))
|
|
if before != after and self.image.image_base + offset not in owned
|
|
), None)
|
|
if unexpected is not None:
|
|
raise RunError(detail=f"unowned module delta at RVA {unexpected:#x}")
|
|
eax = None if spec.ret is ReturnKind.VOID else uc.reg_read(UC_X86_REG_EAX)
|
|
edx = None
|
|
ret_offset = None
|
|
if spec.ret is ReturnKind.INT64:
|
|
edx = uc.reg_read(UC_X86_REG_EDX)
|
|
elif spec.ret is ReturnKind.POINTER_IMAGE:
|
|
pointer = uc.reg_read(UC_X86_REG_EAX)
|
|
if not self.image.image_base <= pointer < self.image.image_base + self.image.size:
|
|
raise RunError(
|
|
detail=f"pointer-image return left its own image: {pointer:#x}"
|
|
)
|
|
ret_offset = pointer - self.image.image_base
|
|
eax = None
|
|
st0 = None
|
|
st0_raw = None
|
|
if spec.ret in (ReturnKind.FLOAT_ST0, ReturnKind.DOUBLE_ST0):
|
|
st0, st0_raw = capture_st0(uc)
|
|
outputs = tuple(
|
|
(tag, bytes(uc.mem_read(address, buf.out_size)))
|
|
for tag, (address, buf) in by_tag.items()
|
|
if buf.out_size
|
|
)
|
|
outputs += self.image.external_outputs(uc)
|
|
deltas = []
|
|
snapshots = []
|
|
for region in spec.global_regions:
|
|
after = bytes(uc.mem_read(self.image.va(region.rva), len(region.data)))
|
|
snapshot = GlobalDelta(region.tag, region.identity_rva, region.data, after)
|
|
snapshots.append(snapshot)
|
|
if after != region.data:
|
|
deltas.append(snapshot)
|
|
written.difference_update(range(
|
|
self.image.va(region.rva), self.image.va(region.rva) + len(region.data),
|
|
))
|
|
for tag, rva, before in globals_before:
|
|
after = bytes(uc.mem_read(self.image.va(rva), len(before)))
|
|
if before != after:
|
|
deltas.append(GlobalDelta(tag, rva, before, after))
|
|
written.difference_update(range(self.image.va(rva), self.image.va(rva) + len(before)))
|
|
addresses = sorted(written)
|
|
index = 0
|
|
while index < len(addresses):
|
|
start = addresses[index]
|
|
end = start + 1
|
|
index += 1
|
|
while index < len(addresses) and addresses[index] == end:
|
|
end += 1
|
|
index += 1
|
|
rva = start - self.image.image_base
|
|
before = image_before[rva:rva + end - start]
|
|
after = bytes(uc.mem_read(start, end - start))
|
|
if before != after:
|
|
deltas.append(GlobalDelta("image", rva, before, after))
|
|
return RunResult(
|
|
eax, st0, outputs, tuple(deltas), esp, esp_after, steps, st0_raw, tuple(branches),
|
|
tuple(snapshots), import_calls, edx, ret_offset,
|
|
)
|