mirror of
https://github.com/edera-dev/sprout.git
synced 2025-12-19 14:00:18 +00:00
chore(code): split much of the efi support code to crates/eficore
This commit is contained in:
20
crates/eficore/Cargo.toml
Normal file
20
crates/eficore/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "edera-sprout-eficore"
|
||||
description = "Sprout EFI Core"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
bitflags.workspace = true
|
||||
log.workspace = true
|
||||
spin.workspace = true
|
||||
uefi.workspace = true
|
||||
uefi-raw.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "eficore"
|
||||
path = "src/lib.rs"
|
||||
317
crates/eficore/src/bootloader_interface.rs
Normal file
317
crates/eficore/src/bootloader_interface.rs
Normal file
@@ -0,0 +1,317 @@
|
||||
use crate::bootloader_interface::bitflags::LoaderFeatures;
|
||||
use crate::platform::timer::PlatformTimer;
|
||||
use crate::variables::{VariableClass, VariableController};
|
||||
use alloc::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result};
|
||||
use uefi::proto::device_path::DevicePath;
|
||||
use uefi::{Guid, guid};
|
||||
use uefi_raw::table::runtime::VariableVendor;
|
||||
|
||||
/// bitflags: LoaderFeatures bitflags.
|
||||
mod bitflags;
|
||||
|
||||
/// The name of the bootloader to tell the system.
|
||||
const LOADER_NAME: &str = "Sprout";
|
||||
|
||||
/// Represents the configured timeout for the bootloader interface.
|
||||
pub enum BootloaderInterfaceTimeout {
|
||||
/// Force the menu to be shown.
|
||||
MenuForce,
|
||||
/// Hide the menu.
|
||||
MenuHidden,
|
||||
/// Disable the menu.
|
||||
MenuDisabled,
|
||||
/// Set a timeout for the menu.
|
||||
Timeout(u64),
|
||||
/// Timeout is unspecified.
|
||||
Unspecified,
|
||||
}
|
||||
|
||||
/// Bootloader Interface support.
|
||||
pub struct BootloaderInterface;
|
||||
|
||||
impl BootloaderInterface {
|
||||
/// Bootloader Interface GUID from https://systemd.io/BOOT_LOADER_INTERFACE
|
||||
const VENDOR: VariableController = VariableController::new(VariableVendor(guid!(
|
||||
"4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"
|
||||
)));
|
||||
|
||||
/// The feature we support in Sprout.
|
||||
fn features() -> LoaderFeatures {
|
||||
LoaderFeatures::Xbootldr
|
||||
| LoaderFeatures::LoadDriver
|
||||
| LoaderFeatures::Tpm2ActivePcrBanks
|
||||
| LoaderFeatures::RetainShim
|
||||
| LoaderFeatures::ConfigTimeout
|
||||
| LoaderFeatures::ConfigTimeoutOneShot
|
||||
| LoaderFeatures::MenuDisable
|
||||
| LoaderFeatures::EntryDefault
|
||||
| LoaderFeatures::EntryOneShot
|
||||
}
|
||||
|
||||
/// Tell the system that Sprout was initialized at the current time.
|
||||
pub fn mark_init(timer: &PlatformTimer) -> Result<()> {
|
||||
Self::mark_time("LoaderTimeInitUSec", timer)
|
||||
}
|
||||
|
||||
/// Tell the system that Sprout is about to execute the boot entry.
|
||||
pub fn mark_exec(timer: &PlatformTimer) -> Result<()> {
|
||||
Self::mark_time("LoaderTimeExecUSec", timer)
|
||||
}
|
||||
|
||||
/// Tell the system that Sprout is about to display the menu.
|
||||
pub fn mark_menu(timer: &PlatformTimer) -> Result<()> {
|
||||
Self::mark_time("LoaderTimeMenuUSec", timer)
|
||||
}
|
||||
|
||||
/// Tell the system about the current time as measured by the platform timer.
|
||||
/// Sets the variable specified by `key` to the number of microseconds.
|
||||
fn mark_time(key: &str, timer: &PlatformTimer) -> Result<()> {
|
||||
// Measure the elapsed time since the hardware timer was started.
|
||||
let elapsed = timer.elapsed_since_lifetime();
|
||||
Self::VENDOR.set_cstr16(
|
||||
key,
|
||||
&elapsed.as_micros().to_string(),
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system what loader is being used and our features.
|
||||
pub fn set_loader_info() -> Result<()> {
|
||||
// Set the LoaderInfo variable with the name of the loader.
|
||||
Self::VENDOR
|
||||
.set_cstr16(
|
||||
"LoaderInfo",
|
||||
LOADER_NAME,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
.context("unable to set loader info variable")?;
|
||||
|
||||
// Set the LoaderFeatures variable with the features we support.
|
||||
Self::VENDOR
|
||||
.set_u64le(
|
||||
"LoaderFeatures",
|
||||
Self::features().bits(),
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
.context("unable to set loader features variable")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tell the system the relative path to the partition root of the current bootloader.
|
||||
pub fn set_loader_path(path: &DevicePath) -> Result<()> {
|
||||
let subpath =
|
||||
crate::path::device_path_subpath(path).context("unable to get loader path subpath")?;
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderImageIdentifier",
|
||||
&subpath,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system what the partition GUID of the ESP Sprout was booted from is.
|
||||
pub fn set_partition_guid(guid: &Guid) -> Result<()> {
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderDevicePartUUID",
|
||||
&guid.to_string(),
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system what boot entries are available.
|
||||
pub fn set_entries<N: AsRef<str>>(entries: impl Iterator<Item = N>) -> Result<()> {
|
||||
// Entries are stored as a null-terminated list of CString16 strings back to back.
|
||||
// Iterate over the entries and convert them to CString16 placing them into data.
|
||||
let mut data = Vec::new();
|
||||
for entry in entries {
|
||||
// Convert the entry to CString16 little endian.
|
||||
let encoded = entry
|
||||
.as_ref()
|
||||
.encode_utf16()
|
||||
.flat_map(|c| c.to_le_bytes())
|
||||
.collect::<Vec<u8>>();
|
||||
// Write the bytes into the data buffer.
|
||||
data.extend_from_slice(&encoded);
|
||||
// Add a null terminator to the end of the entry.
|
||||
data.extend_from_slice(&[0, 0]);
|
||||
}
|
||||
|
||||
// If no data was generated, we will do nothing.
|
||||
if data.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Self::VENDOR.set(
|
||||
"LoaderEntries",
|
||||
&data,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system what the selected boot entry is.
|
||||
pub fn set_selected_entry(entry: String) -> Result<()> {
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderEntrySelected",
|
||||
&entry,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system about the UEFI firmware we are running on.
|
||||
pub fn set_firmware_info() -> Result<()> {
|
||||
// Access the firmware revision.
|
||||
let firmware_revision = uefi::system::firmware_revision();
|
||||
|
||||
// Access the UEFI revision.
|
||||
let uefi_revision = uefi::system::uefi_revision();
|
||||
|
||||
// Format the firmware information string into something human-readable.
|
||||
let firmware_info = format!(
|
||||
"{} {}.{:02}",
|
||||
uefi::system::firmware_vendor(),
|
||||
firmware_revision >> 16,
|
||||
firmware_revision & 0xffff,
|
||||
);
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderFirmwareInfo",
|
||||
&firmware_info,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)?;
|
||||
|
||||
// Format the firmware revision into something human-readable.
|
||||
let firmware_type = format!(
|
||||
"UEFI {}.{:02}",
|
||||
uefi_revision.major(),
|
||||
uefi_revision.minor()
|
||||
);
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderFirmwareType",
|
||||
&firmware_type,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the system what the number of active PCR banks is.
|
||||
/// If this is zero, that is okay.
|
||||
pub fn set_tpm2_active_pcr_banks(value: u32) -> Result<()> {
|
||||
// Format the value into the specification format.
|
||||
let value = format!("0x{:08x}", value);
|
||||
Self::VENDOR.set_cstr16(
|
||||
"LoaderTpm2ActivePcrBanks",
|
||||
&value,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
}
|
||||
|
||||
/// Retrieve the timeout value from the bootloader interface, using the specified `key`.
|
||||
/// `remove` indicates whether, when found, we remove the variable.
|
||||
fn get_timeout_value(key: &str, remove: bool) -> Result<Option<BootloaderInterfaceTimeout>> {
|
||||
// Retrieve the timeout value from the bootloader interface.
|
||||
let Some(value) = Self::VENDOR
|
||||
.get_cstr16(key)
|
||||
.context("unable to get timeout value")?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// If we reach here, we know the value was specified.
|
||||
// If `remove` is true, remove the variable.
|
||||
if remove {
|
||||
Self::VENDOR
|
||||
.remove(key)
|
||||
.context("unable to remove timeout variable")?;
|
||||
}
|
||||
|
||||
// If the value is empty, return Unspecified.
|
||||
if value.is_empty() {
|
||||
return Ok(Some(BootloaderInterfaceTimeout::Unspecified));
|
||||
}
|
||||
|
||||
// If the value is "menu-force", return MenuForce.
|
||||
if value == "menu-force" {
|
||||
return Ok(Some(BootloaderInterfaceTimeout::MenuForce));
|
||||
}
|
||||
|
||||
// If the value is "menu-hidden", return MenuHidden.
|
||||
if value == "menu-hidden" {
|
||||
return Ok(Some(BootloaderInterfaceTimeout::MenuHidden));
|
||||
}
|
||||
|
||||
// If the value is "menu-disabled", return MenuDisabled.
|
||||
if value == "menu-disabled" {
|
||||
return Ok(Some(BootloaderInterfaceTimeout::MenuDisabled));
|
||||
}
|
||||
|
||||
// Parse the value as a u64 to decode an numeric value.
|
||||
let value = value
|
||||
.parse::<u64>()
|
||||
.context("unable to parse timeout value")?;
|
||||
|
||||
// The specification says that a value of 0 means that the menu should be hidden.
|
||||
if value == 0 {
|
||||
return Ok(Some(BootloaderInterfaceTimeout::MenuHidden));
|
||||
}
|
||||
|
||||
// If we reach here, we know it must be a real timeout value.
|
||||
Ok(Some(BootloaderInterfaceTimeout::Timeout(value)))
|
||||
}
|
||||
|
||||
/// Get the timeout from the bootloader interface.
|
||||
/// This indicates how the menu should behave.
|
||||
/// If no values are set, Unspecified is returned.
|
||||
pub fn get_timeout() -> Result<BootloaderInterfaceTimeout> {
|
||||
// Attempt to acquire the value of the LoaderConfigTimeoutOneShot variable.
|
||||
// This should take precedence over the LoaderConfigTimeout variable.
|
||||
let oneshot = Self::get_timeout_value("LoaderConfigTimeoutOneShot", true)
|
||||
.context("unable to check for LoaderConfigTimeoutOneShot variable")?;
|
||||
|
||||
// If oneshot was found, return it.
|
||||
if let Some(oneshot) = oneshot {
|
||||
return Ok(oneshot);
|
||||
}
|
||||
|
||||
// Attempt to acquire the value of the LoaderConfigTimeout variable.
|
||||
// This will be used if the LoaderConfigTimeoutOneShot variable is not set.
|
||||
let direct = Self::get_timeout_value("LoaderConfigTimeout", false)
|
||||
.context("unable to check for LoaderConfigTimeout variable")?;
|
||||
|
||||
// If direct was found, return it.
|
||||
if let Some(direct) = direct {
|
||||
return Ok(direct);
|
||||
}
|
||||
|
||||
// If we reach here, we know that neither variable was set.
|
||||
// We provide the unspecified value instead.
|
||||
Ok(BootloaderInterfaceTimeout::Unspecified)
|
||||
}
|
||||
|
||||
/// Get the default entry set by the bootloader interface.
|
||||
pub fn get_default_entry() -> Result<Option<String>> {
|
||||
Self::VENDOR
|
||||
.get_cstr16("LoaderEntryDefault")
|
||||
.context("unable to get default entry from bootloader interface")
|
||||
}
|
||||
|
||||
/// Get the oneshot entry set by the bootloader interface.
|
||||
/// This should be the entry we boot.
|
||||
pub fn get_oneshot_entry() -> Result<Option<String>> {
|
||||
// Acquire the value of the LoaderEntryOneShot variable.
|
||||
// If it is not set, return None.
|
||||
let Some(value) = Self::VENDOR
|
||||
.get_cstr16("LoaderEntryOneShot")
|
||||
.context("unable to get oneshot entry from bootloader interface")?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// Remove the oneshot entry from the bootloader interface.
|
||||
Self::VENDOR
|
||||
.remove("LoaderEntryOneShot")
|
||||
.context("unable to remove oneshot entry")?;
|
||||
|
||||
// Return the oneshot value.
|
||||
Ok(Some(value))
|
||||
}
|
||||
}
|
||||
46
crates/eficore/src/bootloader_interface/bitflags.rs
Normal file
46
crates/eficore/src/bootloader_interface/bitflags.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use bitflags::bitflags;
|
||||
|
||||
bitflags! {
|
||||
/// Feature bitflags for the bootloader interface.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct LoaderFeatures: u64 {
|
||||
/// Bootloader supports LoaderConfigTimeout.
|
||||
const ConfigTimeout = 1 << 0;
|
||||
/// Bootloader supports LoaderConfigTimeoutOneShot.
|
||||
const ConfigTimeoutOneShot = 1 << 1;
|
||||
/// Bootloader supports LoaderEntryDefault.
|
||||
const EntryDefault = 1 << 2;
|
||||
/// Bootloader supports LoaderEntryOneShot.
|
||||
const EntryOneShot = 1 << 3;
|
||||
/// Bootloader supports boot counting.
|
||||
const BootCounting = 1 << 4;
|
||||
/// Bootloader supports detection from XBOOTLDR partitions.
|
||||
const Xbootldr = 1 << 5;
|
||||
/// Bootloader supports the handling of random seeds.
|
||||
const RandomSeed = 1 << 6;
|
||||
/// Bootloader supports loading drivers.
|
||||
const LoadDriver = 1 << 7;
|
||||
/// Bootloader supports sort keys.
|
||||
const SortKey = 1 << 8;
|
||||
/// Bootloader supports saved entries.
|
||||
const SavedEntry = 1 << 9;
|
||||
/// Bootloader supports device trees.
|
||||
const DeviceTree = 1 << 10;
|
||||
/// Bootloader supports secure boot enroll.
|
||||
const SecureBootEnroll = 1 << 11;
|
||||
/// Bootloader retains the shim.
|
||||
const RetainShim = 1 << 12;
|
||||
/// Bootloader supports disabling the menu via the menu timeout variable.
|
||||
const MenuDisable = 1 << 13;
|
||||
/// Bootloader supports multi-profile UKI.
|
||||
const MultiProfileUki = 1 << 14;
|
||||
/// Bootloader reports URLs.
|
||||
const ReportUrl = 1 << 15;
|
||||
/// Bootloader supports type-1 UKIs.
|
||||
const Type1Uki = 1 << 16;
|
||||
/// Bootloader supports type-1 UKI urls.
|
||||
const Type1UkiUrl = 1 << 17;
|
||||
/// Bootloader indicates TPM2 active PCR banks.
|
||||
const Tpm2ActivePcrBanks = 1 << 18;
|
||||
}
|
||||
}
|
||||
58
crates/eficore/src/framebuffer.rs
Normal file
58
crates/eficore/src/framebuffer.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result};
|
||||
use uefi::proto::console::gop::{BltOp, BltPixel, BltRegion, GraphicsOutput};
|
||||
|
||||
/// Represents the EFI framebuffer.
|
||||
pub struct Framebuffer {
|
||||
/// The width of the framebuffer in pixels.
|
||||
width: usize,
|
||||
/// The height of the framebuffer in pixels.
|
||||
height: usize,
|
||||
/// The pixels of the framebuffer.
|
||||
pixels: Vec<BltPixel>,
|
||||
}
|
||||
|
||||
impl Framebuffer {
|
||||
/// Creates a new framebuffer of the specified `width` and `height`.
|
||||
pub fn new(width: usize, height: usize) -> Result<Self> {
|
||||
// Verify that the size is valid during multiplication.
|
||||
let size = width
|
||||
.checked_mul(height)
|
||||
.context("framebuffer size overflow")?;
|
||||
|
||||
// Initialize the pixel buffer with black pixels, with the verified size.
|
||||
let pixels = vec![BltPixel::new(0, 0, 0); size];
|
||||
|
||||
Ok(Framebuffer {
|
||||
width,
|
||||
height,
|
||||
pixels,
|
||||
})
|
||||
}
|
||||
|
||||
/// Mutably acquires a pixel of the framebuffer at the specified `x` and `y` coordinate.
|
||||
pub fn pixel(&mut self, x: usize, y: usize) -> Option<&mut BltPixel> {
|
||||
// Verify that the coordinates are within the bounds of the framebuffer.
|
||||
if x >= self.width || y >= self.height {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Calculate the index of the pixel safely, returning None if it overflows.
|
||||
let index = y.checked_mul(self.width)?.checked_add(x)?;
|
||||
// Return the pixel at the index. If the index is out of bounds, this will return None.
|
||||
self.pixels.get_mut(index)
|
||||
}
|
||||
|
||||
/// Blit the framebuffer to the specified `gop` [GraphicsOutput].
|
||||
pub fn blit(&self, gop: &mut GraphicsOutput) -> Result<()> {
|
||||
gop.blt(BltOp::BufferToVideo {
|
||||
buffer: &self.pixels,
|
||||
src: BltRegion::Full,
|
||||
dest: (0, 0),
|
||||
dims: (self.width, self.height),
|
||||
})
|
||||
.context("unable to blit framebuffer")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
26
crates/eficore/src/handle.rs
Normal file
26
crates/eficore/src/handle.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use anyhow::{Context, Result};
|
||||
use uefi::boot::SearchType;
|
||||
use uefi::{Guid, Handle};
|
||||
use uefi_raw::Status;
|
||||
|
||||
/// Find a handle that provides the specified `protocol`.
|
||||
pub fn find_handle(protocol: &Guid) -> Result<Option<Handle>> {
|
||||
// Locate the requested protocol handle.
|
||||
match uefi::boot::locate_handle_buffer(SearchType::ByProtocol(protocol)) {
|
||||
// If a handle is found, the protocol is available.
|
||||
Ok(handles) => Ok(if handles.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(handles[0])
|
||||
}),
|
||||
// If an error occurs, check if it is because the protocol is not available.
|
||||
// If so, return false. Otherwise, return the error.
|
||||
Err(error) => {
|
||||
if error.status() == Status::NOT_FOUND {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(error).context("unable to determine if the protocol is available")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
crates/eficore/src/lib.rs
Normal file
39
crates/eficore/src/lib.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! Sprout EFI Core.
|
||||
//! This crate provides tools for working with the EFI environment.
|
||||
#![no_std]
|
||||
extern crate alloc;
|
||||
|
||||
/// EFI handle helpers.
|
||||
pub mod handle;
|
||||
|
||||
/// Logging support for EFI applications.
|
||||
pub mod logger;
|
||||
|
||||
/// Disk partitioning support infrastructure.
|
||||
pub mod partition;
|
||||
|
||||
/// Path handling for UEFI.
|
||||
pub mod path;
|
||||
|
||||
/// platform: Integration or support code for specific hardware platforms.
|
||||
pub mod platform;
|
||||
|
||||
/// Secure Boot support.
|
||||
pub mod secure;
|
||||
|
||||
/// Support for the shim loader application that enables Secure Boot.
|
||||
pub mod shim;
|
||||
|
||||
/// String utilities.
|
||||
pub mod strings;
|
||||
|
||||
/// Implements support for the bootloader interface specification.
|
||||
pub mod bootloader_interface;
|
||||
/// Support code for the EFI framebuffer.
|
||||
pub mod framebuffer;
|
||||
/// Support code for the media loader protocol.
|
||||
pub mod media_loader;
|
||||
/// setup: Code that initializes the UEFI environment for Sprout.
|
||||
pub mod setup;
|
||||
/// Support code for EFI variables.
|
||||
pub mod variables;
|
||||
94
crates/eficore/src/logger.rs
Normal file
94
crates/eficore/src/logger.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! Based on: https://github.com/rust-osdev/uefi-rs/blob/main/uefi/src/helpers/logger.rs
|
||||
|
||||
use alloc::format;
|
||||
use core::fmt::Write;
|
||||
use core::ptr;
|
||||
use core::sync::atomic::{AtomicPtr, Ordering};
|
||||
use log::{Log, Record};
|
||||
use uefi::proto::console::text::Output;
|
||||
|
||||
/// The global logger object.
|
||||
static LOGGER: Logger = Logger::new();
|
||||
|
||||
/// Logging mechanism for Sprout.
|
||||
/// Must be initialized to be used, as we use atomic pointers to store the output to write to.
|
||||
pub struct Logger {
|
||||
writer: AtomicPtr<Output>,
|
||||
}
|
||||
|
||||
impl Default for Logger {
|
||||
/// Creates a default logger, which is uninitialized with an output.
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Logger {
|
||||
/// Create a new logger with an output not specified.
|
||||
/// This will cause the logger to not print anything until it is configured.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
writer: AtomicPtr::new(ptr::null_mut()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieves the pointer to the output.
|
||||
/// SAFETY: This pointer might be null, it should be checked before use.
|
||||
#[must_use]
|
||||
fn output(&self) -> *mut Output {
|
||||
self.writer.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Sets the output to write to.
|
||||
///
|
||||
/// # Safety
|
||||
/// This function is unsafe because the output is technically leaked and unmanaged.
|
||||
pub unsafe fn set_output(&self, output: *mut Output) {
|
||||
self.writer.store(output, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl Log for Logger {
|
||||
/// Enable the logger always.
|
||||
fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Log the specified `record` to the output if one is set.
|
||||
fn log(&self, record: &Record) {
|
||||
// Acquire the output. If one is not set, we do nothing.
|
||||
let Some(output) = (unsafe { self.output().as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Format the log message.
|
||||
let message = format!("{}", record.args());
|
||||
|
||||
// Iterate over every line, formatting the message and writing it to the output.
|
||||
for line in message.lines() {
|
||||
// The format writes the log level in front of every line of text.
|
||||
let _ = writeln!(output, "[{:>5}] {}", record.level(), line);
|
||||
}
|
||||
}
|
||||
|
||||
/// This log is not buffered, so flushing isn't required.
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
/// Initialize the logging environment, calling panic if something goes wrong.
|
||||
pub fn init() {
|
||||
// Retrieve the stdout handle and set it as the output for the global logger.
|
||||
uefi::system::with_stdout(|stdout| unsafe {
|
||||
// SAFETY: We are using the stdout handle to create a pointer to the output.
|
||||
// The handle is global and is guaranteed to be valid for the lifetime of the program.
|
||||
LOGGER.set_output(stdout);
|
||||
});
|
||||
|
||||
// Set the logger to the global logger.
|
||||
if let Err(error) = log::set_logger(&LOGGER) {
|
||||
panic!("unable to set logger: {}", error);
|
||||
}
|
||||
|
||||
// Set the max level to the level specified by the log features.
|
||||
log::set_max_level(log::STATIC_MAX_LEVEL);
|
||||
}
|
||||
278
crates/eficore/src/media_loader.rs
Normal file
278
crates/eficore/src/media_loader.rs
Normal file
@@ -0,0 +1,278 @@
|
||||
use alloc::boxed::Box;
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use core::ffi::c_void;
|
||||
use core::ptr;
|
||||
use uefi::proto::device_path::DevicePath;
|
||||
use uefi::proto::device_path::build::DevicePathBuilder;
|
||||
use uefi::proto::device_path::build::media::Vendor;
|
||||
use uefi::proto::media::load_file::LoadFile2;
|
||||
use uefi::{Guid, Handle};
|
||||
use uefi_raw::protocol::device_path::DevicePathProtocol;
|
||||
use uefi_raw::protocol::media::LoadFile2Protocol;
|
||||
use uefi_raw::{Boolean, Status};
|
||||
|
||||
pub mod constants;
|
||||
|
||||
/// The media loader protocol.
|
||||
#[derive(Debug)]
|
||||
#[repr(C)]
|
||||
struct MediaLoaderProtocol {
|
||||
/// This is the standard EFI LoadFile2 protocol.
|
||||
pub load_file: unsafe extern "efiapi" fn(
|
||||
this: *mut MediaLoaderProtocol,
|
||||
file_path: *const DevicePathProtocol,
|
||||
boot_policy: Boolean,
|
||||
buffer_size: *mut usize,
|
||||
buffer: *mut c_void,
|
||||
) -> Status,
|
||||
/// A pointer to a Box<[u8]> containing the data to load.
|
||||
pub address: *mut c_void,
|
||||
/// The length of the data to load.
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
/// Represents a media loader which has been registered in the UEFI stack.
|
||||
/// You MUST call [MediaLoaderHandle::unregister] when ready to unregister.
|
||||
/// [Drop] is not implemented for this type.
|
||||
pub struct MediaLoaderHandle {
|
||||
/// The handle of the media loader in the UEFI stack.
|
||||
handle: Handle,
|
||||
/// The protocol interface pointer.
|
||||
protocol: *mut MediaLoaderProtocol,
|
||||
/// The device path pointer.
|
||||
path: *mut DevicePath,
|
||||
}
|
||||
|
||||
impl MediaLoaderHandle {
|
||||
/// The behavior of this function is derived from how Linux calls it.
|
||||
///
|
||||
/// Linux calls this function by first passing a NULL `buffer`.
|
||||
/// We must set the size of the buffer it should allocate in `buffer_size`.
|
||||
/// The next call will pass a buffer of the right size, and we should copy
|
||||
/// data into that buffer, checking whether it is safe to copy based on
|
||||
/// the buffer size.
|
||||
///
|
||||
/// SAFETY: `this.address` and `this.length` are set by leaking a Box<[u8]>, so we can
|
||||
/// be sure their pointers are valid when this is called. The caller must call this function
|
||||
/// while inside UEFI boot services to ensure pointers are valid. Copying to `buffer` is
|
||||
/// assumed valid because the caller must ensure `buffer` is valid by function contract.
|
||||
unsafe extern "efiapi" fn load_file(
|
||||
this: *mut MediaLoaderProtocol,
|
||||
file_path: *const DevicePathProtocol,
|
||||
boot_policy: Boolean,
|
||||
buffer_size: *mut usize,
|
||||
buffer: *mut c_void,
|
||||
) -> Status {
|
||||
// Check if the pointers are non-null first.
|
||||
if this.is_null() || buffer_size.is_null() || file_path.is_null() {
|
||||
return Status::INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
// Boot policy must not be true, and if it is, that is special behavior that is irrelevant
|
||||
// for the media loader concept.
|
||||
if boot_policy == Boolean::TRUE {
|
||||
return Status::UNSUPPORTED;
|
||||
}
|
||||
|
||||
// SAFETY: Validated as safe because this is checked to be non-null. It is the caller's
|
||||
// responsibility to ensure that the right pointer is passed for [this].
|
||||
unsafe {
|
||||
// Check if the length and address are valid.
|
||||
if (*this).length == 0 || (*this).address.is_null() {
|
||||
return Status::NOT_FOUND;
|
||||
}
|
||||
|
||||
// Check if the buffer is large enough.
|
||||
// If it is not, we need to set the buffer size to the length of the data.
|
||||
// This is the way that Linux calls this function, to check the size to allocate
|
||||
// for the buffer that holds the data.
|
||||
if buffer.is_null() || *buffer_size < (*this).length {
|
||||
*buffer_size = (*this).length;
|
||||
return Status::BUFFER_TOO_SMALL;
|
||||
}
|
||||
|
||||
// Copy the data into the buffer.
|
||||
buffer.copy_from((*this).address, (*this).length);
|
||||
// Set the buffer size to the length of the data.
|
||||
*buffer_size = (*this).length;
|
||||
}
|
||||
|
||||
// We've successfully loaded the data.
|
||||
Status::SUCCESS
|
||||
}
|
||||
|
||||
/// Creates a new device path for the media loader based on a vendor `guid`.
|
||||
fn device_path(guid: Guid) -> Result<Box<DevicePath>> {
|
||||
// The buffer for the device path.
|
||||
let mut path = Vec::new();
|
||||
// Build a device path for the media loader with a vendor-specific guid.
|
||||
let path = DevicePathBuilder::with_vec(&mut path)
|
||||
.push(&Vendor {
|
||||
vendor_guid: guid,
|
||||
vendor_defined_data: &[],
|
||||
})
|
||||
.context("unable to produce device path")?
|
||||
.finalize()
|
||||
.context("unable to produce device path")?;
|
||||
// Convert the device path to a boxed device path.
|
||||
// This is safer than dealing with a pooled device path.
|
||||
Ok(path.to_boxed())
|
||||
}
|
||||
|
||||
/// Checks if the media loader is already registered with the UEFI stack.
|
||||
fn already_registered(guid: Guid) -> Result<bool> {
|
||||
// Acquire the device path for the media loader.
|
||||
let path = Self::device_path(guid)?;
|
||||
|
||||
let mut existing_path = path.as_ref();
|
||||
|
||||
// Locate the LoadFile2 protocol for the media loader based on the device path.
|
||||
let result = uefi::boot::locate_device_path::<LoadFile2>(&mut existing_path);
|
||||
|
||||
// If the result is okay, the media loader is already registered.
|
||||
if result.is_ok() {
|
||||
return Ok(true);
|
||||
} else if let Err(error) = result
|
||||
&& error.status() != Status::NOT_FOUND
|
||||
// If the error is not found, that means it's not registered.
|
||||
{
|
||||
bail!("unable to locate media loader device path: {}", error);
|
||||
}
|
||||
// The media loader is not registered.
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Registers the provided `data` with the UEFI stack as media loader.
|
||||
/// This uses a special device path that other EFI programs will look at
|
||||
/// to load the data from.
|
||||
pub fn register(guid: Guid, data: Box<[u8]>) -> Result<MediaLoaderHandle> {
|
||||
// Acquire the vendor device path for the media loader.
|
||||
let path = Self::device_path(guid)?;
|
||||
|
||||
// Check if the media loader is already registered.
|
||||
// If it is, we can't register it again safely.
|
||||
if Self::already_registered(guid)? {
|
||||
bail!("media loader already registered");
|
||||
}
|
||||
|
||||
// Leak the device path to pass it to the UEFI stack.
|
||||
let path = Box::leak(path);
|
||||
|
||||
// Install a protocol interface for the device path.
|
||||
// This ensures it can be located by other EFI programs.
|
||||
let primary_handle = unsafe {
|
||||
uefi::boot::install_protocol_interface(
|
||||
None,
|
||||
&DevicePathProtocol::GUID,
|
||||
path.as_ffi_ptr() as *mut c_void,
|
||||
)
|
||||
}
|
||||
.context("unable to install media loader device path handle")?;
|
||||
|
||||
// Leak the data we need to pass to the UEFI stack.
|
||||
let data = Box::leak(data);
|
||||
|
||||
// Allocate a new box for the protocol interface.
|
||||
let protocol = Box::new(MediaLoaderProtocol {
|
||||
load_file: Self::load_file,
|
||||
address: data.as_ptr() as *mut _,
|
||||
length: data.len(),
|
||||
});
|
||||
|
||||
// Leak the protocol interface to pass it to the UEFI stack.
|
||||
let protocol = Box::leak(protocol);
|
||||
|
||||
// Install a protocol interface for the load file protocol for the media loader protocol.
|
||||
let secondary_handle = unsafe {
|
||||
uefi::boot::install_protocol_interface(
|
||||
Some(primary_handle),
|
||||
&LoadFile2Protocol::GUID,
|
||||
// The UEFI API expects an opaque pointer here.
|
||||
protocol as *mut MediaLoaderProtocol as *mut c_void,
|
||||
)
|
||||
};
|
||||
|
||||
// If installing the second protocol interface failed, we need to clean up after ourselves.
|
||||
if secondary_handle.is_err() {
|
||||
// Uninstall the protocol interface for the device path protocol.
|
||||
// SAFETY: If we have reached this point, we know that the protocol is registered.
|
||||
// If this fails, we have no choice but to leak memory. The error will be shown
|
||||
// to the user, so at least they can see it. In most cases, catching this error
|
||||
// will exit, so leaking is safe.
|
||||
unsafe {
|
||||
uefi::boot::uninstall_protocol_interface(
|
||||
primary_handle,
|
||||
&DevicePathProtocol::GUID,
|
||||
path.as_ffi_ptr() as *mut c_void,
|
||||
)
|
||||
.context(
|
||||
"unable to uninstall media loader device path handle, this will leak memory",
|
||||
)?;
|
||||
}
|
||||
|
||||
// SAFETY: We know that the protocol is leaked, so we can safely take a reference to it.
|
||||
let protocol = unsafe { Box::from_raw(protocol) };
|
||||
// SAFETY: We know that the data is leaked, so we can safely take a reference to it.
|
||||
let data = unsafe { Box::from_raw(data) };
|
||||
// SAFETY: We know that the path is leaked, so we can safely take a reference to it.
|
||||
let path = unsafe { Box::from_raw(path) };
|
||||
|
||||
// Drop all the allocations explicitly to clarify the lifetime.
|
||||
drop(protocol);
|
||||
drop(data);
|
||||
drop(path);
|
||||
}
|
||||
|
||||
// If installing the second protocol interface failed, this will return the error.
|
||||
// We should have already cleaned up after ourselves, so this is safe.
|
||||
secondary_handle.context("unable to install media loader load file handle")?;
|
||||
|
||||
// Return a handle to the media loader.
|
||||
Ok(Self {
|
||||
handle: primary_handle,
|
||||
protocol,
|
||||
path,
|
||||
})
|
||||
}
|
||||
|
||||
/// Unregisters a media loader from the UEFI stack.
|
||||
/// This will free the memory allocated by the passed data.
|
||||
pub fn unregister(self) -> Result<()> {
|
||||
// SAFETY: We know that the media loader is registered if the handle is valid,
|
||||
// so we can safely uninstall it.
|
||||
// We should have allocated the pointers involved, so we can safely free them.
|
||||
unsafe {
|
||||
// Uninstall the protocol interface for the device path protocol.
|
||||
uefi::boot::uninstall_protocol_interface(
|
||||
self.handle,
|
||||
&DevicePathProtocol::GUID,
|
||||
self.path as *mut c_void,
|
||||
)
|
||||
.context("unable to uninstall media loader device path handle")?;
|
||||
|
||||
// Uninstall the protocol interface for the load file protocol.
|
||||
uefi::boot::uninstall_protocol_interface(
|
||||
self.handle,
|
||||
&LoadFile2Protocol::GUID,
|
||||
self.protocol as *mut _ as *mut c_void,
|
||||
)
|
||||
.context("unable to uninstall media loader load file handle")?;
|
||||
|
||||
// Retrieve a box for the device path and protocols.
|
||||
let path = Box::from_raw(self.path);
|
||||
let protocol = Box::from_raw(self.protocol);
|
||||
|
||||
// Retrieve a box for the data we passed in.
|
||||
let slice = ptr::slice_from_raw_parts_mut(protocol.address as *mut u8, protocol.length);
|
||||
let data = Box::from_raw(slice);
|
||||
|
||||
// Drop all the allocations explicitly, as we don't want to leak them.
|
||||
drop(path);
|
||||
drop(protocol);
|
||||
drop(data);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
20
crates/eficore/src/media_loader/constants.rs
Normal file
20
crates/eficore/src/media_loader/constants.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
/// These GUIDs are specific to Linux itself.
|
||||
pub mod linux {
|
||||
use uefi::{Guid, guid};
|
||||
|
||||
/// The device path GUID for the Linux EFI initrd.
|
||||
pub const LINUX_EFI_INITRD_MEDIA_GUID: Guid = guid!("5568e427-68fc-4f3d-ac74-ca555231cc68");
|
||||
}
|
||||
|
||||
/// These GUIDs were created by Edera to support Xen loading data
|
||||
/// from Sprout and other EFI bootloaders.
|
||||
pub mod xen {
|
||||
use uefi::{Guid, guid};
|
||||
|
||||
/// The device path GUID for the Xen EFI config.
|
||||
pub const XEN_EFI_CONFIG_MEDIA_GUID: Guid = guid!("bf61f458-a28e-46cd-93d7-07dac5e8cd66");
|
||||
/// The device path GUID for the Xen EFI kernel.
|
||||
pub const XEN_EFI_KERNEL_MEDIA_GUID: Guid = guid!("4010c8bf-6ced-40f5-a53f-e820aee8f34b");
|
||||
/// The device path GUID for the Xen EFI ramdisk.
|
||||
pub const XEN_EFI_RAMDISK_MEDIA_GUID: Guid = guid!("5db1fd01-c3cb-4812-b2ba-8791e52d4a89");
|
||||
}
|
||||
55
crates/eficore/src/partition.rs
Normal file
55
crates/eficore/src/partition.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use anyhow::{Context, Result};
|
||||
use uefi::Guid;
|
||||
use uefi::proto::device_path::DevicePath;
|
||||
use uefi::proto::media::partition::PartitionInfo;
|
||||
use uefi_raw::Status;
|
||||
|
||||
/// Represents the type of partition GUID that can be retrieved.
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub enum PartitionGuidForm {
|
||||
/// The partition GUID is the unique partition GUID.
|
||||
Partition,
|
||||
/// The partition GUID is the partition type GUID.
|
||||
PartitionType,
|
||||
}
|
||||
|
||||
/// Retrieve the partition / partition type GUID of the device root `path`.
|
||||
/// This only works on GPT partitions. If the root is not a GPT partition, None is returned.
|
||||
/// If the GUID is all zeros, this will return None.
|
||||
pub fn partition_guid(path: &DevicePath, form: PartitionGuidForm) -> Result<Option<Guid>> {
|
||||
// Clone the path so we can pass it to the UEFI stack.
|
||||
let path = path.to_boxed();
|
||||
let result = uefi::boot::locate_device_path::<PartitionInfo>(&mut &*path);
|
||||
let handle = match result {
|
||||
Ok(handle) => Ok(Some(handle)),
|
||||
Err(error) => {
|
||||
// If the error is NOT_FOUND or UNSUPPORTED, we can return None.
|
||||
// These are non-fatal errors.
|
||||
if error.status() == Status::NOT_FOUND || error.status() == Status::UNSUPPORTED {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
.context("unable to locate device path")?;
|
||||
|
||||
// If we have the handle, we can try to open the partition info protocol.
|
||||
if let Some(handle) = handle {
|
||||
// Open the partition info protocol.
|
||||
let partition_info = uefi::boot::open_protocol_exclusive::<PartitionInfo>(handle)
|
||||
.context("unable to open partition info protocol")?;
|
||||
// Find the unique partition GUID.
|
||||
// If this is not a GPT partition, this will produce None.
|
||||
Ok(partition_info
|
||||
.gpt_partition_entry()
|
||||
.map(|entry| match form {
|
||||
// Match the form of the partition GUID.
|
||||
PartitionGuidForm::Partition => entry.unique_partition_guid,
|
||||
PartitionGuidForm::PartitionType => entry.partition_type_guid.0,
|
||||
})
|
||||
.filter(|guid| !guid.is_zero()))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
174
crates/eficore/src/path.rs
Normal file
174
crates/eficore/src/path.rs
Normal file
@@ -0,0 +1,174 @@
|
||||
use alloc::borrow::ToOwned;
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result};
|
||||
use core::ops::Deref;
|
||||
use uefi::fs::{FileSystem, Path};
|
||||
use uefi::proto::device_path::text::{AllowShortcuts, DevicePathFromText, DisplayOnly};
|
||||
use uefi::proto::device_path::{DevicePath, PoolDevicePath};
|
||||
use uefi::proto::media::fs::SimpleFileSystem;
|
||||
use uefi::{CString16, Handle};
|
||||
|
||||
/// Represents the components of a resolved path.
|
||||
pub struct ResolvedPath {
|
||||
/// The root path of the resolved path. This is the device itself.
|
||||
/// For example, "PciRoot(0x0)/Pci(0x4,0x0)/NVMe(0x1,00-00-00-00-00-00-00-00)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)/"
|
||||
pub root_path: Box<DevicePath>,
|
||||
/// The subpath of the resolved path. This is the path to the file.
|
||||
/// For example, "\EFI\BOOT\BOOTX64.efi"
|
||||
pub sub_path: Box<DevicePath>,
|
||||
/// The full path of the resolved path. This is the safest path to use.
|
||||
/// For example, "PciRoot(0x0)/Pci(0x4,0x0)/NVMe(0x1,00-00-00-00-00-00-00-00)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)/\EFI\BOOT\BOOTX64.efi"
|
||||
pub full_path: Box<DevicePath>,
|
||||
/// The handle of the filesystem containing the path.
|
||||
/// This can be used to acquire a [SimpleFileSystem] protocol to read the file.
|
||||
pub filesystem_handle: Handle,
|
||||
}
|
||||
|
||||
impl ResolvedPath {
|
||||
/// Read the file specified by this path into a buffer and return it.
|
||||
pub fn read_file(&self) -> Result<Vec<u8>> {
|
||||
let fs = uefi::boot::open_protocol_exclusive::<SimpleFileSystem>(self.filesystem_handle)
|
||||
.context("unable to open filesystem protocol")?;
|
||||
let mut fs = FileSystem::new(fs);
|
||||
let path = self
|
||||
.sub_path
|
||||
.to_string(DisplayOnly(false), AllowShortcuts(false))?;
|
||||
let content = fs.read(Path::new(&path));
|
||||
content.context("unable to read file contents")
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a [CString16] contains a char `c`.
|
||||
/// We need to call to_string() because CString16 doesn't support `contains` with a char.
|
||||
fn cstring16_contains_char(string: &CString16, c: char) -> bool {
|
||||
string.to_string().contains(c)
|
||||
}
|
||||
|
||||
/// Parses the input `path` as a [DevicePath].
|
||||
/// Uses the [DevicePathFromText] protocol exclusively, and will fail if it cannot acquire the protocol.
|
||||
pub fn text_to_device_path(path: &str) -> Result<PoolDevicePath> {
|
||||
let path = CString16::try_from(path).context("unable to convert path to CString16")?;
|
||||
let device_path_from_text = uefi::boot::open_protocol_exclusive::<DevicePathFromText>(
|
||||
uefi::boot::get_handle_for_protocol::<DevicePathFromText>()
|
||||
.context("no device path from text protocol")?,
|
||||
)
|
||||
.context("unable to open device path from text protocol")?;
|
||||
|
||||
device_path_from_text
|
||||
.convert_text_to_device_path(&path)
|
||||
.context("unable to convert text to device path")
|
||||
}
|
||||
|
||||
/// Grabs the root part of the `path`.
|
||||
/// For example, given "PciRoot(0x0)/Pci(0x4,0x0)/NVMe(0x1,00-00-00-00-00-00-00-00)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)/\EFI\BOOT\BOOTX64.efi"
|
||||
/// it will give "PciRoot(0x0)/Pci(0x4,0x0)/NVMe(0x1,00-00-00-00-00-00-00-00)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)"
|
||||
pub fn device_path_root(path: &DevicePath) -> Result<String> {
|
||||
let mut path = path
|
||||
.node_iter()
|
||||
.filter_map(|item| {
|
||||
let item = item.to_string(DisplayOnly(false), AllowShortcuts(false));
|
||||
if item
|
||||
.as_ref()
|
||||
.map(|item| cstring16_contains_char(item, '('))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
Some(item.unwrap_or_default())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.map(|item| item.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
path.push('/');
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Grabs the part of the `path` after the root.
|
||||
/// For example, given "PciRoot(0x0)/Pci(0x4,0x0)/NVMe(0x1,00-00-00-00-00-00-00-00)/HD(1,MBR,0xBE1AFDFA,0x3F,0xFBFC1)/\EFI\BOOT\BOOTX64.efi"
|
||||
/// it will give "\EFI\BOOT\BOOTX64.efi"
|
||||
pub fn device_path_subpath(path: &DevicePath) -> Result<String> {
|
||||
let path = path
|
||||
.node_iter()
|
||||
.filter_map(|item| {
|
||||
let item = item.to_string(DisplayOnly(false), AllowShortcuts(false));
|
||||
if item
|
||||
.as_ref()
|
||||
.map(|item| cstring16_contains_char(item, '('))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(item.unwrap_or_default())
|
||||
}
|
||||
})
|
||||
.map(|item| item.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\\");
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Resolve a path specified by `input` to its various components.
|
||||
/// Uses `default_root_path` as the base root if one is not specified in the path.
|
||||
/// Returns [ResolvedPath] which contains the resolved components.
|
||||
pub fn resolve_path(default_root_path: Option<&DevicePath>, input: &str) -> Result<ResolvedPath> {
|
||||
let mut path = text_to_device_path(input).context("unable to convert text to path")?;
|
||||
let path_has_device = path
|
||||
.node_iter()
|
||||
.next()
|
||||
.map(|it| {
|
||||
it.to_string(DisplayOnly(false), AllowShortcuts(false))
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.map(|it| it.to_string().contains('('))
|
||||
.unwrap_or(false);
|
||||
if !path_has_device {
|
||||
let mut input = input.to_string();
|
||||
if !input.starts_with('\\') {
|
||||
input.insert(0, '\\');
|
||||
}
|
||||
|
||||
let default_root_path = default_root_path.context("unable to get default root path")?;
|
||||
|
||||
input.insert_str(
|
||||
0,
|
||||
device_path_root(default_root_path)
|
||||
.context("unable to get loaded image device root")?
|
||||
.as_str(),
|
||||
);
|
||||
path = text_to_device_path(input.as_str()).context("unable to convert text to path")?;
|
||||
}
|
||||
|
||||
let path = path.to_boxed();
|
||||
let root = device_path_root(path.as_ref()).context("unable to convert root to path")?;
|
||||
let root_path = text_to_device_path(root.as_str())
|
||||
.context("unable to convert root to path")?
|
||||
.to_boxed();
|
||||
let root_path = root_path.as_ref();
|
||||
|
||||
// locate_device_path modifies the path, so we need to clone it.
|
||||
let root_path_modifiable = root_path.to_owned();
|
||||
let handle = uefi::boot::locate_device_path::<SimpleFileSystem>(&mut &*root_path_modifiable)
|
||||
.context("unable to locate filesystem device path")?;
|
||||
let subpath = device_path_subpath(path.deref()).context("unable to get device subpath")?;
|
||||
Ok(ResolvedPath {
|
||||
root_path: root_path.to_boxed(),
|
||||
sub_path: text_to_device_path(subpath.as_str())?.to_boxed(),
|
||||
full_path: path,
|
||||
filesystem_handle: handle,
|
||||
})
|
||||
}
|
||||
|
||||
/// Read the contents of a file at the location specified with the `input` path.
|
||||
/// Internally, this uses [resolve_path] to resolve the path to its various components.
|
||||
/// [resolve_path] is passed the `default_root_path` which should specify a base root.
|
||||
///
|
||||
/// This acquires exclusive protocol access to the [SimpleFileSystem] protocol of the resolved
|
||||
/// filesystem handle, so care must be taken to call this function outside a scope with
|
||||
/// the filesystem handle protocol acquired.
|
||||
pub fn read_file_contents(default_root_path: Option<&DevicePath>, input: &str) -> Result<Vec<u8>> {
|
||||
let resolved = resolve_path(default_root_path, input)?;
|
||||
resolved.read_file()
|
||||
}
|
||||
4
crates/eficore/src/platform.rs
Normal file
4
crates/eficore/src/platform.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
/// Timer support.
|
||||
pub mod timer;
|
||||
/// TPM support.
|
||||
pub mod tpm;
|
||||
94
crates/eficore/src/platform/timer.rs
Normal file
94
crates/eficore/src/platform/timer.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
// Referenced https://github.com/sheroz/tick_counter (MIT license) as a baseline.
|
||||
// Architecturally modified to support UEFI and remove x86 (32-bit) support.
|
||||
|
||||
use core::time::Duration;
|
||||
|
||||
/// Support for aarch64 timers.
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub mod aarch64;
|
||||
|
||||
/// Support for x86_64 timers.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub mod x86_64;
|
||||
|
||||
/// The tick frequency of the platform.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TickFrequency {
|
||||
/// The platform provides the tick frequency.
|
||||
Hardware(u64),
|
||||
/// The tick frequency is measured internally.
|
||||
Measured(u64),
|
||||
}
|
||||
|
||||
impl TickFrequency {
|
||||
/// Acquire the tick frequency reported by the platform.
|
||||
fn ticks(&self) -> u64 {
|
||||
match self {
|
||||
TickFrequency::Hardware(frequency) => *frequency,
|
||||
TickFrequency::Measured(frequency) => *frequency,
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate the nanoseconds represented by a tick.
|
||||
fn nanos(&self) -> f64 {
|
||||
1.0e9_f64 / (self.ticks() as f64)
|
||||
}
|
||||
|
||||
/// Produce a duration from the provided elapsed `ticks` value.
|
||||
fn duration(&self, ticks: u64) -> Duration {
|
||||
let accuracy = self.nanos();
|
||||
let nanos = ticks as f64 * accuracy;
|
||||
Duration::from_nanos(nanos as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire the tick value reported by the platform.
|
||||
fn arch_ticks() -> u64 {
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
return aarch64::ticks();
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
return x86_64::ticks();
|
||||
}
|
||||
|
||||
/// Acquire the tick frequency reported by the platform.
|
||||
fn arch_frequency() -> TickFrequency {
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
let frequency = aarch64::frequency();
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
let frequency = x86_64::frequency();
|
||||
// If the frequency is 0, then something went very wrong and we should panic.
|
||||
if frequency.ticks() == 0 {
|
||||
panic!("timer frequency is zero");
|
||||
}
|
||||
frequency
|
||||
}
|
||||
|
||||
/// Platform timer that allows measurement of the elapsed time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PlatformTimer {
|
||||
/// The start tick value.
|
||||
start: u64,
|
||||
/// The tick frequency of the platform.
|
||||
frequency: TickFrequency,
|
||||
}
|
||||
|
||||
impl PlatformTimer {
|
||||
/// Start a platform timer at the current instant.
|
||||
pub fn start() -> Self {
|
||||
Self {
|
||||
start: arch_ticks(),
|
||||
frequency: arch_frequency(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the elapsed duration since the hardware started ticking upwards.
|
||||
pub fn elapsed_since_lifetime(&self) -> Duration {
|
||||
self.frequency.duration(arch_ticks())
|
||||
}
|
||||
|
||||
/// Measure the elapsed duration since the timer was started.
|
||||
pub fn elapsed_since_start(&self) -> Duration {
|
||||
let duration = arch_ticks().wrapping_sub(self.start);
|
||||
self.frequency.duration(duration)
|
||||
}
|
||||
}
|
||||
23
crates/eficore/src/platform/timer/aarch64.rs
Normal file
23
crates/eficore/src/platform/timer/aarch64.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use crate::platform::timer::TickFrequency;
|
||||
use core::arch::asm;
|
||||
|
||||
/// Reads the cntvct_el0 counter and returns the value.
|
||||
pub fn ticks() -> u64 {
|
||||
let counter: u64;
|
||||
unsafe {
|
||||
asm!("mrs x0, cntvct_el0", out("x0") counter);
|
||||
}
|
||||
counter
|
||||
}
|
||||
|
||||
/// Our frequency is provided by cntfrq_el0 on the platform.
|
||||
pub fn frequency() -> TickFrequency {
|
||||
let frequency: u64;
|
||||
unsafe {
|
||||
asm!(
|
||||
"mrs x0, cntfrq_el0",
|
||||
out("x0") frequency
|
||||
);
|
||||
}
|
||||
TickFrequency::Hardware(frequency)
|
||||
}
|
||||
29
crates/eficore/src/platform/timer/x86_64.rs
Normal file
29
crates/eficore/src/platform/timer/x86_64.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use crate::platform::timer::TickFrequency;
|
||||
use core::time::Duration;
|
||||
|
||||
/// We will measure the frequency of the timer based on 1000 microseconds.
|
||||
/// This will result in a call to BS->Stall(1000) in the end.
|
||||
const MEASURE_FREQUENCY_DURATION: Duration = Duration::from_micros(1000);
|
||||
|
||||
/// Read the number of ticks from the platform timer.
|
||||
pub fn ticks() -> u64 {
|
||||
// SAFETY: Reads the platform timer, which is safe in any context.
|
||||
unsafe { core::arch::x86_64::_rdtsc() }
|
||||
}
|
||||
|
||||
/// Measure the frequency of the platform timer.
|
||||
/// NOTE: Intentionally, we do not synchronize rdtsc during measurement to match systemd behavior.
|
||||
fn measure_frequency() -> u64 {
|
||||
let start = ticks();
|
||||
uefi::boot::stall(MEASURE_FREQUENCY_DURATION);
|
||||
let stop = ticks();
|
||||
let elapsed = stop.wrapping_sub(start) as f64;
|
||||
(elapsed / MEASURE_FREQUENCY_DURATION.as_secs_f64()) as u64
|
||||
}
|
||||
|
||||
/// Acquire the platform timer frequency.
|
||||
/// On x86_64, this is slightly expensive, so it should be done once.
|
||||
pub fn frequency() -> TickFrequency {
|
||||
let frequency = measure_frequency();
|
||||
TickFrequency::Measured(frequency)
|
||||
}
|
||||
129
crates/eficore/src/platform/tpm.rs
Normal file
129
crates/eficore/src/platform/tpm.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use anyhow::{Context, Result};
|
||||
use uefi::ResultExt;
|
||||
use uefi::boot::ScopedProtocol;
|
||||
use uefi::proto::tcg::PcrIndex;
|
||||
use uefi::proto::tcg::v2::{PcrEventInputs, Tcg};
|
||||
use uefi_raw::protocol::tcg::EventType;
|
||||
use uefi_raw::protocol::tcg::v2::{Tcg2HashLogExtendEventFlags, Tcg2Protocol, Tcg2Version};
|
||||
|
||||
/// Represents the platform TPM.
|
||||
pub struct PlatformTpm;
|
||||
|
||||
/// Represents an open TPM handle.
|
||||
pub struct TpmProtocolHandle {
|
||||
/// The version of the TPM protocol.
|
||||
version: Tcg2Version,
|
||||
/// The protocol itself.
|
||||
protocol: ScopedProtocol<Tcg>,
|
||||
}
|
||||
|
||||
impl TpmProtocolHandle {
|
||||
/// Construct a new [TpmProtocolHandle] from the `version` and `protocol`.
|
||||
pub fn new(version: Tcg2Version, protocol: ScopedProtocol<Tcg>) -> Self {
|
||||
Self { version, protocol }
|
||||
}
|
||||
|
||||
/// Access the version provided by the tcg2 protocol.
|
||||
pub fn version(&self) -> Tcg2Version {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// Access the protocol interface for tcg2.
|
||||
pub fn protocol(&mut self) -> &mut ScopedProtocol<Tcg> {
|
||||
&mut self.protocol
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformTpm {
|
||||
/// The PCR for measuring the bootloader configuration into.
|
||||
pub const PCR_BOOT_LOADER_CONFIG: PcrIndex = PcrIndex(5);
|
||||
|
||||
/// Acquire access to the TPM protocol handle, if possible.
|
||||
/// Returns None if TPM is not available.
|
||||
fn protocol() -> Result<Option<TpmProtocolHandle>> {
|
||||
// Attempt to acquire the TCG2 protocol handle. If it's not available, return None.
|
||||
let Some(handle) = crate::handle::find_handle(&Tcg2Protocol::GUID)
|
||||
.context("unable to determine tpm presence")?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// If we reach here, we've already validated that the handle
|
||||
// implements the TCG2 protocol.
|
||||
let mut protocol = uefi::boot::open_protocol_exclusive::<Tcg>(handle)
|
||||
.context("unable to open tcg2 protocol")?;
|
||||
|
||||
// Acquire the capabilities of the TPM.
|
||||
let capability = protocol
|
||||
.get_capability()
|
||||
.context("unable to get tcg2 boot service capability")?;
|
||||
|
||||
// If the TPM is not present, return None.
|
||||
if !capability.tpm_present() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// If the TPM is present, we need to determine the version of the TPM.
|
||||
let version = capability.protocol_version;
|
||||
|
||||
// We have a TPM, so return the protocol version and the protocol handle.
|
||||
Ok(Some(TpmProtocolHandle::new(version, protocol)))
|
||||
}
|
||||
|
||||
/// Determines whether the platform TPM is present.
|
||||
pub fn present() -> Result<bool> {
|
||||
Ok(PlatformTpm::protocol()?.is_some())
|
||||
}
|
||||
|
||||
/// Determine the number of active PCR banks on the TPM.
|
||||
/// If no TPM is available, this will return zero.
|
||||
pub fn active_pcr_banks() -> Result<u32> {
|
||||
// Acquire access to the TPM protocol handle.
|
||||
let Some(mut handle) = PlatformTpm::protocol()? else {
|
||||
return Ok(0);
|
||||
};
|
||||
|
||||
// Check if the TPM supports `GetActivePcrBanks`, and if it doesn't return zero.
|
||||
if (handle.version().major < 1)
|
||||
|| (handle.version().major == 1 && (handle.version().minor < 1))
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// The safe wrapper for this function will decode the bitmap.
|
||||
// Strictly speaking, it's not future-proof to re-encode that, but in practice it will work.
|
||||
let banks = handle
|
||||
.protocol()
|
||||
.get_active_pcr_banks()
|
||||
.context("unable to get active pcr banks")?;
|
||||
|
||||
// Return the number of active PCR banks.
|
||||
Ok(banks.bits())
|
||||
}
|
||||
|
||||
/// Log an event into the TPM pcr `pcr_index` with `buffer` as data. The `description`
|
||||
/// is used to describe what the event is.
|
||||
///
|
||||
/// If a TPM is not available, this will do nothing.
|
||||
pub fn log_event(pcr_index: PcrIndex, buffer: &[u8], description: &str) -> Result<()> {
|
||||
// Acquire access to the TPM protocol handle.
|
||||
let Some(mut handle) = PlatformTpm::protocol()? else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Encode the description as UTF-8.
|
||||
let description = description.as_bytes().to_vec();
|
||||
|
||||
// Construct an event input for the TPM.
|
||||
let event = PcrEventInputs::new_in_box(pcr_index, EventType::IPL, &description)
|
||||
.discard_errdata()
|
||||
.context("unable to construct pcr event inputs")?;
|
||||
|
||||
// Log the event into the TPM.
|
||||
handle
|
||||
.protocol()
|
||||
.hash_log_extend_event(Tcg2HashLogExtendEventFlags::empty(), buffer, &event)
|
||||
.context("unable to log event to tpm")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
14
crates/eficore/src/secure.rs
Normal file
14
crates/eficore/src/secure.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::variables::VariableController;
|
||||
use anyhow::Result;
|
||||
|
||||
/// Secure boot services.
|
||||
pub struct SecureBoot;
|
||||
|
||||
impl SecureBoot {
|
||||
/// Checks if Secure Boot is enabled on the system.
|
||||
/// This might fail if retrieving the variable fails in an irrecoverable way.
|
||||
pub fn enabled() -> Result<bool> {
|
||||
// The SecureBoot variable will tell us whether Secure Boot is enabled at all.
|
||||
VariableController::GLOBAL.get_bool("SecureBoot")
|
||||
}
|
||||
}
|
||||
14
crates/eficore/src/setup.rs
Normal file
14
crates/eficore/src/setup.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::logger;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// Initializes the UEFI environment.
|
||||
pub fn init() -> Result<()> {
|
||||
// Initialize the logger for Sprout.
|
||||
// NOTE: This cannot use a result type as errors need to be printed
|
||||
// using the logger, which is not initialized until this returns.
|
||||
logger::init();
|
||||
|
||||
// Initialize further UEFI internals.
|
||||
uefi::helpers::init().context("unable to initialize uefi environment")?;
|
||||
Ok(())
|
||||
}
|
||||
318
crates/eficore/src/shim.rs
Normal file
318
crates/eficore/src/shim.rs
Normal file
@@ -0,0 +1,318 @@
|
||||
use crate::path::ResolvedPath;
|
||||
use crate::secure::SecureBoot;
|
||||
use crate::shim::hook::SecurityHook;
|
||||
use crate::variables::{VariableClass, VariableController};
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::ToString;
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use core::ffi::c_void;
|
||||
use core::pin::Pin;
|
||||
use log::warn;
|
||||
use uefi::Handle;
|
||||
use uefi::boot::LoadImageSource;
|
||||
use uefi::proto::device_path::text::{AllowShortcuts, DisplayOnly};
|
||||
use uefi::proto::device_path::{DevicePath, FfiDevicePath};
|
||||
use uefi::proto::unsafe_protocol;
|
||||
use uefi_raw::table::runtime::VariableVendor;
|
||||
use uefi_raw::{Guid, Status, guid};
|
||||
|
||||
/// Security hook support.
|
||||
mod hook;
|
||||
|
||||
/// Support for the shim loader application for Secure Boot.
|
||||
pub struct ShimSupport;
|
||||
|
||||
/// Input to the shim mechanisms.
|
||||
pub enum ShimInput<'a> {
|
||||
/// Data loaded into a buffer and ready to be verified, owned.
|
||||
OwnedDataBuffer(Option<&'a ResolvedPath>, Pin<Box<[u8]>>),
|
||||
/// Data loaded into a buffer and ready to be verified.
|
||||
DataBuffer(Option<&'a ResolvedPath>, &'a [u8]),
|
||||
/// Low-level data buffer provided by the security hook.
|
||||
SecurityHookBuffer(Option<*const FfiDevicePath>, &'a [u8]),
|
||||
/// Low-level owned data buffer provided by the security hook.
|
||||
SecurityHookOwnedBuffer(Option<*const FfiDevicePath>, Pin<Box<[u8]>>),
|
||||
/// Low-level path provided by the security hook.
|
||||
SecurityHookPath(*const FfiDevicePath),
|
||||
/// Data is provided as a resolved path. We will need to load the data to verify it.
|
||||
/// The output will them return the loaded data.
|
||||
ResolvedPath(&'a ResolvedPath),
|
||||
}
|
||||
|
||||
impl<'a> ShimInput<'a> {
|
||||
/// Accesses the buffer behind the shim input, if available.
|
||||
pub fn buffer(&self) -> Option<&[u8]> {
|
||||
match self {
|
||||
ShimInput::OwnedDataBuffer(_, data) => Some(data),
|
||||
ShimInput::SecurityHookOwnedBuffer(_, data) => Some(data),
|
||||
ShimInput::SecurityHookBuffer(_, data) => Some(data),
|
||||
ShimInput::SecurityHookPath(_) => None,
|
||||
ShimInput::DataBuffer(_, data) => Some(data),
|
||||
ShimInput::ResolvedPath(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the full device path to the input.
|
||||
pub fn file_path(&self) -> Option<&DevicePath> {
|
||||
match self {
|
||||
ShimInput::OwnedDataBuffer(path, _) => path.as_ref().map(|it| it.full_path.as_ref()),
|
||||
ShimInput::DataBuffer(path, _) => path.as_ref().map(|it| it.full_path.as_ref()),
|
||||
ShimInput::SecurityHookBuffer(path, _) => {
|
||||
path.map(|it| unsafe { DevicePath::from_ffi_ptr(it) })
|
||||
}
|
||||
ShimInput::SecurityHookPath(path) => unsafe { Some(DevicePath::from_ffi_ptr(*path)) },
|
||||
ShimInput::ResolvedPath(path) => Some(path.full_path.as_ref()),
|
||||
ShimInput::SecurityHookOwnedBuffer(path, _) => {
|
||||
path.map(|it| unsafe { DevicePath::from_ffi_ptr(it) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this input into an owned data buffer, where the data is loaded.
|
||||
/// For ResolvedPath, this will read the file.
|
||||
pub fn into_owned_data_buffer(self) -> Result<ShimInput<'a>> {
|
||||
match self {
|
||||
ShimInput::OwnedDataBuffer(root, data) => Ok(ShimInput::OwnedDataBuffer(root, data)),
|
||||
|
||||
ShimInput::DataBuffer(root, data) => Ok(ShimInput::OwnedDataBuffer(
|
||||
root,
|
||||
Box::into_pin(data.to_vec().into_boxed_slice()),
|
||||
)),
|
||||
|
||||
ShimInput::SecurityHookPath(ffi_path) => {
|
||||
// Acquire the file path.
|
||||
let Some(path) = self.file_path() else {
|
||||
bail!("unable to convert security hook path to device path");
|
||||
};
|
||||
// Convert the underlying path to a string.
|
||||
let path = path
|
||||
.to_string(DisplayOnly(false), AllowShortcuts(false))
|
||||
.context("unable to convert device path to string")?;
|
||||
let path = crate::path::resolve_path(None, &path.to_string())
|
||||
.context("unable to resolve path")?;
|
||||
// Read the file path.
|
||||
let data = path.read_file()?;
|
||||
Ok(ShimInput::SecurityHookOwnedBuffer(
|
||||
Some(ffi_path),
|
||||
Box::into_pin(data.to_vec().into_boxed_slice()),
|
||||
))
|
||||
}
|
||||
|
||||
ShimInput::SecurityHookBuffer(_, _) => {
|
||||
bail!("unable to convert security hook buffer to owned data buffer")
|
||||
}
|
||||
|
||||
ShimInput::ResolvedPath(path) => {
|
||||
// Read the file path.
|
||||
let data = path.read_file()?;
|
||||
Ok(ShimInput::OwnedDataBuffer(
|
||||
Some(path),
|
||||
Box::into_pin(data.to_vec().into_boxed_slice()),
|
||||
))
|
||||
}
|
||||
|
||||
ShimInput::SecurityHookOwnedBuffer(path, data) => {
|
||||
Ok(ShimInput::SecurityHookOwnedBuffer(path, data))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output of the shim verification function.
|
||||
/// Since the shim needs to load the data from disk, we will optimize by using that as the data
|
||||
/// to actually boot.
|
||||
pub enum ShimVerificationOutput {
|
||||
/// The verification failed.
|
||||
VerificationFailed(Status),
|
||||
/// The data provided to the verifier was already a buffer.
|
||||
VerifiedDataNotLoaded,
|
||||
/// Verifying the data resulted in loading the data from the source.
|
||||
/// This contains the data that was loaded, so it won't need to be loaded again.
|
||||
VerifiedDataBuffer(Vec<u8>),
|
||||
}
|
||||
|
||||
/// The shim lock protocol as defined by the shim loader application.
|
||||
#[unsafe_protocol(ShimSupport::SHIM_LOCK_GUID)]
|
||||
struct ShimLockProtocol {
|
||||
/// Verify the data in `buffer` with the size `buffer_size` to determine if it is valid.
|
||||
/// NOTE: On x86_64, this function uses SYSV calling conventions. On aarch64 it uses the
|
||||
/// efiapi calling convention. This is truly wild, but you can verify it yourself by
|
||||
/// looking at: https://github.com/rhboot/shim/blob/15.8/shim.h#L207-L212
|
||||
/// There is no calling convention declared like there should be.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub shim_verify: unsafe extern "sysv64" fn(buffer: *const c_void, buffer_size: u32) -> Status,
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub shim_verify: unsafe extern "efiapi" fn(buffer: *const c_void, buffer_size: u32) -> Status,
|
||||
/// Unused function that is defined by the shim.
|
||||
_generate_header: *mut c_void,
|
||||
/// Unused function that is defined by the shim.
|
||||
_read_header: *mut c_void,
|
||||
}
|
||||
|
||||
impl ShimSupport {
|
||||
/// Variable controller for the shim lock.
|
||||
const SHIM_LOCK_VARIABLES: VariableController =
|
||||
VariableController::new(VariableVendor(Self::SHIM_LOCK_GUID));
|
||||
|
||||
/// GUID for the shim lock protocol.
|
||||
const SHIM_LOCK_GUID: Guid = guid!("605dab50-e046-4300-abb6-3dd810dd8b23");
|
||||
/// GUID for the shim image loader protocol.
|
||||
const SHIM_IMAGE_LOADER_GUID: Guid = guid!("1f492041-fadb-4e59-9e57-7cafe73a55ab");
|
||||
|
||||
/// Determines whether the shim is loaded.
|
||||
pub fn loaded() -> Result<bool> {
|
||||
Ok(crate::handle::find_handle(&Self::SHIM_LOCK_GUID)
|
||||
.context("unable to find shim lock protocol")?
|
||||
.is_some())
|
||||
}
|
||||
|
||||
/// Determines whether the shim loader is available.
|
||||
pub fn loader_available() -> Result<bool> {
|
||||
Ok(crate::handle::find_handle(&Self::SHIM_IMAGE_LOADER_GUID)
|
||||
.context("unable to find shim image loader protocol")?
|
||||
.is_some())
|
||||
}
|
||||
|
||||
/// Use the shim to validate the `input`, returning [ShimVerificationOutput] when complete.
|
||||
pub fn verify(input: ShimInput) -> Result<ShimVerificationOutput> {
|
||||
// Acquire the handle to the shim lock protocol.
|
||||
let handle = crate::handle::find_handle(&Self::SHIM_LOCK_GUID)
|
||||
.context("unable to find shim lock protocol")?
|
||||
.ok_or_else(|| anyhow!("unable to find shim lock protocol"))?;
|
||||
// Acquire the protocol exclusively to the shim lock.
|
||||
let protocol = uefi::boot::open_protocol_exclusive::<ShimLockProtocol>(handle)
|
||||
.context("unable to open shim lock protocol")?;
|
||||
|
||||
// If the input type is a device path, we need to load the data.
|
||||
let maybe_loaded_data = match input {
|
||||
ShimInput::OwnedDataBuffer(_, _data) => {
|
||||
bail!("owned data buffer is not supported in the verification function");
|
||||
}
|
||||
ShimInput::SecurityHookBuffer(_, _) => None,
|
||||
ShimInput::SecurityHookOwnedBuffer(_, _) => None,
|
||||
ShimInput::DataBuffer(_, _) => None,
|
||||
ShimInput::ResolvedPath(path) => Some(path.read_file()?),
|
||||
ShimInput::SecurityHookPath(_) => None,
|
||||
};
|
||||
|
||||
// Convert the input to a buffer.
|
||||
// If the input provides the data buffer, we will use that.
|
||||
// Otherwise, we will use the data loaded by this function.
|
||||
let buffer = match &input {
|
||||
ShimInput::OwnedDataBuffer(_root, data) => data,
|
||||
ShimInput::DataBuffer(_root, data) => *data,
|
||||
ShimInput::ResolvedPath(_path) => maybe_loaded_data
|
||||
.as_deref()
|
||||
.context("expected data buffer to be loaded already")?,
|
||||
ShimInput::SecurityHookBuffer(_, data) => data,
|
||||
ShimInput::SecurityHookOwnedBuffer(_, data) => data,
|
||||
ShimInput::SecurityHookPath(_) => {
|
||||
bail!("security hook path input not supported in the verification function")
|
||||
}
|
||||
};
|
||||
|
||||
// Check if the buffer is too large to verify.
|
||||
if buffer.len() > u32::MAX as usize {
|
||||
bail!("buffer is too large to verify with shim lock protocol");
|
||||
}
|
||||
|
||||
// Call the shim verify function.
|
||||
// SAFETY: The shim verify function is specified by the shim lock protocol.
|
||||
// Calling this function is considered safe because the shim verify function is
|
||||
// guaranteed to be defined by the environment if we are able to acquire the protocol.
|
||||
let status = unsafe {
|
||||
(protocol.shim_verify)(buffer.as_ptr() as *const c_void, buffer.len() as u32)
|
||||
};
|
||||
|
||||
// If the verification failed, return the verification failure output.
|
||||
if !status.is_success() {
|
||||
return Ok(ShimVerificationOutput::VerificationFailed(status));
|
||||
}
|
||||
|
||||
// If verification succeeded, return the validation output,
|
||||
// which might include the loaded data.
|
||||
Ok(maybe_loaded_data
|
||||
.map(ShimVerificationOutput::VerifiedDataBuffer)
|
||||
.unwrap_or(ShimVerificationOutput::VerifiedDataNotLoaded))
|
||||
}
|
||||
|
||||
/// Load the image specified by the `input` and returns an image handle.
|
||||
pub fn load(current_image: Handle, input: ShimInput) -> Result<Handle> {
|
||||
// Determine whether Secure Boot is enabled.
|
||||
let secure_boot =
|
||||
SecureBoot::enabled().context("unable to determine if secure boot is enabled")?;
|
||||
|
||||
// Determine whether the shim is loaded.
|
||||
let shim_loaded = Self::loaded().context("unable to determine if shim is loaded")?;
|
||||
|
||||
// Determine whether the shim loader is available.
|
||||
let shim_loader_available =
|
||||
Self::loader_available().context("unable to determine if shim loader is available")?;
|
||||
|
||||
// Determines whether LoadImage in Boot Services must be patched.
|
||||
// Version 16 of the shim doesn't require extra effort to load Secure Boot binaries.
|
||||
// If the image loader is installed, we can skip over the security hook.
|
||||
let requires_security_hook = secure_boot && shim_loaded && !shim_loader_available;
|
||||
|
||||
// If the security hook is required, we will bail for now.
|
||||
if requires_security_hook {
|
||||
// Install the security hook, if possible. If it's not, this is necessary to continue,
|
||||
// so we should bail.
|
||||
let installed = SecurityHook::install().context("unable to install security hook")?;
|
||||
if !installed {
|
||||
bail!("unable to install security hook required for this platform");
|
||||
}
|
||||
}
|
||||
|
||||
// If the shim is loaded, we will need to retain the shim protocol to allow
|
||||
// loading multiple images.
|
||||
if shim_loaded {
|
||||
// Retain the shim protocol after loading the image.
|
||||
Self::retain()?;
|
||||
}
|
||||
|
||||
// Converts the shim input to an owned data buffer.
|
||||
let input = input
|
||||
.into_owned_data_buffer()
|
||||
.context("unable to convert input to loaded data buffer")?;
|
||||
|
||||
// Constructs a LoadImageSource from the input.
|
||||
let source = LoadImageSource::FromBuffer {
|
||||
buffer: input.buffer().context("unable to get buffer from input")?,
|
||||
file_path: input.file_path(),
|
||||
};
|
||||
|
||||
// Loads the image using Boot Services LoadImage function.
|
||||
let result = uefi::boot::load_image(current_image, source).context("unable to load image");
|
||||
|
||||
// If the security override is required, we will uninstall the security hook.
|
||||
if requires_security_hook {
|
||||
let uninstall_result = SecurityHook::uninstall();
|
||||
// Ensure we don't mask load image errors if uninstalling fails.
|
||||
if result.is_err()
|
||||
&& let Err(uninstall_error) = &uninstall_result
|
||||
{
|
||||
// Warn on the error since the load image error is more important.
|
||||
warn!("unable to uninstall security hook: {}", uninstall_error);
|
||||
} else {
|
||||
// Otherwise, ensure we handle the original uninstallation result.
|
||||
uninstall_result?;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Set the ShimRetainProtocol variable to indicate that shim should retain the protocols
|
||||
/// for the full lifetime of boot services.
|
||||
pub fn retain() -> Result<()> {
|
||||
Self::SHIM_LOCK_VARIABLES
|
||||
.set_bool(
|
||||
"ShimRetainProtocol",
|
||||
true,
|
||||
VariableClass::BootAndRuntimeTemporary,
|
||||
)
|
||||
.context("unable to retain shim protocol")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
266
crates/eficore/src/shim/hook.rs
Normal file
266
crates/eficore/src/shim/hook.rs
Normal file
@@ -0,0 +1,266 @@
|
||||
use crate::shim::{ShimInput, ShimSupport, ShimVerificationOutput};
|
||||
use anyhow::{Context, Result};
|
||||
use core::slice;
|
||||
use log::warn;
|
||||
use spin::{Lazy, Mutex};
|
||||
use uefi::proto::device_path::FfiDevicePath;
|
||||
use uefi::proto::unsafe_protocol;
|
||||
use uefi::{Guid, guid};
|
||||
use uefi_raw::Status;
|
||||
|
||||
/// GUID for the EFI_SECURITY_ARCH protocol.
|
||||
const SECURITY_ARCH_GUID: Guid = guid!("a46423e3-4617-49f1-b9ff-d1bfa9115839");
|
||||
/// GUID for the EFI_SECURITY_ARCH2 protocol.
|
||||
const SECURITY_ARCH2_GUID: Guid = guid!("94ab2f58-1438-4ef1-9152-18941a3a0e68");
|
||||
|
||||
/// EFI_SECURITY_ARCH protocol definition.
|
||||
#[unsafe_protocol(SECURITY_ARCH_GUID)]
|
||||
pub struct SecurityArchProtocol {
|
||||
/// Determines the file authentication state.
|
||||
pub file_authentication_state: unsafe extern "efiapi" fn(
|
||||
this: *const SecurityArchProtocol,
|
||||
status: u32,
|
||||
path: *const FfiDevicePath,
|
||||
) -> Status,
|
||||
}
|
||||
|
||||
/// EFI_SECURITY_ARCH2 protocol definition.
|
||||
#[unsafe_protocol(SECURITY_ARCH2_GUID)]
|
||||
pub struct SecurityArch2Protocol {
|
||||
/// Determines the file authentication.
|
||||
pub file_authentication: unsafe extern "efiapi" fn(
|
||||
this: *const SecurityArch2Protocol,
|
||||
path: *const FfiDevicePath,
|
||||
file_buffer: *const u8,
|
||||
file_size: usize,
|
||||
boot_policy: bool,
|
||||
) -> Status,
|
||||
}
|
||||
|
||||
/// Global state for the security hook.
|
||||
struct SecurityHookState {
|
||||
original_hook: SecurityArchProtocol,
|
||||
original_hook2: SecurityArch2Protocol,
|
||||
}
|
||||
|
||||
/// Global state for the security hook.
|
||||
/// This is messy, but it is safe given the mutex.
|
||||
static GLOBAL_HOOK_STATE: Lazy<Mutex<Option<SecurityHookState>>> = Lazy::new(|| Mutex::new(None));
|
||||
|
||||
/// Security hook helper.
|
||||
pub struct SecurityHook;
|
||||
|
||||
impl SecurityHook {
|
||||
/// Shared verifier logic for both hook types.
|
||||
#[must_use]
|
||||
fn verify(input: ShimInput) -> bool {
|
||||
// Verify the input and convert the result to a status.
|
||||
let status = match ShimSupport::verify(input) {
|
||||
Ok(output) => match output {
|
||||
// If the verification failed, return the access-denied status.
|
||||
ShimVerificationOutput::VerificationFailed(status) => status,
|
||||
// If the verification succeeded, return the success status.
|
||||
ShimVerificationOutput::VerifiedDataNotLoaded => Status::SUCCESS,
|
||||
ShimVerificationOutput::VerifiedDataBuffer(_) => Status::SUCCESS,
|
||||
},
|
||||
|
||||
// If an error occurs, log the error since we can't return a better error.
|
||||
// Then return the access-denied status.
|
||||
Err(error) => {
|
||||
warn!("unable to verify image: {}", error);
|
||||
Status::ACCESS_DENIED
|
||||
}
|
||||
};
|
||||
|
||||
// If the status is not a success, log the status.
|
||||
if !status.is_success() {
|
||||
warn!("shim verification failed: {}", status);
|
||||
}
|
||||
// Return whether the status is a success.
|
||||
// If it's not a success, the original hook should be called.
|
||||
status.is_success()
|
||||
}
|
||||
|
||||
/// File authentication state verifier for the EFI_SECURITY_ARCH protocol.
|
||||
/// Takes the `path` and determines the verification.
|
||||
unsafe extern "efiapi" fn arch_file_authentication_state(
|
||||
this: *const SecurityArchProtocol,
|
||||
status: u32,
|
||||
path: *const FfiDevicePath,
|
||||
) -> Status {
|
||||
// Verify the path is not null.
|
||||
if path.is_null() {
|
||||
return Status::INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
// Construct a shim input from the path.
|
||||
let input = ShimInput::SecurityHookPath(path);
|
||||
|
||||
// Convert the input to an owned data buffer.
|
||||
let input = match input.into_owned_data_buffer() {
|
||||
Ok(input) => input,
|
||||
// If an error occurs, log the error and return the not found status.
|
||||
Err(error) => {
|
||||
warn!("unable to read data to be authenticated: {}", error);
|
||||
return Status::NOT_FOUND;
|
||||
}
|
||||
};
|
||||
|
||||
// Verify the input, if it fails, call the original hook.
|
||||
if !Self::verify(input) {
|
||||
// Acquire the global hook state to grab the original hook.
|
||||
let function = match GLOBAL_HOOK_STATE.lock().as_ref() {
|
||||
// The hook state is available, so we can acquire the original hook.
|
||||
Some(state) => state.original_hook.file_authentication_state,
|
||||
|
||||
// The hook state is not available, so we can't call the original hook.
|
||||
None => {
|
||||
warn!("global hook state is not available, unable to call original hook");
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
};
|
||||
|
||||
// Call the original hook function to see what it reports.
|
||||
// SAFETY: This function is safe to call as it is stored by us and is required
|
||||
// in the UEFI specification.
|
||||
unsafe { function(this, status, path) }
|
||||
} else {
|
||||
Status::SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
/// File authentication verifier for the EFI_SECURITY_ARCH2 protocol.
|
||||
/// Takes the `path` and a file buffer to determine the verification.
|
||||
unsafe extern "efiapi" fn arch2_file_authentication(
|
||||
this: *const SecurityArch2Protocol,
|
||||
path: *const FfiDevicePath,
|
||||
file_buffer: *const u8,
|
||||
file_size: usize,
|
||||
boot_policy: bool,
|
||||
) -> Status {
|
||||
// Verify the path and file buffer are not null.
|
||||
if path.is_null() || file_buffer.is_null() {
|
||||
return Status::INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
// If the boot policy is true, we can't continue as we don't support that.
|
||||
if boot_policy {
|
||||
return Status::INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
// Construct a slice out of the file buffer and size.
|
||||
let buffer = unsafe { slice::from_raw_parts(file_buffer, file_size) };
|
||||
|
||||
// Construct a shim input from the path.
|
||||
let input = ShimInput::SecurityHookBuffer(Some(path), buffer);
|
||||
|
||||
// Verify the input, if it fails, call the original hook.
|
||||
if !Self::verify(input) {
|
||||
// Acquire the global hook state to grab the original hook.
|
||||
let function = match GLOBAL_HOOK_STATE.lock().as_ref() {
|
||||
// The hook state is available, so we can acquire the original hook.
|
||||
Some(state) => state.original_hook2.file_authentication,
|
||||
|
||||
// The hook state is not available, so we can't call the original hook.
|
||||
None => {
|
||||
warn!("global hook state is not available, unable to call original hook");
|
||||
return Status::LOAD_ERROR;
|
||||
}
|
||||
};
|
||||
|
||||
// Call the original hook function to see what it reports.
|
||||
// SAFETY: This function is safe to call as it is stored by us and is required
|
||||
// in the UEFI specification.
|
||||
unsafe { function(this, path, file_buffer, file_size, boot_policy) }
|
||||
} else {
|
||||
Status::SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the security hook if needed.
|
||||
pub fn install() -> Result<bool> {
|
||||
// Find the security arch protocol. If we can't find it, we will return false.
|
||||
let Some(hook_arch) = crate::handle::find_handle(&SECURITY_ARCH_GUID)
|
||||
.context("unable to check security arch existence")?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
// Find the security arch2 protocol. If we can't find it, we will return false.
|
||||
let Some(hook_arch2) = crate::handle::find_handle(&SECURITY_ARCH2_GUID)
|
||||
.context("unable to check security arch2 existence")?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
// Open the security arch protocol.
|
||||
let mut arch_protocol =
|
||||
uefi::boot::open_protocol_exclusive::<SecurityArchProtocol>(hook_arch)
|
||||
.context("unable to open security arch protocol")?;
|
||||
|
||||
// Open the security arch2 protocol.
|
||||
let mut arch_protocol2 =
|
||||
uefi::boot::open_protocol_exclusive::<SecurityArch2Protocol>(hook_arch2)
|
||||
.context("unable to open security arch2 protocol")?;
|
||||
|
||||
// Construct the global state to store.
|
||||
let state = SecurityHookState {
|
||||
original_hook: SecurityArchProtocol {
|
||||
file_authentication_state: arch_protocol.file_authentication_state,
|
||||
},
|
||||
original_hook2: SecurityArch2Protocol {
|
||||
file_authentication: arch_protocol2.file_authentication,
|
||||
},
|
||||
};
|
||||
|
||||
// Acquire the lock to the global state and replace it.
|
||||
let mut global_state = GLOBAL_HOOK_STATE.lock();
|
||||
global_state.replace(state);
|
||||
|
||||
// Install the hooks into the UEFI stack.
|
||||
arch_protocol.file_authentication_state = Self::arch_file_authentication_state;
|
||||
arch_protocol2.file_authentication = Self::arch2_file_authentication;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Uninstalls the global security hook, if installed.
|
||||
pub fn uninstall() -> Result<()> {
|
||||
// Find the security arch protocol. If we can't find it, we will do nothing.
|
||||
let Some(hook_arch) = crate::handle::find_handle(&SECURITY_ARCH_GUID)
|
||||
.context("unable to check security arch existence")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Find the security arch2 protocol. If we can't find it, we will do nothing.
|
||||
let Some(hook_arch2) = crate::handle::find_handle(&SECURITY_ARCH2_GUID)
|
||||
.context("unable to check security arch2 existence")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Open the security arch protocol.
|
||||
let mut arch_protocol =
|
||||
uefi::boot::open_protocol_exclusive::<SecurityArchProtocol>(hook_arch)
|
||||
.context("unable to open security arch protocol")?;
|
||||
|
||||
// Open the security arch2 protocol.
|
||||
let mut arch_protocol2 =
|
||||
uefi::boot::open_protocol_exclusive::<SecurityArch2Protocol>(hook_arch2)
|
||||
.context("unable to open security arch2 protocol")?;
|
||||
|
||||
// Acquire the lock to the global state.
|
||||
let mut global_state = GLOBAL_HOOK_STATE.lock();
|
||||
|
||||
// Take the state and replace the original functions.
|
||||
let Some(state) = global_state.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Reinstall the original functions.
|
||||
arch_protocol.file_authentication_state = state.original_hook.file_authentication_state;
|
||||
arch_protocol2.file_authentication = state.original_hook2.file_authentication;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
22
crates/eficore/src/strings.rs
Normal file
22
crates/eficore/src/strings.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use uefi::CString16;
|
||||
|
||||
/// Convert a byte slice into a CString16.
|
||||
pub fn utf16_bytes_to_cstring16(bytes: &[u8]) -> Result<CString16> {
|
||||
// Validate the input bytes are the right length.
|
||||
if !bytes.len().is_multiple_of(2) {
|
||||
bail!("utf16 bytes must be a multiple of 2");
|
||||
}
|
||||
|
||||
// Convert the bytes to UTF-16 data.
|
||||
let data = bytes
|
||||
// Chunk everything into two bytes.
|
||||
.chunks_exact(2)
|
||||
// Reinterpret the bytes as u16 little-endian.
|
||||
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
|
||||
// Collect the result into a vector.
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
CString16::try_from(data).context("unable to convert utf16 bytes to CString16")
|
||||
}
|
||||
157
crates/eficore/src/variables.rs
Normal file
157
crates/eficore/src/variables.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
use crate::strings;
|
||||
use alloc::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
use anyhow::{Context, Result};
|
||||
use log::warn;
|
||||
use uefi::{CString16, guid};
|
||||
use uefi_raw::Status;
|
||||
use uefi_raw::table::runtime::{VariableAttributes, VariableVendor};
|
||||
|
||||
/// The classification of a variable.
|
||||
/// This is an abstraction over various variable attributes.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum VariableClass {
|
||||
/// The variable is available in Boot Services and Runtime Services and is not persistent.
|
||||
BootAndRuntimeTemporary,
|
||||
}
|
||||
|
||||
impl VariableClass {
|
||||
/// The [VariableAttributes] for this classification.
|
||||
fn attributes(&self) -> VariableAttributes {
|
||||
match self {
|
||||
VariableClass::BootAndRuntimeTemporary => {
|
||||
VariableAttributes::BOOTSERVICE_ACCESS | VariableAttributes::RUNTIME_ACCESS
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides access to a particular set of vendor variables.
|
||||
pub struct VariableController {
|
||||
/// The GUID of the vendor.
|
||||
vendor: VariableVendor,
|
||||
}
|
||||
|
||||
impl VariableController {
|
||||
/// Global variables.
|
||||
pub const GLOBAL: VariableController = VariableController::new(VariableVendor(guid!(
|
||||
"8be4df61-93ca-11d2-aa0d-00e098032b8c"
|
||||
)));
|
||||
|
||||
/// Create a new [VariableController] for the `vendor`.
|
||||
pub const fn new(vendor: VariableVendor) -> Self {
|
||||
Self { vendor }
|
||||
}
|
||||
|
||||
/// Convert `key` to a variable name as a CString16.
|
||||
fn name(key: &str) -> Result<CString16> {
|
||||
CString16::try_from(key).context("unable to convert variable name to CString16")
|
||||
}
|
||||
|
||||
/// Retrieve the cstr16 value specified by the `key`.
|
||||
/// Returns None if the value isn't set.
|
||||
/// If the value is not decodable, we will return None and log a warning.
|
||||
pub fn get_cstr16(&self, key: &str) -> Result<Option<String>> {
|
||||
let name = Self::name(key)?;
|
||||
|
||||
// Retrieve the variable data, handling variable not existing as None.
|
||||
match uefi::runtime::get_variable_boxed(&name, &self.vendor) {
|
||||
Ok((data, _)) => {
|
||||
// Try to decode UTF-16 bytes to a CString16.
|
||||
match strings::utf16_bytes_to_cstring16(&data) {
|
||||
Ok(value) => {
|
||||
// We have a value, so return the UTF-8 value.
|
||||
Ok(Some(value.to_string()))
|
||||
}
|
||||
|
||||
Err(error) => {
|
||||
// We encountered an error, so warn and return None.
|
||||
warn!("efi variable '{}' is not valid UTF-16: {}", key, error);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(error) => {
|
||||
// If the variable does not exist, we will return None.
|
||||
if error.status() == Status::NOT_FOUND {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(error).with_context(|| format!("unable to get efi variable {}", key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve a boolean value specified by the `key`.
|
||||
pub fn get_bool(&self, key: &str) -> Result<bool> {
|
||||
let name = Self::name(key)?;
|
||||
|
||||
// Retrieve the variable data, handling variable not existing as false.
|
||||
match uefi::runtime::get_variable_boxed(&name, &self.vendor) {
|
||||
Ok((data, _)) => {
|
||||
// If the variable is zero-length, we treat it as false.
|
||||
if data.is_empty() {
|
||||
Ok(false)
|
||||
} else {
|
||||
// We treat the variable as true if the first byte is non-zero.
|
||||
Ok(data[0] > 0)
|
||||
}
|
||||
}
|
||||
|
||||
Err(error) => {
|
||||
// If the variable does not exist, we treat it as false.
|
||||
if error.status() == Status::NOT_FOUND {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(error).with_context(|| format!("unable to get efi variable {}", key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a variable specified by `key` to `value`.
|
||||
/// The variable `class` controls the attributes for the variable.
|
||||
pub fn set(&self, key: &str, value: &[u8], class: VariableClass) -> Result<()> {
|
||||
let name = Self::name(key)?;
|
||||
uefi::runtime::set_variable(&name, &self.vendor, class.attributes(), value)
|
||||
.with_context(|| format!("unable to set efi variable {}", key))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set a variable specified by `key` to `value`, converting the value to
|
||||
/// a [CString16]. The variable `class` controls the attributes for the variable.
|
||||
pub fn set_cstr16(&self, key: &str, value: &str, class: VariableClass) -> Result<()> {
|
||||
// Encode the value as a CString16 little endian.
|
||||
let mut encoded = value
|
||||
.encode_utf16()
|
||||
.flat_map(|c| c.to_le_bytes())
|
||||
.collect::<Vec<u8>>();
|
||||
// Add a null terminator to the end of the value.
|
||||
encoded.extend_from_slice(&[0, 0]);
|
||||
self.set(key, &encoded, class)
|
||||
}
|
||||
|
||||
/// Set a boolean variable specified by `key` to `value`, converting the value.
|
||||
/// The variable `class` controls the attributes for the variable.
|
||||
pub fn set_bool(&self, key: &str, value: bool, class: VariableClass) -> Result<()> {
|
||||
self.set(key, &[value as u8], class)
|
||||
}
|
||||
|
||||
/// Set the u64 little-endian variable specified by `key` to `value`.
|
||||
/// The variable `class` controls the attributes for the variable.
|
||||
pub fn set_u64le(&self, key: &str, value: u64, class: VariableClass) -> Result<()> {
|
||||
self.set(key, &value.to_le_bytes(), class)
|
||||
}
|
||||
|
||||
/// Remove the variable specified by `key`.
|
||||
/// This can fail if the variable is not set.
|
||||
pub fn remove(&self, key: &str) -> Result<()> {
|
||||
let name = Self::name(key)?;
|
||||
|
||||
// Delete the variable from UEFI.
|
||||
uefi::runtime::delete_variable(&name, &self.vendor)
|
||||
.with_context(|| format!("unable to remove efi variable {}", key))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user