Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
hook_test_harness.hpp
Go to the documentation of this file.
1#pragma once
2// Shared harness for the hook detection tests. Each test executable lists its cases and calls
3// RunHookTests. The executable relaunches itself as a debuggee: the child loads the hook DLL and
4// runs each case, and the parent, acting as the child's debugger, captures the "[Panoptes]"
5// OutputDebugString messages the hooks emit and checks each case produced exactly the expected
6// messages. The hooks only emit these messages in Debug builds, so in other configurations the
7// tests report SKIPPED.
8#include <Windows.h>
9#include <cstdio>
10#include <cstring>
11#include <string>
12#include <vector>
13
14#ifdef _WIN64
15#define HOOK_ARCH "x64"
16#else
17#define HOOK_ARCH "x86"
18#endif
19
20#define HOOK_DLL_NAME "PanoptesDLL" HOOK_ARCH ".dll"
21
24template <typename T>
25inline T NtdllFunction(const char* name) {
26 return (T)GetProcAddress(GetModuleHandleA("ntdll.dll"), name);
27}
28
30inline PROCESS_INFORMATION StartSuspended(const std::string& commandLine) {
31 std::string mutableLine = commandLine;
32 STARTUPINFOA si{ sizeof(si) };
33 PROCESS_INFORMATION pi{};
34 if (!CreateProcessA(NULL, &mutableLine[0], NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW,
35 NULL, NULL, &si, &pi)) {
36 fprintf(stderr, " failed to start %s (error %lu)\n", commandLine.c_str(), GetLastError());
37 pi = {};
38 }
39 return pi;
40}
41
47public:
49 Stop(m_remote);
50 Stop(m_wow64Remote);
51 }
52
54 void Start() {
55 m_remote = StartSuspended("cmd.exe /c exit");
56#ifdef _WIN64
57 char wow64Dir[MAX_PATH];
58 if (GetSystemWow64DirectoryA(wow64Dir, MAX_PATH) != 0) {
59 m_wow64Remote = StartSuspended(std::string("\"") + wow64Dir + "\\cmd.exe\" /c exit");
60 }
61#endif
62 }
63
65 const BYTE* PEImage() const { return (const BYTE*)GetModuleHandleA(NULL); }
66
68 static constexpr SIZE_T PESize = 0x1000;
69
71 HANDLE RemoteProcess() const { return m_remote.hProcess; }
72
74 HANDLE RemoteThread() const { return m_remote.hThread; }
75
78 HANDLE Wow64RemoteProcess() const { return m_wow64Remote.hProcess; }
79
80private:
81 static void Stop(PROCESS_INFORMATION& process) {
82 if (process.hProcess != NULL) {
83 TerminateProcess(process.hProcess, 0);
84 CloseHandle(process.hThread);
85 CloseHandle(process.hProcess);
86 process = {};
87 }
88 }
89
90 PROCESS_INFORMATION m_remote{};
91 PROCESS_INFORMATION m_wow64Remote{};
92};
93
98 const char* Name;
99 void (*Run)(HookTestContext& context);
100 std::vector<std::string> Expected;
101};
102
104
105constexpr const char* kCaseMarker = "@@PANO_CASE ";
106constexpr const char* kEndMarker = "@@PANO_END";
107constexpr const char* kMessagePrefix = "[Panoptes] ";
108
110inline bool WildcardMatch(const char* pattern, const char* text) {
111 if (*pattern == '\0') {
112 return *text == '\0';
113 }
114 if (*pattern == '*') {
115 for (const char* t = text;; t++) {
116 if (WildcardMatch(pattern + 1, t)) {
117 return true;
118 }
119 if (*t == '\0') {
120 return false;
121 }
122 }
123 }
124 return *pattern == *text && WildcardMatch(pattern + 1, text + 1);
125}
126
129inline int RunChild(const std::vector<HookTestCase>& cases) {
130 char dllPath[MAX_PATH];
131 DWORD length = GetModuleFileNameA(NULL, dllPath, MAX_PATH);
132 char* lastSlash = (length != 0 && length < MAX_PATH) ? strrchr(dllPath, '\\') : NULL;
133 if (lastSlash == NULL) {
134 fprintf(stderr, " unexpected executable path\n");
135 return 1;
136 }
137 *(lastSlash + 1) = '\0';
138 strcat_s(dllPath, MAX_PATH, "..\\" HOOK_DLL_NAME);
139
140 if (LoadLibraryA(dllPath) == NULL) {
141 fprintf(stderr, " failed to load %s (error %lu)\n", dllPath, GetLastError());
142 return 1;
143 }
144
145 // Start the remote targets before the first case marker, so anything process creation itself
146 // triggers is reported as setup rather than attributed to a case
147 HookTestContext context;
148 context.Start();
149
150 for (size_t i = 0; i < cases.size(); i++) {
151 std::string marker = kCaseMarker + std::to_string(i);
152 OutputDebugStringA(marker.c_str());
153 cases[i].Run(context);
154 }
155
156 // What follows (terminating the targets, unloading DLLs and removing the hooks at exit) is
157 // teardown, not part of the last case
158 OutputDebugStringA(kEndMarker);
159 return 0;
160}
161
164inline bool CaptureChild(const char* exePath, size_t caseCount, std::vector<std::vector<std::string>>& messages) {
165 messages.assign(caseCount, {});
166
167 char commandLine[MAX_PATH + 32];
168 sprintf_s(commandLine, "\"%s\" --child", exePath);
169
170 // The child's stdout goes to NUL: Debug builds of Detours trace to it while placing hooks.
171 // The harness reports child errors on stderr, which is passed through.
172 SECURITY_ATTRIBUTES inherit{ sizeof(inherit), NULL, TRUE };
173 HANDLE nul = CreateFileA("NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &inherit, OPEN_EXISTING, 0, NULL);
174 STARTUPINFOA si{ sizeof(si) };
175 si.dwFlags = STARTF_USESTDHANDLES;
176 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
177 si.hStdOutput = nul;
178 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
179
180 PROCESS_INFORMATION pi{};
181 BOOL started = CreateProcessA(NULL, commandLine, NULL, NULL, TRUE, DEBUG_ONLY_THIS_PROCESS, NULL, NULL, &si, &pi);
182 DWORD startError = GetLastError();
183 if (nul != INVALID_HANDLE_VALUE) {
184 CloseHandle(nul);
185 }
186 if (!started) {
187 printf("failed to start the test child (error %lu)\n", startError);
188 return false;
189 }
190
191 bool clean = true;
192 bool ended = false;
193 size_t currentCase = SIZE_MAX;
194 DWORD exitCode = 1;
195 for (;;) {
196 DEBUG_EVENT event;
197 if (!WaitForDebugEvent(&event, INFINITE)) {
198 clean = false;
199 break;
200 }
201
202 DWORD continueStatus = DBG_CONTINUE;
203 switch (event.dwDebugEventCode) {
204 case OUTPUT_DEBUG_STRING_EVENT: {
205 // Only ANSI strings are emitted by the hooks and the harness
206 char text[512] = {};
207 SIZE_T toRead = event.u.DebugString.nDebugStringLength;
208 if (toRead > sizeof(text) - 1) {
209 toRead = sizeof(text) - 1;
210 }
211 SIZE_T bytesRead = 0;
212 ReadProcessMemory(pi.hProcess, event.u.DebugString.lpDebugStringData, text, toRead, &bytesRead);
213 text[bytesRead] = '\0';
214
215 std::string line(text);
216 while (!line.empty() && (line.back() == '\n' || line.back() == '\r' || line.back() == '\0')) {
217 line.pop_back();
218 }
219
220 if (line.rfind(kCaseMarker, 0) == 0) {
221 currentCase = strtoul(line.c_str() + strlen(kCaseMarker), NULL, 10);
222 }
223 else if (line == kEndMarker) {
224 ended = true;
225 currentCase = SIZE_MAX;
226 }
227 else if (line.rfind(kMessagePrefix, 0) == 0) {
228 if (currentCase < caseCount) {
229 messages[currentCase].push_back(line.substr(strlen(kMessagePrefix)));
230 }
231 else if (!ended) {
232 // Emitted during setup (loading the DLL, starting the remote processes).
233 // Teardown messages are not printed: they are the hooks reacting to the DLL
234 // unloading and Detours removing them
235 printf(" [setup] %s\n", line.c_str() + strlen(kMessagePrefix));
236 }
237 }
238 break;
239 }
240 case EXCEPTION_DEBUG_EVENT:
241 if (event.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT) {
242 if (!event.u.Exception.dwFirstChance) {
243 printf("test child crashed with exception 0x%08lx\n", event.u.Exception.ExceptionRecord.ExceptionCode);
244 clean = false;
245 }
246 continueStatus = DBG_EXCEPTION_NOT_HANDLED;
247 }
248 break;
249 case CREATE_PROCESS_DEBUG_EVENT:
250 if (event.u.CreateProcessInfo.hFile != NULL) {
251 CloseHandle(event.u.CreateProcessInfo.hFile);
252 }
253 break;
254 case LOAD_DLL_DEBUG_EVENT:
255 if (event.u.LoadDll.hFile != NULL) {
256 CloseHandle(event.u.LoadDll.hFile);
257 }
258 break;
259 case EXIT_PROCESS_DEBUG_EVENT:
260 exitCode = event.u.ExitProcess.dwExitCode;
261 break;
262 }
263
264 ContinueDebugEvent(event.dwProcessId, event.dwThreadId, continueStatus);
265 if (event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) {
266 break;
267 }
268 }
269
270 CloseHandle(pi.hThread);
271 CloseHandle(pi.hProcess);
272
273 if (exitCode != 0) {
274 printf("test child exited with code %lu\n", exitCode);
275 clean = false;
276 }
277 return clean;
278}
279
280} // namespace hook_test_detail
281
284inline int RunHookTests(int argc, char** argv, const char* apiName, const std::vector<HookTestCase>& cases) {
285 using namespace hook_test_detail;
286
287 if (argc >= 2 && strcmp(argv[1], "--child") == 0) {
288 return RunChild(cases);
289 }
290
291 printf("%s hook tests (%s)\n", apiName, HOOK_ARCH);
292
293#ifndef _DEBUG
294 printf("SKIPPED: the hooks only emit detection messages in Debug builds\n");
295 return 0;
296#else
297 char exePath[MAX_PATH];
298 DWORD length = GetModuleFileNameA(NULL, exePath, MAX_PATH);
299 if (length == 0 || length == MAX_PATH) {
300 printf("failed to get the executable path (error %lu)\n", GetLastError());
301 return 1;
302 }
303
304 std::vector<std::vector<std::string>> messages;
305 bool clean = CaptureChild(exePath, cases.size(), messages);
306
307 int failures = 0;
308 for (size_t i = 0; i < cases.size(); i++) {
309 const HookTestCase& testCase = cases[i];
310 const std::vector<std::string>& actual = messages[i];
311
312 bool passed = actual.size() == testCase.Expected.size();
313 for (size_t m = 0; passed && m < actual.size(); m++) {
314 passed = WildcardMatch(testCase.Expected[m].c_str(), actual[m].c_str());
315 }
316
317 printf(" [%s] %s\n", passed ? "PASS" : "FAIL", testCase.Name);
318 if (!passed) {
319 failures++;
320 for (const std::string& expected : testCase.Expected) {
321 printf(" expected: %s\n", expected.c_str());
322 }
323 if (testCase.Expected.empty()) {
324 printf(" expected: no messages\n");
325 }
326 for (const std::string& line : actual) {
327 printf(" actual: %s\n", line.c_str());
328 }
329 if (actual.empty()) {
330 printf(" actual: no messages\n");
331 }
332 }
333 }
334
335 if (!clean) {
336 failures++;
337 }
338
339 printf("%s\n", failures == 0 ? "PASS" : "FAIL");
340 return failures == 0 ? 0 : 1;
341#endif
342}
#define MAX_PATH
Definition callbacks.h:7
Resources shared by the cases of one test run, created in the child process. The remote processes are...
HANDLE RemoteThread() const
The suspended main thread of RemoteProcess.
void Start()
Starts the remote targets. Called by the harness before the first case.
static constexpr SIZE_T PESize
The number of PEImage() bytes the cases copy, one page.
HANDLE Wow64RemoteProcess() const
A suspended 32-bit cmd.exe, started only by x64 runs: from x64, a WOW64 target has both a 64-bit and ...
const BYTE * PEImage() const
A buffer holding a real PE image: this executable's own mapped headers.
HANDLE RemoteProcess() const
A suspended cmd.exe of the same architecture to use as a remote target.
PROCESS_INFORMATION StartSuspended(const std::string &commandLine)
Starts a suspended process. Returns an empty PROCESS_INFORMATION on failure.
#define HOOK_ARCH
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.
#define HOOK_DLL_NAME
bool WildcardMatch(const char *pattern, const char *text)
Matches text against a pattern where '*' matches any run of characters.
constexpr const char * kEndMarker
int RunChild(const std::vector< HookTestCase > &cases)
Child side: loads the hook DLL from bin/<config>, one directory above the tests folder,...
bool CaptureChild(const char *exePath, size_t caseCount, std::vector< std::vector< std::string > > &messages)
Parent side: runs the child under a debug loop and returns the hook messages it emitted,...
constexpr const char * kCaseMarker
constexpr const char * kMessagePrefix
One test case. Run executes in the child with the hooks placed. Expected lists the "[Panoptes] " mess...
const char * Name
void(* Run)(HookTestContext &context)
std::vector< std::string > Expected