forked from tandasat/hvext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhvext.js
1194 lines (1084 loc) · 43.1 KB
/
hvext.js
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
"use strict";
// Registers commands.
function initializeScript() {
return [
new host.apiVersionSupport(1, 7),
new host.functionAlias(hvextHelp, "hvext_help"),
new host.functionAlias(dumpDmar, "dump_dmar"),
new host.functionAlias(dumpEpt, "dump_ept"),
new host.functionAlias(dumpIo, "dump_io"),
new host.functionAlias(dumpMsr, "dump_msr"),
new host.functionAlias(dumpVmcs, "dump_vmcs"),
new host.functionAlias(eptPte, "ept_pte"),
new host.functionAlias(indexesFor, "indexes"),
new host.functionAlias(pte, "pte"),
];
}
// Cache of fully-parsed EPT, keyed by EPTP.
let g_eptCache = {};
// The virtual address of (the first) "VMREAD RAX, RAX" in the HV image range.
let g_vmreadAddress = null;
// Initializes the extension.
function invokeScript() {
exec(".load kext");
g_vmreadAddress = findFirstVmreadRaxRax();
println("hvext loaded. Execute !hvext_help [command] for help.");
// Returns the first virtual address with "VMREAD RAX, RAX" in the HV address range.
function findFirstVmreadRaxRax() {
const isVmreadRaxRax = (memory, i) => (
memory[i] == 0x0f &&
memory[i + 1] == 0x78 &&
memory[i + 2] == 0xc0
);
// Search each page in the HV image range. Returns the first hit.
let hvImageRange = findHvImageRange();
for (let i = hvImageRange.Start; i.compareTo(hvImageRange.End) == -1; i = i.add(0x1000)) {
let found = searchMemory(i, 0x1000, isVmreadRaxRax);
if (found.length != 0) {
return found[0];
}
}
throw new Error("No VMREAD RAX, RAX (0f 78 c0) found.");
// Returns the range of the virtual address where the HV image is mapped.
function findHvImageRange() {
// Get the range with "lm".
// eg: fffff876`b89e0000 fffff876`b8de2000 hv (no symbols)
let chunks = exec("lm m hv").Last().split(" ");
let start = chunks[0].replace("`", "");
let end = chunks[1].replace("`", "");
return {
"Start": host.parseInt64(start, 16),
"End": host.parseInt64(end, 16),
};
}
// Finds an array of virtual addresses that matches the specified condition.
function searchMemory(address, bytes, predicate) {
// Memory read can fail if the address is not mapped.
try {
var memory = host.memory.readMemoryValues(address, bytes);
} catch (error) {
return [];
}
let index = [];
for (let i = 0; i < bytes; i++) {
if (predicate(memory, i)) {
index.push(address.add(i));
}
}
return index;
}
}
}
// Implements the !hvext_help command.
function hvextHelp(command) {
switch (command) {
case "dump_dmar":
println("dump_dmar [pa] - Displays status and configurations of a DMA remapping unit.");
println(" pa - The PA of a DMAR remapping unit. It can be found in the DMAR ACPI table.");
break;
case "dump_ept":
println("dump_ept [verbosity] - Displays contents of the EPT translation for the current EPTP.");
println(" verbosity - 0 = Shows valid translations in a summarized format (default).");
println(" 1 = Shows both valid and invalid translations in a summarized format.");
println(" 2 = Shows every valid translations without summarizing it.");
break;
case "dump_io":
println("dump_io - Displays contents of the IO bitmaps.");
break;
case "dump_msr":
println("dump_msr [verbosity] - Displays contents of the MSR bitmaps.");
println(" verbosity - 0 = Shows only MSRs that are not read or write protected (default).");
println(" 1 = Shows protections of all MSRs managed by the MSR bitmaps.");
break;
case "dump_vmcs":
println("dump_vmcs - Displays contents of all VMCS encodings for ths current VMCS.");
break;
case "ept_pte":
println("ept_pte [gpa] - Displays contents of EPT entries used to translated the given GPA");
println(" gpa - A GPA to translate with EPT (default= 0).");
break;
case "indexes":
println("indexes [address] - Displays index values to walk paging structures for the given address.");
println(" address - An address to decode (default= 0).");
break;
case "pte":
println("pte [la] - Displays contents of paging structure entries used to translated the given LA.");
println(" la - A LA to translate with the paging structures (default= 0).");
break;
case undefined:
default:
println("hvext_help [command] - Displays this message.");
println("dump_dmar [pa] - Displays status and configurations of a DMA remapping unit.");
println("dump_ept [verbosity] - Displays contents of the EPT translation for the current EPTP.");
println("dump_io - Displays contents of the IO bitmaps.");
println("dump_msr [verbosity] - Displays contents of the MSR bitmaps.");
println("dump_vmcs - Displays contents of all VMCS encodings for ths current VMCS.");
println("ept_pte [gpa] - Displays contents of EPT entries used to translated the given GPA.");
println("indexes [address] - Displays index values to walk paging structures for the given address.");
println("pte [la] - Displays contents of paging structure entries used to translated the given LA.");
println("");
println("Note: When executing some of those commands, the processor must be in VMX-root operation with an active VMCS.");
break;
}
}
// Implements the !dump_dmar command.
function dumpDmar(baseAddr, verbosity) {
// See: 9.1 Root Entry
class RootEntry {
constructor(bus, low64, _high64) {
// The higher 64 bits are "Reserved".
this.value = low64;
this.bus = bus;
this.present = bits(low64, 0, 1);
this.contextTablePointer = low64.bitwiseAnd(~0xfff);
this.contextEntries = [];
}
}
// See: 9.3 Context Entry
class ContextEntry {
constructor(device, func, low64, high64) {
this.value = low64;
this.device = device;
this.func = func;
this.present = bits(low64, 0, 1);
this.translationType = bits(low64, 2, 2);
this.ssptPointer = (this.translationType == 0b10) ? "Passthrough" : low64.bitwiseAnd(~0xfff);
this.domainId = bits(high64, 9, 16);
}
}
class DeviceTranslation {
constructor(rootEntry, contextEntry) {
this.bus = (rootEntry) ? rootEntry.bus : 0;
this.device = (contextEntry) ? contextEntry.device : 0;
this.func = (contextEntry) ? contextEntry.func : 0;
this.passthrough = (contextEntry) ? (contextEntry.translationType == 0b10) : false;
this.ssptPointer = (contextEntry) ? contextEntry.ssptPointer : 0;
}
toString() {
return (this.passthrough ? "Passthrough" : hex(this.ssptPointer)) + " - " + this.bdf();
}
bdf() {
return "B" + this.bus + ",D" + this.device + ",F" + this.func;
}
}
if (baseAddr === undefined) {
println("Specify a physical address of the remapping hardware unit. " +
"It is typically 0xfed90000 and 0xfed91000 but may vary between models.");
return;
}
if (verbosity === undefined) {
verbosity = 0;
}
// Read remapping hardware registers.
// See: 11.4 Register Descriptions
//
// 2: kd> !dq 0xfed90000 l6
// #fed90000 00000000`00000010 01c0000c`40660462
// #fed90010 0000019e`2ff0505e c7000000`00000000
// #fed90020 00000001`044fe000 08000000`00000000
let qwords = [];
parseEach16Bytes(baseAddr.bitwiseAnd(~0xfff), 3, (l, h) => qwords.push(l, h));
let version = qwords[0]; // 11.4.1 Version Register
let capability = qwords[1]; // 11.4.2 Capability Register
let capabilityEx = qwords[2]; // 11.4.3 Extended Capability Register
let status = bits(qwords[3], 32, 32); // 11.4.4 Global Command Interface Registers
let rootTableAddr = qwords[4]; // 11.4.5 Root Table Address Register
println("Remapping unit at " + hex(baseAddr));
println(" version: " + bits(version, 4, 4) + "." + bits(version, 0, 4));
println(" capability: " + hex(capability));
println(" extended capability: " + hex(capabilityEx));
println(" status: " + hex(status));
println(" root table address: " + hex(rootTableAddr));
println("");
// Bail if DMA remapping is not enabled.
let translationEnableStatus = bits(status, 31, 1);
if (translationEnableStatus == 0) {
println("DMA remapping is not enabled.");
return;
}
// Bail if not in the legacy translation mode.
let translationTableMode = bits(rootTableAddr, 10, 2);
if (translationTableMode != 0b00) {
println("Unsupported TTM.");
return;
}
// Parse the root table.
// See: 3.4.2 Legacy Mode Address Translation
let rootEntries = [];
parseEach16Bytes(rootTableAddr.bitwiseAnd(~0xfff), 0x100, (l, h) =>
rootEntries.push(new RootEntry(rootEntries.length, l, h)));
// Parse the context tables referenced from the root entries.
// See: 3.4.2 Legacy Mode Address Translation
for (let rootEntry of rootEntries) {
parseEach16Bytes(rootEntry.contextTablePointer, 0x100, (l, h) =>
rootEntry.contextEntries.push(new ContextEntry(
bits(rootEntry.contextEntries.length, 3, 5),
bits(rootEntry.contextEntries.length, 0, 3),
l,
h)));
}
// First, print which BDF is translated with which second stage page table
// (SSPT) structures. There are 65536 BDFs, but only a handful of SSPTs are
// used. So, summarize relation and gather the SSPTs into `ssptPointers`.
println("Translation Device");
let ssptPointers = [];
let start = new DeviceTranslation();
let previous = new DeviceTranslation();
for (let rootEntry of rootEntries) {
for (let contextEntry of rootEntry.contextEntries) {
let current = new DeviceTranslation(rootEntry, contextEntry);
// If the current entry points to a different SSPT than before...
if (current.ssptPointer != start.ssptPointer) {
// Print it out (except the very first entry).
if (start.ssptPointer != 0) {
if (start == previous) {
println(previous);
} else {
println(start + " .. " + previous.bdf());
}
}
// Save the SSPT except when it is pass-through, and record the
// current entry as a new start.
if (!current.passthrough) {
ssptPointers.push(current.ssptPointer);
}
start = current;
}
previous = current;
}
}
// Print the last entry.
if (start == previous) {
println(previous);
} else {
println(start + " .. " + previous.bdf());
}
// Dump the all unique SSPTs. SSPTs have the same format as the EPT entries.
for (let ssptPointer of Array.from(new Set(ssptPointers))) {
println("");
println("Dumping second stage page tables at " + hex(ssptPointer));
dumpEpt(verbosity, getEptPml4(ssptPointer));
}
}
// Implements the !dump_ept command.
function dumpEpt(verbosity = 0, pml4) {
class Region {
constructor(gpa, pa, flags, size) {
this.gpa = gpa;
this.pa = pa;
this.flags = flags;
this.size = size;
this.identifyMapping = (gpa == pa);
}
toString() {
// If this is identify mapping, display so instead of actual PA.
let translation = (this.identifyMapping) ?
"Identity".padEnd(12) :
hex(this.pa).padStart(12);
return hex(this.gpa).padStart(12) + " - " +
hex(this.gpa + this.size).padStart(12) + " -> " +
translation + " " +
this.flags;
}
}
const SIZE_4KB = 0x1000;
const SIZE_2MB = 0x200000;
const SIZE_1GB = 0x40000000;
const SIZE_512GB = 0x8000000000;
if (pml4 === undefined) {
pml4 = getCurrentEptPml4();
}
// Walk through all EPT entries and accumulate them as regions.
let regions = [];
for (let gpa = 0, page_size = 0; ; gpa += page_size) {
let indexFor = indexesFor(gpa);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Exit once GPA exceeds its max value (48bit-width).
if (gpa > 0xfffffffff000) {
break;
}
// Pick and check PML4e.
page_size = SIZE_512GB;
let pml4e = pml4.entries[i4];
if (!pml4e.flags.present()) {
continue;
}
// Pick and check PDPTe.
page_size = SIZE_1GB;
let pdpt = pml4e.nextTable;
let pdpte = pdpt.entries[i3];
if (!pdpte.flags.present()) {
continue;
}
if (pdpte.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte);
regions.push(new Region(gpa, pdpte.pfn.bitwiseShiftLeft(12), flags, page_size));
continue;
}
// Pick and check PDe.
page_size = SIZE_2MB;
let pd = pdpte.nextTable;
let pde = pd.entries[i2];
if (!pde.flags.present()) {
continue;
}
if (pde.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte, pde);
regions.push(new Region(gpa, pde.pfn.bitwiseShiftLeft(12), flags, page_size));
continue;
}
// Pick and check PTe.
page_size = SIZE_4KB;
let pt = pde.nextTable;
let pte = pt.entries[i1];
if (!pte.flags.present()) {
continue;
}
let flags = getEffectiveFlags(pml4e, pdpte, pde, pte);
regions.push(new Region(gpa, pte.pfn.bitwiseShiftLeft(12), flags, page_size));
}
// Display gathered regions.
if (verbosity == 2) {
// Just dump all regions.
println("GPA PA Flags");
for (let region of regions) {
println(hex(region.gpa).padStart(12) + " -> " +
hex(region.pa).padStart(12) + " " +
region.flags);
}
} else {
println("GPA PA Flags");
// Combine regions that are effectively contiguous.
let current_region = null;
for (let region of regions) {
if (current_region === null) {
current_region = region;
continue;
}
// Is this region contiguous to the current region? That is, both
// identify mapped, have the same flags and corresponding GPAs are
// contiguous.
if (current_region.identifyMapping &&
region.identifyMapping &&
current_region.flags.toString() == region.flags.toString() &&
current_region.gpa + current_region.size == region.gpa) {
// It is contiguous. Just expand the size.
current_region.size += region.size;
} else {
// It is not. Display the current region.
println(current_region);
// If not, see if there is an unmapped regions before this region.
if (verbosity == 1 &&
current_region.gpa + current_region.size != region.gpa) {
// Yes, there is. Display that.
let unmapped_base = current_region.gpa + current_region.size;
let unmapped_size = region.gpa - unmapped_base;
println(hex(unmapped_base).padStart(12) + " - " +
hex(unmapped_base + unmapped_size).padStart(12) + " -> " +
"Unmapped".padEnd(12) + " " +
new EptFlags(0));
}
// Move on, and start checking contiguous regions from this region.
current_region = region;
}
}
// Display the last one.
println(current_region);
}
// Computes the effective flag value from the given EPT entries. The large bit
// is always reported as 0.
function getEffectiveFlags(pml4e, pdpte, pde, pte) {
let flags = new EptFlags(0);
flags.read = pml4e.flags.read & pdpte.flags.read;
flags.write = pml4e.flags.write & pdpte.flags.write;
flags.execute = pml4e.flags.execute & pdpte.flags.execute;
flags.executeForUserMode = pml4e.flags.executeForUserMode & pdpte.flags.executeForUserMode;
let leaf = pdpte;
if (pde) {
leaf = pde;
flags.read &= pde.flags.read;
flags.write &= pde.flags.write;
flags.execute &= pde.flags.execute;
flags.executeForUserMode &= pde.flags.executeForUserMode;
}
if (pte) {
leaf = pte;
flags.read &= pte.flags.read;
flags.write &= pte.flags.write;
flags.execute &= pte.flags.execute;
flags.executeForUserMode &= pte.flags.executeForUserMode;
}
flags.memoryType = leaf.flags.memoryType;
flags.verifyGuestPaging = leaf.flags.verifyGuestPaging;
flags.pagingWriteAccess = leaf.flags.pagingWriteAccess;
flags.supervisorShadowStack = leaf.flags.supervisorShadowStack;
return flags;
}
}
// Implements the !dump_io command.
function dumpIo() {
class IoAccessibilityRange {
constructor(begin = undefined, end = undefined, intercepted = undefined) {
this.begin = begin;
this.end = end;
this.intercepted = intercepted;
}
toString() {
return (this.intercepted ? "-- " : "RW ") + hex(this.begin) +
(this.begin == this.end ? "" : " .. " + hex(this.end));
}
}
let exec_control = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control, 25, 1) == 0) {
// Check "unconditional I/O exiting"
if (bits(exec_control, 24, 1) == 0) {
println("IO bitmaps are not used. IO port access does not cause VM-exit.");
} else {
println("IO port access unconditionally causes VM-exit.");
}
return;
}
let bitmap_low = readVmcs(0x00002000); // I/O bitmap A
let bitmap_high = readVmcs(0x00002002); // I/O bitmap B
// Convert the 4KB contents into an array of 64bit integers for processing.
let entries = [];
parseEach16Bytes(bitmap_low, 0x100, (l, h) => entries.push(l, h));
parseEach16Bytes(bitmap_high, 0x100, (l, h) => entries.push(l, h));
let ranges = [];
let range = undefined;
let port = 0;
for (let entry of entries) {
for (let bit_position = 0; bit_position < 64; bit_position++, port++) {
let intercepted = bits(entry, bit_position, 1);
if (port == 0) {
range = new IoAccessibilityRange(port, port, intercepted);
} else if (range.intercepted == intercepted) {
// Interception status remained same. Just extend the range.
range.end = port;
} else {
// Interception status changed. Save the range and start a new one.
ranges.push(range);
range = new IoAccessibilityRange(port, port, intercepted);
}
}
}
ranges.push(range);
ranges.map(println);
}
// Implements the !dump_msr command.
function dumpMsr(verbosity = 0) {
class MsrEntry {
constructor(bit_position, read_protected, write_protected) {
if (bit_position < 0x2000) {
this.msr = bit_position;
} else {
this.msr = bit_position - 0x2000 + 0xc0000000;
}
this.read_protected = read_protected;
this.write_protected = write_protected;
}
toString() {
return (
{ 1: "-", 0: "R" }[this.read_protected] +
{ 1: "-", 0: "W" }[this.write_protected] +
" " +
hex(this.msr)
);
}
}
let exec_control = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control, 28, 1) == 0) {
println("MSR bitmaps are not used. MSR access unconditionally causes VM-exit.");
return;
}
let bitmap = readVmcs(0x00002004); // MSR bitmaps
// Convert the 4KB contents into an array of 64bit integers for processing.
let entries = [];
parseEach16Bytes(bitmap.bitwiseAnd(~0xfff), 0x100, (l, h) => entries.push(l, h));
// The MSR bitmaps are made up of two 2048 bytes segments. The first segment
// manages read access, and the 2nd manages write access, for the same ranges
// of MSRs. Let us walk the half of the `entries` and add offset 2048
// (= 0x100 * 8) to look both segments in a single loop.
let msrs = [];
for (let i = 0; i < 0x100; i++) {
let entry_low = entries[i];
let entry_hi = entries[i + 0x100];
// For the selected upper and lower 64bit entries, walk though each bit
// position and construct `MsrEntry` from the pair of the bits.
for (let bit_position = 0; bit_position < 64; bit_position++) {
let read_protected = bits(entry_low, bit_position, 1);
let write_protected = bits(entry_hi, bit_position, 1);
msrs.push(new MsrEntry(i * 64 + bit_position, read_protected, write_protected));
}
}
for (let msr of msrs) {
if (verbosity == 0) {
if (!msr.read_protected || !msr.write_protected) {
println(msr);
}
} else {
println(msr);
}
}
}
// Implements the !dump_vmcs command.
function dumpVmcs() {
// Capture the current state.
// eg: efl=00000242 rax=0000000000006c1c rip=fffff813d4f00ea1
let output = exec("r efl, rax, rip").Last();
let originalRflags = output.substring(4, 12);
let originalRax = output.substring(17, 33);
let originalRip = output.substring(38, 54);
// Loop over the VMCS encodings.
for (let i = 0; i < VMCS_ENCODINGS.length; i += 2) {
let name = VMCS_ENCODINGS[i];
let encoding = VMCS_ENCODINGS[i + 1];
let value = readVmcsUnsafe(encoding);
if (value === undefined) {
println("***** FAILED *****" + " " + name);
} else {
println(hex(value, 16) + " " + name);
}
}
// All done. Restore the original state.
exec("r rax=" + originalRax + ", " +
"rip=" + originalRip + ", " +
"efl=" + originalRflags);
}
// Implements the !ept_pte command.
function eptPte(gpa) {
if (gpa == undefined) {
gpa = 0;
}
let indexFor = indexesFor(gpa);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Pick and check PML4e.
let pml4 = getCurrentEptPml4();
let pml4e = pml4.entries[i4];
if (!pml4e.flags.present()) {
println("PML4e at " + hex(pml4.address.add(8 * i4)));
println("contains " + hex(pml4e.value));
println("pfn " + pml4e);
return;
}
// Pick and check PDPTe.
let pdpt = pml4e.nextTable;
let pdpte = pdpt.entries[i3];
if (!pdpte.flags.present() || pdpte.flags.large) {
println("PML4e at " + hex(pml4.address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdpt.address.add(8 * i3)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte);
return;
}
// Pick and check PDe.
let pd = pdpte.nextTable;
let pde = pd.entries[i2];
if (!pde.flags.present() || pde.flags.large) {
println("PML4e at " + hex(pml4.address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdpt.address.add(8 * i3)) + " " +
"PDe at " + hex(pd.address.add(8 * i2)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value) + " " +
"contains " + hex(pde.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte + " " +
"pfn " + pde);
return;
}
// Pick PTe.
let pt = pde.nextTable;
let pte = pt.entries[i1];
println("PML4e at " + hex(pml4.address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdpt.address.add(8 * i3)) + " " +
"PDe at " + hex(pd.address.add(8 * i2)) + " " +
"PTe at " + hex(pt.address.add(8 * i1)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value) + " " +
"contains " + hex(pde.value) + " " +
"contains " + hex(pte.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte + " " +
"pfn " + pde + " " +
"pfn " + pte);
}
// Implements the !indexes command.
function indexesFor(address) {
if (address == undefined) {
address = 0;
}
return {
"Pt": bits(address, 12, 9),
"Pd": bits(address, 21, 9),
"Pdpt": bits(address, 30, 9),
"Pml4": bits(address, 39, 9),
};
}
// Implements the !pte command.
function pte(la) {
if (la == undefined) {
la = 0;
}
let indexFor = indexesFor(la);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Pick and check PML4e.
let pml4Address = host.currentThread.Registers.Kernel.cr3.bitwiseAnd(~0xfff);
let pml4e = new PsEntry(readEntry(pml4Address + 8 * i4));
if (!pml4e.flags.present()) {
println("PML4e at " + hex(pml4Address.add(8 * i4)));
println("contains " + hex(pml4e.value));
println("pfn " + pml4e);
return;
}
// Pick and check PDPTe.
let pdptAddress = pml4e.pfn.bitwiseShiftLeft(12);
let pdpte = new PsEntry(readEntry(pdptAddress + 8 * i3));
if (!pdpte.flags.present() || pdpte.flags.large) {
println("PML4e at " + hex(pml4Address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdptAddress.add(8 * i3)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte);
return;
}
// Pick and check PDe.
let pdAddress = pdpte.pfn.bitwiseShiftLeft(12);
let pde = new PsEntry(readEntry(pdAddress + 8 * i2));
if (!pde.flags.present() || pde.flags.large) {
println("PML4e at " + hex(pml4Address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdptAddress.add(8 * i3)) + " " +
"PDe at " + hex(pdAddress.add(8 * i2)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value) + " " +
"contains " + hex(pde.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte + " " +
"pfn " + pde);
return;
}
// Pick PTe.
let ptAddress = pde.pfn.bitwiseShiftLeft(12);
let pte = new PsEntry(readEntry(ptAddress + 8 * i1));
println("PML4e at " + hex(pml4Address.add(8 * i4)) + " " +
"PDPTe at " + hex(pdptAddress.add(8 * i3)) + " " +
"PDe at " + hex(pdAddress.add(8 * i2)) + " " +
"PTe at " + hex(ptAddress.add(8 * i1)));
println("contains " + hex(pml4e.value) + " " +
"contains " + hex(pdpte.value) + " " +
"contains " + hex(pde.value) + " " +
"contains " + hex(pte.value));
println("pfn " + pml4e + " " +
"pfn " + pdpte + " " +
"pfn " + pde + " " +
"pfn " + pte);
function readEntry(address) {
let line = exec("!dq " + hex(address) + " l1").Last();
return host.parseInt64(line.replace(/`/g, "").substring(10).trim().split(" "), 16);
}
}
// Returns fully-parsed EPT entries pointed by the current EPTP VMCS encoding.
function getCurrentEptPml4() {
let exec_control1 = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control1, 31, 1) == 0) {
throw new Error("EPT is not enabled");
}
let exec_control2 = readVmcs(0x0000401E); // Secondary processor-based VM-execution controls
if (bits(exec_control2, 1, 1) == 0) {
throw new Error("EPT is not enabled");
}
let eptp = readVmcs(0x0000201A); // EPT pointer
if (eptp === undefined) {
throw new Error("The VMREAD instruction failed");
}
println("Current EPT pointer " + hex(eptp));
return getEptPml4(eptp.bitwiseAnd(~0xfff));
}
// Returns fully-parsed EPT entries rooted from the specified address.
function getEptPml4(pml4Addr) {
// If this EPT is already in cache, return it.
if (g_eptCache[pml4Addr]) {
return g_eptCache[pml4Addr];
}
// Otherwise, parse it and populate cache.
g_eptCache[pml4Addr] = new EptPml4(pml4Addr);
return g_eptCache[pml4Addr];
}
// Reads a VMCS encoding.
function readVmcs(encoding) {
// Capture the current state.
// eg: efl=00000242 rax=0000000000006c1c rip=fffff813d4f00ea1
let output = exec("r efl, rax, rip").Last();
let originalRflags = output.substring(4, 12);
let originalRax = output.substring(17, 33);
let originalRip = output.substring(38, 54);
let value = readVmcsUnsafe(encoding);
// All done. Restore the original state.
exec("r rax=" + originalRax + ", " +
"rip=" + originalRip + ", " +
"efl=" + originalRflags);
return value;
}
// Reads a VMCS encoding without restoring register values.
function readVmcsUnsafe(encoding) {
// Jump (back) to "VMREAD RAX, RAX", update RAX with encoding to read,
// and execute the instruction.
exec("r rip=" + hex(g_vmreadAddress) + ", rax=" + hex(encoding));
if (exec("p").Last().includes("second chance")) {
throw new Error("CPU exception occurred with the VMREAD instruction." +
" Reboot the system with the .reboot command. This can happen" +
" when the system in an early boot stage where the processor is" +
" not in VMX operation.");
}
// Check whether the VMREAD instruction succeeded.
// eg: efl=00000342 rax=0000000000000000
let output = exec("r efl, rax").Last();
let flags = host.parseInt64(output.substring(4, 12), 16);
if ((flags & 0x41) == 0) { // if CF==0 && ZF==0
// Succeeded. RAX should contain the field value.
return host.parseInt64(output.substring(17, 33), 16);
} else {
// VMREAD failed.
return undefined;
}
}
class EptPml4 {
constructor(address) {
this.address = address;
this.entries = readPageAsTable(address, EptPdpt);
}
}
class EptPdpt {
constructor(address) {
this.address = address;
this.entries = readPageAsTable(address, EptPd);
}
}
class EptPd {
constructor(address) {
this.address = address;
this.entries = readPageAsTable(address, EptPt);
}
}
class EptPt {
constructor(address) {
this.address = address;
this.entries = readPageAsTable(address);
}
}
// Reads a physical address for 4KB and constructs a table with 512 EPT entries.
function readPageAsTable(address, nextTableType) {
let entries = [];
parseEach16Bytes(address.bitwiseAnd(~0xfff), 0x100, (l, h) =>
entries.push(new EptEntry(l, nextTableType), new EptEntry(h, nextTableType)));
return entries;
}
// Represents a single paging structure entry for any level of the tables.
class PsEntry {
constructor(entry) {
this.value = entry;
this.flags = new PsFlags(entry);
this.pfn = bits(entry, 12, 40);
}
toString() {
return hex(this.pfn) + " " + this.flags;
}
}
// Partial representation of flags bits in any paging structure entries. Only
// bits we care are represented.
// See: Figure 4-11. Formats of CR3 and Paging-Structure Entries with 4-Level Paging and 5-Level Paging
class PsFlags {
constructor(entry) {
this.valid = bits(entry, 0, 1);
this.write = bits(entry, 1, 1);
this.user = bits(entry, 2, 1);
this.accessed = bits(entry, 5, 1);
this.dirty = bits(entry, 6, 1);
this.large = bits(entry, 7, 1);
this.nonExecute = bits(entry, 63, 1);
}
toString() {
if (!this.valid) {
return "---------";
}
return (
{ 1: "L", 0: "-" }[this.large] +
{ 1: "D", 0: "-" }[this.dirty] +
{ 1: "A", 0: "-" }[this.accessed] +
"--" +
{ 1: "U", 0: "K" }[this.user] +
{ 1: "W", 0: "R" }[this.write] +
{ 1: "-", 0: "E" }[this.nonExecute] +
{ 1: "V", 0: "-" }[this.valid]
);
}
present() {
return this.valid;
}
}
// Represents a single EPT entry for any level of the tables.
class EptEntry {
constructor(entry, nextTableType) {
this.value = entry;
this.flags = new EptFlags(entry);
this.pfn = bits(entry, 12, 40);
if (this.flags.present() && !this.flags.large && nextTableType !== undefined) {
this.nextTable = new nextTableType(this.pfn.bitwiseShiftLeft(12));
}
}
toString() {
return hex(this.pfn) + " " + this.flags;
}
}
// Partial representation of flags bits in any EPT entries. Only bits we care are
// represented.
// See: Figure 29-1. Formats of EPTP and EPT Paging-Structure Entries
class EptFlags {
constructor(entry) {
this.read = bits(entry, 0, 1);
this.write = bits(entry, 1, 1);
this.execute = bits(entry, 2, 1);
this.memoryType = bits(entry, 3, 3);
this.large = bits(entry, 7, 1);
this.executeForUserMode = bits(entry, 10, 1);
this.verifyGuestPaging = bits(entry, 57, 1);
this.pagingWriteAccess = bits(entry, 58, 1);
this.supervisorShadowStack = bits(entry, 60, 1);
}
toString() {
return (
{ 1: "S", 0: "-" }[this.supervisorShadowStack] +
{ 1: "P", 0: "-" }[this.pagingWriteAccess] +
{ 1: "V", 0: "-" }[this.verifyGuestPaging] +
{ 1: "U", 0: "-" }[this.executeForUserMode] +
{ 1: "L", 0: "-" }[this.large] +
this.memoryType +
{ 1: "X", 0: "-" }[this.execute] +
{ 1: "W", 0: "-" }[this.write] +
{ 1: "R", 0: "-" }[this.read]
);
}
// Checks if translation is available. Note that the bit[10]
// (executeForUserMode) is not consulted even if MBEC is enabled. (So, you
// cannot create a user-mode-execute-only page.)
present() {
return (this.read || this.write || this.execute);
}
}
// Takes specified range of bits from the 64bit value.
function bits(value, offset, size) {
let mask = host.Int64(1).bitwiseShiftLeft(size).subtract(1);
return value.bitwiseShiftRight(offset).bitwiseAnd(mask).asNumber();
}
// Parses 16 bytes at the given physical address into two 8 byte integers.
function parseEach16Bytes(physicalAddress, count, callback) {
for (let line of exec("!dq " + hex(physicalAddress) + " l" + hex(count * 2))) {
let values = line.replace(/`/g, "").substring(10).trim().split(" ");
try {
var low = host.parseInt64(values[0], 16);
var high = host.parseInt64(values[1], 16);
} catch (error) {
throw new Error("Failed to parse: " + line);