Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
service.cpp File Reference
#include "panoptes_service.h"
#include "ResourceCore.h"
#include <iostream>
#include <conio.h>
#include "grpc.hpp"
#include "tray_notifications.h"
#include "error_message.h"
#include "mutex.hpp"
#include "containers.h"
#include "utils.h"
#include "database.hpp"
#include "driver.h"
#include "driver_events.h"
#include "hook_events.h"
#include "shutdown.h"
#include "Configuration.hpp"

Go to the source code of this file.

Macros

#define PANO_GRPC_THREAD_WAIT_MS   5000

Functions

ERRORCODE CleanupWithError (ERRORCODE err)
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)

Macro Definition Documentation

◆ PANO_GRPC_THREAD_WAIT_MS

#define PANO_GRPC_THREAD_WAIT_MS   5000

Definition at line 19 of file service.cpp.

Function Documentation

◆ CleanupWithError()

ERRORCODE CleanupWithError ( ERRORCODE err)

Definition at line 42 of file service.cpp.

42 {
43 StopService();
44 std::string msg = GetErrorMessage(err);
47 return err;
48}
std::string GetErrorMessage(UINT resourceID)
void DisplayErrorMessage(std::string errorMessage)
void NotifyShutdownComplete()
Tells console handlers and the session-end window that teardown has finished, so they can return and ...
Definition shutdown.cpp:183

References DisplayErrorMessage(), ERRORCODE, GetErrorMessage(), and NotifyShutdownComplete().

Referenced by WinMain().

◆ WinMain()

int WINAPI WinMain ( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )

Definition at line 51 of file service.cpp.

