Skip to main content

sim_platform_ubuntu_pc/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
6#![forbid(unsafe_code)]
7//! Ubuntu PC capsule registration and sanitized evidence contracts.
8use serde::{Deserialize, Serialize};
9use sim_platform_core::{
10    ContractProvenance, EvidenceLevel, FactPort, OpenSymbol, PlatformCard, ServiceOffer,
11    stable_digest,
12};
13pub use sim_platform_core::{
14    UbuntuArchitecture as Architecture, UbuntuProfile as UbuntuPcProfile,
15    UbuntuProfileKind as ProfileKind,
16};
17use std::{ffi::OsString, path::PathBuf};
18
19pub use sim_platform_linux as linux;
20mod compute;
21mod loader;
22mod local_check;
23pub use compute::UbuntuComputeProbe;
24pub use loader::UbuntuLoaderPort;
25pub use local_check::{LocalCheckAdapter, LocalCheckError, request_check};
26mod process;
27mod sandbox;
28pub use process::UbuntuProcess;
29pub use sandbox::{BwrapConfinementStatus, BwrapLauncher, ReadOnlyTreeLimits};
30
31/// Owned process-entry facts captured by the Ubuntu capsule.
32///
33/// Portable bootloaders consume this value and never inspect argv, the current
34/// directory, or environment variables themselves.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct UbuntuProcessEnvelope {
37    /// Complete process argument vector.
38    pub argv: Vec<OsString>,
39    /// Explicit working root supplied to configuration and cache policy.
40    pub work_root: PathBuf,
41    /// Explicit cache root override, when supplied by the host.
42    pub cache_root: Option<PathBuf>,
43    /// Explicit registry artifact endpoint, when supplied by the host.
44    pub registry_endpoint: Option<String>,
45    /// Whether the host admits unauthenticated non-loopback registry access.
46    pub allow_insecure_registry: bool,
47}
48
49impl UbuntuProcessEnvelope {
50    /// Captures the bounded process facts owned by this concrete capsule.
51    ///
52    /// # Errors
53    /// Returns an error when the host does not expose a current working root.
54    pub fn capture() -> std::io::Result<Self> {
55        Ok(Self {
56            argv: std::env::args_os().collect(),
57            work_root: std::env::current_dir()?,
58            cache_root: std::env::var_os("SIM_CLI_CACHE_DIR").map(PathBuf::from),
59            registry_endpoint: std::env::var_os("SIM_GIT_REGISTRY_ENDPOINT")
60                .map(|value| value.to_string_lossy().into_owned()),
61            allow_insecure_registry: std::env::var_os("SIM_GIT_REGISTRY_ALLOW_INSECURE")
62                .is_some_and(|value| !value.is_empty()),
63        })
64    }
65}
66pub const BUNDLE_DESCRIPTOR: &str = "sim.platform-bundle.toml";
67/// Ubuntu PC distribution bundle. The one row admits only this capsule.
68pub const UBUNTU_BUNDLE_MANIFEST: &str = r#"
69schema = "sim.platform-bundle/v1"
70capsule = "platform/site/ubuntu-pc"
71artifact = "sim-platform-ubuntu-pc.so"
72loader = "loader/native-v1"
73artifact_content = "sha256:ubuntu-pc-release-content"
74entry = "sim_native_abi_v1"
75"#;
76
77/// Ubuntu PC capsule card paired with [`UBUNTU_BUNDLE_MANIFEST`].
78pub const UBUNTU_CAPSULE_MANIFEST: &str = r#"
79schema = "sim.platform-capsule/v1"
80provider = "platform/site/ubuntu-pc"
81services = ["platform/monotonic", "platform/wall-clock", "platform/entropy"]
82shells = []
83loader_kinds = ["loader/native-v1", "loader/wasm-v1", "loader/source-v1", "loader/static-v1"]
84"#;
85#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
86pub struct RegisteredCard {
87    pub profile: UbuntuPcProfile,
88    pub card: PlatformCard,
89}
90
91const FACTS: &[(&str, FactPort)] = &[
92    ("wall-clock", FactPort::WallClock),
93    ("monotonic-clock", FactPort::MonotonicClock),
94    ("timer", FactPort::Timer),
95    ("entropy", FactPort::Entropy),
96    ("locale", FactPort::Locale),
97    ("timezone", FactPort::Timezone),
98    ("pressure", FactPort::LifecyclePressure),
99    ("limits", FactPort::MachineLimits),
100];
101const DESKTOP: &[&str] = &[
102    "open",
103    "share",
104    "notify",
105    "clipboard",
106    "permission",
107    "keep-awake",
108    "activation",
109];
110/// Construct the exact Card for a supported Ubuntu profile.
111///
112/// # Panics
113/// Panics only if serialization of the closed profile enum fails.
114#[must_use]
115pub fn register(profile: UbuntuPcProfile) -> RegisteredCard {
116    let kind = profile.kind;
117    let mut services = FACTS
118        .iter()
119        .map(|(name, port)| ServiceOffer {
120            service: OpenSymbol(format!("platform/{name}")),
121            port: *port,
122            evidence: EvidenceLevel::Attested,
123        })
124        .collect::<Vec<_>>();
125    services.extend(
126        ["xdg-config", "xdg-cache", "xdg-data", "xdg-state", "temp"]
127            .into_iter()
128            .map(|name| ServiceOffer {
129                service: OpenSymbol(format!("platform/mount/{name}")),
130                port: FactPort::MachineLimits,
131                evidence: EvidenceLevel::Attested,
132            }),
133    );
134    if kind == ProfileKind::Desktop {
135        services.extend(DESKTOP.iter().map(|name| ServiceOffer {
136            service: OpenSymbol(format!("platform/{name}")),
137            port: FactPort::LifecyclePressure,
138            evidence: EvidenceLevel::Attested,
139        }));
140    }
141    let profile_bytes = serde_json::to_vec(&profile).expect("closed profile serializes");
142    RegisteredCard {
143        profile,
144        card: PlatformCard {
145            schema: OpenSymbol("platform/card-v1".into()),
146            site: OpenSymbol(
147                match kind {
148                    ProfileKind::Desktop => "platform/site/ubuntu-pc-desktop",
149                    ProfileKind::Headless => "platform/site/ubuntu-pc-headless",
150                }
151                .into(),
152            ),
153            services,
154            provenance: ContractProvenance {
155                contract: OpenSymbol("contract/ubuntu-pc-v1".into()),
156                content_digest: stable_digest(&profile_bytes),
157                issuer: OpenSymbol("issuer/sim-platform".into()),
158            },
159        },
160    }
161}
162
163#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
164pub struct PhysicalAttestation {
165    pub schema: String,
166    pub provider: String,
167    pub registered_capability: String,
168    pub source_content: String,
169    pub artifact_content: String,
170    pub card_content: String,
171    pub result_content: String,
172    pub source: String,
173    pub artifact: String,
174    pub card: String,
175    pub result: String,
176    pub checks: Vec<String>,
177}
178impl PhysicalAttestation {
179    /// Verify the sanitized, content-bound offline evidence envelope.
180    ///
181    /// # Errors
182    /// Refuses wrong identity, missing content identities, or leaking checks.
183    pub fn validate(&self) -> Result<(), &'static str> {
184        if self.schema != "sim.platform-physical-attestation/v1"
185            || self.provider != "ubuntu-pc"
186            || self.registered_capability != "linux-x86_64"
187        {
188            return Err("wrong attestation identity");
189        }
190        for (claimed, payload) in [
191            (&self.source_content, &self.source),
192            (&self.artifact_content, &self.artifact),
193            (&self.card_content, &self.card),
194            (&self.result_content, &self.result),
195        ] {
196            if *claimed != stable_digest(payload.as_bytes()) {
197                return Err("content identity mismatch");
198            }
199        }
200        if self.checks.len() < 4
201            || self
202                .checks
203                .iter()
204                .any(|v| v.contains('/') || v.contains('@'))
205        {
206            return Err("unsanitized or incomplete evidence");
207        }
208        Ok(())
209    }
210}