-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathmisc.cpp
More file actions
1913 lines (1635 loc) · 72.1 KB
/
Copy pathmisc.cpp
File metadata and controls
1913 lines (1635 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file src/platform/windows/misc.cpp
* @brief Miscellaneous definitions for Windows.
*/
// standard includes
#include <csignal>
#include <filesystem>
#include <iomanip>
#include <iterator>
#include <set>
#include <sstream>
#include <vector>
// lib includes
#include <boost/algorithm/string.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/process/v1.hpp>
#include <boost/program_options/parsers.hpp>
// prevent clang format from "optimizing" the header include order
// clang-format off
#include <dwmapi.h>
#include <iphlpapi.h>
#include <iterator>
#include <timeapi.h>
#include <UserEnv.h>
#include <WinSock2.h>
#include <Windows.h>
#include <WinUser.h>
#include <wlanapi.h>
#include <WS2tcpip.h>
#include <WtsApi32.h>
#include <sddl.h>
// clang-format on
// Boost overrides NTDDI_VERSION, so we re-override it here
#undef NTDDI_VERSION
/**
* @def NTDDI_VERSION
* @brief Macro for NTDDI VERSION.
*/
#define NTDDI_VERSION NTDDI_WIN10
#include <Shlwapi.h>
// local includes
#include "misc.h"
#include "nvprefs/nvprefs_interface.h"
#include "src/entry_handler.h"
#include "src/globals.h"
#include "src/logging.h"
#include "src/platform/common.h"
#include "src/utility.h"
#include "utf_utils.h"
// UDP_SEND_MSG_SIZE was added in the Windows 10 20H1 SDK
#ifndef UDP_SEND_MSG_SIZE
/**
* @def UDP_SEND_MSG_SIZE
* @brief Macro for UDP SEND MSG SIZE.
*/
#define UDP_SEND_MSG_SIZE 2
#endif
// PROC_THREAD_ATTRIBUTE_JOB_LIST is currently missing from MinGW headers
#ifndef PROC_THREAD_ATTRIBUTE_JOB_LIST
/**
* @def PROC_THREAD_ATTRIBUTE_JOB_LIST
* @brief Macro for PROC THREAD ATTRIBUTE JOB LIST.
*/
#define PROC_THREAD_ATTRIBUTE_JOB_LIST ProcThreadAttributeValue(13, FALSE, TRUE, FALSE)
#endif
#include <qos2.h>
#ifndef WLAN_API_MAKE_VERSION
/**
* @def WLAN_API_MAKE_VERSION(_major, _minor)
* @brief Macro for WLAN API MAKE VERSION.
*/
#define WLAN_API_MAKE_VERSION(_major, _minor) (((DWORD) (_minor)) << 16 | (_major))
#endif
#include <winternl.h>
extern "C" {
/**
* @brief Dynamically resolve NtSetTimerResolution from ntdll.
*
* @param DesiredResolution Desired resolution.
* @param SetResolution Set resolution.
* @param CurrentResolution Current resolution.
* @return NTSTATUS reported by the system timer-resolution request.
*/
NTSTATUS NTAPI NtSetTimerResolution(ULONG DesiredResolution, BOOLEAN SetResolution, PULONG CurrentResolution);
}
namespace {
std::atomic<bool> used_nt_set_timer_resolution = false;
bool nt_set_timer_resolution_max() {
ULONG maximum;
ULONG minimum;
if (ULONG current; !NT_SUCCESS(NtQueryTimerResolution(&minimum, &maximum, ¤t)) || !NT_SUCCESS(NtSetTimerResolution(maximum, TRUE, ¤t))) {
return false;
}
return true;
}
bool nt_set_timer_resolution_min() {
ULONG maximum;
ULONG minimum;
if (ULONG current; !NT_SUCCESS(NtQueryTimerResolution(&minimum, &maximum, ¤t)) || !NT_SUCCESS(NtSetTimerResolution(minimum, TRUE, ¤t))) {
return false;
}
return true;
}
} // namespace
namespace bp = boost::process::v1;
using namespace std::literals;
namespace platf {
/**
* @brief Owning pointer for `GetAdaptersAddresses` results.
*/
using adapteraddrs_t = util::c_ptr<IP_ADAPTER_ADDRESSES>;
bool enabled_mouse_keys = false; ///< Tracks whether Windows Mouse Keys was enabled before Sunshine changed it.
MOUSEKEYS previous_mouse_keys_state; ///< Previous mouse keys state.
HANDLE qos_handle = nullptr; ///< QoS handle.
decltype(QOSCreateHandle) *fn_QOSCreateHandle = nullptr; ///< Fn QoS create handle.
decltype(QOSAddSocketToFlow) *fn_QOSAddSocketToFlow = nullptr; ///< Fn QoS add socket to flow.
decltype(QOSRemoveSocketFromFlow) *fn_QOSRemoveSocketFromFlow = nullptr; ///< Fn QoS remove socket from flow.
HANDLE wlan_handle = nullptr; ///< Wlan handle.
decltype(WlanOpenHandle) *fn_WlanOpenHandle = nullptr; ///< Fn wlan open handle.
decltype(WlanCloseHandle) *fn_WlanCloseHandle = nullptr; ///< Fn wlan close handle.
decltype(WlanFreeMemory) *fn_WlanFreeMemory = nullptr; ///< Fn wlan free memory.
decltype(WlanEnumInterfaces) *fn_WlanEnumInterfaces = nullptr; ///< Fn wlan enum interfaces.
decltype(WlanSetInterface) *fn_WlanSetInterface = nullptr; ///< Fn wlan set interface.
std::filesystem::path appdata() {
WCHAR sunshine_path[MAX_PATH];
GetModuleFileNameW(nullptr, sunshine_path, _countof(sunshine_path));
return std::filesystem::path {sunshine_path}.remove_filename() / L"config"sv;
}
std::string from_sockaddr(const sockaddr *const socket_address) {
char data[INET6_ADDRSTRLEN] = {};
auto family = socket_address->sa_family;
if (family == AF_INET6) {
inet_ntop(AF_INET6, &((sockaddr_in6 *) socket_address)->sin6_addr, data, INET6_ADDRSTRLEN);
} else if (family == AF_INET) {
inet_ntop(AF_INET, &((sockaddr_in *) socket_address)->sin_addr, data, INET_ADDRSTRLEN);
}
return std::string {data};
}
std::pair<std::uint16_t, std::string> from_sockaddr_ex(const sockaddr *const ip_addr) {
char data[INET6_ADDRSTRLEN] = {};
auto family = ip_addr->sa_family;
std::uint16_t port = 0;
if (family == AF_INET6) {
inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN);
port = ((sockaddr_in6 *) ip_addr)->sin6_port;
} else if (family == AF_INET) {
inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN);
port = ((sockaddr_in *) ip_addr)->sin_port;
}
return {port, std::string {data}};
}
/**
* @brief Read Windows adapter addresses with automatic buffer sizing.
*
* @return Adapter-address list populated by GetAdaptersAddresses.
*/
adapteraddrs_t get_adapteraddrs() {
adapteraddrs_t info {nullptr};
ULONG size = 0;
while (GetAdaptersAddresses(AF_UNSPEC, 0, nullptr, info.get(), &size) == ERROR_BUFFER_OVERFLOW) {
info.reset((PIP_ADAPTER_ADDRESSES) malloc(size));
}
return info;
}
std::string get_mac_address(const std::string_view &address) {
adapteraddrs_t info = get_adapteraddrs();
for (auto adapter_pos = info.get(); adapter_pos != nullptr; adapter_pos = adapter_pos->Next) {
for (auto addr_pos = adapter_pos->FirstUnicastAddress; addr_pos != nullptr; addr_pos = addr_pos->Next) {
if (adapter_pos->PhysicalAddressLength != 0 && address == from_sockaddr(addr_pos->Address.lpSockaddr)) {
std::stringstream mac_addr;
mac_addr << std::hex;
for (int i = 0; i < adapter_pos->PhysicalAddressLength; i++) {
if (i > 0) {
mac_addr << ':';
}
mac_addr << std::setw(2) << std::setfill('0') << (int) adapter_pos->PhysicalAddress[i];
}
return mac_addr.str();
}
}
}
BOOST_LOG(warning) << "Unable to find MAC address for "sv << address;
return "00:00:00:00:00:00"s;
}
/**
* @brief Synchronize thread desktop.
*/
HDESK syncThreadDesktop() {
auto hDesk = OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, FALSE, GENERIC_ALL);
if (!hDesk) {
auto err = GetLastError();
BOOST_LOG(error) << "Failed to Open Input Desktop [0x"sv << util::hex(err).to_string_view() << ']';
return nullptr;
}
if (!SetThreadDesktop(hDesk)) {
auto err = GetLastError();
BOOST_LOG(error) << "Failed to sync desktop to thread [0x"sv << util::hex(err).to_string_view() << ']';
}
CloseDesktop(hDesk);
return hDesk;
}
/**
* @brief Write status details to the log.
*/
void print_status(const std::string_view &prefix, HRESULT status) {
char err_string[1024];
DWORD bytes = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, status, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_string, sizeof(err_string), nullptr);
BOOST_LOG(error) << prefix << ": "sv << std::string_view {err_string, bytes};
}
/**
* @brief Check whether a Windows access token belongs to an administrator.
*
* @param user_token Windows access token to inspect.
* @return True when the inspected token has administrator privileges.
*/
bool IsUserAdmin(HANDLE user_token) {
WINBOOL ret;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
ret = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0,
0,
0,
0,
0,
0,
&AdministratorsGroup
);
if (ret) {
if (!CheckTokenMembership(user_token, AdministratorsGroup, &ret)) {
ret = false;
BOOST_LOG(error) << "Failed to verify token membership for administrative access: " << GetLastError();
}
FreeSid(AdministratorsGroup);
} else {
BOOST_LOG(error) << "Unable to allocate SID to check administrative access: " << GetLastError();
}
return ret;
}
/**
* @brief Obtain the current sessions user's primary token with elevated privileges.
* @return The user's token. If user has admin capability it will be elevated, otherwise it will be a limited token. On error, `nullptr`.
*
* @param elevated Whether the command should run with elevated privileges.
*/
HANDLE retrieve_users_token(bool elevated) {
DWORD consoleSessionId;
HANDLE userToken;
TOKEN_ELEVATION_TYPE elevationType;
DWORD dwSize;
// Get the session ID of the active console session
consoleSessionId = WTSGetActiveConsoleSessionId();
if (0xFFFFFFFF == consoleSessionId) {
// If there is no active console session, log a warning and return null
BOOST_LOG(warning) << "There isn't an active user session, therefore it is not possible to execute commands under the users profile.";
return nullptr;
}
// Get the user token for the active console session
if (!WTSQueryUserToken(consoleSessionId, &userToken)) {
BOOST_LOG(debug) << "QueryUserToken failed, this would prevent commands from launching under the users profile.";
return nullptr;
}
// We need to know if this is an elevated token or not.
// Get the elevation type of the user token
// Elevation - Default: User is not an admin, UAC enabled/disabled does not matter.
// Elevation - Limited: User is an admin, has UAC enabled.
// Elevation - Full: User is an admin, has UAC disabled.
if (!GetTokenInformation(userToken, TokenElevationType, &elevationType, sizeof(TOKEN_ELEVATION_TYPE), &dwSize)) {
BOOST_LOG(debug) << "Retrieving token information failed: " << GetLastError();
CloseHandle(userToken);
return nullptr;
}
// User is currently not an administrator
// The documentation for this scenario is conflicting, so we'll double check to see if user is actually an admin.
if (elevated && (elevationType == TokenElevationTypeDefault && !IsUserAdmin(userToken))) {
// We don't have to strip the token or do anything here, but let's give the user a warning so they're aware what is happening.
BOOST_LOG(warning) << "This command requires elevation and the current user account logged in does not have administrator rights. "
<< "For security reasons Sunshine will retain the same access level as the current user and will not elevate it.";
}
// User has a limited token, this means they have UAC enabled and is an Administrator
if (elevated && elevationType == TokenElevationTypeLimited) {
TOKEN_LINKED_TOKEN linkedToken;
// Retrieve the administrator token that is linked to the limited token
if (!GetTokenInformation(userToken, TokenLinkedToken, reinterpret_cast<void *>(&linkedToken), sizeof(TOKEN_LINKED_TOKEN), &dwSize)) {
// If the retrieval failed, log an error message and return null
BOOST_LOG(error) << "Retrieving linked token information failed: " << GetLastError();
CloseHandle(userToken);
// There is no scenario where this should be hit, except for an actual error.
return nullptr;
}
// Since we need the elevated token, we'll replace it with their administrative token.
CloseHandle(userToken);
userToken = linkedToken.LinkedToken;
}
// We don't need to do anything for TokenElevationTypeFull users here, because they're already elevated.
return userToken;
}
/**
* @brief Merge user environment variables into a Windows environment block.
*
* @param env Environment variables for the child process.
* @param shell_token Shell token.
* @return True when the user environment block was merged into `env`.
*/
bool merge_user_environment_block(bp::environment &env, HANDLE shell_token) {
// Get the target user's environment block
PVOID env_block;
if (!CreateEnvironmentBlock(&env_block, shell_token, FALSE)) {
return false;
}
// Parse the environment block and populate env
for (auto c = (PWCHAR) env_block; *c != UNICODE_NULL; c += wcslen(c) + 1) {
// Environment variable entries end with a null-terminator, so std::wstring() will get an entire entry.
std::string env_tuple = utf_utils::to_utf8(std::wstring {c});
std::string env_name = env_tuple.substr(0, env_tuple.find('='));
std::string env_val = env_tuple.substr(env_tuple.find('=') + 1);
// Perform a case-insensitive search to see if this variable name already exists
if (auto itr = std::find_if(env.begin(), env.end(), [&](const auto &e) {
return boost::iequals(e.get_name(), env_name);
});
itr != env.end()) {
// Use this existing name if it is already present to ensure we merge properly
env_name = itr->get_name();
}
// For the PATH variable, we will merge the values together
if (boost::iequals(env_name, "PATH")) {
env[env_name] = env_val + ";" + env[env_name].to_string();
} else {
// Other variables will be superseded by those in the user's environment block
env[env_name] = env_val;
}
}
DestroyEnvironmentBlock(env_block);
return true;
}
/**
* @brief Check if the current process is running with system-level privileges.
* @return `true` if the current process has system-level privileges, `false` otherwise.
*/
bool is_running_as_system() {
BOOL ret;
PSID SystemSid;
DWORD dwSize = SECURITY_MAX_SID_SIZE;
// Allocate memory for the SID structure
SystemSid = LocalAlloc(LMEM_FIXED, dwSize);
if (SystemSid == nullptr) {
BOOST_LOG(error) << "Failed to allocate memory for the SID structure: " << GetLastError();
return false;
}
// Create a SID for the local system account
ret = CreateWellKnownSid(WinLocalSystemSid, nullptr, SystemSid, &dwSize);
if (ret) {
// Check if the current process token contains this SID
if (!CheckTokenMembership(nullptr, SystemSid, &ret)) {
BOOST_LOG(error) << "Failed to check token membership: " << GetLastError();
ret = false;
}
} else {
BOOST_LOG(error) << "Failed to create a SID for the local system account. This may happen if the system is out of memory or if the SID buffer is too small: " << GetLastError();
}
// Free the memory allocated for the SID structure
LocalFree(SystemSid);
return ret;
}
// Note: This does NOT append a null terminator
/**
* @brief Append a null-terminated string to a Windows environment block.
*
* @param env_block Env block.
* @param offset Byte offset used when converting from the wide string buffer.
* @param wstr Wide-character string being converted to UTF-8.
*/
void append_string_to_environment_block(wchar_t *env_block, int &offset, const std::wstring &wstr) {
std::memcpy(&env_block[offset], wstr.data(), wstr.length() * sizeof(wchar_t));
offset += wstr.length();
}
/**
* @brief Create environment block.
*
* @param env Environment variables for the child process.
* @return Created environment block object or status.
*/
std::wstring create_environment_block(const bp::environment &env) {
int size = 0;
for (const auto &entry : env) {
auto name = entry.get_name();
auto value = entry.to_string();
size += utf_utils::from_utf8(name).length() + 1 /* L'=' */ + utf_utils::from_utf8(value).length() + 1 /* L'\0' */;
}
size += 1 /* L'\0' */;
std::vector<wchar_t> env_block(size);
int offset = 0;
for (const auto &entry : env) {
auto name = entry.get_name();
auto value = entry.to_string();
// Construct the NAME=VAL\0 string
append_string_to_environment_block(env_block.data(), offset, utf_utils::from_utf8(name));
env_block[offset] = L'=';
offset++;
append_string_to_environment_block(env_block.data(), offset, utf_utils::from_utf8(value));
env_block[offset] = L'\0';
offset++;
}
// Append a final null terminator
env_block[offset] = L'\0';
offset++;
return std::wstring(env_block.data(), offset);
}
/**
* @brief Allocate and initialize a Windows process-thread attribute list.
*
* @param attribute_count Attribute count.
* @return Initialized attribute list, or nullptr when allocation fails.
*/
LPPROC_THREAD_ATTRIBUTE_LIST allocate_proc_thread_attr_list(DWORD attribute_count) {
SIZE_T size;
InitializeProcThreadAttributeList(nullptr, attribute_count, 0, &size);
auto list = (LPPROC_THREAD_ATTRIBUTE_LIST) HeapAlloc(GetProcessHeap(), 0, size);
if (list == nullptr) {
return nullptr;
}
if (!InitializeProcThreadAttributeList(list, attribute_count, 0, &size)) {
HeapFree(GetProcessHeap(), 0, list);
return nullptr;
}
return list;
}
/**
* @brief Release proc thread attr list resources.
*
* @param list Multi-string list returned by the Windows API.
*/
void free_proc_thread_attr_list(LPPROC_THREAD_ATTRIBUTE_LIST list) {
DeleteProcThreadAttributeList(list);
HeapFree(GetProcessHeap(), 0, list);
}
/**
* @brief Create a `bp::child` object from the results of launching a process.
* @param process_launched A boolean indicating if the launch was successful.
* @param cmd The command that was used to launch the process.
* @param ec A reference to an `std::error_code` object that will store any error that occurred during the launch.
* @param process_info A reference to a `PROCESS_INFORMATION` structure that contains information about the new process.
* @return A `bp::child` object representing the new process, or an empty `bp::child` object if the launch failed.
*/
bp::child create_boost_child_from_results(bool process_launched, const std::string &cmd, std::error_code &ec, PROCESS_INFORMATION &process_info) {
// Use RAII to ensure the process is closed when we're done with it, even if there was an error.
auto close_process_handles = util::fail_guard([process_launched, process_info]() {
if (process_launched) {
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
}
});
if (ec) {
// If there was an error, return an empty bp::child object
return bp::child();
}
if (process_launched) {
// If the launch was successful, create a new bp::child object representing the new process
auto child = bp::child((bp::pid_t) process_info.dwProcessId);
BOOST_LOG(info) << cmd << " running with PID "sv << child.id();
return child;
} else {
auto winerror = GetLastError();
BOOST_LOG(error) << "Failed to launch process: "sv << winerror;
ec = std::make_error_code(std::errc::invalid_argument);
// We must NOT attach the failed process here, since this case can potentially be induced by ACL
// manipulation (denying yourself execute permission) to cause an escalation of privilege.
// So to protect ourselves against that, we'll return an empty child process instead.
return bp::child();
}
}
/**
* @brief Impersonate the current user and invoke the callback function.
* @param user_token A handle to the user's token that was obtained from the shell.
* @param callback A function that will be executed while impersonating the user.
* @return Object that will store any error that occurred during the impersonation
*/
std::error_code impersonate_current_user(HANDLE user_token, std::function<void()> callback) {
std::error_code ec;
// Impersonate the user when launching the process. This will ensure that appropriate access
// checks are done against the user token, not our SYSTEM token. It will also allow network
// shares and mapped network drives to be used as launch targets, since those credentials
// are stored per-user.
if (!ImpersonateLoggedOnUser(user_token)) {
auto winerror = GetLastError();
// Log the failure of impersonating the user and its error code
BOOST_LOG(error) << "Failed to impersonate user: "sv << winerror;
ec = std::make_error_code(std::errc::permission_denied);
return ec;
}
// Execute the callback function while impersonating the user
callback();
// End impersonation of the logged on user. If this fails (which is extremely unlikely),
// we will be running with an unknown user token. The only safe thing to do in that case
// is terminate ourselves.
if (!RevertToSelf()) {
auto winerror = GetLastError();
// Log the failure of reverting to self and its error code
BOOST_LOG(fatal) << "Failed to revert to self after impersonation: "sv << winerror;
DebugBreak();
}
return ec;
}
/**
* @brief Create a `STARTUPINFOEXW` structure for launching a process.
* @param file A pointer to a `FILE` object that will be used as the standard output and error for the new process, or null if not needed.
* @param job A job object handle to insert the new process into. This pointer must remain valid for the life of this startup info!
* @param ec A reference to a `std::error_code` object that will store any error that occurred during the creation of the structure.
* @return A structure that contains information about how to launch the new process.
*/
STARTUPINFOEXW create_startup_info(FILE *file, HANDLE *job, std::error_code &ec) {
// Initialize a zeroed-out STARTUPINFOEXW structure and set its size
STARTUPINFOEXW startup_info = {};
startup_info.StartupInfo.cb = sizeof(startup_info);
// Allocate a process attribute list with space for 2 elements
startup_info.lpAttributeList = allocate_proc_thread_attr_list(2);
if (startup_info.lpAttributeList == nullptr) {
// If the allocation failed, set ec to an appropriate error code and return the structure
ec = std::make_error_code(std::errc::not_enough_memory);
return startup_info;
}
if (file) {
// If a file was provided, get its handle and use it as the standard output and error for the new process
HANDLE log_file_handle = (HANDLE) _get_osfhandle(_fileno(file));
// Populate std handles if the caller gave us a log file to use
startup_info.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
startup_info.StartupInfo.hStdInput = nullptr;
startup_info.StartupInfo.hStdOutput = log_file_handle;
startup_info.StartupInfo.hStdError = log_file_handle;
// Allow the log file handle to be inherited by the child process (without inheriting all of
// our inheritable handles, such as our own log file handle created by SunshineSvc).
//
// Note: The value we point to here must be valid for the lifetime of the attribute list,
// so we need to point into the STARTUPINFO instead of our log_file_variable on the stack.
UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &startup_info.StartupInfo.hStdOutput, sizeof(startup_info.StartupInfo.hStdOutput), nullptr, nullptr);
}
if (job) {
// Atomically insert the new process into the specified job.
//
// Note: The value we point to here must be valid for the lifetime of the attribute list,
// so we take a HANDLE* instead of just a HANDLE to use the caller's stack storage.
UpdateProcThreadAttribute(startup_info.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, job, sizeof(*job), nullptr, nullptr);
}
return startup_info;
}
/**
* @brief This function overrides HKEY_CURRENT_USER and HKEY_CLASSES_ROOT using the provided token.
* @param token The primary token identifying the user to use, or `nullptr` to restore original keys.
* @return `true` if the override or restore operation was successful.
*/
bool override_per_user_predefined_keys(HANDLE token) {
HKEY user_classes_root = nullptr;
if (token) {
auto err = RegOpenUserClassesRoot(token, 0, GENERIC_ALL, &user_classes_root);
if (err != ERROR_SUCCESS) {
BOOST_LOG(error) << "Failed to open classes root for target user: "sv << err;
return false;
}
}
auto close_classes_root = util::fail_guard([user_classes_root]() {
if (user_classes_root) {
RegCloseKey(user_classes_root);
}
});
HKEY user_key = nullptr;
if (token) {
impersonate_current_user(token, [&]() {
// RegOpenCurrentUser() doesn't take a token. It assumes we're impersonating the desired user.
auto err = RegOpenCurrentUser(GENERIC_ALL, &user_key);
if (err != ERROR_SUCCESS) {
BOOST_LOG(error) << "Failed to open user key for target user: "sv << err;
user_key = nullptr;
}
});
if (!user_key) {
return false;
}
}
auto close_user = util::fail_guard([user_key]() {
if (user_key) {
RegCloseKey(user_key);
}
});
auto err = RegOverridePredefKey(HKEY_CLASSES_ROOT, user_classes_root);
if (err != ERROR_SUCCESS) {
BOOST_LOG(error) << "Failed to override HKEY_CLASSES_ROOT: "sv << err;
return false;
}
err = RegOverridePredefKey(HKEY_CURRENT_USER, user_key);
if (err != ERROR_SUCCESS) {
BOOST_LOG(error) << "Failed to override HKEY_CURRENT_USER: "sv << err;
RegOverridePredefKey(HKEY_CLASSES_ROOT, nullptr);
return false;
}
return true;
}
/**
* @brief Quote/escape an argument according to the Windows parsing convention.
* @param argument The raw argument to process.
* @return An argument string suitable for use by CreateProcess().
*/
std::wstring escape_argument(const std::wstring &argument) {
// If there are no characters requiring quoting/escaping, we're done
if (argument.find_first_of(L" \t\n\v\"") == argument.npos) {
return argument;
}
// The algorithm implemented here comes from a MSDN blog post:
// https://web.archive.org/web/20120201194949/http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
std::wstring escaped_arg;
escaped_arg.push_back(L'"');
for (auto it = argument.begin();; it++) {
auto backslash_count = 0U;
while (it != argument.end() && *it == L'\\') {
it++;
backslash_count++;
}
if (it == argument.end()) {
escaped_arg.append(backslash_count * 2, L'\\');
break;
} else if (*it == L'"') {
escaped_arg.append(backslash_count * 2 + 1, L'\\');
} else {
escaped_arg.append(backslash_count, L'\\');
}
escaped_arg.push_back(*it);
}
escaped_arg.push_back(L'"');
return escaped_arg;
}
/**
* @brief Escape an argument according to cmd's parsing convention.
* @param argument An argument already escaped by `escape_argument()`.
* @return An argument string suitable for use by cmd.exe.
*/
std::wstring escape_argument_for_cmd(const std::wstring &argument) {
// Start with the original string and modify from there
std::wstring escaped_arg = argument;
// Look for the next cmd metacharacter
size_t match_pos = 0;
while ((match_pos = escaped_arg.find_first_of(L"()%!^\"<>&|", match_pos)) != std::wstring::npos) {
// Insert an escape character and skip past the match
escaped_arg.insert(match_pos, 1, L'^');
match_pos += 2;
}
return escaped_arg;
}
/**
* @brief Resolve the given raw command into a proper command string for CreateProcess().
* @details This converts URLs and non-executable file paths into a runnable command like ShellExecute().
* @param raw_cmd The raw command provided by the user.
* @param working_dir The working directory for the new process.
* @param token The user token currently being impersonated or `nullptr` if running as ourselves.
* @param creation_flags The creation flags for CreateProcess(), which may be modified by this function.
* @return A command string suitable for use by CreateProcess().
*/
std::wstring resolve_command_string(const std::string &raw_cmd, const std::wstring &working_dir, HANDLE token, DWORD &creation_flags) {
std::wstring raw_cmd_w = utf_utils::from_utf8(raw_cmd);
// First, convert the given command into parts so we can get the executable/file/URL without parameters
auto raw_cmd_parts = boost::program_options::split_winmain(raw_cmd_w);
if (raw_cmd_parts.empty()) {
// This is highly unexpected, but we'll just return the raw string and hope for the best.
BOOST_LOG(warning) << "Failed to split command string: "sv << raw_cmd;
return utf_utils::from_utf8(raw_cmd);
}
auto raw_target = raw_cmd_parts.at(0);
std::wstring lookup_string;
HRESULT res;
if (PathIsURLW(raw_target.c_str())) {
std::array<WCHAR, 128> scheme;
DWORD out_len = scheme.size();
res = UrlGetPartW(raw_target.c_str(), scheme.data(), &out_len, URL_PART_SCHEME, 0);
if (res != S_OK) {
BOOST_LOG(warning) << "Failed to extract URL scheme from URL: "sv << raw_target << " ["sv << util::hex(res).to_string_view() << ']';
return utf_utils::from_utf8(raw_cmd);
}
// If the target is a URL, the class is found using the URL scheme (prior to and not including the ':')
lookup_string = scheme.data();
} else {
// If the target is not a URL, assume it's a regular file path
auto extension = PathFindExtensionW(raw_target.c_str());
if (extension == nullptr || *extension == 0) {
// If the file has no extension, assume it's a command and allow CreateProcess()
// to try to find it via PATH
return utf_utils::from_utf8(raw_cmd);
} else if (boost::iequals(extension, L".exe")) {
// If the file has an .exe extension, we will bypass the resolution here and
// directly pass the unmodified command string to CreateProcess(). The argument
// escaping rules are subtly different between CreateProcess() and ShellExecute(),
// and we want to preserve backwards compatibility with older configs.
return utf_utils::from_utf8(raw_cmd);
}
// For regular files, the class is found using the file extension (including the dot)
lookup_string = extension;
}
std::array<WCHAR, MAX_PATH> shell_command_string;
bool needs_cmd_escaping = false;
{
// Overriding these predefined keys affects process-wide state, so serialize all calls
// to ensure the handle state is consistent while we perform the command query.
static std::mutex per_user_key_mutex;
auto lg = std::lock_guard(per_user_key_mutex);
// Override HKEY_CLASSES_ROOT and HKEY_CURRENT_USER to ensure we query the correct class info
if (!override_per_user_predefined_keys(token)) {
return utf_utils::from_utf8(raw_cmd);
}
// Find the command string for the specified class
DWORD out_len = shell_command_string.size();
res = AssocQueryStringW(ASSOCF_NOTRUNCATE, ASSOCSTR_COMMAND, lookup_string.c_str(), L"open", shell_command_string.data(), &out_len);
// In some cases (UWP apps), we might not have a command for this target. If that happens,
// we'll have to launch via cmd.exe. This prevents proper job tracking, but that was already
// broken for UWP apps anyway due to how they are started by Windows. Even 'start /wait'
// doesn't work properly for UWP, so really no termination tracking seems to work at all.
//
// FIXME: Maybe we can improve this in the future.
if (res == HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) {
BOOST_LOG(warning) << "Using trampoline to handle target: "sv << raw_cmd;
std::wcscpy(shell_command_string.data(), L"cmd.exe /c start \"\" /wait \"%1\" %*");
needs_cmd_escaping = true;
// We must suppress the console window that would otherwise appear when starting cmd.exe.
creation_flags &= ~CREATE_NEW_CONSOLE;
creation_flags |= CREATE_NO_WINDOW;
res = S_OK;
}
// Reset per-user keys back to the original value
override_per_user_predefined_keys(nullptr);
}
if (res != S_OK) {
BOOST_LOG(warning) << "Failed to query command string for raw command: "sv << raw_cmd << " ["sv << util::hex(res).to_string_view() << ']';
return utf_utils::from_utf8(raw_cmd);
}
// Finally, construct the real command string that will be passed into CreateProcess().
// We support common substitutions (%*, %1, %2, %L, %W, %V, etc), but there are other
// uncommon ones that are unsupported here.
//
// https://web.archive.org/web/20111002101214/http://msdn.microsoft.com/en-us/library/windows/desktop/cc144101(v=vs.85).aspx
std::wstring cmd_string {shell_command_string.data()};
size_t match_pos = 0;
while ((match_pos = cmd_string.find_first_of(L'%', match_pos)) != std::wstring::npos) {
std::wstring match_replacement;
// If no additional character exists after the match, the dangling '%' is stripped
if (match_pos + 1 == cmd_string.size()) {
cmd_string.erase(match_pos, 1);
break;
}
// Shell command replacements are strictly '%' followed by a single non-'%' character
auto next_char = std::tolower(cmd_string.at(match_pos + 1));
switch (next_char) {
// Escape character
case L'%':
match_replacement = L'%';
break;
// Argument replacements
case L'0':
case L'1':
case L'2':
case L'3':
case L'4':
case L'5':
case L'6':
case L'7':
case L'8':
case L'9':
{
// Arguments numbers are 1-based, except for %0 which is equivalent to %1
int index = next_char - L'0';
if (next_char != L'0') {
index--;
}
// Replace with the matching argument, or nothing if the index is invalid
if (index < raw_cmd_parts.size()) {
match_replacement = raw_cmd_parts.at(index);
}
break;
}
// All arguments following the target
case L'*':
for (int i = 1; i < raw_cmd_parts.size(); i++) {
// Insert a space before arguments after the first one
if (i > 1) {
match_replacement += L' ';
}
// Argument escaping applies only to %*, not the single substitutions like %2
auto escaped_argument = escape_argument(raw_cmd_parts.at(i));
if (needs_cmd_escaping) {
// If we're using the cmd.exe trampoline, we'll need to add additional escaping
escaped_argument = escape_argument_for_cmd(escaped_argument);
}
match_replacement += escaped_argument;
}
break;
// Long file path of target
case L'l':
case L'd':
case L'v':
{
std::array<WCHAR, MAX_PATH> path;
std::array<PCWCHAR, 2> other_dirs {working_dir.c_str(), nullptr};
// PathFindOnPath() is a little gross because it uses the same
// buffer for input and output, so we need to copy our input
// into the path array.
std::wcsncpy(path.data(), raw_target.c_str(), path.size());
if (path[path.size() - 1] != 0) {
// The path was so long it was truncated by this copy. We'll
// assume it was an absolute path (likely) and use it unmodified.
match_replacement = raw_target;
}
// See if we can find the path on our search path or working directory
else if (PathFindOnPathW(path.data(), other_dirs.data())) {
match_replacement = std::wstring {path.data()};
} else {
// We couldn't find the target, so we'll just hope for the best
match_replacement = raw_target;
}
break;
}
// Working directory
case L'w':
match_replacement = working_dir;
break;
default:
BOOST_LOG(warning) << "Unsupported argument replacement: %%" << next_char;
break;
}
// Replace the % and following character with the match replacement
cmd_string.replace(match_pos, 2, match_replacement);
// Skip beyond the match replacement itself to prevent recursive replacement
match_pos += match_replacement.size();
}
BOOST_LOG(info) << "Resolved user-provided command '"sv << raw_cmd << "' to '"sv << cmd_string << '\'';
return cmd_string;
}
/**
* @brief Run a command on the users profile.
*
* Launches a child process as the user, using the current user's environment and a specific working directory.
*
* @param elevated Specify whether to elevate the process.
* @param interactive Specify whether this will run in a window or hidden.
* @param cmd The command to run.
* @param working_dir The working directory for the new process.
* @param env The environment variables to use for the new process.
* @param file A file object to redirect the child process's output to (may be `nullptr`).
* @param ec An error code, set to indicate any errors that occur during the launch process.
* @param group A pointer to a `bp::group` object to which the new process should belong (may be `nullptr`).
* @return A `bp::child` object representing the new process, or an empty `bp::child` object if the launch fails.
*/
bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) {
std::wstring start_dir = utf_utils::from_utf8(working_dir.string());
HANDLE job = group ? group->native_handle() : nullptr;
STARTUPINFOEXW startup_info = create_startup_info(file, job ? &job : nullptr, ec);
PROCESS_INFORMATION process_info;
// Clone the environment to create a local copy. Boost.Process (bp) shares the environment with all spawned processes.
// Since we're going to modify the 'env' variable by merging user-specific environment variables into it,
// we make a clone to prevent side effects to the shared environment.
bp::environment cloned_env = env;
if (ec) {
// In the event that startup_info failed, return a blank child process.
return bp::child();
}
// Use RAII to ensure the attribute list is freed when we're done with it
auto attr_list_free = util::fail_guard([list = startup_info.lpAttributeList]() {
free_proc_thread_attr_list(list);
});