Skip to content

openvmm: a snapshot's host CPU profile can give the guest VMX or SVM #1357

Closed

Description

@tangruize

Restoring a microVM snapshot whose host CPU profile sets CPUID bits that profile derivation always clears gives the restored guest those bits: most importantly VMX (CPUID.1:ECX[5]), or SVM on AMD, although nested_virt is false. Only a crafted or tampered snapshot reaches this: a host profile (<vendor>.host.v<n>) is a document the snapshot itself carries, and the profiles OpenVMM derives follow the policy. Cold boot is not affected. On a KVM host with nested virtualization enabled (KVM's default; without it, the restore's support check refuses the profile), the guest can then enable VMX or SVM and reach KVM's nested-virtualization code, host attack surface that nested_virt false is meant to keep closed. OpenVMM's KVM backend also saves no nested state, so a later snapshot of a VP running a nested guest is not faithful.

Reproduction

On an Intel KVM host with nested virtualization enabled, derive the host's profile (derive_host_profile), set CPUID.1:ECX bit 5 (VMX) in its document, decode it with host_profile_for_restore and the document's own digest, and build a one-VP time-ABI partition from it with nested_virt false. Expected: the profile is refused. Actual: VMX is in the effective CPUID, the support check passes, and a real-mode guest reads VMX with CPUID, sets CR4.VMXE and reads IA32_VMX_BASIC without a #GP. The derived profile itself gives a guest without VMX. SVM on AMD was not reproduced.

Cause

host_profile_for_restore (vmm_core/cpu_profile/src/catalog.rs) accepts any host profile that decodes (which checks its structure and the CPU time bits) and matches the recorded id and digest, and whoever crafts the snapshot can recompute the digest:

// vmm_core/cpu_profile/src/catalog.rs
if canonical::sha256(document).as_slice() != sha256 {
    // ...
}
let profile = CpuProfile::decode(document)?;
if profile.id() != id || profile.generation().name != HOST_GENERATION {
    // ...
}
Ok(profile)

Nothing compares the profile's CPUID with the derivation's policy (apply_policy in derive.rs). On KVM, a time-ABI partition's CPUID is the profile's effective CPUID, and the VMX or SVM strip that new_partition adds for !nested_virt reaches only partitions without a time ABI.

Fix

fix.patch adds a module, cpu_profile::policy, that states the derivation's policy once: the per-register rules (POLICY_RULES), the features cleared without their XSAVE state, the XSAVE allowance, PSFD's rule and the data leaves. derive.rs applies those rules, and CpuProfile::effective_cpuid first checks the profile against them (policy_violation), so derivation and the check cannot drift apart. Every effective CPUID is built there, on cold boot and on restore, for every backend, and a profile outside the policy fails the VM worker's load with E_PROFILE_DIGEST ("CPU profile intel.host.v1 is outside the derivation's CPUID policy: ..."). The tests in policy.rs check that every pinned profile and every profile derived from a recorded host follows the policy, that flipping any rule bit breaks it, and that a restored profile with VMX, SVM or a time bit set is refused. One consequence needs a decision: when the policy changes, host-profile snapshots made under the old policy can no longer be restored. Pinned profiles are not affected.

