upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/code_hooks.h
diff options
context:
space:
mode:
authorVadson159 <154507348+Vadson159@users.noreply.github.com>2026-11-23 17:37:31 +0100
committerGitHub <noreply@github.com>2026-11-23 10:37:31 -0600
commit1924c8f91c9d34e980cd500d2db03c7c438541d4 (patch)
tree24a6d022a200325ad26a17013a956a68dc60d0f2 /runtime/src/code_hooks.h
parent115f3b26113e31f0510c0b906993158be3885714 (diff)
fix(runtime): validate PE64 headers and executable section bounds in code_hooks (#5395)
Squash-merged after diff review of PR #5395
Diffstat (limited to 'runtime/src/code_hooks.h')
-rw-r--r--runtime/src/code_hooks.h76
1 files changed, 59 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);
23 23
24// Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free. 24// Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free.
25inline uint8_t* alloc_near(const void* close_to, std::size_t size) { 25inline uint8_t* alloc_near(const void* close_to, std::size_t size) {
26 if (!close_to || size == 0) return nullptr;
26 SYSTEM_INFO si; 27 SYSTEM_INFO si;
27 GetSystemInfo(&si); 28 GetSystemInfo(&si);
28 const uintptr_t gran = si.dwAllocationGranularity; 29 const uintptr_t gran = si.dwAllocationGranularity;
@@ -30,8 +31,9 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) {
30 const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image 31 const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image
31 for (uintptr_t delta = gran; delta < span; delta += gran) { 32 for (uintptr_t delta = gran; delta < span; delta += gran) {
32 for (int side = 0; side < 2; ++side) { 33 for (int side = 0; side < 2; ++side) {
33 const uintptr_t at = side ? center + delta : center - delta;
34 if (side == 0 && center < delta) continue; 34 if (side == 0 && center < delta) continue;
35 if (side == 1 && UINTPTR_MAX - center < delta) continue;
36 const uintptr_t at = side ? center + delta : center - delta;
35 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT, 37 if (void* p = VirtualAlloc(reinterpret_cast<void*>(at), size, MEM_RESERVE | MEM_COMMIT,
36 PAGE_EXECUTE_READWRITE)) 38 PAGE_EXECUTE_READWRITE))
37 return static_cast<uint8_t*>(p); 39 return static_cast<uint8_t*>(p);
@@ -44,7 +46,7 @@ inline uint8_t* alloc_near(const void* close_to, std::size_t size) {
44// other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and 46// other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and
45// 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3. 47// 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3.
46inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) { 48inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) {
47 if (arg != 0 && arg != 1) return nullptr; 49 if (!close_to || !fn || !original || (arg != 0 && arg != 1)) return nullptr;
48 uint8_t* t = alloc_near(close_to, 4096); 50 uint8_t* t = alloc_near(close_to, 4096);
49 if (!t) return nullptr; 51 if (!t) return nullptr;
50 uint8_t* p = t; 52 uint8_t* p = t;
@@ -69,7 +71,10 @@ inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, cons
69 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original 71 put({0x48, 0xB8}); put64(reinterpret_cast<uint64_t>(original)); // mov rax, original
70 put({0xFF, 0xE0}); // jmp rax 72 put({0xFF, 0xE0}); // jmp rax
71 DWORD old = 0; 73 DWORD old = 0;
72 VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); 74 if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) {
75 VirtualFree(t, 0, MEM_RELEASE);
76 return nullptr;
77 }
73 FlushInstructionCache(GetCurrentProcess(), t, p - t); 78 FlushInstructionCache(GetCurrentProcess(), t, p - t);
74 return t; 79 return t;
75} 80}
@@ -81,6 +86,7 @@ using ResultFn = uint32_t (*)(uint32_t result, uint32_t arg0);
81// register arguments (a stack argument would be one slot off) and an integer result. 86// register arguments (a stack argument would be one slot off) and an integer result.
82// Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls. 87// Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls.
83inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) { 88inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) {
89 if (!close_to || !fn || !original) return nullptr;
84 uint8_t* t = alloc_near(close_to, 4096); 90 uint8_t* t = alloc_near(close_to, 4096);
85 if (!t) return nullptr; 91 if (!t) return nullptr;
86 uint8_t* p = t; 92 uint8_t* p = t;
@@ -97,7 +103,10 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void*
97 put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20 103 put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20
98 put({0x59, 0xC3}); // pop rcx ; ret 104 put({0x59, 0xC3}); // pop rcx ; ret
99 DWORD old = 0; 105 DWORD old = 0;
100 VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old); 106 if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old)) {
107 VirtualFree(t, 0, MEM_RELEASE);
108 return nullptr;
109 }
101 FlushInstructionCache(GetCurrentProcess(), t, p - t); 110 FlushInstructionCache(GetCurrentProcess(), t, p - t);
102 return t; 111 return t;
103} 112}
@@ -106,14 +115,17 @@ inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void*
106// Returns how many were rewritten. 115// Returns how many were rewritten.
107inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target, 116inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target,
108 const uint8_t* thunk) { 117 const uint8_t* thunk) {
118 if (!begin || !target || !thunk || size < 5) return 0;
109 std::size_t n = 0; 119 std::size_t n = 0;
110 for (std::size_t i = 0; i + 5 <= size; ++i) { 120 for (std::size_t i = 0; i + 5 <= size; ++i) {
111 if (begin[i] != 0xE8 && begin[i] != 0xE9) continue; 121 if (begin[i] != 0xE8 && begin[i] != 0xE9) continue;
112 int32_t rel; 122 int32_t rel;
113 std::memcpy(&rel, begin + i + 1, 4); 123 std::memcpy(&rel, begin + i + 1, 4);
114 const uint8_t* next = begin + i + 5; 124 const uint8_t* next = begin + i + 5;
115 if (next + rel != target) continue; 125 const uintptr_t next_addr = reinterpret_cast<uintptr_t>(next);
116 const intptr_t to = thunk - next; 126 const uintptr_t dst_addr = next_addr + static_cast<uintptr_t>(static_cast<intptr_t>(rel));
127 if (dst_addr != reinterpret_cast<uintptr_t>(target)) continue;
128 const intptr_t to = static_cast<intptr_t>(reinterpret_cast<uintptr_t>(thunk) - next_addr);
117 if (to < INT32_MIN || to > INT32_MAX) continue; 129 if (to < INT32_MIN || to > INT32_MAX) continue;
118 const int32_t rel2 = static_cast<int32_t>(to); 130 const int32_t rel2 = static_cast<int32_t>(to);
119 std::memcpy(begin + i + 1, &rel2, 4); 131 std::memcpy(begin + i + 1, &rel2, 4);
@@ -136,27 +148,55 @@ struct HookResult {
136template <class MakeThunk> 148template <class MakeThunk>
137inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) { 149inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) {
138 HookResult r; 150 HookResult r;
151 if (!base) return r.error = "not a mapped PE image", r;
139 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base); 152 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
140 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return r.error = "not a mapped PE image", r; 153 if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < static_cast<LONG>(sizeof(IMAGE_DOS_HEADER)))
141 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew); 154 return r.error = "not a mapped PE image", r;
142 if (nt->Signature != IMAGE_NT_SIGNATURE || target_rva >= nt->OptionalHeader.SizeOfImage) 155 const uint64_t lfanew = static_cast<uint64_t>(dos->e_lfanew);
143 return r.error = "the RVA is outside the image", r; 156 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + lfanew);
157 if (nt->Signature != IMAGE_NT_SIGNATURE ||
158 nt->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64) ||
159 nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
160 return r.error = "not a mapped PE64 image", r;
161 const uint64_t image_size = nt->OptionalHeader.SizeOfImage;
162 const uint64_t sec_table_end =
163 lfanew + offsetof(IMAGE_NT_HEADERS64, OptionalHeader) +
164 static_cast<uint64_t>(nt->FileHeader.SizeOfOptionalHeader) +
165 static_cast<uint64_t>(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER);
166 if (image_size == 0 || sec_table_end > image_size)
167 return r.error = "not a mapped PE64 image", r;
168 if (target_rva >= image_size) return r.error = "the RVA is outside the image", r;
144 const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); 169 const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
170 // Match pe_loader.cpp's effective section span (VirtualSize, falling back to SizeOfRawData when 0), clamped to SizeOfImage.
171 auto exec_section_span = [&](const IMAGE_SECTION_HEADER& s, uint64_t& va, uint64_t& len) -> bool {
172 if (!(s.Characteristics & IMAGE_SCN_MEM_EXECUTE)) return false;
173 va = s.VirtualAddress;
174 const uint64_t raw = s.Misc.VirtualSize ? static_cast<uint64_t>(s.Misc.VirtualSize)
175 : static_cast<uint64_t>(s.SizeOfRawData);
176 if (raw == 0 || va >= image_size) return false;
177 len = raw > image_size - va ? image_size - va : raw;
178 return len > 0;
179 };
145 bool in_code = false; 180 bool in_code = false;
146 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) 181 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
147 if ((sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && target_rva >= sec[i].VirtualAddress && 182 uint64_t va = 0, len = 0;
148 target_rva < sec[i].VirtualAddress + sec[i].Misc.VirtualSize) 183 if (exec_section_span(sec[i], va, len) && target_rva >= va && target_rva < va + len)
149 in_code = true; 184 in_code = true;
185 }
150 if (!in_code) return r.error = "the RVA is not in an executable section", r; 186 if (!in_code) return r.error = "the RVA is not in an executable section", r;
151 uint8_t* target = base + target_rva; 187 uint8_t* target = base + target_rva;
152 uint8_t* thunk = make(target); 188 uint8_t* thunk = make(target);
153 if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r; 189 if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r;
154 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { 190 for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) {
155 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; 191 uint64_t va = 0, len = 0;
156 uint8_t* begin = base + sec[i].VirtualAddress; 192 if (!exec_section_span(sec[i], va, len)) continue;
157 const std::size_t size = sec[i].Misc.VirtualSize; 193 uint8_t* begin = base + va;
194 const std::size_t size = static_cast<std::size_t>(len);
158 DWORD old = 0; 195 DWORD old = 0;
159 if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) return r.error = "VirtualProtect failed", r; 196 if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) {
197 if (r.redirected == 0) VirtualFree(thunk, 0, MEM_RELEASE);
198 return r.error = "VirtualProtect failed", r;
199 }
160 r.redirected += redirect_direct_branches(begin, size, target, thunk); 200 r.redirected += redirect_direct_branches(begin, size, target, thunk);
161 DWORD ignored = 0; 201 DWORD ignored = 0;
162 VirtualProtect(begin, size, old, &ignored); 202 VirtualProtect(begin, size, old, &ignored);
@@ -168,6 +208,7 @@ inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeT
168 208
169// The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`. 209// The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`.
170inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) { 210inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) {
211 if (!fn) return HookResult{false, 0, "hook callback is null"};
171 if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"}; 212 if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"};
172 return redirect_image_calls(base, target_rva, 213 return redirect_image_calls(base, target_rva,
173 [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); }); 214 [&](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
175 216
176// The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument. 217// The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument.
177inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) { 218inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) {
219 if (!fn) return HookResult{false, 0, "hook callback is null"};
178 return redirect_image_calls(base, target_rva, 220 return redirect_image_calls(base, target_rva,
179 [&](uint8_t* target) { return make_result_thunk(target, fn, target); }); 221 [&](uint8_t* target) { return make_result_thunk(target, fn, target); });
180} 222}