-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCreateProcess.cs
373 lines (303 loc) · 12.8 KB
/
CreateProcess.cs
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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Com.Xenthrax.DllInjector
{
public partial class DllInjector : IDisposable
{
public static DllInjector CreateProcess(string FileName, bool CreateSuspended = false, bool FreeOnDispose = false)
{
return CreateProcess(new ProcessStartInfo(FileName), CreateSuspended, FreeOnDispose);
}
public static DllInjector CreateProcess(string FileName, string Arguments, bool CreateSuspended = false, bool FreeOnDispose = false)
{
return CreateProcess(new ProcessStartInfo(FileName, Arguments), CreateSuspended, FreeOnDispose);
}
public static DllInjector CreateProcess(string FileName, string UserName, System.Security.SecureString Password, string Domain, bool CreateSuspended = false, bool FreeOnDispose = false)
{
return CreateProcess(new ProcessStartInfo(FileName)
{
UserName = UserName,
Password = Password,
Domain = Domain
}, CreateSuspended, FreeOnDispose);
}
public static DllInjector CreateProcess(string FileName, string Arguments, string UserName, System.Security.SecureString Password, string Domain, bool CreateSuspended = false, bool FreeOnDispose = false)
{
return CreateProcess(new ProcessStartInfo(FileName, Arguments)
{
UserName = UserName,
Password = Password,
Domain = Domain
}, CreateSuspended, FreeOnDispose);
}
public static DllInjector CreateProcess(ProcessStartInfo StartInfo, bool CreateSuspended = false, bool FreeOnDispose = false)
{
Process process;
if (CreateSuspended)
{
if (StartInfo == null)
throw new ArgumentNullException("StartInfo");
if (string.IsNullOrEmpty(StartInfo.FileName))
throw new ArgumentException("FileNameMissing");
if (StartInfo.StandardOutputEncoding != null && !StartInfo.RedirectStandardOutput)
throw new ArgumentException("StandardOutputEncodingNotAllowed");
if (StartInfo.StandardErrorEncoding != null && !StartInfo.RedirectStandardError)
throw new ArgumentException("StandardErrorEncodingNotAllowed");
/*
* private static StringBuilder BuildCommandLine(string executableFileName, string arguments);
*
* Declaring Type: System.Diagnostics.Process
* Assembly: System, Version=4.0.0.0
*/
StringBuilder cmdLine = new StringBuilder();
string str = StartInfo.FileName.Trim();
bool flag = str.StartsWith("\"", StringComparison.Ordinal) && str.EndsWith("\"", StringComparison.Ordinal);
if (!flag)
cmdLine.Append("\"");
cmdLine.Append(str);
if (!flag)
cmdLine.Append("\"");
if (!string.IsNullOrEmpty(StartInfo.Arguments))
{
cmdLine.Append(" ");
cmdLine.Append(StartInfo.Arguments);
}
/*
* private bool StartWithCreateProcess(ProcessStartInfo startInfo);
*
* Declaring Type: System.Diagnostics.Process
* Assembly: System, Version=4.0.0.0
*/
Win32.STARTUPINFO lpStartupInfo = new Win32.STARTUPINFO()
{
hStdError = new SafeFileHandle(IntPtr.Zero, false),
hStdInput = new SafeFileHandle(IntPtr.Zero, false),
hStdOutput = new SafeFileHandle(IntPtr.Zero, false)
};
Win32.PROCESS_INFORMATION lpProcessInformation = new Win32.PROCESS_INFORMATION();
IntPtr processHandle = IntPtr.Zero;
IntPtr handle2 = IntPtr.Zero;
SafeFileHandle parentHandle = null;
SafeFileHandle handle4 = null;
SafeFileHandle handle5 = null;
int error = 0;
GCHandle handle6 = new GCHandle();
try
{
if (StartInfo.RedirectStandardInput || StartInfo.RedirectStandardOutput || StartInfo.RedirectStandardError)
{
if (StartInfo.RedirectStandardInput)
CreatePipe(out parentHandle, out lpStartupInfo.hStdInput, true);
else
lpStartupInfo.hStdInput = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_INPUT_HANDLE), false);
if (StartInfo.RedirectStandardOutput)
CreatePipe(out handle4, out lpStartupInfo.hStdOutput, false);
else
lpStartupInfo.hStdOutput = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_OUTPUT_HANDLE), false);
if (StartInfo.RedirectStandardError)
CreatePipe(out handle5, out lpStartupInfo.hStdError, false);
else
lpStartupInfo.hStdError = new SafeFileHandle(Win32.GetStdHandle(Win32.StdHandles.STD_ERROR_HANDLE), false);
lpStartupInfo.dwFlags = 0x100;
}
Win32.ProcessCreationFlags creationFlags = Win32.ProcessCreationFlags.CREATE_SUSPENDED;
if (StartInfo.CreateNoWindow)
creationFlags |= Win32.ProcessCreationFlags.CREATE_NO_WINDOW;
if (Utilities.IsNt)
{
creationFlags |= Win32.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
handle6 = GCHandle.Alloc(EnvironmentBlock.ToByteArray(StartInfo.EnvironmentVariables, true), GCHandleType.Pinned);
}
else
handle6 = GCHandle.Alloc(EnvironmentBlock.ToByteArray(StartInfo.EnvironmentVariables, false), GCHandleType.Pinned);
string workingDirectory = StartInfo.WorkingDirectory;
if (workingDirectory == string.Empty)
workingDirectory = Environment.CurrentDirectory;
if (StartInfo.UserName.Length != 0)
{
Win32.LogonFlags logonFlags = 0;
if (StartInfo.LoadUserProfile)
logonFlags = Win32.LogonFlags.LOGON_WITH_PROFILE;
IntPtr password = IntPtr.Zero;
try
{
if (StartInfo.Password == null)
password = Marshal.StringToCoTaskMemUni(string.Empty);
else
password = Marshal.SecureStringToCoTaskMemUnicode(StartInfo.Password);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
flag = Win32.CreateProcessWithLogon(StartInfo.UserName, StartInfo.Domain, password, logonFlags, null, cmdLine, creationFlags, handle6.AddrOfPinnedObject(), workingDirectory, ref lpStartupInfo, out lpProcessInformation);
if (!flag)
error = Marshal.GetLastWin32Error();
if (lpProcessInformation.hProcess != IntPtr.Zero && lpProcessInformation.hProcess != Win32.INVALID_HANDLE_VALUE)
processHandle = lpProcessInformation.hProcess;
if (lpProcessInformation.hThread != IntPtr.Zero && lpProcessInformation.hThread != Win32.INVALID_HANDLE_VALUE)
handle2 = lpProcessInformation.hThread;
}
if (!flag)
{
if ((error != 0xc1) && (error != 0xd8))
throw new Win32Exception(error);
throw new Win32Exception(error, "InvalidApplication");
}
}
finally
{
if (password != IntPtr.Zero)
Marshal.ZeroFreeCoTaskMemUnicode(password);
}
}
else
{
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
flag = Win32.CreateProcess(null, cmdLine, IntPtr.Zero, IntPtr.Zero, true, creationFlags, handle6.AddrOfPinnedObject(), workingDirectory, ref lpStartupInfo, out lpProcessInformation);
if (!flag)
error = Marshal.GetLastWin32Error();
if (lpProcessInformation.hProcess != IntPtr.Zero && lpProcessInformation.hProcess != Win32.INVALID_HANDLE_VALUE)
processHandle = lpProcessInformation.hProcess;
if (lpProcessInformation.hThread != IntPtr.Zero && lpProcessInformation.hThread != Win32.INVALID_HANDLE_VALUE)
handle2 = lpProcessInformation.hThread;
}
if (!flag)
{
if ((error != 0xc1) && (error != 0xd8))
throw new Win32Exception(error);
throw new Win32Exception(error, "InvalidApplication");
}
}
}
finally
{
if (handle6.IsAllocated)
handle6.Free();
if (lpStartupInfo.hStdInput != null && !lpStartupInfo.hStdInput.IsInvalid)
lpStartupInfo.hStdInput.Close();
if (lpStartupInfo.hStdOutput != null && !lpStartupInfo.hStdOutput.IsInvalid)
lpStartupInfo.hStdOutput.Close();
if (lpStartupInfo.hStdError != null && !lpStartupInfo.hStdError.IsInvalid)
lpStartupInfo.hStdError.Close();
}
if (processHandle != IntPtr.Zero && processHandle != Win32.INVALID_HANDLE_VALUE)
Win32.CloseHandle(handle2);
process = Process.GetProcessById((int)lpProcessInformation.dwProcessId);
if (StartInfo.RedirectStandardInput)
{
FieldInfo standardInput = typeof(Process).GetField("standardInput", BindingFlags.Instance | BindingFlags.NonPublic);
standardInput.SetValue(process, new StreamWriter(new FileStream(parentHandle, FileAccess.Write, 0x1000, false), Console.InputEncoding, 0x1000)
{
AutoFlush = true
});
}
if (StartInfo.RedirectStandardOutput)
{
FieldInfo standardOutput = typeof(Process).GetField("standardOutput", BindingFlags.Instance | BindingFlags.NonPublic);
standardOutput.SetValue(process, new StreamReader(new FileStream(handle4, FileAccess.Read, 0x1000, false), (StartInfo.StandardOutputEncoding != null) ? StartInfo.StandardOutputEncoding : Console.OutputEncoding, true, 0x1000));
}
if (StartInfo.RedirectStandardError)
{
FieldInfo standardError = typeof(Process).GetField("standardError", BindingFlags.Instance | BindingFlags.NonPublic);
standardError.SetValue(process, new StreamReader(new FileStream(handle5, FileAccess.Read, 0x1000, false), (StartInfo.StandardErrorEncoding != null) ? StartInfo.StandardErrorEncoding : Console.OutputEncoding, true, 0x1000));
}
}
else
process = Process.Start(StartInfo);
return new DllInjector(process, FreeOnDispose);
}
private static void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
{
/*
* private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs);
*
* Declaring Type: System.Diagnostics.Process
* Assembly: System, Version=4.0.0.0
*/
parentHandle = childHandle = null;
Win32.SECURITY_ATTRIBUTES lpPipeAttributes = new Win32.SECURITY_ATTRIBUTES();
lpPipeAttributes.bInheritHandle = true;
SafeFileHandle hWritePipe = null;
try
{
if (parentInputs && (!Win32.CreatePipe(out childHandle, out hWritePipe, ref lpPipeAttributes, 0) || childHandle.IsInvalid || hWritePipe.IsInvalid))
throw new Win32Exception();
else if (!parentInputs && (!Win32.CreatePipe(out hWritePipe, out childHandle, ref lpPipeAttributes, 0) || hWritePipe.IsInvalid || childHandle.IsInvalid))
throw new Win32Exception();
if (!Win32.DuplicateHandle(Process.GetCurrentProcess().Handle, hWritePipe, Process.GetCurrentProcess().Handle, out parentHandle, 0, false, 2))
throw new Win32Exception();
}
finally
{
if (hWritePipe != null && !hWritePipe.IsInvalid)
hWritePipe.Close();
}
}
private static class EnvironmentBlock
{
private sealed class OrdinalCaseInsensitiveComparer : System.Collections.IComparer
{
/*
* private class OrdinalCaseInsensitiveComparer : IComparer
*
* Name: System.Diagnostics.OrdinalCaseInsensitiveComparer
* Assembly: System, Version=4.0.0.0
*/
public static readonly OrdinalCaseInsensitiveComparer Default = new OrdinalCaseInsensitiveComparer();
public int Compare(object a, object b)
{
string strA = a as string;
string strB = b as string;
if (strA != null && strB != null)
return string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase);
return System.Collections.Comparer.Default.Compare(a, b);
}
}
public static byte[] ToByteArray(System.Collections.Specialized.StringDictionary sd, bool unicode)
{
/*
* public static byte[] ToByteArray(StringDictionary sd, bool unicode);
*
* Declaring Type: System.Diagnostics.EnvironmentBlock
* Assembly: System, Version=4.0.0.0
*/
string[] array = new string[sd.Count];
byte[] bytes = null;
sd.Keys.CopyTo(array, 0);
string[] strArray2 = new string[sd.Count];
sd.Values.CopyTo(strArray2, 0);
Array.Sort(array, strArray2, OrdinalCaseInsensitiveComparer.Default);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < sd.Count; i++)
{
builder.Append(array[i]);
builder.Append('=');
builder.Append(strArray2[i]);
builder.Append('\0');
}
builder.Append('\0');
if (unicode)
bytes = Encoding.Unicode.GetBytes(builder.ToString());
else
bytes = Encoding.Default.GetBytes(builder.ToString());
if (bytes.Length > 0xffff)
throw new InvalidOperationException("EnvironmentBlockTooLong");
return bytes;
}
}
}
}