bootc_lib/install/
baseline.rs

1//! # The baseline installer
2//!
3//! This module handles creation of simple root filesystem setups.  At the current time
4//! it's very simple - just a direct filesystem (e.g. xfs, ext4, btrfs etc.).  It is
5//! intended to add opinionated handling of TPM2-bound LUKS too.  But that's about it;
6//! other more complex flows should set things up externally and use `bootc install to-filesystem`.
7
8use std::borrow::Cow;
9use std::fmt::Display;
10use std::fmt::Write as _;
11use std::io::Write;
12use std::process::Command;
13use std::process::Stdio;
14
15use anyhow::Ok;
16use anyhow::{Context, Result};
17use bootc_utils::CommandRunExt;
18use camino::Utf8Path;
19use camino::Utf8PathBuf;
20use cap_std::fs::Dir;
21use cap_std_ext::cap_std;
22use clap::ValueEnum;
23use fn_error_context::context;
24use serde::{Deserialize, Serialize};
25
26use super::MountSpec;
27use super::RUN_BOOTC;
28use super::RW_KARG;
29use super::RootSetup;
30use super::State;
31use super::config::Filesystem;
32use crate::task::Task;
33use bootc_kernel_cmdline::utf8::Cmdline;
34#[cfg(feature = "install-to-disk")]
35use bootc_mount::is_mounted_in_pid1_mountns;
36
37// This ensures we end up under 512 to be small-sized.
38pub(crate) const BOOTPN_SIZE_MB: u32 = 510;
39pub(crate) const EFIPN_SIZE_MB: u32 = 512;
40/// EFI Partition size for composefs installations
41/// We need more space than ostree as we have UKIs and UKI addons
42/// We might also need to store UKIs for pinned deployments
43pub(crate) const CFS_EFIPN_SIZE_MB: u32 = 1024;
44#[cfg(feature = "install-to-disk")]
45pub(crate) const PREPBOOT_GUID: &str = "9E1A2D38-C612-4316-AA26-8B49521E5A8B";
46#[cfg(feature = "install-to-disk")]
47pub(crate) const PREPBOOT_LABEL: &str = "PowerPC-PReP-boot";
48
49#[derive(clap::ValueEnum, Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "kebab-case")]
51pub(crate) enum BlockSetup {
52    #[default]
53    Direct,
54    Tpm2Luks,
55}
56
57impl Display for BlockSetup {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        self.to_possible_value().unwrap().get_name().fmt(f)
60    }
61}
62
63/// Options for installing to a block device
64#[derive(Debug, Clone, clap::Args, Serialize, Deserialize, PartialEq, Eq)]
65#[serde(rename_all = "kebab-case")]
66pub(crate) struct InstallBlockDeviceOpts {
67    /// Target block device for installation.  The entire device will be wiped.
68    pub(crate) device: Utf8PathBuf,
69
70    /// Automatically wipe all existing data on device
71    #[clap(long)]
72    #[serde(default)]
73    pub(crate) wipe: bool,
74
75    /// Target root block device setup.
76    ///
77    /// direct: Filesystem written directly to block device
78    /// tpm2-luks: Bind unlock of filesystem to presence of the default tpm2 device.
79    #[clap(long, value_enum)]
80    pub(crate) block_setup: Option<BlockSetup>,
81
82    /// Target root filesystem type.
83    #[clap(long, value_enum)]
84    pub(crate) filesystem: Option<Filesystem>,
85
86    /// Size of the root partition (default specifier: M).  Allowed specifiers: M (mebibytes), G (gibibytes), T (tebibytes).
87    ///
88    /// By default, all remaining space on the disk will be used.
89    #[clap(long)]
90    pub(crate) root_size: Option<String>,
91}
92
93impl BlockSetup {
94    /// Returns true if the block setup requires a separate /boot aka XBOOTLDR partition.
95    pub(crate) fn requires_bootpart(&self) -> bool {
96        match self {
97            BlockSetup::Direct => false,
98            BlockSetup::Tpm2Luks => true,
99        }
100    }
101}
102
103#[cfg(feature = "install-to-disk")]
104fn mkfs<'a>(
105    dev: &str,
106    fs: Filesystem,
107    label: &str,
108    wipe: bool,
109    opts: impl IntoIterator<Item = &'a str>,
110) -> Result<uuid::Uuid> {
111    let devinfo = bootc_blockdev::list_dev(dev.into())?;
112    let size = ostree_ext::glib::format_size(devinfo.size);
113
114    // Generate a random UUID for the filesystem
115    let u = uuid::Uuid::new_v4();
116
117    let mut t = Task::new(
118        &format!("Creating {label} filesystem ({fs}) on device {dev} (size={size})"),
119        format!("mkfs.{fs}"),
120    );
121    match fs {
122        Filesystem::Xfs => {
123            if wipe {
124                t.cmd.arg("-f");
125            }
126            t.cmd.arg("-m");
127            t.cmd.arg(format!("uuid={u}"));
128        }
129        Filesystem::Btrfs | Filesystem::Ext4 => {
130            t.cmd.arg("-U");
131            t.cmd.arg(u.to_string());
132        }
133    };
134    // Today all the above mkfs commands take -L
135    t.cmd.args(["-L", label]);
136    t.cmd.args(opts);
137    t.cmd.arg(dev);
138    // All the mkfs commands are unnecessarily noisy by default
139    t.cmd.stdout(Stdio::null());
140    // But this one is notable so let's print the whole thing with verbose()
141    t.verbose().run()?;
142    Ok(u)
143}
144
145pub(crate) fn wipefs(dev: &Utf8Path) -> Result<()> {
146    println!("Wiping device {dev}");
147    Command::new("wipefs")
148        .args(["-a", dev.as_str()])
149        .run_inherited_with_cmd_context()
150}
151
152pub(crate) fn udev_settle() -> Result<()> {
153    // There's a potential window after rereading the partition table where
154    // udevd hasn't yet received updates from the kernel, settle will return
155    // immediately, and lsblk won't pick up partition labels.  Try to sleep
156    // our way out of this.
157    std::thread::sleep(std::time::Duration::from_millis(200));
158
159    let st = super::run_in_host_mountns("udevadm")?
160        .arg("settle")
161        .status()?;
162    if !st.success() {
163        anyhow::bail!("Failed to run udevadm settle: {st:?}");
164    }
165    Ok(())
166}
167
168#[context("Creating rootfs")]
169#[cfg(feature = "install-to-disk")]
170pub(crate) fn install_create_rootfs(
171    state: &State,
172    opts: InstallBlockDeviceOpts,
173) -> Result<RootSetup> {
174    let install_config = state.install_config.as_ref();
175    let luks_name = "root";
176    // Ensure we have a root filesystem upfront
177    let root_filesystem = opts
178        .filesystem
179        .or(install_config
180            .and_then(|c| c.filesystem_root())
181            .and_then(|r| r.fstype))
182        .ok_or_else(|| anyhow::anyhow!("No root filesystem specified"))?;
183    // Verify that the target is empty (if not already wiped in particular, but it's
184    // also good to verify that the wipe worked)
185    let mut device = bootc_blockdev::list_dev(&opts.device)?;
186
187    // Always disallow writing to mounted device
188    if is_mounted_in_pid1_mountns(&device.path())? {
189        anyhow::bail!("Device {} is mounted", device.path())
190    }
191
192    // Handle wiping any existing data
193    if opts.wipe {
194        let dev = &opts.device;
195        for child in device.children.iter().flatten() {
196            let child = child.path();
197            println!("Wiping {child}");
198            wipefs(Utf8Path::new(&child))?;
199        }
200        println!("Wiping {dev}");
201        wipefs(dev)?;
202    } else if device.has_children() {
203        anyhow::bail!(
204            "Detected existing partitions on {}; use e.g. `wipefs` or --wipe if you intend to overwrite",
205            opts.device
206        );
207    }
208
209    let run_bootc = Utf8Path::new(RUN_BOOTC);
210    let mntdir = run_bootc.join("mounts");
211    if mntdir.exists() {
212        std::fs::remove_dir_all(&mntdir)?;
213    }
214
215    // Use the install configuration to find the block setup, if we have one
216    let block_setup = if let Some(config) = install_config {
217        config.get_block_setup(opts.block_setup.as_ref().copied())?
218    } else if opts.filesystem.is_some() {
219        // Otherwise, if a filesystem is specified then we default to whatever was
220        // specified via --block-setup, or the default
221        opts.block_setup.unwrap_or_default()
222    } else {
223        // If there was no default filesystem, then there's no default block setup,
224        // and we need to error out.
225        anyhow::bail!("No install configuration found, and no filesystem specified")
226    };
227    let serial = device.serial.as_deref().unwrap_or("<unknown>");
228    let model = device.model.as_deref().unwrap_or("<unknown>");
229    println!("Block setup: {block_setup}");
230    println!("       Size: {}", device.size);
231    println!("     Serial: {serial}");
232    println!("      Model: {model}");
233
234    let root_size = opts
235        .root_size
236        .as_deref()
237        .map(bootc_blockdev::parse_size_mib)
238        .transpose()
239        .context("Parsing root size")?;
240
241    // Load the policy from the container root, which also must be our install root
242    let sepolicy = state.load_policy()?;
243    let sepolicy = sepolicy.as_ref();
244
245    // Create a temporary directory to use for mount points.  Note that we're
246    // in a mount namespace, so these should not be visible on the host.
247    let physical_root_path = mntdir.join("rootfs");
248    std::fs::create_dir_all(&physical_root_path)?;
249    let bootfs = mntdir.join("boot");
250    std::fs::create_dir_all(bootfs)?;
251
252    // Generate partitioning spec as input to sfdisk
253    let mut partno = 0;
254    let mut partitioning_buf = String::new();
255    writeln!(partitioning_buf, "label: gpt")?;
256    let random_label = uuid::Uuid::new_v4();
257    writeln!(&mut partitioning_buf, "label-id: {random_label}")?;
258    if cfg!(target_arch = "x86_64") {
259        partno += 1;
260        writeln!(
261            &mut partitioning_buf,
262            r#"size=1MiB, bootable, type=21686148-6449-6E6F-744E-656564454649, name="BIOS-BOOT""#
263        )?;
264    } else if cfg!(target_arch = "powerpc64") {
265        // PowerPC-PReP-boot
266        partno += 1;
267        let label = PREPBOOT_LABEL;
268        let uuid = PREPBOOT_GUID;
269        writeln!(
270            &mut partitioning_buf,
271            r#"size=4MiB, bootable, type={uuid}, name="{label}""#
272        )?;
273    } else if cfg!(any(target_arch = "aarch64", target_arch = "s390x")) {
274        // No bootloader partition is necessary
275    } else {
276        anyhow::bail!("Unsupported architecture: {}", std::env::consts::ARCH);
277    }
278
279    let esp_partno = if super::ARCH_USES_EFI {
280        let esp_guid = crate::discoverable_partition_specification::ESP;
281        partno += 1;
282
283        let esp_size = if state.composefs_options.composefs_backend {
284            CFS_EFIPN_SIZE_MB
285        } else {
286            EFIPN_SIZE_MB
287        };
288
289        writeln!(
290            &mut partitioning_buf,
291            r#"size={esp_size}MiB, type={esp_guid}, name="EFI-SYSTEM""#
292        )?;
293        Some(partno)
294    } else {
295        None
296    };
297
298    // Initialize the /boot filesystem.  Note that in the future, we may match
299    // what systemd/uapi-group encourages and make /boot be FAT32 as well, as
300    // it would aid systemd-boot.
301    let boot_partno = if block_setup.requires_bootpart() {
302        partno += 1;
303        writeln!(
304            &mut partitioning_buf,
305            r#"size={BOOTPN_SIZE_MB}MiB, name="boot""#
306        )?;
307        Some(partno)
308    } else {
309        None
310    };
311    let rootpn = partno + 1;
312    let root_size = root_size
313        .map(|v| Cow::Owned(format!("size={v}MiB, ")))
314        .unwrap_or_else(|| Cow::Borrowed(""));
315    let rootpart_uuid =
316        uuid::Uuid::parse_str(crate::discoverable_partition_specification::this_arch_root())?;
317    writeln!(
318        &mut partitioning_buf,
319        r#"{root_size}type={rootpart_uuid}, name="root""#
320    )?;
321    tracing::debug!("Partitioning: {partitioning_buf}");
322    Task::new("Initializing partitions", "sfdisk")
323        .arg("--wipe=always")
324        .arg(device.path())
325        .quiet()
326        .run_with_stdin_buf(Some(partitioning_buf.as_bytes()))
327        .context("Failed to run sfdisk")?;
328    tracing::debug!("Created partition table");
329
330    // Full udev sync; it'd obviously be better to await just the devices
331    // we're targeting, but this is a simple coarse hammer.
332    udev_settle()?;
333
334    // Re-read partition table to get updated children
335    device.refresh()?;
336
337    let root_device = device.find_device_by_partno(rootpn)?;
338    // Verify the partition type matches the DPS root partition type for this architecture
339    let expected_parttype = crate::discoverable_partition_specification::this_arch_root();
340    if !root_device
341        .parttype
342        .as_ref()
343        .is_some_and(|pt| pt.eq_ignore_ascii_case(expected_parttype))
344    {
345        anyhow::bail!(
346            "root partition {rootpn} has type {}; expected {expected_parttype}",
347            root_device.parttype.as_deref().unwrap_or("<none>")
348        );
349    }
350    let (rootdev_path, root_blockdev_kargs) = match block_setup {
351        BlockSetup::Direct => (root_device.path(), None),
352        BlockSetup::Tpm2Luks => {
353            let uuid = uuid::Uuid::new_v4().to_string();
354            // This will be replaced via --wipe-slot=all when binding to tpm below
355            let dummy_passphrase = uuid::Uuid::new_v4().to_string();
356            let mut tmp_keyfile = tempfile::NamedTempFile::new()?;
357            tmp_keyfile.write_all(dummy_passphrase.as_bytes())?;
358            tmp_keyfile.flush()?;
359            let tmp_keyfile = tmp_keyfile.path();
360            let dummy_passphrase_input = Some(dummy_passphrase.as_bytes());
361
362            let root_devpath = root_device.path();
363
364            Task::new("Initializing LUKS for root", "cryptsetup")
365                .args(["luksFormat", "--uuid", uuid.as_str(), "--key-file"])
366                .args([tmp_keyfile])
367                .arg(&root_devpath)
368                .run()?;
369            // The --wipe-slot=all removes our temporary passphrase, and binds to the local TPM device.
370            // We also use .verbose() here as the details are important/notable.
371            Task::new("Enrolling root device with TPM", "systemd-cryptenroll")
372                .args(["--wipe-slot=all", "--tpm2-device=auto", "--unlock-key-file"])
373                .args([tmp_keyfile])
374                .arg(&root_devpath)
375                .verbose()
376                .run_with_stdin_buf(dummy_passphrase_input)?;
377            Task::new("Opening root LUKS device", "cryptsetup")
378                .args(["luksOpen", &root_devpath, luks_name])
379                .run()?;
380            let rootdev = format!("/dev/mapper/{luks_name}");
381            let kargs = vec![
382                format!("luks.uuid={uuid}"),
383                format!("luks.options=tpm2-device=auto,headless=true"),
384            ];
385            (rootdev, Some(kargs))
386        }
387    };
388
389    // Initialize the /boot filesystem
390    let bootdev = if let Some(bootpn) = boot_partno {
391        Some(device.find_device_by_partno(bootpn)?)
392    } else {
393        None
394    };
395    let boot_uuid = if let Some(bootdev) = bootdev {
396        Some(
397            mkfs(&bootdev.path(), root_filesystem, "boot", opts.wipe, [])
398                .context("Initializing /boot")?,
399        )
400    } else {
401        None
402    };
403
404    // Unconditionally enable fsverity for ext4
405    let mkfs_options = match root_filesystem {
406        Filesystem::Ext4 => ["-O", "verity"].as_slice(),
407        _ => [].as_slice(),
408    };
409
410    // Initialize rootfs
411    let root_uuid = mkfs(
412        &rootdev_path,
413        root_filesystem,
414        "root",
415        opts.wipe,
416        mkfs_options.iter().copied(),
417    )?;
418    let rootarg = format!("root=UUID={root_uuid}");
419    let bootsrc = boot_uuid.as_ref().map(|uuid| format!("UUID={uuid}"));
420    let bootarg = bootsrc.as_deref().map(|bootsrc| format!("boot={bootsrc}"));
421    let boot = bootsrc.map(|bootsrc| MountSpec {
422        source: bootsrc,
423        target: "/boot".into(),
424        fstype: MountSpec::AUTO.into(),
425        options: Some("ro".into()),
426    });
427
428    let mut kargs = Cmdline::new();
429
430    // Add root blockdev kargs (e.g., LUKS parameters)
431    if let Some(root_blockdev_kargs) = root_blockdev_kargs {
432        for karg in root_blockdev_kargs {
433            kargs.extend(&Cmdline::from(karg.as_str()));
434        }
435    }
436
437    // Add root= and rw argument
438    kargs.extend(&Cmdline::from(format!("{rootarg} {RW_KARG}")));
439
440    // Add boot= argument if present
441    if let Some(bootarg) = bootarg {
442        kargs.extend(&Cmdline::from(bootarg.as_str()));
443    }
444
445    // Add CLI kargs
446    if let Some(cli_kargs) = state.config_opts.karg.as_ref() {
447        for karg in cli_kargs {
448            kargs.extend(karg);
449        }
450    }
451
452    bootc_mount::mount(&rootdev_path, &physical_root_path)?;
453    let target_rootfs = Dir::open_ambient_dir(&physical_root_path, cap_std::ambient_authority())?;
454    crate::lsm::ensure_dir_labeled(&target_rootfs, "", Some("/".into()), 0o755.into(), sepolicy)?;
455    let physical_root = Dir::open_ambient_dir(&physical_root_path, cap_std::ambient_authority())?;
456    let bootfs = physical_root_path.join("boot");
457    // Create the underlying mount point directory, which should be labeled
458    crate::lsm::ensure_dir_labeled(&target_rootfs, "boot", None, 0o755.into(), sepolicy)?;
459    if let Some(bootdev) = bootdev {
460        bootc_mount::mount(&bootdev.path(), &bootfs)?;
461    }
462    // And we want to label the root mount of /boot
463    crate::lsm::ensure_dir_labeled(&target_rootfs, "boot", None, 0o755.into(), sepolicy)?;
464
465    // Create the EFI system partition, if applicable
466    if let Some(esp_partno) = esp_partno {
467        let espdev = device.find_device_by_partno(esp_partno)?;
468        Task::new("Creating ESP filesystem", "mkfs.fat")
469            .args([&espdev.path(), "-n", "EFI-SYSTEM"])
470            .verbose()
471            .quiet_output()
472            .run()?;
473        let efifs_path = bootfs.join(crate::bootloader::EFI_DIR);
474        std::fs::create_dir(&efifs_path).context("Creating efi dir")?;
475    }
476
477    let luks_device = match block_setup {
478        BlockSetup::Direct => None,
479        BlockSetup::Tpm2Luks => Some(luks_name.to_string()),
480    };
481    Ok(RootSetup {
482        luks_device,
483        device_info: device,
484        physical_root_path,
485        physical_root,
486        target_root_path: None,
487        rootfs_uuid: Some(root_uuid.to_string()),
488        boot,
489        kargs,
490        skip_finalize: false,
491    })
492}