forked from DarthTon/Xenos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInjectionCore.cpp
785 lines (670 loc) · 25.3 KB
/
InjectionCore.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
#include "InjectionCore.h"
#include <BlackBone/src/BlackBone/Process/RPC/RemoteFunction.hpp>
#include <iterator>
InjectionCore::InjectionCore( HWND& hMainDlg )
: _hMainDlg( hMainDlg )
{
// Load driver
//blackbone::Driver().EnsureLoaded();
}
InjectionCore::~InjectionCore()
{
//
// If at least one process with allocated physical pages exist, prevent driver unload or process will crash
// Although PID can be reused, I'm too lazy to implement more reliable detection
//
std::vector<DWORD> existing = blackbone::Process::EnumByName( L"" ), mutual;
std::sort( existing.begin(), existing.end() );
std::sort( _criticalProcList.begin(), _criticalProcList.end() );
std::set_intersection( existing.begin(), existing.end(), _criticalProcList.begin(), _criticalProcList.end(), std::back_inserter( mutual ) );
if (mutual.empty())
blackbone::Driver().Unload();
}
/// <summary>
/// Get injection target
/// </summary>
/// <param name="context">Injection context.</param>
/// <param name="pi">Process info in case of new process</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::GetTargetProcess( InjectContext& context, PROCESS_INFORMATION& pi )
{
NTSTATUS status = ERROR_SUCCESS;
// No process required for driver mapping
if (context.cfg.injectMode == Kernel_DriverMap)
return status;
// Await new process
if (context.cfg.processMode == ManualLaunch)
{
xlog::Normal( "Waiting on process %ls", context.procPath.c_str() );
auto procName = blackbone::Utils::StripPath( context.procPath );
if (procName.empty())
{
Message::ShowWarning( _hMainDlg, L"Please select executable to wait for\n" );
return STATUS_NOT_FOUND;
}
// Filter already existing processes
std::vector<blackbone::ProcessInfo> newList;
if (context.procList.empty())
context.procList = blackbone::Process::EnumByNameOrPID( 0, procName ).result( std::vector<blackbone::ProcessInfo>() );
// Wait for process
for (context.waitActive = true;; Sleep( 10 ))
{
// Canceled by user
if (!context.waitActive)
{
xlog::Warning( "Process wait canceled by user" );
return STATUS_REQUEST_ABORTED;
}
if (!context.procDiff.empty())
{
context.procList = newList;
// Skip first N found processes
if (context.skippedCount < context.cfg.skipProc)
{
context.skippedCount++;
context.procDiff.erase( context.procDiff.begin() );
continue;
}
context.pid = context.procDiff.front().pid;
context.procDiff.erase( context.procDiff.begin() );
xlog::Verbose( "Got process %d", context.pid );
break;
}
else
{
// Detect new process
newList = blackbone::Process::EnumByNameOrPID( 0, procName ).result( std::vector<blackbone::ProcessInfo>() );
std::set_difference(
newList.begin(), newList.end(),
context.procList.begin(), context.procList.end(),
std::inserter( context.procDiff, context.procDiff.begin() )
);
}
}
}
// Create new process
else if (context.cfg.processMode == NewProcess)
{
STARTUPINFOW si = { 0 };
si.cb = sizeof( si );
xlog::Normal( "Creating new process '%ls' with arguments '%ls'", context.procPath.c_str(), context.cfg.procCmdLine.c_str() );
if (!CreateProcessW( context.procPath.c_str(), (LPWSTR)context.cfg.procCmdLine.c_str(),
NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, blackbone::Utils::GetParent( context.procPath ).c_str(), &si, &pi ))
{
Message::ShowError( _hMainDlg, L"Failed to create new process.\n" + blackbone::Utils::GetErrorDescription( LastNtStatus() ) );
return LastNtStatus();
}
// Escalate handle access rights through driver
if (context.cfg.krnHandle)
{
xlog::Normal( "Escalating process handle access" );
status = _process.Attach( pi.dwProcessId, PROCESS_QUERY_LIMITED_INFORMATION );
if (NT_SUCCESS( status ))
{
status = blackbone::Driver().PromoteHandle(
GetCurrentProcessId(),
_process.core().handle(),
DEFAULT_ACCESS_P | PROCESS_QUERY_LIMITED_INFORMATION
);
}
}
else
{
// Attach for thread init
status = _process.Attach( pi.dwProcessId );
}
// Create new thread to make sure LdrInitializeProcess gets called
if (NT_SUCCESS( status ))
_process.EnsureInit();
if (!NT_SUCCESS( status ))
{
xlog::Error( "Failed to attach to process, status 0x%X", status );
return status;
}
// No process handle is required for kernel injection
if (context.cfg.injectMode >= Kernel_Thread)
{
context.pid = pi.dwProcessId;
_process.Detach();
// Thread must be running for APC execution
if (context.cfg.injectMode == Kernel_APC)
{
ResumeThread( pi.hThread );
Sleep( 100 );
}
}
// Because the only suitable thread is suspended, thread hijacking can't be used
context.cfg.hijack = false;
}
// Attach to existing process
if (context.cfg.injectMode < Kernel_Thread && context.cfg.processMode != NewProcess)
{
// Escalate handle access rights through driver
if (context.cfg.krnHandle)
{
xlog::Normal( "Escalating process handle access" );
status = _process.Attach( context.pid, PROCESS_QUERY_LIMITED_INFORMATION );
if (NT_SUCCESS( status ))
{
status = blackbone::Driver().PromoteHandle(
GetCurrentProcessId(),
_process.core().handle(),
DEFAULT_ACCESS_P | PROCESS_QUERY_LIMITED_INFORMATION
);
}
if (!NT_SUCCESS( status ))
xlog::Error( "Failed to escalate process handle access, status 0x%X", status );
}
else
status = _process.Attach( context.pid );
if (NT_SUCCESS( status ) && !_process.valid())
status = STATUS_PROCESS_IS_TERMINATING;
if (status != STATUS_SUCCESS)
{
std::wstring errmsg = L"Can not attach to the process.\n" + blackbone::Utils::GetErrorDescription( status );
Message::ShowError( _hMainDlg, errmsg );
return status;
}
//
// Make sure loader is initialized
//
bool ldrInit = false;
if (_process.core().isWow64())
{
blackbone::_PEB32 peb32 = { 0 };
_process.core().peb32( &peb32 );
ldrInit = peb32.Ldr != 0;
}
else
{
blackbone::_PEB64 peb64 = { 0 };
_process.core().peb64( &peb64 );
ldrInit = peb64.Ldr != 0;
}
// Create new thread to make sure LdrInitializeProcess gets called
if (!ldrInit)
_process.EnsureInit();
}
return ERROR_SUCCESS;
}
/// <summary>
/// Validate all parameters
/// </summary>
/// <param name="context">Injection context</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::ValidateContext( InjectContext& context, const blackbone::pe::PEImage& img )
{
// Invalid path
if (context.images.empty())
{
Message::ShowError( _hMainDlg, L"Please add at least one image to inject" );
return STATUS_INVALID_PARAMETER_1;
}
// Validate driver
if (context.cfg.injectMode == Kernel_DriverMap)
{
// Only x64 drivers are supported
if (img.mType() != blackbone::mt_mod64)
{
Message::ShowError( _hMainDlg, L"Can't map x86 drivers - '" + img.name() + L"'" );
return STATUS_INVALID_IMAGE_WIN_32;
}
// Image must be native
if (img.subsystem() != IMAGE_SUBSYSTEM_NATIVE)
{
Message::ShowError( _hMainDlg, L"Can't map image with non-native subsystem - '" + img.name() + L"'" );
return STATUS_INVALID_IMAGE_HASH;
}
return STATUS_SUCCESS;
}
// No process selected
if (!_process.valid())
{
Message::ShowError( _hMainDlg, L"Please select valid process before injection" );
return STATUS_INVALID_HANDLE;
}
auto& barrier = _process.barrier();
// Validate architecture
if (!img.pureIL() && img.mType() == blackbone::mt_mod32 && barrier.targetWow64 == false)
{
Message::ShowError( _hMainDlg, L"Can't inject 32 bit image '" + img.name() + L"' into native 64 bit process" );
return STATUS_INVALID_IMAGE_WIN_32;
}
// Trying to inject x64 dll into WOW64 process
if (!img.pureIL() && img.mType() == blackbone::mt_mod64 && barrier.targetWow64 == true)
{
Message::ShowError( _hMainDlg, L"Can't inject 64 bit image '" + img.name() + L"' into WOW64 process" );
return STATUS_INVALID_IMAGE_WIN_64;
}
// Can't inject managed dll through WOW64 barrier
/*if (img.pureIL() && (barrier.type == blackbone::wow_32_64 || barrier.type == blackbone::wow_64_32))
{
if (barrier.type == blackbone::wow_32_64)
Message::ShowWarning( _hMainDlg, L"Please use Xenos64.exe to inject managed dll '" + img.name() + L"' into x64 process" );
else
Message::ShowWarning( _hMainDlg, L"Please use Xenos.exe to inject managed dll '" + img.name() + L"' into WOW64 process" );
return STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
}*/
// Can't inject 64 bit image into WOW64 process from x86 version
/*if (img.mType() == blackbone::mt_mod64 && barrier.type == blackbone::wow_32_32)
{
Message::ShowWarning( _hMainDlg, L"Please use Xenos64.exe to inject 64 bit image '" + img.name() + L"' into WOW64 process" );
return STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
}*/
// Can't execute code in another thread trough WOW64 barrier
/*if (context.cfg.hijack && barrier.type != blackbone::wow_32_32 && barrier.type != blackbone::wow_64_64)
{
Message::ShowError( _hMainDlg, L"Can't execute code in existing thread trough WOW64 barrier" );
return STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
}*/
// Manual map restrictions
if (context.cfg.injectMode == Manual || context.cfg.injectMode == Kernel_MMap)
{
if (img.pureIL() && (context.cfg.injectMode == Kernel_MMap || !img.isExe()))
{
Message::ShowError( _hMainDlg, L"Pure managed class library '" + img.name() + L"' can't be manually mapped yet" );
return STATUS_INVALID_IMAGE_FORMAT;
}
/*if (((img.mType() == blackbone::mt_mod32 && barrier.sourceWow64 == false) ||
(img.mType() == blackbone::mt_mod64 && barrier.sourceWow64 == true)))
{
if (img.mType() == blackbone::mt_mod32)
Message::ShowWarning( _hMainDlg, L"Please use Xenos.exe to manually map 32 bit image '" + img.name() + L"'" );
else
Message::ShowWarning( _hMainDlg, L"Please use Xenos64.exe to manually map 64 bit image '" + img.name() + L"'" );
return STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
}*/
}
return STATUS_SUCCESS;
}
/// <summary>
/// Validate initialization routine
/// </summary>
/// <param name="init">Routine name</param>
/// <param name="initRVA">Routine RVA, if found</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::ValidateInit( const std::string& init, uint32_t& initRVA, blackbone::pe::PEImage& img )
{
// Validate init routine
if (img.pureIL())
{
// Pure IL exe doesn't need init routine
if (img.isExe())
{
initRVA = 0;
return STATUS_SUCCESS;
};
blackbone::ImageNET::mapMethodRVA methods;
img.net().Parse( &methods );
bool found = false;
if (!methods.empty() && !init.empty())
{
auto winit = blackbone::Utils::AnsiToWstring( init );
for (auto& val : methods)
if (winit == (val.first.first + L"." + val.first.second))
{
found = true;
break;
}
}
if (!found)
{
if (init.empty())
{
Message::ShowError( _hMainDlg, L"Please select '" + img.name() + L"' entry point" );
}
else
{
auto str = blackbone::Utils::FormatString(
L"Image '%ls' does not contain specified method - '%ls'",
img.name().c_str(),
blackbone::Utils::AnsiToWstring( init.c_str() ).c_str()
);
Message::ShowError( _hMainDlg, str );
}
return STATUS_NOT_FOUND;
}
}
else if (!init.empty())
{
blackbone::pe::vecExports exports;
img.GetExports( exports );
auto iter = std::find_if(
exports.begin(), exports.end(),
[&init]( const blackbone::pe::ExportData& val ){ return val.name == init; } );
if (iter == exports.end())
{
initRVA = 0;
auto str = blackbone::Utils::FormatString(
L"Image '%ls' does not contain specified export - '%ls'",
img.name().c_str(),
blackbone::Utils::AnsiToWstring( init.c_str() ).c_str()
);
Message::ShowError( _hMainDlg, str );
return STATUS_NOT_FOUND;
}
else
{
initRVA = iter->RVA;
}
}
return STATUS_SUCCESS;
}
/// <summary>
/// Inject multiple images
/// </summary>
/// <param name="pCtx">Injection context</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::InjectMultiple( InjectContext* pContext )
{
NTSTATUS status = ERROR_SUCCESS;
PROCESS_INFORMATION pi = { 0 };
// Update PID
if(pContext->cfg.injectMode == Existing && pContext->pid == 0)
pContext->pid = pContext->cfg.pid;
// Log some info
xlog::Critical(
"Injection initiated. Mode: %d, process type: %d, pid: %d, mmap flags: 0x%X, "
"erasePE: %d, unlink: %d, thread hijack: %d, init routine: '%s', init arg: '%ls'",
pContext->cfg.injectMode,
pContext->cfg.processMode,
pContext->pid,
pContext->cfg.mmapFlags,
pContext->cfg.erasePE,
pContext->cfg.unlink,
pContext->cfg.hijack,
pContext->cfg.initRoutine.c_str(),
pContext->cfg.initArgs.c_str()
);
// Get process for injection
status = GetTargetProcess( *pContext, pi );
if (status != STATUS_SUCCESS)
return status;
if (pContext->cfg.delay)
Sleep( pContext->cfg.delay );
// Inject all images
for (auto& img : pContext->images)
{
status |= InjectSingle( *pContext, *img );
if (pContext->cfg.period)
Sleep( pContext->cfg.period );
}
//
// Cleanup after injection
//
if (pi.hThread)
{
if (status == STATUS_SUCCESS)
ResumeThread( pi.hThread );
CloseHandle( pi.hThread );
}
if (pi.hProcess)
{
// TODO: Decide if process should be terminated if at least one module failed to inject
/*if (errCode != ERROR_SUCCESS)
TerminateProcess( pi.hProcess, 0 );*/
CloseHandle( pi.hProcess );
}
// Save PID if using physical memory allocation
if (status == STATUS_SUCCESS && (pContext->cfg.mmapFlags & blackbone::HideVAD) &&
(pContext->cfg.injectMode == Manual || pContext->cfg.injectMode == Kernel_MMap))
{
_criticalProcList.emplace_back( _process.pid() );
}
if (_process.core().handle())
_process.Detach();
return status;
}
/// <summary>
/// Injector thread worker
/// </summary>
/// <param name="context">Injection context</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::InjectSingle( InjectContext& context, blackbone::pe::PEImage& img )
{
NTSTATUS status = ERROR_SUCCESS;
blackbone::ThreadPtr pThread;
blackbone::ModuleDataPtr mod;
uint32_t exportRVA = 0;
xlog::Critical( "Injecting image '%ls'", img.path().c_str() );
// Check export
status = ValidateInit( blackbone::Utils::WstringToUTF8( context.cfg.initRoutine ), exportRVA, img );
if (!NT_SUCCESS( status ))
{
xlog::Error( "Image init routine check failed, status: 0x%X", status );
return status;
}
// Final sanity check
if (context.cfg.injectMode < Kernel_Thread || context.cfg.injectMode == Kernel_DriverMap)
{
if (!NT_SUCCESS( status = ValidateContext( context, img ) ))
{
xlog::Error( "Context validation failed, status: 0x%X", status );
return status;
}
}
// Get context thread
if (context.cfg.hijack && context.cfg.injectMode < Kernel_Thread)
{
xlog::Normal( "Searching for thread to hijack" );
pThread = _process.threads().getMostExecuted();
if (!pThread)
{
Message::ShowError( _hMainDlg, L"Failed to get suitable thread for execution");
return status = STATUS_NOT_FOUND;
}
}
auto modCallback = []( blackbone::CallbackType type, void*, blackbone::Process&, const blackbone::ModuleData& modInfo )
{
if (type == blackbone::PreCallback)
{
if (modInfo.name == L"user32.dll")
return blackbone::LoadData( blackbone::MT_Native, blackbone::Ldr_Ignore );
}
return blackbone::LoadData( blackbone::MT_Default, blackbone::Ldr_Ignore );
};
// Actual injection
if (NT_SUCCESS( status ))
{
switch (context.cfg.injectMode)
{
case Normal:
{
auto injectedMod = InjectDefault( context, img, pThread );
if (!injectedMod)
status = injectedMod.status;
else
mod = injectedMod.result();
}
break;
case Manual:
{
auto flags = static_cast<blackbone::eLoadFlags>(context.cfg.mmapFlags);
if (img.isExe())
flags |= blackbone::RebaseProcess;
auto injectedMod = _process.mmap().MapImage( img.path(), flags, modCallback );
if (!injectedMod)
{
status = injectedMod.status;
xlog::Error( "Failed to inject image using manual map, status: 0x%X", injectedMod.status );
}
else
mod = injectedMod.result();
}
break;
case Kernel_Thread:
case Kernel_APC:
case Kernel_MMap:
if (!NT_SUCCESS( status = InjectKernel( context, img, exportRVA ) ))
xlog::Error( "Failed to inject image using kernel injection, status: 0x%X", status );
break;
case Kernel_DriverMap:
status = MapDriver( context, img );
break;
default:
break;
}
}
// Fix error code
if (!img.pureIL() && mod == nullptr && context.cfg.injectMode < Kernel_Thread && NT_SUCCESS( status ))
{
xlog::Error( "Invalid failure status: 0x%X", status );
status = STATUS_DLL_NOT_FOUND;
}
// Initialize routine
if (NT_SUCCESS( status ) && context.cfg.injectMode < Kernel_Thread)
{
status = CallInitRoutine( context, img, mod, exportRVA, pThread );
}
else if (!NT_SUCCESS( status ))
{
wchar_t errBuf[128] = { 0 };
wsprintfW( errBuf, L"Failed to inject image '%ls'.\nError code 0x%X", img.path().c_str(), status );
Message::ShowError( _hMainDlg, errBuf );
}
// Erase header
if (NT_SUCCESS( status ) && mod && context.cfg.injectMode == Normal && context.cfg.erasePE)
{
auto size = img.headersSize();
DWORD oldProt = 0;
std::unique_ptr<uint8_t[]> zeroBuf( new uint8_t[size]() );
_process.memory().Protect( mod->baseAddress, size, PAGE_EXECUTE_READWRITE, &oldProt );
_process.memory().Write( mod->baseAddress, size, zeroBuf.get() );
_process.memory().Protect( mod->baseAddress, size, oldProt );
}
// Unlink module if required
if (NT_SUCCESS( status ) && mod && context.cfg.injectMode == Normal && context.cfg.unlink)
if (_process.modules().Unlink( mod ) == false)
{
status = ERROR_FUNCTION_FAILED;
Message::ShowError( _hMainDlg, L"Failed to unlink module '" + img.path() + L"'" );
}
return status;
}
/// <summary>
/// Default injection method
/// </summary>
/// <param name="context">Injection context</param>
/// <param name="pThread">Context thread of execution</param>
/// <param name="mod">Resulting module</param>
/// <returns>Error code</returns>
blackbone::call_result_t<blackbone::ModuleDataPtr> InjectionCore::InjectDefault(
InjectContext& context,
const blackbone::pe::PEImage& img,
blackbone::ThreadPtr pThread /*= nullptr*/
)
{
using namespace blackbone;
NTSTATUS status = STATUS_SUCCESS;
// Pure IL image
if (img.pureIL())
{
DWORD code = 0;
xlog::Normal( "Image '%ls' is pure IL", img.path().c_str() );
if (!_process.modules().InjectPureIL(
ImageNET::GetImageRuntimeVer( img.path().c_str() ),
img.path(),
context.cfg.initRoutine,
context.cfg.initArgs,
code ))
{
xlog::Error( "Failed to inject pure IL image, status: %d", code );
if (NT_SUCCESS( code ))
code = STATUS_DLL_NOT_FOUND;
return code;
}
auto mod = _process.modules().GetModule( img.name(), Sections );
return mod ? call_result_t<ModuleDataPtr>( mod ) : call_result_t<ModuleDataPtr>( STATUS_NOT_FOUND );
}
else
{
auto injectedMod = _process.modules().Inject( img.path(), pThread );
if (!injectedMod)
xlog::Error( "Failed to inject image using default injection, status: 0x%X", injectedMod.status );
return injectedMod;
}
}
/// <summary>
/// Kernel-mode injection
/// </summary>
/// <param name="context">Injection context</param>
/// <param name="img">Target image</param>
/// <param name="initRVA">Init function RVA</param>
NTSTATUS InjectionCore::InjectKernel(
InjectContext& context,
const blackbone::pe::PEImage& img,
uint32_t initRVA /*= 0*/
)
{
if (context.cfg.injectMode == Kernel_MMap)
{
return blackbone::Driver().MmapDll(
context.pid,
img.path(),
(KMmapFlags)context.cfg.mmapFlags,
initRVA,
context.cfg.initArgs
);
}
else
{
return blackbone::Driver().InjectDll(
context.pid,
img.path(),
(context.cfg.injectMode == Kernel_Thread ? IT_Thread : IT_Apc),
initRVA,
context.cfg.initArgs,
context.cfg.unlink,
context.cfg.erasePE
);
}
}
/// <summary>
/// Manually map another system driver into system space
/// </summary>
/// <param name="context">Injection context</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::MapDriver( InjectContext& context, const blackbone::pe::PEImage& img )
{
return blackbone::Driver().MMapDriver( img.path() );
}
/// <summary>
/// Call initialization routine
/// </summary>
/// <param name="context">Injection context</param>
/// <param name="mod">Target module</param>
/// <param name="pThread">Context thread of execution</param>
/// <returns>Error code</returns>
NTSTATUS InjectionCore::CallInitRoutine(
InjectContext& context,
const blackbone::pe::PEImage& img,
blackbone::ModuleDataPtr mod,
uint64_t exportRVA,
blackbone::ThreadPtr pThread /*= nullptr*/
)
{
// Call init for native image
if (!context.cfg.initRoutine.empty() && !img.pureIL() && context.cfg.injectMode < Kernel_Thread)
{
auto fnPtr = mod->baseAddress + exportRVA;
xlog::Normal( "Calling initialization routine for image '%ls'", img.path().c_str() );
// Create new thread
if (pThread == nullptr)
{
auto argMem = _process.memory().Allocate( 0x1000, PAGE_READWRITE );
if (!argMem)
return argMem.status;
argMem->Write( 0, context.cfg.initArgs.length() * sizeof( wchar_t ) + 2, context.cfg.initArgs.c_str() );
auto status = _process.remote().ExecDirect( fnPtr, argMem->ptr() );
xlog::Normal( "Initialization routine returned 0x%X", status );
}
// Execute in existing thread
else
{
blackbone::RemoteFunction<fnInitRoutine> pfn( _process, fnPtr );
auto status = pfn.Call( context.cfg.initArgs.c_str(), pThread );
xlog::Normal( "Initialization routine returned 0x%X", status );
}
}
return STATUS_SUCCESS;
}