Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
driver_events.cpp
Go to the documentation of this file.
1#include "driver_events.h"
2#include "pano_events.h"
3#include "error_message.h"
4#include "grpc.hpp"
5#include "pano_log.h"
6#include "detector_stream.h"
7#include "process_images.h"
8#include "utils.h"
9#include <nlohmann/json.hpp>
10#include <algorithm>
11#include <atomic>
12#include <chrono>
13#include <condition_variable>
14#include <iostream>
15#include <mutex>
16#include <string>
17#include <thread>
18#include <unordered_map>
19#include <utility>
20#include <vector>
21
22// Number of IOCTL_PANOPTES_GET_EVENT requests kept pending in the driver at once, so
23// events keep flowing while one completion is being processed
24#define PANO_PENDING_EVENT_REQUESTS 4
25
26// Writes are coalesced into one FileModified event per file. The event is logged (and a PE
27// file scanned) once the file goes PANO_WRITE_SETTLE_MS without a write, so files are
28// scanned once complete. Files that never stop being written are still reported every
29// PANO_WRITE_MAX_WINDOW_MS
30#define PANO_WRITE_SETTLE_MS 2000
31#define PANO_WRITE_MAX_WINDOW_MS 30000
32#define PANO_WRITE_POLL_MS 500
33
39
40static HANDLE g_Device = INVALID_HANDLE_VALUE;
41static HANDLE g_CompletionPort = NULL;
43static std::thread g_ReaderThread;
44static std::thread g_ScanThread;
45static std::atomic<bool> g_Stopping = false;
46
47// Writes to one file since its last FileModified event
48typedef struct _PANO_WRITTEN_FILE
49{
50 ULONGLONG FirstWriteTick;
51 ULONGLONG LastWriteTick;
53 UINT64 ProcessId; // the most recent writer
54 FILETIME LastWriteTime; // when ProcessId wrote, to look up its image
55 UINT64 Writes;
56 UINT64 Bytes;
59
60static std::mutex g_WrittenFilesLock;
61static std::unordered_map<std::string, PANO_WRITTEN_FILE> g_WrittenFiles;
62
63// Files the reader thread wants scanned. Checking whether a file is a PE opens and reads it,
64// so WrittenFileScanThread does that rather than the reader, which must keep up with the driver
65static std::mutex g_PendingScansLock;
66static std::vector<std::string> g_PendingScans;
67
68#ifdef _DEBUG
69// Debug builds echo each logged event to the console. Writing to a console is slow, so lines
70// are collected here and printed in batches by ConsoleEchoThread rather than by the thread
71// that logged them. Past PANO_MAX_ECHO_BUFFER bytes, lines are left out of the echo (never
72// the log file) and counted
73#define PANO_MAX_ECHO_BUFFER (4 * 1024 * 1024)
74static std::mutex g_EchoLock;
75static std::condition_variable g_EchoReady;
76static std::string g_EchoBuffer;
77static UINT64 g_EchoSkipped = 0;
78static bool g_EchoStopping = false;
79static std::thread g_EchoThread;
80#endif
81
82// NT device prefixes (e.g. "\Device\HarddiskVolume3") mapped to drive letters ("C:")
83static std::vector<std::pair<std::wstring, std::wstring>> g_DeviceMap;
84
85// Path patterns from the LogExclusions setting. Matching events are not logged, but the
86// files are still scanned
87static std::vector<std::string> g_LogExclusions;
88
89static bool IsLogExcluded(const std::string &path)
90{
91 return Configuration::IsPathInList(g_LogExclusions, path);
92}
93
94#pragma region Path Conversion
95
96static void BuildDeviceMap()
97{
98 g_DeviceMap.clear();
99 WCHAR drive[] = L"A:";
100 WCHAR target[MAX_PATH];
101 for (WCHAR letter = L'A'; letter <= L'Z'; letter++)
102 {
103 drive[0] = letter;
104 if (QueryDosDeviceW(drive, target, MAX_PATH) != 0)
105 {
106 g_DeviceMap.emplace_back(target, drive);
107 }
108 }
109}
110
111// Converts a name reported by the minifilter (an NT path) into a path the rest of the
112// service can open. Returns an empty string when there is no DOS equivalent.
113static std::wstring ToDosPath(const std::wstring &ntPath)
114{
115 for (const auto &[device, drive] : g_DeviceMap)
116 {
117 if (ntPath.size() > device.size() &&
118 ntPath[device.size()] == L'\\' &&
119 _wcsnicmp(ntPath.c_str(), device.c_str(), device.size()) == 0)
120 {
121 return drive + ntPath.substr(device.size());
122 }
123 }
124
125 const std::wstring mupPrefix = L"\\Device\\Mup\\";
126 if (_wcsnicmp(ntPath.c_str(), mupPrefix.c_str(), mupPrefix.size()) == 0)
127 {
128 return L"\\\\" + ntPath.substr(mupPrefix.size());
129 }
130
131 return L"";
132}
133
134// Named pipes and mailslots are shown the way programs open them (\\.\pipe\name), which is
135// also the form LogExclusions patterns use. Other NT paths are returned unchanged. These are
136// not DOS paths: nothing is scanned under them
137static std::wstring ToPipeOrMailslotPath(const std::wstring &ntPath)
138{
139 static const std::pair<std::wstring, std::wstring> prefixes[] = {
140 {L"\\Device\\NamedPipe\\", L"\\\\.\\pipe\\"},
141 {L"\\Device\\Mailslot\\", L"\\\\.\\mailslot\\"},
142 };
143 for (const auto &[device, display] : prefixes)
144 {
145 if (_wcsnicmp(ntPath.c_str(), device.c_str(), device.size()) == 0)
146 {
147 return display + ntPath.substr(device.size());
148 }
149 }
150 return ntPath;
151}
152
153#pragma endregion
154
155#pragma region Event Handling
156
157static const char *EventTypeName(UINT32 type)
158{
159 switch (type)
160 {
162 return "FileCreated";
164 return "FileOpened";
166 return "FileOverwritten";
168 return "FileSuperseded";
170 return "FileWrite";
172 return "NamedPipeCreate";
174 return "NamedPipeOpen";
176 return "MailslotCreate";
178 return "MailslotOpen";
180 return "FileDeleted";
182 return "FileRenamed";
184 return "ProcessCreated";
186 return "ProcessTerminated";
188 return "FileModified";
190 return "FileSecurityChanged";
192 return "FileExtendedAttributesChanged";
194 return "RegistrySetValue";
196 return "RegistrySaveKey";
198 return "RegistrySetKeySecurity";
200 return "RegistryDeleteKey";
202 return "RegistryCreateKey";
204 return "RegistryLoadKey";
206 return "RegistryReplaceKey";
208 return "RegistryRenameKey";
210 return "RegistryQueryValue";
211 default:
212 return nullptr;
213 }
214}
215
216static FILETIME ToFileTime(INT64 timestamp)
217{
218 FILETIME fileTime;
219 fileTime.dwLowDateTime = (DWORD)(timestamp & 0xFFFFFFFF);
220 fileTime.dwHighDateTime = (DWORD)(timestamp >> 32);
221 return fileTime;
222}
223
224// Events are ordered_json so keys are written in insertion order; every event sets "Event"
225// first so each log line starts with its type. time is when the event happened, which the
226// detector gets as a FILETIME. RecordEvent appends the event's Seq
227static void LogEvent(nlohmann::ordered_json &event, const FILETIME &time)
228{
229 [[maybe_unused]] std::string line = RecordEvent(event, time);
230#ifdef _DEBUG
231 line += '\n';
232 {
233 std::lock_guard<std::mutex> lock(g_EchoLock);
234 if (g_EchoBuffer.size() + line.size() <= PANO_MAX_ECHO_BUFFER)
235 {
236 g_EchoBuffer += line;
237 }
238 else
239 {
240 g_EchoSkipped++;
241 }
242 }
243 g_EchoReady.notify_one();
244#endif
245}
246
247#ifdef _DEBUG
248static void ConsoleEchoThread()
249{
250 std::string batch;
251 for (;;)
252 {
253 UINT64 skipped = 0;
254 bool stopping = false;
255 {
256 std::unique_lock<std::mutex> lock(g_EchoLock);
257 g_EchoReady.wait(lock, [] { return !g_EchoBuffer.empty() || g_EchoStopping; });
258 batch.swap(g_EchoBuffer);
259 skipped = g_EchoSkipped;
260 g_EchoSkipped = 0;
261 stopping = g_EchoStopping;
262 }
263
264 if (!batch.empty())
265 {
266 std::cout.write(batch.data(), batch.size());
267 batch.clear();
268 }
269 if (skipped > 0)
270 {
271 std::cout << "[console echo fell behind: " << skipped << " events not shown here; they are in the log file]\n";
272 }
273 std::cout.flush();
274
275 // Everything logged before stopping has been printed
276 if (stopping)
277 {
278 return;
279 }
280 }
281}
282#endif
283
284// True if the file starts with a DOS header that points at a PE signature
285static bool IsPortableExecutable(const std::string &path)
286{
287 HANDLE file = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
288 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
289 if (file == INVALID_HANDLE_VALUE)
290 {
291 return false;
292 }
293
294 bool isPe = false;
295 IMAGE_DOS_HEADER dosHeader;
296 DWORD bytesRead = 0;
297 if (ReadFile(file, &dosHeader, sizeof(dosHeader), &bytesRead, NULL) &&
298 bytesRead == sizeof(dosHeader) &&
299 dosHeader.e_magic == IMAGE_DOS_SIGNATURE &&
300 dosHeader.e_lfanew > 0)
301 {
302 DWORD signature = 0;
303 LARGE_INTEGER offset;
304 offset.QuadPart = dosHeader.e_lfanew;
305 if (SetFilePointerEx(file, offset, NULL, FILE_BEGIN) &&
306 ReadFile(file, &signature, sizeof(signature), &bytesRead, NULL) &&
307 bytesRead == sizeof(signature))
308 {
309 isPe = (signature == IMAGE_NT_SIGNATURE);
310 }
311 }
312
313 CloseHandle(file);
314 return isPe;
315}
316
317// Only PE files are scanned. The containers scan portable executables, and most file
318// activity (databases, journals, caches) is in files that can never be one
319static bool IsScanCandidate(const std::string &path)
320{
321 DWORD attributes = GetFileAttributesA(path.c_str());
322 if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY))
323 {
324 return false;
325 }
326 return IsPortableExecutable(path);
327}
328
329// Scans the file if it is a PE. Opens and reads the file, so only WrittenFileScanThread calls it
330static void QueueFileScan(const std::string &path)
331{
332 if (IsScanCandidate(path))
333 {
334 SelfQueuePeScan(path, "");
335 }
336}
337
338// Hands a file to WrittenFileScanThread to scan. Used by the reader thread
339static void RequestFileScan(const std::string &path)
340{
341 std::lock_guard<std::mutex> lock(g_PendingScansLock);
342 g_PendingScans.push_back(path);
343}
344
345// Names the parts of a security descriptor in a SECURITY_INFORMATION value. Bits without a
346// name are listed in hex
347static nlohmann::json SecurityInformationNames(UINT32 securityInformation)
348{
349 static const std::pair<UINT32, const char *> names[] = {
350 {OWNER_SECURITY_INFORMATION, "Owner"},
351 {GROUP_SECURITY_INFORMATION, "Group"},
352 {DACL_SECURITY_INFORMATION, "Dacl"},
353 {SACL_SECURITY_INFORMATION, "Sacl"},
354 {LABEL_SECURITY_INFORMATION, "Label"},
355 {ATTRIBUTE_SECURITY_INFORMATION, "Attribute"},
356 {SCOPE_SECURITY_INFORMATION, "Scope"},
357 {PROCESS_TRUST_LABEL_SECURITY_INFORMATION, "ProcessTrustLabel"},
358 {BACKUP_SECURITY_INFORMATION, "Backup"},
359 {PROTECTED_DACL_SECURITY_INFORMATION, "ProtectedDacl"},
360 {PROTECTED_SACL_SECURITY_INFORMATION, "ProtectedSacl"},
361 {UNPROTECTED_DACL_SECURITY_INFORMATION, "UnprotectedDacl"},
362 {UNPROTECTED_SACL_SECURITY_INFORMATION, "UnprotectedSacl"},
363 };
364
365 nlohmann::json result = nlohmann::json::array();
366 UINT32 remaining = securityInformation;
367 for (const auto &[bit, name] : names)
368 {
369 if (securityInformation & bit)
370 {
371 result.push_back(name);
372 remaining &= ~bit;
373 }
374 }
375 if (remaining != 0)
376 {
377 char hex[16];
378 sprintf_s(hex, "0x%X", remaining);
379 result.push_back(hex);
380 }
381 return result;
382}
383
384// One event per handle that wrote to a file, sent by the driver when the handle is closed or,
385// with PANO_FLAG_HANDLE_STILL_OPEN, while it keeps writing. Logged as FileModified like the
386// events WrittenFileScanThread builds from an older driver's individual writes
387static void HandleFileModifiedEvent(const PANO_EVENT_HEADER *header, const PANO_FILE_MODIFIED_EVENT_DATA *data)
388{
389 if (data->ProcessId == GetCurrentProcessId())
390 {
391 return;
392 }
393
394 std::wstring ntPath(data->FileName, data->NameLength);
395 std::wstring dosPath = ToDosPath(ntPath);
396 std::string path = ToString(dosPath.empty() ? ToPipeOrMailslotPath(ntPath) : dosPath);
397 bool stillOpen = (data->Flags & PANO_FLAG_HANDLE_STILL_OPEN) != 0;
398 // The header's timestamp is when the driver reported the writes: when the handle closed, or
399 // when a handle still open was reported. The writes began at FirstWriteTime
400 FILETIME reportTime = ToFileTime(header->Timestamp);
401 FILETIME firstWriteTime = ToFileTime(data->FirstWriteTime);
402
403 nlohmann::ordered_json event;
404 event["Event"] = EventTypeName(header->Type);
405 event["PID"] = data->ProcessId;
406 event["Image"] = ResolveProcessImage((DWORD)data->ProcessId, firstWriteTime);
407 event["Path"] = path;
408 event["Writes"] = data->Writes;
409 event["Bytes"] = data->Bytes;
410 event["Time"] = FormatSystemTime(reportTime);
411 event["FirstWriteTime"] = FormatSystemTime(firstWriteTime);
412 if (stillOpen)
413 {
414 event["StillOpen"] = true;
415 }
417 {
418 event["NameTruncated"] = true;
419 }
420 if (!IsLogExcluded(path))
421 {
422 LogEvent(event, reportTime);
423 }
424
425 // A file still being written is not complete yet; it is scanned when its handle closes
426 if (!stillOpen && !dosPath.empty())
427 {
428 RequestFileScan(path);
429 }
430}
431
432static void HandleFileEvent(const PANO_EVENT_HEADER *header, const PANO_FILE_EVENT_DATA *data)
433{
434 // The service's own I/O (database, logs, hashing) would otherwise feed back into itself
435 if (data->ProcessId == GetCurrentProcessId())
436 {
437 return;
438 }
439
440 // The driver no longer reports opens; this only matters with an older driver
441 if (header->Type == PANO_EVENT_FILE_OPENED)
442 {
443 return;
444 }
445
446 std::wstring ntPath(data->FileName, data->NameLength);
447 std::wstring dosPath = ToDosPath(ntPath);
448 std::string path = ToString(dosPath.empty() ? ToPipeOrMailslotPath(ntPath) : dosPath);
449
450 FILETIME timestamp = ToFileTime(header->Timestamp);
451
452 // Writes arrive in bursts; they are coalesced and logged by WrittenFileScanThread
453 if (header->Type == PANO_EVENT_FILE_WRITE)
454 {
455 if (path.empty())
456 {
457 return;
458 }
459
460 ULONGLONG now = GetTickCount64();
461 std::lock_guard<std::mutex> lock(g_WrittenFilesLock);
462 auto [it, inserted] = g_WrittenFiles.try_emplace(path);
463 PANO_WRITTEN_FILE &file = it->second;
464 if (inserted)
465 {
466 file.FirstWriteTick = now;
467 file.FirstWriteTime = timestamp;
468 file.Writes = 0;
469 file.Bytes = 0;
470 file.IsDosPath = !dosPath.empty();
471 }
472 file.LastWriteTick = now;
473 file.ProcessId = data->ProcessId;
474 file.LastWriteTime = timestamp;
475 file.Writes++;
476 file.Bytes += data->Length;
477 return;
478 }
479
480 nlohmann::ordered_json event;
481 event["Event"] = EventTypeName(header->Type);
482 event["PID"] = data->ProcessId;
483 event["TID"] = data->ThreadId;
484 event["Image"] = ResolveProcessImage((DWORD)data->ProcessId, timestamp);
485 event["Path"] = path;
486 event["Time"] = FormatSystemTime(timestamp);
487 if (data->Flags & PANO_FLAG_OPLOCKED)
488 {
489 event["Oplocked"] = true;
490 }
492 {
493 event["NameTruncated"] = true;
494 }
496 {
497 event["DeleteOnClose"] = true;
498 }
500 {
501 // Length holds the SECURITY_INFORMATION flags of the parts that were set
502 event["Changed"] = SecurityInformationNames(data->Length);
503 }
504 else if (header->Type == PANO_EVENT_FILE_EA_CHANGED)
505 {
506 event["Bytes"] = data->Length;
507 }
508 if (!IsLogExcluded(path))
509 {
510 LogEvent(event, timestamp);
511 }
512
513 // Deleted files need no handling: pending writes to them are still logged, and the scan
514 // check skips files that no longer exist (or are pending deletion)
515 switch (header->Type)
516 {
520 if (!dosPath.empty())
521 {
522 RequestFileScan(path);
523 }
524 break;
525 }
526}
527
528static void HandleRenameEvent(const PANO_EVENT_HEADER *header, const PANO_RENAME_EVENT_DATA *data)
529{
530 if (data->ProcessId == GetCurrentProcessId())
531 {
532 return;
533 }
534
535 std::wstring ntSource(data->Names, data->SourceNameLength);
536 std::wstring ntDestination(data->Names + data->SourceNameLength, data->DestinationNameLength);
537 std::wstring dosSource = ToDosPath(ntSource);
538 std::wstring dosDestination = ToDosPath(ntDestination);
539 std::string source = ToString(dosSource.empty() ? ntSource : dosSource);
540 std::string destination = ToString(dosDestination.empty() ? ntDestination : dosDestination);
541
542 nlohmann::ordered_json event;
543 event["Event"] = EventTypeName(header->Type);
544 event["PID"] = data->ProcessId;
545 event["TID"] = data->ThreadId;
546 event["Image"] = ResolveProcessImage((DWORD)data->ProcessId, ToFileTime(header->Timestamp));
547 event["Path"] = source;
548 event["NewPath"] = destination;
549 event["Time"] = FormatSystemTime(ToFileTime(header->Timestamp));
551 {
552 event["ReplaceExisting"] = true;
553 }
555 {
556 event["NameTruncated"] = true;
557 }
558
559 // A file moving into or out of an excluded folder is still worth seeing, so the rename is
560 // only hidden when both names are excluded
561 if (!(IsLogExcluded(source) && IsLogExcluded(destination)))
562 {
563 LogEvent(event, ToFileTime(header->Timestamp));
564 }
565
566 if (dosDestination.empty())
567 {
568 return;
569 }
570
571 // Writes still pending under the old name follow the file, so it is logged and scanned
572 // under its new name once it settles
573 bool hasPendingWrites = false;
574 {
575 std::lock_guard<std::mutex> lock(g_WrittenFilesLock);
576 auto pending = g_WrittenFiles.find(source);
577 if (pending != g_WrittenFiles.end())
578 {
579 PANO_WRITTEN_FILE file = pending->second;
580 g_WrittenFiles.erase(pending);
581 file.IsDosPath = true;
582
583 auto [it, inserted] = g_WrittenFiles.try_emplace(destination, file);
584 if (!inserted)
585 {
586 PANO_WRITTEN_FILE &existing = it->second;
587 if (file.FirstWriteTick < existing.FirstWriteTick)
588 {
589 existing.FirstWriteTick = file.FirstWriteTick;
590 existing.FirstWriteTime = file.FirstWriteTime;
591 }
592 if (file.LastWriteTick > existing.LastWriteTick)
593 {
594 existing.LastWriteTick = file.LastWriteTick;
595 existing.LastWriteTime = file.LastWriteTime;
596 existing.ProcessId = file.ProcessId;
597 }
598 existing.Writes += file.Writes;
599 existing.Bytes += file.Bytes;
600 }
601 hasPendingWrites = true;
602 }
603 }
604
605 // A finished file given a new name (e.g. a download renamed from .tmp to .exe) is scanned now
606 if (!hasPendingWrites)
607 {
608 RequestFileScan(destination);
609 }
610}
611
612// Shows a key's kernel name (\REGISTRY\MACHINE\...) the way tools and rules write it (HKLM\...).
613// Names under other roots are returned unchanged
614static std::wstring ToRegistryDisplayPath(const std::wstring &kernelPath)
615{
616 static const std::pair<std::wstring, std::wstring> roots[] = {
617 {L"\\REGISTRY\\MACHINE", L"HKLM"},
618 {L"\\REGISTRY\\USER", L"HKU"},
619 };
620 for (const auto &[root, display] : roots)
621 {
622 if (_wcsnicmp(kernelPath.c_str(), root.c_str(), root.size()) == 0 &&
623 (kernelPath.size() == root.size() || kernelPath[root.size()] == L'\\'))
624 {
625 return display + kernelPath.substr(root.size());
626 }
627 }
628 return kernelPath;
629}
630
631// Hive files arrive as the caller wrote them: an NT device path, a \??\C:\ path, or a DOS path.
632// Returns the DOS path where there is one
633static std::string ToRegistryFilePath(const std::wstring &path)
634{
635 static const std::wstring dosDevicePrefixes[] = {L"\\??\\", L"\\DosDevices\\"};
636 for (const auto &prefix : dosDevicePrefixes)
637 {
638 if (_wcsnicmp(path.c_str(), prefix.c_str(), prefix.size()) == 0)
639 {
640 return ToString(path.substr(prefix.size()));
641 }
642 }
643
644 std::wstring dosPath = ToDosPath(path);
645 return ToString(dosPath.empty() ? path : dosPath);
646}
647
648static const char *RegistryValueTypeName(UINT32 type)
649{
650 switch (type)
651 {
652 case REG_NONE:
653 return "REG_NONE";
654 case REG_SZ:
655 return "REG_SZ";
656 case REG_EXPAND_SZ:
657 return "REG_EXPAND_SZ";
658 case REG_BINARY:
659 return "REG_BINARY";
660 case REG_DWORD:
661 return "REG_DWORD";
662 case REG_DWORD_BIG_ENDIAN:
663 return "REG_DWORD_BIG_ENDIAN";
664 case REG_LINK:
665 return "REG_LINK";
666 case REG_MULTI_SZ:
667 return "REG_MULTI_SZ";
668 case REG_QWORD:
669 return "REG_QWORD";
670 default:
671 return nullptr;
672 }
673}
674
675// The value's data exactly as written, as hex. String data may hold anything (a payload stored
676// in a REG_SZ decodes to nonsense), so this is always logged alongside the decoded form
677static std::string RegistryValueHex(const BYTE *data, UINT32 length)
678{
679 static const char digits[] = "0123456789ABCDEF";
680 std::string hex;
681 hex.reserve(length * 2);
682 for (UINT32 i = 0; i < length; i++)
683 {
684 hex += digits[data[i] >> 4];
685 hex += digits[data[i] & 0xF];
686 }
687 return hex;
688}
689
690// The value's data decoded for rules: text for string types, a number for DWORD and QWORD, a
691// list for MULTI_SZ. Null for other types, or data cut short of its type's size
692static nlohmann::json RegistryValueData(UINT32 type, const BYTE *data, UINT32 length)
693{
694 auto readString = [](const BYTE *bytes, UINT32 byteLength) {
695 std::wstring text(byteLength / sizeof(WCHAR), L'\0');
696 memcpy(text.data(), bytes, text.size() * sizeof(WCHAR)); // the data is not aligned
697 return text;
698 };
699
700 switch (type)
701 {
702 case REG_SZ:
703 case REG_EXPAND_SZ:
704 case REG_LINK:
705 {
706 std::wstring text = readString(data, length);
707 text.erase(std::find(text.begin(), text.end(), L'\0'), text.end());
708 return ToString(text);
709 }
710 case REG_MULTI_SZ:
711 {
712 std::wstring text = readString(data, length);
713 nlohmann::json strings = nlohmann::json::array();
714 size_t start = 0;
715 while (start < text.size())
716 {
717 size_t end = text.find(L'\0', start);
718 if (end == start)
719 {
720 break; // the empty string that ends the list
721 }
722 if (end == std::wstring::npos)
723 {
724 end = text.size();
725 }
726 strings.push_back(ToString(text.substr(start, end - start)));
727 start = end + 1;
728 }
729 return strings;
730 }
731 case REG_DWORD:
732 if (length >= sizeof(UINT32))
733 {
734 UINT32 value;
735 memcpy(&value, data, sizeof(value));
736 return value;
737 }
738 break;
739 case REG_QWORD:
740 if (length >= sizeof(UINT64))
741 {
742 UINT64 value;
743 memcpy(&value, data, sizeof(value));
744 return value;
745 }
746 break;
747 }
748 return nullptr;
749}
750
751static void HandleRegistryEvent(const PANO_EVENT_HEADER *header, const PANO_REGISTRY_EVENT_DATA *data)
752{
753 if (data->ProcessId == GetCurrentProcessId())
754 {
755 return;
756 }
757
758 std::wstring keyName(data->Strings, data->KeyNameLength);
759 std::wstring secondName(data->Strings + data->KeyNameLength, data->SecondNameLength);
760 const BYTE *valueData = (const BYTE *)(data->Strings + data->KeyNameLength + data->SecondNameLength);
761 std::string key = ToString(ToRegistryDisplayPath(keyName));
762
763 nlohmann::ordered_json event;
764 event["Event"] = EventTypeName(header->Type);
765 event["PID"] = data->ProcessId;
766 event["TID"] = data->ThreadId;
767 // Rules need to know who changed the registry: services.exe installing a service or lsass.exe
768 // reading the SAM is normal, any other process doing so is not
769 event["Image"] = ResolveProcessImage((DWORD)data->ProcessId, ToFileTime(header->Timestamp));
770 event["Key"] = key;
771
772 switch (header->Type)
773 {
775 {
776 // The default value of a key has no name
777 event["ValueName"] = ToString(secondName);
778 const char *typeName = RegistryValueTypeName(data->Detail);
779 if (typeName != nullptr)
780 {
781 event["Type"] = typeName;
782 }
783 else
784 {
785 event["Type"] = data->Detail;
786 }
787 event["DataSize"] = data->DataSize;
788 nlohmann::json decoded = RegistryValueData(data->Detail, valueData, data->DataLength);
789 if (!decoded.is_null())
790 {
791 event["Data"] = std::move(decoded);
792 }
793 event["DataHex"] = RegistryValueHex(valueData, data->DataLength);
795 {
796 event["DataTruncated"] = true;
797 }
798 break;
799 }
801 event["Path"] = ToRegistryFilePath(secondName);
802 event["Format"] = data->Detail;
803 break;
805 event["Changed"] = SecurityInformationNames(data->Detail);
806 break;
808 event["Path"] = ToRegistryFilePath(secondName);
809 event["LoadFlags"] = data->Detail;
810 break;
812 {
813 // Data holds the file the old hive was saved to
814 std::wstring oldFile(data->DataLength / sizeof(WCHAR), L'\0');
815 memcpy(oldFile.data(), valueData, oldFile.size() * sizeof(WCHAR)); // the data is not aligned
816 event["Path"] = ToRegistryFilePath(secondName);
817 event["OldPath"] = ToRegistryFilePath(oldFile);
819 {
820 event["OldPathTruncated"] = true;
821 }
822 break;
823 }
825 event["NewKey"] = ToString(ToRegistryDisplayPath(secondName));
826 break;
828 event["ValueName"] = ToString(secondName);
829 event["InformationClass"] = data->Detail;
830 break;
831 }
832
833 event["Time"] = FormatSystemTime(ToFileTime(header->Timestamp));
835 {
836 event["KernelMode"] = true;
837 }
839 {
840 event["NameTruncated"] = true;
841 }
843 {
844 event["Incomplete"] = true;
845 }
846
847 // A key renamed into or out of an excluded path is still worth seeing, so the rename is only
848 // hidden when both names are excluded
849 bool excluded = IsLogExcluded(key);
850 if (excluded && header->Type == PANO_EVENT_REGISTRY_RENAME_KEY)
851 {
852 excluded = IsLogExcluded(event["NewKey"].get<std::string>());
853 }
854 if (!excluded)
855 {
856 LogEvent(event, ToFileTime(header->Timestamp));
857 }
858}
859
860static void HandleProcessEvent(const PANO_EVENT_HEADER *header, const PANO_PROCESS_EVENT_DATA *data)
861{
862 nlohmann::ordered_json event;
863 event["Event"] = EventTypeName(header->Type);
864 event["PID"] = data->ProcessId;
865 event["Time"] = FormatSystemTime(ToFileTime(header->Timestamp));
866
867 if (header->Type == PANO_EVENT_PROCESS_CREATED)
868 {
869 std::wstring ntPath(data->Strings, data->ImageNameLength);
870 std::wstring dosPath = ToDosPath(ntPath);
871 std::wstring commandLine(data->Strings + data->ImageNameLength, data->CommandLineLength);
872
873 event["ParentPID"] = data->ParentProcessId;
874 event["CreatorPID"] = data->CreatingProcessId;
875 event["CreatorTID"] = data->CreatingThreadId;
876 event["Image"] = ToString(dosPath.empty() ? ntPath : dosPath);
877 event["CommandLine"] = ToString(commandLine);
879 {
880 event["NameTruncated"] = true;
881 }
883 {
884 event["CommandLineTruncated"] = true;
885 }
886
887 // Before logging, so the image is known before any hook event from this process
888 // can arrive (a truncated name is still the best path available)
889 RecordProcessStart(data->ProcessId, event["Image"].get<std::string>(), ToFileTime(header->Timestamp));
890 }
891 else if (header->Type == PANO_EVENT_PROCESS_TERMINATED)
892 {
894 }
895
896 LogEvent(event, ToFileTime(header->Timestamp));
897}
898
899static void HandleEvent(const BYTE *buffer, DWORD bytes)
900{
901 if (bytes < sizeof(PANO_EVENT_HEADER))
902 {
903 return;
904 }
905
906 const PANO_EVENT_HEADER *header = (const PANO_EVENT_HEADER *)buffer;
907 if (header->Size < sizeof(PANO_EVENT_HEADER) || header->Size > bytes)
908 {
909 return;
910 }
911
912 // The counts cover the gap before this event. NoService: no service was reading events
913 // (this one was stopped, restarting, or not yet started); the driver does not buffer for
914 // it. QueueFull: the service was connected but not keeping up, or the driver could not
915 // allocate the event
916 if (header->DroppedNoConsumer > 0)
917 {
918 nlohmann::ordered_json event;
919 event["Event"] = "EventsDropped";
920 event["Reason"] = "NoService";
921 event["Count"] = header->DroppedNoConsumer;
922 LogEvent(event, CurrentFileTime());
923 }
924 if (header->Dropped > 0)
925 {
926 nlohmann::ordered_json event;
927 event["Event"] = "EventsDropped";
928 event["Reason"] = "QueueFull";
929 event["Count"] = header->Dropped;
930 LogEvent(event, CurrentFileTime());
931 }
932
933 if (EventTypeName(header->Type) == nullptr)
934 {
935 return;
936 }
937
938 UINT32 payloadSize = header->Size - (UINT32)sizeof(PANO_EVENT_HEADER);
939 const BYTE *payload = buffer + sizeof(PANO_EVENT_HEADER);
940
941 if (header->Type == PANO_EVENT_FILE_RENAME)
942 {
943 if (payloadSize < FIELD_OFFSET(PANO_RENAME_EVENT_DATA, Names))
944 {
945 return;
946 }
947
948 const PANO_RENAME_EVENT_DATA *rename = (const PANO_RENAME_EVENT_DATA *)payload;
949 UINT64 nameLength = (UINT64)rename->SourceNameLength + rename->DestinationNameLength;
950 if (nameLength > (payloadSize - FIELD_OFFSET(PANO_RENAME_EVENT_DATA, Names)) / sizeof(WCHAR))
951 {
952 return;
953 }
954
955 HandleRenameEvent(header, rename);
956 return;
957 }
958
960 {
961 if (payloadSize < FIELD_OFFSET(PANO_PROCESS_EVENT_DATA, Strings))
962 {
963 return;
964 }
965
966 const PANO_PROCESS_EVENT_DATA *process = (const PANO_PROCESS_EVENT_DATA *)payload;
967 UINT64 stringsLength = (UINT64)process->ImageNameLength + process->CommandLineLength;
968 if (stringsLength > (payloadSize - FIELD_OFFSET(PANO_PROCESS_EVENT_DATA, Strings)) / sizeof(WCHAR))
969 {
970 return;
971 }
972
973 HandleProcessEvent(header, process);
974 return;
975 }
976
977 // Every PANO_EVENT_REGISTRY_* type, which are numbered consecutively, carries a PANO_REGISTRY_EVENT_DATA
979 {
980 if (payloadSize < FIELD_OFFSET(PANO_REGISTRY_EVENT_DATA, Strings))
981 {
982 return;
983 }
984
985 const PANO_REGISTRY_EVENT_DATA *registry = (const PANO_REGISTRY_EVENT_DATA *)payload;
986 UINT64 neededBytes = ((UINT64)registry->KeyNameLength + registry->SecondNameLength) * sizeof(WCHAR) + registry->DataLength;
987 if (neededBytes > payloadSize - FIELD_OFFSET(PANO_REGISTRY_EVENT_DATA, Strings))
988 {
989 return;
990 }
991
992 HandleRegistryEvent(header, registry);
993 return;
994 }
995
996 if (header->Type == PANO_EVENT_FILE_MODIFIED)
997 {
998 if (payloadSize < FIELD_OFFSET(PANO_FILE_MODIFIED_EVENT_DATA, FileName))
999 {
1000 return;
1001 }
1002
1003 const PANO_FILE_MODIFIED_EVENT_DATA *modified = (const PANO_FILE_MODIFIED_EVENT_DATA *)payload;
1004 if (modified->NameLength > (payloadSize - FIELD_OFFSET(PANO_FILE_MODIFIED_EVENT_DATA, FileName)) / sizeof(WCHAR))
1005 {
1006 return;
1007 }
1008
1009 HandleFileModifiedEvent(header, modified);
1010 return;
1011 }
1012
1013 // Every other event type carries a PANO_FILE_EVENT_DATA
1014 if (payloadSize < FIELD_OFFSET(PANO_FILE_EVENT_DATA, FileName))
1015 {
1016 return;
1017 }
1018
1019 const PANO_FILE_EVENT_DATA *data = (const PANO_FILE_EVENT_DATA *)payload;
1020 if (data->NameLength > (payloadSize - FIELD_OFFSET(PANO_FILE_EVENT_DATA, FileName)) / sizeof(WCHAR))
1021 {
1022 return;
1023 }
1024
1025 HandleFileEvent(header, data);
1026}
1027
1028#pragma endregion
1029
1030#pragma region Threads
1031
1032static bool IssueEventRequest(PPANO_EVENT_REQUEST request)
1033{
1034 ZeroMemory(&request->Overlapped, sizeof(OVERLAPPED));
1035 BOOL ok = DeviceIoControl(
1036 g_Device,
1038 NULL,
1039 0,
1040 request->Buffer,
1041 sizeof(request->Buffer),
1042 NULL,
1043 &request->Overlapped);
1044
1045 // The completion is delivered to the completion port in both cases
1046 return ok || GetLastError() == ERROR_IO_PENDING;
1047}
1048
1049static void EventReaderThread()
1050{
1051 int outstanding = 0;
1052 for (auto &request : g_Requests)
1053 {
1054 if (IssueEventRequest(&request))
1055 {
1056 outstanding++;
1057 }
1058 }
1059
1060 while (outstanding > 0)
1061 {
1062 DWORD bytes = 0;
1063 ULONG_PTR key = 0;
1064 LPOVERLAPPED overlapped = NULL;
1065 BOOL ok = GetQueuedCompletionStatus(g_CompletionPort, &bytes, &key, &overlapped, INFINITE);
1066 if (overlapped == NULL)
1067 {
1068 // The completion port itself failed
1069 break;
1070 }
1071
1072 PPANO_EVENT_REQUEST request = CONTAINING_RECORD(overlapped, PANO_EVENT_REQUEST, Overlapped);
1073 outstanding--;
1074
1075 if (ok)
1076 {
1077 HandleEvent(request->Buffer, bytes);
1078 }
1079 else
1080 {
1081 DWORD error = GetLastError();
1082 if (error != ERROR_OPERATION_ABORTED)
1083 {
1084 std::cerr << "Driver event request failed. Error code: " << error << std::endl;
1085 }
1086 }
1087
1088 if (!g_Stopping && IssueEventRequest(request))
1089 {
1090 outstanding++;
1091 }
1092 }
1093}
1094
1095// Scans the files the reader thread asked for. Logs a FileModified event for every file whose
1096// writes have settled (or that has been written for PANO_WRITE_MAX_WINDOW_MS), and scans the
1097// ones that settled and are PE files
1098static void WrittenFileScanThread()
1099{
1100 while (!g_Stopping)
1101 {
1102 std::this_thread::sleep_for(std::chrono::milliseconds(PANO_WRITE_POLL_MS));
1103
1104 std::vector<std::string> requested;
1105 {
1106 std::lock_guard<std::mutex> lock(g_PendingScansLock);
1107 requested.swap(g_PendingScans);
1108 }
1109 // A file is often created and renamed within one poll; check each one once
1110 std::sort(requested.begin(), requested.end());
1111 requested.erase(std::unique(requested.begin(), requested.end()), requested.end());
1112 for (const auto &path : requested)
1113 {
1114 QueueFileScan(path);
1115 }
1116
1117 std::vector<std::pair<std::string, PANO_WRITTEN_FILE>> ready;
1118 ULONGLONG now = GetTickCount64();
1119 {
1120 std::lock_guard<std::mutex> lock(g_WrittenFilesLock);
1121 for (auto it = g_WrittenFiles.begin(); it != g_WrittenFiles.end();)
1122 {
1123 const PANO_WRITTEN_FILE &file = it->second;
1124 if (now - file.LastWriteTick >= PANO_WRITE_SETTLE_MS ||
1126 {
1127 ready.emplace_back(it->first, file);
1128 it = g_WrittenFiles.erase(it);
1129 }
1130 else
1131 {
1132 ++it;
1133 }
1134 }
1135 }
1136
1137 for (const auto &[path, file] : ready)
1138 {
1139 nlohmann::ordered_json event;
1140 event["Event"] = "FileModified";
1141 event["PID"] = file.ProcessId;
1142 event["Image"] = ResolveProcessImage((DWORD)file.ProcessId, file.LastWriteTime);
1143 event["Path"] = path;
1144 event["Writes"] = file.Writes;
1145 event["Bytes"] = file.Bytes;
1146 // An older driver reports each write and never the close, so the last write stands in
1147 // for it
1148 event["Time"] = FormatSystemTime(file.LastWriteTime);
1149 event["FirstWriteTime"] = FormatSystemTime(file.FirstWriteTime);
1150 if (!IsLogExcluded(path))
1151 {
1152 LogEvent(event, file.LastWriteTime);
1153 }
1154
1155 // A file still being written is not complete yet; it is scanned once it settles
1156 bool settled = now - file.LastWriteTick >= PANO_WRITE_SETTLE_MS;
1157 if (settled && file.IsDosPath)
1158 {
1159 QueueFileScan(path);
1160 }
1161 }
1162 }
1163}
1164
1165#pragma endregion
1166
1168{
1169 BuildDeviceMap();
1170 g_LogExclusions = configuration->m_logExclusions;
1171
1172 // The device only allows SYSTEM and Administrators to open it
1173 g_Device = CreateFileW(
1175 GENERIC_READ,
1176 FILE_SHARE_READ | FILE_SHARE_WRITE,
1177 NULL,
1178 OPEN_EXISTING,
1179 FILE_FLAG_OVERLAPPED,
1180 NULL);
1181 if (g_Device == INVALID_HANDLE_VALUE)
1182 {
1183 DWORD error = GetLastError();
1184 std::cerr << "Failed to open the Panoptes driver device. Error code: " << error << std::endl;
1185 return (error == ERROR_ACCESS_DENIED) ? NOT_ADMIN : KERNEL_PIPE;
1186 }
1187
1188 g_CompletionPort = CreateIoCompletionPort(g_Device, NULL, 0, 1);
1189 if (g_CompletionPort == NULL)
1190 {
1191 CloseHandle(g_Device);
1192 g_Device = INVALID_HANDLE_VALUE;
1193 return WINDOWS_ERR;
1194 }
1195
1196 g_Stopping = false;
1197#ifdef _DEBUG
1198 g_EchoStopping = false;
1199 g_EchoThread = std::thread(ConsoleEchoThread);
1200#endif
1201 g_ReaderThread = std::thread(EventReaderThread);
1202 g_ScanThread = std::thread(WrittenFileScanThread);
1203 return PANO_SUCCESS;
1204}
1205
1207{
1208 if (g_Device == INVALID_HANDLE_VALUE)
1209 {
1210 return;
1211 }
1212
1213 // Cancelling completes every pending request with ERROR_OPERATION_ABORTED, and the
1214 // reader exits once none are outstanding
1215 g_Stopping = true;
1216 CancelIoEx(g_Device, NULL);
1217
1218 if (g_ReaderThread.joinable())
1219 {
1220 g_ReaderThread.join();
1221 }
1222 if (g_ScanThread.joinable())
1223 {
1224 g_ScanThread.join();
1225 }
1226
1227 {
1228 std::lock_guard<std::mutex> lock(g_PendingScansLock);
1229 g_PendingScans.clear();
1230 }
1231
1232#ifdef _DEBUG
1233 // The threads that log are stopped, so the echo thread prints what is left and exits
1234 {
1235 std::lock_guard<std::mutex> lock(g_EchoLock);
1236 g_EchoStopping = true;
1237 }
1238 g_EchoReady.notify_one();
1239 if (g_EchoThread.joinable())
1240 {
1241 g_EchoThread.join();
1242 }
1243#endif
1244
1245 CloseHandle(g_CompletionPort);
1246 CloseHandle(g_Device);
1247 g_CompletionPort = NULL;
1248 g_Device = INVALID_HANDLE_VALUE;
1249}
#define PANO_SUCCESS
#define NOT_ADMIN
#define KERNEL_PIPE
#define WINDOWS_ERR
#define MAX_PATH
Definition callbacks.h:7
static bool IsPathInList(const std::vector< std::string > &patterns, const std::string &path)
Check whether a path matches any pattern in an exclusion list. A pattern with no wildcard matches eve...
std::vector< std::string > m_logExclusions
Path patterns whose driver events are not logged (see IsPathInList). Files matching them are still sc...
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.
struct _PANO_EVENT_REQUEST PANO_EVENT_REQUEST
#define PANO_WRITE_MAX_WINDOW_MS
#define PANO_PENDING_EVENT_REQUESTS
#define PANO_WRITE_SETTLE_MS
struct _PANO_EVENT_REQUEST * PPANO_EVENT_REQUEST
struct _PANO_WRITTEN_FILE PANO_WRITTEN_FILE
#define PANO_WRITE_POLL_MS
ERRORCODE StartDriverEvents(const Configuration *configuration)
Opens the Panoptes driver device and starts the threads that read events from it (IOCTL_PANOPTES_GET_...
void StopDriverEvents()
Cancels the pending event requests and stops the reader threads.
void SelfQueuePeScan(std::string pePath, std::string fileHash)
Definition grpc.cpp:338
#define PANO_FLAG_OPLOCKED
#define PANO_FLAG_HANDLE_STILL_OPEN
PANO_EVENT_FILE_MODIFIED: sent while the handle is still open and writing, so the file may not be com...
#define PANO_FLAG_KERNEL_MODE_CALLER
Registry events: the operation came from kernel mode (a driver or the system) rather than from a user...
#define PANO_FLAG_CAPTURE_FAILED
Registry events: a name or the data could not be read, so the event is incomplete....
struct _PANO_RENAME_EVENT_DATA PANO_RENAME_EVENT_DATA
The data for PANO_EVENT_FILE_RENAME.
struct _PANO_EVENT_HEADER PANO_EVENT_HEADER
The header at the start of every IOCTL_PANOPTES_GET_EVENT response.
@ PANO_EVENT_REGISTRY_SET_KEY_SECURITY
A registry key's security descriptor is about to be changed (a PANO_REGISTRY_EVENT_DATA)....
@ PANO_EVENT_FILE_RENAME
A file was renamed or moved (a PANO_RENAME_EVENT_DATA).
Definition pano_events.h:85
@ PANO_EVENT_MAILSLOT_CREATE
A server created a mailslot (CreateMailslot).
Definition pano_events.h:78
@ PANO_EVENT_NAMED_PIPE_CREATE
A server created a named pipe, or another instance of one (CreateNamedPipe).
Definition pano_events.h:74
@ PANO_EVENT_FILE_MODIFIED
A handle that wrote to a file was closed (a PANO_FILE_MODIFIED_EVENT_DATA). One event covers every wr...
Definition pano_events.h:94
@ PANO_EVENT_MAILSLOT_OPEN
A client opened a mailslot to write to it (CreateFile on \.\mailslot...).
Definition pano_events.h:80
@ PANO_EVENT_REGISTRY_SAVE_KEY
A registry key is about to be saved to a file, e.g. reg save HKLM\SAM (a PANO_REGISTRY_EVENT_DATA)....
@ PANO_EVENT_FILE_SUPERSEDED
Definition pano_events.h:71
@ PANO_EVENT_REGISTRY_REPLACE_KEY
A key's hive file was replaced, taking effect at the next boot, e.g. reg replace (a PANO_REGISTRY_EVE...
@ PANO_EVENT_FILE_EA_CHANGED
A file's extended attributes were written (a PANO_FILE_EVENT_DATA). Length holds the size of the EA b...
@ PANO_EVENT_NAMED_PIPE_OPEN
A client connected to a named pipe (CreateFile on \.\pipe...).
Definition pano_events.h:76
@ PANO_EVENT_REGISTRY_RENAME_KEY
A registry key was renamed (a PANO_REGISTRY_EVENT_DATA). The key name is the old full name and Second...
@ PANO_EVENT_REGISTRY_SET_VALUE
A registry value is about to be written (a PANO_REGISTRY_EVENT_DATA). SecondName is the value name,...
@ PANO_EVENT_FILE_OVERWRITTEN
Definition pano_events.h:70
@ PANO_EVENT_REGISTRY_CREATE_KEY
A new registry key was created (a PANO_REGISTRY_EVENT_DATA with only the key name)....
@ PANO_EVENT_FILE_CREATED
Definition pano_events.h:66
@ PANO_EVENT_FILE_SECURITY_CHANGED
A file's security descriptor was changed (a PANO_FILE_EVENT_DATA). Length holds the SECURITY_INFORMAT...
Definition pano_events.h:97
@ PANO_EVENT_PROCESS_TERMINATED
A process exited (a PANO_PROCESS_EVENT_DATA with only ProcessId set).
Definition pano_events.h:89
@ PANO_EVENT_FILE_WRITE
Definition pano_events.h:72
@ PANO_EVENT_FILE_OPENED
No longer reported: opens of existing files are too frequent and filled the queue....
Definition pano_events.h:69
@ PANO_EVENT_PROCESS_CREATED
A process was created (a PANO_PROCESS_EVENT_DATA).
Definition pano_events.h:87
@ PANO_EVENT_REGISTRY_LOAD_KEY
A hive file was loaded into the registry, e.g. reg load (a PANO_REGISTRY_EVENT_DATA)....
@ PANO_EVENT_REGISTRY_DELETE_KEY
A registry key is about to be deleted (a PANO_REGISTRY_EVENT_DATA with only the key name)....
@ PANO_EVENT_REGISTRY_QUERY_VALUE
A value was read from a key holding credentials (under HKLM\SAM or HKLM\SECURITY) (a PANO_REGISTRY_EV...
@ PANO_EVENT_FILE_DELETE
A file was marked for deletion (a PANO_FILE_EVENT_DATA). The delete happens when the last handle clos...
Definition pano_events.h:83
struct _PANO_REGISTRY_EVENT_DATA PANO_REGISTRY_EVENT_DATA
The data for PANO_EVENT_REGISTRY_* events.
#define PANO_FLAG_COMMAND_LINE_TRUNCATED
PANO_EVENT_PROCESS_CREATED: the command line was truncated to fit the event.
#define PANO_FLAG_REPLACE_EXISTING
PANO_EVENT_FILE_RENAME: the rename replaced an existing file at the destination.
#define PANO_FLAG_NAME_TRUNCATED
#define PANO_MAX_EVENT_SIZE
The output buffer size the service passes with IOCTL_PANOPTES_GET_EVENT. The driver never returns an ...
Definition pano_events.h:59
#define PANOPTES_USER_DEVICE_PATH
Definition pano_events.h:16
struct _PANO_FILE_EVENT_DATA PANO_FILE_EVENT_DATA
The data for file, named pipe and mailslot events.
struct _PANO_PROCESS_EVENT_DATA PANO_PROCESS_EVENT_DATA
The data for PANO_EVENT_PROCESS_CREATED and PANO_EVENT_PROCESS_TERMINATED.
struct _PANO_FILE_MODIFIED_EVENT_DATA PANO_FILE_MODIFIED_EVENT_DATA
The data for PANO_EVENT_FILE_MODIFIED.
#define PANO_FLAG_DELETE_ON_CLOSE
PANO_EVENT_FILE_DELETE: the file was opened with FILE_DELETE_ON_CLOSE rather than having its delete d...
#define PANO_FLAG_DATA_TRUNCATED
PANO_EVENT_REGISTRY_SET_VALUE / _REPLACE_KEY: Data holds only the first PANO_MAX_REGISTRY_DATA_SIZE b...
#define IOCTL_PANOPTES_GET_EVENT
Waits for and returns the next event from the driver.
Definition pano_events.h:19
void RecordProcessExit(DWORD processId)
Records a process exit (ProcessTerminated). Its entry is forgotten a minute later.
void RecordProcessStart(DWORD processId, const std::string &image, const FILETIME &time)
Records a process start (ProcessCreated).
std::string ResolveProcessImage(DWORD processId, const FILETIME &time)
LookupProcessImage, falling back to asking Windows (QueryFullProcessImageName) for processes the serv...
#define ERRORCODE
INT64 Timestamp
When the event occurred, in FILETIME units (UTC).
UINT32 DroppedNoConsumer
Number of events dropped since the previous response because no service was reading events,...
UINT32 Type
A PANO_EVENT_TYPE describing the data that follows the header.
UINT32 Size
Total size in bytes of the response, header plus event data.
UINT32 Dropped
Number of events dropped since the previous response because they could not be queued: the queue was ...
BYTE Buffer[PANO_MAX_EVENT_SIZE]
UINT32 Length
Length of the write, PANO_EVENT_FILE_WRITE only.
UINT32 NameLength
Length of FileName in WCHARs. FileName is not null terminated.
UINT32 Flags
PANO_FLAG_* values.
UINT64 ProcessId
The process and thread of the most recent write.
UINT32 NameLength
Length of FileName in WCHARs. FileName is not null terminated. It is the file's name when the event w...
INT64 FirstWriteTime
When the first of those writes happened, in FILETIME units (UTC).
UINT32 Flags
PANO_FLAG_* values.
UINT64 Bytes
Bytes written by those writes.
UINT64 Writes
Number of writes through the handle covered by this event.
UINT32 Flags
PANO_FLAG_* values. PANO_FLAG_NAME_TRUNCATED refers to the image name and PANO_FLAG_COMMAND_LINE_TRUN...
WCHAR Strings[1]
The image name immediately followed by the command line. Neither is null terminated.
UINT32 CommandLineLength
Length of the command line in WCHARs. PANO_EVENT_PROCESS_CREATED only.
UINT32 ImageNameLength
Length of the image name in WCHARs. PANO_EVENT_PROCESS_CREATED only.
UINT64 ParentProcessId
PANO_EVENT_PROCESS_CREATED only.
UINT64 CreatingProcessId
The process that created the new process, which can differ from the parent. PANO_EVENT_PROCESS_CREATE...
UINT64 CreatingThreadId
The thread that created the new process. PANO_EVENT_PROCESS_CREATED only.
WCHAR Strings[1]
The key name, then the second name (neither null terminated), then DataLength bytes of data....
UINT32 KeyNameLength
Length of the key's full name (\REGISTRY\MACHINE...) in WCHARs.
UINT32 Detail
Per event type: the REG_* value type (SET_VALUE), the REG_*_FORMAT (SAVE_KEY), the SECURITY_INFORMATI...
UINT32 DataSize
The full size of Data in bytes before it was cut to fit: the value's data (SET_VALUE) or the old hive...
UINT32 Flags
PANO_FLAG_* values.
UINT32 SecondNameLength
Length of the second name in WCHARs: the value name (SET_VALUE, QUERY_VALUE), the file (SAVE_KEY,...
UINT32 DataLength
Bytes in Data, at most PANO_MAX_REGISTRY_DATA_SIZE. SET_VALUE and REPLACE_KEY only.
WCHAR Names[1]
The original name immediately followed by the new name. Neither is null terminated.
UINT32 Flags
PANO_FLAG_* values.
UINT32 SourceNameLength
Length of the original name in WCHARs.
UINT32 DestinationNameLength
Length of the new name in WCHARs.
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