-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathkernel32.cpp
More file actions
875 lines (766 loc) · 28.4 KB
/
kernel32.cpp
File metadata and controls
875 lines (766 loc) · 28.4 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
#include <Windows.h>
#include <winnt.h>
#include "kernel32.hpp"
#include "common.h"
/*
* LoadLibrary migration PHASE:
* 1 - this implementation is used to import all the DLLs on which the library depend
* 2 - the import table of the DLLs is modified to use my version of LoadLibrary, FreeLibrary, ecc ...
*/
#define PHASE 2
kernel32* kernel32::instance_ptr = NULL;
/**
* _LoadLibraryExA
* replacement function used when the module is trying to import LoadLibraryExA
*/
HMODULE WINAPI _LoadLibraryExA(LPCSTR lpFileName, HANDLE hFile, DWORD dwFlags)
{
wchar_t *wstring = new wchar_t[2 * lstrlenA(lpFileName) + 1];
MultiByteToWideChar(CP_ACP, 0, lpFileName, lstrlenA(lpFileName) + 1, wstring, lstrlenA(lpFileName) + 1);
HMODULE hMod = kernel32::get_instance()->LoadLibraryExW(wstring, hFile, dwFlags);
delete [] wstring;
return hMod;
}
/**
* _LoadLibraryA
* replacement function used when the module is trying to import LoadLibraryA
*/
HMODULE WINAPI _LoadLibraryA(LPCSTR lpFileName)
{
return _LoadLibraryExA(lpFileName, 0, 0);
}
/**
* _LoadLibraryExW
* replacement function used when the module is trying to import LoadLibraryExW
* Just a simple wrapper for LoadLibraryExA
*/
HMODULE WINAPI _LoadLibraryExW(LPCTSTR lpFileName, HANDLE hFile, DWORD dwFlags)
{
if(!(dwFlags & LOAD_WITH_ALTERED_SEARCH_PATH))
return kernel32::get_instance()->LoadLibraryExW(lpFileName, hFile, dwFlags);
else
return NULL;
}
/**
* _LoadLibraryW
* replacement function used when the module is trying to import LoadLibraryW
*/
HMODULE WINAPI _LoadLibraryW(LPCTSTR lpFileName)
{
return _LoadLibraryExW(lpFileName, 0, 0);
}
/**
* _GetModuleHandleW
* replacement function used when the module is trying to import GetModuleHandleW
*/
HMODULE WINAPI _GetModuleHandleW(LPCTSTR lpModuleName)
{
return kernel32::get_instance()->GetModuleHandle(hash_uppercaseW(lpModuleName));
}
/**
* _GetModuleHandleA
* replacement function used when the module is trying to import GetModuleHandleA
*/
HMODULE WINAPI _GetModuleHandleA(LPCSTR lpModuleName)
{
return kernel32::get_instance()->GetModuleHandle(hash_uppercase(lpModuleName));
}
/**
* _FreeLibrary
* replacement function used when the module is trying to import FreeLibrary
*/
BOOL WINAPI _FreeLibrary(HMODULE hModule)
{
if(!kernel32::get_instance()->FreeLibrary(hModule))
return kernel32::get_instance()->OrigFreeLibrary(hModule);
return TRUE;
}
/**
* Constructor
* it just loads the needed functions dinamically and initializes the critical sections
*/
kernel32::kernel32()
{
// Our private loader, huhuhu
HMODULE hKernel32 = GetModuleHandle(KERNEL32);
MultiByteToWideChar = (_MULTIBYTETOWIDECHAR)GetProcAddress(hKernel32, MULTIBYTETOWIDECHAR, 0);
WideCharToMultiByte = (_WIDECHARTOMULTIBYTE)GetProcAddress(hKernel32, WIDECHARTOMULTIBYTE, 0);
CloseHandle = (_CLOSEHANDLE)GetProcAddress(hKernel32, CLOSEHANDLE, 0);
CreateFile = (_CREATEFILEW)GetProcAddress(hKernel32, CREATEFILEW, 0);
CreateFileMapping = (_CREATEFILEMAPPINGA)GetProcAddress(hKernel32, CREATEFILEMAPPINGA, 0);
DeleteCriticalSection = (_DELETECRITICALSECTION)GetProcAddress(hKernel32, DELETECRITICALSECTION, 0);
EnterCriticalSection = (_ENTERCRITICALSECTION)GetProcAddress(hKernel32, ENTERCRITICALSECTION, 0);
GetCurrentDirectory = (_GETCURRENTDIRECTORYW)GetProcAddress(hKernel32, GETCURRENTDIRECTORYW, 0);
GetFullPathName = (_GETFULLPATHNAMEW)GetProcAddress(hKernel32, GETFULLPATHNAMEA, 0);
GetSystemDirectory = (_GETSYSTEMDIRECTORYW)GetProcAddress(hKernel32, GETSYSTEMDIRECTORYW, 0);
InitializeCriticalSection = (_INITIALIZECRITICALSECTION)GetProcAddress(hKernel32, INITIALIZECRITICALSECTION, 0);
LeaveCriticalSection = (_LEAVECRITICALSECTION)GetProcAddress(hKernel32, LEAVECRITICALSECTION, 0);
MapViewOfFile = (_MAPVIEWOFFILE)GetProcAddress(hKernel32, MAPVIEWOFFILE, 0);
MapViewOfFileEx = (_MAPVIEWOFFILEEX)GetProcAddress(hKernel32, MAPVIEWOFFILEEX, 0);
UnmapViewOfFile = (_UNMAPVIEWOFFILE)GetProcAddress(hKernel32, UNMAPVIEWOFFILE, 0);
VirtualAlloc = (_VIRTUALALLOC)GetProcAddress(hKernel32, VIRTUALALLOC, 0);
VirtualFree = (_VIRTUALFREE)GetProcAddress(hKernel32, VIRTUALFREE, 0);
VirtualProtect = (_VIRTUALPROTECT)GetProcAddress(hKernel32, VIRTUALPROTECT, 0);
OrigFreeLibrary = (_FREELIBRARY)GetProcAddress(hKernel32, FREELIBRARY, 0);
OrigLoadLibraryEx = (_LOADLIBRARYEXW)GetProcAddress(hKernel32, LOADLIBRARYEXW, 0);
InitializeCriticalSection(&libCritical);
}
/**
* Destructor
*/
kernel32::~kernel32()
{
DeleteCriticalSection(&libCritical);
}
/**
* FreeLibraryWrapped
* frees the selected library, decreases the dependency counter and, if
* necessary, frees the not-needed-anymore libraries
*/
BOOL kernel32::FreeLibraryWrapped(HMODULE hModule)
{
std::map<HMODULE, MODULES_LIST *>::iterator& module_entryit = libInstancesMap.find(hModule);
MODULES_LIST *module_entry, *entry, *tmp;
if(module_entryit != libInstancesMap.end())
{
BOOL bRet = TRUE;
module_entry = module_entryit->second;
// already marked for deletion
if(module_entry->markedForDeletion)
return TRUE;
if(module_entry->instances > 0 && module_entry->instances != 0xFFFF)
{
module_entry->instances--;
if(module_entry->instances == 0)
{
// we are deleting it
module_entry->markedForDeletion = TRUE;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)hModule;
if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
PIMAGE_NT_HEADERS pNTHeader = (PIMAGE_NT_HEADERS)((LONG)dosHeader + dosHeader->e_lfanew);
// call the DLL_PROCESS_DETACH routine
if(!(module_entry->flags & (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES)))
{
DllEntryProc entryPoint = (DllEntryProc)((PBYTE)hModule + pNTHeader->OptionalHeader.AddressOfEntryPoint);
(*entryPoint)((HINSTANCE)hModule, DLL_PROCESS_DETACH, 0);
}
if(!(module_entry->flags & DONT_RESOLVE_DLL_REFERENCES))
{
// lemme analyze the modules loaded by this one
entry = module_entry->next;
for(EVER)
{
if(entry == NULL) break;
FreeLibrary(entry->hModule);
tmp = entry->next;
delete entry;
entry = tmp;
}
}
bRet = UnmapViewOfFile(hModule);
libInstancesMap.erase(module_entryit);
delete module_entry;
}
}
return bRet;
}
else
return kernel32::get_instance()->OrigFreeLibrary(hModule);
}
/**
* GetModuleHandle
* Scans the whole PEB, looking for the selected module.
* If not found, it scans the internal list for it.
* byWindows says if the module was loaded by Windows or by this library.
*/
HMODULE kernel32::GetModuleHandle(unsigned int hash, BOOL& byWindows)
{
PPEB peb;
PLIST_ENTRY listEntry, headEntry;
byWindows = TRUE;
typedef struct _LDR_DATA_TABLE_ENTRY {
LIST_ENTRY LoadOrder;
LIST_ENTRY MemoryOrder;
LIST_ENTRY InitializationOrder;
PVOID ModuleBaseAddress;
PVOID EntryPoint;
ULONG ModuleSize;
UNICODE_STRING FullModuleName;
UNICODE_STRING ModuleName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union {
LIST_ENTRY Hash;
struct {
PVOID SectionPointer;
ULONG CheckSum;
};
};
ULONG TimeStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
PLDR_DATA_TABLE_ENTRY dataTableEntry;
__asm
{
mov edx, fs:[0x30] // PEB
mov peb, edx
}
headEntry = peb->Ldr->InMemoryOrderModuleList.Flink;
for(listEntry = headEntry; listEntry != headEntry->Blink; listEntry = listEntry->Flink)
{
dataTableEntry = (PLDR_DATA_TABLE_ENTRY)((PBYTE)listEntry - 8 * sizeof(BYTE));
if(hash_uppercaseW(dataTableEntry->ModuleName.Buffer) == hash)
return (HMODULE)dataTableEntry->ModuleBaseAddress;
if((DWORD)(dataTableEntry->ModuleBaseAddress) == 0)
break;
}
// Let's try to check if we loaded the module with our tricky functions
std::map<HMODULE, MODULES_LIST *>::const_iterator& theEnd = libInstancesMap.end();
for(std::map<HMODULE, MODULES_LIST *>::const_iterator& module_entryit = libInstancesMap.begin();
module_entryit != theEnd;
module_entryit++)
{
if(module_entryit->second->hashName == hash)
{
byWindows = FALSE;
return module_entryit->second->hModule;
}
}
return NULL;
}
/**
* GetModuleHandle
* Public function that hides the byWindows parameter.
* hash HAS to be the hash of the absolute path.
*/
HMODULE kernel32::GetModuleHandle(unsigned int hash)
{
BOOL byWindows;
return GetModuleHandle(hash, byWindows);
}
/**
* GetModuleHandleByString
* Internal function: like GetModuleHandle, but it uses a string instead of a hash
*/
HMODULE kernel32::GetModuleHandleByString(LPCTSTR lpModuleName, BOOL& byWindows)
{
HMODULE handle;
if((handle = GetModuleHandle(hash_uppercaseW(lpModuleName), byWindows)) == NULL)
{
wchar_t curDir[MAX_PATH];
GetCurrentDirectory(MAX_PATH - 1, curDir);
lstrcat(curDir, L"\\");
lstrcpyn(curDir + lstrlen(curDir), lpModuleName, MAX_PATH - lstrlen(lpModuleName));
if((handle = GetModuleHandle(hash_uppercaseW(curDir), byWindows)) == NULL)
{
wchar_t sysDir[MAX_PATH];
GetSystemDirectory(sysDir, MAX_PATH - 1);
lstrcat(sysDir, L"\\");
lstrcpyn(sysDir + lstrlen(sysDir), lpModuleName, MAX_PATH - lstrlen(lpModuleName));
handle = GetModuleHandle(hash_uppercaseW(sysDir), byWindows);
}
}
return handle;
}
/**
* GetModuleHandleByString
* Public function that hides the byWindows parameter.
*/
HMODULE kernel32::GetModuleHandleByString(LPCTSTR lpModuleName)
{
BOOL byWindows;
return GetModuleHandleByString(lpModuleName, byWindows);
}
/**
* GetModuleHandleByString
* Internal function: like GetModuleHandle, but it uses a string instead of a hash
*/
HMODULE kernel32::GetModuleHandleByString(LPCSTR lpModuleName, BOOL& byWindows)
{
wchar_t *wstring = new wchar_t[2 * lstrlenA(lpModuleName) + 1];
MultiByteToWideChar(CP_ACP, 0, lpModuleName, lstrlenA(lpModuleName) + 1, wstring, lstrlenA(lpModuleName) + 1);
HMODULE hModule = GetModuleHandleByString(wstring);
delete [] wstring;
return hModule;
}
/**
* GetModuleHandleByString
* Public function that hides the byWindows parameter.
*/
HMODULE kernel32::GetModuleHandleByString(LPCSTR lpModuleName)
{
BOOL byWindows;
wchar_t *wstring = new wchar_t[2 * lstrlenA(lpModuleName) + 1];
MultiByteToWideChar(CP_ACP, 0, lpModuleName, lstrlenA(lpModuleName) + 1, wstring, lstrlenA(lpModuleName) + 1);
HMODULE hModule = GetModuleHandleByString(wstring, byWindows);
delete [] wstring;
return hModule;
}
/**
* GetProcAddress
* Seeks for a function (given the hash of the name) in the hModule module.
* If the hash is 0, it uses the ordinal number.
*/
FARPROC kernel32::GetProcAddress(HMODULE hModule, unsigned int hash, unsigned int ordinal)
{
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS pNTHeader;
PBYTE baseImage = (PBYTE)hModule;
dosHeader = (PIMAGE_DOS_HEADER)hModule;
// Really an MZ file ?
if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
// Get the NT header
pNTHeader = (PIMAGE_NT_HEADERS)((LONG)dosHeader + dosHeader->e_lfanew);
// This value is always set to 16 by the current tools
if(pNTHeader->OptionalHeader.NumberOfRvaAndSizes != 16)
return NULL;
// The first entry of the export DataDirectory
if(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size == 0)
return NULL;
PIMAGE_EXPORT_DIRECTORY exportTable = (PIMAGE_EXPORT_DIRECTORY)(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress + baseImage);
DWORD numberOfFunctions = exportTable->NumberOfFunctions;
DWORD *addressOfNames = (DWORD *)(baseImage + exportTable->AddressOfNames);
WORD *addressOfNameOrdinals = (WORD *)(baseImage + exportTable->AddressOfNameOrdinals);
PDWORD *addressOfFunctions = (PDWORD *)(baseImage + exportTable->AddressOfFunctions);
FARPROC funcAddress = NULL;
if(hash)
{
// by hash
unsigned int function_hash;
for(DWORD i = 0; i < numberOfFunctions; i++)
{
function_hash = hash_uppercase((char *)(addressOfNames[i] + baseImage));
if(function_hash == hash)
{
funcAddress = (FARPROC)(baseImage + (DWORD)addressOfFunctions[addressOfNameOrdinals[i]]);
break;
}
}
}
else
{
// by ordinal
ordinal -= exportTable->Base;
if(ordinal >= numberOfFunctions)
return NULL;
funcAddress = (FARPROC)(baseImage + (DWORD)addressOfFunctions[ordinal]);
}
if(funcAddress > (FARPROC)exportTable &&
funcAddress < (FARPROC)((PBYTE)exportTable + pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size))
{
// forwarded functions cause problems
char *dllName = new char[MAX_PATH];
char *funcName = new char[256];
char *thedot = strchr((char *)funcAddress, '.');
lstrcpynA(funcName, ++thedot, 256);
lstrcpynA(dllName, (char *)funcAddress, (thedot - (char *)funcAddress));
lstrcatA(dllName, ".dll");
HMODULE hFwdModule = GetModuleHandleByString(dllName);
if(hFwdModule == NULL)
{
#if PHASE > 0
hFwdModule = LoadLibraryA(dllName);
#else
hFwdModule = ::LoadLibraryA(dllName);
#endif
if(hFwdModule == NULL)
return NULL;
}
if((lstrlenA(funcName) > 1) && (funcName[0] == '#'))
funcAddress = GetProcAddress(hFwdModule, 0, funcName[1]);
else
funcAddress = GetProcAddress(hFwdModule, hash_uppercase(funcName), 0);
delete funcName;
delete dllName;
}
return funcAddress;
}
/**
* LoadLibraryExWrapped
* The core of the library. It loads the specified library.
* Just some of the flags are implemented, i.e. LOAD_LIBRARY_AS_DATAFILE and DONT_RESOLVE_DLL_REFERENCES.
*/
HMODULE kernel32::LoadLibraryExWrapped(LPCTSTR lpFileName, HANDLE hFile, DWORD dwFlags)
{
wchar_t lpFilePath[MAX_PATH], sysDir[MAX_PATH], curDir[MAX_PATH];
GetSystemDirectory(sysDir, MAX_PATH - 1);
GetCurrentDirectory(MAX_PATH - 1, curDir);
lstrcat(curDir, L"\\");
lstrcpyn(curDir + lstrlen(curDir), lpFileName, MAX_PATH - lstrlen(lpFileName));
lstrcat(sysDir, L"\\");
lstrcpyn(sysDir + lstrlen(sysDir), lpFileName, MAX_PATH - lstrlen(lpFileName));
// Already loaded ?
BOOL byWindows;
HMODULE hModule = GetModuleHandleByString(lpFileName, byWindows);
if(hModule != NULL)
{
if(!byWindows)
{
// If we loaded it, add 1 to the number of instances
std::map<HMODULE, MODULES_LIST *>::iterator& module_entryit = libInstancesMap.find(hModule);
if(module_entryit != libInstancesMap.end() && module_entryit->second->instances != 0xFFFF)
module_entryit->second->instances++;
}
else
{
// This call is needed to increment by 1 the Windows reference counter
OrigLoadLibraryEx(lpFileName, hFile, dwFlags);
}
return hModule;
}
// Open the library, please
// Maybe an absolute path?
HANDLE handle = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(handle == INVALID_HANDLE_VALUE)
{
// No luck with absolute path, let's try to search it locally
handle = CreateFile(curDir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if(handle == INVALID_HANDLE_VALUE)
{
// No luck with local path, let's try to search in system32
handle = CreateFile(sysDir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if(handle == INVALID_HANDLE_VALUE)
{
// No luck at all
return NULL;
}
else
lstrcpy(lpFilePath, sysDir);
}
else
lstrcpy(lpFilePath, curDir);
}
else
lstrcpy(lpFilePath, lpFileName);
// Map the file in memory
HANDLE hMapping = CreateFileMapping(handle, NULL, PAGE_READONLY, 0, 0, NULL);
if(hMapping == INVALID_HANDLE_VALUE)
{
CloseHandle(handle);
return NULL;
}
LPVOID baseAddress = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
// Not needed anymore, we have the mapping now
CloseHandle(hMapping);
CloseHandle(handle);
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)baseAddress;
PIMAGE_NT_HEADERS pNTHeader;
// Really an MZ file ?
if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
UnmapViewOfFile(baseAddress);
return NULL;
}
// Get the NT header
pNTHeader = (PIMAGE_NT_HEADERS)((LONG)dosHeader + dosHeader->e_lfanew);
// Reserve memory please at the ImageBase
// If this is not possible, base relocation is required
hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, pNTHeader->OptionalHeader.SizeOfImage, NULL);
if(hMapping == NULL)
{
UnmapViewOfFile(baseAddress);
return NULL;
}
LPVOID baseDll = MapViewOfFileEx(hMapping, FILE_EXECUTE | FILE_MAP_WRITE, 0, 0, 0, (LPVOID)(pNTHeader->OptionalHeader.ImageBase));
if(baseDll == NULL)
{
baseDll = MapViewOfFileEx(hMapping, FILE_EXECUTE | FILE_MAP_WRITE, 0, 0, 0, NULL);
if(baseDll == NULL)
{
CloseHandle(hMapping);
UnmapViewOfFile(baseAddress);
return NULL;
}
}
CloseHandle(hMapping);
// Copy the headers
memcpy(baseDll, baseAddress, pNTHeader->OptionalHeader.SizeOfHeaders);
// Point the headers variable to the new version
dosHeader = (PIMAGE_DOS_HEADER)baseDll;
pNTHeader = (PIMAGE_NT_HEADERS)((LONG)dosHeader + dosHeader->e_lfanew);
PIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(pNTHeader);
for(int i = 0; i < pNTHeader->FileHeader.NumberOfSections; i++, pSection++)
memcpy((PBYTE)baseDll + pSection->VirtualAddress, (PBYTE)baseAddress + pSection->PointerToRawData, pSection->SizeOfRawData);
if(!(dwFlags & LOAD_LIBRARY_AS_DATAFILE))
{
// Base relocation if the base address is not the expected one
if((DWORD)baseDll != pNTHeader->OptionalHeader.ImageBase)
{
PIMAGE_DATA_DIRECTORY relocDir = (PIMAGE_DATA_DIRECTORY)&(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]);
if(relocDir->Size)
{
PIMAGE_BASE_RELOCATION baseRel = (PIMAGE_BASE_RELOCATION)((PBYTE)baseDll + relocDir->VirtualAddress);
while(baseRel->VirtualAddress)
{
// We need a 16bit type
unsigned short *relValue = (unsigned short *)((PBYTE)baseRel + sizeof(IMAGE_BASE_RELOCATION));
DWORD nEntries = (baseRel->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
PBYTE pageAddress = (PBYTE)baseDll + baseRel->VirtualAddress;
for(DWORD i = 0; i < nEntries; i++, relValue++)
{
unsigned short pageOffset = *relValue & 0x0FFF;
unsigned char type = *relValue >> 12;
switch(type)
{
case IMAGE_REL_BASED_ABSOLUTE:
// This is a no-op; it is used to align the chunk to a 32-bits-
// border. The position should be 0.
break;
case IMAGE_REL_BASED_HIGHLOW:
// The entire 32-bit-relocation must be applied to the entire 32
// bits in question. This (and the no-op '0') is the only
// relocation type I've actually found in binaries.
*((DWORD *)(pageAddress + pageOffset)) += ((DWORD)baseDll - pNTHeader->OptionalHeader.ImageBase);
break;
default:
break;
}
}
baseRel = (PIMAGE_BASE_RELOCATION)((PBYTE)baseRel + baseRel->SizeOfBlock);
}
}
pNTHeader->OptionalHeader.ImageBase = (DWORD)baseDll;
}
}
// New entry in the map
MODULES_LIST *entry;
entry = new MODULES_LIST;
entry->hashName = hash_uppercaseW(lpFilePath);
entry->hModule = (HMODULE)baseDll;
entry->instances = 1;
entry->flags = dwFlags;
entry->markedForDeletion = FALSE;
entry->next = NULL;
// WINDOWS 7 MESS
wchar_t targetName[MAX_PATH], *filePart, system32Dir[MAX_PATH];
GetFullPathName(lpFilePath, MAX_PATH, targetName, &filePart);
GetSystemDirectory(system32Dir, MAX_PATH - 1);
lstrcpyn(filePart, filePart, 16);
lstrcat(system32Dir, L"\\");
if(hash_uppercaseW(filePart) == 0x5DE52DB9)
{
filePart[0] = 0;
// Is the file in system32 ?
if(hash_uppercaseW(targetName) == hash_uppercaseW(system32Dir))
entry->bMsWinCore = TRUE;
else
entry->bMsWinCore = FALSE;
}
else
entry->bMsWinCore = FALSE;
libInstancesMap[(HMODULE)baseDll] = entry;
if(!(dwFlags & LOAD_LIBRARY_AS_DATAFILE))
{
if(!(dwFlags & DONT_RESOLVE_DLL_REFERENCES))
{
// Resolving imports
PIMAGE_DATA_DIRECTORY importsDir = (PIMAGE_DATA_DIRECTORY)&(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
if(importsDir->Size)
{
PIMAGE_IMPORT_DESCRIPTOR baseImp = (PIMAGE_IMPORT_DESCRIPTOR)((PBYTE)baseDll + importsDir->VirtualAddress);
while(baseImp->OriginalFirstThunk)
{
// List of imports
PDWORD nameRef = (DWORD *)((PBYTE)baseDll + baseImp->OriginalFirstThunk);
// Address entries
PDWORD symbolRef = (DWORD *)((PBYTE)baseDll + baseImp->FirstThunk);
// I know, I know, I know. This could be done just with a
// LoadLibrary call but I need to know, before calling LoadLibrary,
// if we already have an instance of the module available
char importName[MAX_PATH];
lstrcpyA(importName, (const char*)((PBYTE)baseDll + baseImp->Name));
HMODULE hLib = GetModuleHandleByString(importName, byWindows);
if(hLib == NULL)
{
// Load the library
#if PHASE > 0
hLib = LoadLibraryExA((const char *)((PBYTE)baseDll + baseImp->Name), 0, dwFlags);
#else
hLib = ::LoadLibraryExA((const char *)((PBYTE)baseDll + baseImp->Name), 0, dwFlags);
#endif
if(hLib == NULL)
{
FreeLibrary((HMODULE)baseDll);
UnmapViewOfFile(baseAddress);
return NULL;
}
else
{
entry->next = new MODULES_LIST;
entry = entry->next;
entry->hashName = 0; // useless here
entry->hModule = hLib;
entry->markedForDeletion = FALSE; // useless here
entry->instances = 0; // useless here
entry->flags = 0; // useless here
entry->bMsWinCore = FALSE; // useless here
entry->next = NULL;
}
}
else if(!byWindows)
{
// We loaded the library: add it to the dependencies
entry->next = new MODULES_LIST;
entry = entry->next;
entry->hashName = 0; // useless here
entry->hModule = hLib;
entry->markedForDeletion = FALSE; // useless here
entry->instances = 0; // useless here
entry->flags = 0; // useless here
entry->bMsWinCore = FALSE; // useless here
entry->next = NULL;
// Add 1 to the number of instances
std::map<HMODULE, MODULES_LIST *>::iterator& module_entryit = libInstancesMap.find(hLib);
if(module_entryit != libInstancesMap.end() && module_entryit->second->instances != 0xFFFF)
module_entryit->second->instances++;
}
// If it's one of the new messy DLL files, then hijack to kernel32.dll
std::map<HMODULE, MODULES_LIST *>::const_iterator& moduleit = libInstancesMap.find(hLib);
if(moduleit != libInstancesMap.end() && moduleit->second->bMsWinCore)
hLib = GetModuleHandle(KERNEL32);
for (; *nameRef; nameRef++, symbolRef++)
{
if(((PIMAGE_THUNK_DATA)nameRef)->u1.Ordinal & 0x80000000)
{
DWORD nOrdinal = (((PIMAGE_THUNK_DATA)nameRef)->u1.Ordinal & 0xFFFF);
#if 0
if(hash_uppercase((const char *)((PBYTE)baseDll + baseImp->Name)) == KERNEL32)
{
if(nOrdinal == 241) *symbolRef = (DWORD)_FreeLibrary;
else if(nOrdinal == 376) *symbolRef = (DWORD)_GetModuleHandleA;
else if(nOrdinal == 377) *symbolRef = (DWORD)_GetModuleHandleW;
else if(nOrdinal == 581) *symbolRef = (DWORD)_LoadLibraryA;
else if(nOrdinal == 584) *symbolRef = (DWORD)_LoadLibraryW;
else if(nOrdinal == 582) *symbolRef = (DWORD)_LoadLibraryExA;
else if(nOrdinal == 583) *symbolRef = (DWORD)_LoadLibraryExW;
else *symbolRef = (DWORD)GetProcAddress(hLib, 0, nOrdinal);
}
else
#endif
*symbolRef = (DWORD)GetProcAddress(hLib, 0, nOrdinal);
}
else
{
const char *funcName = (const char *)((PIMAGE_IMPORT_BY_NAME)((PBYTE)baseDll + *nameRef))->Name;
// remember the user32.dll hell ?
unsigned int func_hash = hash_uppercase(funcName);
#if PHASE > 1
if(hash_uppercase((const char *)((PBYTE)baseDll + baseImp->Name)) == KERNEL32)
{
if(func_hash == FREELIBRARY) *symbolRef = (DWORD)_FreeLibrary;
else if(func_hash == GETMODULEHANDLEA) *symbolRef = (DWORD)_GetModuleHandleA;
else if(func_hash == GETMODULEHANDLEW) *symbolRef = (DWORD)_GetModuleHandleW;
else if(func_hash == LOADLIBRARYA) *symbolRef = (DWORD)_LoadLibraryA;
else if(func_hash == LOADLIBRARYW) *symbolRef = (DWORD)_LoadLibraryW;
else if(func_hash == LOADLIBRARYEXA) *symbolRef = (DWORD)_LoadLibraryExA;
else if(func_hash == LOADLIBRARYEXW) *symbolRef = (DWORD)_LoadLibraryExW;
else *symbolRef = (DWORD)GetProcAddress(hLib, func_hash, 0);
}
else
#endif
*symbolRef = (DWORD)GetProcAddress(hLib, func_hash, 0);
}
}
baseImp++;
}
}
}
// Protecting sections
pSection = IMAGE_FIRST_SECTION(pNTHeader);
for(int i = 0; i < pNTHeader->FileHeader.NumberOfSections; i++, pSection++)
{
DWORD size = pSection->SizeOfRawData;
if(!size)
{
if(pSection->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
size = pNTHeader->OptionalHeader.SizeOfInitializedData;
else if(pSection->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
size = pNTHeader->OptionalHeader.SizeOfUninitializedData;
else
continue;
}
DWORD oldProtect, newProtect;
BOOL protectR = (pSection->Characteristics & IMAGE_SCN_MEM_READ) ? TRUE : FALSE;
BOOL protectW = (pSection->Characteristics & IMAGE_SCN_MEM_WRITE) ? TRUE : FALSE;
BOOL protectX = (pSection->Characteristics & IMAGE_SCN_MEM_EXECUTE) ? TRUE : FALSE;
if(!protectR && !protectW && protectX) newProtect = PAGE_EXECUTE;
else if(protectR && !protectW && protectX) newProtect = PAGE_EXECUTE_READ;
else if(protectR && !protectW && protectX) newProtect = PAGE_EXECUTE_READWRITE;
else if(!protectR && protectW && protectX) newProtect = PAGE_EXECUTE_WRITECOPY;
else if(!protectR && !protectW && !protectX) newProtect = PAGE_NOACCESS;
else if(!protectR && protectW && !protectX) newProtect = PAGE_WRITECOPY;
else if(protectR && !protectW && !protectX) newProtect = PAGE_READONLY;
else if(protectR && protectW && !protectX) newProtect = PAGE_READWRITE;
if(pSection->Characteristics & IMAGE_SCN_MEM_NOT_CACHED)
newProtect |= PAGE_NOCACHE;
VirtualProtect((PBYTE)baseDll + pSection->VirtualAddress, size, newProtect, &oldProtect);
}
if(!(dwFlags & DONT_RESOLVE_DLL_REFERENCES))
{
// Notify the library
if(pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL)
{
DllEntryProc entryPoint = (DllEntryProc)((PBYTE)baseDll + pNTHeader->OptionalHeader.AddressOfEntryPoint);
if(!lstrcmp(filePart, L"chrome.dll")) __asm { int 3 };
(*entryPoint)((HINSTANCE)baseDll, DLL_PROCESS_ATTACH, 0);
}
}
}
// Unmap the file, please
UnmapViewOfFile(baseAddress);
return (HMODULE)baseDll;
}
/**
* LoadLibraryA
* Loads the library.
*/
HMODULE kernel32::LoadLibraryA(LPCSTR lpFileName)
{
HMODULE hMod = LoadLibraryExA(lpFileName, 0, 0);
return hMod;
}
/**
* LoadLibraryW
* Loads the library.
*/
HMODULE kernel32::LoadLibraryW(LPCTSTR lpFileName)
{
HMODULE hMod = LoadLibraryExW(lpFileName, 0, 0);
return hMod;
}
/**
* LoadLibraryExA
* Wrapping the wrapper: initializes the critical sections and calls LoadLibraryExWrapped
*/
HMODULE kernel32::LoadLibraryExA(LPCSTR lpFileName, HANDLE hFile, DWORD dwFlags)
{
wchar_t *wstring = new wchar_t[2 * lstrlenA(lpFileName) + 1];
MultiByteToWideChar(CP_ACP, 0, lpFileName, lstrlenA(lpFileName) + 1, wstring, lstrlenA(lpFileName) + 1);
HMODULE hMod = LoadLibraryExW(wstring, hFile, dwFlags);
delete [] wstring;
return hMod;
}
/**
* LoadLibraryExW
* Wrapping the wrapper: initializes the critical sections and calls LoadLibraryExWrapped
*/
HMODULE kernel32::LoadLibraryExW(LPCTSTR lpFileName, HANDLE hFile, DWORD dwFlags)
{
EnterCriticalSection(&libCritical);
HMODULE hMod = LoadLibraryExWrapped(lpFileName, hFile, dwFlags);
LeaveCriticalSection(&libCritical);
return hMod;
}
/**
* FreeLibrary
* Critical section initialization and library freeing.
*/
BOOL kernel32::FreeLibrary(HMODULE hModule)
{
EnterCriticalSection(&libCritical);
BOOL bRet = FreeLibraryWrapped(hModule);
LeaveCriticalSection(&libCritical);
return bRet;
}