use anyhow::{bail, Result};
use fn_error_context::context;
use log::info;
use virtfw_libefi::efivar::{ids, sigdb::EfiSigDB};
use virtfw_libefi::sb::certs;
use virtfw_libefi::varstore::sysfs;
fn is_secureboot_enabled() -> bool {
let Some(var) = sysfs::varstore_read(ids::SECURE_BOOT.name, ids::SECURE_BOOT.guid) else {
info!("Could not read the Secure Boot EFI variable. Assuming Secure Boot is not enabled.");
return false;
};
match var.data().first() {
Some(&b) => b != 0,
None => false,
}
}
fn db_contains_ms_2023_cert() -> Result<bool> {
let Some(var) = sysfs::varstore_read(ids::DB.name, ids::DB.guid) else {
bail!("Could not read the signature database variable. Assuming it is not safe to update.");
};
let Some(sigdb) = EfiSigDB::new_from_bytes(var.data()) else {
bail!("Failed to parse Secure Boot signature database (unknown layout). Assuming it is not safe to update.");
};
Ok(sigdb
.get_x509_list()
.contains(&certs::MICROSOFT_DB_UEFI_2023))
}
#[context("Validating Secure Boot certificate compatibility")]
pub(crate) fn validate_secureboot_for_update() -> Result<()> {
if !crate::efi::is_efi_booted()? {
info!("Not EFI-booted, skipping Secure Boot certificate check");
return Ok(());
}
if !is_secureboot_enabled() {
info!("Secure Boot not enabled, skipping Secure Boot certificate check");
return Ok(());
};
match db_contains_ms_2023_cert() {
Ok(true) => {
info!("Secure Boot DB contains Microsoft UEFI CA 2023 certificate. Safe to update.");
Ok(())
}
Ok(false) => bail!(
"Secure Boot is enabled but the Microsoft UEFI CA 2023 certificate was not \
found in the firmware's signature database. Updating the shim could render this system \
unbootable. Please update your system firmware by using, for example, fwupd."
),
Err(e) => Err(e),
}
}