-
Notifications
You must be signed in to change notification settings - Fork 21
/
PGKd.cpp
1313 lines (1140 loc) · 102 KB
/
PGKd.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 "stdafx.h"
#include "pgkd.h"
#include "Progress.h"
#include "PoolTagNote.h"
#include "scope_guard.h"
#include <sstream>
#include <iomanip>
// EXT_DECLARE_GLOBALS must be used to instantiate
// the framework's assumed globals.
EXT_DECLARE_GLOBALS();
extern"C" auto _EFN_Analyze(
PDEBUG_CLIENT4 aClient,
FA_EXTENSION_PLUGIN_PHASE aCallPhase,
PDEBUG_FAILURE_ANALYSIS2 aAnalysis)
->HRESULT
{
return g_ExtInstance._EFN_Analyze(aClient, aCallPhase, aAnalysis);
}
namespace Sunstrider
{
// Exported command !findpg (no options)
EXT_COMMAND(findpg,
"Displays base addresses of PatchGuard pages",
"")
{
try
{
FindPatchGuardContext();
}
catch (std::exception& aWhat)
{
// As an exception string does not appear on Windbg,
// we need to handle it manually.
Err("%s\n", aWhat.what());
}
}
// Exported command !analyzepg (no options)
EXT_COMMAND(analyzepg,
"Analyzes current bugcheck 0x109: CRITICAL_STRUCTURE_CORRUPTION",
"")
{
for (;;)
{
if (IsCurMachine32())
{
Err("!analyzepg not support x86 target!\n");
break;
}
auto vBugCheckCode = 0ul;
UINT64 vBugCheckArgs[4]{};
auto hr = m_Control->ReadBugCheckData(
&vBugCheckCode,
&vBugCheckArgs[0],
&vBugCheckArgs[1],
&vBugCheckArgs[2],
&vBugCheckArgs[3]);
if (FAILED(hr) || vBugCheckCode != 0x109)
{
Err("No CRITICAL_STRUCTURE_CORRUPTION bugcheck information was"
" derived.\n");
break;
}
auto vPGContext = vBugCheckArgs[0] - BUGCHECK_109_ARGS0_KEY;
auto vPGReason = vBugCheckArgs[1] ? vBugCheckArgs[1] - BUGCHECK_109_ARGS1_KEY : 0;
DumpPatchGuard(
vPGContext,
vPGReason,
vBugCheckArgs[2],
vBugCheckArgs[3],
true);
break;
}
}
// Exported command !dumppg <address>
EXT_COMMAND(dumppg,
"Displays the PatchGuard context",
"{;e64;address;An address of a PatchGuard context.}")
{
DumpPatchGuard(GetUnnamedArgU64(0), 0, 0, 0);
}
auto PGKd::_EFN_Analyze(
PDEBUG_CLIENT4 aClient,
FA_EXTENSION_PLUGIN_PHASE aCallPhase,
PDEBUG_FAILURE_ANALYSIS2 /*aAnalysis*/)
-> HRESULT
{
HRESULT hr = S_OK;
if (FA_PLUGIN_POST_BUCKETING == aCallPhase)
{
if (!g_Ext.IsSet())
{
return E_UNEXPECTED;
}
return g_Ext->CallCommand(&g_analyzepgDesc, (PDEBUG_CLIENT)aClient, "");
}
return hr;
}
auto PGKd::Initialize()
-> HRESULT
{
HRESULT hr = S_OK;
for (;;)
{
auto vDbgClient = static_cast<IDebugClient*>(nullptr);
hr = DebugCreate(__uuidof(IDebugClient), (void **)&vDbgClient);
if (FAILED(hr))
{
break;
}
auto vDbgClientScope = std::experimental::scope_guard(
vDbgClient, [](IDebugClient* aDbgClient){ aDbgClient->Release(); });
auto vDbgControl = static_cast<IDebugControl*>(nullptr);
hr = vDbgClient->QueryInterface(__uuidof(IDebugControl), (void **)&vDbgControl);
if (FAILED(hr))
{
break;
}
auto vDbgControlScope = std::experimental::scope_guard(
vDbgControl, [](IDebugControl* aDbgControl){ aDbgControl->Release(); });
ExtensionApis.nSize = sizeof(ExtensionApis);
hr = vDbgControl->GetWindbgExtensionApis64(&ExtensionApis);
if (FAILED(hr))
{
break;
}
auto vTarget = std::string();
if (wdk::SystemVersion::Unknown == GetSystemVersion(vDbgControl, &vTarget))
{
dprintf("Unsupported version detected: %s\n", vTarget.c_str());
hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
break;
}
// Display guide messages
dprintf("Use ");
vDbgControl->ControlledOutput(
DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL,
"<exec cmd=\"!findpg\">!findpg</exec>");
dprintf(" to find base addresses of the pages allocated for PatchGuard.\n");
dprintf("Use ");
vDbgControl->ControlledOutput(
DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL,
"<exec cmd=\"!analyzepg\">!analyzepg</exec>");
dprintf(" to get detailed PatchGuard Bugcheck information.\n");
dprintf("Use !dumppg <address> to display PatchGuard information"
" located at the specific address.\n");
dprintf("\n");
break;
}
return hr;
}
auto PGKd::GetSystemVersion(PDEBUG_CONTROL aDbgControl, std::string* aTarget)
-> wdk::SystemVersion
{
static auto sSystemVersion = wdk::SystemVersion::Unknown;
if (wdk::SystemVersion::Unknown != sSystemVersion)
{
return sSystemVersion;
}
for (;;)
{
if (nullptr == aDbgControl)
{
break;
}
auto vPlatformId = 0ul;
auto vMajorVer = 0ul;
auto vMinorVer = 0ul;
auto vServicePackNumber = 0ul;
auto vBuildBuffer = std::make_unique<std::array<char, 1024>>();
auto hr = aDbgControl->GetSystemVersion(
&vPlatformId,
&vMajorVer,
&vMinorVer,
nullptr, 0, nullptr,
&vServicePackNumber,
vBuildBuffer->data(), static_cast<ULONG>(vBuildBuffer->size()),
nullptr);
if (FAILED(hr))
{
break;
}
const auto vBuild = std::string(vBuildBuffer->data());
if (aTarget) *aTarget = vBuild;
// Check if the target platform is supported
struct VersionMap
{
std::string Build;
wdk::SystemVersion Version;
};
const VersionMap sSupportedVersions[] =
{
{ "Built by: 3790.", wdk::SystemVersion::WindowsXP64, },
{ "Built by: 6000.", wdk::SystemVersion::WindowsVista, },
{ "Built by: 6001.", wdk::SystemVersion::WindowsVista_SP1, },
{ "Built by: 6002.", wdk::SystemVersion::WindowsVista_SP2, },
{ "Built by: 7600.", wdk::SystemVersion::Windows7, },
{ "Built by: 7601.", wdk::SystemVersion::Windows7_SP1, },
{ "Built by: 9200.", wdk::SystemVersion::Windows8, },
{ "Built by: 9600.", wdk::SystemVersion::Windows8_1, },
{ "Built by: 10240.", wdk::SystemVersion::Windows10_1507, },
{ "Built by: 10586.", wdk::SystemVersion::Windows10_1511, },
{ "Built by: 14393.", wdk::SystemVersion::Windows10_1607, },
{ "Built by: 15063.", wdk::SystemVersion::Windows10_1703, },
{ "Built by: 16299.", wdk::SystemVersion::Windows10_1709, },
{ "Built by: 17134.", wdk::SystemVersion::Windows10_1803, },
{ "Built by: 17741.", wdk::SystemVersion::Windows10_1809, }
};
for (const auto& vItem : sSupportedVersions)
{
if (vBuild.substr(0, vItem.Build.length()) == vItem.Build)
{
sSystemVersion = vItem.Version;
break;
}
}
break;
}
return sSystemVersion;
}
auto PGKd::IsWindows10OrGreater()
-> bool
{
return (GetSystemVersion() >= wdk::SystemVersion::Windows10);
}
auto PGKd::IsWindowsRS1OrGreater()
-> bool
{
return (GetSystemVersion() >= wdk::SystemVersion::Windows10_1607);
}
auto PGKd::GetPfnDatabase()
-> UINT64
{
static UINT64 sPfnDatabase = 0;
if (sPfnDatabase)
{
return sPfnDatabase;
}
for (;;)
{
auto vOffset = 0UI64;
auto hr = m_Symbols->GetOffsetByName("nt!MmPfnDatabase", &vOffset);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmPfnDatabase could not be found.");
break;
}
hr = m_Data->ReadPointersVirtual(1, vOffset, &sPfnDatabase);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmGetVirtualForPhysical could not be read PTE_BASE.");
break;
}
break;
}
return sPfnDatabase;
}
auto PGKd::GetPteBase()
-> UINT64
{
static UINT64 sPteBase = 0;
if (sPteBase)
{
return sPteBase;
}
for (;;)
{
if (!IsWindowsRS1OrGreater())
{
sPteBase = 0xFFFFF68000000000UI64;
break;
}
auto vOffset = 0UI64;
auto hr = m_Symbols->GetOffsetByName("nt!MmGetVirtualForPhysical", &vOffset);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmGetVirtualForPhysical could not be found.");
break;
}
static UINT8 sSearchPatten[] =
{
// mov rax,[rax + rdx * 8]
// shl rax, 19h
// mov rdx, PTE_BASE
0x48, 0x8B, 0x04, 0xD0,
0x48, 0xC1, 0xE0, 0x19,
0x48, 0xBA, // 00 00 00 00 80 F6 FF FF
};
hr = m_Data->SearchVirtual(vOffset, 0x60, sSearchPatten, sizeof(sSearchPatten), 1, &vOffset);
if (!SUCCEEDED(hr))
{
throw std::runtime_error("nt!MmGetVirtualForPhysical could not be search PTE_BASE.");
break;
}
hr = m_Data->ReadPointersVirtual(1, vOffset + sizeof(sSearchPatten), &sPteBase);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmGetVirtualForPhysical could not be read PTE_BASE.");
break;
}
break;
}
return sPteBase;
}
auto PGKd::GetPtes(UINT64 aPteBase)
-> std::unique_ptr<std::array<wdk::HARDWARE_PTE, wdk::PTE_PER_PAGE>>
{
auto vPtes = std::make_unique<std::array<wdk::HARDWARE_PTE, wdk::PTE_PER_PAGE>>();
auto vReadBytes = 0ul;
if (FAILED(m_Data->ReadVirtual(
aPteBase,
vPtes->data(), static_cast<ULONG>(vPtes->size() * sizeof(wdk::HARDWARE_PTE)),
&vReadBytes)))
{
throw std::runtime_error("The given Ptes address could not be read.");
}
return std::move(vPtes);
}
auto PGKd::IsNonPagedBigPool(const wdk::POOL_TRACKER_BIG_PAGES & aEntry)
-> bool
{
auto vPoolType = wdk::POOL_TYPE::PagedPool;
if (IsWindows10OrGreater())
{
auto vEntry = (wdk::build_10240::POOL_TRACKER_BIG_PAGES*)&aEntry;
vPoolType = (wdk::POOL_TYPE)vEntry->PoolType;
}
else
{
auto vEntry = (wdk::POOL_TRACKER_BIG_PAGES*)&aEntry;
vPoolType = (wdk::POOL_TYPE)vEntry->PoolType;
}
bool vNonPaged = false;
switch (vPoolType)
{
default:
break;
case wdk::POOL_TYPE::NonPagedPool:
case wdk::POOL_TYPE::NonPagedPoolCacheAligned:
case wdk::POOL_TYPE::NonPagedPoolCacheAlignedMustS:
case wdk::POOL_TYPE::NonPagedPoolCacheAlignedSession:
case wdk::POOL_TYPE::NonPagedPoolMustSucceed:
case wdk::POOL_TYPE::NonPagedPoolMustSucceedSession:
case wdk::POOL_TYPE::NonPagedPoolNx:
case wdk::POOL_TYPE::NonPagedPoolNxCacheAligned:
case wdk::POOL_TYPE::NonPagedPoolSession:
case wdk::POOL_TYPE::NonPagedPoolSessionNx:
vNonPaged = true;
break;
}
return vNonPaged;
}
// Returns true when page protection of the given page is
// Readable/Writable/Executable.
auto PGKd::IsPageValidReadWriteExecutable(UINT64 aPteAddress) -> bool
{
auto vReadBytes = 0ul;
auto vPte = wdk::HARDWARE_PTE{};
auto hr = m_Data->ReadVirtual(aPteAddress, &vPte, sizeof(vPte), &vReadBytes);
if (FAILED(hr))
{
return false;
}
return (vPte.Valid && vPte.Write && !vPte.NoExecute);
}
// Returns true when page protection of the given page or a parant page
// of the given page is Valid and Readable/Writable/Executable.
auto PGKd::IsPatchGuardPageAttribute(UINT64 aPageBase)
-> bool
{
const auto vPte = wdk::MiAddressToPte(reinterpret_cast<void*>(aPageBase));
if (IsPageValidReadWriteExecutable(reinterpret_cast<ULONG64>(vPte)))
{
return true;
}
const auto vPde = wdk::MiAddressToPde(reinterpret_cast<void*>(aPageBase));
if (IsPageValidReadWriteExecutable(reinterpret_cast<ULONG64>(vPde)))
{
return true;
}
return false;
}
auto PGKd::FindPatchGuardContextFromBigPagePool()
-> std::vector<std::tuple<wdk::POOL_TRACKER_BIG_PAGES, RandomnessInfo>>
{
auto vResult = std::vector<std::tuple<wdk::POOL_TRACKER_BIG_PAGES, RandomnessInfo>>();
for (;;)
{
auto vOffset = 0UI64;
auto hr = m_Symbols->GetOffsetByName("nt!PoolBigPageTableSize", &vOffset);
if (FAILED(hr))
{
throw std::runtime_error("nt!PoolBigPageTableSize could not be found.");
break;
}
SIZE_T PoolBigPageTableSize = 0;
hr = m_Data->ReadPointersVirtual(1, vOffset, &PoolBigPageTableSize);
if (FAILED(hr))
{
throw std::runtime_error("nt!PoolBigPageTableSize could not be read.");
break;
}
// Read PoolBigPageTable
hr = m_Symbols->GetOffsetByName("nt!PoolBigPageTable", &vOffset);
if (FAILED(hr))
{
throw std::runtime_error("nt!PoolBigPageTable could not be found.");
break;
}
auto PoolBigPageTable = 0UI64;
hr = m_Data->ReadPointersVirtual(1, vOffset, &PoolBigPageTable);
if (FAILED(hr))
{
throw std::runtime_error("nt!PoolBigPageTable could not be read.");
break;
}
auto vReadBytes = 0ul;
auto vTable = std::vector<wdk::POOL_TRACKER_BIG_PAGES>(PoolBigPageTableSize);
hr = m_Data->ReadVirtual(
PoolBigPageTable,
vTable.data(), static_cast<ULONG>(vTable.size() * sizeof(wdk::POOL_TRACKER_BIG_PAGES)),
&vReadBytes);
if (FAILED(hr))
{
throw std::runtime_error("nt!PoolBigPageTable could not be read.");
break;
}
// Walk BigPageTable
Progress vProgress(this);
for (SIZE_T i = 0; i < PoolBigPageTableSize; ++i)
{
if ((i % 0x1000) == 0)
{
++vProgress;
}
const auto& vEntry = vTable[i];
auto vStartAddress = reinterpret_cast<ULONG_PTR>(vEntry.Va);
// Ignore unused entries
if (!vStartAddress || (vStartAddress & 1))
{
continue;
}
// Filter by the size of region
if (MINIMUM_REGION_SIZE > vEntry.NumberOfBytes ||
vEntry.NumberOfBytes > MAXIMUM_REGION_SIZE)
{
continue;
}
if (!IsNonPagedBigPool(vEntry))
{
continue;
}
// Filter by the page protection
if (!IsPatchGuardPageAttribute(vStartAddress))
{
continue;
}
// Read and check randomness of the contents
auto vContents = std::make_unique<std::array<UINT8, EXAMINATION_BYTES>>();
hr = m_Data->ReadVirtual(vStartAddress,
vContents->data(), static_cast<ULONG>(vContents->size()), &vReadBytes);
if (FAILED(hr))
{
continue;
}
const auto vNumberOfDistinctiveNumbers = GetNumberOfDistinctiveNumbers(
vContents->data(), EXAMINATION_BYTES);
const auto vRandomness = GetRamdomness(vContents->data(), EXAMINATION_BYTES);
if (vNumberOfDistinctiveNumbers > MAXIMUM_DISTINCTIVE_NUMBER ||
vRandomness < MINIMUM_RANDOMNESS)
{
continue;
}
// It seems to be a PatchGuard page
vResult.emplace_back(vEntry,
RandomnessInfo{ vNumberOfDistinctiveNumbers, vRandomness, });
}
break;
}
return std::move(vResult);
}
auto PGKd::FindPatchGuardContextFromIndependentPages()
-> std::vector<std::tuple<UINT64, SIZE_T, RandomnessInfo>>
{
auto vResult = std::vector<std::tuple<UINT64, SIZE_T, RandomnessInfo>>();
for (;;)
{
auto vOffset = 0UI64;
auto hr = m_Symbols->GetOffsetByName("nt!MmSystemRangeStart", &vOffset);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmSystemRangeStart could not be found.");
break;
}
auto MmSystemRangeStart = 0UI64;
hr = m_Data->ReadPointersVirtual(1, vOffset, &MmSystemRangeStart);
if (FAILED(hr))
{
throw std::runtime_error("nt!MmSystemRangeStart could not be read.");
break;
}
Progress vProgress(this);
// Walk entire page table (PXE -> PPE -> PDE -> PTE)
// Start parse PXE (PML4) which represents the beginning of kernel address
const auto vStartPxe = reinterpret_cast<UINT64>(
wdk::MiAddressToPxe(reinterpret_cast<void*>(MmSystemRangeStart)));
const auto vEndPxe = wdk::PXE_TOP;
const auto vPxes = GetPtes(wdk::PXE_BASE);
for (auto vCurrentPxe = vStartPxe; vCurrentPxe < vEndPxe; vCurrentPxe += sizeof(wdk::HARDWARE_PTE))
{
// Make sure that this PXE is valid
const auto vPxeIndex = (vCurrentPxe - wdk::PXE_BASE) / sizeof(wdk::HARDWARE_PTE);
const auto vPxe = (*vPxes)[vPxeIndex];
if (!vPxe.Valid)
{
continue;
}
// If the PXE is valid, analyze PPE belonging to this
const auto vStartPpe = wdk::PPE_BASE + 0x1000 * vPxeIndex;
const auto vEndPpe = wdk::PPE_BASE + 0x1000 * (vPxeIndex + 1);
const auto vPpes = GetPtes(vStartPpe);
for (auto vCurrentPpe = vStartPpe; vCurrentPpe < vEndPpe; vCurrentPpe += sizeof(wdk::HARDWARE_PTE))
{
// Make sure that this PPE is valid
const auto vPpeIndex1 = (vCurrentPpe - wdk::PPE_BASE) / sizeof(wdk::HARDWARE_PTE);
const auto vPpeIndex2 = (vCurrentPpe - vStartPpe) / sizeof(wdk::HARDWARE_PTE);
const auto vPpe = (*vPpes)[vPpeIndex2];
if (!vPpe.Valid)
{
continue;
}
// If the PPE is valid, analyze PDE belonging to this
const auto vStartPde = wdk::PDE_BASE + 0x1000 * vPpeIndex1;
const auto vEndPde = wdk::PDE_BASE + 0x1000 * (vPpeIndex1 + 1);
const auto vPdes = GetPtes(vStartPde);
for (auto vCurrentPde = vStartPde; vCurrentPde < vEndPde; vCurrentPde += sizeof(wdk::HARDWARE_PTE))
{
// Make sure that this PDE is valid as well as is not handling
// a large page as an independent page does not use a large page
const auto vPdeIndex1 = (vCurrentPde - wdk::PDE_BASE) / sizeof(wdk::HARDWARE_PTE);
const auto vPdeIndex2 = (vCurrentPde - vStartPde) / sizeof(wdk::HARDWARE_PTE);
const auto vPde = (*vPdes)[vPdeIndex2];
if (!vPde.Valid || vPde.LargePage)
{
continue;
}
++vProgress;
// If the PDE is valid, analyze PTE belonging to this
const auto vStartPte = wdk::PTE_BASE + 0x1000 * vPdeIndex1;
const auto vEndPte = wdk::PTE_BASE + 0x1000 * (vPdeIndex1 + 1);
const auto vPtes = GetPtes(vStartPte);
for (auto vCurrentPte = vStartPte; vCurrentPte < vEndPte; vCurrentPte += sizeof(wdk::HARDWARE_PTE))
{
// Make sure that this PPE is valid,
// Readable/Writable/Executable
const auto vPteIndex2 = (vCurrentPte - vStartPte) / sizeof(wdk::HARDWARE_PTE);
const auto vPte = (*vPtes)[vPteIndex2];
if (!vPte.Valid ||
!vPte.Write ||
vPte.NoExecute)
{
continue;
}
// This page might be PatchGuard page, so let's analyze it
const auto vVirtualAddress = reinterpret_cast<ULONG64>(
wdk::MiPteToAddress(reinterpret_cast<wdk::HARDWARE_PTE*>(vCurrentPte)))
| 0xffff000000000000;
// Read the contents of the address that is managed by the
// PTE
auto vReadBytes = 0ul;
auto vContents = std::make_unique<std::array<std::uint8_t, EXAMINATION_BYTES + sizeof(ULONG64)>>();
hr = m_Data->ReadVirtual(
vVirtualAddress,
vContents->data(), static_cast<ULONG>(vContents->size()),
&vReadBytes);
if (FAILED(hr))
{
continue;
}
// Check randomness of the contents
const auto vNumberOfDistinctiveNumbers =
GetNumberOfDistinctiveNumbers(vContents->data() + sizeof(ULONG64), EXAMINATION_BYTES);
const auto vRandomness =
GetRamdomness(vContents->data() + sizeof(ULONG64), EXAMINATION_BYTES);
if (vNumberOfDistinctiveNumbers > MAXIMUM_DISTINCTIVE_NUMBER ||
vRandomness < MINIMUM_RANDOMNESS)
{
continue;
}
// Also, check the size of the region. The first page of
// allocated pages as independent pages has its own page
// size in bytes at the first 8 bytes
const auto vIndependentPageSize =
*reinterpret_cast<ULONG64*>(vContents->data());
if (MINIMUM_REGION_SIZE > vIndependentPageSize
|| vIndependentPageSize > MAXIMUM_REGION_SIZE)
{
continue;
}
// It seems to be a PatchGuard page
vResult.emplace_back(vVirtualAddress, vIndependentPageSize,
RandomnessInfo{ vNumberOfDistinctiveNumbers, vRandomness, });
}
}
}
}
break;
}
return std::move(vResult);
}
auto PGKd::FindPatchGuardContext()
-> HRESULT
{
HRESULT hr = S_OK;
for (;;)
{
if (IsCurMachine32())
{
throw std::runtime_error("!findpg not support x86 target!");
break;
}
Out("Wait until analysis is completed. It typically takes 2-5 minutes.\n");
Out("Or press Ctrl+Break or [Debug] > [Break] to stop analysis.\n");
if (IsWindowsRS1OrGreater())
{
wdk::MiInitPte(GetPteBase());
}
// Collect PatchGuard pages from NonPagedPool and Independent pages
auto vFoundBigPagePool = FindPatchGuardContextFromBigPagePool();
Out("Phase 1 analysis has been done. [BigPagePool]\n");
auto vFoundIndependent = FindPatchGuardContextFromIndependentPages();
Out("Phase 2 analysis has been done. [IndependentPages]\n");
// Sort data according to its base addresses
std::sort(vFoundBigPagePool.begin(), vFoundBigPagePool.end(),
[](
const decltype(vFoundBigPagePool)::value_type& Lhs,
const decltype(vFoundBigPagePool)::value_type& Rhs)
{
return std::get<0>(Lhs).Va < std::get<0>(Rhs).Va;
});
std::sort(vFoundIndependent.begin(), vFoundIndependent.end(),
[](
const decltype(vFoundIndependent)::value_type& Lhs,
const decltype(vFoundIndependent)::value_type& Rhs)
{
return std::get<0>(Lhs) < std::get<0>(Rhs);
});
// Display collected data
PoolTagNote vPooltag(this);
for (const auto& vItem : vFoundBigPagePool)
{
const auto vDescription = vPooltag.get(std::get<0>(vItem).Tag);
Out("[BigPagePool] PatchGuard context page base: %y, size: 0x%08x,"
" Randomness %3d:%3d,%s\n",
std::get<0>(vItem).Va, std::get<0>(vItem).NumberOfBytes,
std::get<1>(vItem).NumberOfDistinctiveNumbers,
std::get<1>(vItem).Ramdomness,
vDescription.c_str());
}
for (const auto& vItem : vFoundIndependent)
{
Out("[Independent] PatchGuard context page base: %y, Size: 0x%08x,"
" Randomness %3d:%3d,\n",
std::get<0>(vItem), std::get<1>(vItem),
std::get<2>(vItem).NumberOfDistinctiveNumbers,
std::get<2>(vItem).Ramdomness);
}
break;
}
return hr;
}
auto PGKd::GetPGContextTypeString(
UINT64 aErrorWasFound,
UINT64 aTypeOfCorruption)
-> LPCSTR
{
// Reference:
// https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/bug-check-0x109---critical-structure-corruption
if (!aErrorWasFound)
{
return "N/A";
}
switch (aTypeOfCorruption)
{
case 0x0000: return "A generic data region";
case 0x0001: return "A function modification or the Itanium-based function location";
case 0x0002: return "A processor interrupt dispatch table (IDT)";
case 0x0003: return "A processor global descriptor table (GDT)";
case 0x0004: return "A type-1 process list corruption";
case 0x0005: return "A type-2 process list corruption";
case 0x0006: return "A debug routine modification";
case 0x0007: return "A critical MSR modification";
case 0x0008: return "Object type";
case 0x0009: return "A processor IVT";
case 0x000A: return "Modification of a system service function";
case 0x000B: return "A generic session data region";
case 0x000C: return "Modification of a session function or .pdata";
case 0x000D: return "Modification of an import table";
case 0x000E: return "Modification of a session import table";
case 0x000F: return "Ps Win32 callout modification";
case 0x0010: return "Debug switch routine modification";
case 0x0011: return "IRP allocator modification";
case 0x0012: return "Driver call dispatcher modification";
case 0x0013: return "IRP completion dispatcher modification";
case 0x0014: return "IRP deallocator modification";
case 0x0015: return "A processor control register";
case 0x0016: return "Critical floating point control register modification";
case 0x0017: return "Local APIC modification";
case 0x0018: return "Kernel notification callout modification";
case 0x0019: return "Loaded module list modification";
case 0x001A: return "Type 3 process list corruption";
case 0x001B: return "Type 4 process list corruption";
case 0x001C: return "Driver object corruption";
case 0x001D: return "Executive callback object modification";
case 0x001E: return "Modification of module padding";
case 0x001F: return "Modification of a protected process";
case 0x0020: return "A generic data region";
case 0x0021: return "A page hash mismatch";
case 0x0022: return "A session page hash mismatch";
case 0x0023: return "Load config directory modification";
case 0x0024: return "Inverted function table modification";
case 0x0025: return "Session configuration modification";
case 0x0026: return "An extended processor control register";
case 0x0027: return "Type 1 pool corruption";
case 0x0028: return "Type 2 pool corruption";
case 0x0029: return "Type 3 pool corruption";
case 0x002A: return "Type 4 pool corruption";
case 0x002B: return "Modification of a function or .pdata";
case 0x002C: return "Image integrity corruption";
case 0x002D: return "Processor misconfiguration";
case 0x002E: return "Type 5 process list corruption";
case 0x002F: return "Process shadow corruption";
case 0x0101: return "General pool corruption";
case 0x0102: return "Modification of win32k.sys";
case 0x0103: return "MmAttachSession failure";
case 0x0104: return "KeInsertQueueApc failure";
case 0x0105: return "RtlImageNtHeader failure";
case 0x0106: return "CcBcbProfiler detected modification";
case 0x0107: return "KiTableInformation corruption";
case 0x0108: return "Not investigated :(";
case 0x0109: return "Type 2 context modification";
case 0x010E: return "Inconsistency between before and after sleeping";
default: break;
}
return "Unknown :(";
}
auto PGKd::DumpPatchGuardContextForType106(
UINT64 aFailureDependent)
-> void
{
static const char DUMP_FORMAT[] = R"RAW(
PatchGuard Context : %y, An address of PatchGuard context
Validation Data : %y, An address of validation data that caused the error
Type of Corruption : Available %I64d : %I64x : %s
Failure type dependent information : %y
)RAW";
static const auto TYPE_OF_CORRUPTION = 0x106ull;
const auto vTypeString = GetPGContextTypeString(true, TYPE_OF_CORRUPTION);
Out(DUMP_FORMAT,
0ull,
0ull,
1ull, TYPE_OF_CORRUPTION, vTypeString,
aFailureDependent);
}
template<>
auto PGKd::DumpPatchGuardContext(
UINT64 aPGContext,
UINT64 aPGReason,
UINT64 aFailureDependent,
UINT64 aTypeOfCorruption,
wdk::build_7601::PGContext& aContext)
-> HRESULT
{
static const char DUMP_FORMAT[] = R"RAW(
PatchGuard Context : %y, An address of PatchGuard context
Validation Data : %y, An address of validation data that caused the error
Type of Corruption : Available %I64d : %I64x : %s
Failure type dependent information : %y
Allocated memory base : %y
Prcb : %y
PGSelfValidation : %y
RtlLookupFunctionEntryEx : %y
FsRtlUninitializeSmallMcb : %y
FsRtlMdlReadCompleteDevEx : %y
PGProtectCode2[?] : %y
ContextSizeInBytes : %08x (Can be broken)
DPC Routine : %y
WorkerRoutine : %y
Protected IDT Items : %y[%08x]
Protected Codes Table : %y[%08x]
Protected Values Table : %y[%08x]
)RAW";
auto FsRtlUninitializeSmallMcb = 0I64;
auto hr = m_Symbols->GetOffsetByName("nt!FsRtlUninitializeSmallMcb", (PUINT64)&FsRtlUninitializeSmallMcb);
if (FAILED(hr))
{
return hr;
}
auto FsRtlMdlReadCompleteDevEx = 0I64;
hr = m_Symbols->GetOffsetByName("nt!FsRtlMdlReadCompleteDevEx", (PUINT64)&FsRtlMdlReadCompleteDevEx);
if (FAILED(hr))
{
return hr;
}
auto vFsRtlXXXOffset = FsRtlUninitializeSmallMcb - FsRtlMdlReadCompleteDevEx;
auto vPGContext = aPGContext;
auto vPGReason = aPGReason;
auto vFailureDependent = aFailureDependent;
auto vTypeOfCorruption = aTypeOfCorruption;
auto vPGSelfValidation = aPGContext + aContext.OffsetOfPGSelfValidation;
auto vFsRtlUninitializeSmallMcb = aPGContext + aContext.OffsetOfFsRtlUninitializeSmallMcb;
auto vFsRtlMdlReadCompleteDevEx = vFsRtlUninitializeSmallMcb - vFsRtlXXXOffset;
auto vRtlLookupFunctionEntryEx = aPGContext + aContext.OffsetOfRtlLookupFunctionEntryEx;
auto vPGProtectCode2Table = aContext.OffsetOfPGProtectCode2Table ? aPGContext + aContext.OffsetOfPGProtectCode2Table : 0;
auto vProtectIDTItems = aPGContext + offsetof(std::remove_reference_t<decltype(aContext)>, PGProtectIDTItems);
auto vProtectCodes = aPGContext + sizeof(aContext);
auto vProtectValues = vProtectCodes + (sizeof(wdk::PGProtectCode) * aContext.NumberOfProtectCodes);
if (aContext.IsTiggerPG)
{
vPGContext = aContext.BugCheckArg0 - BUGCHECK_109_ARGS0_KEY;
vPGReason = aContext.BugCheckArg1 - BUGCHECK_109_ARGS1_KEY;
vFailureDependent = aContext.BugCheckArg2;
vTypeOfCorruption = aContext.BugCheckArg3;
}
const auto vTypeString = GetPGContextTypeString(aContext.IsTiggerPG, vTypeOfCorruption);
Out(DUMP_FORMAT,
vPGContext,
vPGReason,
aContext.IsTiggerPG, vTypeOfCorruption, vTypeString,
vFailureDependent,
aContext.PGPageBase,
aContext.Prcb,
vPGSelfValidation,
vRtlLookupFunctionEntryEx,
vFsRtlUninitializeSmallMcb,
vFsRtlMdlReadCompleteDevEx,
vPGProtectCode2Table,
aContext.ContextSizeInQWord * sizeof(UINT64) + sizeof(std::remove_reference_t<decltype(aContext)>::PGContextHeader),
aContext.DcpRoutineToBeScheduled,
aContext.WorkerRoutine,
vProtectIDTItems, _countof(aContext.PGProtectIDTItems),
vProtectCodes, aContext.NumberOfProtectCodes,
vProtectValues, aContext.NumberOfProtectValues);
return S_OK;
}
template<>
auto PGKd::DumpPatchGuardContext(
UINT64 aPGContext,
UINT64 aPGReason,
UINT64 aFailureDependent,
UINT64 aTypeOfCorruption,
wdk::build_9200::PGContext & aContext)
-> HRESULT
{
static const char DUMP_FORMAT[] = R"RAW(
PatchGuard Context : %y, An address of PatchGuard context
Validation Data : %y, An address of validation data that caused the error
Type of Corruption : Available %I64d : %I64x : %s
Failure type dependent information : %y
Allocated memory base : %y
Prcb : %y
PGSelfValidation : %y
RtlLookupFunctionEntryEx : %y
FsRtlUninitializeSmallMcb : %y
FsRtlMdlReadCompleteDevEx : %y
ContextSizeInBytes : %08x (Can be broken)
DPC Routine : %y
WorkerRoutine : %y
Protected IDT Items : %y[%08x]
Protected Strings Table : %y[%08x]
Protected Codes Table : %y[%08x]