-
Notifications
You must be signed in to change notification settings - Fork 18
/
MineSweeperCore.c
executable file
·1815 lines (1401 loc) · 61.9 KB
/
MineSweeperCore.c
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
#include "MineSweeperCore.h"
BOOL beVerbose = FALSE; // verbose flag
// copies over remote process module to a local process buffer using ReadProcessMemory API
DWORD_PTR readRemoteModule(HMODULE hModule, HANDLE hProcess) {
MEMORY_BASIC_INFORMATION memoryBasicInformation = { 0 };
SIZE_T dllAllocationSize = 0;
DWORD_PTR base = (DWORD_PTR)hModule;
DWORD lastError = 0;
LPVOID remoteModuleBuffer = NULL;
// Get memory region info to find out the region size for our target module
// note: for x86 project sizeof(memInfo) returns 0x14 but the QueryVirtualMemoryInformation() function will fail it it's not 0x20 (which is the value that x64 binary would would get)
// Create required struct for the QueryVirtualMemoryInformation func
//WIN32_MEMORY_REGION_INFORMATION memInfo = { 0 };
// if (!QueryVirtualMemoryInformation(hProcess, hModule, MemoryRegionInfo, &memInfo, sizeof(memInfo), &writtenSize)) {
// // note: WinAPI bug alert: for x86 project sizeof(memInfo) returns 0x14 but the QueryVirtualMemoryInformation() function will fail if meminfo size is anything but 0x20 (which is the value that x64 project would have)
// if (!QueryVirtualMemoryInformation(hProcess, hModule, MemoryRegionInfo, &memInfo, 0x20, &writtenSize)) {
//
//#if _DEBUG
// printf("Failed to QueryVirtualMemoryInformation. Last error: %d\n", GetLastError());
//#endif
// return NULL;
// }
// }
// Loop through entire dll memory allocation section by section until we find out it's entire size
while (TRUE) {
if (VirtualQueryEx(hProcess, base, &memoryBasicInformation, sizeof(memoryBasicInformation))) {
// if allocation base matches with our target module handle (which acts as module base address as well)
if (memoryBasicInformation.AllocationBase == (PVOID)hModule) {
dllAllocationSize += memoryBasicInformation.RegionSize;
base += memoryBasicInformation.RegionSize;
}
else {
break;
}
}
else {
#if _DEBUG
printf("[!] Failed to VirtualQueryEx remote process memory! Last error: %d\n", lastError);
#endif
return NULL;
}
}
// now that we know the size of the target module, let's allocate our buffer
remoteModuleBuffer = malloc(dllAllocationSize);
//remoteModuleBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dllAllocationSize);
// now copy over the target module from the remote process
if (!ReadProcessMemory(hProcess, hModule, remoteModuleBuffer, dllAllocationSize, NULL)) {
lastError = GetLastError();
free(remoteModuleBuffer);
// in case ReadProcessMemory received error 299 (ERROR_PARTIAL_COPY) - return 1 - initializeMineSweeperModuleInfo will know what to do
if (lastError == 299) {
return 1;
}
else {
#if _DEBUG
printf("[!] Failed to read remote process memory! Last error: %d\n", lastError);
#endif
return NULL;
}
}
return remoteModuleBuffer;
}
// retrieves target module file path
wchar_t* getModuleFilePath(HMODULE hModule, HANDLE hProcess) {
PWSTR tempFileName[filePathLength] = { 0 }; // create a temporary PWSTR to be used with file name retrieval
DWORD fileNameLength; // to be used with file name retrieval
wchar_t* filePath = NULL;
// if process handle is NULL, let's get a handle to our local process
if (!hProcess)
hProcess = GetCurrentProcess();
// first, let's see how long the file name is:
//fileNameLength = GetModuleFileNameExW(hProcess, hModule, tempFileName, filePathLength);
// Note: we are using GetMappedFileNameW as per thread here in order to avoid wow64 file system redirector for 32-bit processes as per https://stackoverflow.com/questions/48178586/how-to-disable-wow64-file-system-redirection-for-getmodulefilenameex
fileNameLength = GetMappedFileNameW(hProcess, hModule, tempFileName, filePathLength);
// if there was an error retrieving the module's file name
if (fileNameLength == 0 || GetLastError() != 0) {
#if _DEBUG
printf("[!] Error retrieving module file name. Module handle: %#X\n", hModule);
#endif
return NULL;
}
// add 1 to account for the terminating null byte
fileNameLength++;
// now let's allocate enough space to hold our file name
filePath = (wchar_t*)malloc(sizeof(wchar_t) * fileNameLength);
// now, let's finally retrieve the file name
//if (GetModuleFileNameExW(hProcess, hModule, filePath, filePathLength) == 0 || GetLastError() != 0) {
if (GetMappedFileNameW(hProcess, hModule, filePath, filePathLength) == 0 || GetLastError() != 0) {
#if _DEBUG
printf("[!] Error retrieving module file name on the second attempt. Module handle: %#X\n", hModule);
#endif
free(filePath);
return NULL;
}
return filePath;
}
/*
A function to check whether more than 1% of the .text section has been detected to be overwritten. Returns TRUE if more than 1% of the .text section have been modified.
1% was picked based on real-world AV observations.
This function was created to accommodate for an edge case scenario where large parts of .text section of the module happens to be overwritten. While the reason for this phenomenon is uknown it did happened a few times during my testing.
*/
BOOL isTextSectionOverwritten(mineSweeperModuleInfo* targetModule) {
PIMAGE_SECTION_HEADER inMemoryTextSectionHeader = NULL;
inMemoryTextSectionHeader = getTextSection(targetModule->moduleBase);
DWORD sectionSize = inMemoryTextSectionHeader->Misc.VirtualSize;
// if the number of modified bytes in the .text section is greater than 1% of the entire .text section, consider the section to be overwritten
if (targetModule->modifiedRVAsLength > sectionSize / 100 ) {
return TRUE;
}
return FALSE;
}
// Initialize mineSweeperModuleInfo struct. If processHandle is NULL, then the function assumes that the target module is in the local process. Otherwise, it will treat the target module as a remote process module.
mineSweeperModuleInfo* initializeMineSweeperModuleInfo(HMODULE hModule, HANDLE hProcess) {
mineSweeperModuleInfo* targetModule;
// allocate memory for our mineSweeperModuleInfo struct
targetModule = (mineSweeperModuleInfo*)malloc(sizeof(mineSweeperModuleInfo));
// zero the contents of the struct
SecureZeroMemory(targetModule, sizeof(mineSweeperModuleInfo));
targetModule->hModule = hModule;
targetModule->hProcess = hProcess;
// get module filePath
targetModule->filePath = getModuleFilePath(hModule, hProcess);
if (targetModule->filePath == NULL) {
free(targetModule);
return NULL;
}
// extracting the module name out of the module path. the arithmetics below is in order to avoid the last backslash. We add 2 instead of 1 because this is a wide string.
targetModule->moduleName = (DWORD_PTR)wcsrchr(targetModule->filePath, L'\\') + 2;
// check whether we are targeting a local or remote process module
if (hProcess != GetCurrentProcess()) {
// if remote process - copy over the remote process module
targetModule->moduleBase = readRemoteModule(hModule, hProcess);
// in case we failed to read the remote process module - pull back
if (targetModule->moduleBase == 1 || targetModule->moduleBase == NULL) {
// in case ReadProcessMemory received error 299 (ERROR_PARTIAL_COPY)
if (targetModule->moduleBase == 1) {
printf("[!] %#X (%ls): the module is committed into memory only partially, we have to skip it.\n", targetModule->hModule, targetModule->moduleName);
}
free(targetModule);
return NULL;
}
}
else {
// if we are targeting a local process module - set module base to our hModule value
targetModule->moduleBase = hModule;
}
// check for MZ signature at the start of the module, mind little endianness
WORD* mz = targetModule->moduleBase;
if (*mz != 0x5A4D){
#if _DEBUG
printf("[!] MZ signature is missing!\n");
#endif
if (hProcess != GetCurrentProcess()) {
free(targetModule->moduleBase);
}
free(targetModule);
return NULL;
}
// get Export Directory Table - note we path module base and not hModule in case we are working with a remote process module
targetModule->edt = getExportDirectoryTable(targetModule->moduleBase);
if (targetModule->edt == NULL){
if (hProcess != GetCurrentProcess()) {
free(targetModule->moduleBase);
}
free(targetModule);
return NULL;
}
targetModule->eat = targetModule->edt->AddressOfFunctions + targetModule->moduleBase;
targetModule->eot = targetModule->edt->AddressOfNameOrdinals + targetModule->moduleBase;
targetModule->npt = targetModule->edt->AddressOfNames + targetModule->moduleBase;
return targetModule;
}
/*
Builds a hooked functions list using a pointer to a valid mineSweeperModuleInfo struct.
Returns the length of the list or 0 if no list was created.
*/
DWORD buildHookedFunctionsArray(mineSweeperModuleInfo* targetModule) {
DWORD uniqueFuncCounter = 0;
int prevEATOrdinal = -1;
// convenience variables
DWORD RVAsCount = targetModule->modifiedRVAsLength;
DWORD_PTR moduleBase = targetModule->moduleBase;
// if no modified RVAs are present there is nothing to work on
if (targetModule->modifiedRVAsLength < 1)
return uniqueFuncCounter;
// temp array to hold RVA to EAT mapping
PWORD tempRVAtoEatMapping = malloc(sizeof(WORD) * RVAsCount);
// map modified RVAs to respective EAT function ordinals
for (DWORD i = 0; i < RVAsCount; i++) {
tempRVAtoEatMapping[i] = findClosestEAT_RVA(moduleBase + targetModule->modifiedRVAs[i], moduleBase, targetModule->eat, targetModule->edt->NumberOfFunctions);
}
// calculate unique hooked functions
for (DWORD i = 0; i < RVAsCount; i++) {
if (tempRVAtoEatMapping[i] != prevEATOrdinal) {
uniqueFuncCounter++;
prevEATOrdinal = tempRVAtoEatMapping[i];
}
}
// if for some reason we didn't find any hooked functions - return
if (uniqueFuncCounter == 0) {
free(tempRVAtoEatMapping);
return uniqueFuncCounter;
}
// allocate memory for our hookedFunctions array
targetModule->hookedFunctions = malloc(sizeof(hookedFunction) * uniqueFuncCounter);
// now let's populate our hookedFunctions array
for (DWORD i = 0, currentRVAArrayIndex = 0; i < uniqueFuncCounter; i++) {
// assign eat ordinal value to our hooked function
targetModule->hookedFunctions[i].eatOrdinal = tempRVAtoEatMapping[currentRVAArrayIndex];
// increase tempCounter by one since we just assigned the current EAT value
currentRVAArrayIndex++;
// temporary variable to keep track of how many modified RVAs are there for each hookedFunctions memenber. We start with since there is at least 1
DWORD countRVAs = 1;
// let's calculate how many modified RVAs belong to our current hookedFunctions member
for (; currentRVAArrayIndex < RVAsCount; currentRVAArrayIndex++) {
//if our current hooked function EAT matches the tempRVAtoEatMapping[tempCounter] - that RVA belongs to the same function, so increase the RVAs counter, otherwise, we need to get out
if (targetModule->hookedFunctions[i].eatOrdinal == tempRVAtoEatMapping[currentRVAArrayIndex])
countRVAs++;
else
break;
}
// we now know the modifiedRVAsIndexesLength value
targetModule->hookedFunctions[i].modifiedRVAsIndexesCount = countRVAs;
// it's time to allocate memory for our modifiedRVAsIndexes array
targetModule->hookedFunctions[i].modifiedRVAsIndexes = malloc(sizeof(WORD) * countRVAs);
// let's populate modifiedRVAsIndexes values
for (DWORD j = 0, tempRVAIndex = currentRVAArrayIndex - countRVAs; tempRVAIndex < currentRVAArrayIndex; tempRVAIndex++, j++) {
targetModule->hookedFunctions[i].modifiedRVAsIndexes[j] = tempRVAIndex;
}
// let's translate our function EAT index into EOT / NPT index
targetModule->hookedFunctions[i].eotOrdinal = EATIndexToEOTIndex(targetModule->hookedFunctions[i].eatOrdinal, targetModule->eot, targetModule->edt->NumberOfNames);
// checking just in case EATIndexToEOTIndex didn't find appropriate EOT index (which shouldn't normally happen)
if (targetModule->hookedFunctions[i].eotOrdinal != -1)
// get the function name
targetModule->hookedFunctions[i].functionName = EOTIndexToFuncNameMineSweeper(targetModule, targetModule->hookedFunctions[i].eotOrdinal);
}
// now set the hookedFunctionsLength value
targetModule->hookedFunctionsLength = uniqueFuncCounter;
free(tempRVAtoEatMapping);
return uniqueFuncCounter;
}
void printHookedFunctions(mineSweeperModuleInfo* targetModule) {
DWORD ordinalBase;
// check if there are any modified RVAs in the module
if (targetModule->modifiedRVAsLength < 1) {
return;
}
// check if there are any hooked functions detected. If not, try build a new hookedFunctionsList
if (targetModule->hookedFunctionsLength < 1)
buildHookedFunctionsArray(targetModule);
// if still no hooked functions - return
if (targetModule->hookedFunctionsLength < 1)
return;
ordinalBase = targetModule->edt->Base;
printf("\tHooked functions detected: %d\n\n", targetModule->hookedFunctionsLength);
for (DWORD i = 0; i < targetModule->hookedFunctionsLength; i++) {
printf("\t%d) %d %s\n", i + 1, targetModule->hookedFunctions[i].eatOrdinal + ordinalBase, targetModule->hookedFunctions[i].functionName);
if (beVerbose) {
// if one function has over 30 modified RVA, let's skip it - some weird shit is happening (observed on some obscured .dll like windows.storage.dll)
if (targetModule->hookedFunctions[i].modifiedRVAsIndexesCount > 30) {
printf("\t\t%d modified RVAs (too many to print!)\n", targetModule->hookedFunctions[i].modifiedRVAsIndexesCount);
continue;
}
for (WORD j = 0; j < targetModule->hookedFunctions[i].modifiedRVAsIndexesCount; j++) {
WORD index = targetModule->hookedFunctions[i].modifiedRVAsIndexes[j];
// note 0x%2X to append "0x" to zero
printf("\t\tRVA: %#X - 0x%02X -> 0x%02X\n", targetModule->modifiedRVAs[index], targetModule->unhookedRVAValues[index], targetModule->hookedRVAValues[index]);
}
printf("\n");
}
}
}
// Check specified module for user-land hooks by comparing its in-memory copy with the one on disk
// Returns FALSE in case of any errors
BOOL sweepModule(mineSweeperModuleInfo* targetModule) {
PIMAGE_SECTION_HEADER inMemoryTextSectionHeader = NULL, onDiskTextSectionHeader = NULL; // section header variables
DWORD_PTR inMemoryTextSection, onDiskTextSection;
int memcmpResult = 0;
DWORD modifiedRVAsCount = 0;
if (targetModule == NULL)
return FALSE;
// linked list variables
modifiedRVAListNode* head = NULL;
modifiedRVAListNode* prev = NULL;
modifiedRVAListNode* current;
// map module from disk
if (mapFileFromDisk(targetModule) == FALSE) {
#if _DEBUG
printf("[!] Failed to map the file from disk: %s!\n", targetModule->filePath);
#endif
return FALSE;
}
inMemoryTextSectionHeader = getTextSection(targetModule->moduleBase);
onDiskTextSectionHeader = getTextSection(targetModule->hTargetDllOnDiskMappingAddress);
// if we couldn't find one of the text sections - error
if (inMemoryTextSectionHeader == NULL || onDiskTextSectionHeader == NULL) {
printf("[!] %#X (%ls): no text section found. Skipping the module.\n", targetModule->hModule, targetModule->moduleName);
return TRUE;
}
// if text section sizes don't match - error
if (inMemoryTextSectionHeader->Misc.VirtualSize != onDiskTextSectionHeader->Misc.VirtualSize)
return FALSE;
// calculate the actual section locations
onDiskTextSection = onDiskTextSectionHeader->VirtualAddress + (DWORD_PTR)targetModule->hTargetDllOnDiskMappingAddress;
inMemoryTextSection = inMemoryTextSectionHeader->VirtualAddress + targetModule->moduleBase;
while (TRUE) {
// compare on-disk .text section with the one in memory
memcmpResult = memcmpCustom(onDiskTextSection, inMemoryTextSection, inMemoryTextSectionHeader->Misc.VirtualSize, memcmpResult);
// if sections don't match - add the mismatch RVA to the changed list
if (memcmpResult != -1) {
current = (modifiedRVAListNode*)malloc(sizeof(modifiedRVAListNode));
// if head element of the list hasn't been initialized yet - let's make the current our head
if (head == NULL)
head = current;
// if the list has been initialized already - let's update the previous element's "next" pointer with our current element
else
prev->next = current;
// calculating modified byte as an RVA relative to the image base: text_section_start + memcmpResult - base address
current->rva = inMemoryTextSection + memcmpResult - targetModule->moduleBase;
current->next = NULL;
prev = current;
memcmpResult++;
}
else {
// if the rest is identical - break
break;
}
}
// update modifiedRVAsLength value for the target mineSweeperModuleInfo struct
targetModule->modifiedRVAsLength = getModifiedRVAListLength(head);
// if we have modified RVAs, let's initialize our modifiedRVAs array
if (targetModule->modifiedRVAsLength != 0) {
targetModule->modifiedRVAs = (PDWORD)malloc(sizeof(DWORD) * targetModule->modifiedRVAsLength);
//transfer the list elements to an array
// if moveModifiedRVAListToArray returns false - we hit an array overflow and something must be wrong - return false
if (!moveModifiedRVAListToArray(head, targetModule->modifiedRVAs, targetModule->modifiedRVAsLength)) {
cleanModifiedRVAList(head);
return FALSE;
}
// now, let's populate our unhooked and hooked RVA values
if (!populateHookedAndUnhookedRVAValues(targetModule)) {
cleanModifiedRVAList(head);
return FALSE;
}
// lastly, let's build our hooked functions list
// if we get 0 functions at this stage - something went wrong so pull back
if (0 == buildHookedFunctionsArray(targetModule)) {
cleanModifiedRVAList(head);
return FALSE;
}
}
// now, we don't need our linked list anymore, let's clean it up
cleanModifiedRVAList(head);
return TRUE;
}
// populates hookedRVAValues and unhookedRVAValues arrays
// we store hooked RVA values just in case we want to re-hook the module later on
// returns FALSE in case prerequisites are not available
BOOL populateHookedAndUnhookedRVAValues(mineSweeperModuleInfo* targetModule) {
if (targetModule->modifiedRVAsLength < 1 || targetModule->moduleBase == NULL || targetModule->hTargetDllOnDiskMappingAddress == NULL)
return FALSE;
DWORD length = targetModule->modifiedRVAsLength;
DWORD_PTR memoryBase = targetModule->moduleBase;
DWORD_PTR onDiskBase = (DWORD_PTR)targetModule->hTargetDllOnDiskMappingAddress;
DWORD tempRVA;
BYTE* hookedRVATempValue;
BYTE* unhookedRVATempValue;
// allocate memory for both arrays
targetModule->hookedRVAValues = malloc(length);
targetModule->unhookedRVAValues = malloc(length);
// now go through each RVA and populate both hooked and unhooked values
for (DWORD i = 0; i < length; i++) {
tempRVA = targetModule->modifiedRVAs[i];
hookedRVATempValue = memoryBase + tempRVA;
unhookedRVATempValue = onDiskBase + tempRVA;
targetModule->hookedRVAValues[i] = *hookedRVATempValue;
targetModule->unhookedRVAValues[i] = *unhookedRVATempValue;
}
return TRUE;
}
// Empties ModifiedRVAList by freeing each member
void cleanModifiedRVAList(modifiedRVAListNode* head) {
modifiedRVAListNode* current = head, * next = current;
while (next != NULL) {
current = next;
next = next->next;
free(current);
}
}
// Move List members to an array
// Returns false in case of array overflow
BOOL moveModifiedRVAListToArray(modifiedRVAListNode* head, PDWORD array, DWORD arrayLength) {
DWORD counter = 0;
modifiedRVAListNode* next = head;
while (next != NULL) {
// if we are going over the array length - stop and return false
if (counter >= arrayLength)
return FALSE;
array[counter] = next->rva;
counter++;
next = next->next;
}
return TRUE;
}
// Locates a module's Export Directory Table - takes module handle (module base address) as the only parameter.
// Returns NULL in case of an error
// code inspired by https://stackoverflow.com/questions/2273603/getting-ordinal-from-function-name-programmatically
PIMAGE_EXPORT_DIRECTORY getExportDirectoryTable(HMODULE module) {
DWORD_PTR base; // base address of module
PIMAGE_FILE_HEADER cfh; // COFF file header
PIMAGE_EXPORT_DIRECTORY edt; // export directory table (EDT)
DWORD rva; // relative virtual address of EDT
PIMAGE_DOS_HEADER mds; // MS-DOS stub
PIMAGE_OPTIONAL_HEADER64 oh64; // so-called "optional" header
PIMAGE_OPTIONAL_HEADER32 oh32; // 32-bit version of the oh
PDWORD sig; // PE signature
// Start at the base of the module. The MS-DOS stub begins there.
base = (DWORD_PTR)module;
mds = (PIMAGE_DOS_HEADER)module;
// Get the PE signature and verify it.
sig = (DWORD*)(base + mds->e_lfanew);
if (IMAGE_NT_SIGNATURE != *sig) {
// Bad signature -- invalid image or module handle
return NULL;
}
// Get the COFF file header.
cfh = (PIMAGE_FILE_HEADER)(sig + 1);
// Check the architecture of the binary and cast to an appropriate optional header
// if it's a 64-bit binary - use the 64-bit optional header struct, if 32-bit - use 32 one.
if (cfh->Machine == IMAGE_FILE_MACHINE_AMD64) {
oh64 = (PIMAGE_OPTIONAL_HEADER64)(cfh + 1);
if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh64->NumberOfRvaAndSizes) {
// This image doesn't have an export directory table.
return NULL;
}
rva = oh64->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
edt = (PIMAGE_EXPORT_DIRECTORY)(base + rva);
return edt;
}
else if (cfh->Machine == IMAGE_FILE_MACHINE_I386) {
oh32 = (PIMAGE_OPTIONAL_HEADER32)(cfh + 1);
if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh32->NumberOfRvaAndSizes) {
// This image doesn't have an export directory table.
return NULL;
}
rva = oh32->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
edt = (PIMAGE_EXPORT_DIRECTORY)(base + rva);
return edt;
}
//if it's neither x64 or x32, then we are not ready to deal with it :(
return NULL;
}
// Count the number of elements in the modifiedRVAListNode list
DWORD getModifiedRVAListLength(modifiedRVAListNode* head) {
DWORD counter = 0;
modifiedRVAListNode* next = head;
while (next != NULL) {
counter++;
next = next->next;
}
return counter;
}
// Takes a module handle (module base address) and returns a pointer to it's .text section
PIMAGE_SECTION_HEADER getTextSection(HMODULE module) {
//DOS header = module base
PIMAGE_DOS_HEADER pDOSHeader = module;
// get the NT header - i took PBYTE cast inspiration from here https://stackoverflow.com/questions/2273603/getting-ordinal-from-function-name-programmatically
PIMAGE_NT_HEADERS ntHeader = (PBYTE)module + pDOSHeader->e_lfanew;
// check if we get a valid PE signature (PE\0\0)
if (ntHeader->Signature != IMAGE_NT_SIGNATURE)
return NULL;
//coff file header to get our size of optional header value
PIMAGE_FILE_HEADER coffFileHeader = &ntHeader->FileHeader;
WORD sizeOfOptionalheader = coffFileHeader->SizeOfOptionalHeader;
//optional header is located 0x18 bytes after the start of the NT header
PIMAGE_OPTIONAL_HEADER optionalHeader = (PBYTE)ntHeader + 0x18;
PIMAGE_SECTION_HEADER sectionHeaders = (PBYTE)optionalHeader + sizeOfOptionalheader;
// check if the target image has any sections. if there are 0 sections - return NULL
if (coffFileHeader->NumberOfSections < 1)
return NULL;
// if there are some sections, let's enum them
for (int i = 0; i < coffFileHeader->NumberOfSections; i++) {
// enumerate available sections until we find our .text section
if (strcmp(sectionHeaders[i].Name, ".text") == 0)
return §ionHeaders[i];
}
// if we didn't find the .text section - return NULL
return NULL;
}
/*
CUstom memcmp function that will compare two buffers and return an index value of the first mismatch identified.
Returns -1 if the buffers are identical
size_t start value can specify the comparison start offset (used by the sweepModule function)
*/
int memcmpCustom(const void* s1, const void* s2, size_t n, size_t start) {
BYTE* array1 = s1;
BYTE* array2 = s2;
if (n < 1)
{
return -1;
}
for (size_t i = start; i < n; i++) {
if (array1[i] != array2[i])
return i;
}
return -1;
}
/*
Take a memory address (provided by the memcmpCustom function) and find a closest ordinal in the provided EAT. If used properly, the function will allow to find the hooked EAT ordinal.
Returns -1 in a case all RVAs in the EAT are past the target byte memory address.
*/
int findClosestEAT_RVA(DWORD_PTR targetByte, DWORD_PTR moduleBase, PDWORD eat, size_t eat_length) {
int ordinal = -1;
// a variable to hold current difference between the closest EAT function and our target byte. This will be considered the smallest difference currently found
// using long long to avoid variable overflow since DWORD_PTR is unsigned long
long long currentDifference = NULL;
long long tempDifference = NULL;
for (int i = 0; i < eat_length; i++) {
// find the difference between current eat function memory address and our target byte in the .text section
tempDifference = targetByte - (moduleBase + eat[i]);
// if function RVA + module base are greater than our target byte - skip since the function appears in the .text section after our target byte
if (tempDifference < 0)
continue;
// if currentDifference is NULL then take this function as our best match, otherwise take it if the difference is smaller than the current best match
if (currentDifference == NULL || tempDifference < currentDifference) {
currentDifference = tempDifference;
ordinal = i;
// if tempDifference is zero, it means this is the best match possible at this point (i.e: the hook is at the start of the function) and we can stop here
if (tempDifference == 0)
break;
}
}
return ordinal;
}
PDWORD getExportAddressTable(HMODULE module) {
PDWORD eat; // export address table
PIMAGE_EXPORT_DIRECTORY edt; // export directory table
PBYTE moduleBase; // module base address - convenience variable
moduleBase = (PBYTE)module;
edt = getExportDirectoryTable(module);
eat = edt->AddressOfFunctions + moduleBase;
return eat;
}
PWORD getExportOrdinalTable(HMODULE module) {
PWORD eot; // export ordinal table
PIMAGE_EXPORT_DIRECTORY edt; // export directory table
PBYTE moduleBase; // module base address - convenience variable
moduleBase = (PBYTE)module;
edt = getExportDirectoryTable(module);
eot = edt->AddressOfNameOrdinals + moduleBase;
return eot;
}
PDWORD getNamePointerTable(HMODULE module) {
PDWORD npt; // name pointer table
PIMAGE_EXPORT_DIRECTORY edt; // export directory table
DWORD_PTR moduleBase; // module base address - convenience variable
moduleBase = (DWORD_PTR)module;
edt = getExportDirectoryTable(module);
npt = moduleBase + edt->AddressOfNames;
return npt;
}
// Takes a module handle (module base address) and an EOT ordinal to converse that to a function name
// Returns NULL in case of an error
char* EOTIndexToFuncNameMineSweeper(mineSweeperModuleInfo* targetModule, DWORD ordinal) {
char* functionName; // variable to hold our function name pointer
PDWORD npt; // name pointer table
PIMAGE_EXPORT_DIRECTORY edt; // export directory table
DWORD_PTR moduleBase; // module base address - convenience variable
moduleBase = targetModule->moduleBase;
edt = targetModule->edt;
// check for ordinal out of bounds
if (edt->NumberOfNames < ordinal || ordinal < 0) {
return NULL;
}
npt = targetModule->npt;
functionName = moduleBase + npt[ordinal];
return functionName;
}
// Takes a module handle (module base address) and an EOT ordinal to converse that to a function name
// Returns NULL in case of an error
char* EOTIndexToFuncName(HMODULE module, DWORD ordinal) {
char* functionName; // variable to hold our function name pointer
PDWORD npt; // name pointer table
PIMAGE_EXPORT_DIRECTORY edt; // export directory table
DWORD_PTR moduleBase; // module base address - convenience variable
moduleBase = (DWORD_PTR)module;
edt = getExportDirectoryTable(module);
// check for ordinal out of bounds
if (edt->NumberOfNames < ordinal || ordinal < 0) {
return NULL;
}
npt = moduleBase + edt->AddressOfNames;
functionName = moduleBase + npt[ordinal];
return functionName;
}
// Take an EAT index and try to find an element in the provided EOT array that matches the EAT index value
// Returns -1 if no match was found
int EATIndexToEOTIndex(WORD eatIndex, PWORD eot, DWORD eotLength) {
int index = -1;
for (DWORD i = 0; i < eotLength; i++) {
if (eot[i] == eatIndex) {
index = i;
break;
}
}
return index;
}
VOID cleanUpModule(mineSweeperModuleInfo* targetModule) {
if (targetModule->filePath != NULL)
free(targetModule->filePath);
if (targetModule->hTargetDllOnDiskMappingAddress != NULL)
UnmapViewOfFile(targetModule->hTargetDllOnDiskMappingAddress);
if (targetModule->hTargetDllOnDiskFileMapping != NULL)
CloseHandle(targetModule->hTargetDllOnDiskFileMapping);
if (targetModule->hTargetDllOnDisk != NULL)
CloseHandle(targetModule->hTargetDllOnDisk);
if (targetModule->modifiedRVAsLength > 0)
free(targetModule->modifiedRVAs);
if (targetModule->hookedFunctionsLength > 0) {
// first release modifiedRVAsIndexes array for each hooked function
for (short i = 0; i < targetModule->hookedFunctionsLength; i++) {
free(targetModule->hookedFunctions[i].modifiedRVAsIndexes);
}
// now free the entire hooked functions array
free(targetModule->hookedFunctions);
}
// if remote process
// note: hModule and moduleBase should be the same if it's a local process, so that's what we are checking here
if ((DWORD_PTR)targetModule->hModule != targetModule->moduleBase) {
free(targetModule->moduleBase);
}
free(targetModule);
}
BOOL mapFileFromDisk(mineSweeperModuleInfo* targetModule) {
// append "\\?\globalroot" since CreateFileW doesn't accept a canonical path returned by GetMappedFileNameW winapi function. The idea was taken from https://stackoverflow.com/questions/48178586/how-to-disable-wow64-file-system-redirection-for-getmodulefilenameex
wchar_t tempString[filePathLength] = L"\\\\?\\globalroot";
if (0 != wcscat_s(tempString, filePathLength, targetModule->filePath))
return FALSE;
targetModule->hTargetDllOnDisk = CreateFileW(tempString, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (targetModule->hTargetDllOnDisk == INVALID_HANDLE_VALUE)
return FALSE;
// thanks to @slaeryan for SEC_IMAGE_NO_EXECUTE tip B-) https://twitter.com/slaeryan/status/1336959057232449536
targetModule->hTargetDllOnDiskFileMapping = CreateFileMapping(targetModule->hTargetDllOnDisk, NULL, PAGE_READONLY | SEC_IMAGE_NO_EXECUTE, 0, 0, NULL);
if (targetModule->hTargetDllOnDiskFileMapping == NULL)
return FALSE;
targetModule->hTargetDllOnDiskMappingAddress = MapViewOfFile(targetModule->hTargetDllOnDiskFileMapping, FILE_MAP_READ, 0, 0, 0);
if (targetModule->hTargetDllOnDiskMappingAddress == NULL)
return FALSE;
return TRUE;
}
/*
Wrapper for EnumProcessModulesEx. Obtains a process' modules list. Works with both local and remote processes.
Takes a target module handle, a pointer to modules array and a pointer to a DWORD for the array's length
Returns TRUE if successful.
Warning: Don't forget to free the modules array once you are done with it!
*/
BOOL getProcessModules(HANDLE hProcess, HMODULE** modules, DWORD* modulesLength) {
DWORD tempModulesLength;
// setting modules length to 0 just in case it's uninitialized yet
*modulesLength = 0;
// Let's find out how many modules are there
if (!EnumProcessModulesEx(hProcess, NULL, NULL, &tempModulesLength, LIST_MODULES_ALL)) {
#if _DEBUG
printf("[!] Failed to EnumProcessModulesEx!\n");
#endif
return FALSE;
}
// allocate modules array space
*modules = malloc(sizeof(HMODULE) * tempModulesLength);
// set modulesLength
*modulesLength = tempModulesLength;
// Now, let's actually get our target modules
// Notice second condition in the if statement below - we want to make sure that tempModulesLength > *modulesLength is FALSE so we don't miss any modules
if (!EnumProcessModulesEx(hProcess, *modules, *modulesLength, &tempModulesLength, LIST_MODULES_ALL) || tempModulesLength > *modulesLength) {
#if _DEBUG
printf("[!] Failed to EnumProcessModulesEx for the second time - module count must have changed just now!\n");
#endif
return FALSE;
}
// update module length with the actual module length as per https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocessmodulesex
// "To determine how many modules were enumerated by the call to EnumProcessModulesEx, divide the resulting value in the lpcbNeeded parameter by sizeof(HMODULE)."
*modulesLength = *modulesLength / sizeof(HMODULE);
return TRUE;
}
/*
Prints each module handle and it's canonical path for the target process.
*/
void printProcessModules(HANDLE hProcess, HMODULE* modules, DWORD modulesLength) {
if (modulesLength < 1) {
printf("[!] No modules to print. \n");
return;
}
for (DWORD i = 0; i < modulesLength; i++) {
PWSTR tempFileName[filePathLength] = { 0 }; // create a temporary PWSTR to be used with file name retrieval
GetMappedFileNameW(hProcess, modules[i], tempFileName, filePathLength);
printf("\t%d) %#X - %ls\n", i+1, modules[i], tempFileName);
}
}
/*
Searches for modules that contain a specified string in their path.
Returns FALSE in case of an error.
Warning: Don't forget to free the matchedModules array once you are done with it!
*/
BOOL findModuleHandleByFilePath(HANDLE hProcess, HMODULE* modules, DWORD modulesLength, HMODULE ** matchedModules, DWORD * matchedModulesLength, wchar_t * searchString) {
// declaring a quick linked list structure since we don't know how many matches we are going to get
typedef struct matchedModuleStruct {
struct matchedModuleStruct* next;
HMODULE hModule;
} matchedModulesNode;
// initialize our list head
matchedModulesNode head = { 0 };
// initialize our list pointers
matchedModulesNode* prev = NULL, * current = NULL;
// create a temporary PWSTR to be used with file name retrieval
PWSTR tempFileName[filePathLength] = { 0 };
DWORD fileNameLength;
wchar_t* tempSearchPointer = NULL;
// set this to zero just in case
*matchedModulesLength = 0;
// if searchString is empty - return FALSE
if (wcslen(searchString) < 1)
return FALSE;
for (DWORD i = 0; i < modulesLength; i++) {
fileNameLength = GetMappedFileNameW(hProcess, modules[i], tempFileName, filePathLength);
// if we get a filename back, let's search our string within it
if (fileNameLength > 0) {
tempSearchPointer = wcsstr(tempFileName, searchString);
//if we found a match
if (tempSearchPointer != NULL) {
// increase our matched modules counter
(*matchedModulesLength)++;
// add an item to our linked list
// if it's our first match, updated the head, otherwise create a new list element
if (prev == NULL) {
head.hModule = modules[i];
prev = &head;
}
else {
current = malloc(sizeof(matchedModulesNode));
prev->next = current;
current->hModule = modules[i];
current->next = NULL;
prev = current;
}
}
}
}