forked from uItra/Injectora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRemoteLoader.cpp
2424 lines (2065 loc) · 70.1 KB
/
CRemoteLoader.cpp
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 "CRemoteLoader.h"
#include <Tlhelp32.h>
#include <DbgHelp.h>
#pragma comment (lib, "DbgHelp.lib")
//
// Pube lick functions
//
void CRemoteLoader::SetProcess(HANDLE hProcess, DWORD dwProcessId)
{
HMODULE hNtDll = (HMODULE)Utils::GetLocalModuleHandle("ntdll.dll");
fnNTQIP = (tNTQIP)Utils::GetProcAddress(hNtDll, "NtQueryInformationProcess");
fnNTQSI = (tNTQSI)Utils::GetProcAddress(hNtDll, "NtQuerySystemInformation");
m_hProcess = hProcess;
m_dwProcessId = dwProcessId;
m_bIs64bit = GetProcessPlatform() == 2 ? true : false;
}
HMODULE CRemoteLoader::LdrpLoadDll(LPCCH Path)
{
WCHAR WideCharModule[MAX_PATH] = { 0 };
size_t charsConverted;
mbstowcs_s(&charsConverted, WideCharModule, Path, MAX_PATH);
return LdrpLoadDll(WideCharModule);
}
HMODULE CRemoteLoader::LdrpLoadDll(LPCWCH Path)
{
if (Path == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LdrpLoadDll] Path is NULL");
#endif
return NULL;
}
FARPROC RemoteLdrpLoadDll = (FARPROC)Utils::GetProcAddress(Utils::GetLocalModuleHandle("ntdll.dll"), "LdrpLoadDll");//GetRemoteProcAddressA("ntdll.dll", "LdrLoadDll");
if (RemoteLdrpLoadDll == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LdrpLoadDll] RemoteLdrLoadDll resolve failure");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LdrpLoadDll] LdrpLoadDll = 0x%IX", RemoteLdrpLoadDll);
#endif
NTSTATUS Status;
UNICODE_STRING DllString1;
ZeroMemory(&DllString1, sizeof(UNICODE_STRING));
UNICODE_STRING DllString2;
ZeroMemory(&DllString2, sizeof(UNICODE_STRING));
UNICODE_STRING LdrApiDefaultExtension;
ZeroMemory(&LdrApiDefaultExtension, sizeof(UNICODE_STRING));
UNICODE_STRING* DllName = new UNICODE_STRING;
PUNICODE_STRING pPath = nullptr;
ULONG_PTR cookie = 0;
wchar_t wBuf[255] = { 0 };
std::wstring path(Path);
if (path.rfind(L".dll") != std::wstring::npos)
path.erase(path.rfind(L".dll"));
static HMODULE hNtdll = Utils::GetLocalModuleHandle("ntdll.dll");
static tRtlInitUnicodeString RtlInitUnicodeString = (tRtlInitUnicodeString)Utils::GetProcAddress(hNtdll, "RtlInitUnicodeString");
static tRtlFreeUnicodeString RtlFreeUnicodeString = (tRtlFreeUnicodeString)Utils::GetProcAddress(hNtdll, "RtlFreeUnicodeString");
static tRtlNtStatusToDosError RtlNtStatusToDosError = (tRtlNtStatusToDosError)Utils::GetProcAddress(hNtdll, "RtlNtStatusToDosError");
static tRtlDosApplyFileIsolationRedirection_Ustr RtlDosApplyFileIsolationRedirection_Ustr = (tRtlDosApplyFileIsolationRedirection_Ustr)Utils::GetProcAddress(hNtdll, "RtlDosApplyFileIsolationRedirection_Ustr");
RtlInitUnicodeString(DllName, path.c_str());
RtlInitUnicodeString(&LdrApiDefaultExtension, L".DLL");
DllString1.Buffer = wBuf;
DllString1.Length = NULL;
DllString1.MaximumLength = ARRAYSIZE(wBuf);
BOOLEAN RedirectedDll = FALSE;
/* Check if the SxS Assemblies specify another file */
Status = RtlDosApplyFileIsolationRedirection_Ustr(TRUE, DllName, &LdrApiDefaultExtension, &DllString1, &DllString2, &DllName, NULL, NULL, NULL);
/* Check success */
if (NT_SUCCESS(Status))
RedirectedDll = TRUE;
ULONG Flags = NULL; // Maybe use flags later. Idk.
void* flagsPtr = CommitMemory((void*)&Flags, sizeof(ULONG));
void* ReturnPointerValue = RemoteAllocateMemory(sizeof(size_t));
if (m_bIs64bit)
{
// Backup RCX, RDX, R8 and R9 on stack
BeginCall64();
//
PushInt64((unsigned __int64)RedirectedDll);
PushInt64((unsigned __int64)NULL);
PushInt64((unsigned __int64)flagsPtr);
PushUNICODEStringStructure(DllName);
PushInt64((unsigned __int64)ReturnPointerValue);
PushInt64((unsigned __int64)TRUE);
PushCall(CCONV_WIN64, RemoteLdrpLoadDll);
//
// Module Handle is located in RDX and at QWORD PTR [ReturnPointerValue].
// Could do 'mov rax, [ReturnPointerValue]' but it takes many more opcodes to do so.
// We could also just RPM twice on ReturnPointerValue but it's better just to get it from rdx.
//
// mov rax, rdx
AddByteToBuffer(0x48);
AddByteToBuffer(0x89);
AddByteToBuffer(0xD0);
// mov [ReturnPointerValue], rax
AddByteToBuffer(0x48);
AddByteToBuffer(0xA3);
AddLong64ToBuffer((unsigned __int64)ReturnPointerValue);
// Restore RCX, RDX, R8 and R9 from stack and return
EndCall64();
}
else
{
PushInt(RedirectedDll);
PushInt(NULL);
PushInt((unsigned int)flagsPtr);
PushUNICODEStringStructure(DllName);
PushInt((unsigned long)ReturnPointerValue);
PushInt(TRUE);
PushCall(CCONV_STDCALL, RemoteLdrpLoadDll);
//
// Module Handle is located in [EDX].
// To avoid calling RPM twice, we pass the [edx] into eax instead of just edx.
//
// mov eax,DWORD PTR [edx]
AddByteToBuffer(0x8B);
AddByteToBuffer(0x02);
// mov ptr, eax
AddByteToBuffer(0xA3);
AddLongToBuffer((unsigned long)ReturnPointerValue);
// xor eax, eax
AddByteToBuffer(0x33);
AddByteToBuffer(0xC0);
// ret 4
AddByteToBuffer(0xC2);
AddByteToBuffer(0x04);
AddByteToBuffer(0x00);
}
if (!ExecuteRemoteThreadBuffer(m_CurrentRemoteThreadBuffer, true))
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LdrpLoadDll] ExecuteRemoteThreadBuffer failed");
#endif
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LdrpLoadDll] ExecuteRemoteThreadBuffer succeeded");
#endif
HMODULE RemoteModuleHandle = 0;
if (ReadProcessMemory(m_hProcess, ReturnPointerValue, &RemoteModuleHandle, sizeof(HMODULE), NULL))
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
}
else
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
if (RemoteModuleHandle == 0)
RemoteModuleHandle = GetRemoteModuleHandleW(Path);
}
return RemoteModuleHandle;
}
HMODULE CRemoteLoader::LoadDependencyA(LPCCH Path)
{
WCHAR Module[MAX_PATH] = { 0 };
size_t charsConverted;
mbstowcs_s(&charsConverted, Module, Path, MAX_PATH);
return LoadDependencyW(Module);
}
HMODULE CRemoteLoader::LoadDependencyW(LPCWCH Path)
{
if (Path == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadDependencyW] szString is NULL");
#endif
return NULL;
}
FARPROC RemoteLdrLoadDll = (FARPROC)Utils::GetProcAddress(Utils::GetLocalModuleHandle("ntdll.dll"), "LdrLoadDll");//GetRemoteProcAddressA("ntdll.dll", "LdrLoadDll");
if (RemoteLdrLoadDll == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadDependencyW] RemoteLdrLoadDll resolve failure");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadDependencyW] LdrLoadDll = 0x%IX", RemoteLdrLoadDll);
#endif
// Make new unicode string object
static tRtlInitUnicodeString RtlInitUnicodeString = (tRtlInitUnicodeString)Utils::GetProcAddress(Utils::GetLocalModuleHandle("ntdll.dll"), "RtlInitUnicodeString");
UNICODE_STRING unicodePath;
RtlInitUnicodeString(&unicodePath, Path);
ULONG Flags = NULL; // Maybe use flags later. Idk.
void* flagsPtr = CommitMemory((void*)&Flags, sizeof(ULONG));
void* ReturnPointerValue = RemoteAllocateMemory(sizeof(size_t));
if (m_bIs64bit)
{
// Backup RCX, RDX, R8 and R9 on stack
BeginCall64();
//
PushInt64(NULL);
PushInt64((unsigned __int64)flagsPtr);
PushUNICODEStringStructure(&unicodePath);
PushInt64((unsigned __int64)ReturnPointerValue);
PushCall(CCONV_WIN64, RemoteLdrLoadDll);
//
// Module Handle is located in RDX and at QWORD PTR [ReturnPointerValue].
// Could do 'mov rax, [ReturnPointerValue]' but it takes many more opcodes to do so.
// We could also just RPM twice on ReturnPointerValue but it's better just to get it from rdx.
//
// mov rax, rdx
AddByteToBuffer(0x48);
AddByteToBuffer(0x89);
AddByteToBuffer(0xD0);
// mov [ReturnPointerValue], rax
AddByteToBuffer(0x48);
AddByteToBuffer(0xA3);
AddLong64ToBuffer((unsigned __int64)ReturnPointerValue);
// Restore RCX, RDX, R8 and R9 from stack and return
EndCall64();
}
else
{
PushInt(NULL);
PushInt((unsigned int)flagsPtr);
PushUNICODEStringStructure(&unicodePath);
PushInt((unsigned long)ReturnPointerValue);
PushCall(CCONV_STDCALL, RemoteLdrLoadDll);
//
// Module Handle is located in [EDX].
// To avoid calling RPM twice, we pass the [edx] into eax instead of just edx.
//
// mov eax,DWORD PTR [edx]
AddByteToBuffer(0x8B);
AddByteToBuffer(0x02);
// mov ptr, eax
AddByteToBuffer(0xA3);
AddLongToBuffer((unsigned long)ReturnPointerValue);
// xor eax, eax
AddByteToBuffer(0x33);
AddByteToBuffer(0xC0);
// ret 4
AddByteToBuffer(0xC2);
AddByteToBuffer(0x04);
AddByteToBuffer(0x00);
}
if (!ExecuteRemoteThreadBuffer(m_CurrentRemoteThreadBuffer, true))
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathW] ExecuteRemoteThreadBuffer failed");
#endif
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleByNameW] ExecuteRemoteThreadBuffer succeeded");
#endif
HMODULE RemoteModuleHandle = 0;
if (ReadProcessMemory(m_hProcess, ReturnPointerValue, &RemoteModuleHandle, sizeof(HMODULE), NULL))
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
}
else
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
if (RemoteModuleHandle == 0)
RemoteModuleHandle = GetRemoteModuleHandleW(Path);
}
return RemoteModuleHandle;
}
HMODULE CRemoteLoader::LoadLibraryByPathA(LPCCH Path, ULONG Flags/*= NULL*/)
{
WCHAR Module[MAX_PATH] = { 0 };
size_t charsConverted;
mbstowcs_s(&charsConverted, Module, Path, MAX_PATH);
return LoadLibraryByPathW(Module, Flags);
}
HMODULE CRemoteLoader::LoadLibraryByPathW(LPCWCH Path, ULONG Flags/*= NULL*/)
{
if (Path == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathW] szString is NULL");
#endif
return NULL;
}
FARPROC RemoteLdrLoadDll = (FARPROC)Utils::GetProcAddress(Utils::GetLocalModuleHandle("ntdll.dll"), "LdrLoadDll"); //GetRemoteProcAddressA("ntdll.dll", "LdrLoadDll");
if (RemoteLdrLoadDll == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathW] RemoteLdrLoadDll resolve failure");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathW] LdrLoadDll = 0x%IX", RemoteLdrLoadDll);
#endif
// Make new unicode string object
static tRtlInitUnicodeString RtlInitUnicodeString = (tRtlInitUnicodeString)Utils::GetProcAddress(Utils::GetLocalModuleHandle("ntdll.dll"), "RtlInitUnicodeString");
UNICODE_STRING unicodePath;
RtlInitUnicodeString(&unicodePath, Path);
void* flagsPtr = CommitMemory((void*)&Flags, sizeof(ULONG));
void* ReturnPointerValue = RemoteAllocateMemory(sizeof(size_t));
if (m_bIs64bit)
{
// Backup RCX, RDX, R8 and R9 on stack
BeginCall64();
//
PushInt64(NULL);
PushInt64((unsigned __int64)flagsPtr);
PushUNICODEStringStructure(&unicodePath);
PushInt64((unsigned __int64)ReturnPointerValue);
PushCall(CCONV_WIN64, RemoteLdrLoadDll);
//
// Module Handle is located in RDX and at QWORD PTR [ReturnPointerValue].
// Could do 'mov rax, [ReturnPointerValue]' but it takes many more opcodes to do so.
// We could also just RPM twice on ReturnPointerValue but it's better just to get it from rdx.
//
// mov rax, rdx
AddByteToBuffer(0x48);
AddByteToBuffer(0x89);
AddByteToBuffer(0xD0);
// mov [ReturnPointerValue], rax
AddByteToBuffer(0x48);
AddByteToBuffer(0xA3);
AddLong64ToBuffer((unsigned __int64)ReturnPointerValue);
// Restore RCX, RDX, R8 and R9 from stack and return
EndCall64();
}
else
{
PushInt(NULL);
PushInt((unsigned int)flagsPtr);
PushUNICODEStringStructure(&unicodePath);
PushInt((unsigned long)ReturnPointerValue);
PushCall(CCONV_STDCALL, RemoteLdrLoadDll);
//
// Module Handle is located in [EDX].
// To avoid calling RPM twice, we pass the [edx] into eax instead of just edx.
//
// mov eax,DWORD PTR [edx]
AddByteToBuffer(0x8B);
AddByteToBuffer(0x02);
// mov ptr, eax
AddByteToBuffer(0xA3);
AddLongToBuffer((unsigned long)ReturnPointerValue);
// xor eax, eax
AddByteToBuffer(0x33);
AddByteToBuffer(0xC0);
// ret 4
AddByteToBuffer(0xC2);
AddByteToBuffer(0x04);
AddByteToBuffer(0x00);
}
if (ExecuteRemoteThreadBuffer(m_CurrentRemoteThreadBuffer) == false)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathW] ExecuteRemoteThreadBuffer failed");
#endif
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleByNameW] ExecuteRemoteThreadBuffer succeeded");
#endif
HMODULE RemoteModuleHandle = 0;
if (ReadProcessMemory(m_hProcess, ReturnPointerValue, &RemoteModuleHandle, sizeof(HMODULE), NULL))
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
}
else
{
RemoteFreeMemory(ReturnPointerValue, sizeof(size_t));
if (RemoteModuleHandle == 0)
RemoteModuleHandle = GetRemoteModuleHandleW(Path);
}
return RemoteModuleHandle;
}
HMODULE CRemoteLoader::LoadLibraryByPathIntoMemoryA(LPCCH Path, BOOL PEHeader)
{
HMODULE hReturnValue = NULL;
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathIntoMemoryA] %s", Path);
#endif
ModuleFile File = InitModuleFile(Path);
if (File.IsValid() == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathIntoMemoryA] Failed to open file handle!");
#endif
MessageBox(0, "Failed to open DLL file!", "Injectora", MB_ICONERROR);
return NULL;
}
hReturnValue = LoadLibraryFromMemory(File.Buffer, File.Size, PEHeader);
if (FreeModuleFile(File) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryByPathIntoMemoryA] Failed to free file handle...");
#endif
}
return hReturnValue;
}
HMODULE CRemoteLoader::LoadLibraryByPathIntoMemoryW(LPCWCH Path, BOOL PEHeader)
{
CHAR PathAnsi[MAX_PATH] = { 0 };
size_t charsConverted;
wcstombs_s(&charsConverted, PathAnsi, Path, MAX_PATH);
return LoadLibraryByPathIntoMemoryA(PathAnsi, PEHeader);
}
HMODULE CRemoteLoader::LoadLibraryFromMemory(PVOID BaseAddress, DWORD SizeOfModule, BOOL PEHeader)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] BaseAddress (0x%IX) - SizeOfModule (0x%X)", BaseAddress, SizeOfModule);
#endif
IMAGE_NT_HEADERS* ImageNtHeaders = ToNts(BaseAddress);
if (ImageNtHeaders == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Invalid Image: No IMAGE_NT_HEADERS");
#endif
return NULL;
}
if (ImageNtHeaders->FileHeader.NumberOfSections == 0)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Invalid Image: No Sections");
#endif
return NULL;
}
if ( m_bIs64bit)
{
//
// Create Remote Procedure Call environment. No need for this in 32 bit
//
DWORD err = CreateRPCEnvironment();
if (err != ERROR_SUCCESS)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] CreateRPCEnvironment failed. Error 0x%X", err);
#endif
return NULL;
}
//
// Create activation context for the module we're injecting. Not needed for x86 modules.
//
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Creating Activation Context!");
#endif
if (!CreateActx(BaseAddress))
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to obtain embedded resource! Continuing anyway without Activation Context...");
#endif
}
else
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Createed Activation Context successfully!");
#endif
}
}
// We do not trust the value of hdr.OptionalHeader.SizeOfImage so we calculate our own SizeOfImage.
// This is the size of the continuous memory block that can hold the headers and all sections.
//
size_t rva_low = (!PEHeader) ? ((size_t)-1) : 0;
size_t rva_high = 0;
PIMAGE_SECTION_HEADER ImageSectionHeader = (PIMAGE_SECTION_HEADER)((ULONG_PTR)&ImageNtHeaders->OptionalHeader + ImageNtHeaders->FileHeader.SizeOfOptionalHeader);
for (size_t i = 0; i < ImageNtHeaders->FileHeader.NumberOfSections; ++i)
{
if (!ImageSectionHeader[i].Misc.VirtualSize)
continue;
if (ImageSectionHeader[i].VirtualAddress < rva_low)
rva_low = ImageSectionHeader[i].VirtualAddress;
if ((ImageSectionHeader[i].VirtualAddress + ImageSectionHeader[i].Misc.VirtualSize) > rva_high)
rva_high = ImageSectionHeader[i].VirtualAddress + ImageSectionHeader[i].Misc.VirtualSize;
}
// Calculated Image Size
//
size_t ImageSize = rva_high - rva_low;
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Calculated size (0x%IX)", ImageSize);
#endif
if ((ImageNtHeaders->OptionalHeader.ImageBase % 4096) != 0)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Invalid Image: Not Page Aligned");
#endif
return NULL;
}
if (ImageNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size && ::ImageDirectoryEntryToData(BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, NULL))
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] This method is not supported for Managed executables!");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Good, no COM/CLR data found!");
#endif
// SizeOfImage NOT the same as module size MOTHERFUCKER
// http://www.youtube.com/watch?v=pele5vptVgc
void* AllocatedRemoteMemory = RemoteAllocateMemory(ImageSize);
if (AllocatedRemoteMemory == NULL)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to allocate remote memory for module!");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Allocated remote module at [0x%IX]!", AllocatedRemoteMemory);
DebugShout("[LoadLibraryFromMemory] Processing Import Tables....\n");
#endif
if (ProcessImportTable(BaseAddress, AllocatedRemoteMemory) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to fix imports!");
#endif
return NULL;
}
if (ProcessDelayedImportTable(BaseAddress, AllocatedRemoteMemory) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to fix delayed imports!");
#endif
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Fixed Imports!");
DebugShout("[LoadLibraryFromMemory] Processing Relocations....\n");
#endif
if (ProcessRelocations(BaseAddress, AllocatedRemoteMemory) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to process relocations!");
#endif
RemoteFreeMemory(AllocatedRemoteMemory, SizeOfModule);
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Fixed Relocations!");
DebugShout("[LoadLibraryFromMemory] Processing Sections!");
#endif
if (ProcessSections(BaseAddress, AllocatedRemoteMemory, PEHeader) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to process sections!");
#endif
}
if (m_bIs64bit && PEHeader)
EnableExceptions(BaseAddress, AllocatedRemoteMemory, ImageSize);
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Processed sections!");
DebugShout("[LoadLibraryFromMemory] Processing TLS Callback Entries!");
#endif
if (ProcessTlsEntries(BaseAddress, AllocatedRemoteMemory) == FALSE)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] ProcessTlsEntries Failed!");
#endif
// we can also choose to continue here, but we wont cause unsafe
return NULL;
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] Processed Tls Entries!");
#endif
// Security cookie if needed
InitializeCookie(BaseAddress, AllocatedRemoteMemory);
if (ImageNtHeaders->OptionalHeader.AddressOfEntryPoint)
{
FARPROC DllEntryPoint = MakePtr(FARPROC, AllocatedRemoteMemory, ImageNtHeaders->OptionalHeader.AddressOfEntryPoint);
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] DllEntrypoint = 0x%IX", DllEntryPoint);
#endif
if (CallEntryPoint(AllocatedRemoteMemory, DllEntryPoint) == false)
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] Failed to execute remote thread buffer");
#endif
}
else
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] Executed the remote thread buffer successfully [0x%IX]", DllEntryPoint);
#endif
}
}
else
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] AddressOfEntryPoint is NULL");
#endif
}
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadModuleFromMemory] Returning Pointer (0x%IX)", AllocatedRemoteMemory);
#endif
return (HMODULE)AllocatedRemoteMemory;
}
// Private functions
HMODULE CRemoteLoader::GetRemoteModuleHandleA(const char* Module)
{
void* dwModuleHandle = 0;
PPROCESS_BASIC_INFORMATION pbi = NULL;
PEB peb;
PEB_LDR_DATA peb_ldr;
// Try to allocate buffer
HANDLE hHeap = GetProcessHeap();
DWORD dwSize = sizeof(PROCESS_BASIC_INFORMATION);
pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSize);
ULONG dwSizeNeeded = 0;
NTSTATUS dwStatus = fnNTQIP(m_hProcess, ProcessBasicInformation, pbi, dwSize, &dwSizeNeeded);
if (dwStatus >= 0 && dwSize < dwSizeNeeded)
{
if (pbi)
HeapFree(hHeap, 0, pbi);
pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSizeNeeded);
if (!pbi)
{
#ifdef _DEBUG
printf("Couldn't allocate heap buffer!\n");
#endif
return NULL;
}
dwStatus = fnNTQIP(m_hProcess, ProcessBasicInformation, pbi, dwSizeNeeded, &dwSizeNeeded);
}
// Did we successfully get basic info on process
if (dwStatus >= 0)
{
// Read Process Environment Block (PEB)
if (pbi->PebBaseAddress)
{
SIZE_T dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, pbi->PebBaseAddress, &peb, sizeof(peb), &dwBytesRead))
{
dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, peb.Ldr, &peb_ldr, sizeof(peb_ldr), &dwBytesRead))
{
LIST_ENTRY *pLdrListHead = (LIST_ENTRY *)peb_ldr.InLoadOrderModuleList.Flink;
LIST_ENTRY *pLdrCurrentNode = peb_ldr.InLoadOrderModuleList.Flink;
do
{
LDR_DATA_TABLE_ENTRY lstEntry = { 0 };
dwBytesRead = 0;
if (!ReadProcessMemory(m_hProcess, (void*)pLdrCurrentNode, &lstEntry, sizeof(LDR_DATA_TABLE_ENTRY), &dwBytesRead))
{
#ifdef _DEBUG
char dbgOut[1024];
sprintf_s(dbgOut, "CRemoteLoader[GetRemoteModuleHandleA] Could not read list entry from LDR list. Error = %X", GetLastError());
MessageBox(0, dbgOut, "Injectora", MB_ICONERROR);
#endif
if (pbi)
HeapFree(hHeap, 0, pbi);
return NULL;
}
pLdrCurrentNode = lstEntry.InLoadOrderLinks.Flink;
wchar_t wcsBaseDllName[MAX_PATH] = { 0 };
char strBaseDllName[MAX_PATH] = { 0 };
if (lstEntry.BaseDllName.Length > 0)
{
dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, (LPCVOID)lstEntry.BaseDllName.Buffer, &wcsBaseDllName, lstEntry.BaseDllName.Length, &dwBytesRead))
{
size_t bytesCopied = 0;
wcstombs_s(&bytesCopied, strBaseDllName, wcsBaseDllName, MAX_PATH);
}
}
//wchar_t wcsFullDllName[MAX_PATH] = { 0 };
//char strFullDllName[MAX_PATH] = { 0 };
//if (lstEntry.FullDllName.Length > 0)
//{
// dwBytesRead = 0;
// if (ReadProcessMemory(m_hProcess, (LPCVOID)lstEntry.FullDllName.Buffer, &wcsFullDllName, lstEntry.FullDllName.Length, &dwBytesRead))
// {
// size_t bytesCopied = 0;
// wcstombs_s(&bytesCopied, strFullDllName, wcsFullDllName, MAX_PATH);
// }
//}
if (lstEntry.DllBase != nullptr && lstEntry.SizeOfImage != 0)
{
if (_stricmp(strBaseDllName, Module) == 0)
{
dwModuleHandle = lstEntry.DllBase;
break;
}
}
} while (pLdrListHead != pLdrCurrentNode);
} // Get Ldr
} // Read PEB
} // Check for PEB
}
if (pbi)
HeapFree(hHeap, 0, pbi);
return (HMODULE)dwModuleHandle;
}
HMODULE CRemoteLoader::GetRemoteModuleHandleW(LPCWCH Module)
{
char ModuleAnsi[MAX_PATH] = { 0 };
size_t charsConverted;
wcstombs_s(&charsConverted, ModuleAnsi, Module, MAX_PATH);
return GetRemoteModuleHandleA(ModuleAnsi);
}
IMAGE_DOS_HEADER* CRemoteLoader::ToDos(PVOID BaseAddress)
{
PIMAGE_DOS_HEADER ImageDosHeader = (PIMAGE_DOS_HEADER)(BaseAddress);
if (!ImageDosHeader)
return NULL;
if (ImageDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
return ImageDosHeader;
}
IMAGE_NT_HEADERS* CRemoteLoader::ToNts(PVOID BaseAddress)
{
IMAGE_DOS_HEADER* ImageDosHeader = ToDos(BaseAddress);
if (ImageDosHeader == 0)
return 0;
IMAGE_NT_HEADERS* ImageNtHeaders = (IMAGE_NT_HEADERS*)((DWORD_PTR)BaseAddress + ImageDosHeader->e_lfanew);
if (ImageNtHeaders->Signature != IMAGE_NT_SIGNATURE)
return 0;
return ImageNtHeaders;
}
void* CRemoteLoader::RvaToPointer(ULONG RVA, PVOID BaseAddress)
{
PIMAGE_NT_HEADERS ImageNtHeaders = ToNts(BaseAddress);
if (ImageNtHeaders == 0)
return 0;
return ::ImageRvaToVa(ImageNtHeaders, BaseAddress, RVA, 0);
}
BOOL CRemoteLoader::CallEntryPoint(void* BaseAddress, FARPROC Entrypoint)
{
if (m_bIs64bit)
{
// ActivateActCtx
if (m_pAContext)
{
size_t rsp_dif = 0x28;
rsp_dif = Utils::Align(rsp_dif, 0x10);
// sub rsp, (rsp_dif + 8)
AddByteToBuffer(0x48);
AddByteToBuffer(0x83);
AddByteToBuffer(0xEC);
AddByteToBuffer((unsigned char)(rsp_dif + 8));
// >>>
// >>>
// mov rax, m_pAContext
AddByteToBuffer(0x48);
AddByteToBuffer(0xB8);
AddLong64ToBuffer((size_t)m_pAContext);
// mov rax, [rax]
AddByteToBuffer(0x48);
AddByteToBuffer(0x8B);
AddByteToBuffer(0x00);
// mov rcx, rax -> first parameter
AddByteToBuffer(0x48);
AddByteToBuffer(0x89);
AddByteToBuffer(0xC1);
// mov rdx, (m_pAContext + sizeof(HANDLE)) -> second parameter
LoadParam64((size_t)m_pAContext + sizeof(HANDLE), PARAM_INDEX_RDX);
// mov r13, calladdress
AddByteToBuffer(0x49);
AddByteToBuffer(0xBD);
AddLong64ToBuffer((size_t)ActivateActCtx);
// call r13
AddByteToBuffer(0x41);
AddByteToBuffer(0xFF);
AddByteToBuffer(0xD5);
// >>>
// >>>
// add rsp, (rsp_dif + 8)
AddByteToBuffer(0x48);
AddByteToBuffer(0x83);
AddByteToBuffer(0xC4);
AddByteToBuffer((unsigned char)(rsp_dif + 8));
}
/* Call the actual entry point */
PushInt64((unsigned __int64)BaseAddress);
PushInt64(DLL_PROCESS_ATTACH);
PushInt64(0x00);
PushCall(CCONV_WIN64, Entrypoint);
// DeactivateActCtx
if (m_pAContext)
{
size_t rsp_dif = 0x28;
rsp_dif = Utils::Align(rsp_dif, 0x10);
// sub rsp, (rsp_dif + 8)
AddByteToBuffer(0x48);
AddByteToBuffer(0x83);
AddByteToBuffer(0xEC);
AddByteToBuffer((unsigned char)(rsp_dif + 8));
// >>>
// >>>
// mov rax, m_pAContext + sizeof(HANDLE)
AddByteToBuffer(0x48);
AddByteToBuffer(0xB8);
AddLong64ToBuffer((size_t)m_pAContext + sizeof(HANDLE));
// mov rax, [rax]
AddByteToBuffer(0x48);
AddByteToBuffer(0x8B);
AddByteToBuffer(0x00);
// mov rcx, 0 -> first parameter
LoadParam64(0, PARAM_INDEX_RCX);
// mov rdx, rax
AddByteToBuffer(0x48);
AddByteToBuffer(0x89);
AddByteToBuffer(0xC2);
// mov r13, calladdress
AddByteToBuffer(0x49);
AddByteToBuffer(0xBD);
AddLong64ToBuffer((size_t)DeactivateActCtx);
// call r13
AddByteToBuffer(0x41);
AddByteToBuffer(0xFF);
AddByteToBuffer(0xD5);
// >>>
// >>>
// add rsp, (rsp_dif + 8)
AddByteToBuffer(0x48);
AddByteToBuffer(0x83);
AddByteToBuffer(0xC4);
AddByteToBuffer((unsigned char)(rsp_dif + 8));
}
// Signal wait event
SaveRetValAndSignalEvent();
// Restore registers from stack and return
EndCall64();
size_t result;
if (ExecuteInWorkerThread(m_CurrentRemoteThreadBuffer, result) != ERROR_SUCCESS)
{
TerminateWorkerThread();
DestroyRemoteThreadBuffer();
return FALSE;
}
return TRUE;
}
// x86 injection
PushInt((INT)BaseAddress);
PushInt(DLL_PROCESS_ATTACH);
PushInt(0);
PushCall(CCONV_STDCALL, Entrypoint);
// Zero eax and return
// xor eax, eax
AddByteToBuffer(0x33);
AddByteToBuffer(0xC0);
// ret 4
AddByteToBuffer(0xC2);
AddByteToBuffer(0x04);
AddByteToBuffer(0x00);
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("\nCallEntryPoint [0x%IX]:", Entrypoint);
#endif
return ExecuteRemoteThreadBuffer(m_CurrentRemoteThreadBuffer, true);
}
bool CRemoteLoader::CreateActx(PVOID BaseAddress)
{
if (CreateTempManifestFileFromMemory(BaseAddress, 2))
{
bool ret = CreateActxFromManifest(m_tempManifest);
remove(m_tempManifest);
ZeroMemory(m_tempManifest, MAX_PATH);
return ret;
}
else
{
#ifdef DEBUG_MESSAGES_ENABLED
DebugShout("[LoadLibraryFromMemory] Failed to get temp manifest from memory using Resource ID 2. Trying ID 1...");
#endif
//if (CreateTempManifestFileFromMemory(BaseAddress, 1))
//{
// bool ret = CreateActxFromManifest(m_tempManifest);
// remove(m_tempManifest);
// ZeroMemory(m_tempManifest, MAX_PATH);
// return ret;
//}
//else
return false;
}
}
bool CRemoteLoader::CreateTempManifestFileFromMemory(PVOID BaseAddress, DWORD ResourceId)
{
void* ManifestResource = NULL;
DWORD ManifestSize = GetEmbeddedManifestResourceFromMemory(BaseAddress, ResourceId, &ManifestResource);
if (ManifestResource)
{
if (!SetBaseDirectory())