use serde::{Deserialize, Serialize};
#[cfg(target_arch = "x86_64")]
#[allow(unused_unsafe)]
fn cpuid(leaf: u32) -> core::arch::x86_64::CpuidResult {
unsafe { core::arch::x86_64::__cpuid(leaf) }
}
#[cfg(target_arch = "x86")]
#[allow(unused_unsafe)]
fn cpuid(leaf: u32) -> core::arch::x86::CpuidResult {
unsafe { core::arch::x86::__cpuid(leaf) }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HyperVPartition {
Root,
Guest,
Unknown,
}
pub fn hyperv_partition() -> HyperVPartition {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
if (cpuid(0x1).ecx >> 31) & 1 == 0 {
return HyperVPartition::Unknown; }
let vendor = cpuid(0x4000_0000);
let mut vendor_str = [0u8; 12];
vendor_str[0..4].copy_from_slice(&vendor.ebx.to_le_bytes());
vendor_str[4..8].copy_from_slice(&vendor.ecx.to_le_bytes());
vendor_str[8..12].copy_from_slice(&vendor.edx.to_le_bytes());
if String::from_utf8_lossy(&vendor_str).trim_end_matches('\0') != "Microsoft Hv" {
return HyperVPartition::Unknown;
}
if vendor.eax < 0x4000_0003 {
return HyperVPartition::Unknown;
}
let privileges = cpuid(0x4000_0003).ebx;
const CREATE_PARTITIONS: u32 = 1 << 0;
const CPU_MANAGEMENT: u32 = 1 << 12;
if privileges & CREATE_PARTITIONS != 0 && privileges & CPU_MANAGEMENT != 0 {
HyperVPartition::Root
} else {
HyperVPartition::Guest
}
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
HyperVPartition::Unknown
}
}
pub fn hypervisor_indicates_vm() -> Option<bool> {
if hyperv_partition() == HyperVPartition::Root {
return Some(false);
}
if detect_hypervisor().is_some() {
return Some(true);
}
if hypervisor_signals_readable() {
Some(false)
} else {
None
}
}
fn hypervisor_signals_readable() -> bool {
if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
return true;
}
dmi_readable()
}
#[cfg(target_os = "linux")]
fn dmi_field(name: &str) -> Option<String> {
std::fs::read_to_string(format!("/sys/class/dmi/id/{name}"))
.ok()
.map(|s| s.trim().to_lowercase())
}
#[cfg(target_os = "linux")]
fn dmi_readable() -> bool {
["product_name", "sys_vendor", "bios_vendor"]
.iter()
.any(|f| dmi_field(f).is_some())
}
#[cfg(not(target_os = "linux"))]
fn dmi_readable() -> bool {
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Hypervisor {
VMware,
HyperV,
KVM,
QEMU,
VirtualBox,
Xen,
Parallels,
Bhyve,
AmazonNitro,
GoogleCompute,
Azure,
AppleVirt,
WSL2,
Firecracker,
CloudHypervisor,
Lxc,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VirtPlatform {
BareMetal,
VirtualMachine,
Container,
WSL,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HypervisorInfo {
pub hypervisor: Hypervisor,
pub version: Option<String>,
pub cloud_provider: Option<String>,
pub instance_type: Option<String>,
pub detection_method: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuVirtCapability {
pub hardware_virt: bool,
pub ept_npt: Option<bool>,
pub iommu: Option<bool>,
pub sriov: Option<bool>,
pub nested: Option<bool>,
pub technology: String,
}
pub fn detect_platform() -> VirtPlatform {
#[cfg(target_os = "linux")]
{
if is_wsl() {
return VirtPlatform::WSL;
}
if is_container_env() {
return VirtPlatform::Container;
}
}
match hypervisor_indicates_vm() {
Some(true) => VirtPlatform::VirtualMachine,
Some(false) => VirtPlatform::BareMetal,
None => VirtPlatform::Unknown,
}
}
pub fn detect_hypervisor() -> Option<HypervisorInfo> {
if let Some(info) = detect_cpuid_hypervisor() {
return Some(info);
}
#[cfg(target_os = "linux")]
if let Some(info) = detect_dmi_hypervisor() {
return Some(info);
}
None
}
fn detect_cpuid_hypervisor() -> Option<HypervisorInfo> {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let result = cpuid(0x1);
let hypervisor_bit = (result.ecx >> 31) & 1;
if hypervisor_bit == 0 {
return None;
}
let vendor = cpuid(0x40000000);
let mut vendor_str = [0u8; 12];
vendor_str[0..4].copy_from_slice(&vendor.ebx.to_le_bytes());
vendor_str[4..8].copy_from_slice(&vendor.ecx.to_le_bytes());
vendor_str[8..12].copy_from_slice(&vendor.edx.to_le_bytes());
let vendor_id = String::from_utf8_lossy(&vendor_str)
.trim_end_matches('\0')
.to_string();
let hypervisor = match vendor_id.as_str() {
"VMwareVMware" => Hypervisor::VMware,
"Microsoft Hv" => Hypervisor::HyperV,
"KVMKVMKVM\0\0\0" | "KVMKVMKVM" => Hypervisor::KVM,
"TCGTCGTCGTCG" | "TCGTCGTCG" => Hypervisor::QEMU,
"VBoxVBoxVBox" => Hypervisor::VirtualBox,
"XenVMMXenVMM" => Hypervisor::Xen,
"bhyve bhyve " => Hypervisor::Bhyve,
" lrpepyh vr" => Hypervisor::Parallels,
"ACRNACRNACRN" => Hypervisor::Other,
_ => Hypervisor::Other,
};
Some(HypervisorInfo {
hypervisor,
version: None,
cloud_provider: detect_cloud_provider(),
instance_type: None,
detection_method: format!("CPUID: {}", vendor_id),
})
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
None
}
}
#[cfg(target_os = "linux")]
fn detect_dmi_hypervisor() -> Option<HypervisorInfo> {
let product = std::fs::read_to_string("/sys/class/dmi/id/product_name")
.unwrap_or_default()
.trim()
.to_lowercase();
let vendor = std::fs::read_to_string("/sys/class/dmi/id/sys_vendor")
.unwrap_or_default()
.trim()
.to_lowercase();
let bios = std::fs::read_to_string("/sys/class/dmi/id/bios_vendor")
.unwrap_or_default()
.trim()
.to_lowercase();
let hypervisor = if product.contains("virtualbox") || bios.contains("virtualbox") {
Hypervisor::VirtualBox
} else if vendor.contains("vmware") || product.contains("vmware") {
Hypervisor::VMware
} else if vendor.contains("qemu") || product.contains("kvm") {
Hypervisor::KVM
} else if vendor.contains("microsoft") && product.contains("virtual") {
Hypervisor::HyperV
} else if vendor.contains("xen") || product.contains("hvm domu") {
Hypervisor::Xen
} else if vendor.contains("amazon") || product.contains("nitro") {
Hypervisor::AmazonNitro
} else if vendor.contains("google") {
Hypervisor::GoogleCompute
} else if product.contains("parallels") {
Hypervisor::Parallels
} else {
return None;
};
Some(HypervisorInfo {
hypervisor,
version: None,
cloud_provider: detect_cloud_provider(),
instance_type: None,
detection_method: format!("DMI: {} {}", vendor, product),
})
}
fn detect_cloud_provider() -> Option<String> {
#[cfg(target_os = "linux")]
{
let vendor = std::fs::read_to_string("/sys/class/dmi/id/sys_vendor")
.unwrap_or_default()
.trim()
.to_lowercase();
let product = std::fs::read_to_string("/sys/class/dmi/id/product_name")
.unwrap_or_default()
.trim()
.to_lowercase();
if vendor.contains("amazon") || product.contains("nitro") {
return Some("AWS".into());
} else if vendor.contains("google") {
return Some("Google Cloud".into());
} else if vendor.contains("microsoft") && product.contains("virtual") {
return Some("Azure".into());
}
}
None
}
pub fn detect_cpu_virt_caps() -> Option<CpuVirtCapability> {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let result = cpuid(0x1);
let vmx = (result.ecx >> 5) & 1 == 1; let svm = {
let ext = cpuid(0x80000001);
(ext.ecx >> 2) & 1 == 1 };
let hw_virt = vmx || svm;
let tech = if vmx {
"Intel VT-x"
} else if svm {
"AMD-V"
} else {
"None"
};
Some(CpuVirtCapability {
hardware_virt: hw_virt,
ept_npt: None,
iommu: None,
sriov: None,
nested: None,
technology: tech.into(),
})
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
None
}
}
#[cfg(target_os = "linux")]
fn is_wsl() -> bool {
std::fs::read_to_string("/proc/version")
.map(|v| v.to_lowercase().contains("microsoft") || v.to_lowercase().contains("wsl"))
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
fn is_container_env() -> bool {
use std::path::Path;
Path::new("/.dockerenv").exists()
|| Path::new("/run/.containerenv").exists()
|| std::fs::read_to_string("/proc/1/cgroup")
.map(|c| c.contains("docker") || c.contains("containerd") || c.contains("lxc"))
.unwrap_or(false)
}
#[cfg(test)]
mod partition_tests {
use super::*;
#[test]
fn partition_agrees_with_hypervisor_vendor() {
let is_hyperv = matches!(
detect_hypervisor().map(|h| h.hypervisor),
Some(Hypervisor::HyperV)
);
match hyperv_partition() {
HyperVPartition::Root | HyperVPartition::Guest => assert!(
is_hyperv,
"claimed a Hyper-V partition kind without a Hyper-V vendor string"
),
HyperVPartition::Unknown => assert!(
!is_hyperv || cfg!(not(any(target_arch = "x86", target_arch = "x86_64"))),
"Hyper-V is present on an x86 machine but the partition kind was Unknown"
),
}
}
#[test]
fn root_partition_is_not_reported_as_a_vm() {
if hyperv_partition() == HyperVPartition::Root {
assert_eq!(
crate::virtualization::VirtMonitor::new()
.expect("VirtMonitor::new")
.is_virtual_machine(),
Some(false),
"a Hyper-V root partition is bare metal, not a VM"
);
}
}
}