Skip to main content

product_policy/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Measured product policy: enum, per-VM value, codec.
5//!
6//! To add a product: define its body in a sibling module, with the
7//! `vpci_relay` field that the device policy sets, then add one
8//! `N => Variant(body::Body),` line to
9//! `define_product_policy!` below. `N` is a mesh wire tag and must never be
10//! reused.
11
12#![forbid(unsafe_code)]
13
14extern crate alloc;
15
16/// Azure policy body.
17pub mod azure;
18/// Cwcow policy body and validation methods.
19pub mod cwcow;
20/// Shared helpers for product policy validation and serialization.
21pub mod product_policy_helpers;
22/// Sivm policy body and validation methods.
23pub mod sivm;
24/// UEFI enforced security settings.
25pub mod uefi_security_policy;
26
27use alloc::vec::Vec;
28
29#[doc(hidden)]
30pub use paste::paste as __paste;
31
32/// Absolute path of the measured product policy file in the OpenHCL initrd.
33pub const PRODUCT_POLICY_PATH: &str = "/openhcl-product-policy";
34
35/// Per-VM measured product policy.
36///
37/// `None` means no policy was installed; any `Some(_)` carries the
38/// decoded variant body.
39#[derive(Debug, Clone, PartialEq, Default)]
40#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
41#[cfg_attr(feature = "inspect", inspect(transparent))]
42pub struct MeasuredProductPolicy(Option<ProductPolicy>);
43
44impl MeasuredProductPolicy {
45    /// Wrap the decoded policy (or its absence).
46    pub fn new(policy: Option<ProductPolicy>) -> Self {
47        Self(policy)
48    }
49
50    /// The decoded policy, if any.
51    pub fn raw(&self) -> Option<&ProductPolicy> {
52        self.0.as_ref()
53    }
54}
55
56#[derive(mesh_protobuf::Protobuf)]
57struct ProductPolicyInternal {
58    #[mesh(1)]
59    magic: u64,
60    #[mesh(2)]
61    policy: ProductPolicy,
62}
63
64impl ProductPolicyInternal {
65    /// Magic header for an encoded product policy payload ("OHCLPOL").
66    const MAGIC: u64 = 0x4F48434C504F4C00;
67}
68
69/// A PCI device that OpenHCL's VPCI relay may expose to VTL0: one with every
70/// ID that is set.
71#[derive(mesh_protobuf::Protobuf, Debug, Clone, PartialEq, Default)]
72#[cfg_attr(
73    feature = "manifest",
74    derive(serde::Deserialize),
75    serde(deny_unknown_fields)
76)]
77#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
78#[mesh(package = "openhcl.product_policy")]
79pub struct AllowedPciDevice {
80    /// Vendor ID.
81    #[mesh(1)]
82    #[cfg_attr(feature = "inspect", inspect(hex))]
83    pub vendor_id: Option<u16>,
84    /// Device ID.
85    #[mesh(2)]
86    #[cfg_attr(feature = "inspect", inspect(hex))]
87    pub device_id: Option<u16>,
88    /// Revision ID.
89    #[mesh(3)]
90    #[cfg_attr(feature = "inspect", inspect(hex))]
91    pub revision_id: Option<u8>,
92    /// Base class code.
93    #[mesh(4)]
94    #[cfg_attr(feature = "inspect", inspect(hex))]
95    pub base_class: Option<u8>,
96    /// Subclass code.
97    #[mesh(5)]
98    #[cfg_attr(feature = "inspect", inspect(hex))]
99    pub sub_class: Option<u8>,
100    /// Programming interface.
101    #[mesh(6)]
102    #[cfg_attr(feature = "inspect", inspect(hex))]
103    pub prog_if: Option<u8>,
104}
105
106/// When OpenHCL runs the VPCI relay. `OPENHCL_ENABLE_VPCI_RELAY` can override
107/// the defaults, but not [`Self::MustBeOn`].
108#[derive(mesh_protobuf::Protobuf, Debug, Clone, Copy, PartialEq, Eq, Default)]
109#[cfg_attr(
110    feature = "manifest",
111    derive(serde::Deserialize),
112    serde(rename_all = "snake_case")
113)]
114#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
115#[mesh(package = "openhcl.product_policy")]
116pub enum VpciRelayMode {
117    /// Off unless `OPENHCL_ENABLE_VPCI_RELAY=1`.
118    #[default]
119    #[mesh(1)]
120    DefaultOff,
121    /// On unless `OPENHCL_ENABLE_VPCI_RELAY=0`.
122    #[mesh(2)]
123    DefaultOn,
124    /// Always on. OpenHCL fails to boot if it can't run the relay.
125    #[mesh(3)]
126    MustBeOn,
127}
128
129/// The VPCI relay settings from the manifest's device policy file.
130#[derive(mesh_protobuf::Protobuf, Debug, Clone, PartialEq, Default)]
131#[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
132#[mesh(package = "openhcl.product_policy")]
133pub struct VpciRelayPolicy {
134    /// The PCI devices that the VPCI relay may expose to VTL0.
135    #[mesh(1)]
136    #[cfg_attr(feature = "inspect", inspect(iter_by_index))]
137    pub allowed_pci_devices: Vec<AllowedPciDevice>,
138    /// When OpenHCL runs the VPCI relay.
139    #[mesh(2)]
140    pub mode: VpciRelayMode,
141}
142
143/// Defines the `ProductPolicy` enum and, for each variant `Foo(Body)`,
144/// a `MeasuredProductPolicy::foo(|body| ...) -> anyhow::Result<Option<T>>`
145/// accessor (`Ok(None)` when the policy is absent or a different
146/// variant; closure errors propagate).
147macro_rules! define_product_policy {
148    (
149        package = $pkg:literal ;
150        $(
151            $(#[$vmeta:meta])*
152            $tag:literal => $variant:ident ( $body:path )
153        );+ $(;)?
154    ) => {
155        /// Measured product policy. Mesh tags are part of the wire
156        /// format and must never be reused.
157        #[derive(mesh_protobuf::Protobuf, Debug, Clone, PartialEq)]
158        #[cfg_attr(feature = "manifest", derive(serde::Serialize, serde::Deserialize))]
159        #[cfg_attr(
160            feature = "manifest",
161            serde(rename_all = "snake_case", deny_unknown_fields)
162        )]
163        #[cfg_attr(feature = "inspect", derive(inspect::Inspect))]
164        #[cfg_attr(feature = "inspect", inspect(external_tag))]
165        #[mesh(package = $pkg)]
166        pub enum ProductPolicy {
167            $(
168                $(#[$vmeta])*
169                #[mesh($tag)]
170                $variant($body),
171            )+
172        }
173
174        impl ProductPolicy {
175            /// Lowercased variant name.
176            pub fn name(&self) -> &'static str {
177                $crate::__paste! {
178                    match self {
179                        $( Self::$variant(_) => stringify!([<$variant:lower>]), )+
180                    }
181                }
182            }
183
184            /// Sets the VPCI relay settings from the manifest's device policy
185            /// file.
186            pub fn set_vpci_relay(&mut self, vpci_relay: $crate::VpciRelayPolicy) {
187                match self {
188                    $( Self::$variant(p) => p.vpci_relay = Some(vpci_relay), )+
189                }
190            }
191        }
192
193        impl $crate::MeasuredProductPolicy {
194            fn vpci_relay_policy(&self) -> Option<&$crate::VpciRelayPolicy> {
195                match self.raw()? {
196                    $( ProductPolicy::$variant(p) => p.vpci_relay.as_ref(), )+
197                }
198            }
199
200            /// The PCI devices that OpenHCL's VPCI relay may expose to VTL0.
201            pub fn allowed_pci_devices(&self) -> &[$crate::AllowedPciDevice] {
202                self.vpci_relay_policy()
203                    .map_or(&[], |r| &r.allowed_pci_devices)
204            }
205
206            /// When OpenHCL runs the VPCI relay.
207            pub fn vpci_relay(&self) -> $crate::VpciRelayMode {
208                self.vpci_relay_policy()
209                    .map(|r| r.mode)
210                    .unwrap_or_default()
211            }
212        }
213
214        $crate::__paste! {
215            $(
216                impl $crate::MeasuredProductPolicy {
217                    #[doc = concat!(
218                        "Run `f` over the `",
219                        stringify!($variant),
220                        "` body if installed. Closure errors propagate via the outer `Result`; the inner `Option` signals whether the closure ran."
221                    )]
222                    pub fn [<$variant:lower>]<T>(
223                        &self,
224                        f: impl ::core::ops::FnOnce(&$body) -> ::anyhow::Result<T>,
225                    ) -> ::anyhow::Result<::core::option::Option<T>> {
226                        match self.raw() {
227                            ::core::option::Option::Some(ProductPolicy::$variant(p)) => {
228                                f(p).map(::core::option::Option::Some)
229                            }
230                            _ => ::core::result::Result::Ok(::core::option::Option::None),
231                        }
232                    }
233                }
234            )+
235        }
236    };
237}
238
239define_product_policy! {
240    package = "openhcl.product_policy";
241
242    /// Sivm.
243    1 => Sivm(sivm::SivmPolicy);
244
245    /// Cwcow.
246    2 => Cwcow(cwcow::CwcowPolicy);
247
248    /// Azure.
249    3 => Azure(azure::AzurePolicy);
250}
251
252// --- Codec ---
253
254/// Errors from [`decode_product_policy`].
255#[derive(Debug)]
256pub enum ProductPolicyDecodeError {
257    /// `mesh_protobuf` rejected the bytes.
258    Mesh(mesh_protobuf::Error),
259    /// The decoded payload did not carry the expected magic header.
260    BadMagic,
261}
262
263impl core::fmt::Display for ProductPolicyDecodeError {
264    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
265        match self {
266            Self::Mesh(_) => write!(f, "product policy mesh decode error"),
267            Self::BadMagic => write!(f, "product policy magic header mismatch"),
268        }
269    }
270}
271
272impl core::error::Error for ProductPolicyDecodeError {
273    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
274        match self {
275            Self::Mesh(e) => Some(e),
276            Self::BadMagic => None,
277        }
278    }
279}
280
281/// Encode a policy as `mesh_protobuf` bytes for the IGVM payload.
282pub fn encode_product_policy(policy: &ProductPolicy) -> Vec<u8> {
283    let policy = ProductPolicyInternal {
284        magic: ProductPolicyInternal::MAGIC,
285        policy: policy.clone(),
286    };
287    mesh_protobuf::encode(policy)
288}
289
290/// Decode `mesh_protobuf` bytes. Caller must skip empty payloads
291/// (which signal "no policy installed") before calling.
292pub fn decode_product_policy(bytes: &[u8]) -> Result<ProductPolicy, ProductPolicyDecodeError> {
293    let data: ProductPolicyInternal =
294        mesh_protobuf::decode(bytes).map_err(ProductPolicyDecodeError::Mesh)?;
295
296    if data.magic != ProductPolicyInternal::MAGIC {
297        return Err(ProductPolicyDecodeError::BadMagic);
298    }
299
300    Ok(data.policy)
301}
302
303pub use uefi_security_policy::UefiSecurityPolicy;
304
305#[cfg(test)]
306mod tests;