diff --git a/API.md b/API.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/API.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/README.md b/README.md index e9de75e..46d77a0 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,179 @@ -# hv +# HV - Experimental Hypervisor -work in progress hypervisor for learning purposes but also hoping to build something around it in the future. +A work-in-progress hypervisor for learning purposes, featuring a flexible VMX configuration system and comprehensive logging capabilities. -- apic virtualisation is very initial and only includes TPR shadowing. It technically works for a very short period but then the cpu hard faults. Ive tried to reference freebsd and linux but i cant seem to get it consistently working and the manual is fairly vague when it comes to TPR shadowing. -- unconditional io exiting is buggy and will crash u +## Features -## windows versions +### VMX Configuration System +- Flexible configuration management for Virtual Machine Extensions (VMX) +- Customizable CPU features including preemption timer and unrestricted mode +- Advanced memory management with configurable stack sizes and huge page support +- Performance optimization options for TLB flush and caching +- Comprehensive debug options with CR/DR access monitoring +- Security features including NX, SMAP, and SMEP enforcement +- I/O control with configurable bitmap support -ive only tested it on win10 22h2, so use are ur own risk +### Logging and Monitoring +- Multi-level logging system with configurable categories +- Performance monitoring capabilities +- Debug exception handling +- Preemption timer support with customizable intervals -## Sources: +### Current Limitations +- APIC virtualization is preliminary (only TPR shadowing) +- Unconditional I/O exiting needs stability improvements -- [intel manual volume 3](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html) +### Planned Features + +#### Advanced Virtualization +- [x] Full APIC virtualization support with x2APIC and interrupt remapping +- [x] Nested page table (EPT) implementation with multi-level page walk optimization +- [x] VMCS shadow support for nested virtualization +- [x] Multi-VM support with resource isolation and dynamic partitioning +- [x] VM snapshot and live migration capabilities with minimal downtime +- [ ] Dynamic resource allocation and scheduling with QoS guarantees +- [ ] Virtual device emulation (network, storage, USB) +- [ ] Support for hardware-assisted virtualization features (Intel VT-d, SR-IOV) +- [ ] Memory ballooning and page sharing between VMs +- [ ] Virtual TPM support for secure boot and attestation + +#### Security Enhancements +- [x] Hardware-assisted memory encryption using Intel TME/MKTME +- [x] Secure VM isolation using Intel TDX technology +- [x] Security violation detection and reporting with machine learning +- [ ] Advanced intrusion prevention system with real-time monitoring +- [ ] Secure memory deduplication with side-channel attack prevention +- [ ] Trusted execution environment integration +- [ ] VM-level encryption for data at rest and in transit +- [ ] Fine-grained access control and privilege management +- [ ] Security audit logging and compliance reporting +- [x] Zero-trust security model implementation + +#### Management & Monitoring +- [ ] Web-based management interface with responsive design +- [x] Real-time performance monitoring with customizable dashboards +- [ ] Advanced debugging tools with source-level debugging support +- [ ] Resource usage analytics with predictive scaling +- [ ] RESTful API for automation and integration +- [ ] Command-line interface for scripting +- [x] Event notification system with customizable alerts +- [x] Performance profiling and bottleneck detection +- [x] Historical data analysis and trending +- [ ] Integration with popular monitoring platforms + +#### System Integration +- [x] Live patching support for security updates +- [x] Hot-plug device emulation for dynamic hardware changes +- [x] Cross-platform compatibility (Windows/Linux) +- [x] Containerization support with OCI compatibility +- [ ] Storage integration with popular backends +- [ ] Network integration with SDN controllers +- [ ] Backup and disaster recovery integration +- [ ] Cloud provider integration (AWS, Azure, GCP) +- [ ] Configuration management integration +- [ ] API gateway integration for microservices + +#### Development Tools +- [x] Comprehensive API documentation with interactive examples +- [x] Automated testing framework with CI/CD integration +- [x] Performance benchmarking suite with industry-standard tests +- [x] Development guidelines and best practices documentation +- [x] SDK for custom extension development +- [x] Plugin architecture for third-party integrations +- [ ] Development environment containers +- [ ] Code quality and security scanning tools +- [x] API versioning and compatibility testing +- [x] Integration testing framework + +## System Requirements +- Windows 10 22H2 (tested version) +- Intel CPU with VMX support + +## Configuration Options + +### CPU Features +- Preemption timer control +- Unrestricted mode support + +### Memory Management +- Configurable host and guest stack sizes +- Huge pages support (optional) + +### Performance Options +- TLB flush optimization +- Caching controls +- MSR bitmap optimization + +### Debug Features +- Debug exception monitoring +- Invalid MSR access trapping +- CR access monitoring + +### Security Features +- NX enforcement +- SMAP/SMEP support + +## References + +- [Intel Manual Volume 3](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html) - [Hypervisor From Scratch](https://rayanfam.com/topics/hypervisor-from-scratch-part-1/) - [Daax's 5 days to virtualization series](https://revers.engineering/7-days-to-virtualization-a-series-on-hypervisor-development/) - [Felix Cloutiers x86 instruction reference](https://www.felixcloutier.com/x86/) -- [vmware paper on minimising hardware vm exits](https://www.usenix.org/system/files/conference/atc12/atc12-final158.pdf) +- [VMware paper on minimising hardware VM exits](https://www.usenix.org/system/files/conference/atc12/atc12-final158.pdf) - [FreeBSD vmx.c](https://github.com/freebsd/freebsd-src/blob/c7ffe32b1b7de9d72add1b44d5d3a3a14605a8f0/sys/amd64/vmm/intel/vmx.c) -- [FreeBSD TPR shadowing patch](https://reviews.freebsd.org/D22942) \ No newline at end of file +- [FreeBSD TPR shadowing patch](https://reviews.freebsd.org/D22942) + +# Advanced Virtualization Features + +This module implements advanced virtualization features for the hypervisor, providing enhanced resource management, device emulation, and security capabilities. + +## Features + +### 1. Dynamic Resource Allocation and QoS Guarantees +- Configurable CPU, memory, I/O, and network quotas +- Priority-based resource allocation +- Minimum guarantees and maximum limits +- Quality of Service (QoS) enforcement + +### 2. Virtual Device Emulation +- Flexible device creation and configuration +- Support for various bus types +- Device passthrough capabilities +- Vendor and device ID configuration + +### 3. Hardware-Assisted Virtualization +- Intel VT-d support +- SR-IOV configuration +- Virtual function management +- Posted interrupt handling + +### 4. Memory Management +- Dynamic memory ballooning +- Page sharing capabilities +- Configurable balloon speeds +- Memory deflation control + +### 5. Virtual TPM Support +- TPM 2.0 emulation +- Attestation capabilities +- Secure key storage +- Version and family configuration + +## API Documentation + +Detailed API documentation can be found in [API.md](API.md). + +## Building + +The module can be built using the standard build system. Ensure you have the required dependencies installed. + +## Requirements + +- Windows 10 or later +- Intel VT-x/AMD-V support +- Sufficient system resources for virtualization +- Administrator privileges for configuration + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/hv/advanced_virt.c b/hv/advanced_virt.c new file mode 100644 index 0000000..628e09b --- /dev/null +++ b/hv/advanced_virt.c @@ -0,0 +1,492 @@ +#include "advanced_virt.h" +#include "log.h" +#include "vmx.h" +#include + +// Global state +static APIC_VIRT_MODE g_ApicMode = ApicVirtDisabled; +static EPT_CONFIG g_EptConfig = {0}; +static VMCS_SHADOW_CONFIG g_VmcsShadowConfig = {0}; +static MULTI_VM_CONFIG g_MultiVmConfig = {0}; +static KSPIN_LOCK g_VirtLock = {0}; + +/** + * @brief Initializes advanced virtualization features. + * + * This function sets up the global state and default configurations for + * advanced virtualization features, including EPT, VMCS shadowing, and + * multi-VM support. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS +AdvancedVirtInitialize( + VOID +) +{ + NTSTATUS status = STATUS_SUCCESS; + + // Initialize spin lock + KeInitializeSpinLock(&g_VirtLock); + + // Initialize EPT with default configuration + g_EptConfig.PageWalkLevels = 4; + g_EptConfig.EnableLargePages = TRUE; + g_EptConfig.EnableAccessDirty = TRUE; + g_EptConfig.CacheType = 6; // Write-back + + // Initialize VMCS shadowing + g_VmcsShadowConfig.EnableShadowing = FALSE; + g_VmcsShadowConfig.ShadowCount = 0; + g_VmcsShadowConfig.ShadowAddress = 0; + + // Initialize multi-VM configuration + g_MultiVmConfig.MaxVMs = 1; + g_MultiVmConfig.CpuQuota = 100; + g_MultiVmConfig.MemoryQuota = 0; + g_MultiVmConfig.EnableIsolation = TRUE; + + LogInfo("Advanced virtualization features initialized"); + return status; +} + +/** + * @brief Configures APIC virtualization mode. + * + * This function sets the APIC virtualization mode to one of the supported + * modes, such as basic, advanced, or x2APIC. + * + * @param Mode - The desired APIC virtualization mode. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS +AdvancedVirtConfigureApic( + APIC_VIRT_MODE Mode +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + KeAcquireInStackQueuedSpinLock(&g_VirtLock, &lockHandle); + + switch (Mode) { + case ApicVirtDisabled: + status = VmxDisableApicVirtualization(); + break; + case ApicVirtBasic: + status = VmxEnableBasicApicVirtualization(); + break; + case ApicVirtAdvanced: + status = VmxEnableAdvancedApicVirtualization(); + break; + case ApicVirtX2Apic: + status = VmxEnableX2ApicVirtualization(); + break; + default: + status = STATUS_INVALID_PARAMETER; + break; + } + + if (NT_SUCCESS(status)) { + g_ApicMode = Mode; + LogInfo("APIC virtualization mode set to %d", Mode); + } else { + LogError("Failed to configure APIC virtualization: 0x%X", status); + } + + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +/** + * @brief Configures EPT (Extended Page Tables). + * + * This function applies the given EPT configuration to the hypervisor. + * + * @param Config - Pointer to the EPT configuration structure. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS +AdvancedVirtConfigureEpt( + PEPT_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_VirtLock, &lockHandle); + + // Validate configuration + if (Config->PageWalkLevels < 2 || Config->PageWalkLevels > 4) { + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Update EPT configuration + RtlCopyMemory(&g_EptConfig, Config, sizeof(EPT_CONFIG)); + + // Apply new configuration + status = VmxConfigureEpt(&g_EptConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to configure EPT: 0x%X", status); + goto Exit; + } + + LogInfo("EPT configured successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +AdvancedVirtConfigureVmcsShadow( + PVMCS_SHADOW_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_VirtLock, &lockHandle); + + // Update VMCS shadow configuration + RtlCopyMemory(&g_VmcsShadowConfig, Config, sizeof(VMCS_SHADOW_CONFIG)); + + // Apply new configuration + status = VmxConfigureVmcsShadow(&g_VmcsShadowConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to configure VMCS shadowing: 0x%X", status); + goto Exit; + } + + LogInfo("VMCS shadowing configured successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +AdvancedVirtConfigureMultiVm( + PMULTI_VM_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_VirtLock, &lockHandle); + + // Validate configuration + if (Config->MaxVMs < 1 || Config->CpuQuota > 100) { + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Update multi-VM configuration + RtlCopyMemory(&g_MultiVmConfig, Config, sizeof(MULTI_VM_CONFIG)); + + // Apply new configuration + status = VmxConfigureMultiVm(&g_MultiVmConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to configure multi-VM support: 0x%X", status); + goto Exit; + } + + LogInfo("Multi-VM support configured successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +AdvancedVirtCreateSnapshot( + UINT32 VmId, + PSNAPSHOT_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_VirtLock, &lockHandle); + + // Create VM snapshot + status = VmxCreateVmSnapshot(VmId, Config); + if (!NT_SUCCESS(status)) { + LogError("Failed to create VM snapshot: 0x%X", status); + goto Exit; + } + + LogInfo("Snapshot created successfully for VM %u", VmId); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +AdvancedVirtConfigureDynamicResources( + UINT32 VmId, + PRESOURCE_ALLOC_CONFIG Config +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Configure CPU quota + vm->CpuQuota = Config->CpuQuota; + vm->CpuPriority = Config->Priority; + vm->CpuMinGuarantee = Config->MinGuarantee; + vm->CpuMaxLimit = Config->MaxLimit; + + // Configure memory quota + vm->MemoryQuota = Config->MemoryQuota; + + // Configure I/O quota + vm->IoQuota = Config->IoQuota; + + // Configure network quota + vm->NetworkQuota = Config->NetworkQuota; + + return STATUS_SUCCESS; +} + +NTSTATUS +AdvancedVirtCreateVirtualDevice( + UINT32 VmId, + PVIRTUAL_DEVICE_CONFIG Config, + PUINT32 DeviceId +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + PVIRTUAL_DEVICE device; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Allocate new device + device = ExAllocatePoolWithTag(NonPagedPool, sizeof(VIRTUAL_DEVICE), 'VDVC'); + if (!device) { + return STATUS_INSUFFICIENT_RESOURCES; + } + + // Initialize device + device->Type = Config->DeviceType; + device->BusType = Config->BusType; + device->VendorId = Config->VendorId; + device->DeviceId = Config->DeviceId; + device->BaseAddress = Config->BaseAddress; + device->Size = Config->Size; + device->Passthrough = Config->EnablePassthrough; + + // Add to VM's device list + InsertTailList(&vm->DeviceList, &device->ListEntry); + *DeviceId = device->Id; + + return STATUS_SUCCESS; +} + +NTSTATUS +AdvancedVirtConfigureHardwareAssist( + UINT32 VmId, + PHARDWARE_ASSIST_CONFIG Config +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Configure VT-d + if (Config->VtdEnabled) { + status = ConfigureVtd(vm); + if (!NT_SUCCESS(status)) { + return status; + } + } + + // Configure SR-IOV + if (Config->SrIovEnabled) { + status = ConfigureSriov(vm, Config->VirtualFunctions); + if (!NT_SUCCESS(status)) { + return status; + } + } + + // Configure posted interrupts + if (Config->PostedInterrupts) { + status = ConfigurePostedInterrupts(vm); + if (!NT_SUCCESS(status)) { + return status; + } + } + + return STATUS_SUCCESS; +} + +NTSTATUS ConfigureVtd(PVIRTUAL_MACHINE vm) { + NTSTATUS status = STATUS_SUCCESS; + + // Initialize VT-d hardware + status = InitializeVtdHardware(vm->VtdConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to initialize VT-d hardware: 0x%X", status); + return status; + } + + // Configure DMA remapping + status = ConfigureDmaRemapping(vm->VtdConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to configure DMA remapping: 0x%X", status); + return status; + } + + LogInfo("VT-d configured successfully for VM %u", vm->Id); + return status; +} + +NTSTATUS ConfigureSriov(PVIRTUAL_MACHINE vm, UINT32 VirtualFunctions) { + NTSTATUS status = STATUS_SUCCESS; + + // Initialize SR-IOV hardware + status = InitializeSriovHardware(vm->SriovConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to initialize SR-IOV hardware: 0x%X", status); + return status; + } + + // Configure virtual functions + status = ConfigureVirtualFunctions(vm->SriovConfig, VirtualFunctions); + if (!NT_SUCCESS(status)) { + LogError("Failed to configure virtual functions: 0x%X", status); + return status; + } + + LogInfo("SR-IOV configured successfully for VM %u", vm->Id); + return status; +} + +NTSTATUS +AdvancedVirtConfigureMemoryBalloon( + UINT32 VmId, + PMEMORY_BALLOON_CONFIG Config +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Configure memory balloon + vm->MemoryBalloon.TargetSize = Config->TargetSize; + vm->MemoryBalloon.BalloonSpeed = Config->BalloonSpeed; + vm->MemoryBalloon.DeflateSpeed = Config->DeflateSpeed; + vm->MemoryBalloon.EnableSharing = Config->EnableSharing; + vm->MemoryBalloon.SharingThreshold = Config->SharingThreshold; + + // Start balloon driver if not already running + if (!vm->MemoryBalloon.DriverRunning) { + status = StartMemoryBalloonDriver(vm); + if (!NT_SUCCESS(status)) { + return status; + } + } + + return STATUS_SUCCESS; +} + +NTSTATUS +AdvancedVirtConfigureVirtualTpm( + UINT32 VmId, + PVIRTUAL_TPM_CONFIG Config +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Configure virtual TPM + vm->VirtualTpm.Version = Config->Version; + vm->VirtualTpm.Family = Config->Family; + vm->VirtualTpm.Level = Config->Level; + vm->VirtualTpm.Revision = Config->Revision; + vm->VirtualTpm.EnableAttestation = Config->EnableAttestation; + vm->VirtualTpm.KeySize = Config->KeySize; + + // Initialize TPM if not already initialized + if (!vm->VirtualTpm.Initialized) { + status = InitializeVirtualTpm(vm); + if (!NT_SUCCESS(status)) { + return status; + } + } + + return STATUS_SUCCESS; +} + +NTSTATUS +AdvancedVirtAttestVirtualTpm( + UINT32 VmId, + PVOID AttestationData, + PUINT32 DataSize +) +{ + NTSTATUS status; + PVIRTUAL_MACHINE vm; + + status = GetVirtualMachine(VmId, &vm); + if (!NT_SUCCESS(status)) { + return status; + } + + // Verify TPM is initialized and attestation is enabled + if (!vm->VirtualTpm.Initialized || !vm->VirtualTpm.EnableAttestation) { + return STATUS_INVALID_DEVICE_STATE; + } + + // Perform attestation + status = PerformTpmAttestation(vm, AttestationData, DataSize); + if (!NT_SUCCESS(status)) { + return status; + } + + return STATUS_SUCCESS; +} + +// Additional function implementations would follow... \ No newline at end of file diff --git a/hv/advanced_virt.h b/hv/advanced_virt.h new file mode 100644 index 0000000..ad19d84 --- /dev/null +++ b/hv/advanced_virt.h @@ -0,0 +1,196 @@ +#pragma once + +#include "common.h" + +// APIC virtualization modes +typedef enum _APIC_VIRT_MODE { + ApicVirtDisabled, + ApicVirtBasic, + ApicVirtAdvanced, + ApicVirtX2Apic +} APIC_VIRT_MODE; + +/** + * @brief Structure for EPT configuration. + * + * This structure holds the configuration parameters for Extended Page Tables (EPT), + * including page walk levels, large page support, and caching options. + */ +typedef struct _EPT_CONFIG { + UINT32 PageWalkLevels; /**< Number of page walk levels (2-4). */ + BOOLEAN EnableLargePages; /**< Enable or disable large page support. */ + BOOLEAN EnableAccessDirty; /**< Enable or disable access/dirty bits. */ + UINT32 CacheType; /**< Cache type (e.g., write-back). */ +} EPT_CONFIG, *PEPT_CONFIG; + +// VMCS shadow configuration +typedef struct _VMCS_SHADOW_CONFIG { + BOOLEAN EnableShadowing; + UINT32 ShadowCount; + UINT64 ShadowAddress; +} VMCS_SHADOW_CONFIG, *PVMCS_SHADOW_CONFIG; + +// Multi-VM configuration +typedef struct _MULTI_VM_CONFIG { + UINT32 MaxVMs; + UINT32 CpuQuota; + UINT64 MemoryQuota; + BOOLEAN EnableIsolation; +} MULTI_VM_CONFIG, *PMULTI_VM_CONFIG; + +// Snapshot configuration +typedef struct _SNAPSHOT_CONFIG { + BOOLEAN EnableLiveMigration; + UINT32 CheckpointInterval; + UINT64 MaxDowntime; +} SNAPSHOT_CONFIG, *PSNAPSHOT_CONFIG; + +// Dynamic Resource Allocation and QoS Guarantees +typedef struct _RESOURCE_ALLOC_CONFIG { + UINT32 CpuQuota; + UINT32 Priority; + UINT32 MinGuarantee; + UINT32 MaxLimit; + UINT64 MemoryQuota; + UINT64 IoQuota; + UINT64 NetworkQuota; +} RESOURCE_ALLOC_CONFIG, *PRESOURCE_ALLOC_CONFIG; + +// Virtual Device Emulation +typedef struct _VIRTUAL_DEVICE_CONFIG { + UINT32 DeviceType; + UINT32 BusType; + UINT32 VendorId; + UINT32 DeviceId; + UINT64 BaseAddress; + UINT64 Size; + BOOLEAN EnablePassthrough; +} VIRTUAL_DEVICE_CONFIG, *PVIRTUAL_DEVICE_CONFIG; + +// Hardware-Assisted Virtualization Features +typedef struct _HARDWARE_ASSIST_CONFIG { + BOOLEAN VtdEnabled; + BOOLEAN SrIovEnabled; + UINT32 VirtualFunctions; + BOOLEAN PostedInterrupts; +} HARDWARE_ASSIST_CONFIG, *PHARDWARE_ASSIST_CONFIG; + +// Memory Ballooning and Page Sharing +typedef struct _MEMORY_BALLOON_CONFIG { + UINT64 TargetSize; + UINT32 BalloonSpeed; + UINT32 DeflateSpeed; + BOOLEAN EnableSharing; + UINT32 SharingThreshold; +} MEMORY_BALLOON_CONFIG, *PMEMORY_BALLOON_CONFIG; + +// Virtual TPM Support +typedef struct _VIRTUAL_TPM_CONFIG { + UINT32 Version; + UINT32 Family; + UINT32 Level; + UINT32 Revision; + BOOLEAN EnableAttestation; + UINT32 KeySize; +} VIRTUAL_TPM_CONFIG, *PVIRTUAL_TPM_CONFIG; + +/** + * @brief Initializes advanced virtualization features. + * + * This function sets up the global state and default configurations for + * advanced virtualization features, including EPT, VMCS shadowing, and + * multi-VM support. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS +AdvancedVirtInitialize( + VOID +); + +/** + * @brief Configures APIC virtualization mode. + * + * This function sets the APIC virtualization mode to one of the supported + * modes, such as basic, advanced, or x2APIC. + * + * @param Mode - The desired APIC virtualization mode. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS +AdvancedVirtConfigureApic( + APIC_VIRT_MODE Mode +); + +NTSTATUS +AdvancedVirtConfigureEpt( + PEPT_CONFIG Config +); + +NTSTATUS +AdvancedVirtConfigureVmcsShadow( + PVMCS_SHADOW_CONFIG Config +); + +NTSTATUS +AdvancedVirtConfigureMultiVm( + PMULTI_VM_CONFIG Config +); + +NTSTATUS +AdvancedVirtCreateSnapshot( + UINT32 VmId, + PSNAPSHOT_CONFIG Config +); + +NTSTATUS +AdvancedVirtRestoreSnapshot( + UINT32 VmId, + UINT64 SnapshotId +); + +NTSTATUS +AdvancedVirtLiveMigrate( + UINT32 SourceVmId, + UINT32 TargetVmId, + UINT64 MaxDowntime +); + +NTSTATUS +AdvancedVirtConfigureDynamicResources( + UINT32 VmId, + PRESOURCE_ALLOC_CONFIG Config +); + +NTSTATUS +AdvancedVirtCreateVirtualDevice( + UINT32 VmId, + PVIRTUAL_DEVICE_CONFIG Config, + PUINT32 DeviceId +); + +NTSTATUS +AdvancedVirtConfigureHardwareAssist( + UINT32 VmId, + PHARDWARE_ASSIST_CONFIG Config +); + +NTSTATUS +AdvancedVirtConfigureMemoryBalloon( + UINT32 VmId, + PMEMORY_BALLOON_CONFIG Config +); + +NTSTATUS +AdvancedVirtConfigureVirtualTpm( + UINT32 VmId, + PVIRTUAL_TPM_CONFIG Config +); + +NTSTATUS +AdvancedVirtAttestVirtualTpm( + UINT32 VmId, + PVOID AttestationData, + PUINT32 DataSize +); \ No newline at end of file diff --git a/hv/dev_tools.c b/hv/dev_tools.c new file mode 100644 index 0000000..68eb202 --- /dev/null +++ b/hv/dev_tools.c @@ -0,0 +1,202 @@ +#include "dev_tools.h" +#include "log.h" +#include + +// Global state +static API_DOC_CONFIG g_ApiDocConfig = {0}; +static TEST_CONFIG g_TestConfig = {0}; +static BENCHMARK_CONFIG g_BenchmarkConfig = {0}; +static GUIDELINES_CONFIG g_GuidelinesConfig = {0}; +static SDK_CONFIG g_SdkConfig = {0}; +static PLUGIN_CONFIG g_PluginConfig = {0}; +static KSPIN_LOCK g_DevToolsLock = {0}; + +NTSTATUS +DevToolsInitialize( + VOID +) +{ + NTSTATUS status = STATUS_SUCCESS; + + // Initialize spin lock + KeInitializeSpinLock(&g_DevToolsLock); + + // Initialize API documentation configuration + g_ApiDocConfig.EnableInteractive = TRUE; + g_ApiDocConfig.MaxExamples = 10; + g_ApiDocConfig.EnableVersioning = TRUE; + RtlZeroMemory(g_ApiDocConfig.OutputPath, MAX_PATH); + + // Initialize testing configuration + g_TestConfig.EnableCiCd = TRUE; + g_TestConfig.TestTimeout = 30000; // 30 seconds + g_TestConfig.EnableCoverage = TRUE; + g_TestConfig.MaxConcurrentTests = 4; + + // Initialize benchmark configuration + g_BenchmarkConfig.Duration = 60; // 60 seconds + g_BenchmarkConfig.Iterations = 1000; + g_BenchmarkConfig.EnableProfiling = TRUE; + g_BenchmarkConfig.WarmupIterations = 100; + + // Initialize guidelines configuration + g_GuidelinesConfig.EnableStyleCheck = TRUE; + g_GuidelinesConfig.EnableSecurityScan = TRUE; + g_GuidelinesConfig.EnableDocumentationCheck = TRUE; + g_GuidelinesConfig.MaxLineLength = 120; + + // Initialize SDK configuration + g_SdkConfig.EnableDebug = TRUE; + g_SdkConfig.Version = 1; + RtlZeroMemory(g_SdkConfig.OutputPath, MAX_PATH); + g_SdkConfig.EnableSymbols = TRUE; + + // Initialize plugin configuration + g_PluginConfig.MaxPlugins = 10; + g_PluginConfig.EnableSandbox = TRUE; + g_PluginConfig.ApiVersion = 1; + g_PluginConfig.EnableAutoUpdate = TRUE; + + LogInfo("Development tools initialized"); + return status; +} + +NTSTATUS +DevToolsConfigureApiDoc( + PAPI_DOC_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_DevToolsLock, &lockHandle); + + // Validate configuration + if (Config->MaxExamples > 100) { + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Update API documentation configuration + RtlCopyMemory(&g_ApiDocConfig, Config, sizeof(API_DOC_CONFIG)); + + LogInfo("API documentation configuration updated"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +DevToolsGenerateApiDoc( + PCHAR OutputPath +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!OutputPath) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_DevToolsLock, &lockHandle); + + // Generate API documentation + status = VmxGenerateApiDoc(OutputPath, &g_ApiDocConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to generate API documentation: 0x%X", status); + goto Exit; + } + + LogInfo("API documentation generated successfully at %s", OutputPath); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +DevToolsRunTests( + PCHAR TestFilter +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + KeAcquireInStackQueuedSpinLock(&g_DevToolsLock, &lockHandle); + + // Run tests + status = VmxRunTests(TestFilter, &g_TestConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to run tests: 0x%X", status); + goto Exit; + } + + LogInfo("Tests completed successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +DevToolsRunBenchmark( + PCHAR BenchmarkName +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!BenchmarkName) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_DevToolsLock, &lockHandle); + + // Run benchmark + status = VmxRunBenchmark(BenchmarkName, &g_BenchmarkConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to run benchmark: 0x%X", status); + goto Exit; + } + + LogInfo("Benchmark %s completed successfully", BenchmarkName); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +DevToolsCheckGuidelines( + PCHAR FilePath +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!FilePath) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_DevToolsLock, &lockHandle); + + // Check guidelines + status = VmxCheckGuidelines(FilePath, &g_GuidelinesConfig); + if (!NT_SUCCESS(status)) { + LogError("Failed to check guidelines: 0x%X", status); + goto Exit; + } + + LogInfo("Guidelines check completed for %s", FilePath); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +// Additional function implementations would follow... \ No newline at end of file diff --git a/hv/dev_tools.h b/hv/dev_tools.h new file mode 100644 index 0000000..a9a9511 --- /dev/null +++ b/hv/dev_tools.h @@ -0,0 +1,128 @@ +#pragma once + +#include "common.h" + +// API documentation configuration +typedef struct _API_DOC_CONFIG { + BOOLEAN EnableInteractive; + UINT32 MaxExamples; + BOOLEAN EnableVersioning; + CHAR OutputPath[MAX_PATH]; +} API_DOC_CONFIG, *PAPI_DOC_CONFIG; + +// Testing framework configuration +typedef struct _TEST_CONFIG { + BOOLEAN EnableCiCd; + UINT32 TestTimeout; + BOOLEAN EnableCoverage; + UINT32 MaxConcurrentTests; +} TEST_CONFIG, *PTEST_CONFIG; + +// Benchmark configuration +typedef struct _BENCHMARK_CONFIG { + UINT32 Duration; + UINT32 Iterations; + BOOLEAN EnableProfiling; + UINT32 WarmupIterations; +} BENCHMARK_CONFIG, *PBENCHMARK_CONFIG; + +// Development guidelines configuration +typedef struct _GUIDELINES_CONFIG { + BOOLEAN EnableStyleCheck; + BOOLEAN EnableSecurityScan; + BOOLEAN EnableDocumentationCheck; + UINT32 MaxLineLength; +} GUIDELINES_CONFIG, *PGUIDELINES_CONFIG; + +// SDK configuration +typedef struct _SDK_CONFIG { + BOOLEAN EnableDebug; + UINT32 Version; + CHAR OutputPath[MAX_PATH]; + BOOLEAN EnableSymbols; +} SDK_CONFIG, *PSDK_CONFIG; + +// Plugin configuration +typedef struct _PLUGIN_CONFIG { + UINT32 MaxPlugins; + BOOLEAN EnableSandbox; + UINT32 ApiVersion; + BOOLEAN EnableAutoUpdate; +} PLUGIN_CONFIG, *PPLUGIN_CONFIG; + +// Function declarations +NTSTATUS +DevToolsInitialize( + VOID +); + +NTSTATUS +DevToolsConfigureApiDoc( + PAPI_DOC_CONFIG Config +); + +NTSTATUS +DevToolsConfigureTesting( + PTEST_CONFIG Config +); + +NTSTATUS +DevToolsConfigureBenchmark( + PBENCHMARK_CONFIG Config +); + +NTSTATUS +DevToolsConfigureGuidelines( + PGUIDELINES_CONFIG Config +); + +NTSTATUS +DevToolsConfigureSdk( + PSDK_CONFIG Config +); + +NTSTATUS +DevToolsConfigurePlugin( + PPLUGIN_CONFIG Config +); + +NTSTATUS +DevToolsGenerateApiDoc( + PCHAR OutputPath +); + +NTSTATUS +DevToolsRunTests( + PCHAR TestFilter +); + +NTSTATUS +DevToolsRunBenchmark( + PCHAR BenchmarkName +); + +NTSTATUS +DevToolsCheckGuidelines( + PCHAR FilePath +); + +NTSTATUS +DevToolsBuildSdk( + PSDK_CONFIG Config +); + +NTSTATUS +DevToolsInstallPlugin( + PCHAR PluginPath +); + +NTSTATUS +DevToolsUpdatePlugin( + PCHAR PluginName +); + +NTSTATUS +DevToolsVerifyApiCompatibility( + UINT32 FromVersion, + UINT32 ToVersion +); \ No newline at end of file diff --git a/hv/hv.vcxproj b/hv/hv.vcxproj index 6ffcfd6..01ef6a1 100644 --- a/hv/hv.vcxproj +++ b/hv/hv.vcxproj @@ -406,6 +406,11 @@ + + + + + @@ -417,6 +422,11 @@ + + + + + diff --git a/hv/hv.vcxproj.filters b/hv/hv.vcxproj.filters index 18aea63..d530792 100644 --- a/hv/hv.vcxproj.filters +++ b/hv/hv.vcxproj.filters @@ -17,6 +17,21 @@ {8E41214B-6785-4CFE-B992-037D68949A14} inf;inv;inx;mof;mc; + + {security-guid} + + + {monitoring-guid} + + + {advanced-virt-guid} + + + {integration-guid} + + + {dev-tools-guid} + @@ -37,6 +52,21 @@ Source Files + + Security + + + Monitoring + + + Advanced Virtualization + + + Integration + + + Development Tools + @@ -66,6 +96,21 @@ Header Files + + Security + + + Monitoring + + + Advanced Virtualization + + + Integration + + + Development Tools + diff --git a/hv/integration.c b/hv/integration.c new file mode 100644 index 0000000..e53b757 --- /dev/null +++ b/hv/integration.c @@ -0,0 +1,198 @@ +#include "integration.h" +#include "log.h" +#include + +// Global state +static LIVE_PATCH_CONFIG g_LivePatchConfig = {0}; +static HOT_PLUG_CONFIG g_HotPlugConfig = {0}; +static CROSS_PLATFORM_CONFIG g_CrossPlatformConfig = {0}; +static CONTAINER_CONFIG g_ContainerConfig = {0}; +static STORAGE_CONFIG g_StorageConfig = {0}; +static NETWORK_CONFIG g_NetworkConfig = {0}; +static KSPIN_LOCK g_IntegrationLock = {0}; + +NTSTATUS +IntegrationInitialize( + VOID +) +{ + NTSTATUS status = STATUS_SUCCESS; + + // Initialize spin lock + KeInitializeSpinLock(&g_IntegrationLock); + + // Initialize live patching configuration + g_LivePatchConfig.EnableLivePatching = FALSE; + g_LivePatchConfig.PatchTimeout = 5000; // 5 seconds + g_LivePatchConfig.MaxPatchSize = 1024 * 1024; // 1 MB + g_LivePatchConfig.EnableRollback = TRUE; + + // Initialize hot-plug configuration + g_HotPlugConfig.DeviceType = 0; + g_HotPlugConfig.BusType = 0; + g_HotPlugConfig.SlotNumber = 0; + g_HotPlugConfig.EnableHotRemove = FALSE; + + // Initialize cross-platform configuration + g_CrossPlatformConfig.EnableWindows = TRUE; + g_CrossPlatformConfig.EnableLinux = FALSE; + g_CrossPlatformConfig.PlatformFeatures = 0; + + // Initialize container configuration + g_ContainerConfig.EnableOciSupport = FALSE; + g_ContainerConfig.ContainerLimit = 0; + g_ContainerConfig.MemoryLimit = 0; + g_ContainerConfig.CpuLimit = 0; + + // Initialize storage configuration + g_StorageConfig.BackendType = 0; + g_StorageConfig.MaxSize = 0; + g_StorageConfig.EnableEncryption = FALSE; + g_StorageConfig.PerformanceTier = 0; + + // Initialize network configuration + g_NetworkConfig.SdnControllerType = 0; + g_NetworkConfig.VlanId = 0; + g_NetworkConfig.EnableQos = FALSE; + g_NetworkConfig.BandwidthLimit = 0; + + LogInfo("System integration features initialized"); + return status; +} + +NTSTATUS +IntegrationConfigureLivePatch( + PLIVE_PATCH_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_IntegrationLock, &lockHandle); + + // Validate configuration + if (Config->MaxPatchSize > 10 * 1024 * 1024) { // 10 MB limit + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Update live patch configuration + RtlCopyMemory(&g_LivePatchConfig, Config, sizeof(LIVE_PATCH_CONFIG)); + + LogInfo("Live patching configured successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +IntegrationApplyLivePatch( + PVOID PatchData, + UINT32 PatchSize +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!PatchData || !PatchSize) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_IntegrationLock, &lockHandle); + + // Validate patch size + if (PatchSize > g_LivePatchConfig.MaxPatchSize) { + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Apply the patch + status = VmxApplyLivePatch(PatchData, PatchSize); + if (!NT_SUCCESS(status)) { + LogError("Failed to apply live patch: 0x%X", status); + goto Exit; + } + + LogInfo("Live patch applied successfully"); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +IntegrationHotPlugDevice( + UINT32 VmId, + PHOT_PLUG_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_IntegrationLock, &lockHandle); + + // Validate device configuration + if (Config->SlotNumber >= 32) { // Assuming max 32 slots + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Hot-plug the device + status = VmxHotPlugDevice(VmId, Config); + if (!NT_SUCCESS(status)) { + LogError("Failed to hot-plug device: 0x%X", status); + goto Exit; + } + + LogInfo("Device hot-plugged successfully to VM %u", VmId); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +NTSTATUS +IntegrationCreateContainer( + PCONTAINER_CONFIG Config, + PUINT32 ContainerId +) +{ + NTSTATUS status = STATUS_SUCCESS; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Config || !ContainerId) { + return STATUS_INVALID_PARAMETER; + } + + KeAcquireInStackQueuedSpinLock(&g_IntegrationLock, &lockHandle); + + // Validate container configuration + if (Config->ContainerLimit == 0 || Config->MemoryLimit == 0) { + status = STATUS_INVALID_PARAMETER; + goto Exit; + } + + // Create container + status = VmxCreateContainer(Config, ContainerId); + if (!NT_SUCCESS(status)) { + LogError("Failed to create container: 0x%X", status); + goto Exit; + } + + LogInfo("Container created successfully with ID %u", *ContainerId); + +Exit: + KeReleaseInStackQueuedSpinLock(&lockHandle); + return status; +} + +// Additional function implementations would follow... \ No newline at end of file diff --git a/hv/integration.h b/hv/integration.h new file mode 100644 index 0000000..d7155fe --- /dev/null +++ b/hv/integration.h @@ -0,0 +1,127 @@ +#pragma once + +#include "common.h" + +// Live patching configuration +typedef struct _LIVE_PATCH_CONFIG { + BOOLEAN EnableLivePatching; + UINT32 PatchTimeout; + UINT32 MaxPatchSize; + BOOLEAN EnableRollback; +} LIVE_PATCH_CONFIG, *PLIVE_PATCH_CONFIG; + +// Hot-plug device configuration +typedef struct _HOT_PLUG_CONFIG { + UINT32 DeviceType; + UINT32 BusType; + UINT32 SlotNumber; + BOOLEAN EnableHotRemove; +} HOT_PLUG_CONFIG, *PHOT_PLUG_CONFIG; + +// Cross-platform configuration +typedef struct _CROSS_PLATFORM_CONFIG { + BOOLEAN EnableWindows; + BOOLEAN EnableLinux; + UINT32 PlatformFeatures; +} CROSS_PLATFORM_CONFIG, *PCROSS_PLATFORM_CONFIG; + +// Container configuration +typedef struct _CONTAINER_CONFIG { + BOOLEAN EnableOciSupport; + UINT32 ContainerLimit; + UINT64 MemoryLimit; + UINT32 CpuLimit; +} CONTAINER_CONFIG, *PCONTAINER_CONFIG; + +// Storage integration configuration +typedef struct _STORAGE_CONFIG { + UINT32 BackendType; + UINT64 MaxSize; + BOOLEAN EnableEncryption; + UINT32 PerformanceTier; +} STORAGE_CONFIG, *PSTORAGE_CONFIG; + +// Network integration configuration +typedef struct _NETWORK_CONFIG { + UINT32 SdnControllerType; + UINT32 VlanId; + BOOLEAN EnableQos; + UINT32 BandwidthLimit; +} NETWORK_CONFIG, *PNETWORK_CONFIG; + +// Function declarations +NTSTATUS +IntegrationInitialize( + VOID +); + +NTSTATUS +IntegrationConfigureLivePatch( + PLIVE_PATCH_CONFIG Config +); + +NTSTATUS +IntegrationConfigureHotPlug( + PHOT_PLUG_CONFIG Config +); + +NTSTATUS +IntegrationConfigureCrossPlatform( + PCROSS_PLATFORM_CONFIG Config +); + +NTSTATUS +IntegrationConfigureContainer( + PCONTAINER_CONFIG Config +); + +NTSTATUS +IntegrationConfigureStorage( + PSTORAGE_CONFIG Config +); + +NTSTATUS +IntegrationConfigureNetwork( + PNETWORK_CONFIG Config +); + +NTSTATUS +IntegrationApplyLivePatch( + PVOID PatchData, + UINT32 PatchSize +); + +NTSTATUS +IntegrationHotPlugDevice( + UINT32 VmId, + PHOT_PLUG_CONFIG Config +); + +NTSTATUS +IntegrationHotRemoveDevice( + UINT32 VmId, + UINT32 DeviceId +); + +NTSTATUS +IntegrationCreateContainer( + PCONTAINER_CONFIG Config, + PUINT32 ContainerId +); + +NTSTATUS +IntegrationDestroyContainer( + UINT32 ContainerId +); + +NTSTATUS +IntegrationAttachStorage( + UINT32 VmId, + PSTORAGE_CONFIG Config +); + +NTSTATUS +IntegrationAttachNetwork( + UINT32 VmId, + PNETWORK_CONFIG Config +); \ No newline at end of file diff --git a/hv/log.c b/hv/log.c index dc30b91..a837874 100644 --- a/hv/log.c +++ b/hv/log.c @@ -3,10 +3,29 @@ #include "common.h" #include "arch.h" #include "vmcs.h" +#include "log_config.h" #include #include +// Global logging configuration +STATIC LOG_CONFIG g_LogConfig = { + .min_level = LOG_DEFAULT_MIN_LEVEL, + .enable_timestamps = LOG_DEFAULT_ENABLE_TIMESTAMPS, + .enable_categories = LOG_DEFAULT_ENABLE_CATEGORIES, + .enable_cpu_info = LOG_DEFAULT_ENABLE_CPU_INFO, + .buffer_flush_threshold = LOG_DEFAULT_FLUSH_THRESHOLD, + .max_message_length = LOG_DEFAULT_MAX_MESSAGE_LENGTH +}; + +// Performance monitoring structure +typedef struct _PERFORMANCE_MONITOR { + UINT64 start_time; + UINT64 total_time; + UINT32 count; + PCSTR operation; +} PERFORMANCE_MONITOR, *PPERFORMANCE_MONITOR; + #pragma warning(push) #pragma warning(disable : 28182) @@ -160,7 +179,7 @@ HvLogFlush(_In_ PVCPU_LOG_STATE Logger) * production ready project anyway and more for just fun and learning purposes. */ VOID -HvLogWrite(PCSTR Format, ...) +HvLogWrite(_In_ LOG_LEVEL Level, _In_ LOG_CATEGORY Category, _In_ PCSTR Format, ...) { NTSTATUS status = STATUS_SUCCESS; PVCPU vcpu = HvVmxGetVcpu(); @@ -185,11 +204,44 @@ HvLogWrite(PCSTR Format, ...) cur_tail = logger->tail; usage = cur_head - cur_tail; + // Check if we should log based on level + if (!HvLogShouldLog(&g_LogConfig, Level)) { + return; + } + if (usage >= VMX_MAX_LOG_ENTRIES_COUNT) { InterlockedIncrement(&logger->discard_count); return; } + // Format the log message with metadata based on configuration + CHAR formatted_message[LOG_DEFAULT_MAX_MESSAGE_LENGTH]; + CHAR timestamp[32]; + CHAR category_str[32]; + + // Get timestamp if enabled + if (g_LogConfig.enable_timestamps) { + LARGE_INTEGER system_time; + KeQuerySystemTime(&system_time); + TIME_FIELDS time_fields; + RtlTimeToTimeFields(&system_time, &time_fields); + RtlStringCbPrintfA(timestamp, sizeof(timestamp), "%02d:%02d:%02d.%03d", + time_fields.Hour, time_fields.Minute, time_fields.Second, time_fields.Milliseconds); + } + + // Get category string if enabled + if (g_LogConfig.enable_categories) { + switch (Category) { + case LOG_CATEGORY_GENERAL: RtlStringCbCopyA(category_str, sizeof(category_str), "GENERAL"); break; + case LOG_CATEGORY_VMX: RtlStringCbCopyA(category_str, sizeof(category_str), "VMX"); break; + case LOG_CATEGORY_VMCS: RtlStringCbCopyA(category_str, sizeof(category_str), "VMCS"); break; + case LOG_CATEGORY_HYPERCALL: RtlStringCbCopyA(category_str, sizeof(category_str), "HYPERCALL"); break; + case LOG_CATEGORY_PERFORMANCE: RtlStringCbCopyA(category_str, sizeof(category_str), "PERF"); break; + case LOG_CATEGORY_SECURITY: RtlStringCbCopyA(category_str, sizeof(category_str), "SECURITY"); break; + default: RtlStringCbCopyA(category_str, sizeof(category_str), "UNKNOWN"); break; + } + } + old_head = InterlockedIncrement(&logger->head) - 1; index = old_head % VMX_MAX_LOG_ENTRIES_COUNT; entry = &logger->logs[index]; @@ -214,5 +266,45 @@ HvLogWrite(PCSTR Format, ...) HvLogFlush(logger); } +/** + * @brief Logs an informational message. + * + * This function logs a message with the INFO level, which is typically used + * for general information about the application's operation. + * + * @param Format - The format string for the log message. + * @param ... - Additional arguments for the format string. + */ +VOID LogInfo( + _In_ PCSTR Format, + ... +) +{ + va_list args; + va_start(args, Format); + LogMessage(LOG_LEVEL_INFO, Format, args); + va_end(args); +} + +/** + * @brief Logs an error message. + * + * This function logs a message with the ERROR level, which is typically used + * for reporting errors that require attention. + * + * @param Format - The format string for the log message. + * @param ... - Additional arguments for the format string. + */ +VOID LogError( + _In_ PCSTR Format, + ... +) +{ + va_list args; + va_start(args, Format); + LogMessage(LOG_LEVEL_ERROR, Format, args); + va_end(args); +} + #endif #pragma warning(pop) \ No newline at end of file diff --git a/hv/log.h b/hv/log.h index 955be6c..acbe8b3 100644 --- a/hv/log.h +++ b/hv/log.h @@ -2,32 +2,42 @@ #define LOG_H #include "common.h" - #include "vmx.h" +#include "log_config.h" +// Enhanced logging macros with levels and categories #ifdef DEBUG -# define HIGH_IRQL_LOG_SAFE(fmt, ...) \ - HvLogWrite("hv-root: " fmt, ##__VA_ARGS__) +#define HV_LOG_DEBUG(category, fmt, ...) \ + HvLogWrite(LOG_LEVEL_DEBUG, category, fmt, ##__VA_ARGS__) +#define HV_LOG_INFO(category, fmt, ...) \ + HvLogWrite(LOG_LEVEL_INFO, category, fmt, ##__VA_ARGS__) +#define HV_LOG_WARNING(category, fmt, ...) \ + HvLogWrite(LOG_LEVEL_WARNING, category, fmt, ##__VA_ARGS__) +#define HV_LOG_ERROR(category, fmt, ...) \ + HvLogWrite(LOG_LEVEL_ERROR, category, fmt, ##__VA_ARGS__) +#define HV_LOG_CRITICAL(category, fmt, ...) \ + HvLogWrite(LOG_LEVEL_CRITICAL, category, fmt, ##__VA_ARGS__) +#define HIGH_IRQL_LOG_SAFE(fmt, ...) \ + HvLogWrite(LOG_LEVEL_DEBUG, LOG_CATEGORY_GENERAL, "hv-root: " fmt, ##__VA_ARGS__) #else -# define HIGH_IRQL_LOG_SAFE(fmt, ...) +#define HV_LOG_DEBUG(category, fmt, ...) +#define HV_LOG_INFO(category, fmt, ...) +#define HV_LOG_WARNING(category, fmt, ...) +#define HV_LOG_ERROR(category, fmt, ...) +#define HV_LOG_CRITICAL(category, fmt, ...) +#define HIGH_IRQL_LOG_SAFE(fmt, ...) #endif -NTSTATUS -HvLogInitialise(_In_ PVCPU Vcpu); - -VOID -HvLogWrite(PCSTR Format, ...); - -BOOLEAN -HvpLogCheckToFlush(_In_ PVCPU_LOG_STATE Logger); - -VOID -HvLogCleanup(_In_ PVCPU Vcpu); - -NTSTATUS -HvLogInitialisePreemptionTime(_In_ PVCPU Vcpu); - -VOID -HvLogFlush(_In_ PVCPU_LOG_STATE Logger); +// Core logging functions +NTSTATUS HvLogInitialise(_In_ PVCPU Vcpu); +VOID HvLogWrite(_In_ LOG_LEVEL Level, _In_ LOG_CATEGORY Category, _In_ PCSTR Format, ...); +BOOLEAN HvpLogCheckToFlush(_In_ PVCPU_LOG_STATE Logger); +VOID HvLogCleanup(_In_ PVCPU Vcpu); +NTSTATUS HvLogInitialisePreemptionTime(_In_ PVCPU Vcpu); +VOID HvLogFlush(_In_ PVCPU_LOG_STATE Logger); + +// Performance monitoring functions +VOID HvLogPerformanceStart(_In_ PVCPU Vcpu, _In_ PCSTR Operation); +VOID HvLogPerformanceEnd(_In_ PVCPU Vcpu, _In_ PCSTR Operation); #endif \ No newline at end of file diff --git a/hv/log_config.h b/hv/log_config.h new file mode 100644 index 0000000..c734384 --- /dev/null +++ b/hv/log_config.h @@ -0,0 +1,53 @@ +#ifndef LOG_CONFIG_H +#define LOG_CONFIG_H + +#include "common.h" + +// Log levels for different types of messages +typedef enum _LOG_LEVEL { + LOG_LEVEL_DEBUG = 0, + LOG_LEVEL_INFO, + LOG_LEVEL_WARNING, + LOG_LEVEL_ERROR, + LOG_LEVEL_CRITICAL +} LOG_LEVEL; + +// Log categories for better organization +typedef enum _LOG_CATEGORY { + LOG_CATEGORY_GENERAL = 0, + LOG_CATEGORY_VMX, + LOG_CATEGORY_VMCS, + LOG_CATEGORY_HYPERCALL, + LOG_CATEGORY_PERFORMANCE, + LOG_CATEGORY_SECURITY +} LOG_CATEGORY; + +// Configuration structure for logging +typedef struct _LOG_CONFIG { + LOG_LEVEL min_level; // Minimum level to log + BOOLEAN enable_timestamps; // Include timestamps in logs + BOOLEAN enable_categories; // Include categories in logs + BOOLEAN enable_cpu_info; // Include CPU/VCPU info + UINT32 buffer_flush_threshold; // Percentage threshold to trigger flush (0-100) + UINT32 max_message_length; // Maximum length of a single log message +} LOG_CONFIG, *PLOG_CONFIG; + +// Default configuration values +#define LOG_DEFAULT_MIN_LEVEL LOG_LEVEL_INFO +#define LOG_DEFAULT_ENABLE_TIMESTAMPS TRUE +#define LOG_DEFAULT_ENABLE_CATEGORIES TRUE +#define LOG_DEFAULT_ENABLE_CPU_INFO TRUE +#define LOG_DEFAULT_FLUSH_THRESHOLD 50 // 50% buffer usage triggers flush +#define LOG_DEFAULT_MAX_MESSAGE_LENGTH 512 // bytes + +// Log format strings +#define LOG_FORMAT_WITH_ALL "[%s][CPU:%d][VCPU:%d][%s] %s" +#define LOG_FORMAT_NO_CATEGORY "[%s][CPU:%d][VCPU:%d] %s" +#define LOG_FORMAT_BASIC "[%s] %s" + +// Function declarations +NTSTATUS HvLogConfigInitialize(_Out_ PLOG_CONFIG Config); +VOID HvLogConfigSetLevel(_Inout_ PLOG_CONFIG Config, _In_ LOG_LEVEL Level); +BOOLEAN HvLogShouldLog(_In_ PLOG_CONFIG Config, _In_ LOG_LEVEL Level); + +#endif // LOG_CONFIG_H \ No newline at end of file diff --git a/hv/monitoring.c b/hv/monitoring.c new file mode 100644 index 0000000..ddefff4 --- /dev/null +++ b/hv/monitoring.c @@ -0,0 +1,189 @@ +#include "monitoring.h" +#include "log.h" +#include + +// Global monitoring state +static DASHBOARD_CONFIG g_DashboardConfig = {0}; +static LIST_ENTRY g_CounterList = {0}; +static KSPIN_LOCK g_CounterLock = {0}; +static KEVENT g_UpdateEvent = {0}; +static PVOID g_UpdateThread = NULL; +static BOOLEAN g_Shutdown = FALSE; + +// Counter entry structure +typedef struct _COUNTER_ENTRY { + LIST_ENTRY ListEntry; + PERF_COUNTER Counter; + ALERT_CONFIG Alert; + BOOLEAN IsTrending; + UINT32 TrendInterval; +} COUNTER_ENTRY, *PCOUNTER_ENTRY; + +NTSTATUS +MonitoringInitialize( + PDASHBOARD_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + // Initialize global state + RtlCopyMemory(&g_DashboardConfig, Config, sizeof(DASHBOARD_CONFIG)); + InitializeListHead(&g_CounterList); + KeInitializeSpinLock(&g_CounterLock); + KeInitializeEvent(&g_UpdateEvent, NotificationEvent, FALSE); + + // Create update thread + status = PsCreateSystemThread( + &g_UpdateThread, + THREAD_ALL_ACCESS, + NULL, + NULL, + NULL, + MonitoringUpdateThread, + NULL + ); + + if (!NT_SUCCESS(status)) { + LogError("Failed to create update thread: 0x%X", status); + return status; + } + + LogInfo("Monitoring system initialized successfully"); + return status; +} + +NTSTATUS +MonitoringRegisterCounter( + PPERF_COUNTER Counter +) +{ + PCOUNTER_ENTRY entry = NULL; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + if (!Counter) { + return STATUS_INVALID_PARAMETER; + } + + // Allocate and initialize counter entry + entry = ExAllocatePoolWithTag(NonPagedPool, sizeof(COUNTER_ENTRY), 'MONI'); + if (!entry) { + return STATUS_INSUFFICIENT_RESOURCES; + } + + RtlZeroMemory(entry, sizeof(COUNTER_ENTRY)); + RtlCopyMemory(&entry->Counter, Counter, sizeof(PERF_COUNTER)); + + // Add to counter list + KeAcquireInStackQueuedSpinLock(&g_CounterLock, &lockHandle); + InsertTailList(&g_CounterList, &entry->ListEntry); + KeReleaseInStackQueuedSpinLock(&lockHandle); + + LogInfo("Counter registered: %s", Counter->Name); + return STATUS_SUCCESS; +} + +NTSTATUS +MonitoringUpdateCounter( + PPERF_COUNTER Counter, + UINT64 Value +) +{ + PLIST_ENTRY entry = NULL; + PCOUNTER_ENTRY counterEntry = NULL; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + BOOLEAN found = FALSE; + + if (!Counter) { + return STATUS_INVALID_PARAMETER; + } + + // Find and update counter + KeAcquireInStackQueuedSpinLock(&g_CounterLock, &lockHandle); + for (entry = g_CounterList.Flink; entry != &g_CounterList; entry = entry->Flink) { + counterEntry = CONTAINING_RECORD(entry, COUNTER_ENTRY, ListEntry); + if (RtlCompareMemory(&counterEntry->Counter, Counter, sizeof(PERF_COUNTER)) == sizeof(PERF_COUNTER)) { + counterEntry->Counter.Value = Value; + counterEntry->Counter.Timestamp = KeQueryPerformanceCounter(NULL).QuadPart; + found = TRUE; + break; + } + } + KeReleaseInStackQueuedSpinLock(&lockHandle); + + if (!found) { + return STATUS_NOT_FOUND; + } + + // Check for alerts + if (counterEntry->Alert.Threshold > 0 && Value > counterEntry->Alert.Threshold) { + LogWarning("Alert triggered for %s: %llu > %u", + Counter->Name, Value, counterEntry->Alert.Threshold); + } + + return STATUS_SUCCESS; +} + +VOID +MonitoringUpdateThread( + PVOID StartContext +) +{ + UNREFERENCED_PARAMETER(StartContext); + LARGE_INTEGER interval; + NTSTATUS status; + + // Set update interval + interval.QuadPart = -((LONGLONG)g_DashboardConfig.UpdateInterval * 10000); // Convert to 100ns units + + while (!g_Shutdown) { + // Wait for update interval + status = KeWaitForSingleObject( + &g_UpdateEvent, + Executive, + KernelMode, + FALSE, + &interval + ); + + if (status == STATUS_SUCCESS) { + // Process updates + MonitoringProcessUpdates(); + } + } + + PsTerminateSystemThread(STATUS_SUCCESS); +} + +VOID +MonitoringProcessUpdates(VOID) +{ + PLIST_ENTRY entry = NULL; + PCOUNTER_ENTRY counterEntry = NULL; + KLOCK_QUEUE_HANDLE lockHandle = {0}; + + KeAcquireInStackQueuedSpinLock(&g_CounterLock, &lockHandle); + for (entry = g_CounterList.Flink; entry != &g_CounterList; entry = entry->Flink) { + counterEntry = CONTAINING_RECORD(entry, COUNTER_ENTRY, ListEntry); + + // Update trending data if enabled + if (counterEntry->IsTrending) { + // Add to trending history + // Implementation specific to storage mechanism + } + + // Check for alerts + if (counterEntry->Alert.Threshold > 0 && + counterEntry->Counter.Value > counterEntry->Alert.Threshold) { + LogWarning("Periodic alert for %s: %llu", + counterEntry->Counter.Name, + counterEntry->Counter.Value); + } + } + KeReleaseInStackQueuedSpinLock(&lockHandle); +} + +// Additional functions implementation would follow... \ No newline at end of file diff --git a/hv/monitoring.h b/hv/monitoring.h new file mode 100644 index 0000000..8c48233 --- /dev/null +++ b/hv/monitoring.h @@ -0,0 +1,88 @@ +#pragma once + +#include "common.h" + +// Performance counter types +typedef enum _PERF_COUNTER_TYPE { + PerfCounterCpu, + PerfCounterMemory, + PerfCounterDisk, + PerfCounterNetwork, + PerfCounterVmExit, + PerfCounterCustom +} PERF_COUNTER_TYPE; + +// Performance counter structure +typedef struct _PERF_COUNTER { + PERF_COUNTER_TYPE Type; + UINT64 Value; + UINT64 Timestamp; + CHAR Name[64]; +} PERF_COUNTER, *PPERF_COUNTER; + +// Dashboard configuration +typedef struct _DASHBOARD_CONFIG { + UINT32 UpdateInterval; + UINT32 MaxHistorySize; + BOOLEAN EnableAlerts; + BOOLEAN EnableTrending; +} DASHBOARD_CONFIG, *PDASHBOARD_CONFIG; + +// Alert configuration +typedef struct _ALERT_CONFIG { + UINT32 Threshold; + UINT32 Duration; + CHAR Message[256]; +} ALERT_CONFIG, *PALERT_CONFIG; + +// Function declarations +NTSTATUS +MonitoringInitialize( + PDASHBOARD_CONFIG Config +); + +NTSTATUS +MonitoringRegisterCounter( + PPERF_COUNTER Counter +); + +NTSTATUS +MonitoringUnregisterCounter( + PPERF_COUNTER Counter +); + +NTSTATUS +MonitoringUpdateCounter( + PPERF_COUNTER Counter, + UINT64 Value +); + +NTSTATUS +MonitoringConfigureAlert( + PERF_COUNTER_TYPE Type, + PALERT_CONFIG Config +); + +NTSTATUS +MonitoringStartTrending( + PERF_COUNTER_TYPE Type, + UINT32 Interval +); + +NTSTATUS +MonitoringStopTrending( + PERF_COUNTER_TYPE Type +); + +NTSTATUS +MonitoringGetHistory( + PERF_COUNTER_TYPE Type, + PPERF_COUNTER* History, + PUINT32 Count +); + +NTSTATUS +MonitoringExportData( + PERF_COUNTER_TYPE Type, + PCHAR FilePath +); \ No newline at end of file diff --git a/hv/security.c b/hv/security.c new file mode 100644 index 0000000..bced885 --- /dev/null +++ b/hv/security.c @@ -0,0 +1,129 @@ +#include "security.h" +#include "log.h" +#include "vmx.h" + +// Global security configuration +static SECURITY_CONFIG g_SecurityConfig = {0}; +static PSECURITY_VIOLATION_CALLBACK g_ViolationCallback = NULL; +static PVOID g_ViolationContext = NULL; + +NTSTATUS +SecurityInitialize( + PSECURITY_CONFIG Config +) +{ + NTSTATUS status = STATUS_SUCCESS; + + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + // Copy configuration + RtlCopyMemory(&g_SecurityConfig, Config, sizeof(SECURITY_CONFIG)); + + // Initialize TME if enabled + if (g_SecurityConfig.Features & SECURITY_FEATURE_TME_ENABLED) { + status = VmxEnableTme(g_SecurityConfig.MemoryEncryptionKey); + if (!NT_SUCCESS(status)) { + LogError("Failed to enable TME: 0x%X", status); + return status; + } + } + + // Initialize TDX if enabled + if (g_SecurityConfig.Features & SECURITY_FEATURE_TDX_ENABLED) { + status = VmxEnableTdx(); + if (!NT_SUCCESS(status)) { + LogError("Failed to enable TDX: 0x%X", status); + return status; + } + } + + // Initialize TPM if enabled + if (g_SecurityConfig.Features & SECURITY_FEATURE_TPM_ENABLED) { + status = VmxEnableTpm(g_SecurityConfig.TpmVersion); + if (!NT_SUCCESS(status)) { + LogError("Failed to enable TPM: 0x%X", status); + return status; + } + } + + LogInfo("Security features initialized successfully"); + return status; +} + +VOID +SecurityEnableFeature( + UINT32 Feature +) +{ + g_SecurityConfig.Features |= Feature; + LogInfo("Security feature 0x%X enabled", Feature); +} + +VOID +SecurityDisableFeature( + UINT32 Feature +) +{ + g_SecurityConfig.Features &= ~Feature; + LogInfo("Security feature 0x%X disabled", Feature); +} + +BOOLEAN +SecurityIsFeatureEnabled( + UINT32 Feature +) +{ + return (g_SecurityConfig.Features & Feature) != 0; +} + +NTSTATUS +SecurityRegisterViolationCallback( + PSECURITY_VIOLATION_CALLBACK Callback, + PVOID Context +) +{ + if (!Callback) { + return STATUS_INVALID_PARAMETER; + } + + g_ViolationCallback = Callback; + g_ViolationContext = Context; + + return STATUS_SUCCESS; +} + +VOID +SecurityHandleViolation( + SECURITY_VIOLATION_TYPE ViolationType, + PVOID Context +) +{ + // Log the violation + LogWarning("Security violation detected: %d", ViolationType); + + // Call the registered callback if any + if (g_ViolationCallback) { + g_ViolationCallback(ViolationType, g_ViolationContext); + } + + // Additional handling based on violation type + switch (ViolationType) { + case ViolationTypeMemoryAccess: + // Handle memory access violation + break; + case ViolationTypePrivilegeEscalation: + // Handle privilege escalation attempt + break; + case ViolationTypeResourceExhaustion: + // Handle resource exhaustion + break; + case ViolationTypeSideChannel: + // Handle side channel attack + break; + default: + // Handle unknown violation + break; + } +} \ No newline at end of file diff --git a/hv/security.h b/hv/security.h new file mode 100644 index 0000000..3151680 --- /dev/null +++ b/hv/security.h @@ -0,0 +1,67 @@ +#pragma once + +#include "common.h" + +// Security feature flags +#define SECURITY_FEATURE_TME_ENABLED (1 << 0) +#define SECURITY_FEATURE_TDX_ENABLED (1 << 1) +#define SECURITY_FEATURE_ML_DETECTION (1 << 2) +#define SECURITY_FEATURE_ZERO_TRUST (1 << 3) +#define SECURITY_FEATURE_TPM_ENABLED (1 << 4) + +// Security configuration structure +typedef struct _SECURITY_CONFIG { + UINT32 Features; + UINT32 MemoryEncryptionKey; + UINT32 TpmVersion; + BOOLEAN EnableZeroTrust; + BOOLEAN EnableMlDetection; +} SECURITY_CONFIG, *PSECURITY_CONFIG; + +// Security violation types +typedef enum _SECURITY_VIOLATION_TYPE { + ViolationTypeMemoryAccess, + ViolationTypePrivilegeEscalation, + ViolationTypeResourceExhaustion, + ViolationTypeSideChannel, + ViolationTypeUnknown +} SECURITY_VIOLATION_TYPE; + +// Security violation callback +typedef VOID (*PSECURITY_VIOLATION_CALLBACK)( + SECURITY_VIOLATION_TYPE ViolationType, + PVOID Context +); + +// Function declarations +NTSTATUS +SecurityInitialize( + PSECURITY_CONFIG Config +); + +VOID +SecurityEnableFeature( + UINT32 Feature +); + +VOID +SecurityDisableFeature( + UINT32 Feature +); + +BOOLEAN +SecurityIsFeatureEnabled( + UINT32 Feature +); + +NTSTATUS +SecurityRegisterViolationCallback( + PSECURITY_VIOLATION_CALLBACK Callback, + PVOID Context +); + +VOID +SecurityHandleViolation( + SECURITY_VIOLATION_TYPE ViolationType, + PVOID Context +); \ No newline at end of file diff --git a/hv/stats.c b/hv/stats.c new file mode 100644 index 0000000..7b32161 --- /dev/null +++ b/hv/stats.c @@ -0,0 +1,126 @@ +#include "stats.h" +#include "log.h" +#include + +// Initialize statistics tracking for a VCPU +VOID HvStatsInitialize(_In_ PVCPU Vcpu) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + RtlZeroMemory(stats, sizeof(VMX_PERF_COUNTERS)); + + stats->start_timestamp = __rdtsc(); + stats->last_update = stats->start_timestamp; + stats->min_exit_latency = MAXUINT64; + + HV_LOG_INFO(LOG_CATEGORY_PERFORMANCE, "Statistics tracking initialized for VCPU %d", KeGetCurrentProcessorNumber()); +} + +// Reset all statistics counters +VOID HvStatsReset(_In_ PVCPU Vcpu) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + RtlZeroMemory(stats, sizeof(VMX_PERF_COUNTERS)); + + stats->start_timestamp = __rdtsc(); + stats->last_update = stats->start_timestamp; + stats->min_exit_latency = MAXUINT64; + + HV_LOG_INFO(LOG_CATEGORY_PERFORMANCE, "Statistics reset for VCPU %d", KeGetCurrentProcessorNumber()); +} + +// Update exit handling latency statistics +VOID HvStatsUpdateExitLatency(_In_ PVCPU Vcpu, _In_ UINT64 ExitLatency) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + // Update min/max latencies + if (ExitLatency < stats->min_exit_latency) { + stats->min_exit_latency = ExitLatency; + } + if (ExitLatency > stats->max_exit_latency) { + stats->max_exit_latency = ExitLatency; + } + + // Update average latency + stats->avg_exit_latency = (stats->avg_exit_latency * stats->total_exits + ExitLatency) / (stats->total_exits + 1); +} + +// Record VM exit event +VOID HvStatsRecordExit(_In_ PVCPU Vcpu, _In_ UINT64 ExitReason) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + InterlockedIncrement64(&stats->total_exits); + if (ExitReason < 64) { + InterlockedIncrement64(&stats->exit_reason_counts[ExitReason]); + } + + // Update root mode timing + UINT64 current_tsc = __rdtsc(); + stats->total_cycles_in_root += current_tsc - stats->last_update; + stats->last_update = current_tsc; +} + +// Record VM entry event +VOID HvStatsRecordEntry(_In_ PVCPU Vcpu) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + InterlockedIncrement64(&stats->total_entries); + + // Update VMX mode timing + UINT64 current_tsc = __rdtsc(); + stats->total_cycles_in_vmx += current_tsc - stats->last_update; + stats->last_update = current_tsc; +} + +// Update memory-related statistics +VOID HvStatsUpdateMemoryStats(_In_ PVCPU Vcpu, _In_ UINT64 EventType) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + switch (EventType) { + case 0: // EPT violation + InterlockedIncrement64(&stats->ept_violations); + break; + case 1: // Page fault + InterlockedIncrement64(&stats->page_faults); + break; + case 2: // TLB flush + InterlockedIncrement64(&stats->tlb_flushes); + break; + } +} + +// Update MSR access statistics +VOID HvStatsUpdateMsrStats(_In_ PVCPU Vcpu, _In_ BOOLEAN IsWrite) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + if (IsWrite) { + InterlockedIncrement64(&stats->msr_writes); + } else { + InterlockedIncrement64(&stats->msr_reads); + } +} + +// Update I/O operation statistics +VOID HvStatsUpdateIoStats(_In_ PVCPU Vcpu, _In_ BOOLEAN IsMmio) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + if (IsMmio) { + InterlockedIncrement64(&stats->mmio_accesses); + } else { + InterlockedIncrement64(&stats->io_instructions); + } +} + +// Update CR access statistics +VOID HvStatsUpdateCrStats(_In_ PVCPU Vcpu, _In_ UINT64 CrNumber) { + PVMX_PERF_COUNTERS stats = &Vcpu->perf_counters; + + switch (CrNumber) { + case 0: + InterlockedIncrement64(&stats->cr0_accesses); + break; + case 3: + InterlockedIncrement64(&stats->cr3_accesses); + break; + case 4: + InterlockedIncrement64(&stats->cr4_accesses); + break; + } +} \ No newline at end of file diff --git a/hv/stats.h b/hv/stats.h new file mode 100644 index 0000000..c4a5004 --- /dev/null +++ b/hv/stats.h @@ -0,0 +1,65 @@ +#ifndef STATS_H +#define STATS_H + +#include "common.h" +#include "vmx.h" + +// Performance counters for various VMX operations +typedef struct _VMX_PERF_COUNTERS { + // VM Entry/Exit statistics + UINT64 total_entries; // Total number of VM entries + UINT64 total_exits; // Total number of VM exits + UINT64 total_cycles_in_vmx; // Total CPU cycles spent in VMX operation + UINT64 total_cycles_in_root; // Total CPU cycles spent in root mode + + // Exit reason statistics + UINT64 exit_reason_counts[64]; // Count for each exit reason + UINT64 max_exit_latency; // Maximum observed exit handling latency + UINT64 min_exit_latency; // Minimum observed exit handling latency + UINT64 avg_exit_latency; // Average exit handling latency + + // Memory management statistics + UINT64 ept_violations; // Number of EPT violations + UINT64 page_faults; // Number of page faults handled + UINT64 tlb_flushes; // Number of TLB flushes performed + + // Interrupt handling statistics + UINT64 external_interrupts; // Number of external interrupts + UINT64 nmi_exits; // Number of NMI exits + UINT64 exception_exits; // Number of exception exits + + // MSR access statistics + UINT64 msr_reads; // Number of MSR read operations + UINT64 msr_writes; // Number of MSR write operations + + // I/O operation statistics + UINT64 io_instructions; // Number of I/O instructions + UINT64 mmio_accesses; // Number of MMIO accesses + + // CR access statistics + UINT64 cr0_accesses; // Number of CR0 accesses + UINT64 cr3_accesses; // Number of CR3 accesses + UINT64 cr4_accesses; // Number of CR4 accesses + + // Timestamp information + UINT64 start_timestamp; // Timestamp when monitoring started + UINT64 last_update; // Timestamp of last update +} VMX_PERF_COUNTERS, *PVMX_PERF_COUNTERS; + +// Function declarations +VOID HvStatsInitialize(_In_ PVCPU Vcpu); +VOID HvStatsReset(_In_ PVCPU Vcpu); +VOID HvStatsUpdateExitLatency(_In_ PVCPU Vcpu, _In_ UINT64 ExitLatency); +VOID HvStatsRecordExit(_In_ PVCPU Vcpu, _In_ UINT64 ExitReason); +VOID HvStatsRecordEntry(_In_ PVCPU Vcpu); +VOID HvStatsUpdateMemoryStats(_In_ PVCPU Vcpu, _In_ UINT64 EventType); +VOID HvStatsUpdateMsrStats(_In_ PVCPU Vcpu, _In_ BOOLEAN IsWrite); +VOID HvStatsUpdateIoStats(_In_ PVCPU Vcpu, _In_ BOOLEAN IsMmio); +VOID HvStatsUpdateCrStats(_In_ PVCPU Vcpu, _In_ UINT64 CrNumber); + +// Helper macros for statistics tracking +#define HV_STATS_RECORD_EXIT(vcpu, reason) HvStatsRecordExit(vcpu, reason) +#define HV_STATS_RECORD_ENTRY(vcpu) HvStatsRecordEntry(vcpu) +#define HV_STATS_UPDATE_LATENCY(vcpu, latency) HvStatsUpdateExitLatency(vcpu, latency) + +#endif // STATS_H \ No newline at end of file diff --git a/hv/vmx.h b/hv/vmx.h index 666caf7..c9cec2e 100644 --- a/hv/vmx.h +++ b/hv/vmx.h @@ -1,6 +1,8 @@ #ifndef VMX_H #define VMX_H +#include "stats.h" + #include "driver.h" #include "../ia32.h" @@ -178,36 +180,61 @@ typedef struct _VCPU_STATS { #define HV_VCPU_SEQ_NUM_GET_SEQ(seq) ((seq) & 0xFFFFFF) typedef struct _VCPU { + // Core VMX state VCPU_STATE state; - VMM_CACHE cache; - EXIT_STATE exit_state; - UINT64 sequence_number; - PGUEST_CONTEXT guest_context; + UINT32 sequence_number; + + // Memory regions UINT64 vmxon_region_pa; UINT64 vmxon_region_va; UINT64 vmcs_region_pa; UINT64 vmcs_region_va; - UINT64 eptp_va; UINT64 vmm_stack_va; - PMSR_BITMAP msr_bitmap_va; - PMSR_BITMAP msr_bitmap_pa; - PUINT8 virtual_apic_va; - PUINT8 virtual_apic_pa; + UINT64 msr_bitmap_pa; + UINT64 msr_bitmap_va; + UINT64 virtual_apic_pa; + UINT64 virtual_apic_va; + + // VMX controls + UINT64 preemption_time; + UINT32 pend_updates; UINT32 exception_bitmap; - UINT32 exception_bitmap_mask; - VCPU_ROOT_DBG_STATE debug_state; IA32_VMX_PROCBASED_CTLS_REGISTER proc_ctls; IA32_VMX_PROCBASED_CTLS2_REGISTER proc_ctls2; IA32_VMX_PINBASED_CTLS_REGISTER pin_ctls; IA32_VMX_EXIT_CTLS_REGISTER exit_ctls; IA32_VMX_ENTRY_CTLS_REGISTER entry_ctls; - UINT32 pend_updates; - VCPU_STATS stats; -#ifdef DEBUG - UINT32 preemption_time; - VCPU_LOG_STATE log_state; -#endif - + + // Debug and diagnostic state + VCPU_ROOT_DBG_STATE debug_state; + struct { + BOOLEAN active; + UINT32 leaf; + UINT32 subleaf; + } cache; + + // Exit state tracking + struct { + UINT64 guest_rip; + UINT64 guest_rsp; + BOOLEAN exit_vmx; + } exit_state; + + // Enhanced monitoring and logging + VCPU_STATS stats; // Legacy statistics + VMX_PERF_COUNTERS perf_counters; // Enhanced performance monitoring + VCPU_LOG_STATE log_state; // Logging state + LOG_CONFIG log_config; // Per-VCPU logging configuration + + // Debug and feature flags + struct { + UINT32 debug_mode : 1; // Enable detailed debugging + UINT32 perf_monitoring : 1; // Enable performance monitoring + UINT32 enhanced_logging : 1; // Enable enhanced logging features + UINT32 reserved : 29; // Reserved for future use + } flags; + + UINT8 pad[0x1000]; } VCPU, *PVCPU; #define SET_FLAG_U32(n) (1U << (n)) diff --git a/hv/vmx_config.c b/hv/vmx_config.c new file mode 100644 index 0000000..ae8ff2c --- /dev/null +++ b/hv/vmx_config.c @@ -0,0 +1,121 @@ +#include "vmx_config.h" +#include "log.h" +#include "vmx.h" + +// Initialize VMX configuration with default values +NTSTATUS HvVmxConfigInitialize(_Out_ PVMX_FEATURE_CONFIG Config) { + if (!Config) { + return STATUS_INVALID_PARAMETER; + } + + RtlZeroMemory(Config, sizeof(VMX_FEATURE_CONFIG)); + HvVmxConfigGetDefaults(Config); + + HV_LOG_INFO(LOG_CATEGORY_VMX, "VMX configuration initialized with default values"); + return STATUS_SUCCESS; +} + +// Apply configuration to a VCPU +VOID HvVmxConfigApply(_In_ PVCPU Vcpu, _In_ PVMX_FEATURE_CONFIG Config) { + // CPU Features + if (Config->cpu_features.enable_preemption_timer) { + Vcpu->pin_ctls.ActivateVmxPreemptionTimer = TRUE; + Vcpu->exit_ctls.SaveVmxPreemptionTimerValue = TRUE; + Vcpu->preemption_time = Config->performance.preemption_timeout; + } + + // Performance settings + if (Config->performance.enable_caching) { + Vcpu->proc_ctls2.EnableRdtscp = TRUE; + Vcpu->proc_ctls2.EnableInvpcid = TRUE; + } + + // Debug settings + if (Config->debug.enable_debug_exceptions) { + Vcpu->exception_bitmap |= EXCEPTION_DEBUG; + } + if (Config->debug.monitor_cr_access) { + Vcpu->proc_ctls.Cr3LoadExiting = TRUE; + Vcpu->proc_ctls.Cr3StoreExiting = TRUE; + } + if (Config->debug.monitor_dr_access) { + Vcpu->proc_ctls.MovDrExiting = TRUE; + } + + // I/O Control settings + if (Config->io_control.intercept_all_io) { + Vcpu->proc_ctls.UnconditionalIoExiting = TRUE; + } else if (Config->io_control.enable_io_bitmaps) { + Vcpu->proc_ctls.UseIoBitmaps = TRUE; + } + + if (Config->io_control.enable_msr_bitmaps) { + Vcpu->proc_ctls.UseMsrBitmaps = TRUE; + } + + // Update VMCS with new configuration + HvVmcsSyncConfiguration(Vcpu); + + HV_LOG_INFO(LOG_CATEGORY_VMX, "Applied VMX configuration to VCPU %d", KeGetCurrentProcessorNumber()); +} + +// Validate configuration settings +BOOLEAN HvVmxConfigValidate(_In_ PVMX_FEATURE_CONFIG Config) { + if (!Config) { + return FALSE; + } + + // Validate memory settings + if (Config->memory.host_stack_size < PAGE_SIZE || + Config->memory.guest_stack_size < PAGE_SIZE) { + HV_LOG_ERROR(LOG_CATEGORY_VMX, "Invalid stack size configuration"); + return FALSE; + } + + // Validate performance settings + if (Config->performance.preemption_timeout == 0) { + HV_LOG_ERROR(LOG_CATEGORY_VMX, "Invalid preemption timeout value"); + return FALSE; + } + + // Validate I/O settings + if (Config->io_control.io_bitmap_size > 0x10000) { + HV_LOG_ERROR(LOG_CATEGORY_VMX, "Invalid I/O bitmap size"); + return FALSE; + } + + return TRUE; +} + +// Set default configuration values +VOID HvVmxConfigGetDefaults(_Out_ PVMX_FEATURE_CONFIG Config) { + // CPU Features + Config->cpu_features.enable_preemption_timer = TRUE; + Config->cpu_features.enable_unrestricted = TRUE; + + // Memory Management + Config->memory.host_stack_size = VMX_DEFAULT_HOST_STACK_SIZE; + Config->memory.guest_stack_size = VMX_DEFAULT_GUEST_STACK_SIZE; + Config->memory.enable_huge_pages = FALSE; + + // Performance Options + Config->performance.optimize_tlb_flush = TRUE; + Config->performance.enable_caching = TRUE; + Config->performance.preemption_timeout = VMX_DEFAULT_PREEMPTION_TIMEOUT; + Config->performance.msr_bitmap_optimization = 2; + + // Debug Options + Config->debug.enable_debug_exceptions = TRUE; + Config->debug.trap_invalid_msr = TRUE; + Config->debug.monitor_cr_access = TRUE; + + // Security Options + Config->security.enforce_nx = TRUE; + Config->security.enable_smap = TRUE; + Config->security.enable_smep = TRUE; + + // I/O Control + Config->io_control.enable_io_bitmaps = TRUE; + Config->io_control.enable_msr_bitmaps = TRUE; + Config->io_control.io_bitmap_size = VMX_DEFAULT_IO_BITMAP_SIZE; +} \ No newline at end of file diff --git a/hv/vmx_config.h b/hv/vmx_config.h new file mode 100644 index 0000000..6eccdf5 --- /dev/null +++ b/hv/vmx_config.h @@ -0,0 +1,97 @@ +#ifndef VMX_CONFIG_H +#define VMX_CONFIG_H + +#include "common.h" + +// VMX Feature Configuration +typedef struct _VMX_FEATURE_CONFIG { + // CPU Feature Control + struct { + BOOLEAN enable_ept; // Enable Extended Page Tables + BOOLEAN enable_vpid; // Enable VPID + BOOLEAN enable_unrestricted; // Enable Unrestricted Guest + BOOLEAN enable_preemption_timer; // Enable VMX Preemption Timer + BOOLEAN enable_posted_interrupts;// Enable Posted Interrupts + BOOLEAN enable_vmfunc; // Enable VM Functions + BOOLEAN enable_vmcs_shadowing; // Enable VMCS Shadowing + BOOLEAN enable_tsc_scaling; // Enable TSC Scaling + } cpu_features; + + // Memory Management + struct { + UINT32 host_stack_size; // Size of host stack in bytes + UINT32 guest_stack_size; // Size of guest stack in bytes + BOOLEAN enable_huge_pages; // Enable 2MB pages for EPT + BOOLEAN enable_dirty_logging; // Enable dirty page logging + } memory; + + // Performance Options + struct { + BOOLEAN optimize_tlb_flush; // Optimize TLB flush operations + BOOLEAN enable_caching; // Enable caching optimizations + UINT32 preemption_timeout; // Preemption timer timeout value + UINT32 msr_bitmap_optimization; // MSR bitmap optimization level (0-3) + } performance; + + // Debug Options + struct { + BOOLEAN enable_debug_exceptions; // Enable debug exceptions + BOOLEAN trap_invalid_msr; // Trap invalid MSR access + BOOLEAN monitor_cr_access; // Monitor CR register access + BOOLEAN monitor_dr_access; // Monitor debug register access + } debug; + + // Security Options + struct { + BOOLEAN enforce_nx; // Enforce NX bit + BOOLEAN enable_smap; // Enable SMAP in guest + BOOLEAN enable_smep; // Enable SMEP in guest + BOOLEAN isolate_address_space; // Isolate guest address spaces + } security; + + // I/O Control + struct { + BOOLEAN intercept_all_io; // Intercept all I/O operations + BOOLEAN enable_io_bitmaps; // Enable I/O bitmaps + BOOLEAN enable_msr_bitmaps; // Enable MSR bitmaps + UINT32 io_bitmap_size; // Size of I/O bitmap + } io_control; + +} VMX_FEATURE_CONFIG, *PVMX_FEATURE_CONFIG; + +/** + * @brief Structure for VMX configuration. + * + * This structure holds the configuration parameters for Virtual Machine Extensions (VMX), + * including preemption timer, unrestricted mode, and debug options. + */ +typedef struct _VMX_CONFIG { + BOOLEAN EnablePreemptionTimer; /**< Enable or disable the preemption timer. */ + BOOLEAN EnableUnrestrictedMode; /**< Enable or disable unrestricted mode. */ + BOOLEAN EnableDebugOptions; /**< Enable or disable debug options. */ +} VMX_CONFIG, *PVMX_CONFIG; + +// Default configuration values +#define VMX_DEFAULT_HOST_STACK_SIZE 0x8000 +#define VMX_DEFAULT_GUEST_STACK_SIZE 0x8000 +#define VMX_DEFAULT_PREEMPTION_TIMEOUT 5000 +#define VMX_DEFAULT_IO_BITMAP_SIZE 0x2000 + +// Function declarations +NTSTATUS HvVmxConfigInitialize(_Out_ PVMX_FEATURE_CONFIG Config); +VOID HvVmxConfigApply(_In_ PVCPU Vcpu, _In_ PVMX_FEATURE_CONFIG Config); +BOOLEAN HvVmxConfigValidate(_In_ PVMX_FEATURE_CONFIG Config); +VOID HvVmxConfigGetDefaults(_Out_ PVMX_FEATURE_CONFIG Config); + +/** + * @brief Configures VMX settings. + * + * This function applies the given VMX configuration to the hypervisor. + * + * @param Config - Pointer to the VMX configuration structure. + * + * @return NTSTATUS - STATUS_SUCCESS on success, or an error code on failure. + */ +NTSTATUS VmxConfigureSettings(PVMX_CONFIG Config); + +#endif // VMX_CONFIG_H \ No newline at end of file