Skip to main content

sys_lib/
virt.rs

1//! Virtualization and containers: what this program runs inside.
2//!
3//! The answer is layered checks (CPUID, firmware strings, hypervisor files,
4//! container markers, the Kubernetes service account, WSL's kernel release),
5//! read once and cached. Every check that fired is named in
6//! [`Virtualization::evidence`], as a constant string, never a raw value.
7//!
8//! **Detection is advisory.** Do not make security decisions on it: any of
9//! these markers can be planted, and a guest can hide from all of them
10//! (threat T14).
11//!
12//! ```
13//! use sys_lib as sys;
14//!
15//! let v = sys::virt::detect();
16//! if sys::virt::is_container() {
17//!     println!("in {:?}; kubernetes: {}", v.container, v.kubernetes);
18//! }
19//! for e in &v.evidence {
20//!     println!("  {} ({:?})", e.check, e.strength);
21//! }
22//! ```
23
24use std::sync::OnceLock;
25
26/// What this program runs inside. A container inside a VM sets both
27/// `container` and `hypervisor`; inside WSL 2 both `hypervisor` and `wsl`.
28#[derive(Clone, Debug, Default, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct Virtualization {
31    /// The innermost hypervisor visible to this machine.
32    pub hypervisor: Option<Hypervisor>,
33    /// The container runtime.
34    pub container: Option<Container>,
35    /// The WSL version, 1 or 2.
36    pub wsl: Option<u8>,
37    /// Running under Kubernetes. With [`Strength::Weak`] evidence only, this
38    /// rests on an environment variable (E-87).
39    pub kubernetes: bool,
40    /// Every check that fired.
41    pub evidence: Vec<Evidence>,
42}
43
44impl Virtualization {
45    /// Records a check that fired.
46    pub(crate) fn fired(&mut self, check: &'static str, strength: Strength) {
47        self.evidence.push(Evidence { check, strength });
48    }
49}
50
51/// A hypervisor.
52#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
53#[non_exhaustive]
54pub enum Hypervisor {
55    /// Linux KVM.
56    Kvm,
57    /// QEMU without KVM (TCG).
58    Qemu,
59    /// VMware.
60    Vmware,
61    /// Microsoft Hyper-V.
62    HyperV,
63    /// Xen.
64    Xen,
65    /// Oracle VirtualBox.
66    VirtualBox,
67    /// Parallels.
68    Parallels,
69    /// FreeBSD bhyve.
70    Bhyve,
71    /// ACRN.
72    Acrn,
73    /// QNX Hypervisor.
74    Qnx,
75    /// Apple's Virtualization framework.
76    AppleVirtualization,
77    /// AWS Nitro.
78    AmazonNitro,
79    /// Google Compute Engine.
80    GoogleCompute,
81    /// Bochs.
82    Bochs,
83    /// A hypervisor sys-lib cannot name.
84    Other,
85}
86
87/// A container runtime.
88#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
89#[non_exhaustive]
90pub enum Container {
91    /// Docker.
92    Docker,
93    /// Podman.
94    Podman,
95    /// containerd or CRI-O, as Kubernetes runs them.
96    Containerd,
97    /// LXC or LXD.
98    Lxc,
99    /// `systemd-nspawn`.
100    SystemdNspawn,
101    /// OpenVZ or Virtuozzo.
102    OpenVz,
103    /// A container runtime sys-lib cannot name.
104    Other,
105}
106
107/// One check that fired.
108#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
109#[non_exhaustive]
110pub struct Evidence {
111    /// What was checked: a constant, never a value read from the machine.
112    pub check: &'static str,
113    /// How much it proves.
114    pub strength: Strength,
115}
116
117/// How much a piece of evidence proves.
118#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
119#[non_exhaustive]
120pub enum Strength {
121    /// Set by the kernel, the firmware, or the runtime.
122    Strong,
123    /// An environment variable or the like: any parent process can set it.
124    Weak,
125}
126
127/// A cloud vendor, from firmware strings only: sys-lib never contacts a
128/// metadata service.
129#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
130#[non_exhaustive]
131pub enum Cloud {
132    /// Amazon Web Services.
133    Aws,
134    /// Google Cloud.
135    Gcp,
136    /// Microsoft Azure.
137    Azure,
138    /// Oracle Cloud.
139    Oracle,
140    /// Alibaba Cloud.
141    Alibaba,
142    /// Hetzner.
143    Hetzner,
144    /// DigitalOcean.
145    DigitalOcean,
146    /// Linode (Akamai).
147    Linode,
148    /// Vultr.
149    Vultr,
150    /// Scaleway.
151    Scaleway,
152    /// OVHcloud.
153    Ovh,
154    /// A cloud sys-lib cannot name.
155    Other,
156}
157
158/// What this program runs inside. Cached: about 1 ns after the first call.
159#[must_use]
160pub fn detect() -> &'static Virtualization {
161    static FACTS: OnceLock<Virtualization> = OnceLock::new();
162    FACTS.get_or_init(crate::sys::virtualization)
163}
164
165/// Running on a hypervisor. Inside WSL 2 this and [`is_wsl`] are both true.
166/// A Windows host with Hyper-V, WSL 2, or virtualization-based security
167/// enabled is not a VM (E-84).
168#[must_use]
169pub fn is_vm() -> bool {
170    detect().hypervisor.is_some()
171}
172
173/// Running in a container.
174#[must_use]
175pub fn is_container() -> bool {
176    detect().container.is_some()
177}
178
179/// Running under WSL.
180#[must_use]
181pub fn is_wsl() -> bool {
182    detect().wsl.is_some()
183}
184
185/// Running under Kubernetes (see [`Virtualization::kubernetes`]).
186#[must_use]
187pub fn is_kubernetes() -> bool {
188    detect().kubernetes
189}
190
191/// The hypervisor, when there is one.
192#[must_use]
193pub fn hypervisor() -> Option<Hypervisor> {
194    detect().hypervisor
195}
196
197/// The container runtime, when there is one.
198#[must_use]
199pub fn container() -> Option<Container> {
200    detect().container
201}
202
203/// The cloud vendor, from firmware strings and the hypervisor leaves. Instance
204/// types, regions, and zones need a network call and belong in a cloud crate.
205#[must_use]
206pub fn cloud() -> Option<Cloud> {
207    static FACTS: OnceLock<Option<Cloud>> = OnceLock::new();
208    *FACTS.get_or_init(crate::sys::cloud)
209}
210
211/// The firmware strings the detection reads, from sysfs or SMBIOS.
212#[cfg_attr(target_vendor = "apple", allow(dead_code))]
213#[derive(Clone, Copy, Debug, Default)]
214pub(crate) struct Dmi<'a> {
215    pub(crate) sys_vendor: &'a str,
216    pub(crate) product: &'a str,
217    pub(crate) product_version: &'a str,
218    pub(crate) board_vendor: &'a str,
219    pub(crate) bios_vendor: &'a str,
220    pub(crate) asset_tag: &'a str,
221}
222
223impl Dmi<'_> {
224    #[cfg_attr(target_vendor = "apple", allow(dead_code))]
225    fn any(&self, needle: &str) -> bool {
226        [
227            self.sys_vendor,
228            self.product,
229            self.product_version,
230            self.board_vendor,
231            self.bios_vendor,
232        ]
233        .iter()
234        .any(|s| contains_ignore_case(s, needle))
235    }
236}
237
238#[cfg_attr(target_vendor = "apple", allow(dead_code))]
239fn contains_ignore_case(haystack: &str, needle: &str) -> bool {
240    haystack
241        .as_bytes()
242        .windows(needle.len())
243        .any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
244}
245
246/// The hypervisor a CPUID vendor signature (leaf 0x40000000) names.
247pub(crate) fn hypervisor_from_signature(signature: &[u8; 12]) -> Hypervisor {
248    match signature {
249        b"KVMKVMKVM\0\0\0" | b"Linux KVM Hv" => Hypervisor::Kvm,
250        b"TCGTCGTCGTCG" => Hypervisor::Qemu,
251        b"VMwareVMware" => Hypervisor::Vmware,
252        b"Microsoft Hv" => Hypervisor::HyperV,
253        b"XenVMMXenVMM" => Hypervisor::Xen,
254        b"bhyve bhyve " => Hypervisor::Bhyve,
255        b"QNXQVMBSQG\0\0" => Hypervisor::Qnx,
256        b"ACRNACRNACRN" => Hypervisor::Acrn,
257        b"Apple VZ\0\0\0\0" | b"VirtualApple" => Hypervisor::AppleVirtualization,
258        b"VBoxVBoxVBox" => Hypervisor::VirtualBox,
259        b" prl hyperv " | b" lrpepyh vr " => Hypervisor::Parallels,
260        _ => Hypervisor::Other,
261    }
262}
263
264/// The hypervisor firmware strings name. The clouds' own hypervisors are named
265/// first: a Nitro or GCE guest also says KVM.
266#[cfg_attr(target_vendor = "apple", allow(dead_code))]
267pub(crate) fn hypervisor_from_dmi(dmi: &Dmi<'_>) -> Option<Hypervisor> {
268    let table: &[(&str, Hypervisor)] = &[
269        ("Amazon EC2", Hypervisor::AmazonNitro),
270        ("Google Compute Engine", Hypervisor::GoogleCompute),
271        ("Alibaba Cloud ECS", Hypervisor::Kvm),
272        ("KubeVirt", Hypervisor::Kvm),
273        ("OpenStack", Hypervisor::Kvm),
274        ("KVM", Hypervisor::Kvm),
275        ("QEMU", Hypervisor::Qemu),
276        ("VMware", Hypervisor::Vmware),
277        ("innotek GmbH", Hypervisor::VirtualBox),
278        ("VirtualBox", Hypervisor::VirtualBox),
279        ("Xen", Hypervisor::Xen),
280        ("Bochs", Hypervisor::Bochs),
281        ("Parallels", Hypervisor::Parallels),
282        ("BHYVE", Hypervisor::Bhyve),
283        ("Apple Virtualization", Hypervisor::AppleVirtualization),
284    ];
285    if let Some((_, h)) = table.iter().find(|(needle, _)| dmi.any(needle)) {
286        return Some(*h);
287    }
288    // Hyper-V says only "Microsoft Corporation" and "Virtual Machine": physical
289    // Surface machines say the first too.
290    let microsoft = contains_ignore_case(dmi.sys_vendor, "Microsoft Corporation");
291    (microsoft && contains_ignore_case(dmi.product, "Virtual Machine"))
292        .then_some(Hypervisor::HyperV)
293}
294
295/// The cloud firmware strings or the hypervisor name.
296#[cfg_attr(target_vendor = "apple", allow(dead_code))]
297pub(crate) fn cloud_from_dmi(dmi: &Dmi<'_>, hypervisor: Option<Hypervisor>) -> Option<Cloud> {
298    let table: &[(&str, Cloud)] = &[
299        ("Amazon EC2", Cloud::Aws),
300        ("Amazon", Cloud::Aws),
301        ("Google Compute Engine", Cloud::Gcp),
302        ("Google", Cloud::Gcp),
303        ("Alibaba Cloud", Cloud::Alibaba),
304        ("Hetzner", Cloud::Hetzner),
305        ("DigitalOcean", Cloud::DigitalOcean),
306        ("Linode", Cloud::Linode),
307        ("Akamai", Cloud::Linode),
308        ("Vultr", Cloud::Vultr),
309        ("Scaleway", Cloud::Scaleway),
310        ("OVHcloud", Cloud::Ovh),
311    ];
312    if let Some((_, c)) = table.iter().find(|(needle, _)| dmi.any(needle)) {
313        return Some(*c);
314    }
315    // Azure's asset tag is a fixed string; Oracle's is too.
316    if dmi.asset_tag == "7783-7084-3265-9085-8269-3286-77" {
317        return Some(Cloud::Azure);
318    }
319    if dmi.asset_tag == "OracleCloud.com" {
320        return Some(Cloud::Oracle);
321    }
322    match hypervisor {
323        Some(Hypervisor::AmazonNitro) => Some(Cloud::Aws),
324        Some(Hypervisor::GoogleCompute) => Some(Cloud::Gcp),
325        _ => None,
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn test_virt_signatures() {
335        assert_eq!(
336            hypervisor_from_signature(b"KVMKVMKVM\0\0\0"),
337            Hypervisor::Kvm
338        );
339        assert_eq!(hypervisor_from_signature(b"Linux KVM Hv"), Hypervisor::Kvm);
340        assert_eq!(
341            hypervisor_from_signature(b"Microsoft Hv"),
342            Hypervisor::HyperV
343        );
344        assert_eq!(
345            hypervisor_from_signature(b"VMwareVMware"),
346            Hypervisor::Vmware
347        );
348        assert_eq!(
349            hypervisor_from_signature(b"something new"[..12].try_into().unwrap()),
350            Hypervisor::Other
351        );
352    }
353
354    #[test]
355    fn test_virt_dmi_strings() {
356        let dmi = |product, sys_vendor| Dmi {
357            product,
358            sys_vendor,
359            ..Dmi::default()
360        };
361        assert_eq!(
362            hypervisor_from_dmi(&dmi("Standard PC (Q35 + ICH9, 2009)", "QEMU")),
363            Some(Hypervisor::Qemu)
364        );
365        assert_eq!(
366            hypervisor_from_dmi(&dmi("VirtualBox", "innotek GmbH")),
367            Some(Hypervisor::VirtualBox)
368        );
369        assert_eq!(
370            hypervisor_from_dmi(&dmi("m5.large", "Amazon EC2")),
371            Some(Hypervisor::AmazonNitro)
372        );
373        assert_eq!(
374            hypervisor_from_dmi(&dmi("Virtual Machine", "Microsoft Corporation")),
375            Some(Hypervisor::HyperV)
376        );
377        // A real Surface is not a VM.
378        assert_eq!(
379            hypervisor_from_dmi(&dmi("Surface Laptop 5", "Microsoft Corporation")),
380            None
381        );
382        assert_eq!(hypervisor_from_dmi(&dmi("ThinkPad X1", "LENOVO")), None);
383    }
384
385    #[test]
386    fn test_virt_clouds() {
387        let aws = Dmi {
388            sys_vendor: "Amazon EC2",
389            ..Dmi::default()
390        };
391        assert_eq!(cloud_from_dmi(&aws, None), Some(Cloud::Aws));
392        let azure = Dmi {
393            sys_vendor: "Microsoft Corporation",
394            product: "Virtual Machine",
395            asset_tag: "7783-7084-3265-9085-8269-3286-77",
396            ..Dmi::default()
397        };
398        assert_eq!(
399            cloud_from_dmi(&azure, Some(Hypervisor::HyperV)),
400            Some(Cloud::Azure)
401        );
402        let hyperv = Dmi {
403            asset_tag: "",
404            ..azure
405        };
406        assert_eq!(cloud_from_dmi(&hyperv, Some(Hypervisor::HyperV)), None);
407        assert_eq!(cloud_from_dmi(&Dmi::default(), None), None);
408    }
409
410    #[test]
411    fn test_virt_live_is_consistent() {
412        let v = detect();
413        assert!(std::ptr::eq(v, detect()));
414        assert_eq!(is_vm(), v.hypervisor.is_some());
415        assert_eq!(is_container(), v.container.is_some());
416        if let Some(w) = v.wsl {
417            assert!(matches!(w, 1 | 2));
418        }
419        // Evidence names constants, one per check.
420        for e in &v.evidence {
421            assert!(!e.check.is_empty());
422        }
423    }
424}