52{
53 // --stop asks a running service to shut down and waits for it to exit. It shows no dialogs
54 // so installers and scripts can use it. Exits 0 once the service has stopped, otherwise
55 // with the error code
56 if (HasCommandLineFlag("--stop")) {
57 ERRORCODE stopResult = RequestServiceStop();
58 return (stopResult == PANO_SUCCESS) ? 0 : stopResult;
59 }
60
61#ifndef _DEBUG
62 if (IsDebuggerPresent()) {
63 auto msg = GetErrorMessage(DEBUGGER);
65 return DEBUGGER;
66 }
67#endif
68
69#ifdef _DEBUG
70 // --wait pauses before any initialization so a debugger (e.g. a KDNET kernel session)
71 // can attach and set breakpoints first
72 if (HasCommandLineFlag("--wait")) {
73 DWORD pid = GetCurrentProcessId();
74 printf("PanoptesService PID %lu (0x%lx)\n", pid, pid);
75 printf(" WinDbg (kernel): !process 0x%lx 0 then .process /i <EPROCESS>; g; .reload /user\n", pid);
76 printf("Press any key to start...\n");
77 _getch();
78 }
79#endif
80
82 serviceContext.threadError = false;
83
84#pragma region Admin Check
85#ifndef _DEBUG
86 if (!IsRunningAsAdmin()) {
87 auto msg = GetErrorMessage(NOT_ADMIN);
89 return NOT_ADMIN;
90 }
91#endif
92#pragma endregion
93
94#pragma region Mutex Check
95 if (MutexExist() != PANO_SUCCESS) {
97 auto msg = GetErrorMessage(MUTEX_SET);
99 return MUTEX_SET;
100 }
101 }
102 else {
103 auto msg = GetErrorMessage(MUTEX_SET);
105 return MUTEX_SET;
106 }
107#pragma endregion
108
109#pragma region Shutdown Handling
110 // Installed before anything starts so a shutdown requested during startup is handled once
111 // startup finishes
112 ERRORCODE errCode = InitializeShutdown();
113 if (errCode != PANO_SUCCESS) {
114 return CleanupWithError(errCode);
115 }
116#pragma endregion
117
118#pragma region Panoptes Configuration
119#ifdef _DEBUG
120 std::string configPath = GetExecutableDirectory() + "\\panoptes.config";
121#else
122 std::string configPath = "C:\\ProgramData\\Panoptes\\Panoptes.config";
123#endif // _DEBUG
124
125 Configuration* configuration = new Configuration(configPath);
126 try {
127 configuration->Parse();
128 serviceContext.config = configuration;
129 }
130 catch (const int& err) {
131 return CleanupWithError(err);
132 }
133 catch (const std::exception& e) {
134 // Malformed JSON or a missing or invalid setting
135 std::cerr << "Failed to parse " << configPath << ": " << e.what() << std::endl;
137 }
138#pragma endregion
139
140#pragma region Database
141 auto dbTmp = serviceContext.database.load();
142 errCode = dbTmp.InitializeDatabase();
143 if (errCode != PANO_SUCCESS) {
144 return CleanupWithError(errCode);
145 }
146#pragma endregion
147
148#pragma region GRPC Server
149 g_grpcThread = CreateThread(
150 NULL, // default security attributes
151 0, // default stack size
152 (LPTHREAD_START_ROUTINE)RunServiceServer, // thread function
153 &serviceContext, // no thread function arguments
154 0, // default creation flags
155 NULL // receive thread identifier
156 );
157 Sleep(2000);
158
159 if (g_grpcThread == NULL || serviceContext.threadError) {
161 }
162#pragma endregion
163
164#pragma region Container Start
165#ifndef _DEBUG
166 errCode = StartContainers();
167 if (errCode != PANO_SUCCESS) {
168 return CleanupWithError(errCode);
169 }
170#endif
171#pragma endregion
172
173#pragma region Detector
174 // Started in every build: it dials back to the server (retrying until the port is
175 // published) and receives events once the driver and hook events below start
176 errCode = StartDetector();
177 if (errCode != PANO_SUCCESS) {
178 return CleanupWithError(errCode);
179 }
180#pragma endregion
181
182#pragma region Driver
183 // The driver is required and must already be running. Debug builds skip it unless
184 // --driver is passed, so the service can be debugged unelevated without the driver
185 bool useDriver = true;
186#ifdef _DEBUG
187 useDriver = HasCommandLineFlag("--driver");
188#endif
189
190 if (useDriver) {
191 // The driver's device only allows SYSTEM and Administrators to open it
192 if (!IsRunningAsAdmin()) {
194 }
195
196 errCode = GetKernelServiceStatus();
197 if (errCode == PANO_SERVICE_STOPPED)
198 {
199 // The driver is demand start: after a reboot or an MSI install it is installed but
200 // not running, so start it rather than fail
201 errCode = StartKernelService();
202 }
203 if (errCode != PANO_SERVICE_RUNNING)
204 {
205 return CleanupWithError(errCode);
206 }
207
208 // Always sent, even when empty, so a list left in the driver by an earlier run with a
209 // different configuration is replaced
210 errCode = SetInjectionExclusionsInDriver(configuration->m_dontInject);
211 if (errCode != PANO_SUCCESS)
212 {
213 return CleanupWithError(errCode);
214 }
215
216 // Also always sent: the driver keeps the last setting until it is unloaded
217 errCode = SetFileEventsInDriver(configuration->m_fileEvents);
218 if (errCode != PANO_SUCCESS)
219 {
220 return CleanupWithError(errCode);
221 }
222
223 errCode = StartDriverEvents(configuration);
224 if (errCode != PANO_SUCCESS)
225 {
226 return CleanupWithError(errCode);
227 }
228 }
229#pragma endregion
230
231#pragma region Hook Events
232 // Events from the hook DLL arrive over ETW. Starting the trace session needs SYSTEM or
233 // Administrators, which release builds already require for the driver; unelevated Debug
234 // runs go without hook events
235 if (IsRunningAsAdmin()) {
236 errCode = StartHookEvents();
237 if (errCode != PANO_SUCCESS)
238 {
239 return CleanupWithError(errCode);
240 }
241 }
242 else {
243 std::cerr << "Not running elevated: hook events will not be collected" << std::endl;
244 }
245#pragma endregion
246
248 std::cout << "Shutting down" << std::endl;
249
250 StopService();
251 delete configuration;
253 return 0;
254}
#define PANO_SUCCESS
#define DEBUGGER
#define INVALID_INPUT
#define PANO_SERVICE_STOPPED
#define NOT_ADMIN
#define PANO_SERVICE_RUNNING
#define MUTEX_SET
#define GRPC_SERVER_ERROR
std::vector< std::string > m_fileEvents
The groups of file system events the driver reports, from FileEventNames(). Every group if FileEvents...
void Parse()
Parse the configuration file.
std::vector< std::string > m_dontInject
Processes the driver does not inject the hook DLL into. Each entry is either a file name such as "mse...
ERRORCODE StartContainers()
ERRORCODE StartDetector()
Starts PanoptesDetector.exe from the service's folder with the rules in its rules subfolder,...
ERRORCODE StartKernelService()
Starts the Panoptes driver service. It is installed as demand start, so it is not running after a reb...
Definition driver.cpp:36
ERRORCODE SetInjectionExclusionsInDriver(const std::vector< std::string > &imageNames)
Replaces the driver's list of process image names it does not inject the hook DLL into (IOCTL_PANOPTE...
Definition driver.cpp:84
ERRORCODE GetKernelServiceStatus()
Definition driver.cpp:6
ERRORCODE SetFileEventsInDriver(const std::vector< std::string > &groups)
Tells the driver which groups of file system events to report (IOCTL_PANOPTES_SET_FILE_EVENTS).
Definition driver.cpp:154
ERRORCODE StartDriverEvents(const Configuration *configuration)
Opens the Panoptes driver device and starts the threads that read events from it (IOCTL_PANOPTES_GET_...
PanoptesContext * serviceContext
Definition grpc.cpp:33
VOID RunServiceServer(LPVOID lpParam)
Definition grpc.cpp:598
ERRORCODE StartHookEvents()
Starts a real-time ETW session for the hook DLL's "Panoptes.Hook" TraceLogging provider and a thread ...
ERRORCODE SetEnvironmentMutex()
Definition mutex.cpp:5
ERRORCODE MutexExist()
Definition mutex.cpp:19
ERRORCODE CleanupWithError(ERRORCODE err)
Definition service.cpp:42
#define ERRORCODE
ERRORCODE InitializeShutdown()
Creates the stop event and installs the console handler and session-end window. The stop event can on...
Definition shutdown.cpp:113
void WaitForShutdownRequest()
Blocks until a shutdown is requested.
Definition shutdown.cpp:178
ERRORCODE RequestServiceStop()
Implements –stop: sets a running service's stop event and waits for it to exit.
Definition shutdown.cpp:191
std::string GetExecutableDirectory()
Definition utils.cpp:71
bool IsRunningAsAdmin()
Definition utils.cpp:10
bool HasCommandLineFlag(const char *flag)
Definition utils.cpp:85

References CleanupWithError(), DEBUGGER, DisplayErrorMessage(), ERRORCODE, GetErrorMessage(), GetExecutableDirectory(), GetKernelServiceStatus(), GRPC_SERVER_ERROR, HasCommandLineFlag(), InitializeShutdown(), INVALID_INPUT, IsRunningAsAdmin(), Configuration::m_dontInject, Configuration::m_fileEvents, MUTEX_SET, MutexExist(), NOT_ADMIN, NotifyShutdownComplete(), PANO_SERVICE_RUNNING, PANO_SERVICE_STOPPED, PANO_SUCCESS, Configuration::Parse(), RequestServiceStop(), RunServiceServer(), serviceContext, SetEnvironmentMutex(), SetFileEventsInDriver(), SetInjectionExclusionsInDriver(), StartContainers(), StartDetector(), StartDriverEvents(), StartHookEvents(), StartKernelService(), and WaitForShutdownRequest().