Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
process_images.cpp
Go to the documentation of this file.
1#include "process_images.h"
2#include "utils.h"
3#include <algorithm>
4#include <deque>
5#include <mutex>
6#include <unordered_map>
7#include <vector>
8
9// How long an exited process's image is kept for its late hook events. ETW delivers within
10// about a second; this leaves room for a busy machine
11#define PANO_IMAGE_KEEP_MS 60000
12
13// Entries kept per PID. Two covers an event from the old process arriving after the PID was
14// already reused
15#define PANO_IMAGES_PER_PID 2
16
17// The process creation time (kernel clock) and the hook event time (ETW's QPC converted to
18// FILETIME) can disagree slightly; an event this far before the recorded start still counts
19#define PANO_IMAGE_TIME_SLACK (10000000ULL) // 1 second in 100ns units
20
22 std::string Image;
23 ULONGLONG Start = 0; // FILETIME as a number
24 ULONGLONG ExitTick = 0; // GetTickCount64 when the exit was recorded; 0 while running
25};
26
27static std::mutex g_Lock;
28static std::unordered_map<DWORD, std::vector<ProcessImageEntry>> g_Images;
29// Exits in the order they were recorded, so expired entries are found without a full scan
30static std::deque<std::pair<ULONGLONG, DWORD>> g_Exits;
31
32static ULONGLONG ToNumber(const FILETIME& time)
33{
34 return ((ULONGLONG)time.dwHighDateTime << 32) | time.dwLowDateTime;
35}
36
37static bool StartsWithIgnoreCase(const std::string& text, const char* prefix)
38{
39 size_t length = strlen(prefix);
40 return text.size() >= length && _strnicmp(text.c_str(), prefix, length) == 0;
41}
42
43// "\??\C:\x.exe" -> "C:\x.exe" and "\SystemRoot\System32\x.exe" -> "C:\Windows\System32\x.exe"
44static std::string ToWin32Path(const std::string& image)
45{
46 if (StartsWithIgnoreCase(image, "\\??\\")) {
47 return image.substr(4);
48 }
49 if (StartsWithIgnoreCase(image, "\\SystemRoot\\")) {
50 WCHAR windows[MAX_PATH];
51 UINT length = GetWindowsDirectoryW(windows, MAX_PATH);
52 if (length > 0 && length < MAX_PATH) {
53 return ToString(std::wstring(windows, length)) + image.substr(strlen("\\SystemRoot"));
54 }
55 }
56 return image;
57}
58
59// Forgets processes that exited more than PANO_IMAGE_KEEP_MS ago. Called with g_Lock held
60static void Prune(ULONGLONG now)
61{
62 while (!g_Exits.empty() && now - g_Exits.front().first >= PANO_IMAGE_KEEP_MS) {
63 DWORD processId = g_Exits.front().second;
64 g_Exits.pop_front();
65
66 auto found = g_Images.find(processId);
67 if (found == g_Images.end()) {
68 continue;
69 }
70 auto& entries = found->second;
71 entries.erase(std::remove_if(entries.begin(), entries.end(), [now](const ProcessImageEntry& entry) {
72 return entry.ExitTick != 0 && now - entry.ExitTick >= PANO_IMAGE_KEEP_MS;
73 }), entries.end());
74 if (entries.empty()) {
75 g_Images.erase(found);
76 }
77 }
78}
79
80void RecordProcessStart(DWORD processId, const std::string& image, const FILETIME& time)
81{
82 std::lock_guard<std::mutex> guard(g_Lock);
83 Prune(GetTickCount64());
84
85 auto& entries = g_Images[processId];
87 entry.Image = ToWin32Path(image);
88 entry.Start = ToNumber(time);
89 entries.push_back(std::move(entry));
90 if (entries.size() > PANO_IMAGES_PER_PID) {
91 entries.erase(entries.begin());
92 }
93}
94
95void RecordProcessExit(DWORD processId)
96{
97 ULONGLONG now = GetTickCount64();
98 std::lock_guard<std::mutex> guard(g_Lock);
99 Prune(now);
100
101 auto found = g_Images.find(processId);
102 if (found == g_Images.end()) {
103 return; // started before the service
104 }
105 // The newest entry is the process that exited; an older one has already exited
106 auto& newest = found->second.back();
107 if (newest.ExitTick == 0) {
108 newest.ExitTick = now;
109 g_Exits.emplace_back(now, processId);
110 }
111}
112
113std::string LookupProcessImage(DWORD processId, const FILETIME& time)
114{
115 ULONGLONG at = ToNumber(time);
116 std::lock_guard<std::mutex> guard(g_Lock);
117 auto found = g_Images.find(processId);
118 if (found == g_Images.end()) {
119 return "";
120 }
121 // Newest first: the latest process with this ID that had started by then
122 const auto& entries = found->second;
123 for (auto entry = entries.rbegin(); entry != entries.rend(); ++entry) {
124 if (entry->Start <= at + PANO_IMAGE_TIME_SLACK) {
125 return entry->Image;
126 }
127 }
128 return "";
129}
130
131// The System process (PID 4), which the kernel's own registry and file activity is charged to.
132// It has no image file
133#define PANO_SYSTEM_PROCESS_ID 4
134
135// SystemProcessIdInformation (NtQuerySystemInformation class 0x58): a process's image name by ID,
136// with no handle needed
137#define PANO_SYSTEM_PROCESS_ID_INFORMATION_CLASS 0x58
138
140 HANDLE ProcessId;
141 USHORT Length; // the ImageName UNICODE_STRING, filled in by the kernel
143 PWSTR Buffer;
145
146typedef LONG(NTAPI* PanoNtQuerySystemInformation)(ULONG, PVOID, ULONG, PULONG);
147
148// Names the processes QueryFullProcessImageName cannot: "System", and minimal processes such as
149// "Registry" and "MemCompression", which have a name but no image file. For any other process
150// it is the kernel's NT path (\Device\HarddiskVolume2\...). "" when the process is gone
151static std::string KernelProcessImage(DWORD processId)
152{
153 if (processId == PANO_SYSTEM_PROCESS_ID) {
154 return "System";
155 }
156
157 static PanoNtQuerySystemInformation query = (PanoNtQuerySystemInformation)GetProcAddress(
158 GetModuleHandleW(L"ntdll.dll"), "NtQuerySystemInformation");
159 if (query == nullptr) {
160 return "";
161 }
162 WCHAR name[MAX_PATH * 2];
164 info.ProcessId = (HANDLE)(ULONG_PTR)processId;
165 info.MaximumLength = sizeof(name);
166 info.Buffer = name;
167 if (query(PANO_SYSTEM_PROCESS_ID_INFORMATION_CLASS, &info, sizeof(info), nullptr) < 0) {
168 return "";
169 }
170 return ToString(std::wstring(name, info.Length / sizeof(WCHAR)));
171}
172
173std::string ResolveProcessImage(DWORD processId, const FILETIME& time)
174{
175 std::string image = LookupProcessImage(processId, time);
176 if (!image.empty()) {
177 return image;
178 }
179
180 HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
181 if (process != NULL) {
182 WCHAR path[MAX_PATH * 2];
183 DWORD length = ARRAYSIZE(path);
184 if (QueryFullProcessImageNameW(process, 0, path, &length)) {
185 image = ToString(std::wstring(path, length));
186 }
187 CloseHandle(process);
188 }
189 if (image.empty()) {
190 image = KernelProcessImage(processId);
191 }
192 return image;
193}
#define MAX_PATH
Definition callbacks.h:7
void RecordProcessExit(DWORD processId)
Records a process exit (ProcessTerminated). Its entry is forgotten a minute later.
struct _PANO_SYSTEM_PROCESS_ID_INFORMATION PANO_SYSTEM_PROCESS_ID_INFORMATION
LONG(NTAPI * PanoNtQuerySystemInformation)(ULONG, PVOID, ULONG, PULONG)
#define PANO_SYSTEM_PROCESS_ID
void RecordProcessStart(DWORD processId, const std::string &image, const FILETIME &time)
Records a process start (ProcessCreated).
#define PANO_IMAGE_KEEP_MS
#define PANO_SYSTEM_PROCESS_ID_INFORMATION_CLASS
#define PANO_IMAGES_PER_PID
std::string LookupProcessImage(DWORD processId, const FILETIME &time)
The image of the process that had processId at the given time, from the recorded starts....
#define PANO_IMAGE_TIME_SLACK
std::string ResolveProcessImage(DWORD processId, const FILETIME &time)
LookupProcessImage, falling back to asking Windows (QueryFullProcessImageName) for processes the serv...
std::string ToString(const std::wstring &wstr)
Definition utils.cpp:51