-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjector.cpp
More file actions
484 lines (413 loc) · 16 KB
/
Copy pathinjector.cpp
File metadata and controls
484 lines (413 loc) · 16 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
#include "injector.h"
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <tlhelp32.h>
#include <vector>
#include <windows.h>
#include "BlackBone/Asm/AsmFactory.h"
#include "BlackBone/Config.h"
#include "BlackBone/DriverControl/DriverControl.h"
#include <BlackBone/ManualMap/MMap.h>
#include <BlackBone/Misc/Utils.h>
#include <BlackBone/Patterns/PatternSearch.h>
#include <BlackBone/Process/Process.h>
#include <BlackBone/Process/ProcessModules.h>
#include <BlackBone/Process/RPC/RemoteFunction.hpp>
#include <BlackBone/Syscalls/Syscall.h>
#pragma comment(lib, "BlackBone.lib")
static std::wstring convertStringToWideString(const std::string &sourceString)
{
if (sourceString.empty())
{
return std::wstring();
}
int requiredSize = MultiByteToWideChar(CP_UTF8, 0, &sourceString[0], static_cast<int>(sourceString.size()), NULL, 0);
std::wstring wideStringDestination(requiredSize, 0);
MultiByteToWideChar(CP_UTF8, 0, &sourceString[0], static_cast<int>(sourceString.size()), &wideStringDestination[0], requiredSize);
return wideStringDestination;
}
static std::string convertWideStringToString(const std::wstring &sourceWideString)
{
if (sourceWideString.empty())
{
return std::string();
}
int requiredSize = WideCharToMultiByte(CP_UTF8, 0, &sourceWideString[0], static_cast<int>(sourceWideString.size()), NULL, 0, NULL, NULL);
std::string stringDestination(requiredSize, 0);
WideCharToMultiByte(CP_UTF8, 0, &sourceWideString[0], static_cast<int>(sourceWideString.size()), &stringDestination[0], requiredSize, NULL, NULL);
return stringDestination;
}
static bool enableDebugPrivilege()
{
HANDLE tokenHandle = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tokenHandle))
{
return false;
}
LUID luidValue = {0};
if (!LookupPrivilegeValueA(NULL, "SeDebugPrivilege", &luidValue))
{
CloseHandle(tokenHandle);
return false;
}
TOKEN_PRIVILEGES tokenPrivileges = {0};
tokenPrivileges.PrivilegeCount = 1;
tokenPrivileges.Privileges[0].Luid = luidValue;
tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bool adjustmentSuccess = AdjustTokenPrivileges(tokenHandle, FALSE, &tokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
CloseHandle(tokenHandle);
return adjustmentSuccess;
}
static NTSTATUS attachToTargetProcess(blackbone::Process &targetProcess, DWORD targetProcessIdentifier)
{
enableDebugPrivilege();
NTSTATUS status = targetProcess.Attach(targetProcessIdentifier);
if (!NT_SUCCESS(status))
{
status = targetProcess.Attach(targetProcessIdentifier, PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ);
}
return status;
}
static bool isWindowsTestModeEnabled()
{
HMODULE ntdllModuleHandle = GetModuleHandleA("ntdll.dll");
if (!ntdllModuleHandle)
{
return false;
}
using NtQuerySystemInformationFunction = NTSTATUS(WINAPI *)(ULONG, PVOID, ULONG, PULONG);
auto ntQuerySystemInformationPointer = reinterpret_cast<NtQuerySystemInformationFunction>(GetProcAddress(ntdllModuleHandle, "NtQuerySystemInformation"));
if (!ntQuerySystemInformationPointer)
{
return false;
}
struct SystemCodeIntegrityInformationStructure
{
ULONG Length;
ULONG CodeIntegrityOptions;
} systemCodeIntegrityInformation = {0};
systemCodeIntegrityInformation.Length = sizeof(systemCodeIntegrityInformation);
ULONG returnedLength = 0;
NTSTATUS queryStatus = ntQuerySystemInformationPointer(103, &systemCodeIntegrityInformation, sizeof(systemCodeIntegrityInformation), &returnedLength);
if (queryStatus >= 0)
{
return (systemCodeIntegrityInformation.CodeIntegrityOptions & 0x0002) != 0;
}
return false;
}
namespace injector
{
static std::string loadDriver()
{
if (!isWindowsTestModeEnabled())
{
return "driver load failed windows test mode must be enabled to use kernel methods";
}
NTSTATUS status = blackbone::Driver().EnsureLoaded();
if (NT_SUCCESS(status))
{
return "";
}
if (status == 0xC0000034)
{
return "driver load failed sys file not found make sure its next to the exe";
}
if (status == 0xC0000022)
{
return "driver load failed access denied please run the injector as an administrator";
}
return "driver load failed with unknown error code " + std::to_string(status);
}
std::string professionalManualMap(DWORD targetProcessIdentifier, const std::string &dllPath)
{
blackbone::Process targetProcess;
NTSTATUS attachmentStatus = attachToTargetProcess(targetProcess, targetProcessIdentifier);
if (!NT_SUCCESS(attachmentStatus))
{
return "failed to attach to process id " + std::to_string(targetProcessIdentifier);
}
blackbone::eLoadFlags mappingFlags = static_cast<blackbone::eLoadFlags>(blackbone::ManualImports | blackbone::CreateLdrRef | blackbone::WipeHeader);
auto mappingResult = targetProcess.mmap().MapImage(convertStringToWideString(dllPath), mappingFlags);
if (!NT_SUCCESS(mappingResult.status))
{
return "manual mapping failed status " + std::to_string(mappingResult.status);
}
return "manual mapping successful";
}
std::string standardInjection(DWORD targetProcessIdentifier, const std::string &dllPath)
{
blackbone::Process targetProcess;
if (NT_SUCCESS(attachToTargetProcess(targetProcess, targetProcessIdentifier)))
{
auto injectionResult = targetProcess.modules().Inject(convertStringToWideString(dllPath));
if (NT_SUCCESS(injectionResult.status))
{
return "standard injection successful";
}
}
HANDLE processHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, targetProcessIdentifier);
if (!processHandle)
{
processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetProcessIdentifier);
}
if (!processHandle)
{
return "failed to open process id " + std::to_string(targetProcessIdentifier) + " with error code " + std::to_string(GetLastError());
}
std::wstring wideDllPath = convertStringToWideString(dllPath);
size_t allocationSize = (wideDllPath.length() + 1) * sizeof(wchar_t);
LPVOID remoteMemoryAddress = VirtualAllocEx(processHandle, NULL, allocationSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!remoteMemoryAddress)
{
CloseHandle(processHandle);
return "failed to allocate memory in process id " + std::to_string(targetProcessIdentifier);
}
SIZE_T bytesWritten = 0;
if (!WriteProcessMemory(processHandle, remoteMemoryAddress, wideDllPath.c_str(), allocationSize, &bytesWritten))
{
VirtualFreeEx(processHandle, remoteMemoryAddress, 0, MEM_RELEASE);
CloseHandle(processHandle);
return "failed to write memory in process id " + std::to_string(targetProcessIdentifier);
}
HMODULE kernel32Module = GetModuleHandleA("kernel32.dll");
FARPROC loadLibraryAddress = GetProcAddress(kernel32Module, "LoadLibraryW");
if (!loadLibraryAddress)
{
VirtualFreeEx(processHandle, remoteMemoryAddress, 0, MEM_RELEASE);
CloseHandle(processHandle);
return "failed to locate LoadLibraryW address";
}
HANDLE threadHandle = CreateRemoteThread(processHandle, NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(loadLibraryAddress), remoteMemoryAddress, 0, NULL);
if (!threadHandle)
{
VirtualFreeEx(processHandle, remoteMemoryAddress, 0, MEM_RELEASE);
CloseHandle(processHandle);
return "failed to create remote thread in process id " + std::to_string(targetProcessIdentifier);
}
WaitForSingleObject(threadHandle, 5000);
CloseHandle(threadHandle);
CloseHandle(processHandle);
return "standard injection successful";
}
std::string pureILInjection(DWORD targetProcessIdentifier, const std::string &netVersion, const std::string &dllPath,
const std::string &methodName, const std::string &arguments)
{
blackbone::Process targetProcess;
if (!NT_SUCCESS(attachToTargetProcess(targetProcess, targetProcessIdentifier)))
{
return "failed to attach to process id " + std::to_string(targetProcessIdentifier);
}
DWORD injectionReturnCode = 0;
bool executionSuccess = targetProcess.modules().InjectPureIL(
convertStringToWideString(netVersion),
convertStringToWideString(dllPath),
convertStringToWideString(methodName),
convertStringToWideString(arguments),
injectionReturnCode
);
if (!executionSuccess)
{
return "pure il injection failed";
}
return "pure il injection successful return code " + std::to_string(injectionReturnCode);
}
std::string kernelStandardInjection(DWORD targetProcessIdentifier, const std::string &dllPath)
{
std::string driverErrorMessage = loadDriver();
if (!driverErrorMessage.empty())
{
return driverErrorMessage;
}
NTSTATUS driverInjectionStatus = blackbone::Driver().InjectDll(
targetProcessIdentifier,
convertStringToWideString(dllPath),
IT_Thread,
0,
L"",
false,
false,
true
);
if (!NT_SUCCESS(driverInjectionStatus))
{
return "kernel injection failed status " + std::to_string(driverInjectionStatus);
}
return "kernel injection successful";
}
std::string kernelManualMap(DWORD targetProcessIdentifier, const std::string &dllPath)
{
std::string driverErrorMessage = loadDriver();
if (!driverErrorMessage.empty())
{
return driverErrorMessage;
}
KMmapFlags kernelMappingFlags = static_cast<KMmapFlags>(KManualImports | KWipeHeader | KHideVAD);
NTSTATUS kernelMappingStatus = blackbone::Driver().MmapDll(
targetProcessIdentifier,
convertStringToWideString(dllPath),
kernelMappingFlags
);
if (!NT_SUCCESS(kernelMappingStatus))
{
return "kernel manual mapping failed status " + std::to_string(kernelMappingStatus);
}
return "kernel manual mapping successful";
}
std::vector<procInfo> getProcs()
{
std::vector<procInfo> processList;
auto enumerationResult = blackbone::Process::EnumByNameOrPID(0, L"");
if (enumerationResult)
{
for (const auto &processEntry : enumerationResult.result())
{
procInfo information;
information.pid = processEntry.pid;
information.name = convertWideStringToString(processEntry.imageName);
blackbone::Process temporaryProcess;
if (NT_SUCCESS(temporaryProcess.Attach(processEntry.pid, PROCESS_QUERY_LIMITED_INFORMATION)))
{
information.arch = temporaryProcess.core().isWow64() ? "x86" : "x64";
temporaryProcess.Detach();
}
else
{
information.arch = "n/a";
}
processList.push_back(information);
}
}
return processList;
}
std::string injectApc(DWORD targetProcessIdentifier, const std::string &dllPath)
{
blackbone::Process targetProcess;
if (!NT_SUCCESS(targetProcess.Attach(targetProcessIdentifier)))
{
return "failed to attach to process id " + std::to_string(targetProcessIdentifier);
}
std::wstring wideDllPath = convertStringToWideString(dllPath);
auto exportData = targetProcess.modules().GetExport(L"kernel32.dll", "LoadLibraryW");
if (!NT_SUCCESS(exportData.status))
{
return "failed to find LoadLibraryW export in kernel32";
}
size_t requiredPathSizeBytes = (wideDllPath.length() + 1) * sizeof(wchar_t);
auto allocatedMemory = targetProcess.memory().Allocate(requiredPathSizeBytes, PAGE_READWRITE, 0, false);
if (!NT_SUCCESS(allocatedMemory.status))
{
return "memory allocation failed in target process";
}
allocatedMemory->Write(0, requiredPathSizeBytes, wideDllPath.c_str());
auto processThreads = targetProcess.threads().getAll();
if (processThreads.empty())
{
return "process has no active threads";
}
int queuedApcCount = 0;
for (auto &individualThread : processThreads)
{
if (individualThread->Suspended())
{
continue;
}
NTSTATUS queueStatus = targetProcess.core().native()->QueueApcT(
individualThread->handle(),
exportData->procAddress,
allocatedMemory->ptr()
);
if (NT_SUCCESS(queueStatus))
{
queuedApcCount++;
}
}
if (queuedApcCount == 0)
{
return "failed to queue apc no suitable active threads found";
}
bool successfullyLoadedModule = false;
for (int retryAttempt = 0; retryAttempt < 20; retryAttempt++)
{
Sleep(50);
if (targetProcess.modules().GetModule(wideDllPath) != nullptr)
{
successfullyLoadedModule = true;
break;
}
}
if (!successfullyLoadedModule)
{
return "apc queued but module did not load within timeout alertable state required";
}
return "apc injection successful";
}
std::string injectThreadHijack(DWORD targetProcessIdentifier, const std::string &dllPath)
{
blackbone::Process targetProcess;
if (!NT_SUCCESS(targetProcess.Attach(targetProcessIdentifier)))
{
return "failed to attach to process id " + std::to_string(targetProcessIdentifier);
}
std::wstring wideDllPath = convertStringToWideString(dllPath);
blackbone::ThreadPtr targetThreadPointer = targetProcess.threads().getMain();
if (!targetThreadPointer || targetThreadPointer->Suspended())
{
auto allThreads = targetProcess.threads().getAll();
for (auto &individualThread : allThreads)
{
if (!individualThread->Suspended())
{
targetThreadPointer = individualThread;
break;
}
}
}
if (!targetThreadPointer)
{
return "failed to locate a suitable thread to hijack";
}
try
{
auto hijackResult = targetProcess.modules().Inject(wideDllPath, targetThreadPointer);
if (!NT_SUCCESS(hijackResult.status))
{
return "hijack injection failed status " + std::to_string(hijackResult.status);
}
}
catch (const std::exception &caughtException)
{
return std::string("injector exception occurred ") + caughtException.what();
}
catch (...)
{
return "injector caught unknown memory exception";
}
return "thread hijack injection successful";
}
std::string injectBlackBone(DWORD targetProcessIdentifier, const std::string &dllPath, bool erasePeHeaders, bool hideModuleMemory)
{
blackbone::Process targetProcess;
if (!NT_SUCCESS(targetProcess.Attach(targetProcessIdentifier)))
{
return "blackbone failed to attach to process id " + std::to_string(targetProcessIdentifier);
}
blackbone::eLoadFlags mappingFlags = blackbone::NoFlags;
if (!hideModuleMemory)
{
mappingFlags |= blackbone::CreateLdrRef;
}
if (erasePeHeaders)
{
mappingFlags |= blackbone::WipeHeader;
}
auto mappingResult = targetProcess.mmap().MapImage(convertStringToWideString(dllPath), mappingFlags);
targetProcess.Detach();
if (!mappingResult)
{
return "blackbone injection failed status " + std::to_string(mappingResult.status);
}
return "blackbone injection successful";
}
}