Debian Codegraph @

src/daemonizer/windows_service.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include <boost/chrono/chrono.hpp>
30 #include <boost/thread/thread.hpp>
31
32 #undef UNICODE
33 #undef _UNICODE
34
35 #include "common/scoped_message_writer.h"
36 #include "daemonizer/windows_service.h"
37 #include "string_tools.h"
38 #include <chrono>
39 #include <iostream>
40 #include <utility>
41 #include <memory>
42 #include <shellapi.h>
43 #include <thread>
44 #include <windows.h>
45
46 namespace windows {
47
48 namespace {
49 typedef std::unique_ptr<std::remove_pointer<SC_HANDLE>::type, decltype(&::CloseServiceHandle)> service_handle;
50
51 std::string get_last_error()
52 {
53 LPSTR p_error_text = nullptr;
54
55 FormatMessage(
56 FORMAT_MESSAGE_FROM_SYSTEM
57 | FORMAT_MESSAGE_ALLOCATE_BUFFER
58 | FORMAT_MESSAGE_IGNORE_INSERTS
59 , nullptr
60 , GetLastError()
61 , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)
62 , reinterpret_cast<LPSTR>(&p_error_text)
63 , 0
64 , nullptr
65 );
66
67 if (nullptr == p_error_text)
68 {
69 return "";
70 }
71 else
72 {
73 std::string ret{p_error_text};
74 LocalFree(p_error_text);
75 return ret;
76 }
77 }
78
79 bool relaunch_as_admin(
80 std::string const & command
81 , std::string const & arguments
82 )
83 {
84 SHELLEXECUTEINFO info{};
85 info.cbSize = sizeof(info);
86 info.lpVerb = "runas";
87 info.lpFile = command.c_str();
88 info.lpParameters = arguments.c_str();
89 info.hwnd = nullptr;
90 info.nShow = SW_SHOWNORMAL;
91 if (!ShellExecuteEx(&info))
92 {
93 tools::fail_msg_writer() << "Admin relaunch failed: " << get_last_error();
94 return false;
95 }
96 else
97 {
98 return true;
99 }
100 }
101
102 // When we relaunch as admin, Windows opens a new window. This just pauses
103 // to allow the user to read any output.
104 void pause_to_display_admin_window_messages()
105 {
106 boost::chrono::milliseconds how_long{1500};
107 boost::this_thread::sleep_for(how_long);
108 }
109 }
110
111 bool check_admin(bool & result)
112 {
113 BOOL is_admin = FALSE;
114 PSID p_administrators_group = nullptr;
115
116 SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY;
117
118 if (!AllocateAndInitializeSid(
119 &nt_authority
120 , 2
121 , SECURITY_BUILTIN_DOMAIN_RID
122 , DOMAIN_ALIAS_RID_ADMINS
123 , 0, 0, 0, 0, 0, 0
124 , &p_administrators_group
125 ))
126 {
127 tools::fail_msg_writer() << "Security Identifier creation failed: " << get_last_error();
128 return false;
129 }
130
131 if (!CheckTokenMembership(
132 nullptr
133 , p_administrators_group
134 , &is_admin
135 ))
136 {
137 tools::fail_msg_writer() << "Permissions check failed: " << get_last_error();
138 return false;
139 }
140
141 result = is_admin ? true : false;
142
143 return true;
144 }
145
146 bool ensure_admin(
147 std::string const & arguments
148 )
149 {
150 bool admin;
151
152 if (!check_admin(admin))
153 {
154 return false;
155 }
156
157 if (admin)
158 {
159 return true;
160 }
161 else
162 {
163 std::string command = epee::string_tools::get_current_module_path();
164 relaunch_as_admin(command, arguments);
165 return false;
166 }
167 }
168
169 bool install_service(
170 std::string const & service_name
171 , std::string const & arguments
172 )
173 {
174 std::string command = epee::string_tools::get_current_module_path();
175 std::string full_command = "\"" + command + "\"" + arguments;
176
177 service_handle p_manager{
178 OpenSCManager(
179 nullptr
180 , nullptr
181 , SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE
182 )
183 , &::CloseServiceHandle
184 };
185 if (p_manager == nullptr)
186 {
187 tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error();
188 return false;
189 }
190
191 service_handle p_service{
192 CreateService(
193 p_manager.get()
194 , service_name.c_str()
195 , service_name.c_str()
196 , 0
197 //, GENERIC_EXECUTE | GENERIC_READ
198 , SERVICE_WIN32_OWN_PROCESS
199 , SERVICE_DEMAND_START
200 , SERVICE_ERROR_NORMAL
201 , full_command.c_str()
202 , nullptr
203 , nullptr
204 , ""
205 //, "NT AUTHORITY\\LocalService"
206 , nullptr // Implies LocalSystem account
207 , nullptr
208 )
209 , &::CloseServiceHandle
210 };
211 if (p_service == nullptr)
212 {
213 tools::fail_msg_writer() << "Couldn't create service: " << get_last_error();
214 return false;
215 }
216
217 tools::success_msg_writer() << "Service installed";
218
219 pause_to_display_admin_window_messages();
220
221 return true;
222 }
223
224 bool start_service(
225 std::string const & service_name
226 )
227 {
228 tools::msg_writer() << "Starting service";
229
230 SERVICE_STATUS_PROCESS service_status = {};
231 DWORD unused = 0;
232
233 service_handle p_manager{
234 OpenSCManager(
235 nullptr
236 , nullptr
237 , SC_MANAGER_CONNECT
238 )
239 , &::CloseServiceHandle
240 };
241 if (p_manager == nullptr)
242 {
243 tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error();
244 return false;
245 }
246
247 service_handle p_service{
248 OpenService(
249 p_manager.get()
250 , service_name.c_str()
251 //, SERVICE_START | SERVICE_QUERY_STATUS
252 , SERVICE_START
253 )
254 , &::CloseServiceHandle
255 };
256 if (p_service == nullptr)
257 {
258 tools::fail_msg_writer() << "Couldn't find service: " << get_last_error();
259 return false;
260 }
261
262 if (!StartService(
263 p_service.get()
264 , 0
265 , nullptr
266 ))
267 {
268 tools::fail_msg_writer() << "Service start request failed: " << get_last_error();
269 return false;
270 }
271
272 tools::success_msg_writer() << "Service started";
273
274 pause_to_display_admin_window_messages();
275
276 return true;
277 }
278
279 bool stop_service(
280 std::string const & service_name
281 )
282 {
283 tools::msg_writer() << "Stopping service";
284
285 service_handle p_manager{
286 OpenSCManager(
287 nullptr
288 , nullptr
289 , SC_MANAGER_CONNECT
290 )
291 , &::CloseServiceHandle
292 };
293 if (p_manager == nullptr)
294 {
295 tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error();
296 return false;
297 }
298
299 service_handle p_service{
300 OpenService(
301 p_manager.get()
302 , service_name.c_str()
303 , SERVICE_STOP | SERVICE_QUERY_STATUS
304 )
305 , &::CloseServiceHandle
306 };
307 if (p_service == nullptr)
308 {
309 tools::fail_msg_writer() << "Couldn't find service: " << get_last_error();
310 return false;
311 }
312
313 SERVICE_STATUS status = {};
314 if (!ControlService(p_service.get(), SERVICE_CONTROL_STOP, &status))
315 {
316 tools::fail_msg_writer() << "Couldn't request service stop: " << get_last_error();
317 return false;
318 }
319
320 tools::success_msg_writer() << "Service stopped";
321
322 pause_to_display_admin_window_messages();
323
324 return true;
325 }
326
327 bool uninstall_service(
328 std::string const & service_name
329 )
330 {
331 service_handle p_manager{
332 OpenSCManager(
333 nullptr
334 , nullptr
335 , SC_MANAGER_CONNECT
336 )
337 , &::CloseServiceHandle
338 };
339 if (p_manager == nullptr)
340 {
341 tools::fail_msg_writer() << "Couldn't connect to service manager: " << get_last_error();
342 return false;
343 }
344
345 service_handle p_service{
346 OpenService(
347 p_manager.get()
348 , service_name.c_str()
349 , SERVICE_QUERY_STATUS | DELETE
350 )
351 , &::CloseServiceHandle
352 };
353 if (p_service == nullptr)
354 {
355 tools::fail_msg_writer() << "Couldn't find service: " << get_last_error();
356 return false;
357 }
358
359 SERVICE_STATUS status = {};
360 if (!DeleteService(p_service.get()))
361 {
362 tools::fail_msg_writer() << "Couldn't uninstall service: " << get_last_error();
363 return false;
364 }
365
366 tools::success_msg_writer() << "Service uninstalled";
367
368 pause_to_display_admin_window_messages();
369
370 return true;
371 }
372
373 } // namespace windows