-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdink.cpp
More file actions
1389 lines (1214 loc) · 45.7 KB
/
Copy pathdink.cpp
File metadata and controls
1389 lines (1214 loc) · 45.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <windows.h>
#include "resource.h"
#include <commdlg.h>
#include <string>
#include <tchar.h>
#include <tlhelp32.h>
#include <vector>
#include <winternl.h>
#pragma comment(lib, "version.lib")
#pragma comment(linker, "\"/manifestdependency:type='win32' \
name='Microsoft.Windows.Common-Controls' \
version='6.0.0.0' \
processorArchitecture='*' \
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
using pfnNtCreateThreadEx = NTSTATUS(NTAPI *)(
PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess,
LPVOID ObjectAttributes, HANDLE ProcessHandle,
LPVOID StartAddress, LPVOID Parameter,
BOOL CreateSuspended, ULONG_PTR StackZeroBits,
SIZE_T SizeOfStackCommit, SIZE_T SizeOfStackReserve,
LPVOID BytesBuffer);
using pfnRtlCreateUserThread = NTSTATUS(NTAPI *)(
HANDLE ProcessHandle, PSECURITY_DESCRIPTOR SecurityDescriptor,
BOOLEAN CreateSuspended, ULONG StackZeroBits,
PULONG StackReserved, PULONG StackCommit,
PVOID StartAddress, PVOID StartParameter,
PHANDLE ThreadHandle, PVOID ClientID);
using pfnNtCreateSection = NTSTATUS(NTAPI *)(
PHANDLE SectionHandle, ACCESS_MASK DesiredAccess,
LPVOID ObjectAttributes, PLARGE_INTEGER MaximumSize,
ULONG SectionPageProtection, ULONG AllocationAttributes,
HANDLE FileHandle);
using pfnNtMapViewOfSection = NTSTATUS(NTAPI *)(
HANDLE SectionHandle, HANDLE ProcessHandle,
PVOID* BaseAddress, ULONG_PTR ZeroBits,
SIZE_T CommitSize, PLARGE_INTEGER SectionOffset,
PSIZE_T ViewSize, DWORD InheritDisposition,
ULONG AllocationType, ULONG Win32Protect);
using pfnNtUnmapViewOfSection = NTSTATUS(NTAPI *)(
HANDLE ProcessHandle, PVOID BaseAddress);
struct SelectedProcessInfo
{
TCHAR szDisplayString[512];
DWORD dwProcessID;
bool bSelected;
};
std::wstring GetProcessFullPath(DWORD dwProcessId)
{
std::wstring result = L"";
HANDLE hProcess =
OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwProcessId);
if (hProcess)
{
wchar_t szPath[MAX_PATH];
DWORD dwSize = MAX_PATH;
if (QueryFullProcessImageNameW(hProcess, 0, szPath, &dwSize))
{
result = szPath;
}
CloseHandle(hProcess);
}
return result;
}
std::wstring GetProcessDescription(const wchar_t* szFilePath)
{
DWORD dwHandle = 0;
DWORD dwSize = GetFileVersionInfoSizeW(szFilePath, &dwHandle);
if (dwSize == 0)
return L"";
std::vector<BYTE> buffer(dwSize);
if (!GetFileVersionInfoW(szFilePath, dwHandle, dwSize, &buffer[0]))
return L"";
struct LANGANDCODEPAGE
{
WORD wLanguage;
WORD wCodePage;
} * lpTranslate;
UINT cbTranslate = 0;
if (VerQueryValueW(&buffer[0], L"\\VarFileInfo\\Translation",
(LPVOID*)&lpTranslate, &cbTranslate))
{
for (unsigned int i = 0; i < (cbTranslate / sizeof(struct LANGANDCODEPAGE));
i++)
{
wchar_t subBlock[256];
swprintf_s(subBlock, 256, L"\\StringFileInfo\\%04x%04x\\FileDescription",
lpTranslate[i].wLanguage, lpTranslate[i].wCodePage);
wchar_t* lpDescription = nullptr;
UINT cbBytes = 0;
if (VerQueryValueW(&buffer[0], subBlock, (LPVOID*)&lpDescription,
&cbBytes) &&
cbBytes > 0)
{
return lpDescription;
}
}
}
return L"";
}
static bool IsProcessWow64(HANDLE hProcess)
{
BOOL bWow64 = FALSE;
IsWow64Process(hProcess, &bWow64);
return bWow64 == TRUE;
}
static DWORD FindFirstThreadOfProcess(DWORD dwOwnerPID)
{
DWORD dwTID = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnap == INVALID_HANDLE_VALUE) return 0;
THREADENTRY32 te = {};
te.dwSize = sizeof(te);
if (Thread32First(hSnap, &te))
{
do
{
if (te.th32OwnerProcessID == dwOwnerPID)
{
dwTID = te.th32ThreadID;
break;
}
}
while (Thread32Next(hSnap, &te));
}
CloseHandle(hSnap);
return dwTID;
}
static std::vector<DWORD> GetAllThreadsOfProcess(DWORD dwOwnerPID)
{
std::vector<DWORD> tids;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnap == INVALID_HANDLE_VALUE) return tids;
THREADENTRY32 te = {};
te.dwSize = sizeof(te);
if (Thread32First(hSnap, &te))
{
do
{
if (te.th32OwnerProcessID == dwOwnerPID)
tids.push_back(te.th32ThreadID);
}
while (Thread32Next(hSnap, &te));
}
CloseHandle(hSnap);
return tids;
}
static DWORD FindExportRVA(const BYTE* pFileBase, SIZE_T fileSize,
const char* pszName)
{
if (!pFileBase || fileSize < sizeof(IMAGE_DOS_HEADER)) return 0;
auto* pDOS = reinterpret_cast<const IMAGE_DOS_HEADER*>(pFileBase);
if (pDOS->e_magic != IMAGE_DOS_SIGNATURE) return 0;
auto* pNT = reinterpret_cast<const IMAGE_NT_HEADERS*>(
pFileBase + pDOS->e_lfanew);
if (pNT->Signature != IMAGE_NT_SIGNATURE) return 0;
DWORD exportRVA = pNT->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
.VirtualAddress;
if (!exportRVA) return 0;
auto* pSec = IMAGE_FIRST_SECTION(pNT);
WORD nSec = pNT->FileHeader.NumberOfSections;
auto rvaToOffset = [&](DWORD rva) -> DWORD
{
for (WORD i = 0; i < nSec; i++)
{
DWORD start = pSec[i].VirtualAddress;
DWORD end = start + pSec[i].SizeOfRawData;
if (rva >= start && rva < end)
return pSec[i].PointerToRawData + (rva - start);
}
return 0;
};
DWORD exportOff = rvaToOffset(exportRVA);
if (!exportOff) return 0;
auto* pExport = reinterpret_cast<const IMAGE_EXPORT_DIRECTORY*>(
pFileBase + exportOff);
auto* pNames = reinterpret_cast<const DWORD*>(
pFileBase + rvaToOffset(pExport->AddressOfNames));
auto* pOrdinals = reinterpret_cast<const WORD*>(
pFileBase + rvaToOffset(pExport->AddressOfNameOrdinals));
auto* pFunctions = reinterpret_cast<const DWORD*>(
pFileBase + rvaToOffset(pExport->AddressOfFunctions));
if (!pNames || !pOrdinals || !pFunctions) return 0;
for (DWORD i = 0; i < pExport->NumberOfNames; i++)
{
DWORD nameOff = rvaToOffset(pNames[i]);
if (!nameOff) continue;
auto name = reinterpret_cast<const char*>(pFileBase + nameOff);
if (strcmp(name, pszName) == 0)
return pFunctions[pOrdinals[i]];
}
return 0;
}
static bool Inject_CreateRemoteThread(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
const SIZE_T pathBytes = (wcslen(dllPath) + 1) * sizeof(wchar_t);
HANDLE hProc = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,
FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit process. This injector "
L"cannot inject into 32-bit targets.";
return false;
}
LPVOID pRemote = VirtualAllocEx(hProc, nullptr, pathBytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!pRemote)
{
CloseHandle(hProc);
outMsg = L"VirtualAllocEx failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (!WriteProcessMemory(hProc, pRemote, dllPath, pathBytes, nullptr))
{
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"WriteProcessMemory failed. Error: " + std::to_wstring(GetLastError());
return false;
}
FARPROC pLoadLib = GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW");
HANDLE hThread = CreateRemoteThread(
hProc, nullptr, 0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(pLoadLib),
pRemote, 0, nullptr);
if (!hThread)
{
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"CreateRemoteThread failed. Error: " + std::to_wstring(GetLastError());
return false;
}
WaitForSingleObject(hThread, 8000);
DWORD dwExitCode = 0;
GetExitCodeThread(hThread, &dwExitCode);
CloseHandle(hThread);
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
if (dwExitCode == 0)
{
outMsg = L"Remote thread returned NULL — LoadLibraryW likely failed "
L"(DLL not found or access denied in target).";
return false;
}
outMsg = L"[CreateRemoteThread] Injection succeeded. "
L"HMODULE in target: 0x" + std::to_wstring(dwExitCode);
return true;
}
static bool Inject_NativeThread(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
const SIZE_T pathBytes = (wcslen(dllPath) + 1) * sizeof(wchar_t);
HANDLE hProc = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
PROCESS_QUERY_INFORMATION,
FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit (WOW64) process. Unsupported.";
return false;
}
LPVOID pRemote = VirtualAllocEx(hProc, nullptr, pathBytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!pRemote || !WriteProcessMemory(hProc, pRemote, dllPath, pathBytes, nullptr))
{
if (pRemote) VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"Memory allocation/write failed. Error: " + std::to_wstring(GetLastError());
return false;
}
FARPROC pLoadLib = GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW");
HANDLE hThread = nullptr;
NTSTATUS status = 0;
bool usedNtCreate = false;
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
auto pNtCreateThreadEx = reinterpret_cast<pfnNtCreateThreadEx>(
GetProcAddress(hNtdll, "NtCreateThreadEx"));
if (pNtCreateThreadEx)
{
status = pNtCreateThreadEx(
&hThread, THREAD_ALL_ACCESS, nullptr, hProc,
reinterpret_cast<PVOID>(pLoadLib), pRemote,
FALSE, 0, 0, 0, nullptr);
usedNtCreate = true;
}
if (!usedNtCreate || !NT_SUCCESS(status) || !hThread)
{
auto pRtlCreateUserThread = reinterpret_cast<pfnRtlCreateUserThread>(
GetProcAddress(hNtdll, "RtlCreateUserThread"));
if (!pRtlCreateUserThread)
{
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"Neither NtCreateThreadEx nor RtlCreateUserThread resolved.";
return false;
}
status = pRtlCreateUserThread(
hProc, nullptr, FALSE, 0, nullptr, nullptr,
reinterpret_cast<PVOID>(pLoadLib), pRemote, &hThread, nullptr);
usedNtCreate = false;
}
if (!NT_SUCCESS(status) || !hThread)
{
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"Thread creation failed. NTSTATUS: 0x" +
std::to_wstring(static_cast<ULONG>(status));
return false;
}
WaitForSingleObject(hThread, 8000);
DWORD dwExitCode = 0;
GetExitCodeThread(hThread, &dwExitCode);
CloseHandle(hThread);
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
const wchar_t* apiName = usedNtCreate
? L"NtCreateThreadEx"
: L"RtlCreateUserThread";
if (dwExitCode == 0)
{
outMsg = std::wstring(L"[") + apiName + L"] Remote thread returned NULL "
L"— LoadLibraryW likely failed.";
return false;
}
outMsg = std::wstring(L"[") + apiName +
L"] Injection succeeded. HMODULE: 0x" + std::to_wstring(dwExitCode);
return true;
}
static bool Inject_ThreadHijack(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
HANDLE hProc = OpenProcess(
PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ |
PROCESS_QUERY_INFORMATION,
FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit (WOW64) process. Unsupported.";
return false;
}
DWORD dwTID = FindFirstThreadOfProcess(dwPID);
if (!dwTID)
{
CloseHandle(hProc);
outMsg = L"No threads found in target process.";
return false;
}
HANDLE hThread = OpenThread(
THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_SET_CONTEXT,
FALSE, dwTID);
if (!hThread)
{
CloseHandle(hProc);
outMsg = L"OpenThread failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (SuspendThread(hThread) == static_cast<DWORD>(-1))
{
CloseHandle(hThread);
CloseHandle(hProc);
outMsg = L"SuspendThread failed. Error: " + std::to_wstring(GetLastError());
return false;
}
CONTEXT ctx = {};
ctx.ContextFlags = CONTEXT_FULL;
if (!GetThreadContext(hThread, &ctx))
{
ResumeThread(hThread);
CloseHandle(hThread);
CloseHandle(hProc);
outMsg = L"GetThreadContext failed. Error: " + std::to_wstring(GetLastError());
return false;
}
const SIZE_T pathBytes = (wcslen(dllPath) + 1) * sizeof(wchar_t);
const SIZE_T totalSize = pathBytes + 128;
LPVOID pBase = VirtualAllocEx(hProc, nullptr, totalSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pBase)
{
ResumeThread(hThread);
CloseHandle(hThread);
CloseHandle(hProc);
outMsg = L"VirtualAllocEx failed. Error: " + std::to_wstring(GetLastError());
return false;
}
ULONG_PTR pRemotePath = reinterpret_cast<ULONG_PTR>(pBase);
ULONG_PTR pRemoteShell = pRemotePath + pathBytes;
ULONG_PTR pLoadLib = reinterpret_cast<ULONG_PTR>(
GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW"));
ULONG_PTR originalRIP = ctx.Rip;
BYTE shell[64] = {};
int off = 0;
shell[off++] = 0x48;
shell[off++] = 0x83;
shell[off++] = 0xEC;
shell[off++] = 0x28;
shell[off++] = 0x48;
shell[off++] = 0xB9;
memcpy(&shell[off], &pRemotePath, 8);
off += 8;
shell[off++] = 0x48;
shell[off++] = 0xB8;
memcpy(&shell[off], &pLoadLib, 8);
off += 8;
shell[off++] = 0xFF;
shell[off++] = 0xD0;
shell[off++] = 0x48;
shell[off++] = 0x83;
shell[off++] = 0xC4;
shell[off++] = 0x28;
shell[off++] = 0x48;
shell[off++] = 0xB8;
memcpy(&shell[off], &originalRIP, 8);
off += 8;
shell[off++] = 0xFF;
shell[off++] = 0xE0;
WriteProcessMemory(hProc, reinterpret_cast<LPVOID>(pRemotePath),
dllPath, pathBytes, nullptr);
WriteProcessMemory(hProc, reinterpret_cast<LPVOID>(pRemoteShell),
shell, sizeof(shell), nullptr);
ctx.Rip = pRemoteShell;
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
Sleep(2000);
VirtualFreeEx(hProc, pBase, 0, MEM_RELEASE);
CloseHandle(hThread);
CloseHandle(hProc);
outMsg = L"[Thread Context Hijacking] RIP redirected to shellcode in target "
L"thread (TID " + std::to_wstring(dwTID) + L"). "
L"DLL should load within ~2 seconds. "
L"Note: target may crash if thread was inside a system call.";
return true;
}
static bool Inject_APC(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
const SIZE_T pathBytes = (wcslen(dllPath) + 1) * sizeof(wchar_t);
HANDLE hProc = OpenProcess(
PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION,
FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit (WOW64) process. Unsupported.";
return false;
}
LPVOID pRemote = VirtualAllocEx(hProc, nullptr, pathBytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!pRemote || !WriteProcessMemory(hProc, pRemote, dllPath, pathBytes, nullptr))
{
if (pRemote) VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"Memory allocation/write failed. Error: " + std::to_wstring(GetLastError());
return false;
}
FARPROC pLoadLib = GetProcAddress(GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW");
auto tids = GetAllThreadsOfProcess(dwPID);
if (tids.empty())
{
VirtualFreeEx(hProc, pRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"No threads found in target process.";
return false;
}
int queued = 0;
for (DWORD tid : tids)
{
HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, tid);
if (!hThread) continue;
if (QueueUserAPC(reinterpret_cast<PAPCFUNC>(pLoadLib),
hThread,
reinterpret_cast<ULONG_PTR>(pRemote)))
queued++;
CloseHandle(hThread);
}
CloseHandle(hProc);
if (queued == 0)
{
outMsg = L"QueueUserAPC failed on all " + std::to_wstring(tids.size()) +
L" threads. Error: " + std::to_wstring(GetLastError());
return false;
}
outMsg = L"[APC Injection] APC queued on " + std::to_wstring(queued) +
L" of " + std::to_wstring(tids.size()) + L" threads. "
L"DLL will load when any thread next enters an alertable wait "
L"(e.g. SleepEx, WaitForSingleObjectEx with bAlertable=TRUE).";
return true;
}
static bool Inject_WindowHook(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
HMODULE hMod = LoadLibraryExW(dllPath, nullptr, DONT_RESOLVE_DLL_REFERENCES);
if (!hMod)
{
outMsg = L"LoadLibraryEx failed on target DLL. Error: " +
std::to_wstring(GetLastError());
return false;
}
auto pGetMsgProc = reinterpret_cast<HOOKPROC>(
GetProcAddress(hMod, "GetMsgProc"));
if (!pGetMsgProc)
{
FreeLibrary(hMod);
outMsg = L"[Window Hook] The selected DLL does not export \"GetMsgProc\". "
L"This method requires the target DLL to export a function named "
L"GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam).";
return false;
}
struct FindCtx
{
DWORD pid;
DWORD tid;
};
FindCtx ctx = {dwPID, 0};
EnumWindows([](HWND hwnd, LPARAM lp) -> BOOL
{
auto* c = reinterpret_cast<FindCtx*>(lp);
DWORD pid = 0;
DWORD tid = GetWindowThreadProcessId(hwnd, &pid);
if (pid == c->pid && IsWindowVisible(hwnd))
{
c->tid = tid;
return FALSE;
}
return TRUE;
}, reinterpret_cast<LPARAM>(&ctx));
if (!ctx.tid)
{
FreeLibrary(hMod);
outMsg = L"[Window Hook] No visible window found in target process. "
L"This method requires the target to have a GUI message loop.";
return false;
}
HHOOK hHook = SetWindowsHookExW(WH_GETMESSAGE, pGetMsgProc, hMod, ctx.tid);
if (!hHook)
{
FreeLibrary(hMod);
outMsg = L"SetWindowsHookEx failed. Error: " + std::to_wstring(GetLastError());
return false;
}
PostThreadMessageW(ctx.tid, WM_NULL, 0, 0);
Sleep(1000);
UnhookWindowsHookEx(hHook);
FreeLibrary(hMod);
outMsg = L"[Window Hook] Hook installed on thread " +
std::to_wstring(ctx.tid) + L" and triggered via WM_NULL. "
L"DLL should now be mapped into target. "
L"NOTE: DLL must export GetMsgProc(int, WPARAM, LPARAM).";
return true;
}
static bool Inject_ManualMap(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
HANDLE hFile = CreateFileW(dllPath, GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, 0, nullptr);
if (hFile == INVALID_HANDLE_VALUE)
{
outMsg = L"Cannot open DLL file. Error: " + std::to_wstring(GetLastError());
return false;
}
DWORD fileSize = GetFileSize(hFile, nullptr);
std::vector<BYTE> fileBuffer(fileSize);
DWORD bytesRead = 0;
ReadFile(hFile, fileBuffer.data(), fileSize, &bytesRead, nullptr);
CloseHandle(hFile);
if (bytesRead != fileSize)
{
outMsg = L"Failed to read DLL file completely.";
return false;
}
auto* pDOS = reinterpret_cast<IMAGE_DOS_HEADER*>(fileBuffer.data());
if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
{
outMsg = L"Not a valid PE file (bad DOS signature).";
return false;
}
auto* pNT = reinterpret_cast<IMAGE_NT_HEADERS*>(
fileBuffer.data() + pDOS->e_lfanew);
if (pNT->Signature != IMAGE_NT_SIGNATURE)
{
outMsg = L"Not a valid PE file (bad NT signature).";
return false;
}
if (pNT->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
{
outMsg = L"[Manual Map] DLL is not x64. This injector only supports x64 DLLs.";
return false;
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit (WOW64) process. Unsupported.";
return false;
}
SIZE_T imageSize = pNT->OptionalHeader.SizeOfImage;
LPVOID pRemoteBase = VirtualAllocEx(
hProc,
reinterpret_cast<LPVOID>(pNT->OptionalHeader.ImageBase),
imageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!pRemoteBase)
pRemoteBase = VirtualAllocEx(hProc, nullptr, imageSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pRemoteBase)
{
CloseHandle(hProc);
outMsg = L"VirtualAllocEx (image) failed. Error: " + std::to_wstring(GetLastError());
return false;
}
WriteProcessMemory(hProc, pRemoteBase, fileBuffer.data(),
pNT->OptionalHeader.SizeOfHeaders, nullptr);
auto* pSec = IMAGE_FIRST_SECTION(pNT);
for (WORD i = 0; i < pNT->FileHeader.NumberOfSections; i++)
{
if (pSec[i].SizeOfRawData == 0) continue;
auto dest = reinterpret_cast<LPVOID>(
reinterpret_cast<ULONG_PTR>(pRemoteBase) + pSec[i].VirtualAddress);
WriteProcessMemory(hProc, dest,
fileBuffer.data() + pSec[i].PointerToRawData,
pSec[i].SizeOfRawData, nullptr);
}
ULONG_PTR delta = reinterpret_cast<ULONG_PTR>(pRemoteBase) -
pNT->OptionalHeader.ImageBase;
if (delta != 0)
{
DWORD relocRVA = pNT->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]
.VirtualAddress;
DWORD relocSize = pNT->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]
.Size;
ULONG_PTR relocBase =
reinterpret_cast<ULONG_PTR>(fileBuffer.data()) + relocRVA;
ULONG_PTR relocEnd = relocBase + relocSize;
while (relocBase < relocEnd)
{
auto* block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(relocBase);
if (!block->SizeOfBlock) break;
DWORD count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) /
sizeof(WORD);
auto* entries = reinterpret_cast<WORD*>(block + 1);
for (DWORD j = 0; j < count; j++)
{
if ((entries[j] >> 12) == IMAGE_REL_BASED_DIR64)
{
ULONG_PTR patchVA =
reinterpret_cast<ULONG_PTR>(pRemoteBase) +
block->VirtualAddress + (entries[j] & 0x0FFF);
ULONG_PTR orig = 0;
ReadProcessMemory(hProc,
reinterpret_cast<LPVOID>(patchVA),
&orig, sizeof(orig), nullptr);
orig += delta;
WriteProcessMemory(hProc,
reinterpret_cast<LPVOID>(patchVA),
&orig, sizeof(orig), nullptr);
}
}
relocBase += block->SizeOfBlock;
}
}
DWORD importRVA = pNT->OptionalHeader
.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
.VirtualAddress;
if (importRVA)
{
auto* pImport = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(
fileBuffer.data() + importRVA);
for (; pImport->Name; pImport++)
{
auto libName = reinterpret_cast<char*>(
fileBuffer.data() + pImport->Name);
HMODULE hImport = LoadLibraryA(libName);
if (!hImport) continue;
auto* pThunk = reinterpret_cast<IMAGE_THUNK_DATA*>(
fileBuffer.data() + (pImport->OriginalFirstThunk
? pImport->OriginalFirstThunk
: pImport->FirstThunk));
ULONG_PTR iatVA =
reinterpret_cast<ULONG_PTR>(pRemoteBase) + pImport->FirstThunk;
while (pThunk->u1.AddressOfData)
{
FARPROC pFunc = nullptr;
if (IMAGE_SNAP_BY_ORDINAL(pThunk->u1.Ordinal))
{
pFunc = GetProcAddress(
hImport, MAKEINTRESOURCEA(
IMAGE_ORDINAL(pThunk->u1.Ordinal)));
}
else
{
auto* pImportByName =
reinterpret_cast<IMAGE_IMPORT_BY_NAME*>(
fileBuffer.data() + pThunk->u1.AddressOfData);
pFunc = GetProcAddress(hImport, pImportByName->Name);
}
WriteProcessMemory(hProc, reinterpret_cast<LPVOID>(iatVA),
&pFunc, sizeof(pFunc), nullptr);
pThunk++;
iatVA += sizeof(ULONG_PTR);
}
}
}
ULONG_PTR dllMainVA = reinterpret_cast<ULONG_PTR>(pRemoteBase) +
pNT->OptionalHeader.AddressOfEntryPoint;
ULONG_PTR hModuleVA = reinterpret_cast<ULONG_PTR>(pRemoteBase);
constexpr ULONG_PTR reasonAttach = DLL_PROCESS_ATTACH;
BYTE entryShell[64] = {};
int off = 0;
entryShell[off++] = 0x48;
entryShell[off++] = 0x83;
entryShell[off++] = 0xEC;
entryShell[off++] = 0x28;
entryShell[off++] = 0x48;
entryShell[off++] = 0xB9;
memcpy(&entryShell[off], &hModuleVA, 8);
off += 8;
entryShell[off++] = 0x48;
entryShell[off++] = 0xBA;
memcpy(&entryShell[off], &reasonAttach, 8);
off += 8;
entryShell[off++] = 0x4D;
entryShell[off++] = 0x31;
entryShell[off++] = 0xC0;
entryShell[off++] = 0x48;
entryShell[off++] = 0xB8;
memcpy(&entryShell[off], &dllMainVA, 8);
off += 8;
entryShell[off++] = 0xFF;
entryShell[off++] = 0xD0;
entryShell[off++] = 0x48;
entryShell[off++] = 0x83;
entryShell[off++] = 0xC4;
entryShell[off++] = 0x28;
entryShell[off++] = 0xC3;
LPVOID pShellRemote = VirtualAllocEx(hProc, nullptr, sizeof(entryShell),
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pShellRemote)
{
VirtualFreeEx(hProc, pRemoteBase, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"VirtualAllocEx (shellcode) failed. Error: " + std::to_wstring(GetLastError());
return false;
}
WriteProcessMemory(hProc, pShellRemote, entryShell, sizeof(entryShell), nullptr);
HANDLE hThread = CreateRemoteThread(
hProc, nullptr, 0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(pShellRemote),
nullptr, 0, nullptr);
if (!hThread)
{
VirtualFreeEx(hProc, pShellRemote, 0, MEM_RELEASE);
VirtualFreeEx(hProc, pRemoteBase, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"CreateRemoteThread (DllMain) failed. Error: " + std::to_wstring(GetLastError());
return false;
}
WaitForSingleObject(hThread, 8000);
CloseHandle(hThread);
VirtualFreeEx(hProc, pShellRemote, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"[Manual Mapping] DLL mapped at remote base 0x" +
std::to_wstring(reinterpret_cast<ULONG_PTR>(pRemoteBase)) +
L". Module will NOT appear in target's loaded module list. "
L"Note: TLS callbacks and C++ exception tables are not processed.";
return true;
}
static bool Inject_Reflective(DWORD dwPID, const wchar_t* dllPath,
std::wstring& outMsg)
{
HANDLE hFile = CreateFileW(dllPath, GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, 0, nullptr);
if (hFile == INVALID_HANDLE_VALUE)
{
outMsg = L"Cannot open DLL file. Error: " + std::to_wstring(GetLastError());
return false;
}
DWORD fileSize = GetFileSize(hFile, nullptr);
std::vector<BYTE> fileBuffer(fileSize);
DWORD bytesRead = 0;
ReadFile(hFile, fileBuffer.data(), fileSize, &bytesRead, nullptr);
CloseHandle(hFile);
DWORD loaderRVA = FindExportRVA(fileBuffer.data(), fileSize,
"ReflectiveLoader");
if (!loaderRVA)
{
outMsg = L"[Reflective] Export \"ReflectiveLoader\" not found in DLL. "
L"The DLL must be compiled with a reflective loader "
L"(e.g. using Stephen Fewer's ReflectiveDLLInjection framework).";
return false;
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
if (!hProc)
{
outMsg = L"OpenProcess failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (IsProcessWow64(hProc))
{
CloseHandle(hProc);
outMsg = L"Target is a 32-bit (WOW64) process. Unsupported.";
return false;
}
LPVOID pRemoteBase = VirtualAllocEx(hProc, nullptr, fileSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pRemoteBase)
{
CloseHandle(hProc);
outMsg = L"VirtualAllocEx failed. Error: " + std::to_wstring(GetLastError());
return false;
}
if (!WriteProcessMemory(hProc, pRemoteBase, fileBuffer.data(), fileSize, nullptr))
{
VirtualFreeEx(hProc, pRemoteBase, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"WriteProcessMemory failed. Error: " + std::to_wstring(GetLastError());
return false;
}
ULONG_PTR pRemoteLoader =
reinterpret_cast<ULONG_PTR>(pRemoteBase) + loaderRVA;
HANDLE hThread = CreateRemoteThread(
hProc, nullptr, 0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(pRemoteLoader),
pRemoteBase, 0, nullptr);
if (!hThread)
{
VirtualFreeEx(hProc, pRemoteBase, 0, MEM_RELEASE);
CloseHandle(hProc);
outMsg = L"CreateRemoteThread (ReflectiveLoader) failed. Error: " +
std::to_wstring(GetLastError());
return false;
}
WaitForSingleObject(hThread, 8000);
CloseHandle(hThread);