-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathcreateprocess.cpp
3849 lines (3096 loc) · 116 KB
/
createprocess.cpp
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
// A simple program whose sole job is to run custom CreateProcess() commands.
// Useful for executing programs from batch files that don't play nice (e.g. Apache)
// or working around limitations in scripting languages.
//
// (C) 2021 CubicleSoft. All Rights Reserved.
#define UNICODE
#define _UNICODE
#define _CRT_SECURE_NO_WARNINGS
#ifdef _MBCS
#undef _MBCS
#endif
#include <cstdio>
#include <cstdlib>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <tlhelp32.h>
#include <winternl.h>
#include <lm.h>
#include <sddl.h>
//#include <ntsecapi.h>
//#include <wincred.h>
#include <userenv.h>
#include <tchar.h>
#include "templates/static_wc_mixed_var.h"
#include "templates/static_mixed_var.h"
#include "templates/shared_lib.h"
#include "templates/packed_ordered_hash.h"
#ifndef ERROR_ELEVATION_REQUIRED
#define ERROR_ELEVATION_REQUIRED 740
#endif
#ifndef INHERIT_PARENT_AFFINITY
#define INHERIT_PARENT_AFFINITY 0x00010000L
#endif
#ifndef STARTF_TITLEISLINKNAME
#define STARTF_TITLEISLINKNAME 0x00000800L
#endif
#ifndef STARTF_TITLEISAPPID
#define STARTF_TITLEISAPPID 0x00001000L
#endif
#ifndef STARTF_PREVENTPINNING
#define STARTF_PREVENTPINNING 0x00002000L
#endif
#ifdef SUBSYSTEM_WINDOWS
// If the caller is a console application and is waiting for this application to complete, then attach to the console.
void InitVerboseMode(void)
{
if (::AttachConsole(ATTACH_PARENT_PROCESS))
{
if (::GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE)
{
freopen("CONOUT$", "w", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
}
if (::GetStdHandle(STD_ERROR_HANDLE) != INVALID_HANDLE_VALUE)
{
freopen("CONOUT$", "w", stderr);
setvbuf(stderr, NULL, _IONBF, 0);
}
}
}
#endif
void DumpSyntax(TCHAR *currfile)
{
#ifdef SUBSYSTEM_WINDOWS
InitVerboseMode();
#endif
_tprintf(_T("(C) 2021 CubicleSoft. All Rights Reserved.\n\n"));
_tprintf(_T("Syntax: %s [options] EXEToRun [arguments]\n\n"), currfile);
_tprintf(_T("Options:\n"));
_tprintf(_T("\t/v\n\
\tVerbose mode.\n\
\n\
\t/w[=Milliseconds]\n\
\tWaits for the process to complete before exiting.\n\
\tThe default behavior is to return immediately.\n\
\tIf Milliseconds is specified, the number of milliseconds to wait.\n\
\tReturn code, if any, is returned to caller.\n\
\n\
\t/pid=File\n\
\tWrites the process ID to the specified file.\n\
\n\
\t/term\n\
\tUsed with /w=Milliseconds.\n\
\tTerminates the process when the wait time is up.\n\
\n\
\t/runelevated\n\
\tCalls CreateProcess() as a high Integrity Level elevated process.\n\
\t/w should be specified before this option.\n\
\tMay trigger elevation. Not compatible with /term when not elevated.\n\
\n\
\t/elevatedtoken\n\
\tUses an elevated token to create a child process.\n\
\tMay create a temporary SYSTEM service to copy the primary token via\n\
\tundocumented Windows kernel APIs.\n\
\n\
\t/systemtoken\n\
\tUses a SYSTEM token to create a child process.\n\
\tMay create a temporary SYSTEM service to copy the primary token via\n\
\tundocumented Windows kernel APIs.\n\
\n\
\t/usetoken=PIDorSIDsAndPrivileges\n\
\tUses the primary token of the specified process ID,\n\
\tor a process matching specific comma-separated user/group SIDs\n\
\tand/or a process with specific privileges.\n\
\tMay trigger elevation. See /elevatedtoken.\n\
\n\
\t/createtoken=Parameters\n\
\tCreates a primary token from scratch.\n\
\tMay trigger elevation. See /elevatedtoken.\n\
\tUses an undocumented Windows kernel API.\n\
\tThe 'Parameters' are semicolon separated:\n\
\t\tUserSID;\n\
\t\tGroupSID:Attr,GroupSID:Attr,...;\n\
\t\tPrivilege:Attr,Privilege:Attr,...;\n\
\t\tOwnerSID;\n\
\t\tPrimaryGroupSID;\n\
\t\tDefaultDACL;\n\
\t\tSourceInHex:SourceLUID\n\
\n\
\t/mergeenv\n\
\tMerges the current environment with another user environment.\n\
\tUse with /elevatedtoken, /systemtoken, /usetoken, /createtoken.\n\
\n\
\t/mutex=MutexName\n\
\tCreates a mutex with the specified name.\n\
\tUse the named mutex with /singleton or other software\n\
\tto detect an already running instance.\n\
\n\
\t/singleton[=Milliseconds]\n\
\tOnly starts the target process if named /mutex is the only instance.\n\
\tIf Milliseconds is specified, the number of milliseconds to wait.\n\
\n\
\t/semaphore=MaxCount,SemaphoreName\n\
\tCreates a semaphore with the specified name and limit/count.\n\
\tUse the named semaphore with /multiton\n\
\tto limit the number of running processes.\n\
\n\
\t/multiton[=Milliseconds]\n\
\tChecks or waits for a named /semaphore.\n\
\tIf Milliseconds is specified, the number of milliseconds to wait.\n\
\n\
\t/f=PriorityClass\n\
\tSets the priority class of the new process.\n\
\tThere is only one priority class per process.\n\
\tThe 'PriorityClass' can be one of:\n\
\t\tABOVE_NORMAL_PRIORITY_CLASS\n\
\t\tBELOW_NORMAL_PRIORITY_CLASS\n\
\t\tHIGH_PRIORITY_CLASS\n\
\t\tIDLE_PRIORITY_CLASS\n\
\t\tNORMAL_PRIORITY_CLASS\n\
\t\tREALTIME_PRIORITY_CLASS\n\
\n\
\t/f=CreateFlag\n\
\tSets a creation flag for the new process.\n\
\tMultiple /f options can be specified.\n\
\tEach 'CreateFlag' can be one of:\n\
\t\tCREATE_DEFAULT_ERROR_MODE\n\
\t\tCREATE_NEW_CONSOLE\n\
\t\tCREATE_NEW_PROCESS_GROUP\n\
\t\tCREATE_NO_WINDOW\n\
\t\tCREATE_PROTECTED_PROCESS\n\
\t\tCREATE_PRESERVE_CODE_AUTHZ_LEVEL\n\
\t\tCREATE_SEPARATE_WOW_VDM\n\
\t\tCREATE_SHARED_WOW_VDM\n\
\t\tDEBUG_ONLY_THIS_PROCESS\n\
\t\tDEBUG_PROCESS\n\
\t\tDETACHED_PROCESS\n\
\t\tINHERIT_PARENT_AFFINITY\n\
\n\
\t/dir=StartDir\n\
\tSets the starting directory of the new process.\n\
\n\
\t/desktop=Desktop\n\
\tSets the STARTUPINFO.lpDesktop member to target a specific desktop.\n\
\n\
\t/title=WindowTitle\n\
\tSets the STARTUPINFO.lpTitle member to a specific title.\n\
\n\
\t/x=XPositionInPixels\n\
\tSets the STARTUPINFO.dwX member to a specific x-axis position, in pixels.\n\
\n\
\t/y=YPositionInPixels\n\
\tSets the STARTUPINFO.dwY member to a specific y-axis position, in pixels.\n\
\n\
\t/width=WidthInPixels\n\
\tSets the STARTUPINFO.dwXSize member to a specific width, in pixels.\n\
\n\
\t/height=HeightInPixels\n\
\tSets the STARTUPINFO.dwYSize member to a specific height, in pixels.\n\
\n\
\t/xchars=BufferWidthInCharacters\n\
\tSets the STARTUPINFO.dwXCountChars member to buffer width, in characters.\n\
\n\
\t/ychars=BufferHeightInCharacters\n\
\tSets the STARTUPINFO.dwYCountChars member to buffer height, in characters.\n\
\n\
\t/f=FillAttribute\n\
\tSets the STARTUPINFO.dwFillAttribute member text and background colors.\n\
\tMultiple /f options can be specified.\n\
\tEach 'FillAttribute' can be one of:\n\
\t\tFOREGROUND_RED\n\
\t\tFOREGROUND_GREEN\n\
\t\tFOREGROUND_BLUE\n\
\t\tFOREGROUND_INTENSITY\n\
\t\tBACKGROUND_RED\n\
\t\tBACKGROUND_GREEN\n\
\t\tBACKGROUND_BLUE\n\
\t\tBACKGROUND_INTENSITY\n\
\n\
\t/f=StartupFlag\n\
\tSets the STARTUPINFO.dwFlags flag for the new process.\n\
\tMultiple /f options can be specified.\n\
\tEach 'StartupFlag' can be one of:\n\
\t\tSTARTF_FORCEONFEEDBACK\n\
\t\tSTARTF_FORCEOFFFEEDBACK\n\
\t\tSTARTF_PREVENTPINNING\n\
\t\tSTARTF_RUNFULLSCREEN\n\
\t\tSTARTF_TITLEISAPPID\n\
\t\tSTARTF_TITLEISLINKNAME\n\
\n\
\t/f=ShowWindow\n\
\tSets the STARTUPINFO.wShowWindow flag for the new process.\n\
\tThere is only one show window option per process.\n\
\tThe 'ShowWindow' value can be one of:\n\
\t\tSW_FORCEMINIMIZE\n\
\t\tSW_HIDE\n\
\t\tSW_MAXIMIZE\n\
\t\tSW_MINIMIZE\n\
\t\tSW_RESTORE\n\
\t\tSW_SHOW\n\
\t\tSW_SHOWDEFAULT\n\
\t\tSW_SHOWMAXIMIZED\n\
\t\tSW_SHOWMINIMIZED\n\
\t\tSW_SHOWMINNOACTIVE\n\
\t\tSW_SHOWNA\n\
\t\tSW_SHOWNOACTIVATE\n\
\t\tSW_SHOWNORMAL\n\
\n\
\t/hotkey=HotkeyValue\n\
\tSets the STARTUPINFO.hStdInput handle for the new process.\n\
\tSpecifies the wParam member of a WM_SETHOKEY message to the new process.\n\
\n\
\t/socketip=IPAddress\n\
\tSpecifies the IP address to connect to over TCP/IP.\n\
\n\
\t/socketport=PortNumber\n\
\tSpecifies the port number to connect to over TCP/IP.\n\
\n\
\t/sockettoken=Token\n\
\tSpecifies the token to send to each socket.\n\
\tLess secure than using /sockettokenlen and stdin.\n\
\n\
\t/sockettokenlen=TokenLength\n\
\tSpecifies the length of the token to read from stdin.\n\
\tWhen specified, a token must be sent for each socket.\n\
\n\
\t/stdin=FileOrEmptyOrsocket\n\
\tSets the STARTUPINFO.hStdInput handle for the new process.\n\
\tWhen this option is empty, INVALID_HANDLE_VALUE is used.\n\
\tWhen this option is 'socket', the /socket IP and port are used.\n\
\tWhen this option is not specified, the current stdin is used.\n\
\n\
\t/stdout=FileOrEmptyOrsocket\n\
\tSets the STARTUPINFO.hStdOutput handle for the new process.\n\
\tWhen this option is empty, INVALID_HANDLE_VALUE is used.\n\
\tWhen this option is 'socket', the /socket IP and port are used.\n\
\tWhen this option is not specified, the current stdout is used.\n\
\n\
\t/stderr=FileOrEmptyOrstdoutOrsocket\n\
\tSets the STARTUPINFO.hStdError handle for the new process.\n\
\tWhen this option is empty, INVALID_HANDLE_VALUE is used.\n\
\tWhen this option is 'stdout', the value of stdout is used.\n\
\tWhen this option is 'socket', the /socket IP and port are used.\n\
\tWhen this option is not specified, the current stderr is used.\n\
\n\
\t/attach[=ProcessID]\n\
\tAttempt to attach to a parent OR a specific process' console.\n\
\tAlso resets standard handles back to defaults.\n\n"));
}
bool SetThreadProcessPrivilege(LPCWSTR PrivilegeName, bool Enable)
{
HANDLE Token;
TOKEN_PRIVILEGES TokenPrivs;
LUID TempLuid;
bool Result;
if (!::LookupPrivilegeValueW(NULL, PrivilegeName, &TempLuid)) return false;
if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &Token))
{
if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token)) return false;
}
TokenPrivs.PrivilegeCount = 1;
TokenPrivs.Privileges[0].Luid = TempLuid;
TokenPrivs.Privileges[0].Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0);
Result = (::AdjustTokenPrivileges(Token, FALSE, &TokenPrivs, 0, NULL, NULL) && ::GetLastError() == ERROR_SUCCESS);
::CloseHandle(Token);
return Result;
}
DWORD GxConnectPipePID = 0;
HANDLE GxMainCommPipeClient = INVALID_HANDLE_VALUE;
// Creates an event object to be able to timeout on for the named pipe.
HANDLE CreateCommPipeConnectEventObj(DWORD pid)
{
CubicleSoft::StaticWCMixedVar<WCHAR[256]> TempVar;
TempVar.SetStr(L"Global\\CreateProcess_21F9597D-1A55-41AD-BCE0-0DB5CA53BDF8_CommEv_");
TempVar.AppendUInt(pid);
return ::CreateEventW(NULL, FALSE, FALSE, TempVar.GetStr());
}
// Attempt to connect to the named pipe. Does not emit errors.
bool ConnectToMainCommPipe()
{
if (GxMainCommPipeClient != INVALID_HANDLE_VALUE) return true;
if (!GxConnectPipePID) return false;
CubicleSoft::StaticWCMixedVar<WCHAR[256]> TempVar;
HANDLE tempevent;
tempevent = CreateCommPipeConnectEventObj(GxConnectPipePID);
if (tempevent == NULL) return false;
TempVar.SetStr(L"\\\\.\\pipe\\CreateProcess_21F9597D-1A55-41AD-BCE0-0DB5CA53BDF8_Comm_");
TempVar.AppendUInt(GxConnectPipePID);
do
{
// Notify the pipe server that a connection is incoming.
if (!::SetEvent(tempevent)) break;
// Attempt to connect.
GxMainCommPipeClient = ::CreateFile(TempVar.GetStr(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (GxMainCommPipeClient != INVALID_HANDLE_VALUE) return true;
if (::GetLastError() != ERROR_PIPE_BUSY) break;
if (!::WaitNamedPipe(TempVar.GetStr(), 10000)) break;
} while (1);
::CloseHandle(tempevent);
return false;
}
void DisconnectMainCommPipe()
{
if (GxMainCommPipeClient == INVALID_HANDLE_VALUE) return;
::CloseHandle(GxMainCommPipeClient);
GxMainCommPipeClient = INVALID_HANDLE_VALUE;
GxConnectPipePID = 0;
}
HANDLE StartMainCommPipeServer()
{
CubicleSoft::StaticWCMixedVar<WCHAR[256]> TempVar;
TempVar.SetStr(L"\\\\.\\pipe\\CreateProcess_21F9597D-1A55-41AD-BCE0-0DB5CA53BDF8_Comm_");
TempVar.AppendUInt(::GetCurrentProcessId());
return ::CreateNamedPipe(TempVar.GetStr(), PIPE_ACCESS_DUPLEX, 0, 1, 4096, 4096, 0, NULL);
}
void DumpErrorMsg(const char *errorstr, const char *errorcode, DWORD winerror)
{
#ifdef SUBSYSTEM_WINDOWS
InitVerboseMode();
#endif
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
CubicleSoft::StaticMixedVar<char[8192]> TempVar2;
printf("%s (%s)\n", errorstr, errorcode);
TempVar2.SetFormattedStr("[%lu] %s (%s)", ::GetCurrentProcessId(), errorstr, errorcode);
if (winerror)
{
LPSTR errmsg = NULL;
::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, winerror, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&errmsg, 0, NULL);
if (errmsg == NULL)
{
printf("%d - Unknown error\n", winerror);
TempVar2.AppendFormattedStr(" (%lu - Unknown error)", winerror);
}
else
{
size_t y = strlen(errmsg);
while (y && (errmsg[y - 1] == '\r' || errmsg[y - 1] == '\n')) errmsg[--y] = '\0';
printf("%d - %s\n", winerror, errmsg);
TempVar2.AppendFormattedStr(" (%lu - %s)", winerror, errmsg);
::LocalFree(errmsg);
}
}
TempVar2.AppendStr("\n");
// Send the error message to the main process' communication pipe.
if (ConnectToMainCommPipe())
{
TempVar.SetStr(TempVar2.GetStr());
DWORD tempsize = TempVar.GetSize() * sizeof(WCHAR);
::WriteFile(GxMainCommPipeClient, "\x00", 1, NULL, NULL);
::WriteFile(GxMainCommPipeClient, &tempsize, 4, NULL, NULL);
::WriteFile(GxMainCommPipeClient, TempVar.GetStr(), tempsize, NULL, NULL);
DisconnectMainCommPipe();
}
::Sleep(5000);
}
void DumpWideErrorMsg(const WCHAR *errorstr, const char *errorcode, DWORD winerror)
{
char *errorstr2;
BOOL useddefaultchar = FALSE;
int retval = ::WideCharToMultiByte(CP_ACP, 0, errorstr, -1, NULL, 0, NULL, &useddefaultchar);
if (!retval)
{
DumpErrorMsg("Unable to convert error message to multibyte.", "wide_char_to_multibyte_failed", ::GetLastError());
return;
}
DWORD tempsize = (DWORD)retval;
errorstr2 = (char *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tempsize);
if (errorstr2 == NULL)
{
DumpErrorMsg("Error message buffer allocation failed.", "heap_alloc_failed", ::GetLastError());
return;
}
useddefaultchar = FALSE;
retval = ::WideCharToMultiByte(CP_ACP, 0, errorstr, -1, errorstr2, tempsize, NULL, &useddefaultchar);
if (!retval)
{
DumpErrorMsg("Unable to convert error message to multibyte.", "wide_char_to_multibyte_failed", ::GetLastError());
::HeapFree(::GetProcessHeap(), 0, errorstr2);
return;
}
size_t y = strlen(errorstr2);
while (y && (errorstr2[y - 1] == '\r' || errorstr2[y - 1] == '\n')) errorstr2[--y] = '\0';
// Display the error message.
DumpErrorMsg(errorstr2, errorcode, winerror);
::HeapFree(::GetProcessHeap(), 0, errorstr2);
}
// Waits for a client to connect and then validates the session the client is running in.
bool WaitForValidCommPipeClient(HANDLE &pipehandle, HANDLE eventhandle, DWORD timeout)
{
while (1)
{
// Wait for the event object to fire (allows for timeout).
if (::WaitForSingleObject(eventhandle, timeout) != WAIT_OBJECT_0)
{
DumpErrorMsg("An elevated process did not respond before the timeout expired.", "timeout", ::GetLastError());
return false;
}
// Wait for the client to connect.
if (!::ConnectNamedPipe(pipehandle, NULL) && ::GetLastError() != ERROR_PIPE_CONNECTED)
{
DumpErrorMsg("Main communication pipe failed.", "connect_named_pipe_failed", ::GetLastError());
return false;
}
// Allow connections from session 0 (SYSTEM) and the current process' session.
ULONG clientsession;
DWORD currsessionid;
if (::GetNamedPipeClientSessionId(pipehandle, &clientsession) && ::ProcessIdToSessionId(::GetCurrentProcessId(), &currsessionid) && (clientsession == 0 || clientsession == currsessionid))
{
return true;
}
// Restart the named pipe server.
::CloseHandle(pipehandle);
pipehandle = StartMainCommPipeServer();
if (pipehandle == INVALID_HANDLE_VALUE)
{
DumpErrorMsg("Unable to create the main communication pipe.", "start_main_comm_pipe_failed", ::GetLastError());
return false;
}
}
}
BOOL ReadFileExact(HANDLE filehandle, LPVOID buffer, DWORD numbytes)
{
BOOL result;
DWORD bytesread;
do
{
result = ::ReadFile(filehandle, buffer, numbytes, &bytesread, NULL);
if (!result) return result;
buffer = (char *)buffer + bytesread;
numbytes -= bytesread;
} while (numbytes);
return result;
}
// Waits until a single status byte is received.
bool WaitForCommPipeStatus(HANDLE pipehandle)
{
char status;
if (!ReadFileExact(pipehandle, &status, 1))
{
DumpErrorMsg("The main communication pipe broke.", "read_main_comm_pipe_failed", ::GetLastError());
return false;
}
if (status) return true;
// Read the error message.
DWORD tempsize;
WCHAR *msgbuffer;
if (!ReadFileExact(pipehandle, &tempsize, 4))
{
DumpErrorMsg("Unable to read size from the main communication pipe.", "read_main_comm_pipe_failed", ::GetLastError());
return false;
}
if (tempsize < 1 * sizeof(WCHAR) || tempsize % sizeof(WCHAR) != 0)
{
DumpErrorMsg("The read size from the main communication pipe is invalid.", "read_main_comm_pipe_invalid_size", ::GetLastError());
return false;
}
msgbuffer = (WCHAR *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tempsize);
if (msgbuffer == NULL)
{
DumpErrorMsg("Error message buffer allocation failed.", "heap_alloc_failed", ::GetLastError());
return false;
}
if (!ReadFileExact(pipehandle, msgbuffer, tempsize))
{
DumpErrorMsg("Unable to read error message from the main communication pipe.", "read_main_comm_pipe_failed", ::GetLastError());
return false;
}
tempsize /= sizeof(WCHAR);
msgbuffer[tempsize - 1] = L'\0';
// Convert to DumpErrorMsg() format.
DumpWideErrorMsg(msgbuffer, "main_comm_pipe_client_sent_error", 0);
::HeapFree(::GetProcessHeap(), 0, msgbuffer);
return false;
}
bool ReadCommPipeString(HANDLE commpipehandle, WCHAR *&buffer, DWORD &tempsize, size_t minsize)
{
if (commpipehandle == INVALID_HANDLE_VALUE) return false;
if (!ReadFileExact(commpipehandle, &tempsize, 4))
{
DumpErrorMsg("Unable to read size from the main communication pipe.", "read_main_comm_pipe_failed", ::GetLastError());
return false;
}
if (tempsize < minsize * sizeof(WCHAR) || tempsize % sizeof(WCHAR) != 0)
{
DumpErrorMsg("The read size from the main communication pipe is invalid.", "read_main_comm_pipe_invalid_size", 0);
return false;
}
buffer = (WCHAR *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tempsize);
if (buffer == NULL)
{
DumpErrorMsg("Allocation failed.", "heap_alloc_failed", ::GetLastError());
return false;
}
if (!ReadFileExact(commpipehandle, buffer, tempsize))
{
DumpErrorMsg("Unable to read buffer from the main communication pipe.", "read_main_comm_pipe_failed", ::GetLastError());
return false;
}
tempsize /= sizeof(WCHAR);
buffer[tempsize - 1] = L'\0';
return true;
}
void FreeCommPipeString(WCHAR *&buffer)
{
if (buffer != NULL) ::HeapFree(::GetProcessHeap(), 0, (LPVOID)buffer);
}
bool MakeStringArrayFromString(WCHAR *buffer, DWORD buffersize, WCHAR **&arr, int &numitems)
{
if (buffersize < 2)
{
DumpErrorMsg("Insufficient buffer size.", "invalid_buffer_size", ::GetLastError());
return false;
}
buffer[buffersize - 2] = L'\0';
buffer[buffersize - 1] = L'\0';
// Parse the buffer into an array of zero-terminated WCHAR strings.
int x, x2;
numitems = 0;
for (x = 0; x < (int)buffersize - 1; x++)
{
if (!buffer[x]) numitems++;
}
arr = (WCHAR **)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, (numitems + 1) * sizeof(WCHAR *));
if (arr == NULL)
{
DumpErrorMsg("Pointer buffer allocation failed.", "heap_alloc_failed", ::GetLastError());
return false;
}
arr[0] = buffer;
x2 = 1;
for (x = 0; x < (int)buffersize - 2; x++)
{
if (!buffer[x]) arr[x2++] = buffer + x + 1;
}
return true;
}
bool ReadCommPipeStringArray(HANDLE commpipehandle, WCHAR *&buffer, WCHAR **&arr, int &numitems)
{
DWORD tempsize;
if (!ReadCommPipeString(commpipehandle, buffer, tempsize, 2)) return false;
return MakeStringArrayFromString(buffer, tempsize, arr, numitems);
}
void FreeCommPipeStringArray(WCHAR *&buffer, WCHAR **&arr)
{
if (buffer != NULL) ::HeapFree(::GetProcessHeap(), 0, (LPVOID)buffer);
if (arr != NULL) ::HeapFree(::GetProcessHeap(), 0, (LPVOID)arr);
}
inline void FreeTokenInformation(LPVOID tinfo)
{
if (tinfo != NULL) ::HeapFree(::GetProcessHeap(), 0, tinfo);
}
LPVOID AllocateAndGetTokenInformation(HANDLE token, TOKEN_INFORMATION_CLASS infoclass, DWORD sizehint)
{
LPVOID tinfo;
DWORD tinfosize = sizehint;
bool success;
tinfo = (LPVOID)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tinfosize);
if (tinfo == NULL) tinfosize = 0;
// Resize until the buffer is big enough.
while (!(success = ::GetTokenInformation(token, infoclass, tinfo, tinfosize, &tinfosize)) && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
if (tinfo != NULL) FreeTokenInformation(tinfo);
tinfo = (LPVOID)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, tinfosize);
if (tinfo == NULL)
{
tinfosize = 0;
break;
}
}
return tinfo;
}
// Get/Duplicate the primary token of the specified process ID as a primary or impersonation token.
// duptype is ignored if accessmode does not specify TOKEN_DUPLICATE.
HANDLE GetTokenFromPID(DWORD pid, TOKEN_TYPE duptype, DWORD accessmode = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY)
{
HANDLE tempproc;
HANDLE tokenhandle, tokenhandle2;
// Enable SeDebugPrivilege.
SetThreadProcessPrivilege(L"SeDebugPrivilege", true);
// Open a handle to the process.
tempproc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (tempproc == NULL) tempproc = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (tempproc == NULL)
{
DumpErrorMsg("Unable to open a handle to the specified process.", "open_process_failed", ::GetLastError());
return INVALID_HANDLE_VALUE;
}
if (!::OpenProcessToken(tempproc, accessmode, &tokenhandle) && (!(accessmode & TOKEN_QUERY_SOURCE) || !::OpenProcessToken(tempproc, accessmode & ~TOKEN_QUERY_SOURCE, &tokenhandle)))
{
DumpErrorMsg("Unable to open a handle to the specified process token.", "open_process_token_failed", ::GetLastError());
::CloseHandle(tempproc);
return INVALID_HANDLE_VALUE;
}
::CloseHandle(tempproc);
if (!(accessmode & TOKEN_DUPLICATE)) tokenhandle2 = tokenhandle;
else
{
SECURITY_ATTRIBUTES secattr = {0};
secattr.nLength = sizeof(secattr);
secattr.bInheritHandle = FALSE;
secattr.lpSecurityDescriptor = NULL;
if (!::DuplicateTokenEx(tokenhandle, MAXIMUM_ALLOWED, &secattr, SecurityImpersonation, duptype, &tokenhandle2))
{
DumpErrorMsg("Unable to duplicate the specified process token.", "duplicate_token_ex_failed", ::GetLastError());
::CloseHandle(tokenhandle);
return INVALID_HANDLE_VALUE;
}
::CloseHandle(tokenhandle);
}
return tokenhandle2;
}
void GetNumSIDsAndLUIDs(LPWSTR tokenopts, size_t &numsids, size_t &numluids)
{
size_t x = 0;
numsids = 0;
numluids = 0;
while (tokenopts[x] && tokenopts[x] != L';')
{
for (; tokenopts[x] && tokenopts[x] != L';' && tokenopts[x] != L'S'; x++);
if (tokenopts[x] == L'S')
{
if (tokenopts[x + 1] == L'-') numsids++;
else if (tokenopts[x + 1] == L'e') numluids++;
}
for (; tokenopts[x] && tokenopts[x] != L';' && tokenopts[x] != L','; x++);
if (tokenopts[x] == L',') x++;
}
}
bool GetNextTokenOptsSID(LPWSTR tokenopts, size_t &x, PSID &sidbuffer)
{
size_t x2;
WCHAR tempchr;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L':' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
bool result = ::ConvertStringSidToSidW(tokenopts + x, &sidbuffer);
if (!result)
{
DWORD winerror = ::GetLastError();
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
TempVar.SetFormattedStr(L"The specified SID '%ls' in the token options is invalid.", tokenopts + x);
DumpWideErrorMsg(TempVar.GetStr(), "invalid_sid", winerror);
}
tokenopts[x2] = tempchr;
x = x2;
return result;
}
bool GetNextTokenOptsLUID(LPWSTR tokenopts, size_t &x, LUID &luidbuffer)
{
size_t x2;
WCHAR tempchr;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L':' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
bool result = ::LookupPrivilegeValueW(NULL, tokenopts + x, &luidbuffer);
if (!result)
{
DWORD winerror = ::GetLastError();
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
TempVar.SetFormattedStr(L"The specified privilege '%ls' in the token options is invalid.", tokenopts + x);
DumpWideErrorMsg(TempVar.GetStr(), "invalid_privilege", winerror);
}
tokenopts[x2] = tempchr;
x = x2;
return result;
}
DWORD GetNextTokenOptsAttrs(LPWSTR tokenopts, size_t &x)
{
size_t x2;
WCHAR tempchr;
if (tokenopts[x] != L':') return 0;
x++;
for (x2 = x; tokenopts[x2] && tokenopts[x2] != L';' && tokenopts[x2] != L','; x2++);
tempchr = tokenopts[x2];
tokenopts[x2] = L'\0';
DWORD result = (DWORD)_wtoi(tokenopts + x);
tokenopts[x2] = tempchr;
x = x2;
return result;
}
// Attempts to locate an existing token that matches the input option string.
// duptype is ignored if accessmode does not specify TOKEN_DUPLICATE.
// Example: FindExistingTokenFromOpts(L"S-1-16-16384,SeDebugPrivilege,SeAssignPrimaryTokenPrivilege", true)
HANDLE FindExistingTokenFromOpts(LPWSTR tokenopts, TOKEN_TYPE duptype, DWORD accessmode = TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY)
{
if (tokenopts[0] != L'S') return GetTokenFromPID(_wtoi(tokenopts), duptype, accessmode);
// Split and convert the options into SIDs and privilege LUIDs.
CubicleSoft::StaticWCMixedVar<WCHAR[8192]> TempVar;
size_t x, x2, numsids, numluids;
PSID *sids = NULL;
LUID *luids = NULL;
TempVar.SetStr(tokenopts);
WCHAR *tokenopts2 = TempVar.GetStr();
GetNumSIDsAndLUIDs(tokenopts2, numsids, numluids);
if (numsids) sids = (PSID *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, numsids * sizeof(PSID));
if (numluids) luids = (LUID *)::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, numluids * sizeof(LUID));
bool valid = true;
x = 0;
numsids = 0;
numluids = 0;
while (tokenopts2[x])
{
for (; tokenopts2[x] && tokenopts2[x] != L'S'; x++);
if (tokenopts2[x] == L'S')
{
if (tokenopts2[x + 1] == L'-')
{
valid = GetNextTokenOptsSID(tokenopts2, x, sids[numsids]);
if (!valid) break;
numsids++;
}
else if (tokenopts2[x + 1] == L'e')
{
valid = GetNextTokenOptsLUID(tokenopts2, x, luids[numluids]);
if (!valid) break;
numluids++;
}
}
for (; tokenopts2[x] && tokenopts2[x] != L','; x++);
if (tokenopts2[x] == L',') x++;
}
// Find a process that has matching SIDs and LUIDs.
HANDLE result = INVALID_HANDLE_VALUE;
if (valid)
{
// Enable SeDebugPrivilege.
SetThreadProcessPrivilege(L"SeDebugPrivilege", true);
// Get the list of currently running processes.
HANDLE snaphandle, tempproc, proctoken, duptoken;
PTOKEN_USER user = NULL;
PTOKEN_GROUPS groups = NULL;
PTOKEN_PRIVILEGES privs = NULL;
BOOL result2;
snaphandle = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snaphandle == INVALID_HANDLE_VALUE) DumpErrorMsg("Unable to retrieve the list of running processes.", "create_toolhelp32_snapshot_failed", ::GetLastError());
else
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (::Process32First(snaphandle, &pe32))
{
do
{
// Open a handle to the process.
tempproc = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
if (tempproc == NULL) tempproc = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe32.th32ProcessID);
if (tempproc != NULL)
{
result2 = ::OpenProcessToken(tempproc, accessmode, &proctoken);
if (result2 == NULL && (accessmode & TOKEN_QUERY_SOURCE)) result2 = ::OpenProcessToken(tempproc, accessmode & ~TOKEN_QUERY_SOURCE, &proctoken);
// DWORD pid = ::GetProcessId(tempproc);
::CloseHandle(tempproc);
if (result2)
{
// Load token user, groups, and privileges.
user = (PTOKEN_USER)AllocateAndGetTokenInformation(proctoken, TokenUser, 4096);
groups = (PTOKEN_GROUPS)AllocateAndGetTokenInformation(proctoken, TokenGroups, 4096);
privs = (PTOKEN_PRIVILEGES)AllocateAndGetTokenInformation(proctoken, TokenPrivileges, 4096);
if (user != NULL && groups != NULL && privs != NULL)
{
// Match SIDs.
for (x = 0; x < numsids; x++)
{
if (!::EqualSid(user->User.Sid, sids[x]))
{
for (x2 = 0; x2 < groups->GroupCount && !::EqualSid(groups->Groups[x2].Sid, sids[x]); x2++);
if (x2 >= groups->GroupCount) break;
}
}
if (x >= numsids)
{
// Match privileges.
for (x = 0; x < numluids; x++)
{
for (x2 = 0; x2 < privs->PrivilegeCount && (privs->Privileges[x2].Luid.LowPart != luids[x].LowPart || privs->Privileges[x2].Luid.HighPart != luids[x].HighPart); x2++);
if (x2 >= privs->PrivilegeCount) break;
}