Activity

  1. tangruize commented on Nov 8, 2026

    @tangruize
    ContributorAuthor

    Proposed patch

    Patch against OpenVMM 3cf58a5234ed824435825c9f87187f5129219724. Save the contents below as fix.patch and run git apply fix.patch.

    fix.patch
    diff --git a/vmm_core/cpu_profile/src/derive.rs b/vmm_core/cpu_profile/src/derive.rs
    index 9d6ff1e..560bd86 100644
    --- a/vmm_core/cpu_profile/src/derive.rs
    +++ b/vmm_core/cpu_profile/src/derive.rs
    @@ -59,6 +59,10 @@
     use crate::fingerprint::CpuFingerprint;
     use crate::fingerprint::IA32_ARCH_CAPABILITIES;
     use crate::hv_banks;
    +use crate::policy::POLICY_RULES;
    +use crate::policy::PolicyAction;
    +use crate::policy::STATELESS_FEATURES;
    +use crate::policy::is_data_leaf;
     use crate::profile::CpuProfile;
     use crate::profile::CpuidLeafValue;
     use crate::profile::Generation;
    @@ -709,8 +713,7 @@ fn apply_policy(vendor: CpuVendor, combined: &Table) -> Result<Table, DeriveErro
         let mut leaves = Table::new();
         let all_leaves = (0..=max_basic).chain(EXTENDED_LEAF_BASE..=max_extended);
         for leaf in all_leaves.filter(|leaf| !VM_OWNED_LEAVES.contains(leaf)) {
    -        let data = DATA_LEAVES.contains(&leaf)
    -            || (vendor == CpuVendor::Amd && AMD_DATA_LEAVES.contains(&leaf));
    +        let data = is_data_leaf(vendor == CpuVendor::Amd, leaf);
             if !cpuid::is_indexed_leaf(leaf) {
                 leaves.insert((leaf, None), if data { get(leaf, None) } else { [0; 4] });
                 continue;
    @@ -752,146 +755,23 @@ fn apply_policy(vendor: CpuVendor, combined: &Table) -> Result<Table, DeriveErro
                     Ok(())
                 }
             };
    -    // CPUID.1: the hypervisor bit (time ABI); no VMX, SMX, EST, TM2, DTES64,
    -    // MONITOR, DS-CPL, SDBG, xTPR, PDCM (time ABI, no PMU), DCA, or
    -    // TSC-deadline (time ABI); no DS, ACPI, TM, or PBE.
    -    edit(
    -        &mut leaves,
    -        (0x1, None),
    -        2,
    -        1 << 31,
    -        1 << 2
    -            | 1 << 3
    -            | 1 << 4
    -            | 1 << 5
    -            | 1 << 6
    -            | 1 << 7
    -            | 1 << 8
    -            | 1 << 11
    -            | 1 << 14
    -            | 1 << 15
    -            | 1 << 18
    -            | 1 << 24,
    -    );
    -    edit(
    -        &mut leaves,
    -        (0x1, None),
    -        3,
    -        0,
    -        1 << 21 | 1 << 22 | 1 << 29 | 1 << 31,
    -    );
    -    require(&leaves, (0x1, None), 3, 1 << 4, "the TSC")?;
    -    // CPUID.6: ARAT only (time ABI).
    -    leaves.insert((0x6, None), [1 << 2, 0, 0, 0]);
    -    // CPUID.(7,0): no TSC_ADJUST (time ABI), SGX, RDT, or Intel PT; no CET,
    -    // key locker, or SGX launch control; no hybrid, PCONFIG, or arch LBR.
    -    edit(
    -        &mut leaves,
    -        (0x7, Some(0)),
    -        1,
    -        0,
    -        1 << 1 | 1 << 2 | 1 << 12 | 1 << 15 | 1 << 25,
    -    );
    -    edit(
    -        &mut leaves,
    -        (0x7, Some(0)),
    -        2,
    -        0,
    -        1 << 7 | 1 << 23 | 1 << 30,
    -    );
    -    edit(
    -        &mut leaves,
    -        (0x7, Some(0)),
    -        3,
    -        0,
    -        1 << 15 | 1 << 18 | 1 << 19 | 1 << 20,
    -    );
    -    // CPUID.0x80000001: RDTSCP (time ABI).
    -    require(
    -        &leaves,
    -        (EXTENDED_LEAF_BASE + 1, None),
    -        3,
    -        1 << 27,
    -        "RDTSCP",
    -    )?;
    -    // CPUID.0x80000007: the invariant TSC only (time ABI).
    -    leaves.insert((EXTENDED_LEAF_BASE + 7, None), [0, 0, 0, 1 << 8]);
    -    // CPUID.0x80000008: the address widths only; no GuestPhysBits, which only
    -    // newer KVM reports, and no AMD core count.
    -    edit(
    -        &mut leaves,
    -        (EXTENDED_LEAF_BASE + 8, None),
    -        0,
    -        0,
    -        0xffff_0000,
    -    );
    -    edit(&mut leaves, (EXTENDED_LEAF_BASE + 8, None), 2, 0, !0);
    -    edit(&mut leaves, (EXTENDED_LEAF_BASE + 8, None), 3, 0, !0);
    +    // The policy's rules ([`POLICY_RULES`]), in their order: the AMD rules
    +    // only in AMD profiles.
    +    for rule in POLICY_RULES
    +        .iter()
    +        .filter(|rule| !rule.amd_only || vendor == CpuVendor::Amd)
    +    {
    +        let key = (rule.leaf, rule.subleaf);
    +        match rule.action {
    +            PolicyAction::Edit => edit(&mut leaves, key, rule.register, rule.set, rule.clear),
    +            PolicyAction::Fill => {
    +                leaves.entry(key).or_insert([0; 4]);
    +                edit(&mut leaves, key, rule.register, rule.set, rule.clear);
    +            }
    +            PolicyAction::Require => require(&leaves, key, rule.register, rule.set, rule.name)?,
    +        }
    +    }
         if vendor == CpuVendor::Amd {
    -        // CPUID.0x80000001 EBX: no brand ID or package type, which describe
    -        // the host's SKU and socket rather than the CPU's features.
    -        edit(&mut leaves, (EXTENDED_LEAF_BASE + 1, None), 1, 0, !0);
    -        // CPUID.0x80000001 ECX: no SVM, IBS, SKINIT, watchdog timer, LWP, or
    -        // node ID MSR; no core, northbridge, or LLC performance counter
    -        // extensions, performance TSC, data breakpoint or address mask
    -        // extensions, or MONITORX. No 3DNowPrefetch either: the Hyper-V root
    -        // of a nested Azure host does not see it, so that host's cold-boot
    -        // support check, which reads the root's CPUID, would fail a profile
    -        // that pins it, although WHP's guests see it; Linux infers PREFETCHW
    -        // from long mode whatever the bit says.
    -        edit(
    -            &mut leaves,
    -            (EXTENDED_LEAF_BASE + 1, None),
    -            2,
    -            0,
    -            1 << 2
    -                | 1 << 8
    -                | 1 << 10
    -                | 1 << 12
    -                | 1 << 13
    -                | 1 << 15
    -                | 1 << 19
    -                | 1 << 23
    -                | 1 << 24
    -                | 1 << 26
    -                | 1 << 27
    -                | 1 << 28
    -                | 1 << 29
    -                | 1 << 30,
    -        );
    -        // CPUID.0x80000008 EBX: no instructions-retired counter, INVLPGB
    -        // (nested pages included), RDPRU, which reads APERF and MPERF, memory
    -        // bandwidth enforcement, PPIN, CPPC, or branch sampling. No BTC_NO
    -        // either: KVM never enumerates it in KVM_GET_SUPPORTED_CPUID, so every
    -        // KVM host would fail a profile that set it, and a guest loses
    -        // nothing without it, because Linux marks no CPU of family 0x19 or
    -        // later as affected by RETBLEED, which is all the bit decides. The
    -        // speculation controls and the other immunities stay.
    -        edit(
    -            &mut leaves,
    -            (EXTENDED_LEAF_BASE + 8, None),
    -            1,
    -            0,
    -            1 << 1 | 1 << 3 | 1 << 4 | 1 << 6 | 1 << 21 | 1 << 23 | 1 << 27 | AMD_BTC_NO | 1 << 31,
    -        );
    -        // CPUID.(7,0) EDX: none of Intel's speculation controls or
    -        // IA32_ARCH_CAPABILITIES, which KVM enumerates on AMD hosts beside
    -        // AMD's own controls in 0x80000008 EBX, and emulates. No AMD CPU has
    -        // them: AMD enumerates its controls and immunities in 0x80000008 and
    -        // 0x80000021, which the Hyper-V banks map, and the Milan host's WHP
    -        // presents none of the bits, so a profile derived from KVM alone
    -        // would otherwise fail the Hyper-V hosts of its generation. A guest
    -        // loses nothing: it uses AMD's controls, and Linux takes no AMD CPU
    -        // to be affected by the vulnerabilities whose immunities the MSR
    -        // reports. With the bit clear, the profile pins no
    -        // IA32_ARCH_CAPABILITIES value.
    -        edit(
    -            &mut leaves,
    -            (0x7, Some(0)),
    -            3,
    -            0,
    -            INTEL_SPECULATION_ENUMERATIONS,
    -        );
             // PSFD is a bit of SPEC_CTRL, so it means nothing to a guest that
             // cannot access SPEC_CTRL, and KVM lets a guest access it only if the
             // guest's CPUID has a SPEC_CTRL control. The rule reads the derived
    @@ -909,66 +789,18 @@ fn apply_policy(vendor: CpuVendor, combined: &Table) -> Result<Table, DeriveErro
             ) {
                 edit(&mut leaves, (EXTENDED_LEAF_BASE + 8, None), 1, 0, AMD_PSFD);
             }
    -        // CPUID.0x80000021: AutoIBRS, LFENCE serialization, SBPB, SRSO_NO,
    -        // and the TSA immunities stay; no CPUID faulting, which writes HWCR,
    -        // or workload classification; nothing in EBX (the microcode patch and
    -        // return address predictor sizes) or EDX.
    -        edit(
    -            &mut leaves,
    -            (EXTENDED_LEAF_BASE + 0x21, None),
    -            0,
    -            0,
    -            1 << 17 | 1 << 22,
    -        );
    -        edit(&mut leaves, (EXTENDED_LEAF_BASE + 0x21, None), 1, 0, !0);
    -        edit(&mut leaves, (EXTENDED_LEAF_BASE + 0x21, None), 3, 0, !0);
         }
         Ok(leaves)
     }
     
    -/// Clears the features whose XSAVE state `xcr0` does not enable.
    +/// Clears the features whose XSAVE state `xcr0` does not enable
    +/// ([`STATELESS_FEATURES`]).
     fn clear_stateless_features(leaves: &mut Table, xcr0: u64) {
    -    const AVX: u64 = 1 << 2;
    -    const MPX: u64 = 3 << 3;
    -    const AVX512: u64 = 7 << 5;
    -    const PKRU: u64 = 1 << 9;
    -    let enabled = |state: u64| xcr0 & state == state;
    -    if let Some(value) = leaves.get_mut(&(0x1, None)) {
    -        if !enabled(AVX) {
    -            // AVX, FMA, and F16C.
    -            value[2] &= !(1 << 28 | 1 << 12 | 1 << 29);
    -        }
    -    }
    -    if let Some(value) = leaves.get_mut(&(0x7, Some(0))) {
    -        if !enabled(AVX) {
    -            // AVX2, VAES, and VPCLMULQDQ.
    -            value[1] &= !(1 << 5);
    -            value[2] &= !(1 << 9 | 1 << 10);
    -        }
    -        if !enabled(MPX) {
    -            value[1] &= !(1 << 14);
    -        }
    -        if !enabled(AVX512) {
    -            // AVX512F, DQ, IFMA, PF, ER, CD, BW, and VL; VBMI, VBMI2, VNNI,
    -            // BITALG, and VPOPCNTDQ; 4VNNIW, 4FMAPS, VP2INTERSECT, and FP16.
    -            value[1] &=
    -                !(1 << 16 | 1 << 17 | 1 << 21 | 1 << 26 | 1 << 27 | 1 << 28 | 1 << 30 | 1 << 31);
    -            value[2] &= !(1 << 1 | 1 << 6 | 1 << 11 | 1 << 12 | 1 << 14);
    -            value[3] &= !(1 << 2 | 1 << 3 | 1 << 8 | 1 << 23);
    -        }
    -        if !enabled(PKRU) {
    -            // PKU.
    -            value[2] &= !(1 << 3);
    -        }
    -    }
    -    if let Some(value) = leaves.get_mut(&(0x7, Some(1))) {
    -        if !enabled(AVX) {
    -            // AVX-VNNI.
    -            value[0] &= !(1 << 4);
    -        }
    -        if !enabled(AVX512) {
    -            // AVX512-BF16.
    -            value[0] &= !(1 << 5);
    +    for feature in &STATELESS_FEATURES {
    +        if xcr0 & feature.state != feature.state {
    +            if let Some(value) = leaves.get_mut(&(feature.leaf, feature.subleaf)) {
    +                value[feature.register] &= !feature.clear;
    +            }
             }
         }
     }
    diff --git a/vmm_core/cpu_profile/src/effective.rs b/vmm_core/cpu_profile/src/effective.rs
    index 4bb752e..aaa35d0 100644
    --- a/vmm_core/cpu_profile/src/effective.rs
    +++ b/vmm_core/cpu_profile/src/effective.rs
    @@ -8,12 +8,15 @@
     use crate::canonical;
     use crate::error::ProfileError;
     use crate::error::ProfileErrorCode;
    +use crate::policy::describe_violation;
    +use crate::policy::policy_violation;
     use crate::profile::CpuProfile;
     use crate::profile::CpuidLeafValue;
     use crate::profile::VM_OWNED_LEAVES;
     use crate::profile::describe_leaf;
     use crate::profile::find;
     use crate::profile::vm_owned_bits;
    +use crate::vendor::CpuVendor;
     use serde::Deserialize;
     use std::cmp::Ordering;
     
    @@ -328,8 +331,12 @@ impl CpuProfile {
         /// time ABI's hypervisor identity leaves, which must lie in
         /// `0x40000000..=0x4fffffff`. Later results override earlier ones.
         ///
    -    /// Fails with `E_CPU_SURFACE` when the inputs do not complete the profile
    -    /// exactly.
    +    /// Fails with `E_PROFILE_DIGEST`, before anything else, for a profile
    +    /// outside the derivation's CPUID policy
    +    /// ([`policy_violation`](crate::policy::policy_violation)): a pinned or
    +    /// derived profile follows it, so only a restored host profile, which is
    +    /// the snapshot's own document, can be refused so. Fails with
    +    /// `E_CPU_SURFACE` when the inputs do not complete the profile exactly.
         pub fn effective_cpuid(
             &self,
             vm: &[CpuidResult],
    @@ -344,6 +351,20 @@ pub fn effective_cpuid(
                     ),
                 )
             };
    +        // A VM's CPUID comes only from a profile that the derivation could
    +        // have made: a restored host profile is the snapshot's own document,
    +        // and nothing else holds it to the policy.
    +        let vendor = self.cpu_vendor();
    +        if let Some(violation) = policy_violation(vendor == CpuVendor::Amd, self.cpuid()) {
    +            return Err(ProfileError::new(
    +                ProfileErrorCode::ProfileDigest,
    +                format!(
    +                    "CPU profile {} is outside the derivation's CPUID policy: {}",
    +                    self.id(),
    +                    describe_violation(violation, self.cpuid())
    +                ),
    +            ));
    +        }
             // The profile's table is sorted by key, so a sorted vector serves as
             // the map, with less code to run on a VM's first start than a tree.
             let mut entries = self
    @@ -352,7 +373,6 @@ pub fn effective_cpuid(
                 .map(|entry| (entry.key(), (entry.values(), entry.masks())))
                 .collect::<Vec<_>>();
             let max_basic = self.lookup(0, 0)[0];
    -        let vendor = self.cpu_vendor();
     
             for leaf in vm.iter().filter(|leaf| leaf.mask != [0; 4]) {
                 let what = || describe_leaf(leaf.function, leaf.index);
    diff --git a/vmm_core/cpu_profile/src/lib.rs b/vmm_core/cpu_profile/src/lib.rs
    index bf4f02d..b20aa0a 100644
    --- a/vmm_core/cpu_profile/src/lib.rs
    +++ b/vmm_core/cpu_profile/src/lib.rs
    @@ -75,6 +75,7 @@
     pub mod fingerprint;
     pub mod host;
     pub mod hv_banks;
    +pub mod policy;
     
     mod canonical;
     mod catalog;
    diff --git a/vmm_core/cpu_profile/src/policy.rs b/vmm_core/cpu_profile/src/policy.rs
    new file mode 100644
    index 0000000..dc8e058
    --- /dev/null
    +++ b/vmm_core/cpu_profile/src/policy.rs
    @@ -0,0 +1,1013 @@
    +// Copyright (c) Microsoft Corporation.
    +// Licensed under the MIT License.
    +
    +//! The derivation's CPUID policy, written once.
    +//!
    +//! The derivation ([`derive`](mod@crate::derive)) applies these rules to the
    +//! hosts' combined CPUID, so every profile it derives, pinned or host,
    +//! follows them. A VM's effective CPUID is built only from a profile that
    +//! follows them: [`CpuProfile::effective_cpuid`](crate::CpuProfile::effective_cpuid)
    +//! refuses any other ([`policy_violation`]), on cold boot and on restore. A
    +//! restored host profile is the snapshot's own document, so that check is
    +//! what holds it to the policy.
    +//!
    +//! The policy has five parts: the rules of [`POLICY_RULES`], each fixing
    +//! bits of one register; the features of [`STATELESS_FEATURES`], cleared
    +//! when their XSAVE state is not enabled; the XSAVE features within
    +//! [`ALLOWED_XCR0`], [`ALLOWED_XSS`] and [`ALLOWED_XSAVE_EXTENSIONS`]; PSFD
    +//! only beside a `SPEC_CTRL` control ([`has_spec_ctrl_control`]); and every
    +//! leaf outside [`DATA_LEAVES`] (and [`AMD_DATA_LEAVES`] in AMD profiles)
    +//! zero.
    +
    +use crate::cpuid::EXTENDED_LEAF_BASE;
    +use crate::derive::ALLOWED_XCR0;
    +use crate::derive::ALLOWED_XSAVE_EXTENSIONS;
    +use crate::derive::ALLOWED_XSS;
    +use crate::derive::AMD_BTC_NO;
    +use crate::derive::AMD_DATA_LEAVES;
    +use crate::derive::AMD_PSFD;
    +use crate::derive::DATA_LEAVES;
    +use crate::derive::INTEL_SPECULATION_ENUMERATIONS;
    +use crate::derive::has_spec_ctrl_control;
    +use crate::profile::CpuidLeafValue;
    +use crate::profile::describe_leaf;
    +
    +/// How the derivation establishes a [`PolicyRule`].
    +#[derive(Clone, Copy, Debug, PartialEq, Eq)]
    +pub enum PolicyAction {
    +    /// It sets and clears the rule's bits in the leaf, where the hosts
    +    /// report the leaf.
    +    Edit,
    +    /// It sets the register to the rule's bits, adding the leaf where the
    +    /// hosts do not report it.
    +    Fill,
    +    /// It fails where the hosts lack the rule's bits
    +    /// ([`DeriveError::TimeFeature`](crate::derive::DeriveError::TimeFeature),
    +    /// with the rule's name).
    +    Require,
    +}
    +
    +/// One rule of the derivation's CPUID policy: in CPUID `leaf` and `subleaf`
    +/// (`None` for a leaf whose output does not depend on `ECX`), register
    +/// `register` (0 to 3: `EAX`, `EBX`, `ECX`, `EDX`) has every bit of `set` and
    +/// no bit of `clear`.
    +#[derive(Clone, Copy, Debug, PartialEq, Eq)]
    +pub struct PolicyRule {
    +    /// The leaf.
    +    pub leaf: u32,
    +    /// The subleaf, or `None` for a leaf that is not indexed.
    +    pub subleaf: Option<u32>,
    +    /// The register: 0 to 3 for `EAX` to `EDX`.
    +    pub register: usize,
    +    /// The bits the rule sets.
    +    pub set: u32,
    +    /// The bits the rule clears.
    +    pub clear: u32,
    +    /// Whether the rule applies to AMD profiles only.
    +    pub amd_only: bool,
    +    /// How the derivation establishes it.
    +    pub action: PolicyAction,
    +    /// What the rule keeps or removes.
    +    pub name: &'static str,
    +}
    +
    +/// The rules of the derivation's policy that fix bits of one register, in
    +/// the order the derivation applies them; the AMD rules apply only to AMD
    +/// profiles.
    +pub const POLICY_RULES: [PolicyRule; 26] = [
    +    // CPUID.1: the hypervisor bit (time ABI); no VMX, SMX, EST, TM2, DTES64,
    +    // MONITOR, DS-CPL, SDBG, xTPR, PDCM (time ABI, no PMU), DCA, or
    +    // TSC-deadline (time ABI); no DS, ACPI, TM, or PBE. The TSC (time ABI).
    +    PolicyRule {
    +        leaf: 0x1,
    +        subleaf: None,
    +        register: 2,
    +        set: 1 << 31,
    +        clear: 1 << 2
    +            | 1 << 3
    +            | 1 << 4
    +            | 1 << 5
    +            | 1 << 6
    +            | 1 << 7
    +            | 1 << 8
    +            | 1 << 11
    +            | 1 << 14
    +            | 1 << 15
    +            | 1 << 18
    +            | 1 << 24,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.1:ECX: the hypervisor bit; no VMX, SMX, EST, TM2, DTES64, MONITOR, DS-CPL, SDBG, xTPR, PDCM, DCA or TSC-deadline",
    +    },
    +    PolicyRule {
    +        leaf: 0x1,
    +        subleaf: None,
    +        register: 3,
    +        set: 0,
    +        clear: 1 << 21 | 1 << 22 | 1 << 29 | 1 << 31,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.1:EDX: no DS, ACPI, TM or PBE",
    +    },
    +    PolicyRule {
    +        leaf: 0x1,
    +        subleaf: None,
    +        register: 3,
    +        set: 1 << 4,
    +        clear: 0,
    +        amd_only: false,
    +        action: PolicyAction::Require,
    +        name: "the TSC",
    +    },
    +    // CPUID.6: ARAT only (time ABI).
    +    PolicyRule {
    +        leaf: 0x6,
    +        subleaf: None,
    +        register: 0,
    +        set: 1 << 2,
    +        clear: !(1 << 2),
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.6: ARAT only",
    +    },
    +    PolicyRule {
    +        leaf: 0x6,
    +        subleaf: None,
    +        register: 1,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.6: ARAT only",
    +    },
    +    PolicyRule {
    +        leaf: 0x6,
    +        subleaf: None,
    +        register: 2,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.6: ARAT only",
    +    },
    +    PolicyRule {
    +        leaf: 0x6,
    +        subleaf: None,
    +        register: 3,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.6: ARAT only",
    +    },
    +    // CPUID.(7,0): no TSC_ADJUST (time ABI), SGX, RDT, or Intel PT; no CET,
    +    // key locker, or SGX launch control; no hybrid, PCONFIG, or arch LBR.
    +    PolicyRule {
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 1,
    +        set: 0,
    +        clear: 1 << 1 | 1 << 2 | 1 << 12 | 1 << 15 | 1 << 25,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.(7,0):EBX: no TSC_ADJUST, SGX, RDT or Intel PT",
    +    },
    +    PolicyRule {
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 2,
    +        set: 0,
    +        clear: 1 << 7 | 1 << 23 | 1 << 30,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.(7,0):ECX: no CET shadow stacks, key locker or SGX launch control",
    +    },
    +    PolicyRule {
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 3,
    +        set: 0,
    +        clear: 1 << 15 | 1 << 18 | 1 << 19 | 1 << 20,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.(7,0):EDX: no hybrid, PCONFIG, arch LBR or CET IBT",
    +    },
    +    // CPUID.0x80000001: RDTSCP (time ABI). No SVM, in every profile: AMD
    +    // profiles cleared it with AMD's other features before, and Intel CPUs
    +    // leave it zero, so the rule changes no profile derived from a real host;
    +    // it makes a profile with SVM, of either vendor, outside the policy
    +    //
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 1,
    +        subleaf: None,
    +        register: 3,
    +        set: 1 << 27,
    +        clear: 0,
    +        amd_only: false,
    +        action: PolicyAction::Require,
    +        name: "RDTSCP",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 1,
    +        subleaf: None,
    +        register: 2,
    +        set: 0,
    +        clear: 1 << 2,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000001:ECX: no SVM",
    +    },
    +    // CPUID.0x80000007: the invariant TSC only (time ABI).
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 7,
    +        subleaf: None,
    +        register: 0,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.0x80000007: the invariant TSC only",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 7,
    +        subleaf: None,
    +        register: 1,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.0x80000007: the invariant TSC only",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 7,
    +        subleaf: None,
    +        register: 2,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.0x80000007: the invariant TSC only",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 7,
    +        subleaf: None,
    +        register: 3,
    +        set: 1 << 8,
    +        clear: !(1 << 8),
    +        amd_only: false,
    +        action: PolicyAction::Fill,
    +        name: "CPUID.0x80000007: the invariant TSC only",
    +    },
    +    // CPUID.0x80000008: the address widths only; no GuestPhysBits, which only
    +    // newer KVM reports, and no AMD core count.
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 8,
    +        subleaf: None,
    +        register: 0,
    +        set: 0,
    +        clear: 0xffff_0000,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000008:EAX: the address widths only",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 8,
    +        subleaf: None,
    +        register: 2,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000008:ECX: nothing",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 8,
    +        subleaf: None,
    +        register: 3,
    +        set: 0,
    +        clear: !0,
    +        amd_only: false,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000008:EDX: nothing",
    +    },
    +    // AMD profiles only from here on.
    +    //
    +    // CPUID.0x80000001 EBX: no brand ID or package type, which describe
    +    // the host's SKU and socket rather than the CPU's features.
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 1,
    +        subleaf: None,
    +        register: 1,
    +        set: 0,
    +        clear: !0,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000001:EBX (AMD): no brand ID or package type",
    +    },
    +    // CPUID.0x80000001 ECX: no SVM (the rule above), IBS, SKINIT, watchdog
    +    // timer, LWP, or node ID MSR; no core, northbridge, or LLC performance
    +    // counter extensions, performance TSC, data breakpoint or address mask
    +    // extensions, or MONITORX. No 3DNowPrefetch either: the Hyper-V root
    +    // of a nested Azure host does not see it, so that host's cold-boot
    +    // support check, which reads the root's CPUID, would fail a profile
    +    // that pins it, although WHP's guests see it; Linux infers PREFETCHW
    +    // from long mode whatever the bit says.
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 1,
    +        subleaf: None,
    +        register: 2,
    +        set: 0,
    +        clear: 1 << 8
    +            | 1 << 10
    +            | 1 << 12
    +            | 1 << 13
    +            | 1 << 15
    +            | 1 << 19
    +            | 1 << 23
    +            | 1 << 24
    +            | 1 << 26
    +            | 1 << 27
    +            | 1 << 28
    +            | 1 << 29
    +            | 1 << 30,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000001:ECX (AMD): no IBS, SKINIT, WDT, LWP, node ID, performance counter extensions, performance TSC, data breakpoint or address mask extensions, MONITORX or 3DNowPrefetch",
    +    },
    +    // CPUID.0x80000008 EBX: no instructions-retired counter, INVLPGB
    +    // (nested pages included), RDPRU, which reads APERF and MPERF, memory
    +    // bandwidth enforcement, PPIN, CPPC, or branch sampling. No BTC_NO
    +    // either: KVM never enumerates it in KVM_GET_SUPPORTED_CPUID, so every
    +    // KVM host would fail a profile that set it, and a guest loses
    +    // nothing without it, because Linux marks no CPU of family 0x19 or
    +    // later as affected by RETBLEED, which is all the bit decides. The
    +    // speculation controls and the other immunities stay.
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 8,
    +        subleaf: None,
    +        register: 1,
    +        set: 0,
    +        clear: 1 << 1
    +            | 1 << 3
    +            | 1 << 4
    +            | 1 << 6
    +            | 1 << 21
    +            | 1 << 23
    +            | 1 << 27
    +            | AMD_BTC_NO
    +            | 1 << 31,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000008:EBX (AMD): no instructions-retired counter, INVLPGB, RDPRU, memory bandwidth enforcement, PPIN, CPPC, branch sampling or BTC_NO",
    +    },
    +    // CPUID.(7,0) EDX: none of Intel's speculation controls or
    +    // IA32_ARCH_CAPABILITIES, which KVM enumerates on AMD hosts beside
    +    // AMD's own controls in 0x80000008 EBX, and emulates. No AMD CPU has
    +    // them: AMD enumerates its controls and immunities in 0x80000008 and
    +    // 0x80000021, which the Hyper-V banks map, and the Milan host's WHP
    +    // presents none of the bits, so a profile derived from KVM alone
    +    // would otherwise fail the Hyper-V hosts of its generation. A guest
    +    // loses nothing: it uses AMD's controls, and Linux takes no AMD CPU
    +    // to be affected by the vulnerabilities whose immunities the MSR
    +    // reports. With the bit clear, the profile pins no
    +    // IA32_ARCH_CAPABILITIES value.
    +    //
    +    // (PSFD's rule follows these: see `policy_violation` and the
    +    // derivation.)
    +    PolicyRule {
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 3,
    +        set: 0,
    +        clear: INTEL_SPECULATION_ENUMERATIONS,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.(7,0):EDX (AMD): none of Intel's speculation enumerations",
    +    },
    +    // CPUID.0x80000021: AutoIBRS, LFENCE serialization, SBPB, SRSO_NO,
    +    // and the TSA immunities stay; no CPUID faulting, which writes HWCR,
    +    // or workload classification; nothing in EBX (the microcode patch and
    +    // return address predictor sizes) or EDX.
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 0x21,
    +        subleaf: None,
    +        register: 0,
    +        set: 0,
    +        clear: 1 << 17 | 1 << 22,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000021:EAX (AMD): no CPUID faulting or workload classification",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 0x21,
    +        subleaf: None,
    +        register: 1,
    +        set: 0,
    +        clear: !0,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000021:EBX (AMD): nothing",
    +    },
    +    PolicyRule {
    +        leaf: EXTENDED_LEAF_BASE + 0x21,
    +        subleaf: None,
    +        register: 3,
    +        set: 0,
    +        clear: !0,
    +        amd_only: true,
    +        action: PolicyAction::Edit,
    +        name: "CPUID.0x80000021:EDX (AMD): nothing",
    +    },
    +];
    +
    +/// A feature that the derivation clears when the profile does not enable its
    +/// XSAVE state: in CPUID `leaf` and `subleaf`, register `register`, the bits
    +/// of `clear` are zero unless XCR0 enables every bit of `state`.
    +#[derive(Clone, Copy, Debug, PartialEq, Eq)]
    +pub struct StatelessFeature {
    +    /// The XSAVE state components the feature needs.
    +    pub state: u64,
    +    /// The leaf.
    +    pub leaf: u32,
    +    /// The subleaf, or `None` for a leaf that is not indexed.
    +    pub subleaf: Option<u32>,
    +    /// The register: 0 to 3 for `EAX` to `EDX`.
    +    pub register: usize,
    +    /// The feature's bits.
    +    pub clear: u32,
    +    /// The feature.
    +    pub name: &'static str,
    +}
    +
    +/// AVX's XSAVE state: the upper halves of the YMM registers.
    +pub const XSTATE_AVX: u64 = 1 << 2;
    +/// MPX's XSAVE state: the bound registers and their configuration.
    +pub const XSTATE_MPX: u64 = 3 << 3;
    +/// AVX-512's XSAVE state: the opmask registers and the upper ZMM registers.
    +pub const XSTATE_AVX512: u64 = 7 << 5;
    +/// PKU's XSAVE state: PKRU.
    +pub const XSTATE_PKRU: u64 = 1 << 9;
    +
    +/// The features the derivation clears when their XSAVE state is not enabled.
    +pub const STATELESS_FEATURES: [StatelessFeature; 10] = [
    +    StatelessFeature {
    +        state: XSTATE_AVX,
    +        leaf: 0x1,
    +        subleaf: None,
    +        register: 2,
    +        clear: 1 << 28 | 1 << 12 | 1 << 29,
    +        name: "AVX, FMA and F16C",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 1,
    +        clear: 1 << 5,
    +        name: "AVX2",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 2,
    +        clear: 1 << 9 | 1 << 10,
    +        name: "VAES and VPCLMULQDQ",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_MPX,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 1,
    +        clear: 1 << 14,
    +        name: "MPX",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX512,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 1,
    +        clear: 1 << 16 | 1 << 17 | 1 << 21 | 1 << 26 | 1 << 27 | 1 << 28 | 1 << 30 | 1 << 31,
    +        name: "AVX512F, DQ, IFMA, PF, ER, CD, BW and VL",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX512,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 2,
    +        clear: 1 << 1 | 1 << 6 | 1 << 11 | 1 << 12 | 1 << 14,
    +        name: "VBMI, VBMI2, VNNI, BITALG and VPOPCNTDQ",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX512,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 3,
    +        clear: 1 << 2 | 1 << 3 | 1 << 8 | 1 << 23,
    +        name: "4VNNIW, 4FMAPS, VP2INTERSECT and FP16",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_PKRU,
    +        leaf: 0x7,
    +        subleaf: Some(0),
    +        register: 2,
    +        clear: 1 << 3,
    +        name: "PKU",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX,
    +        leaf: 0x7,
    +        subleaf: Some(1),
    +        register: 0,
    +        clear: 1 << 4,
    +        name: "AVX-VNNI",
    +    },
    +    StatelessFeature {
    +        state: XSTATE_AVX512,
    +        leaf: 0x7,
    +        subleaf: Some(1),
    +        register: 0,
    +        clear: 1 << 5,
    +        name: "AVX512-BF16",
    +    },
    +];
    +
    +/// The part of the policy that a profile's CPUID breaks.
    +#[derive(Clone, Copy, Debug, PartialEq, Eq)]
    +pub enum PolicyViolation {
    +    /// The rule of [`POLICY_RULES`] at this index; `value` is the register's.
    +    Rule {
    +        /// The rule's index.
    +        index: usize,
    +        /// The register's value.
    +        value: u32,
    +    },
    +    /// The feature of [`STATELESS_FEATURES`] at this index, set although
    +    /// XCR0 does not enable its state; `value` is the register's.
    +    Stateless {
    +        /// The feature's index.
    +        index: usize,
    +        /// The register's value.
    +        value: u32,
    +    },
    +    /// XSAVE state or extensions beyond [`ALLOWED_XCR0`], [`ALLOWED_XSS`] or
    +    /// [`ALLOWED_XSAVE_EXTENSIONS`].
    +    Xsave,
    +    /// PSFD in an AMD profile without a `SPEC_CTRL` control.
    +    Psfd,
    +    /// The entry at this index of the profile's CPUID, of a leaf outside
    +    /// [`DATA_LEAVES`] (and, in an AMD profile, [`AMD_DATA_LEAVES`]), is not
    +    /// zero.
    +    DataLeaf {
    +        /// The entry's index.
    +        index: usize,
    +    },
    +}
    +
    +/// Returns register `register` of the CPUID that `entries` give for `leaf`
    +/// and `subleaf`: the first entry for `leaf` that is subleaf-independent or
    +/// for `subleaf`, as [`CpuProfile::lookup`](crate::CpuProfile::lookup)
    +/// finds it, or 0.
    +fn lookup_register(entries: &[CpuidLeafValue], leaf: u32, subleaf: u32, register: usize) -> u32 {
    +    let mut i = 0;
    +    while i < entries.len() {
    +        let entry = &entries[i];
    +        let answers = entry.leaf.0 == leaf
    +            && match entry.subleaf {
    +                None => true,
    +                Some(entry_subleaf) => entry_subleaf.0 == subleaf,
    +            };
    +        if answers {
    +            return if register < 4 {
    +                entry.value[register].0
    +            } else {
    +                0
    +            };
    +        }
    +        i += 1;
    +    }
    +    0
    +}
    +
    +/// Returns the subleaf a rule's `subleaf` reads: its own, or 0.
    +fn subleaf_of(subleaf: Option<u32>) -> u32 {
    +    match subleaf {
    +        Some(subleaf) => subleaf,
    +        None => 0,
    +    }
    +}
    +
    +/// Returns the first part of the derivation's policy that `entries`, the
    +/// CPUID table of a profile whose CPUs are AMD's when `amd` and Intel's
    +/// otherwise, breaks, or `None` if it follows the whole policy.
    +///
    +/// [`CpuProfile::effective_cpuid`](crate::CpuProfile::effective_cpuid)
    +/// refuses a profile that breaks it, whatever its source.
    +pub fn policy_violation(amd: bool, entries: &[CpuidLeafValue]) -> Option<PolicyViolation> {
    +    let mut index = 0;
    +    while index < POLICY_RULES.len() {
    +        let rule = POLICY_RULES[index];
    +        if !rule.amd_only || amd {
    +            let value =
    +                lookup_register(entries, rule.leaf, subleaf_of(rule.subleaf), rule.register);
    +            if value & (rule.set | rule.clear) != rule.set {
    +                return Some(PolicyViolation::Rule { index, value });
    +            }
    +        }
    +        index += 1;
    +    }
    +    let xcr0 = lookup_register(entries, 0xd, 0, 0) as u64
    +        | (lookup_register(entries, 0xd, 0, 3) as u64) << 32;
    +    let xss = lookup_register(entries, 0xd, 1, 2) as u64
    +        | (lookup_register(entries, 0xd, 1, 3) as u64) << 32;
    +    if xcr0 & !ALLOWED_XCR0 != 0
    +        || xss & !ALLOWED_XSS != 0
    +        || lookup_register(entries, 0xd, 1, 0) & !ALLOWED_XSAVE_EXTENSIONS != 0
    +    {
    +        return Some(PolicyViolation::Xsave);
    +    }
    +    let mut index = 0;
    +    while index < STATELESS_FEATURES.len() {
    +        let feature = STATELESS_FEATURES[index];
    +        if xcr0 & feature.state != feature.state {
    +            let value = lookup_register(
    +                entries,
    +                feature.leaf,
    +                subleaf_of(feature.subleaf),
    +                feature.register,
    +            );
    +            if value & feature.clear != 0 {
    +                return Some(PolicyViolation::Stateless { index, value });
    +            }
    +        }
    +        index += 1;
    +    }
    +    if amd {
    +        let ext8_ebx = lookup_register(entries, EXTENDED_LEAF_BASE + 8, 0, 1);
    +        if !has_spec_ctrl_control(lookup_register(entries, 0x7, 0, 3), ext8_ebx)
    +            && ext8_ebx & AMD_PSFD != 0
    +        {
    +            return Some(PolicyViolation::Psfd);
    +        }
    +    }
    +    let mut index = 0;
    +    while index < entries.len() {
    +        let entry = &entries[index];
    +        if !is_data_leaf(amd, entry.leaf.0)
    +            && (entry.value[0].0 | entry.value[1].0 | entry.value[2].0 | entry.value[3].0) != 0
    +        {
    +            return Some(PolicyViolation::DataLeaf { index });
    +        }
    +        index += 1;
    +    }
    +    None
    +}
    +
    +/// Returns whether `leaf` keeps data in a profile whose CPUs are AMD's when
    +/// `amd`: it is in [`DATA_LEAVES`], or `amd` and it is in
    +/// [`AMD_DATA_LEAVES`].
    +pub fn is_data_leaf(amd: bool, leaf: u32) -> bool {
    +    contains_leaf(&DATA_LEAVES, leaf) || (amd && contains_leaf(&AMD_DATA_LEAVES, leaf))
    +}
    +
    +/// Returns whether `leaves` holds `leaf`.
    +fn contains_leaf(leaves: &[u32], leaf: u32) -> bool {
    +    let mut index = 0;
    +    while index < leaves.len() {
    +        if leaves[index] == leaf {
    +            return true;
    +        }
    +        index += 1;
    +    }
    +    false
    +}
    +
    +/// Describes `violation`, a violation of the policy by the CPUID table
    +/// `entries`, for an error message.
    +pub fn describe_violation(violation: PolicyViolation, entries: &[CpuidLeafValue]) -> String {
    +    let register = |register: usize| ["EAX", "EBX", "ECX", "EDX"].get(register).copied();
    +    match violation {
    +        PolicyViolation::Rule { index, value } => {
    +            let rule = &POLICY_RULES[index];
    +            format!(
    +                "{} ({}:{} is {value:#010x}; the policy sets {:#010x} and clears {:#010x})",
    +                rule.name,
    +                describe_leaf(rule.leaf, rule.subleaf),
    +                register(rule.register).unwrap_or("?"),
    +                rule.set,
    +                rule.clear
    +            )
    +        }
    +        PolicyViolation::Stateless { index, value } => {
    +            let feature = &STATELESS_FEATURES[index];
    +            format!(
    +                "{} without its XSAVE state ({:#x}): {}:{} is {value:#010x}",
    +                feature.name,
    +                feature.state,
    +                describe_leaf(feature.leaf, feature.subleaf),
    +                register(feature.register).unwrap_or("?")
    +            )
    +        }
    +        PolicyViolation::Xsave => format!(
    +            "XSAVE state or extensions beyond XCR0 {ALLOWED_XCR0:#x}, IA32_XSS {ALLOWED_XSS:#x} and \
    +             CPUID.(0xd,1):EAX {ALLOWED_XSAVE_EXTENSIONS:#x}"
    +        ),
    +        PolicyViolation::Psfd => {
    +            "CPUID.0x80000008:EBX has PSFD without a SPEC_CTRL control".to_owned()
    +        }
    +        PolicyViolation::DataLeaf { index } => match entries.get(index) {
    +            Some(entry) => format!(
    +                "{} keeps no data in a profile, but is not zero",
    +                describe_leaf(entry.leaf.0, entry.subleaf.map(|subleaf| subleaf.0))
    +            ),
    +            None => "a leaf that keeps no data is not zero".to_owned(),
    +        },
    +    }
    +}
    +
    +#[cfg(test)]
    +mod tests {
    +    use super::*;
    +    use crate::CpuProfile;
    +    use crate::canonical;
    +    use crate::error::ProfileErrorCode;
    +    use crate::test_support::fingerprint;
    +    use crate::test_support::genoa_kvm_entries;
    +    use crate::test_support::host_fingerprint;
    +    use crate::test_support::milan_whp_entries;
    +    use crate::test_support::turin_kvm_entries;
    +    use crate::vendor::CpuVendor;
    +    use serde_json::Value;
    +    use serde_json::json;
    +    use test_with_tracing::test;
    +
    +    const INTEL: &str = "intel.emeraldrapids.v1";
    +    const AMD: &str = "amd.genoa.v1";
    +
    +    fn is_amd(profile: &CpuProfile) -> bool {
    +        profile.cpu_vendor() == CpuVendor::Amd
    +    }
    +
    +    /// The host profiles of the recorded hosts: one derived from each pinned
    +    /// profile's CPUID as a KVM host's, and the AMD hosts' own recordings.
    +    fn recorded_host_profiles() -> Vec<CpuProfile> {
    +        let mut profiles = crate::pinned_profiles()
    +            .iter()
    +            .map(|pinned| crate::derive_host_profile(&fingerprint(pinned, "kvm")).unwrap())
    +            .collect::<Vec<_>>();
    +        for (backend, entries) in [
    +            ("whp", milan_whp_entries()),
    +            ("kvm", genoa_kvm_entries()),
    +            ("kvm", turin_kvm_entries()),
    +        ] {
    +            profiles.push(crate::derive_host_profile(&host_fingerprint(backend, entries)).unwrap());
    +        }
    +        profiles
    +    }
    +
    +    /// Returns `profile` with register `register` of CPUID `leaf`, `subleaf`
    +    /// changed by `edit`, decoded as a restore decodes a snapshot's host
    +    /// profile (`host_profile_for_restore`, with the document's own digest).
    +    fn edited(
    +        profile: &CpuProfile,
    +        leaf: u32,
    +        subleaf: Option<u32>,
    +        register: usize,
    +        edit: impl FnOnce(u32) -> u32,
    +    ) -> Result<CpuProfile, crate::ProfileError> {
    +        let mut value: Value = serde_json::from_slice(&profile.encode()).unwrap();
    +        let entry = value["cpuid"]
    +            .as_array_mut()
    +            .unwrap()
    +            .iter_mut()
    +            .find(|entry| {
    +                entry["leaf"] == json!(format!("{leaf:#010x}"))
    +                    && entry["subleaf"]
    +                        == subleaf.map_or(Value::Null, |s| json!(format!("{s:#010x}")))
    +            })
    +            .unwrap();
    +        let old = entry["value"][register].as_str().unwrap();
    +        let old = u32::from_str_radix(old.trim_start_matches("0x"), 16).unwrap();
    +        entry["value"][register] = json!(format!("{:#010x}", edit(old)));
    +        let document = canonical::to_compact(&value);
    +        crate::host_profile_for_restore(
    +            profile.id(),
    +            &canonical::sha256(document.as_bytes()),
    +            document.as_bytes(),
    +        )
    +    }
    +
    +    /// Asserts that a restore of `profile` is refused with `E_PROFILE_DIGEST`:
    +    /// at its decode (which checks the CPU time bits), or else when building an
    +    /// effective CPUID from it, for the policy, naming `what`.
    +    fn assert_refused(profile: Result<CpuProfile, crate::ProfileError>, what: &str) {
    +        let profile = match profile {
    +            Ok(profile) => profile,
    +            Err(error) => {
    +                assert_eq!(
    +                    error.code,
    +                    ProfileErrorCode::ProfileDigest,
    +                    "{what}: {error}"
    +                );
    +                return;
    +            }
    +        };
    +        let error = profile.effective_cpuid(&[], &[]).unwrap_err();
    +        assert_eq!(
    +            error.code,
    +            ProfileErrorCode::ProfileDigest,
    +            "{what}: {error}"
    +        );
    +        assert!(
    +            error
    +                .message
    +                .contains("outside the derivation's CPUID policy"),
    +            "{what}: {error}"
    +        );
    +    }
    +
    +    /// Every pinned profile follows the policy, so the check refuses no cold
    +    /// boot with one (and catalog profiles, which a restore takes from this
    +    /// OpenVMM by ID, follow it too).
    +    #[test]
    +    fn every_pinned_profile_follows_the_policy() {
    +        for profile in crate::pinned_profiles() {
    +            assert_eq!(
    +                policy_violation(is_amd(profile), profile.cpuid()),
    +                None,
    +                "{}",
    +                profile.id()
    +            );
    +        }
    +    }
    +
    +    /// Every host profile derived from a recorded host, Intel and AMD, KVM
    +    /// and WHP, follows the policy, so the check refuses no cold boot with
    +    /// `--cpu-profile host` on such a host.
    +    #[test]
    +    fn host_profiles_of_the_recorded_hosts_follow_the_policy() {
    +        for profile in recorded_host_profiles() {
    +            assert_eq!(
    +                policy_violation(is_amd(&profile), profile.cpuid()),
    +                None,
    +                "{}",
    +                profile.description()
    +            );
    +        }
    +    }
    +
    +    /// Every bit of every rule: a profile with one bit of an applicable rule
    +    /// flipped, where the profile pins it, breaks that rule and no earlier
    +    /// one; on an Intel and an AMD host profile.
    +    #[test]
    +    fn flipping_any_rule_bit_breaks_that_rule() {
    +        for id in [INTEL, AMD] {
    +            let profile =
    +                crate::derive_host_profile(&fingerprint(crate::pinned(id).unwrap(), "kvm"))
    +                    .unwrap();
    +            let amd = is_amd(&profile);
    +            let mut flipped = 0;
    +            for (index, rule) in POLICY_RULES.iter().enumerate() {
    +                if rule.amd_only && !amd {
    +                    continue;
    +                }
    +                let subleaf = rule.subleaf.unwrap_or(0);
    +                let position = profile
    +                    .cpuid()
    +                    .iter()
    +                    .position(|entry| {
    +                        entry.leaf.0 == rule.leaf
    +                            && entry
    +                                .subleaf
    +                                .is_none_or(|entry_subleaf| entry_subleaf.0 == subleaf)
    +                    })
    +                    .unwrap_or_else(|| panic!("{id}: {} is listed", rule.name));
    +                for bit in (0..32).map(|bit| 1u32 << bit) {
    +                    let pinned = profile.cpuid()[position].masks()[rule.register] & bit != 0;
    +                    if (rule.set | rule.clear) & bit == 0 || !pinned {
    +                        continue;
    +                    }
    +                    let mut entries = profile.cpuid().to_vec();
    +                    entries[position].value[rule.register].0 ^= bit;
    +                    assert!(
    +                        matches!(
    +                            policy_violation(amd, &entries),
    +                            Some(PolicyViolation::Rule { index: broken, .. }) if broken == index
    +                        ),
    +                        "{id}: rule {index} ({}), bit {bit:#x}: {:?}",
    +                        rule.name,
    +                        policy_violation(amd, &entries)
    +                    );
    +                    flipped += 1;
    +                }
    +            }
    +            assert!(flipped > 100, "{id}: {flipped} bits");
    +        }
    +    }
    +
    +    /// VMX and SVM bits through the restore's decode and the effective CPUID's
    +    /// build: VMX on Intel, SVM on AMD (and on Intel), and each of the time
    +    /// ABI's bits, on host profiles derived from an Intel and an AMD host.
    +    #[test]
    +    fn a_restored_host_profile_outside_the_policy_is_refused() {
    +        let intel =
    +            crate::derive_host_profile(&fingerprint(crate::pinned(INTEL).unwrap(), "kvm")).unwrap();
    +        let amd =
    +            crate::derive_host_profile(&fingerprint(crate::pinned(AMD).unwrap(), "kvm")).unwrap();
    +        type Edit = (&'static str, u32, Option<u32>, usize, fn(u32) -> u32);
    +        let edits: [Edit; 14] = [
    +            ("VMX", 0x1, None, 2, |v| v | 1 << 5),
    +            ("SVM", 0x8000_0001, None, 2, |v| v | 1 << 2),
    +            ("TSC-deadline", 0x1, None, 2, |v| v | 1 << 24),
    +            ("PDCM", 0x1, None, 2, |v| v | 1 << 15),
    +            ("EST", 0x1, None, 2, |v| v | 1 << 7),
    +            ("TM2", 0x1, None, 2, |v| v | 1 << 8),
    +            ("no hypervisor bit", 0x1, None, 2, |v| v & !(1 << 31)),
    +            ("no TSC", 0x1, None, 3, |v| v & !(1 << 4)),
    +            ("no ARAT", 0x6, None, 0, |v| v & !(1 << 2)),
    +            ("more than ARAT", 0x6, None, 0, |v| v | 1),
    +            ("TSC_ADJUST", 0x7, Some(0), 1, |v| v | 1 << 1),
    +            ("no RDTSCP", 0x8000_0001, None, 3, |v| v & !(1 << 27)),
    +            ("no invariant TSC", 0x8000_0007, None, 3, |v| v & !(1 << 8)),
    +            ("more than the invariant TSC", 0x8000_0007, None, 3, |v| {
    +                v | 1
    +            }),
    +        ];
    +        for profile in [&intel, &amd] {
    +            assert_eq!(policy_violation(is_amd(profile), profile.cpuid()), None);
    +            for (what, leaf, subleaf, register, edit) in edits {
    +                assert_refused(edited(profile, leaf, subleaf, register, edit), what);
    +            }
    +            // The time ABI's zero leaves: PMU, the TSC and crystal clock, and
    +            // the processor frequency, where the profile lists them.
    +            for leaf in [0xa, 0x15, 0x16] {
    +                if profile.lookup(0, 0)[0] >= leaf {
    +                    assert_refused(edited(profile, leaf, None, 0, |v| v | 1), "a zero leaf");
    +                }
    +            }
    +        }
    +    }
    +
    +    /// The other parts of the policy: a feature without its XSAVE state, XSAVE
    +    /// state beyond the allowed XCR0, PSFD without a SPEC_CTRL control, and a
    +    /// data in a leaf that keeps none.
    +    #[test]
    +    fn the_policys_other_parts_are_checked() {
    +        let amd =
    +            crate::derive_host_profile(&fingerprint(crate::pinned(AMD).unwrap(), "kvm")).unwrap();
    +        let mut entries = amd.cpuid().to_vec();
    +        let position = |entries: &[CpuidLeafValue], leaf: u32, subleaf: Option<u32>| {
    +            entries
    +                .iter()
    +                .position(|entry| entry.key() == (leaf, subleaf))
    +                .unwrap()
    +        };
    +        // XCR0 without AVX, with AVX2 still set: the AVX2 feature.
    +        let xsave = position(&entries, 0xd, Some(0));
    +        let leaf7 = position(&entries, 0x7, Some(0));
    +        let mut no_avx = entries.clone();
    +        no_avx[xsave].value[0].0 &= !(1 << 2);
    +        no_avx[leaf7].value[1].0 |= 1 << 5;
    +        assert!(matches!(
    +            policy_violation(true, &no_avx),
    +            Some(PolicyViolation::Stateless { .. })
    +        ));
    +        // XCR0 with AMX's XTILE_CFG, beyond ALLOWED_XCR0.
    +        let mut amx = entries.clone();
    +        amx[xsave].value[0].0 |= 1 << 17;
    +        assert_eq!(policy_violation(true, &amx), Some(PolicyViolation::Xsave));
    +        // PSFD with no SPEC_CTRL control: IBRS, STIBP and SSBD cleared.
    +        let ext8 = position(&entries, 0x8000_0008, None);
    +        let mut psfd = entries.clone();
    +        psfd[ext8].value[1].0 &= !(1 << 14 | 1 << 15 | 1 << 24);
    +        psfd[leaf7].value[3].0 &= !(1 << 26);
    +        psfd[ext8].value[1].0 |= AMD_PSFD;
    +        assert_eq!(policy_violation(true, &psfd), Some(PolicyViolation::Psfd));
    +        // A leaf that keeps no data (Intel PT, 0x14) with data.
    +        let index = entries
    +            .iter()
    +            .position(|entry| !is_data_leaf(true, entry.leaf.0))
    +            .unwrap();
    +        entries[index].value[1].0 |= 1;
    +        assert_eq!(
    +            policy_violation(true, &entries),
    +            Some(PolicyViolation::DataLeaf { index })
    +        );
    +    }
    +
    +    /// The support check's skipped time bits are bits the policy sets.
    +    #[test]
    +    fn the_support_checks_time_bits_are_set_by_the_policy() {
    +        for (leaf, subleaf, register, bit) in crate::TIME_POLICY_BITS {
    +            assert!(
    +                POLICY_RULES.iter().any(|rule| {
    +                    rule.leaf == leaf
    +                        && rule.subleaf.unwrap_or(0) == subleaf
    +                        && rule.register == register
    +                        && rule.set & bit == bit
    +                }),
    +                "{leaf:#x}.{subleaf} {register} {bit:#x}"
    +            );
    +        }
    +    }
    +}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions