Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
Test_NtWriteVirtualMemory.cpp
Go to the documentation of this file.
1// Tests the Hooked_NtWriteVirtualMemory post-call checks, which only run when the write succeeds:
2// - A buffer starting with the "MZ" magic bytes is reported, with whether the target is the
3// current process and whether the destination is executable.
4// - A write overlapping the target's PEB page is reported, with the offset into the PEB. From
5// x64, a WOW64 target's 32-bit PEB counts too.
7#include <winternl.h>
8
9static BYTE* Alloc(DWORD protection) {
10 return (BYTE*)VirtualAlloc(NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, protection);
11}
12
14static BYTE* QueryPeb(HANDLE process, bool wow64 = false) {
15 auto query = NtdllFunction<decltype(&NtQueryInformationProcess)>("NtQueryInformationProcess");
16 if (wow64) {
17 ULONG_PTR peb32 = 0;
18 query(process, ProcessWow64Information, &peb32, sizeof(peb32), NULL);
19 return (BYTE*)peb32;
20 }
21 PROCESS_BASIC_INFORMATION info{};
22 query(process, ProcessBasicInformation, &info, sizeof(info), NULL);
23 return (BYTE*)info.PebBaseAddress;
24}
25
26typedef NTSTATUS(NTAPI* NtReadWriteVirtualMemory_t)(HANDLE ProcessHandle, PVOID BaseAddress,
27 PVOID Buffer, SIZE_T NumberOfBytes, PSIZE_T NumberOfBytesTransferred);
28
33static void RewriteInPlace(HANDLE process, BYTE* address, SIZE_T size) {
34 BYTE value[16];
35 SIZE_T transferred;
36 NtdllFunction<NtReadWriteVirtualMemory_t>("NtReadVirtualMemory")(process, address, value, size, &transferred);
37 NtdllFunction<NtReadWriteVirtualMemory_t>("NtWriteVirtualMemory")(process, address, value, size, &transferred);
38}
39
40// Offsets of PEB fields, which differ by architecture
41#define PEB_BEING_DEBUGGED_OFFSET 0x2
42#ifdef _WIN64
43#define PEB_IMAGE_BASE_OFFSET 0x10
44#define PEB_IMAGE_BASE_OFFSET_TEXT "0x10"
45#else
46#define PEB_IMAGE_BASE_OFFSET 0x8
47#define PEB_IMAGE_BASE_OFFSET_TEXT "0x8"
48#endif
49#define POINTER_SIZE_TEXT (sizeof(void*) == 8 ? "8" : "4")
50
52#define REMOTE_IMAGE_BASE_READ (std::string("NtReadVirtualMemory: ") + POINTER_SIZE_TEXT + \
53 " bytes read from the PEB of the remote process at offset " PEB_IMAGE_BASE_OFFSET_TEXT)
54
57struct MainImage {
58 BYTE* Base;
61};
62
64static MainImage MainImageAt(HANDLE process, BYTE* base) {
65 auto read = NtdllFunction<NtReadWriteVirtualMemory_t>("NtReadVirtualMemory");
66 SIZE_T transferred;
67 IMAGE_DOS_HEADER dos{};
68 read(process, base, &dos, sizeof(dos), &transferred);
69 IMAGE_NT_HEADERS nt{};
70 read(process, base + dos.e_lfanew, &nt, sizeof(nt), &transferred);
71 return { base, base + nt.OptionalHeader.AddressOfEntryPoint,
72 base + dos.e_lfanew + offsetof(IMAGE_NT_HEADERS, OptionalHeader.AddressOfEntryPoint) };
73}
74
77static MainImage RemoteMainImage(HANDLE process) {
78 BYTE* base = NULL;
79 SIZE_T transferred;
80 NtdllFunction<NtReadWriteVirtualMemory_t>("NtReadVirtualMemory")(
81 process, QueryPeb(process) + PEB_IMAGE_BASE_OFFSET, &base, sizeof(base), &transferred);
82 return MainImageAt(process, base);
83}
84
87static void RewriteProtected(HANDLE process, BYTE* address, SIZE_T size, DWORD protection) {
88 DWORD old;
89 VirtualProtectEx(process, address, size, protection, &old);
90 RewriteInPlace(process, address, size);
91 VirtualProtectEx(process, address, size, old, &old);
92}
93
94static const std::vector<HookTestCase> g_Cases = {
95 // PE image writes
96
97 {
98 "PE into current process RW memory (pseudo-handle)",
99 [](HookTestContext& context) {
100 SIZE_T written;
101 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), context.PEImage(), context.PESize, &written);
102 },
103 { "NtWriteVirtualMemory: PE image written to * in the current process, destination not executable" },
104 },
105 {
106 "PE into current process RW memory (real handle to self)",
107 [](HookTestContext& context) {
108 HANDLE self = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
109 SIZE_T written;
110 WriteProcessMemory(self, Alloc(PAGE_READWRITE), context.PEImage(), context.PESize, &written);
111 CloseHandle(self);
112 },
113 { "NtWriteVirtualMemory: PE image written to * in the current process, destination not executable" },
114 },
115 {
116 "PE into current process RWX memory",
117 [](HookTestContext& context) {
118 SIZE_T written;
119 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_EXECUTE_READWRITE), context.PEImage(), context.PESize, &written);
120 },
121 {
122 "NtAllocateVirtualMemory: 4096 executable bytes allocated at * in the current process (protection 0x40)",
123 "NtWriteVirtualMemory: PE image written to * in the current process, destination executable",
124 },
125 },
126 {
127 // WriteProcessMemory makes the RX page writable for the write and restores it afterwards;
128 // both protection changes go through NtProtectVirtualMemory and are reported by that hook
129 "PE into current process RX memory",
130 [](HookTestContext& context) {
131 SIZE_T written;
132 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_EXECUTE_READ), context.PEImage(), context.PESize, &written);
133 },
134 {
135 "NtAllocateVirtualMemory: 4096 executable bytes allocated at * in the current process (protection 0x20)",
136 "NtProtectVirtualMemory: PE image at * in the current process made executable (0x20 -> *)",
137 "NtWriteVirtualMemory: PE image written to * in the current process, destination executable",
138 "NtProtectVirtualMemory: PE image at * in the current process made executable (0x40 -> *)",
139 },
140 },
141 {
142 "PE into remote process RW memory",
143 [](HookTestContext& context) {
144 HANDLE remote = context.RemoteProcess();
145 BYTE* destination = (BYTE*)VirtualAllocEx(remote, NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
146 SIZE_T written;
147 WriteProcessMemory(remote, destination, context.PEImage(), context.PESize, &written);
148 },
149 { "NtWriteVirtualMemory: PE image written to * in the remote process, destination not executable" },
150 },
151 {
152 "PE into remote process RWX memory",
153 [](HookTestContext& context) {
154 HANDLE remote = context.RemoteProcess();
155 BYTE* destination = (BYTE*)VirtualAllocEx(remote, NULL, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
156 SIZE_T written;
157 WriteProcessMemory(remote, destination, context.PEImage(), context.PESize, &written);
158 },
159 {
160 "NtAllocateVirtualMemory: 4096 executable bytes allocated at * in the remote process (protection 0x40)",
161 "NtWriteVirtualMemory: PE image written to * in the remote process, destination executable",
162 },
163 },
164 {
165 // Only the magic bytes are checked, so a DOS header with no PE signature still counts
166 "MZ without a PE signature is reported",
167 [](HookTestContext&) {
168 BYTE buffer[0x1000] = { 'M', 'Z' };
169 SIZE_T written;
170 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), buffer, sizeof(buffer), &written);
171 },
172 { "NtWriteVirtualMemory: PE image written to * in the current process, destination not executable" },
173 },
174 {
175 "Just the two MZ bytes are reported",
176 [](HookTestContext& context) {
177 SIZE_T written;
178 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), context.PEImage(), 2, &written);
179 },
180 { "NtWriteVirtualMemory: PE image written to * in the current process, destination not executable" },
181 },
182 {
183 "A single M byte is not reported",
184 [](HookTestContext& context) {
185 SIZE_T written;
186 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), context.PEImage(), 1, &written);
187 },
188 {},
189 },
190 {
191 "ZM (byte-swapped magic) is not reported",
192 [](HookTestContext&) {
193 BYTE buffer[0x1000] = { 'Z', 'M' };
194 SIZE_T written;
195 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), buffer, sizeof(buffer), &written);
196 },
197 {},
198 },
199 {
200 "Non-PE data is not reported",
201 [](HookTestContext&) {
202 BYTE buffer[0x1000];
203 memset(buffer, 0x90, sizeof(buffer));
204 SIZE_T written;
205 WriteProcessMemory(GetCurrentProcess(), Alloc(PAGE_READWRITE), buffer, sizeof(buffer), &written);
206 },
207 {},
208 },
209 {
210 "Failed write of a PE is not reported",
211 [](HookTestContext& context) {
212 // Reserved but not committed, so the write fails
213 BYTE* reserved = (BYTE*)VirtualAlloc(NULL, 0x1000, MEM_RESERVE, PAGE_READWRITE);
214 SIZE_T written;
215 WriteProcessMemory(GetCurrentProcess(), reserved, context.PEImage(), context.PESize, &written);
216 },
217 {},
218 },
219
220 // PEB writes
221
222 {
223 "Write to current process PEB (pseudo-handle)",
224 [](HookTestContext&) {
225 BYTE* peb = (BYTE*)NtCurrentTeb()->ProcessEnvironmentBlock;
226 RewriteInPlace(GetCurrentProcess(), peb + PEB_BEING_DEBUGGED_OFFSET, 1);
227 },
228 {
229 "NtReadVirtualMemory: 1 bytes read from the PEB of the current process at offset 0x2",
230 "NtWriteVirtualMemory: 1 bytes written to the PEB of the current process at offset 0x2",
231 },
232 },
233 {
234 "Write to current process PEB (real handle to self)",
235 [](HookTestContext&) {
236 HANDLE self = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
237 RewriteInPlace(self, QueryPeb(self) + PEB_BEING_DEBUGGED_OFFSET, 1);
238 CloseHandle(self);
239 },
240 {
241 "NtReadVirtualMemory: 1 bytes read from the PEB of the current process at offset 0x2",
242 "NtWriteVirtualMemory: 1 bytes written to the PEB of the current process at offset 0x2",
243 },
244 },
245 {
246 // The PEB is checked as a whole page, so the last byte of the page still counts
247 "Write to the last byte of the PEB page",
248 [](HookTestContext&) {
249 BYTE* peb = (BYTE*)NtCurrentTeb()->ProcessEnvironmentBlock;
250 RewriteInPlace(GetCurrentProcess(), peb + 0xFFF, 1);
251 },
252 {
253 "NtReadVirtualMemory: 1 bytes read from the PEB of the current process at offset 0xfff",
254 "NtWriteVirtualMemory: 1 bytes written to the PEB of the current process at offset 0xfff",
255 },
256 },
257 {
258 // What process hollowing does after mapping its own image into the target
259 "Write to remote process PEB ImageBaseAddress",
260 [](HookTestContext& context) {
261 HANDLE remote = context.RemoteProcess();
262 RewriteInPlace(remote, QueryPeb(remote) + PEB_IMAGE_BASE_OFFSET, sizeof(void*));
263 },
264 {
265 std::string("NtReadVirtualMemory: ") + POINTER_SIZE_TEXT +
266 " bytes read from the PEB of the remote process at offset " PEB_IMAGE_BASE_OFFSET_TEXT,
267 std::string("NtWriteVirtualMemory: ") + POINTER_SIZE_TEXT +
268 " bytes written to the PEB of the remote process at offset " PEB_IMAGE_BASE_OFFSET_TEXT,
269 },
270 },
271#ifdef _WIN64
272 {
273 "Write to remote WOW64 process 32-bit PEB",
274 [](HookTestContext& context) {
275 HANDLE remote = context.Wow64RemoteProcess();
276 RewriteInPlace(remote, QueryPeb(remote, true) + PEB_BEING_DEBUGGED_OFFSET, 1);
277 },
278 {
279 "NtReadVirtualMemory: 1 bytes read from the PEB of the remote process at offset 0x2",
280 "NtWriteVirtualMemory: 1 bytes written to the PEB of the remote process at offset 0x2",
281 },
282 },
283#endif
284 {
285 "Write next to the PEB is not reported",
286 [](HookTestContext&) {
287 // The TEB is a separate allocation, so a write to it is outside the PEB's page
288 BYTE* teb = (BYTE*)NtCurrentTeb();
289 RewriteInPlace(GetCurrentProcess(), teb + 0x100, 1);
290 },
291 {},
292 },
293 {
294 // The handle can read but not write, so only the read hook reports
295 "Failed write to the PEB is not reported",
296 [](HookTestContext&) {
297 HANDLE self = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId());
298 RewriteInPlace(self, QueryPeb(self) + PEB_BEING_DEBUGGED_OFFSET, 1);
299 CloseHandle(self);
300 },
301 { "NtReadVirtualMemory: 1 bytes read from the PEB of the current process at offset 0x2" },
302 },
303
304 // Main image entry point writes. The code pages are made RWX for the write, which the protect
305 // hook reports; the header page is made RW, which it does not.
306
307 {
308 // Entry point patching: shellcode written over a suspended process's entry point
309 "Write to remote process entry point code",
310 [](HookTestContext& context) {
311 HANDLE remote = context.RemoteProcess();
312 RewriteProtected(remote, RemoteMainImage(remote).EntryPoint, 1, PAGE_EXECUTE_READWRITE);
313 },
314 {
316 "NtProtectVirtualMemory: PE image at * in the remote process made executable (0x20 -> 0x40)",
317 "NtWriteVirtualMemory: 1 bytes written over the main image's entry point code in the remote process, entry point *",
318 "NtProtectVirtualMemory: PE image at * in the remote process made executable (* -> 0x20)",
319 },
320 },
321 {
322 "Write to remote process AddressOfEntryPoint field",
323 [](HookTestContext& context) {
324 HANDLE remote = context.RemoteProcess();
325 RewriteProtected(remote, RemoteMainImage(remote).EntryPointField, sizeof(DWORD), PAGE_READWRITE);
326 },
327 {
329 "NtWriteVirtualMemory: 4 bytes written over the main image's AddressOfEntryPoint field in the remote process, entry point *",
330 },
331 },
332 {
333 "Write to current process entry point code",
334 [](HookTestContext&) {
335 MainImage image = MainImageAt(GetCurrentProcess(), (BYTE*)GetModuleHandle(NULL));
336 RewriteProtected(GetCurrentProcess(), image.EntryPoint, 1, PAGE_EXECUTE_READWRITE);
337 },
338 {
339 "NtProtectVirtualMemory: PE image at * in the current process made executable (0x20 -> 0x40)",
340 "NtWriteVirtualMemory: 1 bytes written over the main image's entry point code in the current process, entry point *",
341 "NtProtectVirtualMemory: PE image at * in the current process made executable (* -> 0x20)",
342 },
343 },
344 {
345 "Write elsewhere in the remote main image's headers is not reported",
346 [](HookTestContext& context) {
347 HANDLE remote = context.RemoteProcess();
348 // e_cblp, a field of the DOS header nothing reads
349 RewriteProtected(remote, RemoteMainImage(remote).Base + 2, 1, PAGE_READWRITE);
350 },
352 },
353};
354
355int main(int argc, char** argv) {
356 return RunHookTests(argc, argv, "NtWriteVirtualMemory", g_Cases);
357}
#define POINTER_SIZE_TEXT
#define PEB_IMAGE_BASE_OFFSET
#define PEB_IMAGE_BASE_OFFSET_TEXT
NTSTATUS(NTAPI * NtReadWriteVirtualMemory_t)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytes, PSIZE_T NumberOfBytesTransferred)
#define PEB_BEING_DEBUGGED_OFFSET
#define REMOTE_IMAGE_BASE_READ
The read hook's report of the PEB.ImageBaseAddress read in RemoteMainImage.
int main()
Loads the hook DLL for this architecture from bin/<config>, one directory above the tests folder this...
Resources shared by the cases of one test run, created in the child process. The remote processes are...
T NtdllFunction(const char *name)
Looks up an ntdll export. Calls through the result go through the hooks, because the hooks patch the ...
int RunHookTests(int argc, char **argv, const char *apiName, const std::vector< HookTestCase > &cases)
Runs the cases and prints a PASS/FAIL line for each. Call from main.
A process's main image: its base, entry point and the address of the AddressOfEntryPoint header field...