forked from FuzzySecurity/Sharp-Suite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreprobate.cs
1445 lines (1299 loc) · 70.3 KB
/
reprobate.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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace YourProjectHere
{
class reprobate
{
/// <summary>
/// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments.
/// </summary>
/// <author>The Wover (@TheRealWover)</author>
/// <param name="DLLName">Name of the DLL.</param>
/// <param name="FunctionName">Name of the function.</param>
/// <param name="FunctionDelegateType">Prototype for the function, represented as a Delegate object.</param>
/// <param name="Parameters">Parameters to pass to the function. Can be modified if function uses call by reference.</param>
/// <returns>Object returned by the function. Must be unmarshalled by the caller.</returns>
public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters)
{
IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName);
return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters);
}
/// <summary>
/// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory.
/// </summary>
/// <author>The Wover (@TheRealWover)</author>
/// <param name="FunctionPointer">A pointer to the unmanaged function.</param>
/// <param name="FunctionDelegateType">Prototype for the function, represented as a Delegate object.</param>
/// <param name="Parameters">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>
/// <returns>Object returned by the function. Must be unmarshalled by the caller.</returns>
public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters)
{
Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType);
return funcDelegate.DynamicInvoke(Parameters);
}
/// <summary>
/// Resolves LdrLoadDll and uses that function to load a DLL from disk.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLPath">The path to the DLL on disk. Uses the LoadLibrary convention.</param>
/// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully.</returns>
public static IntPtr LoadModuleFromDisk(string DLLPath)
{
h_reprobate.UNICODE_STRING uModuleName = new h_reprobate.UNICODE_STRING();
h_reprobate.RtlInitUnicodeString(ref uModuleName, DLLPath);
IntPtr hModule = IntPtr.Zero;
h_reprobate.NTSTATUS CallResult = h_reprobate.LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule);
if (CallResult != h_reprobate.NTSTATUS.Success || hModule == IntPtr.Zero)
{
return IntPtr.Zero;
}
return hModule;
}
/// <summary>
/// Helper for getting the pointer to a function from a DLL loaded by the process.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLName">The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").</param>
/// <param name="FunctionName">Name of the exported procedure.</param>
/// <param name="CanLoadFromDisk">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false)
{
IntPtr hModule = GetLoadedModuleAddress(DLLName);
if (hModule == IntPtr.Zero && CanLoadFromDisk)
{
hModule = LoadModuleFromDisk(DLLName);
if (hModule == IntPtr.Zero)
{
throw new FileNotFoundException(DLLName + ", unable to find the specified file.");
}
}
else if (hModule == IntPtr.Zero)
{
throw new DllNotFoundException(DLLName + ", Dll was not found.");
}
return GetExportAddress(hModule, FunctionName);
}
/// <summary>
/// Helper for getting the pointer to a function from a DLL loaded by the process.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLName">The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").</param>
/// <param name="Ordinal">Ordinal of the exported procedure.</param>
/// <param name="CanLoadFromDisk">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetLibraryAddress(string DLLName, short Ordinal, bool CanLoadFromDisk = false)
{
IntPtr hModule = GetLoadedModuleAddress(DLLName);
if (hModule == IntPtr.Zero && CanLoadFromDisk)
{
hModule = LoadModuleFromDisk(DLLName);
if (hModule == IntPtr.Zero)
{
throw new FileNotFoundException(DLLName + ", unable to find the specified file.");
}
}
else if (hModule == IntPtr.Zero)
{
throw new DllNotFoundException(DLLName + ", Dll was not found.");
}
return GetExportAddress(hModule, Ordinal);
}
/// <summary>
/// Helper for getting the pointer to a function from a DLL loaded by the process.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLName">The name of the DLL (e.g. "ntdll.dll" or "C:\Windows\System32\ntdll.dll").</param>
/// <param name="FunctionHash">Hash of the exported procedure.</param>
/// <param name="Key">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>
/// <param name="CanLoadFromDisk">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetLibraryAddress(string DLLName, string FunctionHash, long Key, bool CanLoadFromDisk = false)
{
IntPtr hModule = GetLoadedModuleAddress(DLLName);
if (hModule == IntPtr.Zero && CanLoadFromDisk)
{
hModule = LoadModuleFromDisk(DLLName);
if (hModule == IntPtr.Zero)
{
throw new FileNotFoundException(DLLName + ", unable to find the specified file.");
}
}
else if (hModule == IntPtr.Zero)
{
throw new DllNotFoundException(DLLName + ", Dll was not found.");
}
return GetExportAddress(hModule, FunctionHash, Key);
}
/// <summary>
/// Helper for getting the base address of a module loaded by the current process. This base
/// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for
/// manual export parsing. This function uses the .NET System.Diagnostics.Process class.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLName">The name of the DLL (e.g. "ntdll.dll").</param>
/// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.</returns>
public static IntPtr GetLoadedModuleAddress(string DLLName)
{
ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;
foreach (ProcessModule Mod in ProcModules)
{
if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower()))
{
return Mod.BaseAddress;
}
}
return IntPtr.Zero;
}
/// <summary>
/// Helper for getting the base address of a module loaded by the current process. This base
/// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for
/// manual export parsing. This function parses the _PEB_LDR_DATA structure.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLName">The name of the DLL (e.g. "ntdll.dll").</param>
/// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.</returns>
public static IntPtr GetPebLdrModuleEntry(string DLLName)
{
// Get _PEB pointer
h_reprobate.PROCESS_BASIC_INFORMATION pbi = h_reprobate.NtQueryInformationProcessBasicInformation((IntPtr)(-1));
// Set function variables
bool Is32Bit = false;
UInt32 LdrDataOffset = 0;
UInt32 InLoadOrderModuleListOffset = 0;
if (IntPtr.Size == 4)
{
Is32Bit = true;
LdrDataOffset = 0xc;
InLoadOrderModuleListOffset = 0xC;
}
else
{
LdrDataOffset = 0x18;
InLoadOrderModuleListOffset = 0x10;
}
// Get module InLoadOrderModuleList -> _LIST_ENTRY
IntPtr PEB_LDR_DATA = Marshal.ReadIntPtr((IntPtr)((UInt64)pbi.PebBaseAddress + LdrDataOffset));
IntPtr pInLoadOrderModuleList = (IntPtr)((UInt64)PEB_LDR_DATA + InLoadOrderModuleListOffset);
h_reprobate.LIST_ENTRY le = (h_reprobate.LIST_ENTRY)Marshal.PtrToStructure(pInLoadOrderModuleList, typeof(h_reprobate.LIST_ENTRY));
// Loop entries
IntPtr flink = le.Flink;
IntPtr hModule = IntPtr.Zero;
h_reprobate.PE.LDR_DATA_TABLE_ENTRY dte = (h_reprobate.PE.LDR_DATA_TABLE_ENTRY)Marshal.PtrToStructure(flink, typeof(h_reprobate.PE.LDR_DATA_TABLE_ENTRY));
while (dte.InLoadOrderLinks.Flink != le.Blink)
{
// Match module name
if (Marshal.PtrToStringUni(dte.FullDllName.Buffer).EndsWith(DLLName, StringComparison.OrdinalIgnoreCase))
{
hModule = dte.DllBase;
}
// Move Ptr
flink = dte.InLoadOrderLinks.Flink;
dte = (h_reprobate.PE.LDR_DATA_TABLE_ENTRY)Marshal.PtrToStructure(flink, typeof(h_reprobate.PE.LDR_DATA_TABLE_ENTRY));
}
return hModule;
}
/// <summary>
/// Generate an HMAC-MD5 hash of the supplied string using an Int64 as the key. This is useful for unique hash based API lookups.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="APIName">API name to hash.</param>
/// <param name="Key">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>
/// <returns>string, the computed MD5 hash value.</returns>
public static string GetAPIHash(string APIName, long Key)
{
byte[] data = Encoding.UTF8.GetBytes(APIName.ToLower());
byte[] kbytes = BitConverter.GetBytes(Key);
using (HMACMD5 hmac = new HMACMD5(kbytes))
{
byte[] bHash = hmac.ComputeHash(data);
return BitConverter.ToString(bHash).Replace("-", "");
}
}
/// <summary>
/// Given a module base address, resolve the address of a function by manually walking the module export table.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
/// <param name="ExportName">The name of the export to search for (e.g. "NtAlertResumeThread").</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
{
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));
// Loop the array of export name RVA's
for (int i = 0; i < NumberOfNames; i++)
{
string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))
{
Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
break;
}
}
}
catch
{
// Catch parser failure
throw new InvalidOperationException("Failed to parse module exports.");
}
if (FunctionPtr == IntPtr.Zero)
{
// Export not found
throw new MissingMethodException(ExportName + ", export not found.");
}
return FunctionPtr;
}
/// <summary>
/// Given a module base address, resolve the address of a function by manually walking the module export table.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
/// <param name="Ordinal">The ordinal number to search for (e.g. 0x136 -> ntdll!NtCreateThreadEx).</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetExportAddress(IntPtr ModuleBase, short Ordinal)
{
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));
// Loop the array of export name RVA's
for (int i = 0; i < NumberOfNames; i++)
{
Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
if (FunctionOrdinal == Ordinal)
{
Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
break;
}
}
}
catch
{
// Catch parser failure
throw new InvalidOperationException("Failed to parse module exports.");
}
if (FunctionPtr == IntPtr.Zero)
{
// Export not found
throw new MissingMethodException(Ordinal + ", ordinal not found.");
}
return FunctionPtr;
}
/// <summary>
/// Given a module base address, resolve the address of a function by manually walking the module export table.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
/// <param name="FunctionHash">Hash of the exported procedure.</param>
/// <param name="Key">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetExportAddress(IntPtr ModuleBase, string FunctionHash, long Key)
{
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));
// Loop the array of export name RVA's
for (int i = 0; i < NumberOfNames; i++)
{
string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
if (GetAPIHash(FunctionName, Key).Equals(FunctionHash, StringComparison.OrdinalIgnoreCase))
{
Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
break;
}
}
}
catch
{
// Catch parser failure
throw new InvalidOperationException("Failed to parse module exports.");
}
if (FunctionPtr == IntPtr.Zero)
{
// Export not found
throw new MissingMethodException(FunctionHash + ", export hash not found.");
}
return FunctionPtr;
}
/// <summary>
/// Given a module base address, resolve the address of a function by calling LdrGetProcedureAddress.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
/// <param name="ExportName">The name of the export to search for (e.g. "NtAlertResumeThread").</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetNativeExportAddress(IntPtr ModuleBase, string ExportName)
{
h_reprobate.ANSI_STRING aFunc = new h_reprobate.ANSI_STRING
{
Length = (ushort)ExportName.Length,
MaximumLength = (ushort)(ExportName.Length + 2),
Buffer = Marshal.StringToCoTaskMemAnsi(ExportName)
};
IntPtr pAFunc = Marshal.AllocHGlobal(Marshal.SizeOf(aFunc));
Marshal.StructureToPtr(aFunc, pAFunc, true);
IntPtr pFuncAddr = IntPtr.Zero;
h_reprobate.LdrGetProcedureAddress(ModuleBase, pAFunc, IntPtr.Zero, ref pFuncAddr);
Marshal.FreeHGlobal(pAFunc);
return pFuncAddr;
}
/// <summary>
/// Given a module base address, resolve the address of a function by calling LdrGetProcedureAddress.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
/// <param name="Ordinal">The ordinal number to search for (e.g. 0x136 -> ntdll!NtCreateThreadEx).</param>
/// <returns>IntPtr for the desired function.</returns>
public static IntPtr GetNativeExportAddress(IntPtr ModuleBase, short Ordinal)
{
IntPtr pFuncAddr = IntPtr.Zero;
IntPtr pOrd = (IntPtr)Ordinal;
h_reprobate.LdrGetProcedureAddress(ModuleBase, IntPtr.Zero, pOrd, ref pFuncAddr);
return pFuncAddr;
}
/// <summary>
/// Retrieve PE header information from the module base pointer.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="pModule">Pointer to the module base.</param>
/// <returns>h_reprobate.PE.PE_META_DATA</returns>
public static h_reprobate.PE.PE_META_DATA GetPeMetaData(IntPtr pModule)
{
h_reprobate.PE.PE_META_DATA PeMetaData = new h_reprobate.PE.PE_META_DATA();
try
{
UInt32 e_lfanew = (UInt32)Marshal.ReadInt32((IntPtr)((UInt64)pModule + 0x3c));
PeMetaData.Pe = (UInt32)Marshal.ReadInt32((IntPtr)((UInt64)pModule + e_lfanew));
// Validate PE signature
if (PeMetaData.Pe != 0x4550)
{
throw new InvalidOperationException("Invalid PE signature.");
}
PeMetaData.ImageFileHeader = (h_reprobate.PE.IMAGE_FILE_HEADER)Marshal.PtrToStructure((IntPtr)((UInt64)pModule + e_lfanew + 0x4), typeof(h_reprobate.PE.IMAGE_FILE_HEADER));
IntPtr OptHeader = (IntPtr)((UInt64)pModule + e_lfanew + 0x18);
UInt16 PEArch = (UInt16)Marshal.ReadInt16(OptHeader);
// Validate PE arch
if (PEArch == 0x010b) // Image is x32
{
PeMetaData.Is32Bit = true;
PeMetaData.OptHeader32 = (h_reprobate.PE.IMAGE_OPTIONAL_HEADER32)Marshal.PtrToStructure(OptHeader, typeof(h_reprobate.PE.IMAGE_OPTIONAL_HEADER32));
}
else if (PEArch == 0x020b) // Image is x64
{
PeMetaData.Is32Bit = false;
PeMetaData.OptHeader64 = (h_reprobate.PE.IMAGE_OPTIONAL_HEADER64)Marshal.PtrToStructure(OptHeader, typeof(h_reprobate.PE.IMAGE_OPTIONAL_HEADER64));
}
else
{
throw new InvalidOperationException("Invalid magic value (PE32/PE32+).");
}
// Read sections
h_reprobate.PE.IMAGE_SECTION_HEADER[] SectionArray = new h_reprobate.PE.IMAGE_SECTION_HEADER[PeMetaData.ImageFileHeader.NumberOfSections];
for (int i = 0; i < PeMetaData.ImageFileHeader.NumberOfSections; i++)
{
IntPtr SectionPtr = (IntPtr)((UInt64)OptHeader + PeMetaData.ImageFileHeader.SizeOfOptionalHeader + (UInt32)(i * 0x28));
SectionArray[i] = (h_reprobate.PE.IMAGE_SECTION_HEADER)Marshal.PtrToStructure(SectionPtr, typeof(h_reprobate.PE.IMAGE_SECTION_HEADER));
}
PeMetaData.Sections = SectionArray;
}
catch
{
throw new InvalidOperationException("Invalid module base specified.");
}
return PeMetaData;
}
/// <summary>
/// Resolve host DLL for API Set DLL.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <returns>Dictionary, a combination of Key:APISetDLL and Val:HostDLL.</returns>
public static Dictionary<string, string> GetApiSetMapping()
{
h_reprobate.PROCESS_BASIC_INFORMATION pbi = h_reprobate.NtQueryInformationProcessBasicInformation((IntPtr)(-1));
UInt32 ApiSetMapOffset = IntPtr.Size == 4 ? (UInt32)0x38 : 0x68;
// Create mapping dictionary
Dictionary<string, string> ApiSetDict = new Dictionary<string, string>();
IntPtr pApiSetNamespace = Marshal.ReadIntPtr((IntPtr)((UInt64)pbi.PebBaseAddress + ApiSetMapOffset));
h_reprobate.PE.ApiSetNamespace Namespace = (h_reprobate.PE.ApiSetNamespace)Marshal.PtrToStructure(pApiSetNamespace, typeof(h_reprobate.PE.ApiSetNamespace));
for (var i = 0; i < Namespace.Count; i++)
{
h_reprobate.PE.ApiSetNamespaceEntry SetEntry = new h_reprobate.PE.ApiSetNamespaceEntry();
SetEntry = (h_reprobate.PE.ApiSetNamespaceEntry)Marshal.PtrToStructure((IntPtr)((UInt64)pApiSetNamespace + (UInt64)Namespace.EntryOffset + (UInt64)(i * Marshal.SizeOf(SetEntry))), typeof(h_reprobate.PE.ApiSetNamespaceEntry));
string ApiSetEntryName = Marshal.PtrToStringUni((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetEntry.NameOffset), SetEntry.NameLength / 2) + ".dll";
h_reprobate.PE.ApiSetValueEntry SetValue = new h_reprobate.PE.ApiSetValueEntry();
SetValue = (h_reprobate.PE.ApiSetValueEntry)Marshal.PtrToStructure((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetEntry.ValueOffset), typeof(h_reprobate.PE.ApiSetValueEntry));
string ApiSetValue = string.Empty;
if (SetValue.ValueCount != 0)
{
ApiSetValue = Marshal.PtrToStringUni((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetValue.ValueOffset), SetValue.ValueCount / 2);
}
// Add pair to dict
ApiSetDict.Add(ApiSetEntryName, ApiSetValue);
}
// Return dict
return ApiSetDict;
}
/// <summary>
/// Call a manually mapped PE by its EntryPoint.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="PEINFO">Module meta data struct (h_reprobate.PE.PE_META_DATA).</param>
/// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
/// <returns>void</returns>
public static void CallMappedPEModule(h_reprobate.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
{
// Call module by EntryPoint (eg Mimikatz.exe)
IntPtr hRemoteThread = IntPtr.Zero;
IntPtr lpStartAddress = PEINFO.Is32Bit ? (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader32.AddressOfEntryPoint) :
(IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader64.AddressOfEntryPoint);
h_reprobate.NtCreateThreadEx(
ref hRemoteThread,
h_reprobate.Win32.WinNT.ACCESS_MASK.STANDARD_RIGHTS_ALL,
IntPtr.Zero, (IntPtr)(-1),
lpStartAddress, IntPtr.Zero,
false, 0, 0, 0, IntPtr.Zero
);
}
/// <summary>
/// Call a manually mapped DLL by DllMain -> DLL_PROCESS_ATTACH.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="PEINFO">Module meta data struct (h_reprobate.PE.PE_META_DATA).</param>
/// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
/// <returns>void</returns>
public static void CallMappedDLLModule(h_reprobate.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
{
IntPtr lpEntryPoint = PEINFO.Is32Bit ? (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader32.AddressOfEntryPoint) :
(IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader64.AddressOfEntryPoint);
h_reprobate.PE.DllMain fDllMain = (h_reprobate.PE.DllMain)Marshal.GetDelegateForFunctionPointer(lpEntryPoint, typeof(h_reprobate.PE.DllMain));
bool CallRes = fDllMain(ModuleMemoryBase, h_reprobate.PE.DLL_PROCESS_ATTACH, IntPtr.Zero);
if (!CallRes)
{
throw new InvalidOperationException("Failed to call DllMain -> DLL_PROCESS_ATTACH");
}
}
/// <summary>
/// Call a manually mapped DLL by Export.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="PEINFO">Module meta data struct (h_reprobate.PE.PE_META_DATA).</param>
/// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
/// <param name="ExportName">The name of the export to search for (e.g. "NtAlertResumeThread").</param>
/// <param name="FunctionDelegateType">Prototype for the function, represented as a Delegate object.</param>
/// <param name="Parameters">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>
/// <param name="CallEntry">Specify whether to invoke the module's entry point.</param>
/// <returns>void</returns>
public static object CallMappedDLLModuleExport(h_reprobate.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase, string ExportName, Type FunctionDelegateType, object[] Parameters, bool CallEntry = true)
{
// Call entry point if user has specified
if (CallEntry)
{
CallMappedDLLModule(PEINFO, ModuleMemoryBase);
}
// Get export pointer
IntPtr pFunc = GetExportAddress(ModuleMemoryBase, ExportName);
// Call export
return DynamicFunctionInvoke(pFunc, FunctionDelegateType, ref Parameters);
}
/// <summary>
/// Read ntdll from disk, find/copy the appropriate syscall stub and free ntdll.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="FunctionName">The name of the function to search for (e.g. "NtAlertResumeThread").</param>
/// <returns>IntPtr, Syscall stub</returns>
public static IntPtr GetSyscallStub(string FunctionName)
{
// Verify process & architecture
bool isWOW64 = h_reprobate.NtQueryInformationProcessWow64Information((IntPtr)(-1));
if (IntPtr.Size == 4 && isWOW64)
{
throw new InvalidOperationException("Generating Syscall stubs is not supported for WOW64.");
}
// Find the path for ntdll by looking at the currently loaded module
string NtdllPath = string.Empty;
ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;
foreach (ProcessModule Mod in ProcModules)
{
if (Mod.FileName.EndsWith("ntdll.dll", StringComparison.OrdinalIgnoreCase))
{
NtdllPath = Mod.FileName;
}
}
// Alloc module into memory for parsing
IntPtr pModule = AllocateFileToMemory(NtdllPath);
// Fetch PE meta data
h_reprobate.PE.PE_META_DATA PEINFO = GetPeMetaData(pModule);
// Alloc PE image memory -> RW
IntPtr BaseAddress = IntPtr.Zero;
IntPtr RegionSize = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;
UInt32 SizeOfHeaders = PEINFO.Is32Bit ? PEINFO.OptHeader32.SizeOfHeaders : PEINFO.OptHeader64.SizeOfHeaders;
IntPtr pImage = h_reprobate.NtAllocateVirtualMemory(
(IntPtr)(-1), ref BaseAddress, IntPtr.Zero, ref RegionSize,
h_reprobate.Win32.Kernel32.AllocationType.Commit | h_reprobate.Win32.Kernel32.AllocationType.Reserve,
h_reprobate.Win32.WinNT.PAGE_READWRITE
);
// Write PE header to memory
UInt32 BytesWritten = h_reprobate.NtWriteVirtualMemory((IntPtr)(-1), pImage, pModule, SizeOfHeaders);
// Write sections to memory
foreach (h_reprobate.PE.IMAGE_SECTION_HEADER ish in PEINFO.Sections)
{
// Calculate offsets
IntPtr pVirtualSectionBase = (IntPtr)((UInt64)pImage + ish.VirtualAddress);
IntPtr pRawSectionBase = (IntPtr)((UInt64)pModule + ish.PointerToRawData);
// Write data
BytesWritten = h_reprobate.NtWriteVirtualMemory((IntPtr)(-1), pVirtualSectionBase, pRawSectionBase, ish.SizeOfRawData);
if (BytesWritten != ish.SizeOfRawData)
{
throw new InvalidOperationException("Failed to write to memory.");
}
}
// Get Ptr to function
IntPtr pFunc = GetExportAddress(pImage, FunctionName);
if (pFunc == IntPtr.Zero)
{
throw new InvalidOperationException("Failed to resolve ntdll export.");
}
// Alloc memory for call stub
BaseAddress = IntPtr.Zero;
RegionSize = (IntPtr)0x50;
IntPtr pCallStub = h_reprobate.NtAllocateVirtualMemory(
(IntPtr)(-1), ref BaseAddress, IntPtr.Zero, ref RegionSize,
h_reprobate.Win32.Kernel32.AllocationType.Commit | h_reprobate.Win32.Kernel32.AllocationType.Reserve,
h_reprobate.Win32.WinNT.PAGE_READWRITE
);
// Write call stub
BytesWritten = h_reprobate.NtWriteVirtualMemory((IntPtr)(-1), pCallStub, pFunc, 0x50);
if (BytesWritten != 0x50)
{
throw new InvalidOperationException("Failed to write to memory.");
}
// Change call stub permissions
h_reprobate.NtProtectVirtualMemory((IntPtr)(-1), ref pCallStub, ref RegionSize, h_reprobate.Win32.WinNT.PAGE_EXECUTE_READ);
// Free temporary allocations
Marshal.FreeHGlobal(pModule);
RegionSize = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;
h_reprobate.NtFreeVirtualMemory((IntPtr)(-1), ref pImage, ref RegionSize, h_reprobate.Win32.Kernel32.AllocationType.Reserve);
return pCallStub;
}
/// <summary>
/// Maps a DLL from disk into a Section using NtCreateSection.
/// </summary>
/// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>
/// <param name="DLLPath">Full path fo the DLL on disk.</param>
/// <returns>h_reprobate.PE.PE_MANUAL_MAP</returns>
public static h_reprobate.PE.PE_MANUAL_MAP MapModuleFromDisk(string DLLPath)
{
// Check file exists
if (!File.Exists(DLLPath))
{
throw new InvalidOperationException("Filepath not found.");
}
// Open file handle
h_reprobate.UNICODE_STRING ObjectName = new h_reprobate.UNICODE_STRING();
h_reprobate.RtlInitUnicodeString(ref ObjectName, (@"\??\" + DLLPath));
IntPtr pObjectName = Marshal.AllocHGlobal(Marshal.SizeOf(ObjectName));
Marshal.StructureToPtr(ObjectName, pObjectName, true);
h_reprobate.OBJECT_ATTRIBUTES objectAttributes = new h_reprobate.OBJECT_ATTRIBUTES();
objectAttributes.Length = Marshal.SizeOf(objectAttributes);
objectAttributes.ObjectName = pObjectName;
objectAttributes.Attributes = 0x40; // OBJ_CASE_INSENSITIVE
h_reprobate.IO_STATUS_BLOCK ioStatusBlock = new h_reprobate.IO_STATUS_BLOCK();
IntPtr hFile = IntPtr.Zero;
h_reprobate.NtOpenFile(
ref hFile,
h_reprobate.Win32.Kernel32.FileAccessFlags.FILE_READ_DATA |
h_reprobate.Win32.Kernel32.FileAccessFlags.FILE_EXECUTE |
h_reprobate.Win32.Kernel32.FileAccessFlags.FILE_READ_ATTRIBUTES |
h_reprobate.Win32.Kernel32.FileAccessFlags.SYNCHRONIZE,
ref objectAttributes, ref ioStatusBlock,
h_reprobate.Win32.Kernel32.FileShareFlags.FILE_SHARE_READ |
h_reprobate.Win32.Kernel32.FileShareFlags.FILE_SHARE_DELETE,
h_reprobate.Win32.Kernel32.FileOpenFlags.FILE_SYNCHRONOUS_IO_NONALERT |
h_reprobate.Win32.Kernel32.FileOpenFlags.FILE_NON_DIRECTORY_FILE
);
// Create section from hFile
IntPtr hSection = IntPtr.Zero;
ulong MaxSize = 0;
h_reprobate.NTSTATUS ret = h_reprobate.NtCreateSection(
ref hSection,
(UInt32)h_reprobate.Win32.WinNT.ACCESS_MASK.SECTION_ALL_ACCESS,
IntPtr.Zero,
ref MaxSize,
h_reprobate.Win32.WinNT.PAGE_READONLY,
h_reprobate.Win32.WinNT.SEC_IMAGE,
hFile
);
// Map view of file
IntPtr pBaseAddress = IntPtr.Zero;
h_reprobate.NtMapViewOfSection(
hSection, (IntPtr)(-1), ref pBaseAddress,
IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
ref MaxSize, 0x2, 0x0,
h_reprobate.Win32.WinNT.PAGE_READWRITE
);
// Prepare return object
h_reprobate.PE.PE_MANUAL_MAP SecMapObject = new h_reprobate.PE.PE_MANUAL_MAP
{
PEINFO = GetPeMetaData(pBaseAddress),
ModuleBase = pBaseAddress
};
return SecMapObject;
}
/// <summary>
/// Allocate file to memory from disk
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="FilePath">Full path to the file to be alloacted.</param>
/// <returns>IntPtr base address of the allocated file.</returns>
public static IntPtr AllocateFileToMemory(string FilePath)
{
if (!File.Exists(FilePath))
{
throw new InvalidOperationException("Filepath not found.");
}
byte[] bFile = File.ReadAllBytes(FilePath);
return AllocateBytesToMemory(bFile);
}
/// <summary>
/// Allocate a byte array to memory
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="FileByteArray">Byte array to be allocated.</param>
/// <returns>IntPtr base address of the allocated file.</returns>
public static IntPtr AllocateBytesToMemory(byte[] FileByteArray)
{
IntPtr pFile = Marshal.AllocHGlobal(FileByteArray.Length);
Marshal.Copy(FileByteArray, 0, pFile, FileByteArray.Length);
return pFile;
}
/// <summary>
/// Relocates a module in memory.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="PEINFO">Module meta data struct (h_reprobate.PE.PE_META_DATA).</param>
/// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
/// <returns>void</returns>
public static void RelocateModule(h_reprobate.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
{
h_reprobate.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.BaseRelocationTable : PEINFO.OptHeader64.BaseRelocationTable;
Int64 ImageDelta = PEINFO.Is32Bit ? (Int64)((UInt64)ModuleMemoryBase - PEINFO.OptHeader32.ImageBase) :
(Int64)((UInt64)ModuleMemoryBase - PEINFO.OptHeader64.ImageBase);
// Ptr for the base reloc table
IntPtr pRelocTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);
Int32 nextRelocTableBlock = -1;
// Loop reloc blocks
while (nextRelocTableBlock != 0)
{
h_reprobate.PE.IMAGE_BASE_RELOCATION ibr = new h_reprobate.PE.IMAGE_BASE_RELOCATION();
ibr = (h_reprobate.PE.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(pRelocTable, typeof(h_reprobate.PE.IMAGE_BASE_RELOCATION));
Int64 RelocCount = ((ibr.SizeOfBlock - Marshal.SizeOf(ibr)) / 2);
for (int i = 0; i < RelocCount; i++)
{
// Calculate reloc entry ptr
IntPtr pRelocEntry = (IntPtr)((UInt64)pRelocTable + (UInt64)Marshal.SizeOf(ibr) + (UInt64)(i * 2));
UInt16 RelocValue = (UInt16)Marshal.ReadInt16(pRelocEntry);
// Parse reloc value
// The type should only ever be 0x0, 0x3, 0xA
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#base-relocation-types
UInt16 RelocType = (UInt16)(RelocValue >> 12);
UInt16 RelocPatch = (UInt16)(RelocValue & 0xfff);
// Perform relocation
if (RelocType != 0) // IMAGE_REL_BASED_ABSOLUTE (0 -> skip reloc)
{
try
{
IntPtr pPatch = (IntPtr)((UInt64)ModuleMemoryBase + ibr.VirtualAdress + RelocPatch);
if (RelocType == 0x3) // IMAGE_REL_BASED_HIGHLOW (x86)
{
Int32 OriginalPtr = Marshal.ReadInt32(pPatch);
Marshal.WriteInt32(pPatch, (OriginalPtr + (Int32)ImageDelta));
}
else // IMAGE_REL_BASED_DIR64 (x64)
{
Int64 OriginalPtr = Marshal.ReadInt64(pPatch);
Marshal.WriteInt64(pPatch, (OriginalPtr + ImageDelta));
}
}
catch
{
throw new InvalidOperationException("Memory access violation.");
}
}
}
// Check for next block
pRelocTable = (IntPtr)((UInt64)pRelocTable + ibr.SizeOfBlock);
nextRelocTableBlock = Marshal.ReadInt32(pRelocTable);
}
}
/// <summary>
/// Rewrite IAT for manually mapped module.
/// </summary>
/// <author>Ruben Boonen (@FuzzySec)</author>
/// <param name="PEINFO">Module meta data struct (h_reprobate.PE.PE_META_DATA).</param>
/// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
/// <returns>void</returns>
public static void RewriteModuleIAT(h_reprobate.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
{
h_reprobate.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.ImportTable : PEINFO.OptHeader64.ImportTable;
// Check if there is no import table
if (idd.VirtualAddress == 0)
{
// Return so that the rest of the module mapping process may continue.
return;
}
// Ptr for the base import directory
IntPtr pImportTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);
// Get API Set mapping dictionary if on Win10+
h_reprobate.OSVERSIONINFOEX OSVersion = new h_reprobate.OSVERSIONINFOEX();
h_reprobate.RtlGetVersion(ref OSVersion);
Dictionary<string, string> ApiSetDict = new Dictionary<string, string>();
if (OSVersion.MajorVersion >= 10)
{
ApiSetDict = GetApiSetMapping();
}
// Loop IID's
int counter = 0;
h_reprobate.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR iid = new h_reprobate.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR();
iid = (h_reprobate.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(
(IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),
typeof(h_reprobate.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)
);
while (iid.Name != 0)
{
// Get DLL
string DllName = string.Empty;
try
{
DllName = Marshal.PtrToStringAnsi((IntPtr)((UInt64)ModuleMemoryBase + iid.Name));
}
catch { }
// Loop imports
if (DllName == string.Empty)
{
throw new InvalidOperationException("Failed to read DLL name.");
}
else
{
// API Set DLL?
if (OSVersion.MajorVersion >= 10 && (DllName.StartsWith("api-") || DllName.StartsWith("ext-")) &&
ApiSetDict.ContainsKey(DllName) && ApiSetDict[DllName].Length > 0)
{
// Not all API set DLL's have a registered host mapping
DllName = ApiSetDict[DllName];
}
// Check and / or load DLL
IntPtr hModule = GetLoadedModuleAddress(DllName);
if (hModule == IntPtr.Zero)
{
hModule = LoadModuleFromDisk(DllName);
if (hModule == IntPtr.Zero)
{
throw new FileNotFoundException(DllName + ", unable to find the specified file.");
}
}
// Loop thunks
if (PEINFO.Is32Bit)
{
h_reprobate.PE.IMAGE_THUNK_DATA32 oft_itd = new h_reprobate.PE.IMAGE_THUNK_DATA32();
for (int i = 0; true; i++)
{
oft_itd = (h_reprobate.PE.IMAGE_THUNK_DATA32)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt32)(i * (sizeof(UInt32)))), typeof(h_reprobate.PE.IMAGE_THUNK_DATA32));
IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt32))));
if (oft_itd.AddressOfData == 0)
{
break;
}
if (oft_itd.AddressOfData < 0x80000000) // !IMAGE_ORDINAL_FLAG32
{
IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));
IntPtr pFunc = IntPtr.Zero;
pFunc = GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));
// Write ProcAddress
Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
}
else
{
ulong fOrdinal = oft_itd.AddressOfData & 0xFFFF;
IntPtr pFunc = IntPtr.Zero;
pFunc = GetNativeExportAddress(hModule, (short)fOrdinal);
// Write ProcAddress
Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
}
}