Skip to main content

petri/
linux_bootstrap.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Minimal Linux guest initialization shared by Incubator and mshv tests.
5
6use crate::PetriInitrd;
7use crate::initrd::InitrdFile;
8use anyhow::Context;
9use std::path::Path;
10use std::path::PathBuf;
11use std::time::SystemTime;
12use std::time::UNIX_EPOCH;
13
14const INIT_SCRIPT_NAME: &str = "incubator-init.sh";
15const CA_CERTIFICATES_NAME: &str = "incubator-ca-certificates.crt";
16const GUEST_SHARE_ROOT: &str = "/share";
17
18/// Network addressing and agent transport supplied by the outer VMM.
19#[derive(Clone, Copy)]
20pub enum GuestNetwork {
21    /// User-mode networking and TCP Pipette.
22    QemuUser,
23    /// Consomme networking and guest-initiated vsock Pipette.
24    Consomme,
25}
26
27/// Source of the guest agent.
28#[derive(Clone, Copy)]
29pub enum AgentLocation<'a> {
30    /// Embed this host binary in the initrd.
31    Initrd(&'a Path),
32    /// Execute an existing guest path on the hostshare mount.
33    Share(&'a str),
34}
35
36/// Prepare an agent-owned initrd with filesystem, network, clock, and CA setup.
37pub fn prepare_initrd(
38    initrd: &Path,
39    network: GuestNetwork,
40    agent: AgentLocation<'_>,
41    require_mshv: bool,
42    output_directory: Option<&Path>,
43) -> anyhow::Result<PetriInitrd> {
44    let pipette = match agent {
45        AgentLocation::Initrd(path) => Some(fs_err::read(path).context("reading guest Pipette")?),
46        AgentLocation::Share(_) => None,
47    };
48    let certificates = host_ca_certificates()?;
49    let epoch = SystemTime::now()
50        .duration_since(UNIX_EPOCH)
51        .context("host clock is before the Unix epoch")?
52        .as_secs();
53    let script = build_init_script(network, agent, require_mshv, epoch);
54    let mut files = vec![
55        InitrdFile {
56            name: INIT_SCRIPT_NAME,
57            contents: script.as_bytes(),
58            permissions: 0o755,
59        },
60        InitrdFile {
61            name: CA_CERTIFICATES_NAME,
62            contents: &certificates,
63            permissions: 0o644,
64        },
65    ];
66    if let Some(pipette) = &pipette {
67        files.push(InitrdFile {
68            name: "pipette",
69            contents: pipette,
70            permissions: 0o755,
71        });
72    }
73    PetriInitrd::prepare(
74        initrd,
75        &files,
76        &format!("/{INIT_SCRIPT_NAME}"),
77        output_directory,
78    )
79}
80
81fn build_init_script(
82    network: GuestNetwork,
83    agent: AgentLocation<'_>,
84    require_mshv: bool,
85    epoch: u64,
86) -> String {
87    let (address, gateway, dns) = match network {
88        GuestNetwork::Consomme => ("10.0.0.2", "10.0.0.1", "10.0.0.1"),
89        GuestNetwork::QemuUser => ("10.0.2.15", "10.0.2.2", "10.0.2.3"),
90    };
91    let mut script = String::from("#!/bin/sh\n");
92    if matches!(agent, AgentLocation::Initrd(_)) {
93        script.push_str("set -eu\n");
94    }
95    script.push_str(&format!(
96        "/bin/busybox --install /bin\n\
97         mount -t devtmpfs none /dev\nmount -t proc none /proc\n\
98         mount -t sysfs none /sys\nmkdir -p /dev/pts /root /tmp /etc\n\
99         mount -t devpts devpts /dev/pts\ndate -u -s @{epoch}\n"
100    ));
101    if require_mshv {
102        script.push_str("test -c /dev/mshv\nuname -a\n");
103    }
104    let pipette = match agent {
105        AgentLocation::Initrd(_) => "/pipette",
106        AgentLocation::Share(path) => {
107            // A shared agent needs its filesystem mounted before it can start.
108            script.push_str(&format!(
109                "mkdir -p {GUEST_SHARE_ROOT}\n\
110             mount -t 9p -o trans=virtio,version=9p2000.L hostshare {GUEST_SHARE_ROOT}\n\
111             cd {GUEST_SHARE_ROOT}\n"
112            ));
113            path
114        }
115    };
116    let pipette = format!("'{}'", pipette.replace('\'', "'\\''"));
117    let transport = match network {
118        GuestNetwork::QemuUser => "tcp",
119        GuestNetwork::Consomme => "vsock",
120    };
121    script.push_str(&format!(
122        "ip link set eth0 up\nip addr add {address}/24 dev eth0\n\
123         ip route add default via {gateway}\n\
124         echo 'nameserver {dns}' > /etc/resolv.conf\n\
125         export HOME=/root\n\
126         export SSL_CERT_FILE=/{CA_CERTIFICATES_NAME}\n\
127         exec {pipette} --transport {transport}\n"
128    ));
129    script
130}
131
132fn host_ca_certificates() -> anyhow::Result<Vec<u8>> {
133    if let Some(path) = std::env::var_os("SSL_CERT_FILE")
134        .filter(|path| !path.is_empty())
135        .map(PathBuf::from)
136    {
137        return fs_err::read(&path)
138            .with_context(|| format!("reading SSL_CERT_FILE {}", path.display()));
139    }
140    system_ca_certificates()
141}
142
143#[cfg(not(windows))]
144fn system_ca_certificates() -> anyhow::Result<Vec<u8>> {
145    let path = select_ca_bundle(
146        None,
147        &[
148            "/etc/ssl/certs/ca-certificates.crt".into(),
149            "/etc/pki/tls/certs/ca-bundle.crt".into(),
150            "/etc/ssl/ca-bundle.pem".into(),
151        ],
152    )?;
153    fs_err::read(&path).with_context(|| format!("reading host CA bundle {}", path.display()))
154}
155
156#[cfg(windows)]
157fn system_ca_certificates() -> anyhow::Result<Vec<u8>> {
158    let output = powershell_builder::PowerShellBuilder::new()
159        .cmdlet(
160            "$ErrorActionPreference = 'Stop'; \
161             Get-ChildItem Cert:\\LocalMachine\\Root,Cert:\\CurrentUser\\Root | \
162             ForEach-Object { \
163                 '-----BEGIN CERTIFICATE-----'; \
164                 [Convert]::ToBase64String($_.RawData, [Base64FormattingOptions]::InsertLineBreaks); \
165                 '-----END CERTIFICATE-----' \
166             }",
167        )
168        .finish()
169        .build()
170        .output()
171        .context("exporting Windows root certificates for the Linux guest")?;
172    anyhow::ensure!(
173        output.status.success(),
174        "exporting Windows root certificates failed: {}",
175        String::from_utf8_lossy(&output.stderr)
176    );
177    anyhow::ensure!(
178        !output.stdout.is_empty(),
179        "Windows root certificate stores are empty"
180    );
181    Ok(output.stdout)
182}
183
184#[cfg(any(not(windows), test))]
185fn select_ca_bundle(explicit: Option<PathBuf>, defaults: &[PathBuf]) -> anyhow::Result<PathBuf> {
186    if let Some(path) = explicit {
187        anyhow::ensure!(
188            path.is_file(),
189            "SSL_CERT_FILE is not a file: {}",
190            path.display()
191        );
192        return Ok(path);
193    }
194    defaults
195        .iter()
196        .find(|path| path.is_file())
197        .cloned()
198        .context("could not find a host CA certificate bundle for the Linux guest")
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use test_with_tracing::test;
205
206    #[test]
207    fn both_guests_receive_trust_and_clock_setup() {
208        for (network, agent, mshv) in [
209            (
210                GuestNetwork::QemuUser,
211                AgentLocation::Share("/share/agent's pipette"),
212                false,
213            ),
214            (
215                GuestNetwork::Consomme,
216                AgentLocation::Initrd(Path::new("unused")),
217                false,
218            ),
219            (
220                GuestNetwork::Consomme,
221                AgentLocation::Initrd(Path::new("unused")),
222                true,
223            ),
224            (
225                GuestNetwork::QemuUser,
226                AgentLocation::Initrd(Path::new("unused")),
227                true,
228            ),
229        ] {
230            let script = build_init_script(network, agent, mshv, 123456789);
231            assert!(script.contains("export SSL_CERT_FILE=/incubator-ca-certificates.crt\n"));
232            assert!(script.contains("date -u -s @123456789\n"));
233            assert_eq!(script.contains("test -c /dev/mshv\n"), mshv);
234            if matches!(agent, AgentLocation::Initrd(_)) {
235                let transport = match network {
236                    GuestNetwork::QemuUser => "tcp",
237                    GuestNetwork::Consomme => "vsock",
238                };
239                assert!(script.contains(&format!("exec '/pipette' --transport {transport}")));
240                assert!(!script.contains("mount -t 9p"));
241            } else {
242                assert!(script.contains("exec '/share/agent'\\''s pipette' --transport tcp"));
243                assert!(script.contains("mount -t 9p"));
244            }
245            assert_eq!(
246                script.contains("ip addr add 10.0.0.2/24"),
247                matches!(network, GuestNetwork::Consomme)
248            );
249            assert_eq!(
250                script.contains("ip addr add 10.0.2.15/24"),
251                matches!(network, GuestNetwork::QemuUser)
252            );
253        }
254    }
255
256    #[test]
257    fn ca_selection_honors_explicit_bundle_and_reports_errors() -> anyhow::Result<()> {
258        let temp = tempfile::tempdir()?;
259        let explicit = temp.path().join("explicit");
260        let default = temp.path().join("default");
261        fs_err::write(&explicit, b"explicit")?;
262        fs_err::write(&default, b"default")?;
263        let defaults = [default.clone()];
264        assert_eq!(
265            select_ca_bundle(Some(explicit.clone()), &defaults)?,
266            explicit
267        );
268        assert_eq!(select_ca_bundle(None, &defaults)?, default);
269        assert!(select_ca_bundle(Some(temp.path().join("missing")), &defaults).is_err());
270        assert!(select_ca_bundle(None, &[]).is_err());
271        Ok(())
272    }
273}