/
MMap.cpp
1593 lines (1349 loc) · 52.2 KB
/
MMap.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 "MMap.h"
#include "../Process/Process.h"
#include "../Misc/NameResolve.h"
#include "../Misc/Utils.h"
#include "../Misc/DynImport.h"
#include "../Misc/Trace.hpp"
#include "../DriverControl/DriverControl.h"
#include <random>
#include <3rd_party/VersionApi.h>
#ifndef STATUS_INVALID_EXCEPTION_HANDLER
#define STATUS_INVALID_EXCEPTION_HANDLER ((NTSTATUS)0xC00001A5L)
#endif
namespace blackbone
{
MMap::MMap( Process& proc )
: _process( proc )
{
}
MMap::~MMap(void)
{
//UnmapAllModules();
}
/// <summary>
/// Manually map PE image into underlying target process
/// </summary>
/// <param name="path">Image path</param>
/// <param name="flags">Image mapping flags</param>
/// <param name="mapCallback">Mapping callback. Triggers for each mapped module</param>
/// <param name="context">User-supplied callback context</param>
/// <returns>Mapped image info </returns>
call_result_t<ModuleDataPtr> MMap::MapImage(
const std::wstring& path,
eLoadFlags flags /*= NoFlags*/,
MapCallback mapCallback /*= nullptr*/,
void* context /*= nullptr*/,
CustomArgs_t* pCustomArgs /*= nullptr*/
)
{
return MapImageInternal( path, nullptr, 0, false, flags, mapCallback, context, pCustomArgs );
}
/// <summary>
///Manually map PE image into underlying target process
/// </summary>
/// <param name="buffer">Image data buffer</param>
/// <param name="size">Buffer size.</param>
/// <param name="asImage">If set to true - buffer has image memory layout</param>
/// <param name="flags">Image mapping flags</param>
/// <param name="mapCallback">Mapping callback. Triggers for each mapped module</param>
/// <param name="context">User-supplied callback context</param>
/// <returns>Mapped image info</returns>
call_result_t<ModuleDataPtr> MMap::MapImage(
size_t size, void* buffer,
bool asImage /*= false*/,
eLoadFlags flags /*= NoFlags*/,
MapCallback mapCallback /*= nullptr*/,
void* context /*= nullptr*/,
CustomArgs_t* pCustomArgs /*= nullptr*/
)
{
// Create fake path
wchar_t path[64];
wsprintfW( path, L"MemoryImage_0x%p", buffer );
return MapImageInternal( path, buffer, size, asImage, flags, mapCallback, context, pCustomArgs );
}
/// <summary>
/// Manually map PE image into underlying target process
/// </summary>
/// <param name="path">Image path</param>
/// <param name="buffer">Image data buffer</param>
/// <param name="size">Buffer size.</param>
/// <param name="asImage">If set to true - buffer has image memory layout</param>
/// <param name="flags">Image mapping flags</param>
/// <param name="mapCallback">Mapping callback. Triggers for each mapped module</param>
/// <param name="context">User-supplied callback context</param>
/// <returns>Mapped image info</returns>
call_result_t<ModuleDataPtr> MMap::MapImageInternal(
const std::wstring& path,
void* buffer, size_t size,
bool asImage /*= false*/,
eLoadFlags flags /*= NoFlags*/,
MapCallback mapCallback /*= nullptr*/,
void* context /*= nullptr*/,
CustomArgs_t* pCustomArgs /*= nullptr*/
)
{
if (!(flags & ForceRemap))
{
// Already loaded
if (auto hMod = _process.modules().GetModule(path))
return hMod;
}
// Prepare target process
auto mode = (flags & NoThreads) ? Worker_UseExisting : Worker_CreateNew;
auto status = _process.remote().CreateRPCEnvironment( mode, true );
if (!NT_SUCCESS( status ))
{
Cleanup();
return status;
}
// No need to support exceptions if DEP is disabled
if (_process.core().DEP() == false)
flags |= NoExceptions;
// Ignore MapInHighMem for native x64 process
if (!_process.core().isWow64())
flags &= ~MapInHighMem;
// Set native loader callback
_mapCallback = mapCallback;
_userContext = context;
BLACKBONE_TRACE( L"ManualMap: Mapping image '%ls' with flags 0x%x", path.c_str(), flags );
// Map module and all dependencies
auto mod = FindOrMapModule( path, buffer, size, asImage, flags );
if (!mod)
{
Cleanup();
return mod.status;
}
// Change process base module address if needed
if (flags & RebaseProcess && !_images.empty() && _images.rbegin()->get()->peImage.isExe())
{
BLACKBONE_TRACE( L"ManualMap: Rebasing process to address 0x%p", (*mod)->baseAddress );
// Managed path fix
if (_images.rbegin()->get()->peImage.pureIL() && !path.empty())
{
CALL_64_86(
(*mod)->type == mt_mod64,
FixManagedPath,
_process.modules().GetMainModule()->baseAddress,
path
);
}
// PEB64
_process.memory().Write(
fieldPtr( _process.core().peb64(), &_PEB64::ImageBaseAddress ),
sizeof( uint64_t ),
&(*mod)->baseAddress
);
// PEB32
if(_process.core().isWow64())
{
_process.memory().Write(
fieldPtr(_process.core().peb32(), &_PEB32::ImageBaseAddress ),
sizeof( uint32_t ),
&(*mod)->baseAddress
);
}
}
auto wipeMemory = []( Process& proc, ImageContext* img, uintptr_t offset, uintptr_t size )
{
size = Align( size, 0x1000 );
std::unique_ptr<uint8_t[]> zeroBuf( new uint8_t[size]() );
if (img->flags & HideVAD)
{
Driver().WriteMem( proc.pid(), img->imgMem.ptr() + offset, size, zeroBuf.get() );
}
else
{
img->imgMem.Write( offset, size, zeroBuf.get() );
proc.memory().Protect( img->imgMem.ptr() + offset, size, PAGE_NOACCESS );
proc.memory().Free( img->imgMem.ptr() + offset, size, MEM_DECOMMIT );
}
};
// Run initializers
for (auto& img : _images)
{
// Init once
if (!img->initialized)
{
// Hack for IL dlls
if (!img->peImage.isExe() && img->peImage.pureIL())
{
DWORD flOld = 0;
auto flg = img->imgMem.Read( img->peImage.ilFlagOffset(), 0 );
img->imgMem.Protect( PAGE_EXECUTE_READWRITE, img->peImage.ilFlagOffset(), sizeof( flg ), &flOld );
img->imgMem.Write( img->peImage.ilFlagOffset(), flg & ~COMIMAGE_FLAGS_ILONLY );
img->imgMem.Protect( flOld, img->peImage.ilFlagOffset(), sizeof( flg ), &flOld );
}
// Don't run initializer for pure IL dlls
if (!img->peImage.pureIL() || img->peImage.isExe())
status = RunModuleInitializers( img, DLL_PROCESS_ATTACH, pCustomArgs ).status;
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: ModuleInitializers failed for '%ls', status: 0x%X", img->ldrEntry.name.c_str(), status );
Cleanup();
return status;
}
// Wipe header
if (img->flags & WipeHeader)
wipeMemory( _process, img.get(), 0, img->peImage.headersSize() );
// Wipe discardable sections
if(!img->peImage.pureIL())
{
for (auto& sec : img->peImage.sections())
if (sec.Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
wipeMemory( _process, img.get(), sec.VirtualAddress, sec.Misc.VirtualSize );
}
img->initialized = true;
}
}
//Cleanup();
return mod;
}
/// <summary>
/// Fix image path for pure managed mapping
/// </summary>
/// <param name="base">Image base</param>
/// <param name="path">New image path</param>
template<typename T>
void MMap::FixManagedPath( ptr_t base, const std::wstring &path )
{
_PEB_T<T> peb = { 0 };
_PEB_LDR_DATA2_T<T> ldr = { 0 };
if (_process.core().peb( &peb ) != 0 && _process.memory().Read( peb.Ldr, sizeof( ldr ), &ldr ) == STATUS_SUCCESS)
{
// Get PEB loader entry
for (auto head = ldr.InLoadOrderModuleList.Flink;
head != fieldPtr( peb.Ldr, &_PEB_LDR_DATA2_T<T>::InLoadOrderModuleList );
head = _process.memory().Read<T>( head ).result( 0 ))
{
_LDR_DATA_TABLE_ENTRY_BASE_T<T> localdata = { { 0 } };
_process.memory().Read( head, sizeof( localdata ), &localdata );
if (localdata.DllBase == base)
{
auto len = path.length()* sizeof( wchar_t );
_process.memory().Write( localdata.FullDllName.Buffer, len + 2, path.c_str() );
_process.memory().Write<short>(
head + FIELD_OFFSET( _LDR_DATA_TABLE_ENTRY_BASE_T<T>, FullDllName.Length ),
static_cast<short>(len)
);
return;
}
}
}
}
/// <summary>
/// Get existing module or map it if absent
/// </summary>
/// <param name="path">Image path</param>
/// <param name="buffer">Image data buffer</param>
/// <param name="size">Buffer size.</param>
/// <param name="asImage">If set to true - buffer has image memory layout</param>
/// <param name="flags">Mapping flags</param>
/// <returns>Module info</returns>
call_result_t<ModuleDataPtr> MMap::FindOrMapModule(
const std::wstring& path,
void* buffer, size_t size, bool asImage,
eLoadFlags flags /*= NoFlags*/
)
{
NTSTATUS status = STATUS_SUCCESS;
ImageContextPtr pImage( new ImageContext() );
auto& ldrEntry = pImage->ldrEntry;
ldrEntry.fullPath = Utils::ToLower( path );
ldrEntry.name = Utils::StripPath( ldrEntry.fullPath );
pImage->flags = flags;
// Load and parse image
status = buffer ? pImage->peImage.Load( buffer, size, !asImage ) : pImage->peImage.Load( path, flags & NoSxS ? true : false );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to load image '%ls'/0x%p. Status 0x%X", path.c_str(), buffer, status );
pImage->peImage.Release();
return status;
}
// Check if already loaded, but only if doesn't explicitly excluded
if (!(flags & ForceRemap))
{
if (auto hMod = _process.modules().GetModule( path, LdrList, pImage->peImage.mType() ))
{
pImage->peImage.Release();
return hMod;
}
}
// Check architecture
if (pImage->peImage.mType() == mt_mod32 && !_process.core().isWow64())
{
BLACKBONE_TRACE( L"ManualMap: Can't map x86 dll '%ls' into native x64 process", path.c_str() );
pImage->peImage.Release();
return STATUS_INVALID_IMAGE_WIN_32;
}
BLACKBONE_TRACE( L"ManualMap: Loading new image '%ls'", path.c_str() );
ldrEntry.type = pImage->peImage.mType();
// Try to map image in high (>4GB) memory range
if (flags & MapInHighMem)
{
AllocateInHighMem( pImage->imgMem, pImage->peImage.imageSize() );
}
// Try to map image at it's original ASRL-aware base
else if (flags & HideVAD)
{
ptr_t base = pImage->peImage.imageBase();
ptr_t image_size = pImage->peImage.imageSize();
if (!NT_SUCCESS( Driver().EnsureLoaded() ))
{
pImage->peImage.Release();
return Driver().status();
}
// Allocate as physical at desired base
status = Driver().AllocateMem( _process.pid(), base, image_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE, true );
// Allocate at any base
if (!NT_SUCCESS( status ))
{
base = 0;
image_size = pImage->peImage.imageSize();
status = Driver().AllocateMem( _process.pid(), base, image_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE, true );
}
// Store allocated region
if (NT_SUCCESS( status ))
{
pImage->imgMem = MemBlock( &_process.memory(), base, static_cast<size_t>(image_size), PAGE_EXECUTE_READWRITE, true, true );
}
// Stop mapping
else
{
//flags &= ~HideVAD;
BLACKBONE_TRACE( L"ManualMap: Failed to allocate physical memory for image, status 0x%X", status );
pImage->peImage.Release();
return status;
}
}
// Allocate normally if something went wrong
if (!pImage->imgMem.valid())
{
auto mem = _process.memory().Allocate( pImage->peImage.imageSize(), PAGE_EXECUTE_READWRITE, pImage->peImage.imageBase() );
if (!mem)
{
BLACKBONE_TRACE( L"ManualMap: Failed to allocate memory for image, status 0x%X", status );
pImage->peImage.Release();
return mem.status;
}
pImage->imgMem = std::move( mem.result() );
}
ldrEntry.baseAddress = pImage->imgMem.ptr();
ldrEntry.size = pImage->peImage.imageSize();
BLACKBONE_TRACE( L"ManualMap: Image base allocated at 0x%016llx", pImage->imgMem.ptr() );
// Create Activation context for SxS
if (pImage->peImage.manifestID() == 0)
flags |= NoSxS;
if (!(flags & NoSxS))
{
status = CreateActx( pImage->peImage );
if (!NT_SUCCESS( status ))
{
pImage->peImage.Release();
return status;
}
}
// Core image mapping operations
if (!NT_SUCCESS( status = CopyImage( pImage ) ))
{
pImage->peImage.Release();
return status;
}
if (!NT_SUCCESS( status = RelocateImage( pImage ) ))
{
pImage->peImage.Release();
return status;
}
auto mt = ldrEntry.type;
ModuleDataPtr pMod;
if (flags & ForceRemap)
pMod = std::make_shared<const ModuleData>( _process.modules().Canonicalize( ldrEntry, true ) );
else
pMod = _process.modules().AddManualModule( ldrEntry );
{
// Handle x64 system32 dlls for wow64 process
bool fsRedirect = !(flags & IsDependency) && mt == mt_mod64 && _process.barrier().sourceWow64;
FsRedirector fsr( fsRedirect );
// Import
if (!NT_SUCCESS( status = ResolveImport( pImage ) ))
{
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
// Delayed import
if (!(flags & NoDelayLoad) && !NT_SUCCESS( status = ResolveImport( pImage, true ) ))
{
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
}
// Apply proper memory protection for sections
if (!(flags & HideVAD))
ProtectImageMemory( pImage );
// Make exception handling possible (C and C++)
if (!(flags & NoExceptions))
{
if (!NT_SUCCESS( status = EnableExceptions( pImage ) ) && status != STATUS_NOT_FOUND)
{
BLACKBONE_TRACE( L"ManualMap: Failed to enable exception handling for image %ls", ldrEntry.name.c_str() );
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
}
// Initialize security cookie
if (!NT_SUCCESS ( status = InitializeCookie( pImage ) ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to initialize cookie for image %ls", ldrEntry.name.c_str() );
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
// Unlink image from VAD list
if (flags & HideVAD && !NT_SUCCESS( status = ConcealVad( pImage->imgMem ) ))
{
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
// Get entry point
pImage->ldrEntry.entryPoint = pImage->peImage.entryPoint( pImage->imgMem.ptr<ptr_t>() );
// Create reference for native loader functions
pImage->ldrEntry.flags = flags & CreateLdrRef ? Ldr_All : Ldr_None;
if (_mapCallback != nullptr)
{
auto mapData = _mapCallback( PostCallback, _userContext, _process, *pMod );
if(mapData.ldrFlags != Ldr_Ignore)
pImage->ldrEntry.flags = mapData.ldrFlags;
}
if (pImage->ldrEntry.flags != Ldr_None)
{
if (!_process.nativeLdr().CreateNTReference( pImage->ldrEntry ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to add loader reference for image %ls", ldrEntry.name.c_str() );
}
}
// Static TLS data
if (!(flags & NoTLS) && !NT_SUCCESS( status = InitStaticTLS( pImage ) ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to initialize static TLS for image %ls, status 0x%X", ldrEntry.name.c_str(), status );
pImage->peImage.Release();
_process.modules().RemoveManualModule( ldrEntry.name, mt );
return status;
}
// Fill TLS callbacks
pImage->peImage.GetTLSCallbacks( pImage->imgMem.ptr<ptr_t>(), pImage->tlsCallbacks );
// Unload local copy
pImage->peImage.Release();
// Release ownership of image memory block
pImage->imgMem.Release();
// Store image
_images.emplace_back( std::move( pImage ) );
return pMod;
}
/// <summary>
/// Unmap all manually mapped modules
/// </summary>
/// <returns>Status code</returns>
NTSTATUS MMap::UnmapAllModules()
{
for (auto img = _images.rbegin(); img != _images.rend(); ++img)
{
auto pImage = *img;
BLACKBONE_TRACE( L"ManualMap: Unmapping image '%ls'", pImage->ldrEntry.name.c_str() );
// Call main
RunModuleInitializers( pImage, DLL_PROCESS_DETACH );
// Remove VEH
if (!(pImage->flags & NoExceptions))
DisableExceptions( pImage );
_process.nativeLdr().UnloadTLS( pImage->ldrEntry );
// Remove from loader
if (pImage->ldrEntry.flags != Ldr_None)
_process.nativeLdr().Unlink( pImage->ldrEntry );
// Free memory
pImage->imgMem.Free();
// Remove reference from local modules list
_process.modules().RemoveManualModule( pImage->ldrEntry.name, pImage->peImage.mType() );
}
Cleanup();
return STATUS_SUCCESS;
}
/// <summary>
/// Copies image into target process
/// </summary>
/// <param name="pImage">Image data</param>
/// <returns>Status code</returns>
NTSTATUS MMap::CopyImage( ImageContextPtr pImage )
{
NTSTATUS status = STATUS_SUCCESS;
BLACKBONE_TRACE( L"ManualMap: Performing image copy" );
// offset to first section equals to header size
size_t dwHeaderSize = pImage->peImage.headersSize();
// Copy header
if (pImage->flags & HideVAD)
status = Driver().WriteMem( _process.pid(), pImage->imgMem.ptr(), dwHeaderSize, pImage->peImage.base() );
else
status = pImage->imgMem.Write( 0, dwHeaderSize, pImage->peImage.base() );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to copy image headers. Status = 0x%x", status );
return status;
}
// Set header protection
if (!(pImage->flags & HideVAD))
{
status = pImage->imgMem.Protect( PAGE_READONLY, 0, dwHeaderSize );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to set header memory protection. Status = 0x%x", status );
return status;
}
}
// Copy sections
for (auto& section : pImage->peImage.sections())
{
// Skip discardable sections
if (section.Characteristics & (IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE))
{
if (section.SizeOfRawData == 0)
continue;
uint8_t* pSource = reinterpret_cast<uint8_t*>(pImage->peImage.ResolveRVAToVA( section.VirtualAddress ));
// Copy section data
if (pImage->flags & HideVAD)
{
status = Driver().WriteMem(
_process.pid(), pImage->imgMem.ptr() + section.VirtualAddress,
section.SizeOfRawData, pSource
);
}
else
{
status = pImage->imgMem.Write( section.VirtualAddress, section.SizeOfRawData, pSource );
}
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE(
L"ManualMap: Failed to copy image section at offset 0x%x. Status = 0x%x",
section.VirtualAddress, status
);
return status;
}
}
}
return STATUS_SUCCESS;
}
/// <summary>
/// Adjust image memory protection
/// </summary>
/// <param name="pImage">image data</param>
/// <returns>Status code</returns>
NTSTATUS MMap::ProtectImageMemory( ImageContextPtr pImage )
{
// Set section memory protection
for (auto& section : pImage->peImage.sections())
{
auto prot = GetSectionProt( section.Characteristics );
if (prot != PAGE_NOACCESS)
{
auto status = pImage->imgMem.Protect( prot, section.VirtualAddress, section.Misc.VirtualSize );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE(
L"ManualMap: Failed to set section memory protection at offset 0x%x. Status = 0x%x",
section.VirtualAddress, status
);
return status;
}
}
// Decommit pages with NO_ACCESS protection
else
{
auto status = _process.memory().Free( pImage->imgMem.ptr() + section.VirtualAddress, section.Misc.VirtualSize, MEM_DECOMMIT );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE(
L"ManualMap: Failed to set section memory protection at offset 0x%x. Status = 0x%x",
section.VirtualAddress, status
);
}
}
}
return STATUS_SUCCESS;
}
/// <summary>
/// Fix relocations if image wasn't loaded at base address
/// </summary>
/// <param name="pImage">image data</param>
/// <returns>true on success</returns>
NTSTATUS MMap::RelocateImage( ImageContextPtr pImage )
{
NTSTATUS status = STATUS_SUCCESS;
BLACKBONE_TRACE( L"ManualMap: Relocating image '%ls'", pImage->ldrEntry.fullPath.c_str() );
// Reloc delta
ptr_t Delta = pImage->imgMem.ptr() - pImage->peImage.imageBase();
// No need to relocate
if (Delta == 0)
{
BLACKBONE_TRACE( L"ManualMap: No need for relocation" );
return STATUS_SUCCESS;
}
// Dll can't be relocated
if (!(pImage->peImage.DllCharacteristics() & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
{
BLACKBONE_TRACE( L"ManualMap: Can't relocate image, no relocation flag" );
return STATUS_INVALID_IMAGE_HASH;
}
auto start = pImage->peImage.DirectoryAddress( IMAGE_DIRECTORY_ENTRY_BASERELOC );
auto end = start + pImage->peImage.DirectorySize( IMAGE_DIRECTORY_ENTRY_BASERELOC );
auto fixrec = reinterpret_cast<pe::RelocData*>(start);
// No relocatable data
if (fixrec == nullptr)
{
BLACKBONE_TRACE( L"ManualMap: Image does not use relocations" );
return STATUS_SUCCESS;
}
// Read whole image to process it locally
std::unique_ptr<uint8_t[]> localImage( new uint8_t[pImage->ldrEntry.size] );
auto pLocal = localImage.get();
_process.memory().Read( pImage->imgMem.ptr(), pImage->ldrEntry.size, pLocal );
while ((uintptr_t)fixrec < end && fixrec->BlockSize)
{
DWORD count = (fixrec->BlockSize - 8) >> 1; // records count
for (DWORD i = 0; i < count; ++i)
{
WORD fixtype = (fixrec->Item[i].Type); // fixup type
WORD fixoffset = (fixrec->Item[i].Offset) % 4096; // offset in 4K block
// no fixup required
if (fixtype == IMAGE_REL_BASED_ABSOLUTE)
continue;
// add delta
if (fixtype == IMAGE_REL_BASED_HIGHLOW || fixtype == IMAGE_REL_BASED_DIR64)
{
uintptr_t fixRVA = fixoffset + fixrec->PageRVA;
if (pImage->ldrEntry.type == mt_mod64)
{
uint64_t val = *reinterpret_cast<uint64_t*>(pLocal + fixRVA) + Delta;
*reinterpret_cast<uint64_t*>(pLocal + fixRVA) = val;
}
else
{
uint32_t val = *reinterpret_cast<uint32_t*>(pLocal + fixRVA) + static_cast<uint32_t>(Delta);
*reinterpret_cast<uint32_t*>(pLocal + fixRVA) = static_cast<uint32_t>(val);
}
}
else
{
// TODO: support for all remaining relocations
BLACKBONE_TRACE( L"ManualMap: Abnormal relocation type %d. Aborting", fixtype );
return STATUS_INVALID_IMAGE_FORMAT;
}
}
// next reloc entry
fixrec = reinterpret_cast<pe::RelocData*>(reinterpret_cast<uintptr_t>(fixrec) + fixrec->BlockSize);
}
// Apply relocations, skip header
if (pImage->flags & HideVAD)
status = Driver().WriteMem( _process.pid(), pImage->ldrEntry.baseAddress + 0x1000, pImage->ldrEntry.size - 0x1000, pLocal + 0x1000 );
else
status = _process.memory().Write( pImage->ldrEntry.baseAddress + 0x1000, pImage->ldrEntry.size - 0x1000, pLocal + 0x1000 );
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to apply relocations. Status = 0x%x", status );
}
return status;
}
/// <summary>
/// Return existing or load missing dependency
/// </summary>
/// <param name="pImage">Currently napped image data</param>
/// <param name="path">Dependency path</param>
/// <returns></returns>
call_result_t<ModuleDataPtr> MMap::FindOrMapDependency( ImageContextPtr pImage, std::wstring& path )
{
// Already loaded
auto hMod = _process.modules().GetModule( path, LdrList, pImage->peImage.mType(), pImage->ldrEntry.fullPath.c_str() );
if (hMod)
return hMod;
BLACKBONE_TRACE( L"ManualMap: Loading new dependency '%ls'", path.c_str() );
auto flags = NameResolve::EnsureFullPath;
// Wow64 fs redirection
if (pImage->ldrEntry.type == mt_mod32 && !_process.barrier().sourceWow64)
flags = static_cast<NameResolve::eResolveFlag>(static_cast<int32_t>(flags) | NameResolve::Wow64);
auto basedir = pImage->peImage.noPhysFile() ? Utils::GetExeDirectory() : Utils::GetParent( pImage->ldrEntry.fullPath );
auto status = NameResolve::Instance().ResolvePath(
path,
pImage->ldrEntry.name,
basedir,
flags,
_process,
pImage->peImage.actx()
);
// Do remote SxS probe
if (status == STATUS_SXS_IDENTITIES_DIFFERENT)
{
status = ProbeRemoteSxS( path );
}
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to resolve dependency path '%ls', status 0x%x", path.c_str(), status );
return status;
}
BLACKBONE_TRACE( L"ManualMap: Dependency path resolved to '%ls'", path.c_str() );
LoadData data;
if (_mapCallback != nullptr)
{
ModuleData tmpData;
tmpData.baseAddress = 0;
tmpData.manual = ((pImage->flags & ManualImports) != 0);
tmpData.fullPath = path;
tmpData.name = Utils::ToLower( Utils::StripPath( path ) );
tmpData.size = 0;
tmpData.type = pImage->ldrEntry.type;
data = _mapCallback( PreCallback, _userContext, _process, tmpData );
}
// Loading method
if (data.mtype == MT_Manual || (data.mtype == MT_Default && pImage->flags & ManualImports))
{
return FindOrMapModule( path, nullptr, 0, false, pImage->flags | NoSxS | NoDelayLoad | PartialExcept | IsDependency );
}
else if (data.mtype != MT_None)
{
return _process.modules().Inject( path );
}
// Aborted by user
else
{
return STATUS_REQUEST_CANCELED;
}
};
/// <summary>
/// Resolves image import or delayed image import
/// </summary>
/// <param name="pImage">Image data</param>
/// <param name="useDelayed">Resolve delayed import instead</param>
/// <returns>Status code</returns>
NTSTATUS MMap::ResolveImport( ImageContextPtr pImage, bool useDelayed /*= false */ )
{
auto imports = pImage->peImage.GetImports( useDelayed );
if (imports.empty())
return STATUS_SUCCESS;
// Read whole image to process it locally
std::unique_ptr<uint8_t[]> localImage( new uint8_t[pImage->ldrEntry.size] );
auto pLocal = localImage.get();
_process.memory().Read( pImage->imgMem.ptr(), pImage->ldrEntry.size, pLocal );
// Traverse entries
for (auto& importMod : imports)
{
std::wstring wstrDll = importMod.first;
// Load dependency if needed
auto hMod = FindOrMapDependency( pImage, wstrDll );
if (!hMod)
{
BLACKBONE_TRACE( L"ManualMap: Failed to load dependency '%ls'. Status 0x%x", wstrDll.c_str(), hMod.status );
return hMod.status;
}
for (auto& importFn : importMod.second)
{
call_result_t<exportData> expData;
if (importFn.importByOrd)
expData = _process.modules().GetExport( hMod.result(), reinterpret_cast<const char*>(importFn.importOrdinal) );
else
expData = _process.modules().GetExport( hMod.result(), importFn.importName.c_str() );
// Still forwarded, load missing modules
while (expData && expData->procAddress && expData->isForwarded)
{
std::wstring wdllpath = expData->forwardModule;
// Ensure module is loaded
auto hFwdMod = FindOrMapDependency( pImage, wdllpath );
if (!hFwdMod)
{
BLACKBONE_TRACE( L"ManualMap: Failed to load forwarded dependency '%ls'. Status 0x%x", wstrDll.c_str(), hFwdMod.status );
return hFwdMod.status;
}
if (expData->forwardByOrd)
{
expData = _process.modules().GetExport(
hFwdMod.result(),
reinterpret_cast<const char*>(expData->forwardOrdinal),
wdllpath.c_str()
);
}
else
expData = _process.modules().GetExport( hFwdMod.result(), expData->forwardName.c_str(), wdllpath.c_str() );
}
// Failed to resolve import
if (!expData)
{
if (importFn.importByOrd)
{
BLACKBONE_TRACE(
L"ManualMap: Failed to get import #%d from image '%ls'",
importFn.importOrdinal,
wstrDll.c_str()
);
}
else
{
BLACKBONE_TRACE(
L"ManualMap: Failed to get import '%ls' from image '%ls'",
Utils::AnsiToWstring( importFn.importName ).c_str(),
wstrDll.c_str()
);
}
return expData.status;
}
if (pImage->ldrEntry.type == mt_mod64)
*reinterpret_cast<uint64_t*>(pLocal + importFn.ptrRVA) = expData->procAddress;
else
*reinterpret_cast<uint32_t*>(pLocal + importFn.ptrRVA) = static_cast<uint32_t>(expData->procAddress);
}
}
auto status = STATUS_SUCCESS;
// Apply imports, skip header
if (pImage->flags & HideVAD)
{
status = Driver().WriteMem(
_process.pid(),
pImage->ldrEntry.baseAddress + 0x1000,
pImage->ldrEntry.size - 0x1000,
pLocal + 0x1000
);
}
else
{
status = _process.memory().Write(
pImage->ldrEntry.baseAddress + 0x1000,
pImage->ldrEntry.size - 0x1000,
pLocal + 0x1000
);
}
// Write function address
if (!NT_SUCCESS( status ))
{
BLACKBONE_TRACE( L"ManualMap: Failed to write import function. Status 0x%x", status );
}
return status;
}
/// <summary>
/// Set custom exception handler to bypass SafeSEH under DEP
/// </summary>
/// <param name="pImage">image data</param>
/// <returns>true on success</returns>
NTSTATUS MMap::EnableExceptions( ImageContextPtr pImage )
{
BLACKBONE_TRACE( L"ManualMap: Enabling exception support for image '%ls'", pImage->ldrEntry.name.c_str() );
bool partial = (pImage->flags & PartialExcept) != 0;
bool success = _process.nativeLdr().InsertInvertedFunctionTable( pImage->ldrEntry );
if (pImage->ldrEntry.type == mt_mod64)
{
// Try RtlIsertInvertedTable
if (!success)
{
// Retry with documented method
auto expTableRVA = pImage->peImage.DirectoryAddress( IMAGE_DIRECTORY_ENTRY_EXCEPTION, pe::RVA );
size_t size = pImage->peImage.DirectorySize( IMAGE_DIRECTORY_ENTRY_EXCEPTION );
// Invoke RtlAddFunctionTable
if (expTableRVA)
{
auto a = AsmFactory::GetAssembler( pImage->ldrEntry.type );
uint64_t result = 0;
pImage->pExpTableAddr = expTableRVA + pImage->imgMem.ptr<ptr_t>();
auto pAddTable = _process.modules().GetNtdllExport( "RtlAddFunctionTable", pImage->ldrEntry.type );
if (!pAddTable)
return pAddTable.status;
a->GenPrologue();
a->GenCall(
pAddTable->procAddress, {
pImage->pExpTableAddr,
size / sizeof( IMAGE_RUNTIME_FUNCTION_ENTRY ),