-
Notifications
You must be signed in to change notification settings - Fork 35
/
NtUtils.Processes.Create.Clone.pas
334 lines (270 loc) · 9.59 KB
/
NtUtils.Processes.Create.Clone.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
unit NtUtils.Processes.Create.Clone;
{
This module provides support for cloning (aka forking) the current process.
}
interface
uses
Ntapi.WinNt, Ntapi.ntrtl, Ntapi.ntdbg, Ntapi.ntseapi, NtUtils,
NtUtils.Processes.Create;
{ Helper functions (parent) }
// Make as many handles inheritable as possible
function RtlxInheritAllHandles(
out Reverter: IAutoReleasable
): TNtxStatus;
// Map a shared memory region to talk to the clone
function RtlxMapSharableMemory(
Size: NativeUInt;
out SharedMemory: IMemory
): TNtxStatus;
{ Helper functions (clone) }
// Attach the clone to parent's console
function RtlxAttachToParentConsole: TNtxStatus;
{ Cloning }
// Clone the current process.
// The function returns STATUS_PROCESS_CLONED in the cloned process.
function RtlxCloneCurrentProcess(
out Info: TProcessInfo;
Flags: TRtlProcessCloneFlags = RTL_CLONE_PROCESS_FLAGS_INHERIT_HANDLES;
[opt, Access(TOKEN_ASSIGN_PRIMARY)] const hxPrimaryToken: IHandle = nil;
[opt, Access(DEBUG_PROCESS_ASSIGN)] const hxDebugPort: IHandle = nil;
[in, opt] ProcessSecurity: PSecurityDescriptor = nil;
[in, opt] ThreadSecurity: PSecurityDescriptor = nil
): TNtxStatus;
// Clone the current process and execute an anonymous function inside of it.
// Consider calling RtlxInheritAllHandles beforehand if necessary.
function RtlxExecuteInClone(
Payload: TNtxOperation;
const Timeout: Int64 = NT_INFINITE;
[opt, Access(TOKEN_ASSIGN_PRIMARY)] hxToken: IHandle = nil;
Flags: TRtlProcessCloneFlags = RTL_CLONE_PROCESS_FLAGS_INHERIT_HANDLES
): TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntdef, Ntapi.ntpsapi, Ntapi.ntmmapi, Ntapi.ConsoleApi,
NtUtils.Threads, NtUtils.Objects, NtUtils.Objects.Snapshots, NtUtils.Sections,
NtUtils.Synchronization, NtUtils.Processes, NtUtils.SysUtils, NtUtils.Jobs,
NtUtils.Tokens.Impersonate, DelphiUtils.AutoObjects;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
function RtlxInheritAllHandles;
var
Handles: TArray<TProcessHandleEntry>;
i: Integer;
begin
// Snapshot all our handles
Result := NtxEnumerateHandlesProcess(NtxCurrentProcess, Handles);
if not Result.IsSuccess then
Exit;
// Mark them inheritable
for i := 0 to High(Handles) do
NtxSetFlagsHandle(Auto.RefHandle(Handles[i].HandleValue), True,
BitTest(Handles[i].HandleAttributes and OBJ_PROTECT_CLOSE));
Reverter := Auto.Delay(
procedure
var
i: Integer;
begin
// Restore handle attributes
for i := 0 to High(Handles) do
NtxSetFlagsHandle(
Auto.RefHandle(Handles[i].HandleValue),
BitTest(Handles[i].HandleAttributes and OBJ_INHERIT),
BitTest(Handles[i].HandleAttributes and OBJ_PROTECT_CLOSE)
);
end
);
end;
function RtlxMapSharableMemory;
var
hxSection: IHandle;
begin
Result := NtxCreateSection(hxSection, Size, PAGE_READWRITE);
if not Result.IsSuccess then
Exit;
Result := NtxMapViewOfSection(hxSection, NtxCurrentProcess, SharedMemory,
MappingParameters
.UseProtection(PAGE_READWRITE)
.UseInheritDisposition(ViewShare)
);
end;
function RtlxAttachToParentConsole;
begin
Result.Location := 'FreeConsole';
Result.Win32Result := FreeConsole;
if not Result.IsSuccess then
Exit;
Result.Location := 'AttachConsole';
Result.Win32Result := AttachConsole(ATTACH_PARENT_PROCESS);
end;
function RtlxCloneCurrentProcess;
var
RtlProcessInfo: TRtlUserProcessInformation;
ModifiedFlags: TRtlProcessCloneFlags;
begin
Info := Default(TProcessInfo);
ModifiedFlags := Flags;
// Suspend the clone whenever swapping the primary token
if Assigned(hxPrimaryToken) then
ModifiedFlags := ModifiedFlags or RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED;
Result.Location := 'RtlCloneUserProcess';
if Assigned(hxDebugPort) then
Result.LastCall.Expects<TDebugObjectAccessMask>(DEBUG_PROCESS_ASSIGN);
Result.Status := RtlCloneUserProcess(ModifiedFlags, ProcessSecurity,
ThreadSecurity, HandleOrDefault(hxDebugPort), RtlProcessInfo);
if Result.IsSuccess and (Result.Status <> STATUS_PROCESS_CLONED) then
begin
Info.ValidFields := [piProcessID, piThreadID, piProcessHandle,
piThreadHandle, piImageInformation];
Info.ClientId := RtlProcessInfo.ClientId;
Info.hxProcess := Auto.CaptureHandle(RtlProcessInfo.Process);
Info.hxThread := Auto.CaptureHandle(RtlProcessInfo.Thread);
Info.ImageInformation := RtlProcessInfo.ImageInformation;
if Assigned(hxPrimaryToken) then
begin
// Swap the primary token while the clone is suspended
Result := NtxAssignPrimaryToken(Info.hxProcess, hxPrimaryToken);
if not Result.IsSuccess then
begin
// Fail and cleanup
NtxTerminateProcess(Info.hxProcess, STATUS_CANCELLED);
Exit;
end;
// Resume when necessary
if not BitTest(Flags and RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED) then
NtxResumeThread(Info.hxThread);
end;
end;
end;
function RtlxpPrepareJobForClone(
out hxJob: IHandle
): TNtxStatus;
var
Info: TJobObjectExtendedLimitInformation;
begin
Result := NtxCreateJob(hxJob);
if not Result.IsSuccess then
Exit;
// Terminate the clone on unexpected errors
Info := Default(TJobObjectExtendedLimitInformation);
Info.BasicLimitInformation.LimitFlags :=
JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION or
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE or
JOB_OBJECT_LIMIT_BREAKAWAY_OK;
Result := NtxJob.Set(hxJob, JobObjectExtendedLimitInformation, Info);
end;
const
CLONE_MAX_STACK_TRACE_DEPTH = 254;
CLONE_MAX_STRING_LENGTH = 1024;
type
TCloneSharedData = record
Status: NTSTATUS;
StackTraceLength: Cardinal;
Location: PWideChar;
StackTrace: array [0 .. CLONE_MAX_STACK_TRACE_DEPTH - 1] of Pointer;
LocationBuffer: array [0 .. CLONE_MAX_STRING_LENGTH - 1] of WideChar
end;
PCloneSharedData = ^TCloneSharedData;
function RtlxExecuteInClone;
var
SharedMemory: IMemory<PCloneSharedData>;
hxJob: IHandle;
Info: TProcessInfo;
Completed: Boolean;
begin
Result := RtlxpPrepareJobForClone(hxJob);
if not Result.IsSuccess then
Exit;
// Map shared memory for getting TNtxStatus back from the clone
Result := RtlxMapSharableMemory(SizeOf(TCloneSharedData),
IMemory(SharedMemory));
if not Result.IsSuccess then
Exit;
SharedMemory.Data.Location := 'Clone';
SharedMemory.Data.Status := STATUS_UNSUCCESSFUL;
// Clone the process
Result := RtlxCloneCurrentProcess(Info, Flags or
RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED, hxToken);
if not Result.IsSuccess then
Exit;
if Result.Status = STATUS_PROCESS_CLONED then
try
// Executing in the clone
Completed := False;
try
// Run the payload and save the result
Result := Payload();
SharedMemory.Data.Status := Result.Status;
// Constant strings appear at the same shared address
if StringRefCount(Result.Location) <= 0 then
SharedMemory.Data.Location := PWideChar(Result.Location)
// Dynamic strings require marshaling
else if Length(Result.Location) < CLONE_MAX_STRING_LENGTH then
begin
MarshalString(Result.Location, @SharedMemory.Data.LocationBuffer);
SharedMemory.Data.Location := @SharedMemory.Data.LocationBuffer[0];
end;
// Save the stack trace
if CaptureStackTraces and (Length(Result.LastCall.StackTrace) > 0) and
(Length(Result.LastCall.StackTrace) <= CLONE_MAX_STACK_TRACE_DEPTH) then
begin
Move(Result.LastCall.StackTrace[0], SharedMemory.Data.StackTrace,
Length(Result.LastCall.StackTrace) * SizeOf(Pointer));
SharedMemory.Data.StackTraceLength := Length(Result.LastCall.StackTrace);
end;
Completed := True;
finally
if not Completed then
begin
// Report unhandled exceptions
SharedMemory.Data.Location := 'Clone';
SharedMemory.Data.Status := STATUS_UNHANDLED_EXCEPTION;
// Provide a stack trace of the exception when possible
if CaptureStackTraces then
SharedMemory.Data.StackTraceLength := RtlCaptureStackBackTrace(0,
CLONE_MAX_STACK_TRACE_DEPTH, @SharedMemory.Data.StackTrace, nil);
end;
end;
finally
// Do not try to clean up
NtxTerminateProcess(NtxCurrentProcess, STATUS_PROCESS_CLONED);
end;
// Put the clone into the job, but don't fail if we can not
NtxAssignProcessToJob(Info.hxProcess, hxJob);
// Let the clone execute
Result := NtxResumeThread(Info.hxThread);
if not Result.IsSuccess then
Exit;
// Wait for clone's completion
Result := NtxWaitForSingleObject(Info.hxProcess, Timeout);
if not Result.IsSuccess then
Exit;
if Result.Status = STATUS_TIMEOUT then
begin
Result.Status := STATUS_WAIT_TIMEOUT;
NtxTerminateProcess(Info.hxProcess, STATUS_WAIT_TIMEOUT);
Exit;
end;
// Forward the result
if SharedMemory.Data.Location = @SharedMemory.Data.LocationBuffer[0] then
Result.Location := RtlxCaptureString(SharedMemory.Data.Location,
CLONE_MAX_STRING_LENGTH)
else
Result.Location := String(SharedMemory.Data.Location);
Result.Status := SharedMemory.Data.Status;
if CaptureStackTraces then
begin
// Suppress a stack trace from the current process
Result.LastCall.StackTrace := nil;
// Get a stack trace from the clone
if (SharedMemory.Data.StackTraceLength > 0) and
(SharedMemory.Data.StackTraceLength <= CLONE_MAX_STACK_TRACE_DEPTH) then
begin
Result.LastCall.StackTrace := nil;
SetLength(Result.LastCall.StackTrace, SharedMemory.Data.StackTraceLength);
Move(SharedMemory.Data.StackTrace, Result.LastCall.StackTrace[0],
Length(Result.LastCall.StackTrace) * SizeOf(Pointer));
end;
end;
end;
end.