/
Remap.c
1317 lines (1077 loc) · 43.5 KB
/
Remap.c
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 "Remap.h"
#include "Utils.h"
#include <Ntstrsafe.h>
RTL_AVL_TABLE g_ProcessPageTables; // Mapping table
KGUARDED_MUTEX g_globalLock; // ProcessPageTables mutex
/// <summary>
/// Walk region list and create MDL for each region
/// </summary>
/// <param name="pList">Region list</param>
/// <returns>Status code</returns>
NTSTATUS BBPrepareMDLList( IN PLIST_ENTRY pList );
/// <summary>
/// Build MDL for memory region
/// </summary>
/// <param name="pEntry">Region data</param>
/// <returns>Status code</returns>
NTSTATUS BBPrepareMDLListEntry( IN PMAP_ENTRY pEntry );
/// <summary>
/// Map locked physical pages into caller process
/// </summary>
/// <param name="pList">Region list</param>
/// <param name="noWarning">If set to FALSE, warning will be printed if region is already mapped</param>
/// <returns>Status code</returns>
NTSTATUS BBMapRegionListIntoCurrentProcess( IN PLIST_ENTRY pList, IN BOOLEAN noWarning );
/// <summary>
/// Map locked physical pages into caller process
/// </summary>
/// <param name="pEntry">Memory region</param>
/// <param name="pPrevEntry">Last mapped region</param>
/// <returns>Status code</returns>
NTSTATUS BBMapRegionIntoCurrentProcess( IN PMAP_ENTRY pEntry, IN PMAP_ENTRY pPrevEntry );
/// <summary>
/// Allocate kernel page from NonPaged pool and build MDL for it
/// </summary>
/// <param name="pPage">Resulting address</param>
/// <param name="pResultMDL">Resulting MDL</param>
/// <returns>Status code</returns>
NTSTATUS BBAllocateSharedPage( OUT PVOID* pPage, OUT PMDL* pResultMDL );
/// <summary>
/// Map kernel page into current process address space
/// </summary>
/// <param name="pMDL">Page MDL</param>
/// <param name="pResult">Mapped address</param>
/// <returns>Status code</returns>
NTSTATUS BBMapSharedPage( IN PMDL pMDL, OUT PVOID* pResult );
/// <summary>
/// Consolidate adjacent memory regions
/// </summary>
/// <param name="pList">Region list</param>
/// <returns>Status code</returns>
NTSTATUS BBConsolidateRegionList( IN PLIST_ENTRY pList );
/// <summary>
/// Process section object pages
/// Function will attempt to trigger copy-on-write for underlying pages to convert them into private
/// If copy-on-write fails, region will be then mapped as read-only
/// </summary>
/// <param name="pEntry">Region data</param>
/// <returns>Status code</returns>
NTSTATUS BBHandleSharedRegion( IN PMAP_ENTRY pEntry );
/// <summary>
/// Unmap memory region, release corresponding MDL, and remove region form list
/// </summary>
/// <param name="pPageEntry">Region data</param>
/// <param name="pFoundEntry">Process data</param>
/// <returns>Status code</returns>
NTSTATUS BBUnmapRegionEntry( IN PMAP_ENTRY pPageEntry, IN PPROCESS_MAP_ENTRY pFoundEntry );
//
// Lookup routines
//
/// <summary>
/// Find memory region containing at least one byte from specific region
/// </summary>
/// <param name="pList">Region list to search in</param>
/// <param name="baseAddress">Base of region to find</param>
/// <param name="size">Size of the region to find</param>
/// <returns>Status code</returns>
PMAP_ENTRY BBFindPageEntry( IN PLIST_ENTRY pList, IN ULONG_PTR baseAddress, IN ULONG_PTR size );
//
// Cleanup routines
//
/// <summary>
/// Unmap pages, destroy MDLs, remove entry from list
/// </summary>
/// <param name="attached">TRUE indicates that function is executed
/// in the context of host process and pages can be safely unmapped</param>
/// <param name="pList">Region list</param>
VOID BBCleanupPageList( IN BOOLEAN attached, IN PLIST_ENTRY pList );
/// <summary>
/// Close handle if process isn't in signaled state
/// </summary>
/// <param name="pProcess">Process object</param>
/// <param name="handle">Handle</param>
/// <param name="mode">KernelMode or UserMode handle</param>
/// <returns>Status code</returns>
NTSTATUS BBSafeHandleClose( IN PEPROCESS pProcess, IN HANDLE handle, IN KPROCESSOR_MODE mode );
#pragma alloc_text(PAGE, BBBuildProcessRegionListForRange)
#pragma alloc_text(PAGE, BBPrepareMDLList)
#pragma alloc_text(PAGE, BBPrepareMDLListEntry)
#pragma alloc_text(PAGE, BBMapRegionListIntoCurrentProcess)
#pragma alloc_text(PAGE, BBMapRegionIntoCurrentProcess)
#pragma alloc_text(PAGE, BBAllocateSharedPage)
#pragma alloc_text(PAGE, BBMapSharedPage)
#pragma alloc_text(PAGE, BBConsolidateRegionList)
#pragma alloc_text(PAGE, BBHandleSharedRegion)
#pragma alloc_text(PAGE, BBUnmapRegionEntry)
#pragma alloc_text(PAGE, BBMapMemory)
#pragma alloc_text(PAGE, BBMapMemoryRegion)
#pragma alloc_text(PAGE, BBUnmapMemory)
#pragma alloc_text(PAGE, BBUnmapMemoryRegion)
#pragma alloc_text(PAGE, BBGetRequiredRemapOutputSize)
#pragma alloc_text(PAGE, BBLookupProcessEntry)
#pragma alloc_text(PAGE, BBFindPageEntry)
#pragma alloc_text(PAGE, BBCleanupProcessTable)
#pragma alloc_text(PAGE, BBCleanupProcessEntry)
#pragma alloc_text(PAGE, BBCleanupHostProcess)
#pragma alloc_text(PAGE, BBCleanupPageList)
#pragma alloc_text(PAGE, BBSafeHandleClose)
#pragma alloc_text(PAGE, AvlCompare)
#pragma alloc_text(PAGE, AvlAllocate)
#pragma alloc_text(PAGE, AvlFree)
/*
*/
RTL_GENERIC_COMPARE_RESULTS AvlCompare( IN RTL_AVL_TABLE *Table, IN PVOID FirstStruct, IN PVOID SecondStruct )
{
UNREFERENCED_PARAMETER( Table );
PPROCESS_MAP_ENTRY pFirstEntry = (PPROCESS_MAP_ENTRY)FirstStruct;
PPROCESS_MAP_ENTRY pSecondEntry = (PPROCESS_MAP_ENTRY)SecondStruct;
// Find by target
if (pFirstEntry->target.pid != 0 && pSecondEntry->target.pid != 0)
{
if (pFirstEntry->target.pid == pSecondEntry->target.pid)
return GenericEqual;
if (pSecondEntry->target.pid > pFirstEntry->target.pid)
return GenericGreaterThan;
return GenericLessThan;
}
// Find by Host
else
{
if (pFirstEntry->host.pid == pSecondEntry->host.pid)
return GenericEqual;
if (pSecondEntry->host.pid > pFirstEntry->host.pid)
return GenericGreaterThan;
return GenericLessThan;
}
}
/*
*/
PVOID AvlAllocate( IN RTL_AVL_TABLE *Table, IN CLONG ByteSize )
{
UNREFERENCED_PARAMETER( Table );
return ExAllocatePoolWithTag( PagedPool, ByteSize, BB_POOL_TAG );
}
/*
*/
VOID AvlFree( IN RTL_AVL_TABLE *Table, IN PVOID Buffer )
{
UNREFERENCED_PARAMETER( Table );
ExFreePoolWithTag( Buffer, BB_POOL_TAG );
}
/// <summary>
/// Enumerate committed, accessible, non-guarded memory regions
/// </summary>
/// <param name="pList">Region list</param>
/// <param name="start">Region start</param>
/// <param name="end">Region end</param>
/// <param name="mapSections">If set to FALSE, section objects will be excluded from list</param>
/// <returns>Status code</returns>
NTSTATUS BBBuildProcessRegionListForRange( IN PLIST_ENTRY pList, IN ULONG_PTR start, IN ULONG_PTR end, IN BOOLEAN mapSections )
{
NTSTATUS status = STATUS_SUCCESS;
MEMORY_BASIC_INFORMATION mbi = { 0 };
SIZE_T length = 0;
ULONG_PTR memptr = 0;
PMAP_ENTRY pEntry = NULL;
for (memptr = start; memptr < end; memptr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize)
{
status = ZwQueryVirtualMemory( ZwCurrentProcess(), (PVOID)memptr, MemoryBasicInformationEx, &mbi, sizeof( mbi ), &length );
if (!NT_SUCCESS( status ))
{
DPRINT( "BlackBone: %s: ZwQueryVirtualMemory for address 0x%p returned status 0x%X\n", __FUNCTION__, memptr, status );
// STATUS_INVALID_PARAMETER is a normal status for last secured VAD under Win7
return status == STATUS_INVALID_PARAMETER ? STATUS_SUCCESS : status;
}
// Skip non-committed, no-access and guard pages
else if (mbi.State == MEM_COMMIT && mbi.Protect != PAGE_NOACCESS && !(mbi.Protect & PAGE_GUARD))
{
// Ignore shared memory if required
if (mbi.Type != MEM_PRIVATE && !mapSections)
continue;
pEntry = ExAllocatePoolWithTag( PagedPool, sizeof( MAP_ENTRY ), BB_POOL_TAG );
if (pEntry == NULL)
{
DPRINT( "BlackBone: %s: Failed to allocate memory for Remap descriptor\n", __FUNCTION__ );
BBCleanupPageList( FALSE, pList );
return STATUS_NO_MEMORY;
}
pEntry->mem = mbi;
pEntry->newPtr = 0;
pEntry->pMdl = NULL;
pEntry->locked = FALSE;
pEntry->shared = mbi.Type != MEM_PRIVATE;
InsertTailList( pList, &pEntry->link );
}
}
//if (NT_SUCCESS( status ))
//status = BBConsolidateRegionList( pList );
return status;
}
/// <summary>
/// Consolidate adjacent memory regions
/// </summary>
/// <param name="pList">Region list</param>
/// <returns>Status code</returns>
NTSTATUS BBConsolidateRegionList( IN PLIST_ENTRY pList )
{
NTSTATUS status = STATUS_SUCCESS;
for (PLIST_ENTRY pListEntry = pList->Flink; pListEntry != pList; )
{
PMAP_ENTRY pNextEntry = NULL;
PMAP_ENTRY pEntry = CONTAINING_RECORD( pListEntry, MAP_ENTRY, link );
// End of list
if (pListEntry->Flink == pList)
break;
pNextEntry = CONTAINING_RECORD( pListEntry->Flink, MAP_ENTRY, link );
// Consolidate only non-mapped entries. Both entries must have same sharing flags
if (pEntry->pMdl == NULL && pNextEntry->pMdl == NULL && pEntry->shared == pNextEntry->shared)
{
// Regions are adjacent
if ((PUCHAR)pEntry->mem.BaseAddress + pEntry->mem.RegionSize == pNextEntry->mem.BaseAddress)
{
pEntry->mem.RegionSize += pNextEntry->mem.RegionSize;
RemoveEntryList( &pNextEntry->link );
}
else
pListEntry = pListEntry->Flink;
}
else
pListEntry = pListEntry->Flink;
}
return status;
}
/// <summary>
/// Unmap memory region, release corresponding MDL, and remove region form list
/// </summary>
/// <param name="pPageEntry">Region data</param>
/// <param name="pFoundEntry">Process data</param>
/// <returns>Status code</returns>
NTSTATUS BBUnmapRegionEntry( IN PMAP_ENTRY pPageEntry, IN PPROCESS_MAP_ENTRY pFoundEntry )
{
NTSTATUS status = STATUS_SUCCESS;
UNREFERENCED_PARAMETER( pFoundEntry );
// MDL is valid
if (pPageEntry->pMdl)
{
// If MDL is mapped
if (pPageEntry->newPtr)
{
DPRINT( "BlackBone: %s: Unmapping region at 0x%p from process %u\n", __FUNCTION__, pPageEntry->newPtr, pFoundEntry->target.pid );
MmUnmapLockedPages( (PVOID)pPageEntry->newPtr, pPageEntry->pMdl );
pPageEntry->newPtr = 0;
}
if (pPageEntry->locked)
MmUnlockPages( pPageEntry->pMdl );
IoFreeMdl( pPageEntry->pMdl );
}
RemoveEntryList( &pPageEntry->link );
ExFreePoolWithTag( pPageEntry, BB_POOL_TAG );
return status;
}
/// <summary>
/// Process section object pages
/// Function will attempt to trigger copy-on-write for underlying pages to convert them into private
/// If copy-on-write fails, region will be then mapped as read-only
/// </summary>
/// <param name="pEntry">Region data</param>
/// <returns>Status code</returns>
NTSTATUS BBHandleSharedRegion( IN PMAP_ENTRY pEntry )
{
NTSTATUS status = STATUS_SUCCESS;
MEMORY_BASIC_INFORMATION mbi = { 0 };
SIZE_T length = 0;
ULONG_PTR memptr = 0;
// Iterate underlying memory regions
for (memptr = (ULONG_PTR)pEntry->mem.BaseAddress;
memptr < (ULONG_PTR)pEntry->mem.BaseAddress + pEntry->mem.RegionSize;
memptr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize)
{
PVOID pBase = NULL;
SIZE_T size = 0;
MEMORY_WORKING_SET_EX_INFORMATION wsInfo = { 0 };
ULONG oldProt = 0;
BOOLEAN writable = FALSE;
status = ZwQueryVirtualMemory( ZwCurrentProcess(), (PVOID)memptr, MemoryBasicInformation, &mbi, sizeof( mbi ), &length );
if (!NT_SUCCESS( status ))
{
DPRINT( "BlackBone: %s: ZwQueryVirtualMemory for address 0x%p failed\n", __FUNCTION__, memptr );
return status;
}
writable = (mbi.Protect & (PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE));
pBase = mbi.BaseAddress;
size = (SIZE_T)mbi.RegionSize;
// Make readonly pages writable
if (writable || NT_SUCCESS( ZwProtectVirtualMemory( ZwCurrentProcess(), &pBase, &size, PAGE_EXECUTE_READWRITE, &oldProt ) ))
{
BOOLEAN failed = FALSE;
// Touch pages to trigger copy-on-write and create private copies
// This is crucial to prevent changes on section pages
__try
{
ProbeForWrite( mbi.BaseAddress, mbi.RegionSize, PAGE_SIZE );
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
DPRINT( "BlackBone: %s: Exception while touching address 0x%p\n", __FUNCTION__, mbi.BaseAddress );
failed = TRUE;
}
// Restore protection
if (writable == FALSE)
ZwProtectVirtualMemory( ZwCurrentProcess(), &pBase, &size, oldProt, &oldProt );
if (failed)
return STATUS_SHARING_VIOLATION;
// If region was writable, it's safe to map shared pages
if (writable)
continue;
//
// Ensure pages were made private
//
for (ULONG_PTR pPage = (ULONG_PTR)mbi.BaseAddress; pPage < (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; pPage += PAGE_SIZE)
{
RtlZeroMemory( &wsInfo, sizeof( wsInfo ) );
wsInfo.VirtualAddress = (PVOID)pPage;
// Check page 'shared' flag
if (NT_SUCCESS( ZwQueryVirtualMemory( ZwCurrentProcess(), NULL, MemoryWorkingSetExInformation, &wsInfo, sizeof( wsInfo ), &length ) ) &&
wsInfo.VirtualAttributes.Shared)
{
DPRINT( "BlackBone: %s: Page at address 0x%p is still shared!", __FUNCTION__, pPage );
return STATUS_SHARING_VIOLATION;
}
}
}
else
{
DPRINT( "BlackBone: %s: Failed to alter protection of region at 0x%p\n", __FUNCTION__, mbi.BaseAddress );
return STATUS_SHARING_VIOLATION;
}
}
return status;
}
/// <summary>
/// Build MDL for memory region
/// </summary>
/// <param name="pEntry">Region data</param>
/// <returns>Status code</returns>
NTSTATUS BBPrepareMDLListEntry( IN OUT PMAP_ENTRY pEntry )
{
NTSTATUS status = STATUS_SUCCESS;
ASSERT( pEntry != NULL );
if (pEntry == NULL)
return STATUS_INVALID_PARAMETER;
// Handle shared pages
if (pEntry->shared != FALSE && !NT_SUCCESS( BBHandleSharedRegion( pEntry ) ))
pEntry->readonly = TRUE;
else
pEntry->readonly = FALSE;
pEntry->pMdl = IoAllocateMdl( pEntry->mem.BaseAddress, (ULONG)pEntry->mem.RegionSize, FALSE, FALSE, NULL );
if (pEntry->pMdl == NULL)
{
DPRINT( "BlackBone: %s: Failed to allocate MDL for address 0x%p\n", __FUNCTION__, pEntry->mem.BaseAddress );
return STATUS_NO_MEMORY;
}
__try
{
MmProbeAndLockPages( pEntry->pMdl, UserMode, IoReadAccess );
pEntry->locked = TRUE;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
DPRINT( "BlackBone: %s: Exception in MmProbeAndLockPages. Base = 0x%p\n", __FUNCTION__, pEntry->mem.BaseAddress );
IoFreeMdl( pEntry->pMdl );
pEntry->pMdl = NULL;
}
return status;
}
/// <summary>
/// Walk region list and create MDL for each region
/// </summary>
/// <param name="pList">Region list</param>
/// <returns>Status code</returns>
NTSTATUS BBPrepareMDLList( IN PLIST_ENTRY pList )
{
NTSTATUS status = STATUS_SUCCESS;
PMAP_ENTRY pEntry = NULL;
for (PLIST_ENTRY pListEntry = pList->Flink; pListEntry != pList; pListEntry = pListEntry->Flink)
{
pEntry = CONTAINING_RECORD( pListEntry, MAP_ENTRY, link );
if (pEntry->pMdl == NULL)
BBPrepareMDLListEntry( pEntry );
}
return status;
}
/// <summary>
/// Map locked physical pages into caller process
/// </summary>
/// <param name="pEntry">Memory region</param>
/// <param name="pPrevEntry">Last mapped region</param>
/// <returns>Status code</returns>
NTSTATUS BBMapRegionIntoCurrentProcess( IN PMAP_ENTRY pEntry, IN PMAP_ENTRY pPrevEntry )
{
NTSTATUS status = STATUS_SUCCESS;
UNREFERENCED_PARAMETER( pPrevEntry );
ASSERT( pEntry != NULL );
if (pEntry == NULL)
return STATUS_INVALID_PARAMETER;
// Try to map at original address
__try {
pEntry->newPtr = (ULONG_PTR)MmMapLockedPagesSpecifyCache(
pEntry->pMdl, UserMode, MmCached, pEntry->mem.BaseAddress, FALSE, NormalPagePriority
);
}
__except (EXCEPTION_EXECUTE_HANDLER) { }
// Try to map immediately after previous entry
if (pEntry->newPtr == 0 && pPrevEntry != NULL && pPrevEntry->newPtr != 0)
{
__try {
pEntry->newPtr = (ULONG_PTR)MmMapLockedPagesSpecifyCache(
pEntry->pMdl, UserMode, MmCached, (PVOID)(pPrevEntry->newPtr + pPrevEntry->mem.RegionSize), FALSE, NormalPagePriority
);
}
__except (EXCEPTION_EXECUTE_HANDLER) { }
}
// Map at arbitrary available location
if (pEntry->newPtr == 0)
{
__try {
pEntry->newPtr = (ULONG_PTR)MmMapLockedPagesSpecifyCache( pEntry->pMdl, UserMode, MmCached, NULL, FALSE, NormalPagePriority );
}
__except (EXCEPTION_EXECUTE_HANDLER) { }
}
if (pEntry->newPtr != 0)
{
//if (pEntry->newPtr != pEntry->originalPtr)
//DPRINT( "BlackBone: %s: Remapped 0x%p --> 0x%p\n", __FUNCTION__, pEntry->originalPtr, pEntry->newPtr );
// Update region protection only for the sake of NtQueryVirtualMemory
// It has no other effect because real protection is determined by underlying PTEs
BBProtectVAD( PsGetCurrentProcess(), pEntry->newPtr, pEntry->readonly ? MM_READONLY : MM_EXECUTE_READWRITE );
// ZwProtectVirtualMemory can't update protection of pages that represent Physical View
// So PTEs are updated directly
for (ULONG_PTR pAdress = pEntry->newPtr; pAdress < pEntry->newPtr + pEntry->mem.RegionSize; pAdress += PAGE_SIZE)
{
PMMPTE pPTE = GetPTEForVA( (PVOID)pAdress );
if (pEntry->readonly)
pPTE->u.Hard.Dirty1 = pPTE->u.Hard.Write = 0;
else
pPTE->u.Hard.NoExecute = 0;
}
}
else
{
DPRINT( "BlackBone: %s: Failed to map region at adress 0x%p\n", __FUNCTION__, pEntry->mem.BaseAddress );
status = STATUS_NONE_MAPPED;
}
return status;
}
/// <summary>
/// Map memory regions into caller process
/// </summary>
/// <param name="pList">Region list</param>
/// <param name="noWarning">If set to FALSE, warning will be printed if region is already mapped</param>
/// <returns>Status code</returns>
NTSTATUS BBMapRegionListIntoCurrentProcess( IN PLIST_ENTRY pList, IN BOOLEAN noWarning )
{
NTSTATUS status = STATUS_SUCCESS;
PMAP_ENTRY pEntry = NULL, pPrevEntry = NULL;
for (PLIST_ENTRY pListEntry = pList->Flink; pListEntry != pList; pListEntry = pListEntry->Flink)
{
pEntry = CONTAINING_RECORD( pListEntry, MAP_ENTRY, link );
// Skip already mapped entries
if (pEntry->newPtr != 0)
{
if (noWarning == FALSE)
DPRINT( "BlackBone: %s: Warning! Region 0x%p already mapped to 0x%p\n", __FUNCTION__, pEntry->mem.BaseAddress, pEntry->newPtr );
continue;
}
// Non-locked pages can't be mapped
if (pEntry->pMdl && pEntry->locked)
status |= BBMapRegionIntoCurrentProcess( pEntry, pPrevEntry );
else
DPRINT( "BlackBone: %s: No valid MDL for address 0x%p. Either not allocated or not locked\n", __FUNCTION__, pEntry->mem.BaseAddress );
pPrevEntry = pEntry;
}
return status;
}
/// <summary>
/// Allocate kernel page from NonPaged pool and build MDL for it
/// </summary>
/// <param name="pPage">Resulting address</param>
/// <param name="pResultMDL">Resulting MDL</param>
/// <returns>Status code</returns>
NTSTATUS BBAllocateSharedPage( OUT PVOID* pPage, OUT PMDL* pResultMDL )
{
NTSTATUS status = STATUS_SUCCESS;
ASSERT( pPage != NULL && pResultMDL != NULL );
if (pPage == NULL || pResultMDL == NULL)
return STATUS_INVALID_PARAMETER;
*pPage = ExAllocatePoolWithTag( NonPagedPool, PAGE_SIZE, BB_POOL_TAG );
if (*pPage)
{
// Cleanup buffer before mapping it into UserMode to prevent exposure of kernel data
RtlZeroMemory( *pPage, PAGE_SIZE );
*pResultMDL = IoAllocateMdl( *pPage, PAGE_SIZE, FALSE, FALSE, NULL );
if (*pResultMDL)
MmBuildMdlForNonPagedPool( *pResultMDL );
}
else
{
DPRINT( "BlackBone: %s: Failed to allocate kernel page\n", __FUNCTION__ );
status = STATUS_MEMORY_NOT_ALLOCATED;
}
return status;
}
/// <summary>
/// Map kernel page into current process address space
/// </summary>
/// <param name="pMDL">Page MDL</param>
/// <param name="pResult">Mapped address</param>
/// <returns>Status code</returns>
NTSTATUS BBMapSharedPage( IN PMDL pMDL, OUT PVOID* pResult )
{
NTSTATUS status = STATUS_SUCCESS;
ASSERT( pMDL != NULL && pResult != NULL );
if (pMDL == NULL || pResult == NULL)
return STATUS_INVALID_PARAMETER;
__try
{
// Map into user space
*pResult = MmMapLockedPagesSpecifyCache( pMDL, UserMode, MmCached, NULL, FALSE, NormalPagePriority );
if (*pResult)
{
//DPRINT( "BlackBone: %s: Shared page at 0x%p\n", __FUNCTION__, *pResult );
// Make executable
BBProtectVAD( PsGetCurrentProcess(), (ULONG_PTR)*pResult, MM_EXECUTE_READWRITE );
GetPTEForVA( *pResult )->u.Hard.NoExecute = 0;
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
if (*pResult == NULL)
{
DPRINT( "BlackBone: %s: Failed to map kernel page\n", __FUNCTION__ );
status = STATUS_NOT_MAPPED_DATA;
}
return status;
}
/// <summary>
/// Map entire address space of target process into current
/// Subsequent calls won't map any additional regions, only return info about existing mapping
/// </summary>
/// <param name="pRemap">Mapping params</param>
/// <param name="ppEntry">Mapped context</param>
/// <returns>Status code</returns>
NTSTATUS BBMapMemory( IN PMAP_MEMORY pRemap, OUT PPROCESS_MAP_ENTRY* ppEntry )
{
NTSTATUS status = STATUS_SUCCESS;
PEPROCESS pProcess = NULL;
PROCESS_MAP_ENTRY processEntry = { 0 };
PPROCESS_MAP_ENTRY pFoundEntry = NULL;
BOOLEAN newEntry = FALSE;
// Sanity checks
// Can't remap self
if ((HANDLE)pRemap->pid == PsGetCurrentProcessId())
return STATUS_INVALID_PARAMETER;
processEntry.target.pid = (HANDLE)pRemap->pid;
KeAcquireGuardedMutex( &g_globalLock );
status = PsLookupProcessByProcessId( processEntry.target.pid, &pProcess );
if (!NT_SUCCESS( status ))
{
DPRINT( "BlackBone: %s: Failed to find process with PID %u\n", __FUNCTION__, processEntry.target.pid );
KeReleaseGuardedMutex( &g_globalLock );
return status;
}
// Process in signaled state, abort any operations
if (BBCheckProcessTermination( pProcess ))
{
DPRINT( "BlackBone: %s: Process %u is terminating. Abort\n", __FUNCTION__, processEntry.target.pid );
ObDereferenceObject( pProcess );
KeReleaseGuardedMutex( &g_globalLock );
return STATUS_PROCESS_IS_TERMINATING;
}
pFoundEntry = (PPROCESS_MAP_ENTRY)RtlInsertElementGenericTableAvl( &g_ProcessPageTables, &processEntry, sizeof( processEntry ), &newEntry );
if (newEntry != FALSE)
{
InitializeListHead( &pFoundEntry->pageList );
// Allocate shared Page
status = BBAllocateSharedPage( &pFoundEntry->pSharedPage, &pFoundEntry->pMDLShared );
if (NT_SUCCESS( status ))
{
KAPC_STATE apc;
WCHAR wbuf[48] = { 0 };
UNICODE_STRING pipeName = { 0 };
OBJECT_ATTRIBUTES attr = { 0 };
IO_STATUS_BLOCK ioStatusBlock = { 0 };
pipeName.Buffer = wbuf;
pipeName.Length = 0;
pipeName.MaximumLength = sizeof( wbuf );
KeStackAttachProcess( pProcess, &apc );
status = BBBuildProcessRegionListForRange( &pFoundEntry->pageList, (ULONG_PTR)MM_LOWEST_USER_ADDRESS,
(ULONG_PTR)MM_HIGHEST_USER_ADDRESS, pRemap->mapSections );
if (NT_SUCCESS( status ))
status = BBPrepareMDLList( &pFoundEntry->pageList );
// Map shared page into target process
if (NT_SUCCESS( status ))
status = BBMapSharedPage( pFoundEntry->pMDLShared, &pFoundEntry->target.sharedPage );
// Open pipe endpoint
if (NT_SUCCESS( status ))
{
status = RtlUnicodeStringPrintf( &pipeName, L"\\??\\pipe\\%ls", pRemap->pipeName );
InitializeObjectAttributes( &attr, &pipeName, OBJ_CASE_INSENSITIVE, NULL, NULL );
status = ZwOpenFile( &pFoundEntry->targetPipe, GENERIC_WRITE, &attr, &ioStatusBlock, FILE_SHARE_READ | FILE_SHARE_WRITE, 0 );
}
KeUnstackDetachProcess( &apc );
}
}
else
{
DPRINT( "BlackBone: %s: Found mapping entry for process %u\n", __FUNCTION__, pFoundEntry->target.pid );
// Caller is not Host and Host still exists
// Does not allow remapping into new process
if (pFoundEntry->host.pid != PsGetCurrentProcessId() && pFoundEntry->host.pid != NULL)
{
DPRINT( "BlackBone: %s: Host process %u still exists. Cannot map into new process\n", __FUNCTION__, pFoundEntry->host.pid );
status = STATUS_ADDRESS_ALREADY_EXISTS;
}
}
// Update host process
if (NT_SUCCESS( status ) && (newEntry || pFoundEntry->host.pid == NULL))
{
// Map memory
BBMapRegionListIntoCurrentProcess( &pFoundEntry->pageList, FALSE );
// Map shared page into Host process
BBMapSharedPage( pFoundEntry->pMDLShared, &pFoundEntry->host.sharedPage );
pFoundEntry->host.pid = PsGetCurrentProcessId();
}
if (ppEntry)
*ppEntry = pFoundEntry;
if (pProcess)
ObDereferenceObject( pProcess );
// Remove entry if something went wrong
if (!NT_SUCCESS( status ) && status != STATUS_ADDRESS_ALREADY_EXISTS)
BBCleanupProcessEntry(pFoundEntry);
KeReleaseGuardedMutex( &g_globalLock );
return status;
}
/// <summary>
/// Map specific memory region
/// </summary>
/// <param name="pRegion">Region data</param>
/// <param name="pResult">Mapping results</param>
/// <returns>Status code</returns>
NTSTATUS BBMapMemoryRegion( IN PMAP_MEMORY_REGION pRegion, OUT PMAP_MEMORY_REGION_RESULT pResult )
{
NTSTATUS status = STATUS_SUCCESS;
ULONG pageCount = ADDRESS_AND_SIZE_TO_SPAN_PAGES( pRegion->base, pRegion->size );
PROCESS_MAP_ENTRY processEntry = { 0 };
PPROCESS_MAP_ENTRY pFoundEntry = NULL;
PEPROCESS pProcess = NULL;
BOOLEAN newEntry = FALSE;
BOOLEAN alreadyExists = FALSE;
ULONG_PTR removedBase = 0;
ULONG removedSize = 0;
// Don't allow remapping of kernel addresses
if (pRegion->base >= (ULONGLONG)MM_HIGHEST_USER_ADDRESS || pRegion->base + pRegion->size > (ULONGLONG)MM_HIGHEST_USER_ADDRESS)
{
DPRINT( "BlackBone: %s: Invalid address range: 0x%p - 0x%p\n", __FUNCTION__, pRegion->base, pRegion->base + pRegion->size );
return STATUS_INVALID_ADDRESS;
}
KeAcquireGuardedMutex( &g_globalLock );
// Align on page boundaries
pRegion->base = (ULONGLONG)PAGE_ALIGN( pRegion->base );
pRegion->size = pageCount << PAGE_SHIFT;
processEntry.target.pid = (HANDLE)pRegion->pid;
processEntry.host.pid = PsGetCurrentProcessId();
status = PsLookupProcessByProcessId( processEntry.target.pid, &pProcess );
if (!NT_SUCCESS( status ))
{
DPRINT( "BlackBone: %s: Failed to find process 0x%u\n", __FUNCTION__, processEntry.target.pid );
KeReleaseGuardedMutex( &g_globalLock );
return status;
}
// Process in signaled state, abort any operations
if (BBCheckProcessTermination( pProcess ))
{
DPRINT( "BlackBone: %s: Process %u is terminating. Abort\n", __FUNCTION__, processEntry.target.pid );
ObDereferenceObject( pProcess );
KeReleaseGuardedMutex( &g_globalLock );
return STATUS_PROCESS_IS_TERMINATING;
}
// Store or retrieve context
pFoundEntry = (PPROCESS_MAP_ENTRY)RtlInsertElementGenericTableAvl( &g_ProcessPageTables, &processEntry, sizeof( processEntry ), &newEntry );
if (newEntry != FALSE)
{
DPRINT( "BlackBone: %s: Process entry 0x%u was not found, creating new\n", __FUNCTION__, processEntry.target.pid );
InitializeListHead( &pFoundEntry->pageList );
// Allocate shared Page
status = BBAllocateSharedPage( &pFoundEntry->pSharedPage, &pFoundEntry->pMDLShared );
}
else
{
PMAP_ENTRY pPageEntry = NULL;
// Does not allow call from non-original process
if (pFoundEntry->host.pid != PsGetCurrentProcessId() && pFoundEntry->host.pid != NULL)
{
DPRINT( "BlackBone: %s: Call from non-original process not supported\n", __FUNCTION__ );
status = STATUS_INVALID_PARAMETER;
}
// Conflicting region
// Target region isn't considered conflicting if it completely fits into existing
// TODO: Find source of the problem
pPageEntry = BBFindPageEntry( &pFoundEntry->pageList, pRegion->base, pRegion->size );
if (pPageEntry)
{
if (pRegion->base < (ULONGLONG)pPageEntry->mem.BaseAddress ||
pRegion->base + pRegion->size > (ULONGLONG)pPageEntry->mem.BaseAddress + pPageEntry->mem.RegionSize)
{
DPRINT(
"BlackBone: %s: Target region 0%p - 0x%p conficts with existing: 0x%p - 0x%p\n", __FUNCTION__,
pRegion->base, pRegion->base + pRegion->size,
pPageEntry->mem.BaseAddress, (ULONGLONG)pPageEntry->mem.BaseAddress + pPageEntry->mem.RegionSize
);
// Unmap conflicting region
removedBase = (ULONG_PTR)pPageEntry->mem.BaseAddress;
removedSize = (ULONG)pPageEntry->mem.RegionSize;
status = BBUnmapRegionEntry( pPageEntry, pFoundEntry );
}
else
alreadyExists = TRUE;
}
}
// Map region if required
if (alreadyExists == FALSE && NT_SUCCESS( status ))
{
KAPC_STATE apc;
// Allocate MDLs and lock pages
KeStackAttachProcess( pProcess, &apc );
status = BBBuildProcessRegionListForRange( &pFoundEntry->pageList, pRegion->base, pRegion->base + pRegion->size, TRUE );
if (NT_SUCCESS( status ))
status = BBPrepareMDLList( &pFoundEntry->pageList );
// Map shared page into target process
if (NT_SUCCESS( status ) && newEntry)
status = BBMapSharedPage( pFoundEntry->pMDLShared, &pFoundEntry->target.sharedPage );
KeUnstackDetachProcess( &apc );
// Map shared page into Host process
if (NT_SUCCESS( status ) && newEntry)
status = BBMapSharedPage( pFoundEntry->pMDLShared, &pFoundEntry->host.sharedPage );
if (NT_SUCCESS( status ))
status = BBMapRegionListIntoCurrentProcess( &pFoundEntry->pageList, TRUE );
}
if (pProcess)
ObDereferenceObject( pProcess );
// Fill result
if (NT_SUCCESS( status ) && pResult)
{
// FIXME:
// Target region could be divided into several smaller ones
// This function will return only first found
PMAP_ENTRY pEntry = BBFindPageEntry( &pFoundEntry->pageList, pRegion->base, pRegion->size );
if (pEntry)
{
DPRINT( "BlackBone: %s: Updated 0x%p --> 0x%p\n", __FUNCTION__, pEntry->mem.BaseAddress, pEntry->newPtr );
pResult->originalPtr = (ULONGLONG)pEntry->mem.BaseAddress;
pResult->newPtr = pEntry->newPtr;
pResult->removedPtr = removedBase;
pResult->size = (ULONG)pEntry->mem.RegionSize;
pResult->removedSize = removedSize;
}
}
// Remove entry if something goes wrong
if (!NT_SUCCESS( status ))
BBCleanupProcessEntry( pFoundEntry );
KeReleaseGuardedMutex( &g_globalLock );
return status;
}
/// <summary>
/// Unmap any mapped memory from host and target processes
/// </summary>
/// <param name="pUnmap">Request params</param>
/// <returns>Status code</returns>
NTSTATUS BBUnmapMemory( IN PUNMAP_MEMORY pUnmap )
{
NTSTATUS status = STATUS_SUCCESS;
PPROCESS_MAP_ENTRY pFoundEntry = NULL;
KeAcquireGuardedMutex( &g_globalLock );
pFoundEntry = BBLookupProcessEntry( (HANDLE)pUnmap->pid, FALSE );
if (pFoundEntry == NULL)
{
DPRINT( "BlackBone: %s: Process entry with PID %u was not found\n", __FUNCTION__, pUnmap->pid );
status = STATUS_NOT_FOUND;
}
else
{
DPRINT( "BlackBone: %s: BBUnmapMemory cleanup for PID %u\n", __FUNCTION__, pUnmap->pid );
BBCleanupProcessEntry( pFoundEntry );
}
KeReleaseGuardedMutex( &g_globalLock );
return status;
}
/// <summary>
/// Unmap specific memory region
/// </summary>
/// <param name="pRegion">Region info</param>
/// <returns>Status ode</returns>
NTSTATUS BBUnmapMemoryRegion( IN PUNMAP_MEMORY_REGION pRegion )
{
NTSTATUS status = STATUS_SUCCESS;
PPROCESS_MAP_ENTRY pFoundEntry = NULL;
PMAP_ENTRY pPageEntry = NULL;
PEPROCESS pProcess = NULL;
ULONG pageCount = ADDRESS_AND_SIZE_TO_SPAN_PAGES(pRegion->base, pRegion->size);
// Sanity check
if (pRegion->base >= (ULONGLONG)MM_HIGHEST_USER_ADDRESS || pRegion->base + pRegion->size > (ULONGLONG)MM_HIGHEST_USER_ADDRESS)