Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
shutdown.cpp
Go to the documentation of this file.
1#include "shutdown.h"
2#include "error_message.h"
3#include "mutex.hpp"
4#include "utils.h"
5#include <sddl.h>
6#include <iostream>
7#include <thread>
8
9#pragma comment(lib, "advapi32.lib")
10
11// Session-local, like the service mutex, so "--stop" works from the session the service was
12// started in
13#define PANO_STOP_EVENT_NAME L"PanoptesStop"
14
15// How long --stop waits for the service to exit after setting its stop event
16#define PANO_STOP_EXIT_WAIT_MS 15000
17
18#define PANO_SHUTDOWN_WINDOW_CLASS L"PanoptesShutdownWindow"
19
20static HANDLE g_StopEvent = NULL;
21static HANDLE g_ShutdownComplete = NULL;
22
23static void RequestShutdown()
24{
25 if (g_StopEvent != NULL)
26 {
27 SetEvent(g_StopEvent);
28 }
29}
30
31// Requests shutdown and holds off the end of the process until teardown has finished
32static void RequestShutdownAndWait()
33{
34 RequestShutdown();
35 WaitForSingleObject(g_ShutdownComplete, PANO_SHUTDOWN_WAIT_MS);
36}
37
38#pragma region Console Handler
39
40static BOOL WINAPI ConsoleHandler(DWORD controlType)
41{
42 switch (controlType)
43 {
44 case CTRL_C_EVENT:
45 case CTRL_BREAK_EVENT:
46 // The process keeps running after these return, so there is nothing to wait for
47 RequestShutdown();
48 return TRUE;
49 case CTRL_CLOSE_EVENT:
50 case CTRL_LOGOFF_EVENT:
51 case CTRL_SHUTDOWN_EVENT:
52 RequestShutdownAndWait();
53 return TRUE;
54 default:
55 return FALSE;
56 }
57}
58
59#pragma endregion
60
61#pragma region Session End Window
62
63static LRESULT CALLBACK ShutdownWindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
64{
65 switch (message)
66 {
67 case WM_QUERYENDSESSION:
68 return TRUE;
69 case WM_ENDSESSION:
70 // wParam is FALSE when the session end was cancelled
71 if (wParam)
72 {
73 RequestShutdownAndWait();
74 }
75 return 0;
76 default:
77 return DefWindowProcW(window, message, wParam, lParam);
78 }
79}
80
81// Owns the hidden window and pumps its messages for the life of the process. The window is
82// top-level rather than message-only because message-only windows do not receive the
83// WM_QUERYENDSESSION and WM_ENDSESSION broadcasts
84static void ShutdownWindowThread(HANDLE ready, HWND *created)
85{
86 HINSTANCE instance = GetModuleHandleW(NULL);
87
88 WNDCLASSW windowClass{};
89 windowClass.lpfnWndProc = ShutdownWindowProc;
90 windowClass.hInstance = instance;
91 windowClass.lpszClassName = PANO_SHUTDOWN_WINDOW_CLASS;
92 RegisterClassW(&windowClass);
93
94 // Never shown
95 *created = CreateWindowExW(0, PANO_SHUTDOWN_WINDOW_CLASS, L"Panoptes", 0,
96 0, 0, 0, 0, NULL, NULL, instance, NULL);
97 SetEvent(ready);
98 if (*created == NULL)
99 {
100 return;
101 }
102
103 MSG message;
104 while (GetMessageW(&message, NULL, 0, 0) > 0)
105 {
106 TranslateMessage(&message);
107 DispatchMessageW(&message);
108 }
109}
110
111#pragma endregion
112
114{
115 // Elevated, the event is restricted to SYSTEM and Administrators so an unelevated process
116 // cannot stop the service. Unelevated Debug runs use the default security so --stop still
117 // works from the same user
118 SECURITY_ATTRIBUTES security{ sizeof(security), NULL, FALSE };
119 PSECURITY_DESCRIPTOR descriptor = NULL;
120 if (IsRunningAsAdmin())
121 {
122 if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;GA;;;SY)(A;;GA;;;BA)",
123 SDDL_REVISION_1, &descriptor, NULL))
124 {
125 return WINDOWS_ERR;
126 }
127 security.lpSecurityDescriptor = descriptor;
128 }
129
130 g_StopEvent = CreateEventW(&security, TRUE, FALSE, PANO_STOP_EVENT_NAME);
131 DWORD error = GetLastError();
132 if (descriptor != NULL)
133 {
134 LocalFree(descriptor);
135 }
136 if (g_StopEvent == NULL)
137 {
138 std::cerr << "Failed to create the stop event. Error code: " << error << std::endl;
139 return WINDOWS_ERR;
140 }
141 if (error == ERROR_ALREADY_EXISTS)
142 {
143 // Named objects disappear with their last handle, so another process is holding one
144 // with this name, possibly to stop the service through it. Do not use it
145 std::cerr << "The stop event already exists in another process" << std::endl;
146 CloseHandle(g_StopEvent);
147 g_StopEvent = NULL;
148 return WINDOWS_ERR;
149 }
150
151 g_ShutdownComplete = CreateEventW(NULL, TRUE, FALSE, NULL);
152 if (g_ShutdownComplete == NULL)
153 {
154 return WINDOWS_ERR;
155 }
156
157 SetConsoleCtrlHandler(ConsoleHandler, TRUE);
158
159 HANDLE ready = CreateEventW(NULL, TRUE, FALSE, NULL);
160 if (ready == NULL)
161 {
162 return WINDOWS_ERR;
163 }
164 HWND window = NULL;
165 std::thread(ShutdownWindowThread, ready, &window).detach();
166 WaitForSingleObject(ready, INFINITE);
167 CloseHandle(ready);
168
169 if (window == NULL)
170 {
171 std::cerr << "Failed to create the session end window" << std::endl;
172 return WINDOWS_ERR;
173 }
174
175 return PANO_SUCCESS;
176}
177
179{
180 WaitForSingleObject(g_StopEvent, INFINITE);
181}
182
184{
185 if (g_ShutdownComplete != NULL)
186 {
187 SetEvent(g_ShutdownComplete);
188 }
189}
190
192{
193 HANDLE stopEvent = OpenEventW(EVENT_MODIFY_STATE, FALSE, PANO_STOP_EVENT_NAME);
194 if (stopEvent == NULL)
195 {
196 DWORD error = GetLastError();
197 if (error == ERROR_ACCESS_DENIED)
198 {
199 return NOT_ADMIN;
200 }
201 std::cerr << "Panoptes is not running" << std::endl;
202 return WINDOWS_ERR;
203 }
204
205 SetEvent(stopEvent);
206 CloseHandle(stopEvent);
207
208 // The service holds the mutex until the end of its teardown
209 ULONGLONG deadline = GetTickCount64() + PANO_STOP_EXIT_WAIT_MS;
210 while (GetTickCount64() < deadline)
211 {
212 HANDLE mutex = OpenMutexA(SYNCHRONIZE, FALSE, SERVICE_MUTEX);
213 if (mutex == NULL)
214 {
215 return PANO_SUCCESS;
216 }
217 CloseHandle(mutex);
218 Sleep(100);
219 }
220
221 std::cerr << "Panoptes did not stop within " << PANO_STOP_EXIT_WAIT_MS / 1000 << " seconds" << std::endl;
222 return WINDOWS_ERR;
223}
#define PANO_SUCCESS
#define NOT_ADMIN
#define WINDOWS_ERR
#define ERRORCODE
#define SERVICE_MUTEX
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
#define PANO_STOP_EXIT_WAIT_MS
Definition shutdown.cpp:16
void NotifyShutdownComplete()
Tells console handlers and the session-end window that teardown has finished, so they can return and ...
Definition shutdown.cpp:183
#define PANO_SHUTDOWN_WINDOW_CLASS
Definition shutdown.cpp:18
#define PANO_STOP_EVENT_NAME
Definition shutdown.cpp:13
#define PANO_SHUTDOWN_WAIT_MS
Definition shutdown.h:15
bool IsRunningAsAdmin()
Definition utils.cpp:10