Repository navigation
Expand file tree
/
Copy pathhv.js
More file actions
735 lines (625 loc) · 23 KB
/
Copy pathhv.js
File metadata and controls
735 lines (625 loc) · 23 KB
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
"use strict";
const log = (x) => host.diagnostics.debugLog(`${x}\n`);
const system = (x) => host.namespace.Debugger.Utility.Control.ExecuteCommand(x);
const asUint64 = (x) => host.evaluateExpression(`(unsigned __int64) ${x}`);
const greaterEqual = (a, b) => a.compareTo(b) == 1 || a.compareTo(b) == 0;
const lessThan = (a, b) => a.compareTo(b) == -1;
const sizeof = (module, symbol) => host.getModuleType(module, symbol).size;
function getSymbolFromAddress(x) {
return system(`.printf "%y", ${x.toString(16)}`).First();
}
// Based on Satoshi extension.
function bits(value, offset, size) {
let mask = host.Int64(1).bitwiseShiftLeft(size).subtract(1);
return value.bitwiseShiftRight(offset).bitwiseAnd(mask).asNumber();
}
// Symbol Files
const SYMBOLS_FILE_PATHS = [
"C:\\Dev\\HyperV-WinDbg\\VMCS.h",
"C:\\Dev\\HyperV-WinDbg\\EPT.h",
];
let g_isSymbolsLoaded = false;
function loadHyperVTypes() {
if (g_isSymbolsLoaded) {
return;
}
for (let path of SYMBOLS_FILE_PATHS) {
host.namespace.Debugger.Utility.Analysis.SyntheticTypes.ReadHeader(
path,
"hv",
);
}
g_isSymbolsLoaded = true; // Cache
}
// GS offsets for 24H2, 25H2.
// These offset found be reverse engineering hvix64.exe.
const HV_GS_SELF_OFFSET = 0x0; // Also can be found under the current VMCS' `HostGsBase` field.
const HV_GS_CURRENT_VMCS_OFFSET = 0x2c680;
const HV_GS_CURRENT_VIRTUAL_PROCESSOR_OFFSET = 0x358;
const HV_CURRENT_CR3_OFFSET = 0x458; // Also can be found under the current VMCS' `HostCr3` field.
const HV_GS_IDT_BASE_OFFSE = 0x440;
const HV_GS_GDT_BASE_OFFSE = 0x448;
// More offsets for 24H2, 25H2
const VTL_OFFSET_FROM_VIRTUAL_PROCESSOR = 0x3c0;
// For 24H2 (Potentially also 25H2)
const VTL_ARRAY_OFFSET_FROM_VIRTUAL_PROCESSOR = 0x148;
const HV_PARTITION_OFFSET_FROM_GS_BASE = 0x360;
const VP_ARRAY_OFFSET_FROM_HV_PARTITION = 0x1e0;
const NUMBER_OF_VPS_OFFSET_FROM_HV_PARTITION = 0x1d0; // Holds the number of VPs under partition
const VTL_STATE_REGION_OFFSET_FROM_HV_VTL = 0x13c0;
const VMCS_INFO_STRUCTURE_OFFSET_FROM_VTL_STATE_REGION = 0x28;
const VMCS_VIRTUAL_ADDRESS_OFFSET_FROM_VMCS_INFO_STRUCTURE = 0x180;
const VMCS_PHYSICAL_ADDRESS_OFFSET_FROM_VMCS_INFO_STRUCTURE = 0x188;
// Memory
const PFN_MASK = 0x000fffffffff000;
const PFN_MASK_2M = 0x000ffffffe00000;
const PFN_MASK_1G = 0x000ffffffc00000;
const PAGE_SIZE = 0x1000;
const PAGE_MASK = host.Int64(PAGE_SIZE - 1).bitwiseNot();
const ONE_MB = 1 << 20;
// PE
const NT_IMAGE_NAMES = new Set([
"ntoskrnl", // UP (uniprocessor), no PAE
"ntkrnlpa", // UP + PAE
"ntkrnlmp", // MP (multiprocessor), no PAE
"ntkrpamp", // MP + PAE
"ntkrnlmp", // MP x64
]);
const IMAGE_DOS_MAGIC = 0x5a4d;
// Read memory utilities
const u8 = (x) => host.memory.readMemoryValues(x, 1, 1)[0];
const u16 = (x) => host.memory.readMemoryValues(x, 1, 2)[0];
const u32 = (x) => host.memory.readMemoryValues(x, 1, 4)[0];
const u64 = (x) => host.memory.readMemoryValues(x, 1, 8)[0];
const u128 = (x) => host.memory.readMemoryValues(x, 1, 16)[0];
function read16(x, phy = false) {
if (phy) {
x = host.memory.physicalAddress(x);
}
return u16(x);
}
// Based on Hugsy extensions.
function read64(x, phy = false) {
if (phy) {
x = host.memory.physicalAddress(x);
}
return u64(x, 1, 8);
}
class CR4 {
constructor(value) {
const raw = host.Int64(value);
this.VME = bits(raw, 0, 1) !== 0; // Virtual-8086 Mode Extensions
this.PVI = bits(raw, 1, 1) !== 0; // Protected-mode Virtual Interrupts
this.TSD = bits(raw, 2, 1) !== 0; // Time Stamp Disable
this.DE = bits(raw, 3, 1) !== 0; // Debugging Extensions
this.PSE = bits(raw, 4, 1) !== 0; // Page Size Extensions
this.PAE = bits(raw, 5, 1) !== 0; // Physical Address Extension
this.MCE = bits(raw, 6, 1) !== 0; // Machine-Check Enable
this.PGE = bits(raw, 7, 1) !== 0; // Page Global Enable
this.PCE = bits(raw, 8, 1) !== 0; // Performance Counter Enable
this.OSFXSR = bits(raw, 9, 1) !== 0; // OS support for FXSAVE/FXRSTOR
this.OSXMMEXCPT = bits(raw, 10, 1) !== 0; // OS support for unmasked SIMD FP exceptions
this.UMIP = bits(raw, 11, 1) !== 0; // User-Mode Instruction Prevention
this.LA57 = bits(raw, 12, 1) !== 0; // 5-Level Paging
this.VMXE = bits(raw, 13, 1) !== 0; // VMX Enable
this.SMXE = bits(raw, 14, 1) !== 0; // SMX Enable
this.FSGSBASE = bits(raw, 16, 1) !== 0; // FSGSBASE Enable
this.PCIDE = bits(raw, 17, 1) !== 0; // PCID Enable
this.OSXSAVE = bits(raw, 18, 1) !== 0; // XSAVE Enable
this.KL = bits(raw, 19, 1) !== 0; // Key Locker Enable
this.SMEP = bits(raw, 20, 1) !== 0; // Supervisor Mode Execution Prevention
this.SMAP = bits(raw, 21, 1) !== 0; // Supervisor Mode Access Prevention
this.PKE = bits(raw, 22, 1) !== 0; // Protection Keys Enable
this.CET = bits(raw, 23, 1) !== 0; // Control-flow Enforcement Technology
this.PKS = bits(raw, 24, 1) !== 0; // Protection Keys for Supervisor pages
this.UINTR = bits(raw, 25, 1) !== 0; // User Interrupts
this.toString = () => {
const enabled = Object.keys(this).filter(
(member) => this[member] === true,
);
return `0x${raw.toString(16)} [${enabled.join(" ")}]`;
};
}
}
class CR0 {
constructor(value) {
const raw = host.Int64(value);
this.PE = bits(raw, 0, 1) !== 0; // Protection Enable
this.MP = bits(raw, 1, 1) !== 0; // Monitor Coprocessor
this.EM = bits(raw, 2, 1) !== 0; // Emulation (FPU absent)
this.TS = bits(raw, 3, 1) !== 0; // Task Switched
this.ET = bits(raw, 4, 1) !== 0; // Extension Type (always 1)
this.NE = bits(raw, 5, 1) !== 0; // Numeric Error
this.WP = bits(raw, 16, 1) !== 0; // Write Protect (supervisor)
this.AM = bits(raw, 18, 1) !== 0; // Alignment Mask
this.NW = bits(raw, 29, 1) !== 0; // Not Write-through
this.CD = bits(raw, 30, 1) !== 0; // Cache Disable
this.PG = bits(raw, 31, 1) !== 0; // Paging Enable
this.toString = () => {
const enabled = Object.keys(this).filter(
(member) => this[member] === true,
);
return `0x${raw.toString(16)} [${enabled.join(" ")}]`;
};
}
}
class DR7 {
constructor(value) {
const raw = host.Int64(value);
// RW encoding: 00=exec, 01=write, 10=I/O, 11=read/write
const RW = ["exec", "write", "io", "read/write"];
// LEN encoding: 00=1b, 01=2b, 10=8b, 11=4b (non-obvious: 10=8, 11=4)
const LEN = ["1b", "2b", "8b", "4b"];
// Per-breakpoint enable flags
this.L0 = bits(raw, 0, 1) !== 0; // Local enable BP0
this.G0 = bits(raw, 1, 1) !== 0; // Global enable BP0
this.L1 = bits(raw, 2, 1) !== 0; // Local enable BP1
this.G1 = bits(raw, 3, 1) !== 0; // Global enable BP1
this.L2 = bits(raw, 4, 1) !== 0; // Local enable BP2
this.G2 = bits(raw, 5, 1) !== 0; // Global enable BP2
this.L3 = bits(raw, 6, 1) !== 0; // Local enable BP3
this.G3 = bits(raw, 7, 1) !== 0; // Global enable BP3
this.LE = bits(raw, 8, 1) !== 0; // Local exact (obsolete, ignored by modern CPUs)
this.GE = bits(raw, 9, 1) !== 0; // Global exact (obsolete, ignored by modern CPUs)
this.RTM = bits(raw, 11, 1) !== 0; // Advanced debugging of RTM regions
this.GD = bits(raw, 13, 1) !== 0; // General detect — #DB before any DR access
// Per-breakpoint condition and length (decoded to human-readable strings)
this.RW0 = RW[bits(raw, 16, 2)];
this.LEN0 = LEN[bits(raw, 18, 2)];
this.RW1 = RW[bits(raw, 20, 2)];
this.LEN1 = LEN[bits(raw, 22, 2)];
this.RW2 = RW[bits(raw, 24, 2)];
this.LEN2 = LEN[bits(raw, 26, 2)];
this.RW3 = RW[bits(raw, 28, 2)];
this.LEN3 = LEN[bits(raw, 30, 2)];
this.toString = () => {
const active = [0, 1, 2, 3]
.filter((i) => this[`L${i}`] || this[`G${i}`])
.map((i) => `BP${i}:${this[`RW${i}`]}/${this[`LEN${i}`]}`);
const summary = active.length ? active.join(" ") : "no breakpoints";
return `0x${raw.toString(16)} [${summary}]`;
};
}
}
function getGsBase() {
return host.parseInt64(system("dq gs:[0] L1")[0].split(" ")[2], 16);
}
function getCurrentVtlNumber() {
const gsBase = getGsBase();
const vp_address = u64(gsBase.add(HV_GS_CURRENT_VIRTUAL_PROCESSOR_OFFSET));
const vtl_number = u8(vp_address.add(VTL_OFFSET_FROM_VIRTUAL_PROCESSOR));
return vtl_number;
}
/**
Returns a HV_VP structure representing a virtual processor.
*/
function getCurrentVirtualProcessor() {
const gsBase = getGsBase();
const vp_address = u64(gsBase.add(HV_GS_CURRENT_VIRTUAL_PROCESSOR_OFFSET));
return vp_address;
}
/**
Returns a HV_VTL structure (representing a VTL) base address.
*/
function getCurrentVtl() {
const gsBase = getGsBase();
const vp_address = u64(gsBase.add(HV_GS_CURRENT_VIRTUAL_PROCESSOR_OFFSET));
const vtl = u64(vp_address.add(VTL_OFFSET_FROM_VIRTUAL_PROCESSOR));
return vtl;
}
function getVtlsList() {
let VirtualProcessor = getCurrentVirtualProcessor();
let vtlsListDoublePointer = VirtualProcessor.add(
VTL_ARRAY_OFFSET_FROM_VIRTUAL_PROCESSOR,
);
return vtlsListDoublePointer;
}
function printVtlsList() {
let vtls = getVtlsList();
// Since there are currently only 2 VTLs (VTL0 & VTL1) supported, the function will iterate only on 2 VTLs.
// but we can get per the number of active VTLs per VP - by reading
// HvRegisterVsmVpStatus.EnabledVtlSet bitmask field
for (let index = 0; index < 2; index++) {
let vtl = u64(vtls.add(8 * index));
log(`\t[*] VTL[${index}]: 0x${vtl.toString(16)}`);
}
}
function getCurrentPartition() {
let gsBase = getGsBase();
return u64(gsBase.add(HV_PARTITION_OFFSET_FROM_GS_BASE));
}
/**
Prints a list of Virtual Processor structure's base addresses that
are under the current partition.
*/
function getVpsList() {
let currentParition = getCurrentPartition();
let numberOfVps = u32(
currentParition.add(NUMBER_OF_VPS_OFFSET_FROM_HV_PARTITION),
);
let vpsListPointer = u64(
currentParition.add(VP_ARRAY_OFFSET_FROM_HV_PARTITION),
);
log(`\t[*] Number Of Virtual Processors: 0x${numberOfVps.toString(8)}\n`);
for (let index = 0; index < numberOfVps; index++) {
let vp = u64(
currentParition.add(VP_ARRAY_OFFSET_FROM_HV_PARTITION + 8 * index),
);
log(`\t[*] Virtual Processor[${index}]: 0x${vp.toString(16)}\n`);
}
}
function getVmcsAddressesList() {
let vtlsListDoublePointer = getVtlsList();
// Hardcoding the number of VTLs since we know there are 2 VTLs.
// We can get the exact number of active VTLs in 2 ways:
// 1. Partition-wide active VTLs - by reading HvRegisterVsmPartitionStatus.EnabledVtlSet bitmask field
// 2. Per Virtual Processor active VTLs - by reading HvRegisterVsmVpStatus.EnabledVtlSet bitmask field
for (let index = 0; index < 2; index++) {
let vtl = u64(vtlsListDoublePointer.add(8 * index));
let vtlStateRegion = vtl.add(VTL_STATE_REGION_OFFSET_FROM_HV_VTL);
let vmcsInfo = vtlStateRegion.add(
VMCS_INFO_STRUCTURE_OFFSET_FROM_VTL_STATE_REGION,
);
const vmcsVirtualAddress = u64(
u64(vmcsInfo).add(VMCS_VIRTUAL_ADDRESS_OFFSET_FROM_VMCS_INFO_STRUCTURE),
);
const vmcsPhysicalAddress = u64(
u64(vmcsInfo).add(VMCS_PHYSICAL_ADDRESS_OFFSET_FROM_VMCS_INFO_STRUCTURE),
);
log(`\t[*] VTL[${index}]:`);
log(`\t\t[*] VMCS Virtual Address = 0x${vmcsVirtualAddress.toString(16)}`);
log(
`\t\t[*] VMCS Physical Address = 0x${vmcsPhysicalAddress.toString(16)}\n`,
);
}
}
function getCurrentVmcs() {
const gsBase = getGsBase();
const vmcs_address = u64(gsBase.add(HV_GS_CURRENT_VMCS_OFFSET));
loadHyperVTypes();
return host.namespace.Debugger.Utility.Analysis.SyntheticTypes.CreateInstance(
"HV_VMX_ENLIGHTENED_VMCS",
vmcs_address,
);
}
function getCurrentEptPointer() {
const currentVmcs = getCurrentVmcs();
const eptRoot = currentVmcs.EptRoot;
return eptRoot;
}
class Address {
constructor(address, cr3 = undefined, physAddress = undefined) {
this.address = asUint64(address);
this.pml4Index = bits(this.address, 39, 9);
this.pdptIndex = bits(this.address, 30, 9);
this.pdIndex = bits(this.address, 21, 9);
this.ptIndex = bits(this.address, 12, 9);
this.cr3 = cr3;
this.physAddress = physAddress;
}
toString() {
return `Virt: 0x${this.address.toString(16)}, Phys: 0x${this.physAddress.toString(16)}`;
}
}
class EptEntry {
constructor(raw) {
this.raw = asUint64(raw);
}
isPresent() {
return !(this.raw.bitwiseAnd(0x7) == 0);
}
isLargePage() {
return !(this.raw.bitwiseAnd(0x80) == 0);
}
entry(index) {
return this.raw.bitwiseAnd(PFN_MASK).add(index.multiply(8));
}
}
function gpa2Hpa(gpa) {
const address = new Address(gpa);
const pml4 = new EptEntry(getCurrentEptPointer());
if (!pml4.isPresent()) return;
const pdpt = new EptEntry(read64(pml4.entry(address.pml4Index), true));
if (!pdpt.isPresent()) return;
const pd = new EptEntry(read64(pdpt.entry(address.pdptIndex), true));
if (!pd.isPresent()) return;
// 1GB huge page
if (pd.isLargePage()) {
return pd.raw.bitwiseAnd(PFN_MASK_1G).bitwiseOr(gpa.bitwiseAnd(0x3fffffff));
}
const pde = new EptEntry(read64(pd.entry(address.pdIndex), true));
if (!pde.isPresent()) return;
// 2MB large page
if (pde.isLargePage()) {
return pde.raw.bitwiseAnd(PFN_MASK_2M).bitwiseOr(gpa.bitwiseAnd(0x1fffff));
}
// 4KB page
const pte = new EptEntry(read64(pde.entry(address.ptIndex), true));
return pte.raw.bitwiseAnd(PFN_MASK).bitwiseOr(gpa.bitwiseAnd(0xfff));
}
/**
Wrapper to get the physical address for a virtual address and CR3.
Assumes `kext` extension is loaded.
*/
function v2p(cr3, va) {
const vtopOutput = system(`!vtop 0x${cr3.toString(16)} 0x${va.toString(16)}`);
for (let line of vtopOutput) {
if (line.includes("Mapped phys")) {
return host.parseInt64(`0x${line.split(" ")[3].toString(16)}`);
}
if (line.includes("Large page mapped phys")) {
return host.parseInt64(`0x${line.split(" ")[5].toString(16)}`);
}
}
return null;
}
/**
Wrapper for all the information about the module PE header.
Assumes virtual memory of the module is available (`.context ....` was called).
*/
class PeHeaders {
constructor(moduleBaseVirtAddress) {
this.imageBase = asUint64(moduleBaseVirtAddress);
const headers = system(`!dh 0x${moduleBaseVirtAddress.toString(16)}`);
this.imageSize = parseInt(this.__getImageSize(headers), 16);
this.moduleFileName = this.__getModuleFilename(headers);
}
__findInfo(headersDump, textToSearch, offsetToValue) {
for (let line of headersDump) {
if (line.includes(textToSearch)) {
return line.split(" ")[offsetToValue];
}
}
}
__getImageSize(headersDump) {
for (let line of headersDump) {
if (line.includes("size of image")) {
const m = line.match(/^\s*([0-9a-fA-F]+)\s+size of image/i);
return m ? m[1] : null;
}
}
}
__getModuleFilename(headersDump) {
for (let line of headersDump) {
const m = line.match(
/Format:\s*RSDS\s*,\s*\S+\s*,\s*\d+\s*,\s*(\S+\.pdb)/i,
);
if (m) return m[1].replace(/\.[^.]+$/, ""); //stripExtension
}
}
// TODO: Make it work.
contains(modulePcVirtAddress) {
return (
this.imageBase.add(this.imageSize) > asUint64(modulePcVirtAddress) &&
this.imageBase <= asUint64(modulePcVirtAddress)
);
}
reload() {
let moduleName = this.moduleFileName;
if (NT_IMAGE_NAMES.has(this.moduleFileName)) {
moduleName = "nt";
}
system(`.reload /f ${moduleName}=0x${this.imageBase.toString(16)}`);
}
}
/**
Returns the current guest image base virtual and physical addresses.
*/
function findGuestModuleInfo() {
const CHUNK_SIZE = PAGE_SIZE;
const NUM_OF_PAGES_IN_1MB = ONE_MB / 256;
// Find the guest return address by reading the guest top of the stack:
let guestRspVirtAddr = getCurrentVmcs().GuestRsp;
let guestCr3PhysAddr = getCurrentVmcs().GuestCr3;
let guestRspPhysAddr = v2p(guestCr3PhysAddr, guestRspVirtAddr);
// TODO: handle guestRspPhysAddr==null
let guestReturnAddrVirtAddr = asUint64(read64(guestRspPhysAddr, true));
let guestSymbolAligned = guestReturnAddrVirtAddr.bitwiseAnd(PAGE_MASK);
// Now that we have an address in the guest memory space,
// We can search for the guest module base address.
// Find the guest module base address.
let currentVirtAddr = guestSymbolAligned;
for (let i = 0; i < NUM_OF_PAGES_IN_1MB; i++) {
let currentPhysAddress = v2p(guestCr3PhysAddr, currentVirtAddr);
if (null == currentPhysAddress) {
return `[-] Probably Got invalid PTE for VA=0x${currentVirtAddr.toString(16)}`;
}
let tempPeMagic = read16(currentPhysAddress, true);
// 'MZ'
if (tempPeMagic == IMAGE_DOS_MAGIC) {
system(`.context 0x${guestCr3PhysAddr.toString(16)}`);
const peInfo = new PeHeaders(currentVirtAddr);
// We assume a valid guest image will have a PDB file.
if (peInfo.moduleFileName) {
return peInfo;
}
}
currentVirtAddr = currentVirtAddr.subtract(CHUNK_SIZE);
}
return None;
}
function getGuestCallStack() {
const currentRip = host.currentThread.Registers.User.rip;
const currentRsp = host.currentThread.Registers.User.rsp;
const currentVmcs = getCurrentVmcs();
const guestRip = currentVmcs.GuestRip;
const guestRsp = currentVmcs.GuestRsp;
const guestCr3 = currentVmcs.GuestCr3;
system(`.context 0x${guestCr3.toString(16)}`);
system(`r rip=0x${guestRip.toString(16)}`);
system(`r rsp=0x${guestRsp.toString(16)}`);
const guestCallStack = system("k");
system(`r rip=0x${currentRip.toString(16)}`);
system(`r rsp=0x${currentRsp.toString(16)}`);
return guestCallStack;
}
/**
Lookup for the module Data Model by RIP.
Equvalent to:
dx @$getMod = (addr) => @$curprocess.Modules.Where(
x => (addr < x.BaseAddress + x.Size) && (x.BaseAddress <= addr)
).First()
*/
function getModuleByPc(pc) {
const modules = host.currentProcess.Modules;
for (let module of modules) {
if (
greaterEqual(pc, module.BaseAddress) &&
lessThan(pc, module.BaseAddress.add(module.Size))
) {
return module;
}
}
}
class Guest {
constructor() {
const currentVmcs = getCurrentVmcs();
this.rsp = currentVmcs.GuestRsp;
this.rip = currentVmcs.GuestRip;
this.cr0 = new CR0(currentVmcs.GuestCr0);
this.cr3 = currentVmcs.GuestCr3;
this.cr4 = new CR4(currentVmcs.GuestCr4);
this.dr7 = new DR7(currentVmcs.GuestDr7);
this.gs = currentVmcs.GuestGsBase;
this.module = this.__getModule(
currentVmcs.GuestCr3,
currentVmcs.GuestRip,
currentVmcs.GuestRsp,
);
this.idt = this.__getIdt(
currentVmcs.GuestIdtrLimit,
currentVmcs.GuestIdtrBase,
);
this.callStack = getGuestCallStack();
this.toString = () => {
return `RIP = 0x${this.rip.toString(16)}`;
};
}
__getIdt(guestIdtrLimit, guestIdtrBase) {
try {
// If symbols are loaded, parse the IDT.
return getIdt(guestIdtrLimit, guestIdtrBase);
} catch (e) {
// Otherwise, just return the IDT base address.
return guestIdtrBase;
}
}
__getModuleBaseFromDataModule(guestCr3, guestRip, guestRsp) {
system(`.context 0x${guestCr3.toString(16)}`);
const module = getModuleByPc(guestRip) ?? getModuleByPc(read64(guestRsp));
if (!module) {
throw new Error("Failed to find the module");
}
return module;
}
__getModule(guestCr3, guestRip, guestRsp) {
try {
// Try to fetch the module object from the Data Model (pif it already loaded).
return this.__getModuleBaseFromDataModule(guestCr3, guestRip, guestRsp);
} catch (e) {
// Otherwise, run memory scan and load it.
const modulePeHeadersInfo = findGuestModuleInfo();
modulePeHeadersInfo.reload();
// Now return the module object from the Data Model.
return this.__getModuleBaseFromDataModule(guestCr3, guestRip, guestRsp);
}
}
}
function getModuleBaseFromDataModule(guestCr3, guestRip, guestRsp) {
system(`.context 0x${guestCr3.toString(16)}`);
const moduleBaseAddress =
getModuleByPc(guestRip) ?? getModuleByPc(read64(guestRsp));
return moduleBaseAddress;
}
class IdtEntry {
constructor(index, idtEntryAddress) {
this.raw = host.createPointerObject(idtEntryAddress, "nt", "_KIDTENTRY64*");
this.index = index;
this.isr = this.__getIsr(this.raw);
}
__getIsr(idtEntry) {
const isrMiddle = idtEntry.OffsetMiddle.bitwiseShiftLeft(16);
const isrHigh = idtEntry.OffsetHigh.bitwiseShiftLeft(32);
const isr = idtEntry.OffsetLow.bitwiseOr(isrMiddle).bitwiseOr(isrHigh);
return isr;
}
toString() {
const symbolName = getSymbolFromAddress(this.isr);
return symbolName ? symbolName : `0x${this.isr.toString(16)}`;
}
}
function getIdt(idtLimit, idtBase) {
const sizeOfIdtEntry = sizeof("nt", "_KIDTENTRY64");
const numberOfIdtEntries = idtLimit / sizeOfIdtEntry;
let idtEntries = [];
let currentIdtEntryAddress = idtBase;
for (
let currentEntryIndex = 0;
currentEntryIndex < numberOfIdtEntries;
currentEntryIndex++
) {
const idtEntryAddress = currentIdtEntryAddress.add(
currentEntryIndex * sizeOfIdtEntry,
);
idtEntries.push(new IdtEntry(currentEntryIndex, idtEntryAddress));
}
return idtEntries;
}
function getHvIdt() {
const idtLimit = host.Int64(host.currentThread.Registers.Kernel.idtl);
const idtBase = host.Int64(host.currentThread.Registers.Kernel.idtr);
return getIdt(idtLimit, idtBase);
}
/**
Returns information about the current guest.
*/
function getGuestInfo() {
return new Guest();
}
function printUsage() {
log(" HyperV Research Tools:");
log(" !gpa2hpa <gpa> - Translates GPA to SPA");
log(
" !vmcs - Prints the current active VMCS base address on logical processor",
);
log(" !vtlnumber - Prints the active VTL's VTL number");
log(
" !currentvp - Prints the current Virtual Processor's HV_VP data structure base address",
);
log(
" !partition - Prints the current partition's HV_PARTITION data structure base address",
);
log(
" !currentvtl - Prints the current VTL's HV_VTL data structure base address",
);
log(
" !vtls - Prints all the existing VTL's HV_VTL data structure base addresses",
);
log(
" !vps - Prints all the existing VPs HV_VP data structure base addresses",
);
log(
" !vmcslist - Prints a list of all VMCSes Virtual and Physical addresses",
);
log(
" !guest - Prints information about the guest VM and loads its symbols",
);
log(" !hvidt - Prints HyperV interrupt descriptor table");
}
function initializeScript() {
printUsage();
return [
new host.apiVersionSupport(1, 9),
new host.functionAlias(gpa2Hpa, "gpa2hpa"),
new host.functionAlias(getCurrentVmcs, "vmcs"),
new host.functionAlias(getCurrentVtlNumber, "vtlnumber"),
new host.functionAlias(getCurrentVirtualProcessor, "currentvp"),
new host.functionAlias(getCurrentVtl, "currentvtl"),
new host.functionAlias(printVtlsList, "vtls"),
new host.functionAlias(getCurrentPartition, "partition"),
new host.functionAlias(getVpsList, "vps"),
new host.functionAlias(getVmcsAddressesList, "vmcslist"),
new host.functionAlias(getGuestInfo, "guest"),
new host.functionAlias(getHvIdt, "hvidt"),
];
}