nixos/lanzaboote: use upstream bootspec for extension generation

This commit is contained in:
Raito Bezarius 2022-12-18 00:31:09 +01:00
parent 92e7e4f49a
commit e3f6029643
9 changed files with 103 additions and 70 deletions

View File

@ -31,6 +31,7 @@ to take something up:
- Experimenting with `fwupd` / Green Checkmark in GNOME Device Security - Experimenting with `fwupd` / Green Checkmark in GNOME Device Security
- https://github.com/fwupd/fwupd/issues/5284 - https://github.com/fwupd/fwupd/issues/5284
- Experimenting with TPM2 measurements - Experimenting with TPM2 measurements
- Support bootspec with no initrd
- Studying the initrd secrets feature in NixOS wrt SecureBoot & TPM2 - Studying the initrd secrets feature in NixOS wrt SecureBoot & TPM2
- ... - ...

View File

@ -14,11 +14,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1669605882, "lastModified": 1670900067,
"narHash": "sha256-TiQtL5sUI5rp28S63v+VX25qNjcrc8Xeu+shf3g7Tj4=", "narHash": "sha256-VXVa+KBfukhmWizaiGiHRVX/fuk66P8dgSFfkVN4/MY=",
"owner": "ipetkov", "owner": "ipetkov",
"repo": "crane", "repo": "crane",
"rev": "24591d5f8cc979f7b243b88a2d39da09976970ad", "rev": "59b31b41a589c0a65e4a1f86b0e5eac68081468b",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -30,11 +30,11 @@
"flake-compat": { "flake-compat": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1650374568, "lastModified": 1668681692,
"narHash": "sha256-Z+s0J8/r907g149rllvwhb4pKi8Wam5ij0st8PwAh+E=", "narHash": "sha256-Ht91NGdewz8IQLtWZ9LCeNXMSXHUss+9COoqu6JLmXU=",
"owner": "edolstra", "owner": "edolstra",
"repo": "flake-compat", "repo": "flake-compat",
"rev": "b4a34015c698c7793d592d66adbab377907a2be8", "rev": "009399224d5e398d03b22badca40a37ac85412a1",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -60,32 +60,32 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1669535121, "lastModified": 1671755972,
"narHash": "sha256-koZLM7oWVGrjyHnYDo7/w5qlmUn9UZUKSFNfmIjueE8=", "narHash": "sha256-X977apvpqBqqRf2XBNorfunZmQNn3cQYGEnQE4L90Fo=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "b45ec953794bb07922f0468152ad1ebaf8a084b3", "rev": "e8ee153b1717dca9c6aa38d5cf198329480d5b41",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "NixOS", "owner": "NixOS",
"ref": "nixpkgs-unstable", "ref": "nixos-unstable-small",
"repo": "nixpkgs", "repo": "nixpkgs",
"type": "github" "type": "github"
} }
}, },
"nixpkgs-test": { "nixpkgs-test": {
"locked": { "locked": {
"lastModified": 1669495095, "lastModified": 1671812130,
"narHash": "sha256-wasu8T7ac+LVm4aXuAYkH76Rr98VW0Cp9oZvNPuKiiU=", "narHash": "sha256-GALBK+qB9rhnB+lVnxdgtMoXCySXughZZ3+qGO1Ke/k=",
"owner": "RaitoBezarius", "owner": "RaitoBezarius",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "8bbe1bb1f7352dd9c2e448e8d68846a66d0c2aca", "rev": "e51bf8cc8e2c75192e930ad83ed272938729e7be",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "RaitoBezarius", "owner": "RaitoBezarius",
"ref": "experimental-secureboot", "ref": "simplified-qemu-boot-disks",
"repo": "nixpkgs", "repo": "nixpkgs",
"type": "github" "type": "github"
} }
@ -109,11 +109,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1669602829, "lastModified": 1671243596,
"narHash": "sha256-I3LBvBiVui4Rf0iQvTqUIgBovaLDzpOzsoNEzCsDowg=", "narHash": "sha256-vQ1q6uwx2gKsHbQVhkq17nT8HwUmRbIG8cJVFafNb5s=",
"owner": "oxalica", "owner": "oxalica",
"repo": "rust-overlay", "repo": "rust-overlay",
"rev": "b9da8e68a08707115be750c0cf7ade33f49d8ec4", "rev": "905db21103d646ddc1eb81920e05180e6e2b6734",
"type": "github" "type": "github"
}, },
"original": { "original": {

View File

@ -2,7 +2,8 @@
description = "Lanzaboot Secure Boot Madness"; description = "Lanzaboot Secure Boot Madness";
inputs = { inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable-small";
nixpkgs-test.url = "github:RaitoBezarius/nixpkgs/simplified-qemu-boot-disks";
crane = { crane = {
url = "github:ipetkov/crane"; url = "github:ipetkov/crane";
@ -11,7 +12,6 @@
inputs.flake-utils.follows = "flake-utils"; inputs.flake-utils.follows = "flake-utils";
}; };
nixpkgs-test.url = "github:RaitoBezarius/nixpkgs/experimental-secureboot";
rust-overlay = { rust-overlay = {
url = "github:oxalica/rust-overlay"; url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
@ -21,7 +21,7 @@
flake-utils.url = "github:numtide/flake-utils"; flake-utils.url = "github:numtide/flake-utils";
}; };
outputs = { self, nixpkgs, crane, nixpkgs-test, rust-overlay, ... }: outputs = { self, nixpkgs, nixpkgs-test, crane, rust-overlay, ... }:
let let
pkgs = import nixpkgs { pkgs = import nixpkgs {
system = "x86_64-linux"; system = "x86_64-linux";
@ -140,7 +140,6 @@
}; };
boot.loader.efi = { boot.loader.efi = {
enable = true;
canTouchEfiVariables = true; canTouchEfiVariables = true;
}; };
boot.lanzaboote = { boot.lanzaboote = {
@ -166,7 +165,8 @@
return f'/boot/EFI/nixos/{store_dir}-{filename}.efi' return f'/boot/EFI/nixos/{store_dir}-{filename}.efi'
machine.start() machine.start()
bootspec = json.loads(machine.succeed("cat /run/current-system/bootspec/boot.v1.json")) bootspec = json.loads(machine.succeed("cat /run/current-system/boot.json")).get('v1')
assert bootspec is not None, "Unsupported bootspec version!"
src_path = ${path.src} src_path = ${path.src}
dst_path = ${path.dst} dst_path = ${path.dst}
machine.succeed(f"cp -rf {src_path} {dst_path}") machine.succeed(f"cp -rf {src_path} {dst_path}")
@ -263,7 +263,7 @@
testScript = '' testScript = ''
machine.start() machine.start()
print(machine.succeed("ls -lah /boot/EFI/Linux")) print(machine.succeed("ls -lah /boot/EFI/Linux"))
print(machine.succeed("cat /run/current-system/bootspec/boot.v1.json")) print(machine.succeed("cat /run/current-system/boot.json"))
# TODO: make it more reliable to find this filename, i.e. read it from somewhere? # TODO: make it more reliable to find this filename, i.e. read it from somewhere?
machine.succeed("bootctl set-default nixos-generation-1-specialisation-variant.efi") machine.succeed("bootctl set-default nixos-generation-1-specialisation-variant.efi")
machine.succeed("sync") machine.succeed("sync")

View File

@ -32,9 +32,11 @@ in
}; };
config = mkIf cfg.enable { config = mkIf cfg.enable {
# bootspec is putting at false boot.bootspec = {
# until we fix this upstream, we will mkForce it. enable = true;
boot.loader.supportsInitrdSecrets = mkForce true; extensions."lanzaboote"."osRelease" = config.environment.etc."os-release".source;
};
boot.loader.supportsInitrdSecrets = true;
boot.loader.external = { boot.loader.external = {
enable = true; enable = true;
installHook = pkgs.writeShellScript "bootinstall" '' installHook = pkgs.writeShellScript "bootinstall" ''

View File

@ -69,7 +69,7 @@ dependencies = [
[[package]] [[package]]
name = "bootspec" name = "bootspec"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/RaitoBezarius/bootspec-1?branch=secureboot-needs#a5d327ceb25da6ae4147fbf0b15088f44214a91a" source = "git+https://github.com/RaitoBezarius/bootspec-1?branch=secureboot-needs#3d5acac24d353c5e9998067abb1b458b996cba81"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",

View File

@ -17,7 +17,7 @@
"toplevel": "/run/current-system", "toplevel": "/run/current-system",
"specialisation": {}, "specialisation": {},
"extensions": { "extensions": {
"org.lanzaboote.osRelease": "/etc/os-release" "lanzaboote": { "osRelease": "/etc/os-release" }
} }
} }
} }

View File

@ -1,7 +1,7 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::generation::OSGeneration; use crate::generation::Generation;
pub struct EspPaths { pub struct EspPaths {
pub esp: PathBuf, pub esp: PathBuf,
@ -17,20 +17,26 @@ pub struct EspPaths {
} }
impl EspPaths { impl EspPaths {
pub fn new(esp: impl AsRef<Path>, generation: &OSGeneration) -> Result<Self> { pub fn new(esp: impl AsRef<Path>, generation: &Generation) -> Result<Self> {
let esp = esp.as_ref(); let esp = esp.as_ref();
let esp_nixos = esp.join("EFI/nixos"); let esp_nixos = esp.join("EFI/nixos");
let esp_linux = esp.join("EFI/Linux"); let esp_linux = esp.join("EFI/Linux");
let esp_systemd = esp.join("EFI/systemd"); let esp_systemd = esp.join("EFI/systemd");
let esp_efi_fallback_dir = esp.join("EFI/BOOT"); let esp_efi_fallback_dir = esp.join("EFI/BOOT");
let bootspec = &generation.bootspec; let bootspec = &generation.spec.bootspec;
Ok(Self { Ok(Self {
esp: esp.to_path_buf(), esp: esp.to_path_buf(),
nixos: esp_nixos.clone(), nixos: esp_nixos.clone(),
kernel: esp_nixos.join(nixos_path(&bootspec.kernel, "bzImage")?), kernel: esp_nixos.join(nixos_path(&bootspec.kernel, "bzImage")?),
initrd: esp_nixos.join(nixos_path(&bootspec.initrd, "initrd")?), initrd: esp_nixos.join(nixos_path(
bootspec
.initrd
.as_ref()
.context("Lanzaboote does not support missing initrd yet")?,
"initrd",
)?),
linux: esp_linux.clone(), linux: esp_linux.clone(),
lanzaboote_image: esp_linux.join(generation_path(generation)), lanzaboote_image: esp_linux.join(generation_path(generation)),
efi_fallback_dir: esp_efi_fallback_dir.clone(), efi_fallback_dir: esp_efi_fallback_dir.clone(),
@ -66,7 +72,7 @@ fn nixos_path(path: impl AsRef<Path>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(nixos_filename)) Ok(PathBuf::from(nixos_filename))
} }
fn generation_path(generation: &OSGeneration) -> PathBuf { fn generation_path(generation: &Generation) -> PathBuf {
if let Some(specialisation_name) = generation.is_specialized() { if let Some(specialisation_name) = generation.is_specialized() {
PathBuf::from(format!( PathBuf::from(format!(
"nixos-generation-{}-specialisation-{}.efi", "nixos-generation-{}-specialisation-{}.efi",

View File

@ -1,63 +1,79 @@
use serde::de::IntoDeserializer;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::{anyhow, Context, Result};
use bootspec::generation::Generation as BootspecGeneration;
use bootspec::BootJson; use bootspec::BootJson;
use bootspec::SpecialisationName; use bootspec::SpecialisationName;
use bootspec::generation::Generation;
// TODO: actually, I'm not sure it's a good thing to have Default #[derive(Debug, Clone, Serialize, Deserialize)]
// we should maybe have TryDefault?
// discuss this with upstream.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SecureBootExtension { pub struct SecureBootExtension {
#[serde(rename="org.lanzaboote.osRelease")] #[serde(rename = "osRelease")]
pub os_release: PathBuf pub os_release: PathBuf,
} }
pub type ExtendedBootJson = BootJson<SecureBootExtension>; #[derive(Debug, Clone)]
pub struct ExtendedBootJson {
pub bootspec: BootJson,
pub extensions: SecureBootExtension,
}
#[derive(Debug)] #[derive(Debug)]
pub struct OSGeneration { pub struct Generation {
/// Top-level nixpkgs version /// Profile symlink index
version: u64, version: u64,
/// Top-level specialisation name /// Top-level specialisation name
specialisation_name: Option<SpecialisationName>, specialisation_name: Option<SpecialisationName>,
/// Top-level bootspec document /// Top-level extended boot specification
pub bootspec: ExtendedBootJson, pub spec: ExtendedBootJson,
} }
fn into_boot_json(generation: Generation<SecureBootExtension>) -> Result<ExtendedBootJson> { impl Generation {
Ok(match generation { fn extract_extensions(bootspec: &BootJson) -> Result<SecureBootExtension> {
Generation::V1(json) => json, Ok(Deserialize::deserialize(
_ => panic!("Failed") bootspec.extensions.get("lanzaboote")
}) .context("Failed to extract Lanzaboote-specific extension from Bootspec, missing lanzaboote field in `extensions`")?
.clone()
.into_deserializer()
)?)
} }
impl OSGeneration {
pub fn from_toplevel(toplevel: impl AsRef<Path>) -> Result<Self> { pub fn from_toplevel(toplevel: impl AsRef<Path>) -> Result<Self> {
let bootspec_path = toplevel.as_ref().join("bootspec/boot.json"); let bootspec_path = toplevel.as_ref().join("boot.json");
let generation: Generation<SecureBootExtension> = serde_json::from_slice( let generation: BootspecGeneration = serde_json::from_slice(
&fs::read(bootspec_path).context("Failed to read bootspec file")?, &fs::read(bootspec_path).context("Failed to read bootspec file")?,
) )
.context("Failed to parse bootspec json")?; .context("Failed to parse bootspec json")?;
let bootspec: BootJson = generation
.try_into()
.map_err(|err: &'static str| anyhow!(err))?;
let extensions = Self::extract_extensions(&bootspec)?;
Ok(Self { Ok(Self {
version: parse_version(toplevel)?, version: parse_version(toplevel)?,
specialisation_name: None, specialisation_name: None,
bootspec: into_boot_json(generation)?, spec: ExtendedBootJson {
bootspec,
extensions,
},
}) })
} }
pub fn specialise(&self, name: &SpecialisationName, bootspec: &ExtendedBootJson) -> Self { pub fn specialise(&self, name: &SpecialisationName, bootspec: &BootJson) -> Result<Self> {
Self { Ok(Self {
version: self.version, version: self.version,
specialisation_name: Some(name.clone()), specialisation_name: Some(name.clone()),
bootspec: bootspec.clone() spec: ExtendedBootJson {
} bootspec: bootspec.clone(),
extensions: Self::extract_extensions(&bootspec)?,
},
})
} }
pub fn is_specialized(&self) -> Option<SpecialisationName> { pub fn is_specialized(&self) -> Option<SpecialisationName> {
@ -65,7 +81,7 @@ impl OSGeneration {
} }
} }
impl fmt::Display for OSGeneration { impl fmt::Display for Generation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.version) write!(f, "{}", self.version)
} }

View File

@ -8,7 +8,7 @@ use nix::unistd::sync;
use tempfile::tempdir; use tempfile::tempdir;
use crate::esp::EspPaths; use crate::esp::EspPaths;
use crate::generation::OSGeneration; use crate::generation::Generation;
use crate::pe; use crate::pe;
use crate::signature::KeyPair; use crate::signature::KeyPair;
@ -36,7 +36,7 @@ impl Installer {
pub fn install(&self) -> Result<()> { pub fn install(&self) -> Result<()> {
for toplevel in &self.generations { for toplevel in &self.generations {
let generation = OSGeneration::from_toplevel(toplevel).with_context(|| { let generation = Generation::from_toplevel(toplevel).with_context(|| {
format!("Failed to build generation from toplevel: {toplevel:?}") format!("Failed to build generation from toplevel: {toplevel:?}")
})?; })?;
@ -45,8 +45,8 @@ impl Installer {
self.install_generation(&generation) self.install_generation(&generation)
.context("Failed to install generation")?; .context("Failed to install generation")?;
for (name, bootspec) in &generation.bootspec.specialisation { for (name, bootspec) in &generation.spec.bootspec.specialisation {
let specialised_generation = generation.specialise(name, bootspec); let specialised_generation = generation.specialise(name, bootspec)?;
println!("Installing specialisation: {name} of generation: {generation}"); println!("Installing specialisation: {name} of generation: {generation}");
@ -58,8 +58,9 @@ impl Installer {
Ok(()) Ok(())
} }
fn install_generation(&self, generation: &OSGeneration) -> Result<()> { fn install_generation(&self, generation: &Generation) -> Result<()> {
let bootspec = &generation.bootspec; let bootspec = &generation.spec.bootspec;
let secureboot_extensions = &generation.spec.extensions;
let esp_paths = EspPaths::new(&self.esp, generation)?; let esp_paths = EspPaths::new(&self.esp, generation)?;
@ -77,13 +78,20 @@ impl Installer {
println!("Appending secrets to initrd..."); println!("Appending secrets to initrd...");
let initrd_location = secure_temp_dir.path().join("initrd"); let initrd_location = secure_temp_dir.path().join("initrd");
copy(&bootspec.initrd, &initrd_location)?; copy(
bootspec
.initrd
.as_ref()
.context("Lanzaboote does not support missing initrd yet")?,
&initrd_location,
)?;
if let Some(initrd_secrets_script) = &bootspec.initrd_secrets { if let Some(initrd_secrets_script) = &bootspec.initrd_secrets {
append_initrd_secrets(initrd_secrets_script, &initrd_location)?; append_initrd_secrets(initrd_secrets_script, &initrd_location)?;
} }
let systemd_boot = bootspec let systemd_boot = bootspec
.toplevel.0 .toplevel
.0
.join("systemd/lib/systemd/boot/efi/systemd-bootx64.efi"); .join("systemd/lib/systemd/boot/efi/systemd-bootx64.efi");
[ [
@ -102,7 +110,7 @@ impl Installer {
let lanzaboote_image = pe::lanzaboote_image( let lanzaboote_image = pe::lanzaboote_image(
&secure_temp_dir, &secure_temp_dir,
&self.lanzaboote_stub, &self.lanzaboote_stub,
&bootspec.extensions.os_release, &secureboot_extensions.os_release,
&kernel_cmdline, &kernel_cmdline,
&esp_paths.kernel, &esp_paths.kernel,
&esp_paths.initrd, &esp_paths.initrd,