-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathNtUtils.Processes.Create.Com.pas
628 lines (503 loc) · 16.3 KB
/
NtUtils.Processes.Create.Com.pas
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
unit NtUtils.Processes.Create.Com;
{
This module provides support for asking various user-mode OS components via
COM to create processes on our behalf.
}
interface
uses
Ntapi.ShellApi, Ntapi.ObjBase, NtUtils, NtUtils.Processes.Create;
// Create a new process via WMI
[RequiresCOM]
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoSuspended)]
[SupportedOption(spoWindowMode)]
[SupportedOption(spoDesktop)]
[SupportedOption(spoToken)]
function WmixCreateProcess(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Ask Explorer via IShellDispatch2 to create a process on our behalf
[RequiresCOM]
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoRequireElevation)]
[SupportedOption(spoWindowMode)]
function ComxShellDispatchExecute(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via WDC
[RequiresCOM]
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoRequireElevation)]
function WdcxRunAsInteractive(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via Task Scheduler using Task Manager's interactive task
[RequiresCOM]
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoRequireElevation)]
[SupportedOption(spoSessionId)]
function SchxRunAsInteractive(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via a BITS job trigger
[RequiresCOM]
function ComxCreateProcessBITS(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
implementation
uses
Ntapi.WinNt, Ntapi.ntstatus, Ntapi.ProcessThreadsApi, Ntapi.WinError,
Ntapi.ObjIdl, Ntapi.taskschd, Ntapi.ntpebteb, Ntapi.winsta, Ntapi.Bits,
NtUtils.Ldr, NtUtils.Com, NtUtils.Threads, NtUtils.Tokens.Impersonate,
NtUtils.WinStation, NtUtils.SysUtils, NtUtils.Synchronization,
NtUtils.TaskScheduler;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
{ ----------------------------------- WMI ----------------------------------- }
function WmixCreateProcess;
var
ImpersonationReverter: IAutoReleasable;
Win32_ProcessStartup, Win32_Process: IDispatch;
ProcessId: TProcessId32;
ResultCode: TVarData;
begin
Info := Default(TProcessInfo);
// TODO: add support for providing environment variables
// We pass the token to WMI by impersonating it
if Assigned(Options.hxToken) then
begin
// Revert to the original one when we are done.
ImpersonationReverter := NtxBackupThreadToken(NtxCurrentThread);
Result := NtxImpersonateAnyToken(Options.hxToken);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we did not change it.
ImpersonationReverter.AutoRelease := False;
Exit;
end;
end;
// Start preparing the startup info
Result := DispxBindToObject('winmgmts:Win32_ProcessStartup',
Win32_ProcessStartup);
if not Result.IsSuccess then
Exit;
// Fill-in CreateFlags
if poSuspended in Options.Flags then
begin
// For some reason, when specifying Win32_ProcessStartup.CreateFlags,
// processes would not start without CREATE_BREAKAWAY_FROM_JOB.
Result := DispxSetPropertyByName(
Win32_ProcessStartup,
'CreateFlags',
VarFromCardinal(CREATE_BREAKAWAY_FROM_JOB or CREATE_SUSPENDED)
);
if not Result.IsSuccess then
Exit;
end;
// Fill-in the Window Mode
if poUseWindowMode in Options.Flags then
begin
Result := DispxSetPropertyByName(
Win32_ProcessStartup,
'ShowWindow',
VarFromWord(Word(Options.WindowMode))
);
if not Result.IsSuccess then
Exit;
end;
// Fill-in the desktop
if Options.Desktop <> '' then
begin
Result := DispxSetPropertyByName(
Win32_ProcessStartup,
'WinstationDesktop',
VarFromWideString(Options.Desktop)
);
if not Result.IsSuccess then
Exit;
end;
// Prepare the process object
Result := DispxBindToObject('winmgmts:Win32_Process', Win32_Process);
if not Result.IsSuccess then
Exit;
ProcessId := 0;
// Create the process
Result := DispxCallMethodByName(
Win32_Process,
'Create',
[
VarFromWideString(WideString(Options.CommandLine)),
VarFromWideString(WideString(Options.CurrentDirectory)),
VarFromIDispatch(Win32_ProcessStartup),
VarFromIntegerRef(ProcessId)
],
@ResultCode
);
if not Result.IsSuccess then
Exit;
Result.Location := 'Win32_Process::Create';
Result.Status := STATUS_UNSUCCESSFUL;
// This method returns custom status codes; convert them
if ResultCode.VType and varTypeMask = varInteger then
case TWmiWin32ProcessCreateStatus(ResultCode.VInteger) of
Process_STATUS_SUCCESS:
Result.Status := STATUS_SUCCESS;
Process_STATUS_NOT_SUPPORTED:
Result.Status := STATUS_NOT_SUPPORTED;
Process_STATUS_ACCESS_DENIED:
Result.Status := STATUS_ACCESS_DENIED;
Process_STATUS_INSUFFICIENT_PRIVILEGE:
Result.Status := STATUS_PRIVILEGE_NOT_HELD;
Process_STATUS_UNKNOWN_FAILURE:
Result.Status := STATUS_UNSUCCESSFUL;
Process_STATUS_PATH_NOT_FOUND:
Result.Status := STATUS_OBJECT_NAME_NOT_FOUND;
Process_STATUS_INVALID_PARAMETER:
Result.Status := STATUS_INVALID_PARAMETER;
end;
VariantClear(ResultCode);
// Return the process ID to the caller
if Result.IsSuccess then
begin
Include(Info.ValidFields, piProcessID);
Info.ClientId.UniqueProcess := ProcessId;
end;
end;
{ ----------------------------- IShellDispatch2 ----------------------------- }
// Retrieve the shell view for the desktop
function ComxFindDesktopFolderView(
out ShellView: IShellView
): TNtxStatus;
var
ShellWindows: IShellWindows;
wnd: Integer;
Dispatch: IDispatch;
ServiceProvider: IServiceProvider;
ShellBrowser: IShellBrowser;
begin
Result := ComxCreateInstance(CLSID_ShellWindows, IShellWindows, ShellWindows,
'CLSID_ShellWindows', CLSCTX_LOCAL_SERVER);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellWindows::FindWindowSW';
Result.HResultAllowFalse := ShellWindows.FindWindowSW(
VarFromCardinal(CSIDL_DESKTOP),
VarEmpty,
SWC_DESKTOP,
wnd,
SWFO_NEEDDISPATCH,
Dispatch
);
// S_FALSE indicates that the the function did not find the window.
// We cannot proceed in this case, so fail the function with a meaningful code
if Result.HResult = S_FALSE then
Result.Status := STATUS_NOT_FOUND;
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface';
Result.LastCall.Parameter := 'IServiceProvider';
Result.HResult := Dispatch.QueryInterface(IServiceProvider, ServiceProvider);
if not Result.IsSuccess then
Exit;
Result.Location := 'IServiceProvider::QueryService';
Result.LastCall.Parameter := 'SID_STopLevelBrowser';
Result.HResult := ServiceProvider.QueryService(SID_STopLevelBrowser,
IShellBrowser, ShellBrowser);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellBrowser::QueryActiveShellView';
Result.HResult := ShellBrowser.QueryActiveShellView(ShellView);
end;
// Locate the desktop folder view object
function ComxGetDesktopAutomationObject(
out FolderView: IShellFolderViewDual
): TNtxStatus;
var
ShellView: IShellView;
Dispatch: IDispatch;
begin
Result := ComxFindDesktopFolderView(ShellView);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellView::GetItemObject';
Result.HResult := ShellView.GetItemObject(SVGIO_BACKGROUND, IDispatch,
Dispatch);
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface';
Result.LastCall.Parameter := 'IShellFolderViewDual';
Result.HResult := Dispatch.QueryInterface(IShellFolderViewDual, FolderView);
end;
// Access the shell dispatch object
function ComxGetShellDispatch(
out ShellDispatch: IShellDispatch2
): TNtxStatus;
var
FolderView: IShellFolderViewDual;
Dispatch: IDispatch;
begin
Result := ComxGetDesktopAutomationObject(FolderView);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellFolderViewDual::get_Application';
Result.HResult := FolderView.get_Application(Dispatch);
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface';
Result.LastCall.Parameter := 'IShellDispatch2';
Result.HResult := Dispatch.QueryInterface(IShellDispatch2, ShellDispatch);
end;
function ComxShellDispatchExecute;
var
ShellDispatch: IShellDispatch2;
vOperation, vShow: TVarData;
begin
Info := Default(TProcessInfo);
// Retrieve the Shell Dispatch object
Result := ComxGetShellDispatch(ShellDispatch);
if not Result.IsSuccess then
Exit;
// Prepare the verb
if poRequireElevation in Options.Flags then
vOperation := VarFromWideString('runas')
else
vOperation := VarEmpty;
// Prepare the window mode
if poUseWindowMode in Options.Flags then
vShow := VarFromWord(Word(Options.WindowMode))
else
vShow := VarEmpty;
Result.Location := 'IShellDispatch2::ShellExecute';
Result.HResult := ShellDispatch.ShellExecute(
WideString(Options.ApplicationWin32),
VarFromWideString(WideString(Options.Parameters)),
VarFromWideString(WideString(Options.CurrentDirectory)),
vOperation,
vShow
);
// This method does not provide any information about the new process
end;
{ ----------------------------------- WDC ----------------------------------- }
function WdcxRunAsInteractive;
var
SeclFlags: TSeclFlags;
begin
Info := Default(TProcessInfo);
Result := LdrxCheckDelayedImport(delayed_WdcRunTaskAsInteractiveUser);
if not Result.IsSuccess then
Exit;
SeclFlags := SECL_NO_UI or SECL_ALLOW_NONEXE;
if poRequireElevation in Options.Flags then
SeclFlags := SeclFlags or SECL_RUNAS;
Result.Location := 'WdcRunTaskAsInteractiveUser';
Result.HResult := WdcRunTaskAsInteractiveUser(
PWideChar(Options.CommandLine),
RefStrOrNil(Options.CurrentDirectory),
SeclFlags
);
// This method does not provide any information about the new process
end;
function SchxRunAsInteractive;
const
TIMEOUT_DELAY = 64 * MILLISEC;
TIMEOUT_CHECK_COUNT = (5000 * MILLISEC) div TIMEOUT_DELAY;
TASK_MANAGER_TASK_PATH = '\Microsoft\Windows\Task Manager\Interactive';
var
Task: IRegisteredTask;
RunningTask: IRunningTask;
SeclFlags: TSeclFlags;
SessionId: TSessionId;
SessionInfo: TWinStationInformation;
Domain, User: String;
ParameterStr: WideString;
RemainingTimeoutChecks: NativeInt;
State: TTaskState;
LastResult: HResult;
begin
// This method does not provide any information about the new process
Info := Default(TProcessInfo);
// Open Task Manager's run-as-interactive task.
Result := ComxTaskSchedulerOpenTask(Task, TASK_MANAGER_TASK_PATH);
if not Result.IsSuccess then
Exit;
SeclFlags := SECL_NO_UI or SECL_ALLOW_NONEXE;
// Prepare the parameters
if poRequireElevation in Options.Flags then
SeclFlags := SeclFlags or SECL_RUNAS;
if poUseSessionId in Options.Flags then
SessionId := Options.SessionId
else
SessionId := RtlGetCurrentPeb.SessionID;
if (Options.Domain <> '') and (Options.Username <> '') then
begin
// Use the provided account name to avoid querying it
Domain := Options.Domain;
User := Options.Username;
end
else
begin
// Query the username of the specified session
Result := WsxWinStation.Query(SessionId, WinStationInformation, SessionInfo);
if not Result.IsSuccess then
Exit;
Domain := String(SessionInfo.Domain);
User := String(SessionInfo.UserName);
end;
// Pack the parameters
ParameterStr := RtlxFormatString('%08x|%s\%s|%s|%s', [
SeclFlags,
Domain,
User,
Options.CurrentDirectory,
Options.CommandLine
]);
// Invoke the task
Result.Location := 'IRegisteredTask::RunEx';
Result.LastCall.Parameter := TASK_MANAGER_TASK_PATH;
Result.HResult := Task.RunEx(
VarFromWideString(ParameterStr),
TASK_RUN_IGNORE_CONSTRAINTS or TASK_RUN_USE_SESSION_ID,
SessionId,
'',
RunningTask
);
if not Result.IsSuccess then
Exit;
RemainingTimeoutChecks := TIMEOUT_CHECK_COUNT;
repeat
// Check if the task completed
Result.Location := 'IRegisteredTask::get_State';
Result.HResult := Task.get_State(State);
if not Result.IsSuccess then
Exit;
if State <> TASK_STATE_RUNNING then
Break;
if RemainingTimeoutChecks >= 0 then
begin
// Wait before checking again
Result := NtxDelayExecution(TIMEOUT_DELAY);
if not Result.IsSuccess then
Exit;
end
else
begin
// Waited too many times
Result.Location := 'SchxRunAsInteractive';
Result.Win32Error := ERROR_TIMEOUT;
Exit;
end;
Dec(RemainingTimeoutChecks);
until False;
// Forward the result
Result.Location := 'IRegisteredTask::get_LastTaskResult';
Result.HResult := Task.get_LastTaskResult(LastResult);
if not Result.IsSuccess then
Exit;
Result.Location := 'WdcRunTask::Start';
Result.HResult := LastResult;
end;
{ ----------------------------------- BITS -----------------------------------}
function ComxCreateProcessBITS(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
const
TIMEOUT_DELAY = 64 * MILLISEC;
TIMEOUT_CHECK_COUNT = (5000 * MILLISEC) div TIMEOUT_DELAY;
var
BackgroundCopyManager: IBackgroundCopyManager;
JobId: TGuid;
BackgroundCopyJob: IBackgroundCopyJob;
BackgroundCopyJob2: IBackgroundCopyJob2;
AutoCancel: IAutoReleasable;
JobState: TBgJobState;
RemainingTimeoutChecks: NativeInt;
begin
// No info about the new process on output
Info := Default(TProcessInfo);
// Connect to BITS
Result := ComxCreateInstance(CLSID_BackgroundCopyManager,
IBackgroundCopyManager, BackgroundCopyManager);
Result.LastCall.Parameter := 'CLSID_BackgroundCopyManager';
if not Result.IsSuccess then
Exit;
// Create a temporary transfer job
Result.Location := 'IBackgroundCopyManager::CreateJob';
Result.HResult := BackgroundCopyManager.CreateJob('Program Start Task',
BG_JOB_TYPE_UPLOAD, JobId, BackgroundCopyJob);
if not Result.IsSuccess then
Exit;
// Make sure to delete it once finished/failed
AutoCancel := Auto.Delay(
procedure
begin
BackgroundCopyJob.Cancel;
end
);
// Upgrade the interface to v2
Result.Location := 'IBackgroundCopyJob::QueryInterface';
Result.LastCall.Parameter := 'IBackgroundCopyJob2';
Result.HResult := BackgroundCopyJob.QueryInterface(IBackgroundCopyJob2,
BackgroundCopyJob2);
if not Result.IsSuccess then
Exit;
// Use the error notifications as our trigger
Result.Location := 'IBackgroundCopyJob::SetNotifyFlags';
Result.HResult := BackgroundCopyJob.SetNotifyFlags(BG_NOTIFY_JOB_ERROR);
if not Result.IsSuccess then
Exit;
// Disable retries
Result.Location := 'IBackgroundCopyJob::SetNoProgressTimeout';
Result.HResult := BackgroundCopyJob.SetNoProgressTimeout(0);
if not Result.IsSuccess then
Exit;
// Use an upload request that is guaranteed to fail. We still need to provide
// something as a remote location and a valid readable file on input.
Result.Location := 'IBackgroundCopyJob::AddFile';
Result.HResult := BackgroundCopyJob.AddFile('\\?\NUL',
'\\?\BootPartition\Windows\system32\kernel32.dll');
if not Result.IsSuccess then
Exit;
// Configure process creation on error
Result.Location := 'IBackgroundCopyJob2::SetNotifyCmdLine';
Result.HResult := BackgroundCopyJob2.SetNotifyCmdLine(
PWideChar(Options.ApplicationWin32), PWideChar(Options.Parameters));
if not Result.IsSuccess then
Exit;
// Let the task run and fail
Result.Location := 'IBackgroundCopyJob::Resume';
Result.HResult := BackgroundCopyJob.Resume;
if not Result.IsSuccess then
Exit;
RemainingTimeoutChecks := TIMEOUT_CHECK_COUNT;
repeat
Result.Location := 'IBackgroundCopyJob::GetState';
Result.HResult := BackgroundCopyJob.GetState(JobState);
if not Result.IsSuccess then
Exit;
if JobState > BG_JOB_STATE_SUSPENDED then
Break;
if RemainingTimeoutChecks >= 0 then
begin
// Wait before checking again
Result := NtxDelayExecution(TIMEOUT_DELAY);
if not Result.IsSuccess then
Exit;
end
else
begin
// Waited for too many times
Result.Location := 'ComxCreateProcessBITS';
Result.Win32Error := ERROR_TIMEOUT;
Exit;
end;
Dec(RemainingTimeoutChecks);
until False;
end;
end.