-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathSimpleSvm.cpp
More file actions
2008 lines (1780 loc) · 67 KB
/
SimpleSvm.cpp
File metadata and controls
2008 lines (1780 loc) · 67 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
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
/*!
@file SimpleSvm.cpp
@brief All C code.
@author Satoshi Tanda
@copyright Copyright (c) 2017-2020, Satoshi Tanda. All rights reserved.
*/
#define POOL_NX_OPTIN 1
#include "SimpleSvm.hpp"
#include <intrin.h>
#include <ntifs.h>
#include <stdarg.h>
EXTERN_C DRIVER_INITIALIZE DriverEntry;
static DRIVER_UNLOAD SvDriverUnload;
static CALLBACK_FUNCTION SvPowerCallbackRoutine;
EXTERN_C
VOID
_sgdt (
_Out_ PVOID Descriptor
);
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
DECLSPEC_NORETURN
EXTERN_C
VOID
NTAPI
SvLaunchVm (
_In_ PVOID HostRsp
);
//
// x86-64 defined structures.
//
//
// See "2-Mbyte PML4E-Long Mode" and "2-Mbyte PDPE-Long Mode".
//
typedef struct _PML4_ENTRY_2MB
{
union
{
UINT64 AsUInt64;
struct
{
UINT64 Valid : 1; // [0]
UINT64 Write : 1; // [1]
UINT64 User : 1; // [2]
UINT64 WriteThrough : 1; // [3]
UINT64 CacheDisable : 1; // [4]
UINT64 Accessed : 1; // [5]
UINT64 Reserved1 : 3; // [6:8]
UINT64 Avl : 3; // [9:11]
UINT64 PageFrameNumber : 40; // [12:51]
UINT64 Reserved2 : 11; // [52:62]
UINT64 NoExecute : 1; // [63]
} Fields;
};
} PML4_ENTRY_2MB, *PPML4_ENTRY_2MB,
PDPT_ENTRY_2MB, *PPDPT_ENTRY_2MB;
static_assert(sizeof(PML4_ENTRY_2MB) == 8,
"PML4_ENTRY_1GB Size Mismatch");
//
// See "2-Mbyte PDE-Long Mode".
//
typedef struct _PD_ENTRY_2MB
{
union
{
UINT64 AsUInt64;
struct
{
UINT64 Valid : 1; // [0]
UINT64 Write : 1; // [1]
UINT64 User : 1; // [2]
UINT64 WriteThrough : 1; // [3]
UINT64 CacheDisable : 1; // [4]
UINT64 Accessed : 1; // [5]
UINT64 Dirty : 1; // [6]
UINT64 LargePage : 1; // [7]
UINT64 Global : 1; // [8]
UINT64 Avl : 3; // [9:11]
UINT64 Pat : 1; // [12]
UINT64 Reserved1 : 8; // [13:20]
UINT64 PageFrameNumber : 31; // [21:51]
UINT64 Reserved2 : 11; // [52:62]
UINT64 NoExecute : 1; // [63]
} Fields;
};
} PD_ENTRY_2MB, *PPD_ENTRY_2MB;
static_assert(sizeof(PD_ENTRY_2MB) == 8,
"PDE_ENTRY_2MB Size Mismatch");
//
// See "GDTR and IDTR Format-Long Mode"
//
#include <pshpack1.h>
typedef struct _DESCRIPTOR_TABLE_REGISTER
{
UINT16 Limit;
ULONG_PTR Base;
} DESCRIPTOR_TABLE_REGISTER, *PDESCRIPTOR_TABLE_REGISTER;
static_assert(sizeof(DESCRIPTOR_TABLE_REGISTER) == 10,
"DESCRIPTOR_TABLE_REGISTER Size Mismatch");
#include <poppack.h>
//
// See "Long-Mode Segment Descriptors" and some of definitions
// (eg, "Code-Segment Descriptor-Long Mode")
//
typedef struct _SEGMENT_DESCRIPTOR
{
union
{
UINT64 AsUInt64;
struct
{
UINT16 LimitLow; // [0:15]
UINT16 BaseLow; // [16:31]
UINT32 BaseMiddle : 8; // [32:39]
UINT32 Type : 4; // [40:43]
UINT32 System : 1; // [44]
UINT32 Dpl : 2; // [45:46]
UINT32 Present : 1; // [47]
UINT32 LimitHigh : 4; // [48:51]
UINT32 Avl : 1; // [52]
UINT32 LongMode : 1; // [53]
UINT32 DefaultBit : 1; // [54]
UINT32 Granularity : 1; // [55]
UINT32 BaseHigh : 8; // [56:63]
} Fields;
};
} SEGMENT_DESCRIPTOR, *PSEGMENT_DESCRIPTOR;
static_assert(sizeof(SEGMENT_DESCRIPTOR) == 8,
"SEGMENT_DESCRIPTOR Size Mismatch");
typedef struct _SEGMENT_ATTRIBUTE
{
union
{
UINT16 AsUInt16;
struct
{
UINT16 Type : 4; // [0:3]
UINT16 System : 1; // [4]
UINT16 Dpl : 2; // [5:6]
UINT16 Present : 1; // [7]
UINT16 Avl : 1; // [8]
UINT16 LongMode : 1; // [9]
UINT16 DefaultBit : 1; // [10]
UINT16 Granularity : 1; // [11]
UINT16 Reserved1 : 4; // [12:15]
} Fields;
};
} SEGMENT_ATTRIBUTE, *PSEGMENT_ATTRIBUTE;
static_assert(sizeof(SEGMENT_ATTRIBUTE) == 2,
"SEGMENT_ATTRIBUTE Size Mismatch");
//
// SimpleSVM specific structures.
//
typedef struct _PML4E_TREE
{
DECLSPEC_ALIGN(PAGE_SIZE) PDPT_ENTRY_2MB PdptEntries[512];
DECLSPEC_ALIGN(PAGE_SIZE) PD_ENTRY_2MB PdEntries[512][512];
} PML4E_TREE, *PPML4E_TREE;
typedef struct _SHARED_VIRTUAL_PROCESSOR_DATA
{
PVOID MsrPermissionsMap;
DECLSPEC_ALIGN(PAGE_SIZE) PML4_ENTRY_2MB Pml4Entries[512];
DECLSPEC_ALIGN(PAGE_SIZE) PML4E_TREE Pml4eTrees[2]; // For 1TB
} SHARED_VIRTUAL_PROCESSOR_DATA, *PSHARED_VIRTUAL_PROCESSOR_DATA;
typedef struct _VIRTUAL_PROCESSOR_DATA
{
union
{
//
// Low HostStackLimit[0] StackLimit
// ^ ...
// ^ HostStackLimit[KERNEL_STACK_SIZE - 2] StackBase
// High HostStackLimit[KERNEL_STACK_SIZE - 1] StackBase
//
DECLSPEC_ALIGN(PAGE_SIZE) UINT8 HostStackLimit[KERNEL_STACK_SIZE];
struct
{
UINT8 StackContents[KERNEL_STACK_SIZE - (sizeof(PVOID) * 6) - sizeof(KTRAP_FRAME)];
KTRAP_FRAME TrapFrame;
UINT64 GuestVmcbPa; // HostRsp
UINT64 HostVmcbPa;
struct _VIRTUAL_PROCESSOR_DATA* Self;
PSHARED_VIRTUAL_PROCESSOR_DATA SharedVpData;
UINT64 Padding1; // To keep HostRsp 16 bytes aligned
UINT64 Reserved1;
} HostStackLayout;
};
DECLSPEC_ALIGN(PAGE_SIZE) VMCB GuestVmcb;
DECLSPEC_ALIGN(PAGE_SIZE) VMCB HostVmcb;
DECLSPEC_ALIGN(PAGE_SIZE) UINT8 HostStateArea[PAGE_SIZE];
} VIRTUAL_PROCESSOR_DATA, *PVIRTUAL_PROCESSOR_DATA;
static_assert(sizeof(VIRTUAL_PROCESSOR_DATA) == KERNEL_STACK_SIZE + PAGE_SIZE * 3,
"VIRTUAL_PROCESSOR_DATA Size Mismatch");
typedef struct _GUEST_REGISTERS
{
UINT64 R15;
UINT64 R14;
UINT64 R13;
UINT64 R12;
UINT64 R11;
UINT64 R10;
UINT64 R9;
UINT64 R8;
UINT64 Rdi;
UINT64 Rsi;
UINT64 Rbp;
UINT64 Rsp;
UINT64 Rbx;
UINT64 Rdx;
UINT64 Rcx;
UINT64 Rax;
} GUEST_REGISTERS, *PGUEST_REGISTERS;
typedef struct _GUEST_CONTEXT
{
PGUEST_REGISTERS VpRegs;
BOOLEAN ExitVm;
} GUEST_CONTEXT, *PGUEST_CONTEXT;
//
// x86-64 defined constants.
//
#define IA32_MSR_PAT 0x00000277
#define IA32_MSR_EFER 0xc0000080
#define EFER_SVME (1UL << 12)
#define RPL_MASK 3
#define DPL_SYSTEM 0
#define CPUID_FN8000_0001_ECX_SVM (1UL << 2)
#define CPUID_FN0000_0001_ECX_HYPERVISOR_PRESENT (1UL << 31)
#define CPUID_FN8000_000A_EDX_NP (1UL << 0)
#define CPUID_MAX_STANDARD_FN_NUMBER_AND_VENDOR_STRING 0x00000000
#define CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS 0x00000001
#define CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS_EX 0x80000001
#define CPUID_SVM_FEATURES 0x8000000a
//
// The Microsoft Hypervisor interface defined constants.
//
#define CPUID_HV_VENDOR_AND_MAX_FUNCTIONS 0x40000000
#define CPUID_HV_INTERFACE 0x40000001
//
// SimpleSVM specific constants.
//
#define CPUID_UNLOAD_SIMPLE_SVM 0x41414141
#define CPUID_HV_MAX CPUID_HV_INTERFACE
/*!
@brief Breaks into a kernel debugger when it is present.
@details This macro is emits software breakpoint that only hits when a
kernel debugger is present. This macro is useful because it does
not change the current frame unlike the DbgBreakPoint function,
and breakpoint by this macro can be overwritten with NOP without
impacting other breakpoints.
*/
#define SV_DEBUG_BREAK() \
if (KD_DEBUGGER_NOT_PRESENT) \
{ \
NOTHING; \
} \
else \
{ \
__debugbreak(); \
} \
reinterpret_cast<void*>(0)
//
// A power state callback handle.
//
static PVOID g_PowerCallbackRegistration;
/*!
@brief Sends a message to the kernel debugger.
@param[in] Format - The format string to print.
*/
#pragma prefast(push)
#pragma prefast(disable : 26826, "C-style variable arguments needed for DbgPrint.")
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
static
VOID
SvDebugPrint (
_In_z_ _Printf_format_string_ PCSTR Format,
...
)
{
va_list argList;
va_start(argList, Format);
vDbgPrintExWithPrefix("[SimpleSvm] ",
DPFLTR_IHVDRIVER_ID,
DPFLTR_ERROR_LEVEL,
Format,
argList);
va_end(argList);
}
#pragma prefast(pop)
/*!
@brief Allocates page aligned, zero filled physical memory.
@details This function allocates page aligned nonpaged pool. The
allocated memory is zero filled and must be freed with
SvFreePageAlingedPhysicalMemory. On Windows 8 and later versions
of Windows, the allocated memory is non executable.
@param[in] NumberOfBytes - A size of memory to allocate in byte. This must
be equal or greater than PAGE_SIZE.
@result A pointer to the allocated memory filled with zero; or NULL when
there is insufficient memory to allocate requested size.
*/
__drv_allocatesMem(Mem)
_Post_writable_byte_size_(NumberOfBytes)
_Post_maybenull_
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Must_inspect_result_
static
PVOID
SvAllocatePageAlingedPhysicalMemory (
_In_ SIZE_T NumberOfBytes
)
{
PVOID memory;
//
// The size must be equal or greater than PAGE_SIZE in order to allocate
// page aligned memory.
//
NT_ASSERT(NumberOfBytes >= PAGE_SIZE);
memory = ExAllocatePool2(POOL_FLAG_NON_PAGED, NumberOfBytes, 'MVSS');
if (memory != nullptr)
{
NT_ASSERT(PAGE_ALIGN(memory) == memory);
RtlZeroMemory(memory, NumberOfBytes);
}
return memory;
}
/*!
@brief Frees memory allocated by SvAllocatePageAlingedPhysicalMemory.
@param[in] BaseAddress - The address returned by
SvAllocatePageAlingedPhysicalMemory.
*/
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
static
VOID
SvFreePageAlingedPhysicalMemory (
_Pre_notnull_ __drv_freesMem(Mem) PVOID BaseAddress
)
{
ExFreePoolWithTag(BaseAddress, 'MVSS');
}
/*!
@brief Allocates page aligned, zero filled contiguous physical memory.
@details This function allocates page aligned nonpaged pool where backed
by contiguous physical pages. The allocated memory is zero
filled and must be freed with SvFreeContiguousMemory. The
allocated memory is executable.
@param[in] NumberOfBytes - A size of memory to allocate in byte.
@result A pointer to the allocated memory filled with zero; or NULL when
there is insufficient memory to allocate requested size.
*/
_Post_writable_byte_size_(NumberOfBytes)
_Post_maybenull_
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
_Must_inspect_result_
static
PVOID
SvAllocateContiguousMemory (
_In_ SIZE_T NumberOfBytes
)
{
PVOID memory;
PHYSICAL_ADDRESS boundary, lowest, highest;
boundary.QuadPart = lowest.QuadPart = 0;
highest.QuadPart = -1;
memory = MmAllocateContiguousNodeMemory(NumberOfBytes,
lowest,
highest,
boundary,
PAGE_READWRITE,
MM_ANY_NODE_OK);
if (memory != nullptr)
{
RtlZeroMemory(memory, NumberOfBytes);
}
return memory;
}
/*!
@brief Frees memory allocated by SvAllocateContiguousMemory.
@param[in] BaseAddress - The address returned by SvAllocateContiguousMemory.
*/
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_same_
static
VOID
SvFreeContiguousMemory (
_In_ PVOID BaseAddress
)
{
MmFreeContiguousMemory(BaseAddress);
}
/*!
@brief Injects #GP with 0 of error code.
@param[in,out] VpData - Per processor data.
*/
_IRQL_requires_same_
static
VOID
SvInjectGeneralProtectionException (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData
)
{
EVENTINJ event;
//
// Inject #GP(vector = 13, type = 3 = exception) with a valid error code.
// An error code are always zero. See "#GP-General-Protection Exception
// (Vector 13)" for details about the error code.
//
event.AsUInt64 = 0;
event.Fields.Vector = 13;
event.Fields.Type = 3;
event.Fields.ErrorCodeValid = 1;
event.Fields.Valid = 1;
VpData->GuestVmcb.ControlArea.EventInj = event.AsUInt64;
}
/*!
@brief Handles #VMEXIT due to execution of the CPUID instructions.
@details This function returns unmodified results of the CPUID
instruction, except for few cases to indicate presence of
the hypervisor, and to process an unload request.
CPUID leaf 0x40000000 and 0x40000001 return modified values
to conform to the hypervisor interface to some extent. See
"Requirements for implementing the Microsoft Hypervisor interface"
https://msdn.microsoft.com/en-us/library/windows/hardware/Dn613994(v=vs.85).aspx
for details of the interface.
@param[in,out] VpData - Per processor data.
@param[in,out] GuestContext - Guest's GPRs.
*/
_IRQL_requires_same_
static
VOID
SvHandleCpuid (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData,
_Inout_ PGUEST_CONTEXT GuestContext
)
{
int registers[4]; // EAX, EBX, ECX, and EDX
int leaf, subLeaf;
SEGMENT_ATTRIBUTE attribute;
//
// Execute CPUID as requested.
//
leaf = static_cast<int>(GuestContext->VpRegs->Rax);
subLeaf = static_cast<int>(GuestContext->VpRegs->Rcx);
__cpuidex(registers, leaf, subLeaf);
switch (leaf)
{
case CPUID_PROCESSOR_AND_PROCESSOR_FEATURE_IDENTIFIERS:
//
// Indicate presence of a hypervisor by setting the bit that are
// reserved for use by hypervisor to indicate guest status. See "CPUID
// Fn0000_0001_ECX Feature Identifiers".
//
registers[2] |= CPUID_FN0000_0001_ECX_HYPERVISOR_PRESENT;
break;
case CPUID_HV_VENDOR_AND_MAX_FUNCTIONS:
//
// Return a maximum supported hypervisor CPUID leaf range and a vendor
// ID signature as required by the spec.
//
registers[0] = CPUID_HV_MAX;
registers[1] = 'pmiS'; // "SimpleSvm "
registers[2] = 'vSel';
registers[3] = ' m';
break;
case CPUID_HV_INTERFACE:
//
// Return non Hv#1 value. This indicate that the SimpleSvm does NOT
// conform to the Microsoft hypervisor interface.
//
registers[0] = '0#vH'; // Hv#0
registers[1] = registers[2] = registers[3] = 0;
break;
case CPUID_UNLOAD_SIMPLE_SVM:
if (subLeaf == CPUID_UNLOAD_SIMPLE_SVM)
{
//
// Unload itself if the request is from the kernel mode.
//
attribute.AsUInt16 = VpData->GuestVmcb.StateSaveArea.SsAttrib;
if (attribute.Fields.Dpl == DPL_SYSTEM)
{
GuestContext->ExitVm = TRUE;
}
}
break;
default:
break;
}
//
// Update guest's GPRs with results.
//
GuestContext->VpRegs->Rax = registers[0];
GuestContext->VpRegs->Rbx = registers[1];
GuestContext->VpRegs->Rcx = registers[2];
GuestContext->VpRegs->Rdx = registers[3];
//
// Debug prints results. Very important to note that any use of API from
// the host context is unsafe and absolutely avoided, unless the API is
// documented to be accessible on IRQL IPI_LEVEL+. This is because
// interrupts are disabled when host code is running, and IPI is not going
// to be delivered when it is issued.
//
// This code is not exception and violating this rule. The reasons for this
// code are to demonstrate a bad example, and simply show that the SimpleSvm
// is functioning for a test purpose.
//
if (KeGetCurrentIrql() <= DISPATCH_LEVEL)
{
SvDebugPrint("CPUID: %08x-%08x : %08x %08x %08x %08x\n",
leaf,
subLeaf,
registers[0],
registers[1],
registers[2],
registers[3]);
}
//
// Then, advance RIP to "complete" the instruction.
//
VpData->GuestVmcb.StateSaveArea.Rip = VpData->GuestVmcb.ControlArea.NRip;
}
/*!
@brief Handles #VMEXIT due to execution of the WRMSR and RDMSR
instructions.
@details This protects EFER.SVME from being cleared by the guest by
injecting #GP when it is about to be cleared. For other MSR
access, it passes-through.
@param[in,out] VpData - Per processor data.
@param[in,out] GuestContext - Guest's GPRs.
*/
_IRQL_requires_same_
static
VOID
SvHandleMsrAccess (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData,
_Inout_ PGUEST_CONTEXT GuestContext
)
{
ULARGE_INTEGER value;
UINT32 msr;
BOOLEAN writeAccess;
msr = GuestContext->VpRegs->Rcx & MAXUINT32;
writeAccess = (VpData->GuestVmcb.ControlArea.ExitInfo1 != 0);
//
// If IA32_MSR_EFER is accessed for write, we must protect the EFER_SVME bit
// from being cleared.
//
if (msr == IA32_MSR_EFER)
{
//
// #VMEXIT on IA32_MSR_EFER access should only occur on write access.
//
NT_ASSERT(writeAccess != FALSE);
value.LowPart = GuestContext->VpRegs->Rax & MAXUINT32;
value.HighPart = GuestContext->VpRegs->Rdx & MAXUINT32;
if ((value.QuadPart & EFER_SVME) == 0)
{
//
// Inject #GP if the guest attempts to clear the SVME bit. Protection of
// this bit is required because clearing the bit while guest is running
// leads to undefined behavior.
//
SvInjectGeneralProtectionException(VpData);
return;
}
//
// Otherwise, update the MSR as requested. Important to note that the value
// should be checked not to allow any illegal values, and inject #GP as
// needed. Otherwise, the hypervisor attempts to resume the guest with an
// illegal EFER and immediately receives #VMEXIT due to VMEXIT_INVALID,
// which in our case, results in a bug check. See "Extended Feature Enable
// Register (EFER)" for what values are allowed.
//
// This code does not implement the check intentionally, for simplicity.
//
VpData->GuestVmcb.StateSaveArea.Efer = value.QuadPart;
}
else
{
//
// If the MSR being accessed is not IA32_MSR_EFER, assert that #VMEXIT
// can only occur on access to MSR outside the ranges controlled with
// the MSR permissions map. This is true because the map is configured
// not to intercept any MSR access but IA32_MSR_EFER. See
// "MSR Ranges Covered by MSRPM" in "MSR Intercepts" for the MSR ranges
// controlled by the map.
//
// Note that VMware Workstation has a bug that access to unimplemented
// MSRs unconditionally causes #VMEXIT ignoring bits in the MSR
// permissions map. This can be tested by reading MSR zero, for example.
//
NT_ASSERT(((msr > 0x00001fff) && (msr < 0xc0000000)) ||
((msr > 0xc0001fff) && (msr < 0xc0010000)) ||
(msr > 0xc0011fff));
//
// Execute WRMSR or RDMSR on behalf of the guest. Important that this
// can cause bug check when the guest tries to access unimplemented MSR
// *even within the SEH block* because the below WRMSR or RDMSR raises
// #GP and are not protected by the SEH block (or cannot be protected
// either as this code run outside the thread stack region Windows
// requires to proceed SEH). Hypervisors typically handle this by noop-ing
// WRMSR and returning zero for RDMSR with non-architecturally defined
// MSRs. Alternatively, one can probe which MSRs should cause #GP prior
// to installation of a hypervisor and the hypervisor can emulate the
// results.
//
if (writeAccess != FALSE)
{
value.LowPart = GuestContext->VpRegs->Rax & MAXUINT32;
value.HighPart = GuestContext->VpRegs->Rdx & MAXUINT32;
__writemsr(msr, value.QuadPart);
}
else
{
value.QuadPart = __readmsr(msr);
GuestContext->VpRegs->Rax = value.LowPart;
GuestContext->VpRegs->Rdx = value.HighPart;
}
}
//
// Then, advance RIP to "complete" the instruction.
//
VpData->GuestVmcb.StateSaveArea.Rip = VpData->GuestVmcb.ControlArea.NRip;
}
/*!
@brief Handles #VMEXIT due to execution of the VMRUN instruction.
@details This function always injects #GP to the guest.
@param[in,out] VpData - Per processor data.
@param[in,out] GuestContext - Guest's GPRs.
*/
_IRQL_requires_same_
static
VOID
SvHandleVmrun (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData,
_Inout_ PGUEST_CONTEXT GuestContext
)
{
UNREFERENCED_PARAMETER(GuestContext);
SvInjectGeneralProtectionException(VpData);
}
/*!
@brief C-level entry point of the host code called from SvLaunchVm.
@details This function loads save host state first, and then, handles
#VMEXIT which may or may not change guest's state via VpData
or GuestRegisters.
Interrupts are disabled when this function is called due to
the cleared GIF. Not all host state are loaded yet, so do it
with the VMLOAD instruction.
If the #VMEXIT handler detects a request to unload the
hypervisor, this function loads guest state, disables SVM
and returns to execution flow where the #VMEXIT triggered.
@param[in,out] VpData - Per processor data.
@param[in,out] GuestRegisters - Guest's GPRs.
@result TRUE when virtualization is terminated; otherwise FALSE.
*/
_IRQL_requires_same_
EXTERN_C
BOOLEAN
NTAPI
SvHandleVmExit (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData,
_Inout_ PGUEST_REGISTERS GuestRegisters
)
{
GUEST_CONTEXT guestContext;
KIRQL oldIrql;
guestContext.VpRegs = GuestRegisters;
guestContext.ExitVm = FALSE;
//
// Load some host state that are not loaded on #VMEXIT.
//
__svm_vmload(VpData->HostStackLayout.HostVmcbPa);
NT_ASSERT(VpData->HostStackLayout.Reserved1 == MAXUINT64);
//
// Raise the IRQL to the DISPATCH_LEVEL level. This has no actual effect since
// interrupts are disabled at #VMEXI but warrants bug check when some of
// kernel API that are not usable on this context is called with Driver
// Verifier. This protects developers from accidentally writing such #VMEXIT
// handling code. This should actually raise IRQL to HIGH_LEVEL to represent
// this running context better, but our Logger code is not designed to run at
// that level unfortunately. Finally, note that this API is a thin wrapper
// of mov-to-CR8 on x64 and safe to call on this context.
//
oldIrql = KeGetCurrentIrql();
if (oldIrql < DISPATCH_LEVEL)
{
KeRaiseIrqlToDpcLevel();
}
//
// Guest's RAX is overwritten by the host's value on #VMEXIT and saved in
// the VMCB instead. Reflect the guest RAX to the context.
//
GuestRegisters->Rax = VpData->GuestVmcb.StateSaveArea.Rax;
//
// Update the _KTRAP_FRAME structure values in hypervisor stack, so that
// Windbg can reconstruct call stack of the guest during debug session.
// This is optional but very useful thing to do for debugging.
//
VpData->HostStackLayout.TrapFrame.Rsp = VpData->GuestVmcb.StateSaveArea.Rsp;
VpData->HostStackLayout.TrapFrame.Rip = VpData->GuestVmcb.ControlArea.NRip;
//
// Handle #VMEXIT according with its reason.
//
switch (VpData->GuestVmcb.ControlArea.ExitCode)
{
case VMEXIT_CPUID:
SvHandleCpuid(VpData, &guestContext);
break;
case VMEXIT_MSR:
SvHandleMsrAccess(VpData, &guestContext);
break;
case VMEXIT_VMRUN:
SvHandleVmrun(VpData, &guestContext);
break;
default:
SV_DEBUG_BREAK();
#pragma prefast(suppress : __WARNING_USE_OTHER_FUNCTION, "Unrecoverable path.")
KeBugCheck(MANUALLY_INITIATED_CRASH);
}
//
// Again, no effect to change IRQL but restoring it here since a #VMEXIT
// handler where the developers most likely call the kernel API inadvertently
// is already executed.
//
if (oldIrql < DISPATCH_LEVEL)
{
KeLowerIrql(oldIrql);
}
//
// Terminate the SimpleSvm hypervisor if requested.
//
if (guestContext.ExitVm != FALSE)
{
NT_ASSERT(VpData->GuestVmcb.ControlArea.ExitCode == VMEXIT_CPUID);
//
// Set return values of CPUID instruction as follows:
// RBX = An address to return
// RCX = A stack pointer to restore
// EDX:EAX = An address of per processor data to be freed by the caller
//
guestContext.VpRegs->Rax = reinterpret_cast<UINT64>(VpData) & MAXUINT32;
guestContext.VpRegs->Rbx = VpData->GuestVmcb.ControlArea.NRip;
guestContext.VpRegs->Rcx = VpData->GuestVmcb.StateSaveArea.Rsp;
guestContext.VpRegs->Rdx = reinterpret_cast<UINT64>(VpData) >> 32;
//
// Load guest state (currently host state is loaded).
//
__svm_vmload(MmGetPhysicalAddress(&VpData->GuestVmcb).QuadPart);
//
// Set the global interrupt flag (GIF) but still disable interrupts by
// clearing IF. GIF must be set to return to the normal execution, but
// interruptions are not desirable until SVM is disabled as it would
// execute random kernel-code in the host context.
//
_disable();
__svm_stgi();
//
// Disable SVM, and restore the guest RFLAGS. This may enable interrupts.
// Some of arithmetic flags are destroyed by the subsequent code.
//
__writemsr(IA32_MSR_EFER, __readmsr(IA32_MSR_EFER) & ~EFER_SVME);
__writeeflags(VpData->GuestVmcb.StateSaveArea.Rflags);
goto Exit;
}
//
// Reflect potentially updated guest's RAX to VMCB. Again, unlike other GPRs,
// RAX is loaded from VMCB on VMRUN.
//
VpData->GuestVmcb.StateSaveArea.Rax = guestContext.VpRegs->Rax;
Exit:
NT_ASSERT(VpData->HostStackLayout.Reserved1 == MAXUINT64);
return guestContext.ExitVm;
}
/*!
@brief Returns attributes of a segment specified by the segment selector.
@details This function locates a segment descriptor from the segment
selector and the GDT base, extracts attributes of the segment,
and returns it. The returned value is the same as what the "dg"
command of Windbg shows as "Flags". Here is an example output
with 0x18 of the selector:
----
0: kd> dg 18
P Si Gr Pr Lo
Sel Base Limit Type l ze an es ng Flags
---- ----------------- ----------------- ---------- - -- -- -- -- --------
0018 00000000`00000000 00000000`00000000 Data RW Ac 0 Bg By P Nl 00000493
----
@param[in] SegmentSelector - A segment selector to get attributes of a
corresponding descriptor.
@param[in] GdtBase - A base address of GDT.
@result Attributes of the segment.
*/
_IRQL_requires_same_
_Check_return_
static
UINT16
SvGetSegmentAccessRight (
_In_ UINT16 SegmentSelector,
_In_ ULONG_PTR GdtBase
)
{
PSEGMENT_DESCRIPTOR descriptor;
SEGMENT_ATTRIBUTE attribute;
//
// Get a segment descriptor corresponds to the specified segment selector.
//
descriptor = reinterpret_cast<PSEGMENT_DESCRIPTOR>(
GdtBase + (SegmentSelector & ~RPL_MASK));
//
// Extract all attribute fields in the segment descriptor to a structure
// that describes only attributes (as opposed to the segment descriptor
// consists of multiple other fields).
//
attribute.Fields.Type = descriptor->Fields.Type;
attribute.Fields.System = descriptor->Fields.System;
attribute.Fields.Dpl = descriptor->Fields.Dpl;
attribute.Fields.Present = descriptor->Fields.Present;
attribute.Fields.Avl = descriptor->Fields.Avl;
attribute.Fields.LongMode = descriptor->Fields.LongMode;
attribute.Fields.DefaultBit = descriptor->Fields.DefaultBit;
attribute.Fields.Granularity = descriptor->Fields.Granularity;
attribute.Fields.Reserved1 = 0;
return attribute.AsUInt16;
}
/*!
@brief Tests whether the SimpleSvm hypervisor is installed.
@details This function checks a result of CPUID leaf 40000000h, which
should return a vendor name of the hypervisor if any of those
who implement the Microsoft Hypervisor interface is installed.
If the SimpleSvm hypervisor is installed, this should return
"SimpleSvm", and if no hypervisor is installed, it the result of
CPUID is undefined. For more details of the interface, see
"Requirements for implementing the Microsoft Hypervisor interface"
https://msdn.microsoft.com/en-us/library/windows/hardware/Dn613994(v=vs.85).aspx
@result TRUE when the SimpleSvm is installed; otherwise, FALSE.
*/
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
_Check_return_
static
BOOLEAN
SvIsSimpleSvmHypervisorInstalled (
VOID
)
{
int registers[4]; // EAX, EBX, ECX, and EDX
char vendorId[13];
//
// When the SimpleSvm hypervisor is installed, CPUID leaf 40000000h will
// return "SimpleSvm " as the vendor name.
//
__cpuid(registers, CPUID_HV_VENDOR_AND_MAX_FUNCTIONS);
RtlCopyMemory(vendorId + 0, ®isters[1], sizeof(registers[1]));
RtlCopyMemory(vendorId + 4, ®isters[2], sizeof(registers[2]));
RtlCopyMemory(vendorId + 8, ®isters[3], sizeof(registers[3]));
vendorId[12] = ANSI_NULL;
return (strcmp(vendorId, "SimpleSvm ") == 0);
}
/*!
@brief Virtualizes the current processor.
@details This function enables SVM, initialize VMCB with the current
processor state, and enters the guest mode on the current
processor.
@param[in,out] VpData - The address of per processor data.
@param[in] SharedVpData - The address of share data.
@param[in] ContextRecord - The address of CONETEXT to use as an initial
context of the processor after it is virtualized.
*/
_IRQL_requires_max_(DISPATCH_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
static
VOID
SvPrepareForVirtualization (
_Inout_ PVIRTUAL_PROCESSOR_DATA VpData,
_In_ PSHARED_VIRTUAL_PROCESSOR_DATA SharedVpData,
_In_ const CONTEXT* ContextRecord
)
{
DESCRIPTOR_TABLE_REGISTER gdtr, idtr;
PHYSICAL_ADDRESS guestVmcbPa, hostVmcbPa, hostStateAreaPa, pml4BasePa, msrpmPa;
//
// Capture the current GDTR and IDTR to use as initial values of the guest
// mode.