Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
hook_events.cpp
Go to the documentation of this file.
1#include "hook_events.h"
2#include "error_message.h"
3#include "pano_log.h"
4#include "detector_stream.h"
5#include "process_images.h"
6#include "utils.h"
7#include <evntrace.h>
8#include <evntcons.h>
9#include <tdh.h>
10#include <nlohmann/json.hpp>
11#include <chrono>
12#include <condition_variable>
13#include <cstdio>
14#include <iostream>
15#include <mutex>
16#include <string>
17#include <thread>
18#include <vector>
19
20#pragma comment(lib, "advapi32.lib")
21#pragma comment(lib, "tdh.lib")
22
23// The real-time session the service owns. ETW sessions outlive the process that started them,
24// so a session with this name left by a service that was killed is stopped and replaced
25#define HOOK_SESSION_NAME L"Panoptes Hook Trace"
26
27// The hook DLL's TraceLogging provider, "Panoptes.Hook". Must match the GUID in
28// src/hook/src/hook_trace.cpp
29// {D9AA2FDD-2853-4A97-A42F-E77E42921704}
30static const GUID HookProviderGuid =
31 { 0xd9aa2fdd, 0x2853, 0x4a97, { 0xa4, 0x2f, 0xe7, 0x7e, 0x42, 0x92, 0x17, 0x04 } };
32
33// Matches HOOK_KEYWORD_DETECTION in src/hook/include/hook_trace.hpp
34#define HOOK_KEYWORD_DETECTION 0x1
35
36// How often the session's loss counters are checked
37#define HOOK_LOSS_CHECK_MS 5000
38
39static TRACEHANDLE g_SessionHandle = 0;
40static TRACEHANDLE g_ConsumerHandle = INVALID_PROCESSTRACE_HANDLE;
41static std::thread g_ConsumerThread;
42
43// Loss monitoring. ETW counts what the session lost rather than telling the consumer, so a
44// thread reads the counters every HOOK_LOSS_CHECK_MS and logs any increase
45static std::thread g_LossThread;
46static std::mutex g_LossLock;
47static std::condition_variable g_LossWake;
48static bool g_LossStopping = false;
49static ULONG g_ReportedEventsLost = 0;
50static ULONG g_ReportedBuffersLost = 0;
51
52// time is when the event happened, which the detector gets as a FILETIME. RecordEvent appends
53// the event's Seq
54static void LogHookEvent(nlohmann::ordered_json &event, const FILETIME &time)
55{
56 [[maybe_unused]] std::string line = RecordEvent(event, time);
57#ifdef _DEBUG
58 std::cout << line << std::endl;
59#endif
60}
61
62#pragma region Event Decoding
63
64static std::string FormatHex(UINT64 value)
65{
66 char text[19];
67 snprintf(text, sizeof(text), "0x%llx", value);
68 return text;
69}
70
71// Reads an unsigned integer of 1, 2, 4 or 8 bytes
72static UINT64 ReadUnsigned(const BYTE *data, ULONG size)
73{
74 switch (size)
75 {
76 case 1: return *(const UINT8 *)data;
77 case 2: return *(const UINT16 *)data;
78 case 4: return *(const UINT32 *)data;
79 case 8: return *(const UINT64 *)data;
80 default: return 0;
81 }
82}
83
84static INT64 ReadSigned(const BYTE *data, ULONG size)
85{
86 switch (size)
87 {
88 case 1: return *(const INT8 *)data;
89 case 2: return *(const INT16 *)data;
90 case 4: return *(const INT32 *)data;
91 case 8: return *(const INT64 *)data;
92 default: return 0;
93 }
94}
95
96// Converts one decoded property to JSON. Pointers and hex-formatted integers become "0x..."
97// strings. Pointer properties are 4 or 8 bytes depending on whether the hook DLL that wrote
98// the event was x86 or x64; TDH reports the size actually written
99static nlohmann::ordered_json PropertyToJson(const EVENT_PROPERTY_INFO &property, const BYTE *data, ULONG size)
100{
101 USHORT inType = property.nonStructType.InType;
102 USHORT outType = property.nonStructType.OutType;
103
104 switch (inType)
105 {
106 case TDH_INTYPE_UNICODESTRING:
107 {
108 std::wstring text((const wchar_t *)data, size / sizeof(wchar_t));
109 text.erase(text.find_last_not_of(L'\0') + 1);
110 return ToString(text);
111 }
112 case TDH_INTYPE_ANSISTRING:
113 {
114 std::string text((const char *)data, size);
115 text.erase(text.find_last_not_of('\0') + 1);
116 return text;
117 }
118 case TDH_INTYPE_BOOLEAN:
119 return ReadUnsigned(data, size) != 0;
120 case TDH_INTYPE_POINTER:
121 case TDH_INTYPE_SIZET:
122 case TDH_INTYPE_HEXINT32:
123 case TDH_INTYPE_HEXINT64:
124 return FormatHex(ReadUnsigned(data, size));
125 case TDH_INTYPE_INT8:
126 case TDH_INTYPE_INT16:
127 case TDH_INTYPE_INT32:
128 case TDH_INTYPE_INT64:
129 return ReadSigned(data, size);
130 case TDH_INTYPE_UINT8:
131 case TDH_INTYPE_UINT16:
132 case TDH_INTYPE_UINT32:
133 case TDH_INTYPE_UINT64:
134 if (outType == TDH_OUTTYPE_HEXINT8 || outType == TDH_OUTTYPE_HEXINT16 ||
135 outType == TDH_OUTTYPE_HEXINT32 || outType == TDH_OUTTYPE_HEXINT64)
136 {
137 return FormatHex(ReadUnsigned(data, size));
138 }
139 return ReadUnsigned(data, size);
140 default:
141 {
142 // A type the hook DLL does not write today: keep the raw bytes
143 std::string hex;
144 char byte[3];
145 for (ULONG i = 0; i < size; i++)
146 {
147 snprintf(byte, sizeof(byte), "%02x", data[i]);
148 hex += byte;
149 }
150 return hex;
151 }
152 }
153}
154
155static FILETIME ToFileTime(const LARGE_INTEGER &timestamp)
156{
157 FILETIME fileTime;
158 fileTime.dwLowDateTime = timestamp.LowPart;
159 fileTime.dwHighDateTime = (DWORD)timestamp.HighPart;
160 return fileTime;
161}
162
163// Logs one hook event as a JSON line, in the same log as the driver's events. PID and TID come
164// from the event header, which the kernel fills in, so they identify the process the hook ran
165// in even though the payload is written by code inside that (untrusted) process
166static void WINAPI OnHookEvent(PEVENT_RECORD record)
167{
168 if (!IsEqualGUID(record->EventHeader.ProviderId, HookProviderGuid))
169 {
170 return;
171 }
172
173 ULONG infoSize = 0;
174 if (TdhGetEventInformation(record, 0, NULL, NULL, &infoSize) != ERROR_INSUFFICIENT_BUFFER)
175 {
176 return;
177 }
178 std::vector<BYTE> infoBuffer(infoSize);
179 PTRACE_EVENT_INFO info = (PTRACE_EVENT_INFO)infoBuffer.data();
180 if (TdhGetEventInformation(record, 0, NULL, info, &infoSize) != ERROR_SUCCESS)
181 {
182 return;
183 }
184
185 // For TraceLogging events TaskNameOffset holds the event name
186 ULONG nameOffset = info->EventNameOffset != 0 ? info->EventNameOffset : info->TaskNameOffset;
187 std::string eventName = nameOffset != 0
188 ? ToString((PCWSTR)(infoBuffer.data() + nameOffset))
189 : "HookEvent";
190
191 DWORD processId = record->EventHeader.ProcessId;
192 FILETIME eventTime = ToFileTime(record->EventHeader.TimeStamp);
193
194 nlohmann::ordered_json event;
195 event["Event"] = eventName;
196 event["Source"] = "Hook";
197 event["PID"] = processId;
198 event["TID"] = record->EventHeader.ThreadId;
199 event["Image"] = ResolveProcessImage(processId, eventTime);
200 event["Time"] = FormatSystemTime(eventTime);
201
202 for (ULONG i = 0; i < info->TopLevelPropertyCount; i++)
203 {
204 const EVENT_PROPERTY_INFO &property = info->EventPropertyInfoArray[i];
205 PCWSTR propertyName = (PCWSTR)(infoBuffer.data() + property.NameOffset);
206
207 // The hook events only have scalar fields; structs and arrays are not decoded
208 if ((property.Flags & (PropertyStruct | PropertyParamCount)) || property.count > 1)
209 {
210 continue;
211 }
212
213 PROPERTY_DATA_DESCRIPTOR descriptor{};
214 descriptor.PropertyName = (ULONGLONG)propertyName;
215 descriptor.ArrayIndex = ULONG_MAX;
216
217 ULONG size = 0;
218 if (TdhGetPropertySize(record, 0, NULL, 1, &descriptor, &size) != ERROR_SUCCESS || size == 0)
219 {
220 continue;
221 }
222 std::vector<BYTE> data(size);
223 if (TdhGetProperty(record, 0, NULL, 1, &descriptor, size, data.data()) != ERROR_SUCCESS)
224 {
225 continue;
226 }
227
228 // Event, Source, PID, TID, Image and Time come from the event header and the service. The
229 // payload is written by code in the hooked (untrusted) process, so a payload field with one
230 // of those names is kept under a "Payload" prefix instead of replacing it
231 std::string name = ToString(propertyName);
232 if (event.contains(name))
233 {
234 name = "Payload" + name;
235 }
236 event[name] = PropertyToJson(property, data.data(), size);
237 }
238
239 // Name the process acted on when it is not the one the hook ran in. TargetProcessId is 0 when
240 // the hook could not find out whose handle it was, even after re-opening it for query access.
241 // An attack on a target it hides is itself suspicious, so this is stated rather than left as
242 // a 0 rules might take for a real ID
243 if (event.value("Remote", false) && event.contains("TargetProcessId") && event["TargetProcessId"].is_number())
244 {
245 DWORD targetProcessId = event["TargetProcessId"].get<DWORD>();
246 event["TargetResolved"] = targetProcessId != 0;
247 event["TargetImage"] = targetProcessId != 0 ? ResolveProcessImage(targetProcessId, eventTime) : "";
248 }
249
250 LogHookEvent(event, eventTime);
251}
252
253#pragma endregion
254
255#pragma region Session
256
257// EVENT_TRACE_PROPERTIES followed by room for the session name, which StartTrace and
258// ControlTrace copy in after the structure
260{
261 EVENT_TRACE_PROPERTIES Properties;
262 wchar_t SessionName[ARRAYSIZE(HOOK_SESSION_NAME)];
263
265 {
266 ZeroMemory(this, sizeof(*this));
267 Properties.Wnode.BufferSize = sizeof(*this);
268 Properties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;
269 Properties.Wnode.ClientContext = 1; // QPC timestamps, converted to FILETIME for consumers
270 Properties.LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
271 Properties.BufferSize = 64; // KB
272 Properties.FlushTimer = 1; // deliver buffered events at least once a second
273 Properties.LoggerNameOffset = offsetof(HookSessionProperties, SessionName);
274 }
275};
276
277// Logs what the session has lost since the last report, from counters filled in by a query or
278// stop. The two counters mean different things:
279// - EventsLost: events a hooked process wrote while every session buffer was full. Reported
280// as Reason "QueueFull" with the number of events
281// - RealTimeBuffersLost: full buffers ETW discarded because the service did not take them in
282// time. How many events each held is not known, so it is reported as Reason "BuffersLost"
283// with the number of buffers
284static void ReportLoss(const EVENT_TRACE_PROPERTIES &properties)
285{
286 if (properties.EventsLost > g_ReportedEventsLost)
287 {
288 nlohmann::ordered_json event;
289 event["Event"] = "EventsDropped";
290 event["Source"] = "Hook";
291 event["Reason"] = "QueueFull";
292 event["Count"] = properties.EventsLost - g_ReportedEventsLost;
293 LogHookEvent(event, CurrentFileTime());
294 g_ReportedEventsLost = properties.EventsLost;
295 }
296 if (properties.RealTimeBuffersLost > g_ReportedBuffersLost)
297 {
298 nlohmann::ordered_json event;
299 event["Event"] = "EventsDropped";
300 event["Source"] = "Hook";
301 event["Reason"] = "BuffersLost";
302 event["Buffers"] = properties.RealTimeBuffersLost - g_ReportedBuffersLost;
303 LogHookEvent(event, CurrentFileTime());
304 g_ReportedBuffersLost = properties.RealTimeBuffersLost;
305 }
306}
307
308static void LossMonitorThread()
309{
310 std::unique_lock<std::mutex> lock(g_LossLock);
311 while (!g_LossWake.wait_for(lock, std::chrono::milliseconds(HOOK_LOSS_CHECK_MS), [] { return g_LossStopping; }))
312 {
313 HookSessionProperties properties;
314 if (ControlTraceW(g_SessionHandle, NULL, &properties.Properties, EVENT_TRACE_CONTROL_QUERY) == ERROR_SUCCESS)
315 {
316 ReportLoss(properties.Properties);
317 }
318 }
319}
320
321static void ConsumerThread()
322{
323 ULONG status = ProcessTrace(&g_ConsumerHandle, 1, NULL, NULL);
324 if (status != ERROR_SUCCESS && status != ERROR_CANCELLED)
325 {
326 std::cerr << "Hook event trace stopped. Error code: " << status << std::endl;
327 }
328}
329
331{
332 HookSessionProperties properties;
333 ULONG status = StartTraceW(&g_SessionHandle, HOOK_SESSION_NAME, &properties.Properties);
334 if (status == ERROR_ALREADY_EXISTS)
335 {
336 // Left behind by a previous run of the service
338 ControlTraceW(0, HOOK_SESSION_NAME, &stale.Properties, EVENT_TRACE_CONTROL_STOP);
339
340 properties = HookSessionProperties();
341 status = StartTraceW(&g_SessionHandle, HOOK_SESSION_NAME, &properties.Properties);
342 }
343 if (status != ERROR_SUCCESS)
344 {
345 std::cerr << "Failed to start the hook event trace session. Error code: " << status << std::endl;
346 g_SessionHandle = 0;
347 return (status == ERROR_ACCESS_DENIED) ? NOT_ADMIN : WINDOWS_ERR;
348 }
349
350 status = EnableTraceEx2(g_SessionHandle, &HookProviderGuid, EVENT_CONTROL_CODE_ENABLE_PROVIDER,
351 TRACE_LEVEL_WARNING, HOOK_KEYWORD_DETECTION, 0, 0, NULL);
352 if (status != ERROR_SUCCESS)
353 {
354 std::cerr << "Failed to enable the hook event provider. Error code: " << status << std::endl;
356 return WINDOWS_ERR;
357 }
358
359 EVENT_TRACE_LOGFILEW logFile{};
360 logFile.LoggerName = (LPWSTR)HOOK_SESSION_NAME;
361 logFile.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD;
362 logFile.EventRecordCallback = OnHookEvent;
363
364 g_ConsumerHandle = OpenTraceW(&logFile);
365 if (g_ConsumerHandle == INVALID_PROCESSTRACE_HANDLE)
366 {
367 std::cerr << "Failed to open the hook event trace. Error code: " << GetLastError() << std::endl;
369 return WINDOWS_ERR;
370 }
371
372 g_ConsumerThread = std::thread(ConsumerThread);
373
374 g_ReportedEventsLost = 0;
375 g_ReportedBuffersLost = 0;
376 g_LossStopping = false;
377 g_LossThread = std::thread(LossMonitorThread);
378 return PANO_SUCCESS;
379}
380
382{
383 // The monitor goes first so it never queries a session that has been stopped
384 if (g_LossThread.joinable())
385 {
386 {
387 std::lock_guard<std::mutex> lock(g_LossLock);
388 g_LossStopping = true;
389 }
390 g_LossWake.notify_all();
391 g_LossThread.join();
392 }
393
394 // Stopping the session flushes its buffers to the consumer, after which ProcessTrace
395 // returns. The stop also returns the session's final counters, so losses since the last
396 // check are still reported
397 if (g_SessionHandle != 0)
398 {
399 HookSessionProperties properties;
400 if (ControlTraceW(g_SessionHandle, NULL, &properties.Properties, EVENT_TRACE_CONTROL_STOP) == ERROR_SUCCESS)
401 {
402 ReportLoss(properties.Properties);
403 }
404 g_SessionHandle = 0;
405 }
406
407 if (g_ConsumerThread.joinable())
408 {
409 g_ConsumerThread.join();
410 }
411
412 if (g_ConsumerHandle != INVALID_PROCESSTRACE_HANDLE)
413 {
414 CloseTrace(g_ConsumerHandle);
415 g_ConsumerHandle = INVALID_PROCESSTRACE_HANDLE;
416 }
417}
418
419#pragma endregion
#define PANO_SUCCESS
#define NOT_ADMIN
#define WINDOWS_ERR
std::string RecordEvent(nlohmann::ordered_json &event, const FILETIME &time)
Gives event the next sequence number (appended as "Seq"), writes it to pano.log and queues it for eve...
FILETIME CurrentFileTime()
The current time as a FILETIME, for events that carry no timestamp of their own.
#define HOOK_LOSS_CHECK_MS
#define HOOK_SESSION_NAME
void StopHookEvents()
Stops the ETW session and waits for the consumer thread to deliver what it buffered.
ERRORCODE StartHookEvents()
Starts a real-time ETW session for the hook DLL's "Panoptes.Hook" TraceLogging provider and a thread ...
#define HOOK_KEYWORD_DETECTION
std::string ResolveProcessImage(DWORD processId, const FILETIME &time)
LookupProcessImage, falling back to asking Windows (QueryFullProcessImageName) for processes the serv...
#define ERRORCODE
EVENT_TRACE_PROPERTIES Properties
wchar_t SessionName[ARRAYSIZE(HOOK_SESSION_NAME)]
std::string FormatSystemTime(const FILETIME &ft)
The log's Time format: "2026/11/15 21:05:48.123", in the FILETIME's zone (UTC).
Definition utils.cpp:109
std::string ToString(const std::wstring &wstr)
Definition utils.cpp:51