From 1924c8f91c9d34e980cd500d2db03c7c438541d4 Mon Sep 17 00:00:00 2001 From: Vadson159 <154507348+Vadson159@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:37:31 +0100 Subject: [PATCH] fix(runtime): validate PE64 headers and executable section bounds in code_hooks (#5395) Squash-merged after diff review of PR #5395 --- runtime/src/code_hooks.h | 76 ++++++++++---- runtime/test/code_hooks_test.cpp | 168 +++++++++++++++++++++++++++++++ 2 files changed, 227 insertions(+), 17 deletions(-) diff --git a/runtime/src/code_hooks.h b/runtime/src/code_hooks.h index a079f95dd..147a84830 100644 --- a/runtime/src/code_hooks.h +++ b/runtime/src/code_hooks.h @@ -23,6 +23,7 @@ using RemapFn = uint32_t (*)(uint32_t); // Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free. inline uint8_t* alloc_near(const void* close_to, std::size_t size) { + if (!close_to || size == 0) return nullptr; SYSTEM_INFO si; GetSystemInfo(&si); const uintptr_t gran = si.dwAllocationGranularity; @@ -30,8 +31,9 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) { const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image for (uintptr_t delta = gran; delta < span; delta += gran) { for (int side = 0; side < 2; ++side) { - const uintptr_t at = side ? center + delta : center - delta; if (side == 0 && center < delta) continue; + if (side == 1 && UINTPTR_MAX - center < delta) continue; + const uintptr_t at = side ? center + delta : center - delta; if (void* p = VirtualAlloc(reinterpret_cast(at), size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)) return static_cast(p); @@ -44,7 +46,7 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) { // other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and // 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3. inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) { - if (arg != 0 && arg != 1) return nullptr; + if (!close_to || !fn || !original || (arg != 0 && arg != 1)) return nullptr; uint8_t* t = alloc_near(close_to, 4096); if (!t) return nullptr; uint8_t* p = t; @@ -69,7 +71,10 @@ inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, cons put({0x48, 0xB8}); put64(reinterpret_cast(original)); // mov rax, original put({0xFF, 0xE0}); // jmp rax DWORD old = 0; - VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); + if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) { + VirtualFree(t, 0, MEM_RELEASE); + return nullptr; + } FlushInstructionCache(GetCurrentProcess(), t, p - t); return t; } @@ -81,6 +86,7 @@ using ResultFn = uint32_t (*)(uint32_t result, uint32_t arg0); // register arguments (a stack argument would be one slot off) and an integer result. // Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls. inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) { + if (!close_to || !fn || !original) return nullptr; uint8_t* t = alloc_near(close_to, 4096); if (!t) return nullptr; uint8_t* p = t; @@ -97,7 +103,10 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20 put({0x59, 0xC3}); // pop rcx ; ret DWORD old = 0; - VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); + if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) { + VirtualFree(t, 0, MEM_RELEASE); + return nullptr; + } FlushInstructionCache(GetCurrentProcess(), t, p - t); return t; } @@ -106,14 +115,17 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* // Returns how many were rewritten. inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target, const uint8_t* thunk) { + if (!begin || !target || !thunk || size < 5) return 0; std::size_t n = 0; for (std::size_t i = 0; i + 5 <= size; ++i) { if (begin[i] != 0xE8 && begin[i] != 0xE9) continue; int32_t rel; std::memcpy(&rel, begin + i + 1, 4); const uint8_t* next = begin + i + 5; - if (next + rel != target) continue; - const intptr_t to = thunk - next; + const uintptr_t next_addr = reinterpret_cast(next); + const uintptr_t dst_addr = next_addr + static_cast(static_cast(rel)); + if (dst_addr != reinterpret_cast(target)) continue; + const intptr_t to = static_cast(reinterpret_cast(thunk) - next_addr); if (to < INT32_MIN || to > INT32_MAX) continue; const int32_t rel2 = static_cast(to); std::memcpy(begin + i + 1, &rel2, 4); @@ -136,27 +148,55 @@ struct HookResult { template inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) { HookResult r; + if (!base) return r.error = "not a mapped PE image", r; const auto* dos = reinterpret_cast(base); - if (dos->e_magic != IMAGE_DOS_SIGNATURE) return r.error = "not a mapped PE image", r; - const auto* nt = reinterpret_cast(base + dos->e_lfanew); - if (nt->Signature != IMAGE_NT_SIGNATURE || target_rva >= nt->OptionalHeader.SizeOfImage) - return r.error = "the RVA is outside the image", r; + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < static_cast(sizeof(IMAGE_DOS_HEADER))) + return r.error = "not a mapped PE image", r; + const uint64_t lfanew = static_cast(dos->e_lfanew); + const auto* nt = reinterpret_cast(base + lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || + nt->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64) || + nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return r.error = "not a mapped PE64 image", r; + const uint64_t image_size = nt->OptionalHeader.SizeOfImage; + const uint64_t sec_table_end = + lfanew + offsetof(IMAGE_NT_HEADERS64, OptionalHeader) + + static_cast(nt->FileHeader.SizeOfOptionalHeader) + + static_cast(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER); + if (image_size == 0 || sec_table_end > image_size) + return r.error = "not a mapped PE64 image", r; + if (target_rva >= image_size) return r.error = "the RVA is outside the image", r; const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); + // Match pe_loader.cpp's effective section span (VirtualSize, falling back to SizeOfRawData when 0), clamped to SizeOfImage. + auto exec_section_span = [&](const IMAGE_SECTION_HEADER& s, uint64_t& va, uint64_t& len) -> bool { + if (!(s.Characteristics & IMAGE_SCN_MEM_EXECUTE)) return false; + va = s.VirtualAddress; + const uint64_t raw = s.Misc.VirtualSize ? static_cast(s.Misc.VirtualSize) + : static_cast(s.SizeOfRawData); + if (raw == 0 || va >= image_size) return false; + len = raw > image_size - va ? image_size - va : raw; + return len > 0; + }; bool in_code = false; - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) - if ((sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && target_rva >= sec[i].VirtualAddress && - target_rva < sec[i].VirtualAddress + sec[i].Misc.VirtualSize) + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { + uint64_t va = 0, len = 0; + if (exec_section_span(sec[i], va, len) && target_rva >= va && target_rva < va + len) in_code = true; + } if (!in_code) return r.error = "the RVA is not in an executable section", r; uint8_t* target = base + target_rva; uint8_t* thunk = make(target); if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r; for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { - if (!(sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; - uint8_t* begin = base + sec[i].VirtualAddress; - const std::size_t size = sec[i].Misc.VirtualSize; + uint64_t va = 0, len = 0; + if (!exec_section_span(sec[i], va, len)) continue; + uint8_t* begin = base + va; + const std::size_t size = static_cast(len); DWORD old = 0; - if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) return r.error = "VirtualProtect failed", r; + if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) { + if (r.redirected == 0) VirtualFree(thunk, 0, MEM_RELEASE); + return r.error = "VirtualProtect failed", r; + } r.redirected += redirect_direct_branches(begin, size, target, thunk); DWORD ignored = 0; VirtualProtect(begin, size, old, &ignored); @@ -168,6 +208,7 @@ inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeT // The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`. inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) { + if (!fn) return HookResult{false, 0, "hook callback is null"}; if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"}; return redirect_image_calls(base, target_rva, [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); }); @@ -175,6 +216,7 @@ inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn f // The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument. inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) { + if (!fn) return HookResult{false, 0, "hook callback is null"}; return redirect_image_calls(base, target_rva, [&](uint8_t* target) { return make_result_thunk(target, fn, target); }); } diff --git a/runtime/test/code_hooks_test.cpp b/runtime/test/code_hooks_test.cpp index cb5e266da..cb8ce1727 100644 --- a/runtime/test/code_hooks_test.cpp +++ b/runtime/test/code_hooks_test.cpp @@ -5,6 +5,7 @@ #include #include +#include namespace { @@ -40,10 +41,26 @@ void caller(uint8_t* at, const uint8_t* to) { put(at + 9, {0x48, 0x83, 0xC4, 0x28, 0xC3}); } +void init_pe64(uint8_t* img, uint32_t size_of_image, const std::vector& sections) { + auto* dos = reinterpret_cast(img); + dos->e_magic = IMAGE_DOS_SIGNATURE; + dos->e_lfanew = 0x80; + auto* nt = reinterpret_cast(img + dos->e_lfanew); + nt->Signature = IMAGE_NT_SIGNATURE; + nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; + nt->FileHeader.NumberOfSections = static_cast(sections.size()); + nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); + nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; + nt->OptionalHeader.SizeOfImage = size_of_image; + IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); + for (std::size_t i = 0; i < sections.size(); ++i) sec[i] = sections[i]; +} + } // namespace int main() { using namespace leonida::hooks; + std::setvbuf(stdout, nullptr, _IONBF, 0); uint8_t* mem = alloc_near(reinterpret_cast(&remap_lucia), 4096); check(mem != nullptr, "executable memory near the module"); if (!mem) return 1; @@ -123,6 +140,157 @@ int main() { } check(!hook_image_results(mem, 0, first_person_on_foot).ok, "hook_image_results refuses memory without a PE"); + // Test A: PE64 executable section with Misc.VirtualSize == 0 falls back to SizeOfRawData (matching pe_loader.cpp). + uint8_t* img_a = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); + check(img_a != nullptr, "synthetic PE64 image A allocated near module"); + if (img_a) { + std::memset(img_a, 0, 0x2000); + IMAGE_SECTION_HEADER sec_a{}; + std::memcpy(sec_a.Name, ".text", 5); + sec_a.Misc.VirtualSize = 0; + sec_a.VirtualAddress = 0x1000; + sec_a.SizeOfRawData = 0x200; + sec_a.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; + init_pe64(img_a, 0x2000, {sec_a}); + put(img_a + 0x1000, {0x89, 0xC8, 0xC3}); // mov eax, ecx ; ret + caller(img_a + 0x1020, img_a + 0x1000); + DWORD old_a = 0; + check(VirtualProtect(img_a + 0x1000, 0x1000, PAGE_EXECUTE_READ, &old_a) != FALSE, + "image A code page marked PAGE_EXECUTE_READ"); + FlushInstructionCache(GetCurrentProcess(), img_a + 0x1000, 0x1000); + + const HookResult ra = hook_image_calls(img_a, 0x1000, &remap_lucia, 0); + check(ra.ok && ra.redirected == 1, + "VirtualSize == 0 executable section uses SizeOfRawData and redirects its caller"); + if (ra.ok) { + check(reinterpret_cast(img_a + 0x1020)(lucia) == mandy, + "hooked caller in VirtualSize == 0 section remaps Lucia to Mandy"); + check(reinterpret_cast(img_a + 0x1020)(1234) == 1234, + "hooked caller in VirtualSize == 0 section passes other hashes through"); + } + } + + // Test B: a 0-byte executable section (VirtualSize == 0 && SizeOfRawData == 0) is skipped rather than failing VirtualProtect. + uint8_t* img_b = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); + check(img_b != nullptr, "synthetic PE64 image B allocated near module"); + if (img_b) { + std::memset(img_b, 0, 0x2000); + IMAGE_SECTION_HEADER sec_empty{}; + std::memcpy(sec_empty.Name, ".empty", 6); + sec_empty.Misc.VirtualSize = 0; + sec_empty.VirtualAddress = 0x1000; + sec_empty.SizeOfRawData = 0; + sec_empty.Characteristics = IMAGE_SCN_MEM_EXECUTE; + IMAGE_SECTION_HEADER sec_text{}; + std::memcpy(sec_text.Name, ".text", 5); + sec_text.Misc.VirtualSize = 0x200; + sec_text.VirtualAddress = 0x1000; + sec_text.SizeOfRawData = 0x200; + sec_text.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; + init_pe64(img_b, 0x2000, {sec_empty, sec_text}); + put(img_b + 0x1040, {0xB8, 0x02, 0x00, 0x00, 0x00, 0xC3}); // mov eax, 2 ; ret + caller(img_b + 0x1060, img_b + 0x1040); + DWORD old_b = 0; + check(VirtualProtect(img_b + 0x1000, 0x1000, PAGE_EXECUTE_READ, &old_b) != FALSE, + "image B code page marked PAGE_EXECUTE_READ"); + FlushInstructionCache(GetCurrentProcess(), img_b + 0x1000, 0x1000); + + const int before_calls = original_calls; + const HookResult rb = hook_image_results(img_b, 0x1040, first_person_on_foot); + check(rb.ok && rb.redirected == 1, + "0-byte executable section is skipped and the non-empty section is hooked"); + if (rb.ok) { + using Ctx = uint32_t (*)(uint32_t); + check(reinterpret_cast(img_b + 0x1060)(0) == 4, + "result hook in PE64 image overrides context 0"); + check(reinterpret_cast(img_b + 0x1060)(3) == 2, + "result hook in PE64 image preserves non-overridden contexts"); + check(original_calls == before_calls + 2, + "result hook invokes the original getter on each call"); + } + } + + // Test C: sections extending past SizeOfImage are clamped and 32-bit VirtualAddress + VirtualSize wraparound is safe. + uint8_t* img_c = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); + check(img_c != nullptr, "synthetic PE64 image C allocated near module"); + if (img_c) { + std::memset(img_c, 0, 0x2000); + IMAGE_SECTION_HEADER sec_wrap{}; + std::memcpy(sec_wrap.Name, ".wrap", 5); + sec_wrap.Misc.VirtualSize = 0x200u; + sec_wrap.VirtualAddress = 0xFFFFFF00u; + sec_wrap.Characteristics = IMAGE_SCN_MEM_EXECUTE; + IMAGE_SECTION_HEADER sec_over{}; + std::memcpy(sec_over.Name, ".text", 5); + sec_over.Misc.VirtualSize = 0x1800u; // spans 0x0800..0x2000, past SizeOfImage = 0x1000 + sec_over.VirtualAddress = 0x0800u; + sec_over.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; + init_pe64(img_c, 0x1000, {sec_wrap, sec_over}); + put(img_c + 0x0800, {0x89, 0xC8, 0xC3}); // mov eax, ecx ; ret + caller(img_c + 0x0820, img_c + 0x0800); // in-image caller + caller(img_c + 0x1020, img_c + 0x0800); // out-of-image bytes past SizeOfImage + uint8_t out_before[16]; + std::memcpy(out_before, img_c + 0x1020, sizeof(out_before)); + FlushInstructionCache(GetCurrentProcess(), img_c, 0x2000); + + const HookResult rc = hook_image_calls(img_c, 0x0800, &remap_lucia, 0); + check(rc.ok && rc.redirected == 1, + "section past SizeOfImage is clamped and wraparound section is ignored"); + if (rc.ok) { + check(reinterpret_cast(img_c + 0x0820)(lucia) == mandy, + "in-image caller inside clamped section is remapped"); + check(std::memcmp(img_c + 0x1020, out_before, sizeof(out_before)) == 0, + "bytes beyond SizeOfImage are left untouched"); + } + } + + // Test D: malformed headers, PE32 optional header, out-of-image section table, and null arguments/callbacks. + uint8_t* bad = static_cast(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + check(bad != nullptr, "scratch buffer for malformed PE checks allocated"); + if (bad) { + std::memset(bad, 0, 0x1000); + auto* bad_dos = reinterpret_cast(bad); + bad_dos->e_magic = IMAGE_DOS_SIGNATURE; + bad_dos->e_lfanew = 0; + check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "MZ with e_lfanew == 0 is refused"); + bad_dos->e_lfanew = -16; + check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "MZ with negative e_lfanew is refused"); + + std::memset(bad, 0, 0x1000); + init_pe64(bad, 0x1000, {}); + auto* bad_nt = reinterpret_cast(bad + 0x80); + bad_nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC; + check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "PE32 optional header magic is refused"); + + std::memset(bad, 0, 0x1000); + init_pe64(bad, 0x200, {}); + bad_nt->FileHeader.NumberOfSections = 100; + check(!hook_image_calls(bad, 0x100, &remap_lucia, 0).ok, + "section table extending past SizeOfImage is refused"); + VirtualFree(bad, 0, MEM_RELEASE); + } + + if (img_a) { + check(!hook_image_calls(img_a, 0x1000, nullptr, 0).ok, "hook_image_calls refuses null callback"); + VirtualFree(img_a, 0, MEM_RELEASE); + } + if (img_b) { + check(!hook_image_results(img_b, 0x1040, nullptr).ok, "hook_image_results refuses null callback"); + VirtualFree(img_b, 0, MEM_RELEASE); + } + if (img_c) VirtualFree(img_c, 0, MEM_RELEASE); + + check(!hook_image_calls(nullptr, 0x1000, &remap_lucia, 0).ok, "hook_image_calls refuses null base"); + check(!hook_image_results(nullptr, 0x1000, first_person_on_foot).ok, "hook_image_results refuses null base"); + check(make_remap_thunk(target0, 0, nullptr, target0) == nullptr, "make_remap_thunk refuses null callback"); + check(make_remap_thunk(nullptr, 0, &remap_lucia, target0) == nullptr, "make_remap_thunk refuses null close_to"); + check(make_result_thunk(getter, nullptr, getter) == nullptr, "make_result_thunk refuses null callback"); + check(make_result_thunk(getter, first_person_on_foot, nullptr) == nullptr, + "make_result_thunk refuses null original"); + check(redirect_direct_branches(nullptr, 16, target0, thunk0) == 0, + "redirect_direct_branches returns 0 for null begin"); + VirtualFree(mem, 0, MEM_RELEASE); + std::printf("code_hooks_test: %d checks, %d failures\n", g_checks, g_failures); return g_failures == 0 ? 0 : 1; }