phoebus_os/installer-rs/crates/phoebus-executor/src/boot.rs

234 lines
8.5 KiB
Rust

//! Bootloader installation: UEFI + systemd-boot with BLS entries.
//!
//! UKI is deferred: the dracut UKI generator did not embed the kernel command
//! line in the verified environment, producing an unbootable image. BLS
//! entries carry `options` and are the proven path.
use std::path::{Path, PathBuf};
use phoebus_core::system as sysgen;
use phoebus_core::InstallConfig;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
use crate::portage;
pub fn write_install_conf(exec: &Exec) -> Result<()> {
exec.target()
.write("etc/kernel/install.conf", sysgen::install_conf())?;
exec.logger
.info("wrote /etc/kernel/install.conf (layout=bls)");
Ok(())
}
pub fn write_dracut_conf(exec: &Exec, config: &InstallConfig) -> Result<()> {
exec.target().write(
"etc/dracut.conf.d/10-phoebus.conf",
sysgen::dracut_conf(config),
)?;
exec.logger.info("wrote /etc/dracut.conf.d/10-phoebus.conf");
Ok(())
}
pub fn esp_path(exec: &Exec, config: &InstallConfig) -> std::path::PathBuf {
exec.root
.join(config.storage.efi_mount.trim_start_matches('/'))
}
pub fn install_systemd_boot(exec: &Exec, config: &InstallConfig) -> Result<()> {
portage::chroot(
exec,
Path::new(&exec.root),
"bootctl",
&["--esp-path", &config.storage.efi_mount, "install"],
)
}
pub fn write_loader_conf(exec: &Exec, config: &InstallConfig) -> Result<()> {
let dir = esp_path(exec, config).join("loader");
std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?;
let text = "# systemd-boot configuration\ndefault *\ntimeout 3\nconsole-mode keep\neditor no\n";
std::fs::write(dir.join("loader.conf"), text)
.map_err(|e| ExecError::io(dir.join("loader.conf"), e))?;
exec.logger
.info(format!("wrote {}", dir.join("loader.conf").display()));
Ok(())
}
pub fn generate_entries(exec: &Exec) -> Result<()> {
portage::chroot(exec, Path::new(&exec.root), "kernel-install", &["add-all"])
}
pub fn install_fallback(exec: &Exec, config: &InstallConfig) -> Result<()> {
let esp = esp_path(exec, config);
let boot_dir = esp.join("EFI/BOOT");
let systemd_dir = esp.join("EFI/systemd");
std::fs::create_dir_all(&boot_dir).map_err(|e| ExecError::io(boot_dir.clone(), e))?;
std::fs::create_dir_all(&systemd_dir).map_err(|e| ExecError::io(systemd_dir.clone(), e))?;
let mut src = systemd_dir.join("systemd-bootx64.efi");
if !src.exists() {
let vendor = exec
.root
.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi");
if vendor.exists() {
src = vendor;
} else {
exec.logger
.warn("systemd-boot binary not found; EFI fallback not installed");
return Ok(());
}
}
let dst = boot_dir.join("BOOTX64.EFI");
std::fs::copy(&src, &dst).map_err(|e| ExecError::io(dst.clone(), e))?;
exec.logger.info("installed EFI fallback bootloader");
Ok(())
}
pub fn random_seed(exec: &Exec, config: &InstallConfig) -> Result<()> {
let dir = esp_path(exec, config).join("loader");
std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?;
let path = dir.join("random-seed");
if !path.exists() {
let bytes: Vec<u8> = (0..512)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(7))
.collect();
std::fs::write(&path, bytes).map_err(|e| ExecError::io(path.clone(), e))?;
}
Ok(())
}
/// Write an additional BLS entry that boots the newest kernel into
/// `rescue.target`. This is a real recovery path: it unlocks LUKS and gives a
/// root shell with the network stack available.
pub fn write_recovery_entry(exec: &Exec, config: &InstallConfig) -> Result<()> {
let entries = esp_path(exec, config).join("loader/entries");
if !entries.is_dir() {
return Ok(());
}
let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
for entry in std::fs::read_dir(&entries).map_err(|e| ExecError::io(entries.clone(), e))? {
let entry = entry.map_err(|e| ExecError::io(entries.clone(), e))?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("conf") {
continue;
}
let name = entry.file_name().to_string_lossy().to_string();
if name.contains("recovery") {
continue;
}
let modified = entry
.metadata()
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
if newest.as_ref().map(|(t, _)| modified > *t).unwrap_or(true) {
newest = Some((modified, path));
}
}
let Some((_, source)) = newest else {
return Ok(());
};
let text = std::fs::read_to_string(&source).map_err(|e| ExecError::io(source.clone(), e))?;
let mut linux = String::new();
let mut initrds: Vec<String> = Vec::new();
let mut options = String::new();
for line in text.lines() {
if let Some(v) = line.strip_prefix("linux") {
linux = v.trim().to_string();
} else if let Some(v) = line.strip_prefix("initrd") {
initrds.push(v.trim().to_string());
} else if let Some(v) = line.strip_prefix("options") {
options = v.trim().to_string();
}
}
if linux.is_empty() {
return Ok(());
}
let mut out = String::new();
out.push_str("# Phoebus recovery entry (generated by the installer)\n");
out.push_str("title Phoebus Recovery\n");
out.push_str(&format!("linux {linux}\n"));
for initrd in &initrds {
out.push_str(&format!("initrd {initrd}\n"));
}
let recovery_options = format!("{options} systemd.unit=rescue.target");
out.push_str(&format!("options {}\n", recovery_options.trim()));
let dest = entries.join("phoebus-recovery.conf");
std::fs::write(&dest, out).map_err(|e| ExecError::io(dest.clone(), e))?;
exec.logger
.info(format!("wrote recovery entry {}", dest.display()));
Ok(())
}
pub fn verify(exec: &Exec, config: &InstallConfig) -> Result<()> {
let esp = esp_path(exec, config);
let loader_a = esp.join("EFI/systemd/systemd-bootx64.efi");
let loader_b = esp.join("EFI/BOOT/BOOTX64.EFI");
if !loader_a.exists() && !loader_b.exists() {
return Err(ExecError::operation(
"boot_install",
"verify",
format!("no systemd-boot loader found in {}", esp.display()),
));
}
let loader_conf = esp.join("loader/loader.conf");
if !loader_conf.exists() {
return Err(ExecError::operation(
"boot_install",
"verify",
"loader.conf not found",
));
}
Ok(())
}
pub fn secureboot_status(exec: &Exec) -> String {
if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() {
return "not booted in UEFI mode".into();
}
if crate::exec::find_in_path("mokutil").is_none() {
return "Secure Boot state unknown (mokutil not installed)".into();
}
match exec
.runner
.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state"))
{
Ok(out) => out.stdout_lossy().trim().to_string(),
Err(_) => "unknown".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
use phoebus_core::Redactor;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn recovery_entry_reuses_kernel_and_initrd() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let cfg = InstallConfig::default();
let entries = exec.root.join("efi/loader/entries");
std::fs::create_dir_all(&entries).unwrap();
std::fs::write(
entries.join("token-6.18.48.conf"),
"title Gentoo Linux\nlinux /token/6.18.48/linux\ninitrd /token/6.18.48/initrd\noptions rd.luks.name=x=cryptroot root=/dev/mapper/cryptroot rw quiet\n",
)
.unwrap();
write_recovery_entry(&exec, &cfg).unwrap();
let text = std::fs::read_to_string(entries.join("phoebus-recovery.conf")).unwrap();
assert!(text.contains("Phoebus Recovery"));
assert!(text.contains("/token/6.18.48/linux"));
assert!(text.contains("/token/6.18.48/initrd"));
assert!(text.contains("systemd.unit=rescue.target"));
}
}