Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
detector.cpp
Go to the documentation of this file.
1// winsock2.h has to come before Windows.h (which pulls in the older winsock.h)
2#include <winsock2.h>
3#include <ws2tcpip.h>
4#include <iphlpapi.h>
5#include <winternl.h>
6
7#include "detector.h"
8#include "panoptes.pb.h"
9#include "containers.h"
10#include "driver.h"
11#include "error_message.h"
12#include "grpc.hpp"
13#include "utils.h"
14#include "Configuration.hpp"
15#include <vector>
16
17#pragma region Peer Check
18
19// The port at the end of a gRPC peer string: "ipv4:127.0.0.1:50123" or "ipv6:%5B::1%5D:50123"
20static bool PeerPort(const std::string& peer, USHORT& port)
21{
22 size_t colon = peer.find_last_of(':');
23 if (colon == std::string::npos || colon + 1 == peer.size()) {
24 return false;
25 }
26 unsigned long value = 0;
27 for (size_t i = colon + 1; i < peer.size(); i++) {
28 if (peer[i] < '0' || peer[i] > '9') {
29 return false;
30 }
31 value = value * 10 + (peer[i] - '0');
32 if (value > 0xFFFF) {
33 return false;
34 }
35 }
36 port = (USHORT)value;
37 return true;
38}
39
40// The TCP tables hold ports in network byte order in the low 16 bits
41static USHORT TablePort(DWORD port)
42{
43 return _byteswap_ushort((USHORT)port);
44}
45
46// Finds the process that owns the client end of a connection to serverPort from clientPort
47static bool FindConnectionOwner(ULONG family, USHORT clientPort, USHORT serverPort, DWORD& processId)
48{
49 std::vector<BYTE> buffer;
50 DWORD size = 0;
51 DWORD result;
52 do {
53 buffer.resize(size);
54 result = GetExtendedTcpTable(buffer.empty() ? NULL : buffer.data(), &size, FALSE, family,
55 TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
56 } while (result == ERROR_INSUFFICIENT_BUFFER);
57 if (result != NO_ERROR) {
58 return false;
59 }
60
61 if (family == AF_INET) {
62 auto table = (const MIB_TCPTABLE_OWNER_PID*)buffer.data();
63 for (DWORD i = 0; i < table->dwNumEntries; i++) {
64 const auto& row = table->table[i];
65 if (TablePort(row.dwLocalPort) == clientPort && TablePort(row.dwRemotePort) == serverPort) {
66 processId = row.dwOwningPid;
67 return true;
68 }
69 }
70 }
71 else {
72 auto table = (const MIB_TCP6TABLE_OWNER_PID*)buffer.data();
73 for (DWORD i = 0; i < table->dwNumEntries; i++) {
74 const auto& row = table->table[i];
75 if (TablePort(row.dwLocalPort) == clientPort && TablePort(row.dwRemotePort) == serverPort) {
76 processId = row.dwOwningPid;
77 return true;
78 }
79 }
80 }
81 return false;
82}
83
84static std::wstring ProcessImagePath(HANDLE process)
85{
86 WCHAR path[MAX_PATH * 2];
87 DWORD length = ARRAYSIZE(path);
88 return QueryFullProcessImageNameW(process, 0, path, &length) ? std::wstring(path, length) : L"";
89}
90
91bool IsDetectorPeer(const std::string& peer, int serverPort, std::string& why)
92{
93 USHORT clientPort = 0;
94 if (!PeerPort(peer, clientPort)) {
95 why = "unrecognized peer " + peer;
96 return false;
97 }
98
99 DWORD processId = 0;
100 if (!FindConnectionOwner(AF_INET, clientPort, (USHORT)serverPort, processId) &&
101 !FindConnectionOwner(AF_INET6, clientPort, (USHORT)serverPort, processId)) {
102 why = "no local process owns the connection from " + peer;
103 return false;
104 }
105
106 HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
107 if (process == NULL) {
108 why = "cannot open process " + std::to_string(processId);
109 return false;
110 }
111 std::wstring image = ProcessImagePath(process);
112 CloseHandle(process);
113
114 std::wstring expected = DetectorExecutablePath();
115 if (image.empty() || expected.empty() || _wcsicmp(image.c_str(), expected.c_str()) != 0) {
116 why = "process " + std::to_string(processId) + " (" + ToString(image) + ") is not " + ToString(expected);
117 return false;
118 }
119 return true;
120}
121
122#pragma endregion
123
124#pragma region Response
125
126// ProcessBreakOnTermination: the process is critical, and ending it stops the system
127#define PANO_PROCESS_BREAK_ON_TERMINATION 29
128
129typedef NTSTATUS(NTAPI* NtQueryInformationProcess_t)(HANDLE, ULONG, PVOID, ULONG, PULONG);
130
131// Whether ending the process would bug check the machine. Unknown counts as critical
132static bool IsCriticalProcess(HANDLE process)
133{
134 static auto query = (NtQueryInformationProcess_t)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationProcess");
135 ULONG critical = 0;
136 if (query == NULL || query(process, PANO_PROCESS_BREAK_ON_TERMINATION, &critical, sizeof(critical), NULL) < 0) {
137 return true;
138 }
139 return critical != 0;
140}
141
142// Ends a detected process. Returns what happened; terminated says whether it was ended
143static std::string TerminateDetectedProcess(const Detection& detection, HANDLE& process, bool& terminated,
144 std::wstring& image)
145{
146 terminated = false;
147 DWORD processId = detection.process_id();
148 if (processId == 0 || processId == 4) {
149 return "refused: system process";
150 }
151 if (processId == GetCurrentProcessId()) {
152 return "refused: the service itself";
153 }
154
155 process = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, processId);
156 if (process == NULL) {
157 DWORD error = GetLastError();
158 return (error == ERROR_INVALID_PARAMETER) ? "not needed: the process has exited"
159 : "refused: cannot open the process (error " + std::to_string(error) + ")";
160 }
161 if (WaitForSingleObject(process, 0) == WAIT_OBJECT_0) {
162 return "not needed: the process has exited";
163 }
164 if (IsServiceChildProcess(process)) {
165 return "refused: a process the service started";
166 }
167 if (IsCriticalProcess(process)) {
168 return "refused: critical system process";
169 }
170
171 // The detection reaches the service seconds after the events. If the process was created
172 // after the last matching event, its ID belonged to another process that has since exited
173 FILETIME created, exited, kernel, user;
174 FILETIME matched;
175 matched.dwLowDateTime = (DWORD)(detection.timestamp() & 0xFFFFFFFF);
176 matched.dwHighDateTime = (DWORD)((UINT64)detection.timestamp() >> 32);
177 if (detection.timestamp() == 0) {
178 return "refused: the detection has no event time";
179 }
180 if (!GetProcessTimes(process, &created, &exited, &kernel, &user) || CompareFileTime(&created, &matched) > 0) {
181 return "refused: the process ID was reused after the match";
182 }
183
184 image = ProcessImagePath(process);
185 ERRORCODE result = TerminateProcessByDriver(processId);
186 if (result != PANO_SUCCESS) {
187 return "kill failed (error " + std::to_string(result) + ")";
188 }
189 terminated = true;
190 return "terminated";
191}
192
193std::string RespondToDetection(const Detection& detection, const Configuration& configuration)
194{
195 if (detection.action() != DETECTION_ACTION_KILL && detection.action() != DETECTION_ACTION_QUARANTINE) {
196 return "alerted";
197 }
198 if (!configuration.m_enforceDetectionActions) {
199 return "alerted (EnforceDetectionActions is off)";
200 }
201
202 HANDLE process = NULL;
203 bool terminated = false;
204 std::wstring imagePath;
205 std::string outcome = TerminateDetectedProcess(detection, process, terminated, imagePath);
206 if (detection.action() == DETECTION_ACTION_QUARANTINE && terminated) {
207 // The image is resolved by the service rather than taken from the detection, whose path
208 // comes from the event and may be empty
209 std::string image = ToString(imagePath);
210 // A running image cannot be moved, so wait for the kill to complete
211 WaitForSingleObject(process, 5000);
212 if (image.empty()) {
213 outcome += "; not quarantined: image path unknown";
214 }
215 else if (Configuration::IsPathInList(configuration.m_exclusions, image)) {
216 outcome += "; not quarantined: " + image + " is in Exclusions";
217 }
218 else {
219 outcome += MoveFileToQuarantine(image) ? "; quarantined " + image : "; quarantine of " + image + " failed";
220 }
221 }
222 if (process != NULL) {
223 CloseHandle(process);
224 }
225 return outcome;
226}
227
228#pragma endregion
#define PANO_SUCCESS
#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_exclusions
Path patterns that are not scanned (see IsPathInList).
bool m_enforceDetectionActions
Whether the service carries out the kill and quarantine actions of detector rules....
bool IsServiceChildProcess(HANDLE process)
Whether a process is one the service started (a container or the detector).
std::wstring DetectorExecutablePath()
The path the service starts the detector from: PanoptesDetector.exe in the service's folder....
bool IsDetectorPeer(const std::string &peer, int serverPort, std::string &why)
Whether a gRPC peer is PanoptesDetector.exe from the service's folder. The server listens on localhos...
Definition detector.cpp:91
std::string RespondToDetection(const Detection &detection, const Configuration &configuration)
Carries out a detection's action and describes what was done, for the log. Kill and quarantine only h...
Definition detector.cpp:193
#define PANO_PROCESS_BREAK_ON_TERMINATION
Definition detector.cpp:127
NTSTATUS(NTAPI * NtQueryInformationProcess_t)(HANDLE, ULONG, PVOID, ULONG, PULONG)
Definition detector.cpp:129
ERRORCODE TerminateProcessByDriver(UINT64 processId)
Asks the driver to terminate a process (IOCTL_PANOPTES_TERMINATE_PROCESS).
Definition driver.cpp:66
bool MoveFileToQuarantine(std::string filePath)
Moves a file into C:\ProgramData\Panoptes\Quarantine.
Definition grpc.cpp:71
#define ERRORCODE
std::string ToString(const std::wstring &wstr)
Definition utils.cpp:51