Files
speakeasy/tests/test_api_inline_hooks.py
Willi Ballenthin 4730f34fbe Resolve Windows APIs through mapped entry points
Synthetic API modules were decoy PE husks whose export stubs only
returned an index. Import binding and GetProcAddress gave out sentinel
addresses such as 0xFEEDFACE outside any mapping, and the emulator
caught calls through the invalid-fetch callback and a code hook on
each module. The export table and the IAT therefore gave different
addresses for one function, and a guest or debugger could not read,
hook, patch or break on the address of an imported API. A module
without a handler loaded the default_exe or default_driver decoy PE.

One session API registry now owns every synthesized entry.
ApiModuleLoader in api_image.py builds a mapped image for each API
module, from the exact declarations of the signature database
and the explicit function and data handlers. The export table, the IAT
and the resolvers give the same mapped entry for a function. Each
function entry jumps to a private trap token in a permanently unmapped 1
MiB reservation. A fetch of a token stops Unicorn, and _run_api_engine
dispatches the handler outside the native callback. Other accesses to
the reservation raise an access violation in the guest. The pc of an API
event is the call instruction when memory tracing is enabled, and the
caller's return address otherwise. A module without a handler gets an
empty placeholder image with a dynamic arena.

The get_proc and resolve_export resolvers back GetProcAddress,
LdrGetProcedureAddress and MmGetSystemRoutineAddress. They follow
forwarders and create dynamic-only entries in the .dyn arena of a
synthetic module. Import binding works on each IAT slot: a missing
synthetic export gets a dynamic entry, and an invalid slot keeps its
bytes. Data exports have writable storage in .data, and the CRT
_fmode, _commode and __initenv exports share it with their pointer
accessors. The per-run timeout and max_instructions limits now count
across API yields, with exact instruction accounting when a limit is
set.

The sentinel addresses, import_table, impdata_queue, the module access
hook and the default_exe/default_driver fallback are removed. Handler
callbacks always run inside an API frame, so setup_callback no longer
takes caller arguments, and the unused _normalize_mod_name is removed. A
guest PE without relocation data cannot be rebased. get_symbols returns
a snapshot, GDB breakpoints use the public entries, and
doc/unified-api-addresses.md describes the design.
2026-10-11 20:08:51 +01:00

41 lines
2.1 KiB
Python

"""Guest five-byte inline hooks on an API entry can call the original through a trampoline."""
import struct
import pytest
from speakeasy import Speakeasy, common
@pytest.mark.parametrize("memory_tracing", [False, True], ids=["plain", "traced"])
def test_x86_guest_five_byte_hook_calls_original_trampoline(config, memory_tracing):
config["analysis"]["memory_tracing"] = memory_tracing
with Speakeasy(config=config) as se:
caller = se.load_shellcode(data=b"\xcc" * 0x1000, arch="x86")
address = se.emu.get_proc("kernel32", "GetTickCount")
trampoline, hook = caller + 0x100, caller + 0x200
# The guest hook CALLs its saved trampoline, then adds one to the result.
hook_code = b"\xe8" + struct.pack("<I", (trampoline - hook - 5) & 0xFFFFFFFF)
se.mem_write(hook, hook_code + b"\x83\xc0\x01\xc3")
# Like an inline-hook installer, the guest copies exactly five bytes,
# appends JMP original+5, patches the original with JMP hook, then calls it.
code = b"\xbe" + struct.pack("<I", address) + b"\xbf" + struct.pack("<I", trampoline)
code += b"\xa5\xa4"
code += b"\xc6\x05" + struct.pack("<I", trampoline + 5) + b"\xe9"
code += b"\xc7\x05" + struct.pack("<II", trampoline + 6, (address + 5 - trampoline - 10) & 0xFFFFFFFF)
code += b"\xc6\x05" + struct.pack("<I", address) + b"\xe9"
code += b"\xc7\x05" + struct.pack("<II", address + 1, (hook - address - 5) & 0xFFFFFFFF)
code += b"\xb8" + struct.pack("<I", address) + b"\xff\xd0\xc3"
se.mem_write(caller, code)
se.emu.mem_protect(address & ~0xFFF, 0x1000, common.PERM_MEM_RWX)
hits = []
se.add_api_hook(lambda e, api, original, args: hits.append(api) or 77, "kernel32", "GetTickCount", argc=0)
se.run_shellcode(caller)
run = se.get_report().entry_points[0]
assert run.error is None
assert run.ret_val == 78
assert hits == ["kernel32.GetTickCount"]
assert [event.api_name for event in run.events if event.event == "api"] == ["kernel32.GetTickCount"]