mirror of
https://github.com/edera-dev/sprout.git
synced 2025-12-19 20:40:17 +00:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
524d0871f3
|
|||
|
f0628f77e2
|
|||
|
cc37c2b26a
|
|||
|
8d403d74c9
|
|||
|
cc4bc6efcc
|
|||
|
d4bcfcd9b1
|
|||
|
c34462b812
|
|||
|
79471f6862
|
|||
|
9c31dba6fa
|
|||
|
84d60e09be
|
|||
|
eabb612330
|
|||
|
1a6ed0af99
|
|||
|
3b4a66879f
|
|||
|
01b3706914
|
|||
|
5033bc7bf4
|
|||
|
f6441b5694
|
|||
|
03d0e40141
|
|||
|
3a54970386
|
|||
|
8a5dc33b5a
|
|||
|
757d10ec65
|
|||
|
3b32f6c3ce
|
|||
|
6b1d220490
|
|||
|
f7558fd024
|
|||
|
d1fd13163f
|
|||
|
a998832f6b
|
|||
|
992520c201
|
|||
|
e9cba9da33
|
|||
|
0f8f12c70f
|
|||
|
1c732a1c43
|
|||
|
08b9e2570e
|
|||
|
f361570b0e
|
|||
|
679b0c0290
|
|||
|
f9dd56c8e7
|
3
Cargo.lock
generated
3
Cargo.lock
generated
@@ -116,9 +116,10 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "edera-sprout"
|
name = "edera-sprout"
|
||||||
version = "0.0.16"
|
version = "0.0.17"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"bitflags",
|
||||||
"image",
|
"image",
|
||||||
"log",
|
"log",
|
||||||
"serde",
|
"serde",
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
name = "edera-sprout"
|
name = "edera-sprout"
|
||||||
description = "Modern UEFI bootloader"
|
description = "Modern UEFI bootloader"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
version = "0.0.16"
|
version = "0.0.17"
|
||||||
homepage = "https://sprout.edera.dev"
|
homepage = "https://sprout.edera.dev"
|
||||||
repository = "https://github.com/edera-dev/sprout"
|
repository = "https://github.com/edera-dev/sprout"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.100"
|
anyhow = "1.0.100"
|
||||||
|
bitflags = "2.10.0"
|
||||||
toml = "0.9.8"
|
toml = "0.9.8"
|
||||||
log = "0.4.28"
|
log = "0.4.28"
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::context::SproutContext;
|
use crate::context::SproutContext;
|
||||||
use crate::utils::framebuffer::Framebuffer;
|
use crate::utils::framebuffer::Framebuffer;
|
||||||
use crate::utils::read_file_contents;
|
use crate::utils::read_file_contents;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result, bail};
|
||||||
use image::imageops::{FilterType, resize};
|
use image::imageops::{FilterType, resize};
|
||||||
use image::math::Rect;
|
use image::math::Rect;
|
||||||
use image::{DynamicImage, ImageBuffer, ImageFormat, ImageReader, Rgba};
|
use image::{DynamicImage, ImageBuffer, ImageFormat, ImageReader, Rgba};
|
||||||
@@ -118,6 +118,11 @@ fn draw(image: DynamicImage) -> Result<()> {
|
|||||||
// Fit the image to the display frame.
|
// Fit the image to the display frame.
|
||||||
let fit = fit_to_frame(&image, display_frame);
|
let fit = fit_to_frame(&image, display_frame);
|
||||||
|
|
||||||
|
// If the image is zero-sized, then we should bail with an error.
|
||||||
|
if fit.width == 0 || fit.height == 0 {
|
||||||
|
bail!("calculated frame size is zero");
|
||||||
|
}
|
||||||
|
|
||||||
// Resize the image to fit the display frame.
|
// Resize the image to fit the display frame.
|
||||||
let image = resize_to_fit(&image, fit);
|
let image = resize_to_fit(&image, fit);
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use crate::entries::EntryDeclaration;
|
|||||||
use crate::generators::GeneratorDeclaration;
|
use crate::generators::GeneratorDeclaration;
|
||||||
use crate::generators::list::ListConfiguration;
|
use crate::generators::list::ListConfiguration;
|
||||||
use crate::utils;
|
use crate::utils;
|
||||||
|
use crate::utils::vercmp;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use uefi::CString16;
|
use uefi::CString16;
|
||||||
@@ -170,6 +171,9 @@ pub fn scan(
|
|||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sort the kernel pairs by kernel version, if it has one, newer kernels first.
|
||||||
|
pairs.sort_by(|a, b| vercmp::compare_versions(&a.kernel, &b.kernel).reverse());
|
||||||
|
|
||||||
// Generate a unique name for the linux chainload action.
|
// Generate a unique name for the linux chainload action.
|
||||||
let chainload_action_name = format!("{}{}", LINUX_CHAINLOAD_ACTION_PREFIX, root_unique_hash,);
|
let chainload_action_name = format!("{}{}", LINUX_CHAINLOAD_ACTION_PREFIX, root_unique_hash,);
|
||||||
|
|
||||||
|
|||||||
@@ -94,6 +94,11 @@ impl BootableEntry {
|
|||||||
self.default = true;
|
self.default = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Unmark this entry as the default entry.
|
||||||
|
pub fn unmark_default(&mut self) {
|
||||||
|
self.default = false;
|
||||||
|
}
|
||||||
|
|
||||||
/// Mark this entry as being pinned, which prevents prefixing.
|
/// Mark this entry as being pinned, which prevents prefixing.
|
||||||
pub fn mark_pin_name(&mut self) {
|
pub fn mark_pin_name(&mut self) {
|
||||||
self.pin_name = true;
|
self.pin_name = true;
|
||||||
|
|||||||
@@ -138,14 +138,11 @@ pub fn extract(
|
|||||||
let mut filesystem = FileSystem::new(filesystem);
|
let mut filesystem = FileSystem::new(filesystem);
|
||||||
|
|
||||||
// Check the metadata of the item.
|
// Check the metadata of the item.
|
||||||
let metadata = filesystem.metadata(Path::new(&want_item));
|
|
||||||
|
|
||||||
// Ignore filesystem errors as we can't do anything useful with the error.
|
// Ignore filesystem errors as we can't do anything useful with the error.
|
||||||
if metadata.is_err() {
|
let Some(metadata) = filesystem.metadata(Path::new(&want_item)).ok() else {
|
||||||
continue;
|
continue;
|
||||||
}
|
};
|
||||||
|
|
||||||
let metadata = metadata?;
|
|
||||||
// Only check directories and files.
|
// Only check directories and files.
|
||||||
if !(metadata.is_directory() || metadata.is_regular_file()) {
|
if !(metadata.is_directory() || metadata.is_regular_file()) {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ use crate::context::SproutContext;
|
|||||||
use crate::entries::{BootableEntry, EntryDeclaration};
|
use crate::entries::{BootableEntry, EntryDeclaration};
|
||||||
use crate::generators::bls::entry::BlsEntry;
|
use crate::generators::bls::entry::BlsEntry;
|
||||||
use crate::utils;
|
use crate::utils;
|
||||||
|
use crate::utils::vercmp;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::cmp::Ordering;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use uefi::cstr16;
|
use uefi::cstr16;
|
||||||
@@ -40,6 +42,60 @@ fn quirk_initrd_remove_tuned(input: String) -> String {
|
|||||||
input.replace("$tuned_initrd", "").trim().to_string()
|
input.replace("$tuned_initrd", "").trim().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sorts two entries according to the BLS sort system.
|
||||||
|
/// Reference: https://uapi-group.org/specifications/specs/boot_loader_specification/#sorting
|
||||||
|
fn sort_entries(a: &(BlsEntry, BootableEntry), b: &(BlsEntry, BootableEntry)) -> Ordering {
|
||||||
|
// Grab the components of both entries.
|
||||||
|
let (a_bls, a_boot) = a;
|
||||||
|
let (b_bls, b_boot) = b;
|
||||||
|
|
||||||
|
// Grab the sort keys from both entries.
|
||||||
|
let a_sort_key = a_bls.sort_key();
|
||||||
|
let b_sort_key = b_bls.sort_key();
|
||||||
|
|
||||||
|
// Compare the sort keys of both entries.
|
||||||
|
match a_sort_key.cmp(&b_sort_key) {
|
||||||
|
// If A and B sort keys are equal, sort by machine-id.
|
||||||
|
Ordering::Equal => {
|
||||||
|
// Grab the machine-id from both entries.
|
||||||
|
let a_machine_id = a_bls.machine_id();
|
||||||
|
let b_machine_id = b_bls.machine_id();
|
||||||
|
|
||||||
|
// Compare the machine-id of both entries.
|
||||||
|
match a_machine_id.cmp(&b_machine_id) {
|
||||||
|
// If both machine-id values are equal, sort by version.
|
||||||
|
Ordering::Equal => {
|
||||||
|
// Grab the version from both entries.
|
||||||
|
let a_version = a_bls.version();
|
||||||
|
let b_version = b_bls.version();
|
||||||
|
|
||||||
|
// Compare the version of both entries, sorting newer versions first.
|
||||||
|
match vercmp::compare_versions_optional(
|
||||||
|
a_version.as_deref(),
|
||||||
|
b_version.as_deref(),
|
||||||
|
)
|
||||||
|
.reverse()
|
||||||
|
{
|
||||||
|
// If both versions are equal, sort by file name in reverse order.
|
||||||
|
Ordering::Equal => {
|
||||||
|
// Grab the file name from both entries.
|
||||||
|
let a_name = a_boot.name();
|
||||||
|
let b_name = b_boot.name();
|
||||||
|
|
||||||
|
// Compare the file names of both entries, sorting newer entries first.
|
||||||
|
vercmp::compare_versions(a_name, b_name).reverse()
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Generates entries from the BLS entries directory using the specified `bls` configuration and
|
/// Generates entries from the BLS entries directory using the specified `bls` configuration and
|
||||||
/// `context`. The BLS conversion is best-effort and will ignore any unsupported entries.
|
/// `context`. The BLS conversion is best-effort and will ignore any unsupported entries.
|
||||||
pub fn generate(context: Rc<SproutContext>, bls: &BlsConfiguration) -> Result<Vec<BootableEntry>> {
|
pub fn generate(context: Rc<SproutContext>, bls: &BlsConfiguration) -> Result<Vec<BootableEntry>> {
|
||||||
@@ -93,6 +149,11 @@ pub fn generate(context: Rc<SproutContext>, bls: &BlsConfiguration) -> Result<Ve
|
|||||||
// Remove the .conf extension.
|
// Remove the .conf extension.
|
||||||
name.truncate(name.len() - 5);
|
name.truncate(name.len() - 5);
|
||||||
|
|
||||||
|
// Skip over files that are named just ".conf" as they are not valid entry files.
|
||||||
|
if name.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Create a mutable path so we can append the file name to produce the full path.
|
// Create a mutable path so we can append the file name to produce the full path.
|
||||||
let mut full_entry_path = entries_path.to_path_buf();
|
let mut full_entry_path = entries_path.to_path_buf();
|
||||||
full_entry_path.push(entry.file_name());
|
full_entry_path.push(entry.file_name());
|
||||||
@@ -116,20 +177,33 @@ pub fn generate(context: Rc<SproutContext>, bls: &BlsConfiguration) -> Result<Ve
|
|||||||
// Produce a new sprout context for the entry with the extracted values.
|
// Produce a new sprout context for the entry with the extracted values.
|
||||||
let mut context = context.fork();
|
let mut context = context.fork();
|
||||||
|
|
||||||
let title = entry.title().unwrap_or_else(|| name.clone());
|
let title_base = entry.title().unwrap_or_else(|| name.clone());
|
||||||
let chainload = entry.chainload_path().unwrap_or_default();
|
let chainload = entry.chainload_path().unwrap_or_default();
|
||||||
let options = entry.options().unwrap_or_default();
|
let options = entry.options().unwrap_or_default();
|
||||||
|
let version = entry.version().unwrap_or_default();
|
||||||
|
let machine_id = entry.machine_id().unwrap_or_default();
|
||||||
|
|
||||||
// Put the initrd through a quirk modifier to support Fedora.
|
// Put the initrd through a quirk modifier to support Fedora.
|
||||||
let initrd = quirk_initrd_remove_tuned(entry.initrd_path().unwrap_or_default());
|
let initrd = quirk_initrd_remove_tuned(entry.initrd_path().unwrap_or_default());
|
||||||
|
|
||||||
context.set("title", title);
|
// Combine the title with the version if a version is present, except if it already contains it.
|
||||||
|
// Sometimes BLS will have a version in the title already, and this makes it unique.
|
||||||
|
let title_full = if !version.is_empty() && !title_base.contains(&version) {
|
||||||
|
format!("{} {}", title_base, version)
|
||||||
|
} else {
|
||||||
|
title_base.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
context.set("title-base", title_base);
|
||||||
|
context.set("title", title_full);
|
||||||
context.set("chainload", chainload);
|
context.set("chainload", chainload);
|
||||||
context.set("options", options);
|
context.set("options", options);
|
||||||
context.set("initrd", initrd);
|
context.set("initrd", initrd);
|
||||||
|
context.set("version", version);
|
||||||
|
context.set("machine-id", machine_id);
|
||||||
|
|
||||||
// Produce a new bootable entry.
|
// Produce a new bootable entry.
|
||||||
let mut entry = BootableEntry::new(
|
let mut boot = BootableEntry::new(
|
||||||
name,
|
name,
|
||||||
bls.entry.title.clone(),
|
bls.entry.title.clone(),
|
||||||
context.freeze(),
|
context.freeze(),
|
||||||
@@ -139,11 +213,15 @@ pub fn generate(context: Rc<SproutContext>, bls: &BlsConfiguration) -> Result<Ve
|
|||||||
// Pin the entry name to prevent prefixing.
|
// Pin the entry name to prevent prefixing.
|
||||||
// This is needed as the bootloader interface requires the name to be
|
// This is needed as the bootloader interface requires the name to be
|
||||||
// the same as the entry file name, minus the .conf extension.
|
// the same as the entry file name, minus the .conf extension.
|
||||||
entry.mark_pin_name();
|
boot.mark_pin_name();
|
||||||
|
|
||||||
// Add the entry to the list with a frozen context.
|
// Add the BLS entry to the list, along with the bootable entry.
|
||||||
entries.push(entry);
|
entries.push((entry, boot));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(entries)
|
// Sort all the entries according to the BLS sort system.
|
||||||
|
entries.sort_by(sort_entries);
|
||||||
|
|
||||||
|
// Collect all the bootable entries and return them.
|
||||||
|
Ok(entries.into_iter().map(|(_, boot)| boot).collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ pub struct BlsEntry {
|
|||||||
pub initrd: Option<String>,
|
pub initrd: Option<String>,
|
||||||
/// The path to an EFI image.
|
/// The path to an EFI image.
|
||||||
pub efi: Option<String>,
|
pub efi: Option<String>,
|
||||||
|
/// The sort key for the entry.
|
||||||
|
pub sort_key: Option<String>,
|
||||||
|
/// The version of the entry.
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// The machine id of the entry.
|
||||||
|
pub machine_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parser for a BLS entry.
|
/// Parser for a BLS entry.
|
||||||
@@ -30,6 +36,9 @@ impl FromStr for BlsEntry {
|
|||||||
let mut linux: Option<String> = None;
|
let mut linux: Option<String> = None;
|
||||||
let mut initrd: Option<String> = None;
|
let mut initrd: Option<String> = None;
|
||||||
let mut efi: Option<String> = None;
|
let mut efi: Option<String> = None;
|
||||||
|
let mut sort_key: Option<String> = None;
|
||||||
|
let mut version: Option<String> = None;
|
||||||
|
let mut machine_id: Option<String> = None;
|
||||||
|
|
||||||
// Iterate over each line in the input and parse it.
|
// Iterate over each line in the input and parse it.
|
||||||
for line in input.lines() {
|
for line in input.lines() {
|
||||||
@@ -74,6 +83,18 @@ impl FromStr for BlsEntry {
|
|||||||
efi = Some(value.trim().to_string());
|
efi = Some(value.trim().to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
"sort-key" => {
|
||||||
|
sort_key = Some(value.trim().to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
"version" => {
|
||||||
|
version = Some(value.trim().to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
"machine-id" => {
|
||||||
|
machine_id = Some(value.trim().to_string());
|
||||||
|
}
|
||||||
|
|
||||||
// Ignore any other key.
|
// Ignore any other key.
|
||||||
_ => {
|
_ => {
|
||||||
continue;
|
continue;
|
||||||
@@ -88,6 +109,9 @@ impl FromStr for BlsEntry {
|
|||||||
linux,
|
linux,
|
||||||
initrd,
|
initrd,
|
||||||
efi,
|
efi,
|
||||||
|
sort_key,
|
||||||
|
version,
|
||||||
|
machine_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -125,4 +149,19 @@ impl BlsEntry {
|
|||||||
pub fn title(&self) -> Option<String> {
|
pub fn title(&self) -> Option<String> {
|
||||||
self.title.clone()
|
self.title.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fetches the sort key of the entry, if any.
|
||||||
|
pub fn sort_key(&self) -> Option<String> {
|
||||||
|
self.sort_key.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches the version of the entry, if any.
|
||||||
|
pub fn version(&self) -> Option<String> {
|
||||||
|
self.version.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches the machine id of the entry, if any.
|
||||||
|
pub fn machine_id(&self) -> Option<String> {
|
||||||
|
self.machine_id.clone()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::integrations::bootloader_interface::bitflags::LoaderFeatures;
|
||||||
use crate::platform::timer::PlatformTimer;
|
use crate::platform::timer::PlatformTimer;
|
||||||
use crate::utils::device_path_subpath;
|
use crate::utils::device_path_subpath;
|
||||||
use crate::utils::variables::{VariableClass, VariableController};
|
use crate::utils::variables::{VariableClass, VariableController};
|
||||||
@@ -6,9 +7,26 @@ use uefi::proto::device_path::DevicePath;
|
|||||||
use uefi::{Guid, guid};
|
use uefi::{Guid, guid};
|
||||||
use uefi_raw::table::runtime::VariableVendor;
|
use uefi_raw::table::runtime::VariableVendor;
|
||||||
|
|
||||||
|
/// bitflags: LoaderFeatures bitflags.
|
||||||
|
mod bitflags;
|
||||||
|
|
||||||
/// The name of the bootloader to tell the system.
|
/// The name of the bootloader to tell the system.
|
||||||
const LOADER_NAME: &str = "Sprout";
|
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.
|
/// Bootloader Interface support.
|
||||||
pub struct BootloaderInterface;
|
pub struct BootloaderInterface;
|
||||||
|
|
||||||
@@ -18,6 +36,19 @@ impl BootloaderInterface {
|
|||||||
"4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"
|
"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.
|
/// Tell the system that Sprout was initialized at the current time.
|
||||||
pub fn mark_init(timer: &PlatformTimer) -> Result<()> {
|
pub fn mark_init(timer: &PlatformTimer) -> Result<()> {
|
||||||
Self::mark_time("LoaderTimeInitUSec", timer)
|
Self::mark_time("LoaderTimeInitUSec", timer)
|
||||||
@@ -30,7 +61,7 @@ impl BootloaderInterface {
|
|||||||
|
|
||||||
/// Tell the system that Sprout is about to display the menu.
|
/// Tell the system that Sprout is about to display the menu.
|
||||||
pub fn mark_menu(timer: &PlatformTimer) -> Result<()> {
|
pub fn mark_menu(timer: &PlatformTimer) -> Result<()> {
|
||||||
Self::mark_time("LoaderTimeMenuUsec", timer)
|
Self::mark_time("LoaderTimeMenuUSec", timer)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tell the system about the current time as measured by the platform timer.
|
/// Tell the system about the current time as measured by the platform timer.
|
||||||
@@ -45,13 +76,26 @@ impl BootloaderInterface {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tell the system what loader is being used.
|
/// Tell the system what loader is being used and our features.
|
||||||
pub fn set_loader_info() -> Result<()> {
|
pub fn set_loader_info() -> Result<()> {
|
||||||
Self::VENDOR.set_cstr16(
|
// Set the LoaderInfo variable with the name of the loader.
|
||||||
|
Self::VENDOR
|
||||||
|
.set_cstr16(
|
||||||
"LoaderInfo",
|
"LoaderInfo",
|
||||||
LOADER_NAME,
|
LOADER_NAME,
|
||||||
VariableClass::BootAndRuntimeTemporary,
|
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.
|
/// Tell the system the relative path to the partition root of the current bootloader.
|
||||||
@@ -90,6 +134,12 @@ impl BootloaderInterface {
|
|||||||
// Add a null terminator to the end of the entry.
|
// Add a null terminator to the end of the entry.
|
||||||
data.extend_from_slice(&[0, 0]);
|
data.extend_from_slice(&[0, 0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If no data was generated, we will do nothing.
|
||||||
|
if data.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
Self::VENDOR.set(
|
Self::VENDOR.set(
|
||||||
"LoaderEntries",
|
"LoaderEntries",
|
||||||
&data,
|
&data,
|
||||||
@@ -97,15 +147,6 @@ impl BootloaderInterface {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tell the system what the default boot entry is.
|
|
||||||
pub fn set_default_entry(entry: String) -> Result<()> {
|
|
||||||
Self::VENDOR.set_cstr16(
|
|
||||||
"LoaderEntryDefault",
|
|
||||||
&entry,
|
|
||||||
VariableClass::BootAndRuntimeTemporary,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tell the system what the selected boot entry is.
|
/// Tell the system what the selected boot entry is.
|
||||||
pub fn set_selected_entry(entry: String) -> Result<()> {
|
pub fn set_selected_entry(entry: String) -> Result<()> {
|
||||||
Self::VENDOR.set_cstr16(
|
Self::VENDOR.set_cstr16(
|
||||||
@@ -160,4 +201,114 @@ impl BootloaderInterface {
|
|||||||
VariableClass::BootAndRuntimeTemporary,
|
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
src/integrations/bootloader_interface/bitflags.rs
Normal file
46
src/integrations/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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
use crate::integrations::shim::hook::SecurityHook;
|
use crate::integrations::shim::hook::SecurityHook;
|
||||||
|
use crate::secure::SecureBoot;
|
||||||
use crate::utils;
|
use crate::utils;
|
||||||
use crate::utils::ResolvedPath;
|
use crate::utils::ResolvedPath;
|
||||||
use crate::utils::variables::{VariableClass, VariableController};
|
use crate::utils::variables::{VariableClass, VariableController};
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
use std::ffi::c_void;
|
use std::ffi::c_void;
|
||||||
|
use std::pin::Pin;
|
||||||
use uefi::Handle;
|
use uefi::Handle;
|
||||||
use uefi::boot::LoadImageSource;
|
use uefi::boot::LoadImageSource;
|
||||||
use uefi::proto::device_path::text::{AllowShortcuts, DisplayOnly};
|
use uefi::proto::device_path::text::{AllowShortcuts, DisplayOnly};
|
||||||
@@ -22,13 +24,13 @@ pub struct ShimSupport;
|
|||||||
/// Input to the shim mechanisms.
|
/// Input to the shim mechanisms.
|
||||||
pub enum ShimInput<'a> {
|
pub enum ShimInput<'a> {
|
||||||
/// Data loaded into a buffer and ready to be verified, owned.
|
/// Data loaded into a buffer and ready to be verified, owned.
|
||||||
OwnedDataBuffer(Option<&'a ResolvedPath>, Vec<u8>),
|
OwnedDataBuffer(Option<&'a ResolvedPath>, Pin<Box<[u8]>>),
|
||||||
/// Data loaded into a buffer and ready to be verified.
|
/// Data loaded into a buffer and ready to be verified.
|
||||||
DataBuffer(Option<&'a ResolvedPath>, &'a [u8]),
|
DataBuffer(Option<&'a ResolvedPath>, &'a [u8]),
|
||||||
/// Low-level data buffer provided by the security hook.
|
/// Low-level data buffer provided by the security hook.
|
||||||
SecurityHookBuffer(Option<*const FfiDevicePath>, &'a [u8]),
|
SecurityHookBuffer(Option<*const FfiDevicePath>, &'a [u8]),
|
||||||
/// Low-level owned data buffer provided by the security hook.
|
/// Low-level owned data buffer provided by the security hook.
|
||||||
SecurityHookOwnedBuffer(Option<*const FfiDevicePath>, Vec<u8>),
|
SecurityHookOwnedBuffer(Option<*const FfiDevicePath>, Pin<Box<[u8]>>),
|
||||||
/// Low-level path provided by the security hook.
|
/// Low-level path provided by the security hook.
|
||||||
SecurityHookPath(*const FfiDevicePath),
|
SecurityHookPath(*const FfiDevicePath),
|
||||||
/// Data is provided as a resolved path. We will need to load the data to verify it.
|
/// Data is provided as a resolved path. We will need to load the data to verify it.
|
||||||
@@ -71,9 +73,10 @@ impl<'a> ShimInput<'a> {
|
|||||||
match self {
|
match self {
|
||||||
ShimInput::OwnedDataBuffer(root, data) => Ok(ShimInput::OwnedDataBuffer(root, data)),
|
ShimInput::OwnedDataBuffer(root, data) => Ok(ShimInput::OwnedDataBuffer(root, data)),
|
||||||
|
|
||||||
ShimInput::DataBuffer(root, data) => {
|
ShimInput::DataBuffer(root, data) => Ok(ShimInput::OwnedDataBuffer(
|
||||||
Ok(ShimInput::OwnedDataBuffer(root, data.to_vec()))
|
root,
|
||||||
}
|
Box::into_pin(data.to_vec().into_boxed_slice()),
|
||||||
|
)),
|
||||||
|
|
||||||
ShimInput::SecurityHookPath(ffi_path) => {
|
ShimInput::SecurityHookPath(ffi_path) => {
|
||||||
// Acquire the file path.
|
// Acquire the file path.
|
||||||
@@ -88,7 +91,10 @@ impl<'a> ShimInput<'a> {
|
|||||||
.context("unable to resolve path")?;
|
.context("unable to resolve path")?;
|
||||||
// Read the file path.
|
// Read the file path.
|
||||||
let data = path.read_file()?;
|
let data = path.read_file()?;
|
||||||
Ok(ShimInput::SecurityHookOwnedBuffer(Some(ffi_path), data))
|
Ok(ShimInput::SecurityHookOwnedBuffer(
|
||||||
|
Some(ffi_path),
|
||||||
|
Box::into_pin(data.to_vec().into_boxed_slice()),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
ShimInput::SecurityHookBuffer(_, _) => {
|
ShimInput::SecurityHookBuffer(_, _) => {
|
||||||
@@ -96,7 +102,12 @@ impl<'a> ShimInput<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ShimInput::ResolvedPath(path) => {
|
ShimInput::ResolvedPath(path) => {
|
||||||
Ok(ShimInput::OwnedDataBuffer(Some(path), path.read_file()?))
|
// 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) => {
|
ShimInput::SecurityHookOwnedBuffer(path, data) => {
|
||||||
@@ -111,7 +122,7 @@ impl<'a> ShimInput<'a> {
|
|||||||
/// to actually boot.
|
/// to actually boot.
|
||||||
pub enum ShimVerificationOutput {
|
pub enum ShimVerificationOutput {
|
||||||
/// The verification failed.
|
/// The verification failed.
|
||||||
VerificationFailed,
|
VerificationFailed(Status),
|
||||||
/// The data provided to the verifier was already a buffer.
|
/// The data provided to the verifier was already a buffer.
|
||||||
VerifiedDataNotLoaded,
|
VerifiedDataNotLoaded,
|
||||||
/// Verifying the data resulted in loading the data from the source.
|
/// Verifying the data resulted in loading the data from the source.
|
||||||
@@ -123,7 +134,14 @@ pub enum ShimVerificationOutput {
|
|||||||
#[unsafe_protocol(ShimSupport::SHIM_LOCK_GUID)]
|
#[unsafe_protocol(ShimSupport::SHIM_LOCK_GUID)]
|
||||||
struct ShimLockProtocol {
|
struct ShimLockProtocol {
|
||||||
/// Verify the data in `buffer` with the size `buffer_size` to determine if it is valid.
|
/// Verify the data in `buffer` with the size `buffer_size` to determine if it is valid.
|
||||||
pub shim_verify: unsafe extern "efiapi" fn(buffer: *mut c_void, buffer_size: u32) -> Status,
|
/// 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.
|
/// Unused function that is defined by the shim.
|
||||||
_generate_header: *mut c_void,
|
_generate_header: *mut c_void,
|
||||||
/// Unused function that is defined by the shim.
|
/// Unused function that is defined by the shim.
|
||||||
@@ -201,12 +219,13 @@ impl ShimSupport {
|
|||||||
// SAFETY: The shim verify function is specified by the shim lock protocol.
|
// SAFETY: The shim verify function is specified by the shim lock protocol.
|
||||||
// Calling this function is considered safe because the shim verify function is
|
// 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.
|
// guaranteed to be defined by the environment if we are able to acquire the protocol.
|
||||||
let status =
|
let status = unsafe {
|
||||||
unsafe { (protocol.shim_verify)(buffer.as_ptr() as *mut c_void, buffer.len() as u32) };
|
(protocol.shim_verify)(buffer.as_ptr() as *const c_void, buffer.len() as u32)
|
||||||
|
};
|
||||||
|
|
||||||
// If the verification failed, return the verification failure output.
|
// If the verification failed, return the verification failure output.
|
||||||
if !status.is_success() {
|
if !status.is_success() {
|
||||||
return Ok(ShimVerificationOutput::VerificationFailed);
|
return Ok(ShimVerificationOutput::VerificationFailed(status));
|
||||||
}
|
}
|
||||||
|
|
||||||
// If verification succeeded, return the validation output,
|
// If verification succeeded, return the validation output,
|
||||||
@@ -218,6 +237,10 @@ impl ShimSupport {
|
|||||||
|
|
||||||
/// Load the image specified by the `input` and returns an image handle.
|
/// Load the image specified by the `input` and returns an image handle.
|
||||||
pub fn load(current_image: Handle, input: ShimInput) -> Result<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.
|
// Determine whether the shim is loaded.
|
||||||
let shim_loaded = Self::loaded().context("unable to determine if shim is loaded")?;
|
let shim_loaded = Self::loaded().context("unable to determine if shim is loaded")?;
|
||||||
|
|
||||||
@@ -228,7 +251,7 @@ impl ShimSupport {
|
|||||||
// Determines whether LoadImage in Boot Services must be patched.
|
// Determines whether LoadImage in Boot Services must be patched.
|
||||||
// Version 16 of the shim doesn't require extra effort to load Secure Boot binaries.
|
// 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.
|
// If the image loader is installed, we can skip over the security hook.
|
||||||
let requires_security_hook = shim_loaded && !shim_loader_available;
|
let requires_security_hook = secure_boot && shim_loaded && !shim_loader_available;
|
||||||
|
|
||||||
// If the security hook is required, we will bail for now.
|
// If the security hook is required, we will bail for now.
|
||||||
if requires_security_hook {
|
if requires_security_hook {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub struct SecurityArchProtocol {
|
|||||||
pub file_authentication_state: unsafe extern "efiapi" fn(
|
pub file_authentication_state: unsafe extern "efiapi" fn(
|
||||||
this: *const SecurityArchProtocol,
|
this: *const SecurityArchProtocol,
|
||||||
status: u32,
|
status: u32,
|
||||||
path: *mut FfiDevicePath,
|
path: *const FfiDevicePath,
|
||||||
) -> Status,
|
) -> Status,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,8 +30,8 @@ pub struct SecurityArch2Protocol {
|
|||||||
/// Determines the file authentication.
|
/// Determines the file authentication.
|
||||||
pub file_authentication: unsafe extern "efiapi" fn(
|
pub file_authentication: unsafe extern "efiapi" fn(
|
||||||
this: *const SecurityArch2Protocol,
|
this: *const SecurityArch2Protocol,
|
||||||
path: *mut FfiDevicePath,
|
path: *const FfiDevicePath,
|
||||||
file_buffer: *mut u8,
|
file_buffer: *const u8,
|
||||||
file_size: usize,
|
file_size: usize,
|
||||||
boot_policy: bool,
|
boot_policy: bool,
|
||||||
) -> Status,
|
) -> Status,
|
||||||
@@ -53,12 +53,13 @@ pub struct SecurityHook;
|
|||||||
|
|
||||||
impl SecurityHook {
|
impl SecurityHook {
|
||||||
/// Shared verifier logic for both hook types.
|
/// Shared verifier logic for both hook types.
|
||||||
fn verify(input: ShimInput) -> Status {
|
#[must_use]
|
||||||
// Verify the input.
|
fn verify(input: ShimInput) -> bool {
|
||||||
match ShimSupport::verify(input) {
|
// Verify the input and convert the result to a status.
|
||||||
|
let status = match ShimSupport::verify(input) {
|
||||||
Ok(output) => match output {
|
Ok(output) => match output {
|
||||||
// If the verification failed, return the access-denied status.
|
// If the verification failed, return the access-denied status.
|
||||||
ShimVerificationOutput::VerificationFailed => Status::ACCESS_DENIED,
|
ShimVerificationOutput::VerificationFailed(status) => status,
|
||||||
// If the verification succeeded, return the success status.
|
// If the verification succeeded, return the success status.
|
||||||
ShimVerificationOutput::VerifiedDataNotLoaded => Status::SUCCESS,
|
ShimVerificationOutput::VerifiedDataNotLoaded => Status::SUCCESS,
|
||||||
ShimVerificationOutput::VerifiedDataBuffer(_) => Status::SUCCESS,
|
ShimVerificationOutput::VerifiedDataBuffer(_) => Status::SUCCESS,
|
||||||
@@ -70,15 +71,23 @@ impl SecurityHook {
|
|||||||
warn!("unable to verify image: {}", error);
|
warn!("unable to verify image: {}", error);
|
||||||
Status::ACCESS_DENIED
|
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.
|
/// File authentication state verifier for the EFI_SECURITY_ARCH protocol.
|
||||||
/// Takes the `path` and determines the verification.
|
/// Takes the `path` and determines the verification.
|
||||||
unsafe extern "efiapi" fn arch_file_authentication_state(
|
unsafe extern "efiapi" fn arch_file_authentication_state(
|
||||||
_this: *const SecurityArchProtocol,
|
this: *const SecurityArchProtocol,
|
||||||
_status: u32,
|
status: u32,
|
||||||
path: *mut FfiDevicePath,
|
path: *const FfiDevicePath,
|
||||||
) -> Status {
|
) -> Status {
|
||||||
// Verify the path is not null.
|
// Verify the path is not null.
|
||||||
if path.is_null() {
|
if path.is_null() {
|
||||||
@@ -88,16 +97,56 @@ impl SecurityHook {
|
|||||||
// Construct a shim input from the path.
|
// Construct a shim input from the path.
|
||||||
let input = ShimInput::SecurityHookPath(path);
|
let input = ShimInput::SecurityHookPath(path);
|
||||||
|
|
||||||
// Verify the input.
|
// Convert the input to an owned data buffer.
|
||||||
Self::verify(input)
|
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() {
|
||||||
|
// We have acquired the lock, so we can find the original hook.
|
||||||
|
Ok(state) => match state.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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Err(error) => {
|
||||||
|
warn!(
|
||||||
|
"unable to acquire global hook state lock to call original hook: {}",
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
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.
|
/// File authentication verifier for the EFI_SECURITY_ARCH2 protocol.
|
||||||
/// Takes the `path` and a file buffer to determine the verification.
|
/// Takes the `path` and a file buffer to determine the verification.
|
||||||
unsafe extern "efiapi" fn arch2_file_authentication(
|
unsafe extern "efiapi" fn arch2_file_authentication(
|
||||||
_this: *const SecurityArch2Protocol,
|
this: *const SecurityArch2Protocol,
|
||||||
path: *mut FfiDevicePath,
|
path: *const FfiDevicePath,
|
||||||
file_buffer: *mut u8,
|
file_buffer: *const u8,
|
||||||
file_size: usize,
|
file_size: usize,
|
||||||
boot_policy: bool,
|
boot_policy: bool,
|
||||||
) -> Status {
|
) -> Status {
|
||||||
@@ -117,8 +166,38 @@ impl SecurityHook {
|
|||||||
// Construct a shim input from the path.
|
// Construct a shim input from the path.
|
||||||
let input = ShimInput::SecurityHookBuffer(Some(path), buffer);
|
let input = ShimInput::SecurityHookBuffer(Some(path), buffer);
|
||||||
|
|
||||||
// Verify the input.
|
// Verify the input, if it fails, call the original hook.
|
||||||
Self::verify(input)
|
if !Self::verify(input) {
|
||||||
|
// Acquire the global hook state to grab the original hook.
|
||||||
|
let function = match GLOBAL_HOOK_STATE.lock() {
|
||||||
|
// We have acquired the lock, so we can find the original hook.
|
||||||
|
Ok(state) => match state.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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
Err(error) => {
|
||||||
|
warn!(
|
||||||
|
"unable to acquire global hook state lock to call original hook: {}",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
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.
|
/// Install the security hook if needed.
|
||||||
|
|||||||
90
src/main.rs
90
src/main.rs
@@ -1,6 +1,5 @@
|
|||||||
#![doc = include_str!("../README.md")]
|
#![doc = include_str!("../README.md")]
|
||||||
#![feature(uefi_std)]
|
#![feature(uefi_std)]
|
||||||
extern crate core;
|
|
||||||
|
|
||||||
/// The delay to wait for when an error occurs in Sprout.
|
/// The delay to wait for when an error occurs in Sprout.
|
||||||
const DELAY_ON_ERROR: Duration = Duration::from_secs(10);
|
const DELAY_ON_ERROR: Duration = Duration::from_secs(10);
|
||||||
@@ -8,7 +7,7 @@ const DELAY_ON_ERROR: Duration = Duration::from_secs(10);
|
|||||||
use crate::config::RootConfiguration;
|
use crate::config::RootConfiguration;
|
||||||
use crate::context::{RootContext, SproutContext};
|
use crate::context::{RootContext, SproutContext};
|
||||||
use crate::entries::BootableEntry;
|
use crate::entries::BootableEntry;
|
||||||
use crate::integrations::bootloader_interface::BootloaderInterface;
|
use crate::integrations::bootloader_interface::{BootloaderInterface, BootloaderInterfaceTimeout};
|
||||||
use crate::options::SproutOptions;
|
use crate::options::SproutOptions;
|
||||||
use crate::options::parser::OptionsRepresentable;
|
use crate::options::parser::OptionsRepresentable;
|
||||||
use crate::phases::phase;
|
use crate::phases::phase;
|
||||||
@@ -263,24 +262,6 @@ fn run() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no entries were the default, pick the first entry as the default entry.
|
|
||||||
if entries.iter().all(|entry| !entry.is_default())
|
|
||||||
&& let Some(entry) = entries.first_mut()
|
|
||||||
{
|
|
||||||
entry.mark_default();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Iterate over all the entries and tell the bootloader interface what the entries are.
|
|
||||||
for entry in &entries {
|
|
||||||
// If the entry is the default entry, tell the bootloader interface it is the default.
|
|
||||||
if entry.is_default() {
|
|
||||||
// Tell the bootloader interface what the default entry is.
|
|
||||||
BootloaderInterface::set_default_entry(entry.name().to_string())
|
|
||||||
.context("unable to set default entry in bootloader interface")?;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tell the bootloader interface what entries are available.
|
// Tell the bootloader interface what entries are available.
|
||||||
BootloaderInterface::set_entries(entries.iter().map(|entry| entry.name()))
|
BootloaderInterface::set_entries(entries.iter().map(|entry| entry.name()))
|
||||||
.context("unable to set entries in bootloader interface")?;
|
.context("unable to set entries in bootloader interface")?;
|
||||||
@@ -288,18 +269,81 @@ fn run() -> Result<()> {
|
|||||||
// Execute the late phase.
|
// Execute the late phase.
|
||||||
phase(context.clone(), &config.phases.late).context("unable to execute late phase")?;
|
phase(context.clone(), &config.phases.late).context("unable to execute late phase")?;
|
||||||
|
|
||||||
|
// Acquire the timeout setting from the bootloader interface.
|
||||||
|
let bootloader_interface_timeout =
|
||||||
|
BootloaderInterface::get_timeout().context("unable to get bootloader interface timeout")?;
|
||||||
|
|
||||||
|
// Acquire the default entry from the bootloader interface.
|
||||||
|
let bootloader_interface_default_entry = BootloaderInterface::get_default_entry()
|
||||||
|
.context("unable to get bootloader interface default entry")?;
|
||||||
|
|
||||||
|
// Acquire the oneshot entry from the bootloader interface.
|
||||||
|
let bootloader_interface_oneshot_entry = BootloaderInterface::get_oneshot_entry()
|
||||||
|
.context("unable to get bootloader interface oneshot entry")?;
|
||||||
|
|
||||||
// If --boot is specified, boot that entry immediately.
|
// If --boot is specified, boot that entry immediately.
|
||||||
let force_boot_entry = context.root().options().boot.as_ref();
|
let mut force_boot_entry = context.root().options().boot.clone();
|
||||||
// If --force-menu is specified, show the boot menu regardless of the value of --boot.
|
// If --force-menu is specified, show the boot menu regardless of the value of --boot.
|
||||||
let force_boot_menu = context.root().options().force_menu;
|
let mut force_boot_menu = context.root().options().force_menu;
|
||||||
|
|
||||||
// Determine the menu timeout in seconds based on the options or configuration.
|
// Determine the menu timeout in seconds based on the options or configuration.
|
||||||
// We prefer the options over the configuration to allow for overriding.
|
// We prefer the options over the configuration to allow for overriding.
|
||||||
let menu_timeout = context
|
let mut menu_timeout = context
|
||||||
.root()
|
.root()
|
||||||
.options()
|
.options()
|
||||||
.menu_timeout
|
.menu_timeout
|
||||||
.unwrap_or(config.options.menu_timeout);
|
.unwrap_or(config.options.menu_timeout);
|
||||||
|
|
||||||
|
// Apply bootloader interface timeout settings.
|
||||||
|
match bootloader_interface_timeout {
|
||||||
|
BootloaderInterfaceTimeout::MenuForce => {
|
||||||
|
// Force the boot menu.
|
||||||
|
force_boot_menu = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
BootloaderInterfaceTimeout::MenuHidden | BootloaderInterfaceTimeout::MenuDisabled => {
|
||||||
|
// Hide the boot menu by setting the timeout to zero.
|
||||||
|
menu_timeout = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
BootloaderInterfaceTimeout::Timeout(timeout) => {
|
||||||
|
// Configure the timeout to the specified value.
|
||||||
|
menu_timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
BootloaderInterfaceTimeout::Unspecified => {
|
||||||
|
// Do nothing.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply bootloader interface default entry settings.
|
||||||
|
if let Some(ref bootloader_interface_default_entry) = bootloader_interface_default_entry {
|
||||||
|
// Iterate over all the entries and mark the default entry as the one specified.
|
||||||
|
for entry in &mut entries {
|
||||||
|
// Mark the entry as the default entry if it matches the specified entry.
|
||||||
|
// If the entry does not match the specified entry, unmark it as the default entry.
|
||||||
|
if entry.is_match(bootloader_interface_default_entry) {
|
||||||
|
entry.mark_default();
|
||||||
|
} else {
|
||||||
|
entry.unmark_default();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply bootloader interface oneshot entry settings.
|
||||||
|
// If set, we will force booting the oneshot entry.
|
||||||
|
if let Some(ref bootloader_interface_oneshot_entry) = bootloader_interface_oneshot_entry {
|
||||||
|
force_boot_entry = Some(bootloader_interface_oneshot_entry.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no entries were the default, pick the first entry as the default entry.
|
||||||
|
if entries.iter().all(|entry| !entry.is_default())
|
||||||
|
&& let Some(entry) = entries.first_mut()
|
||||||
|
{
|
||||||
|
entry.mark_default();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert the menu timeout to a duration.
|
||||||
let menu_timeout = Duration::from_secs(menu_timeout);
|
let menu_timeout = Duration::from_secs(menu_timeout);
|
||||||
|
|
||||||
// Use the forced boot entry if possible, otherwise pick the first entry using a boot menu.
|
// Use the forced boot entry if possible, otherwise pick the first entry using a boot menu.
|
||||||
|
|||||||
29
src/menu.rs
29
src/menu.rs
@@ -2,7 +2,7 @@ use crate::entries::BootableEntry;
|
|||||||
use crate::integrations::bootloader_interface::BootloaderInterface;
|
use crate::integrations::bootloader_interface::BootloaderInterface;
|
||||||
use crate::platform::timer::PlatformTimer;
|
use crate::platform::timer::PlatformTimer;
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use log::info;
|
use log::{info, warn};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use uefi::ResultExt;
|
use uefi::ResultExt;
|
||||||
use uefi::boot::TimerTrigger;
|
use uefi::boot::TimerTrigger;
|
||||||
@@ -56,15 +56,34 @@ fn read(input: &mut Input, timeout: &Duration) -> Result<MenuOperation> {
|
|||||||
uefi::boot::set_timer(&timer_event, trigger).context("unable to set timeout timer")?;
|
uefi::boot::set_timer(&timer_event, trigger).context("unable to set timeout timer")?;
|
||||||
|
|
||||||
let mut events = vec![timer_event, key_event];
|
let mut events = vec![timer_event, key_event];
|
||||||
let event = uefi::boot::wait_for_event(&mut events)
|
|
||||||
|
// Wait for either the timer event or the key event to trigger.
|
||||||
|
// Store the result so that we can free the timer event.
|
||||||
|
let event_result = uefi::boot::wait_for_event(&mut events)
|
||||||
.discard_errdata()
|
.discard_errdata()
|
||||||
.context("unable to wait for event")?;
|
.context("unable to wait for event");
|
||||||
|
|
||||||
// Close the timer event that we acquired.
|
// Close the timer event that we acquired.
|
||||||
// We don't need to close the key event because it is owned globally.
|
// We don't need to close the key event because it is owned globally.
|
||||||
if let Some(timer_event) = events.into_iter().next() {
|
if let Some(timer_event) = events.into_iter().next() {
|
||||||
uefi::boot::close_event(timer_event).context("unable to close timer event")?;
|
// Store the result of the close event so we can determine if we can safely assert it.
|
||||||
|
let close_event_result =
|
||||||
|
uefi::boot::close_event(timer_event).context("unable to close timer event");
|
||||||
|
if event_result.is_err()
|
||||||
|
&& let Err(ref close_event_error) = close_event_result
|
||||||
|
{
|
||||||
|
// Log a warning if we failed to close the timer event.
|
||||||
|
// This is done to ensure we don't mask the wait_for_event error.
|
||||||
|
warn!("unable to close timer event: {}", close_event_error);
|
||||||
|
} else {
|
||||||
|
// If we reach here, we can safely assert that the close event succeeded without
|
||||||
|
// masking the wait_for_event error.
|
||||||
|
close_event_result?;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire the event that triggered.
|
||||||
|
let event = event_result?;
|
||||||
|
|
||||||
// The first event is the timer event.
|
// The first event is the timer event.
|
||||||
// If it has triggered, the user did not select a numbered entry.
|
// If it has triggered, the user did not select a numbered entry.
|
||||||
@@ -114,7 +133,7 @@ fn select_with_input<'a>(
|
|||||||
info!("Boot Menu:");
|
info!("Boot Menu:");
|
||||||
for (index, entry) in entries.iter().enumerate() {
|
for (index, entry) in entries.iter().enumerate() {
|
||||||
let title = entry.context().stamp(&entry.declaration().title);
|
let title = entry.context().stamp(&entry.declaration().title);
|
||||||
info!(" [{}] {} ({})", index, title, entry.name());
|
info!(" [{}] {}", index, title);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,13 @@ impl OptionsRepresentable for SproutOptions {
|
|||||||
/// All the Sprout options that are defined.
|
/// All the Sprout options that are defined.
|
||||||
fn options() -> &'static [(&'static str, OptionDescription<'static>)] {
|
fn options() -> &'static [(&'static str, OptionDescription<'static>)] {
|
||||||
&[
|
&[
|
||||||
|
(
|
||||||
|
"autoconfigure",
|
||||||
|
OptionDescription {
|
||||||
|
description: "Enable Sprout Autoconfiguration",
|
||||||
|
form: OptionForm::Flag,
|
||||||
|
},
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"config",
|
"config",
|
||||||
OptionDescription {
|
OptionDescription {
|
||||||
|
|||||||
@@ -46,8 +46,24 @@ pub trait OptionsRepresentable {
|
|||||||
let configured: BTreeMap<_, _> = BTreeMap::from_iter(Self::options().to_vec());
|
let configured: BTreeMap<_, _> = BTreeMap::from_iter(Self::options().to_vec());
|
||||||
|
|
||||||
// Collect all the arguments to Sprout.
|
// Collect all the arguments to Sprout.
|
||||||
// Skip the first argument which is the path to our executable.
|
// Skip the first argument, which is the path to our executable.
|
||||||
let args = std::env::args().skip(1).collect::<Vec<_>>();
|
let mut args = std::env::args().skip(1).collect::<Vec<_>>();
|
||||||
|
|
||||||
|
// Correct firmware that may add invalid arguments at the start.
|
||||||
|
// Witnessed this on a Dell Precision 5690 when direct booting.
|
||||||
|
loop {
|
||||||
|
// Grab the first argument or break.
|
||||||
|
let Some(arg) = args.first() else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
|
||||||
|
// If the argument starts with a tilde, remove it.
|
||||||
|
if arg.starts_with("`") {
|
||||||
|
args.remove(0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// Represent options as key-value pairs.
|
// Represent options as key-value pairs.
|
||||||
let mut options = BTreeMap::new();
|
let mut options = BTreeMap::new();
|
||||||
|
|||||||
@@ -53,9 +53,14 @@ fn arch_ticks() -> u64 {
|
|||||||
/// Acquire the tick frequency reported by the platform.
|
/// Acquire the tick frequency reported by the platform.
|
||||||
fn arch_frequency() -> TickFrequency {
|
fn arch_frequency() -> TickFrequency {
|
||||||
#[cfg(target_arch = "aarch64")]
|
#[cfg(target_arch = "aarch64")]
|
||||||
return aarch64::frequency();
|
let frequency = aarch64::frequency();
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
return x86_64::frequency();
|
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.
|
/// Platform timer that allows measurement of the elapsed time.
|
||||||
|
|||||||
@@ -50,17 +50,17 @@ pub fn stop() -> u64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Measure the frequency of the platform timer.
|
/// Measure the frequency of the platform timer.
|
||||||
fn measure_frequency(duration: &Duration) -> u64 {
|
fn measure_frequency() -> u64 {
|
||||||
let start = start();
|
let start = start();
|
||||||
uefi::boot::stall(*duration);
|
uefi::boot::stall(MEASURE_FREQUENCY_DURATION);
|
||||||
let stop = stop();
|
let stop = stop();
|
||||||
let elapsed = stop.wrapping_sub(start) as f64;
|
let elapsed = stop.wrapping_sub(start) as f64;
|
||||||
(elapsed / duration.as_secs_f64()) as u64
|
(elapsed / MEASURE_FREQUENCY_DURATION.as_secs_f64()) as u64
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Acquire the platform timer frequency.
|
/// Acquire the platform timer frequency.
|
||||||
/// On x86_64, this is slightly expensive, so it should be done once.
|
/// On x86_64, this is slightly expensive, so it should be done once.
|
||||||
pub fn frequency() -> TickFrequency {
|
pub fn frequency() -> TickFrequency {
|
||||||
let frequency = measure_frequency(&MEASURE_FREQUENCY_DURATION);
|
let frequency = measure_frequency();
|
||||||
TickFrequency::Measured(frequency, MEASURE_FREQUENCY_DURATION)
|
TickFrequency::Measured(frequency, MEASURE_FREQUENCY_DURATION)
|
||||||
}
|
}
|
||||||
|
|||||||
24
src/utils.rs
24
src/utils.rs
@@ -1,4 +1,4 @@
|
|||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result, bail};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use uefi::boot::SearchType;
|
use uefi::boot::SearchType;
|
||||||
use uefi::fs::{FileSystem, Path};
|
use uefi::fs::{FileSystem, Path};
|
||||||
@@ -18,6 +18,9 @@ pub mod media_loader;
|
|||||||
/// Support code for EFI variables.
|
/// Support code for EFI variables.
|
||||||
pub mod variables;
|
pub mod variables;
|
||||||
|
|
||||||
|
/// Implements a version comparison algorithm according to the BLS specification.
|
||||||
|
pub mod vercmp;
|
||||||
|
|
||||||
/// Parses the input `path` as a [DevicePath].
|
/// Parses the input `path` as a [DevicePath].
|
||||||
/// Uses the [DevicePathFromText] protocol exclusively, and will fail if it cannot acquire the protocol.
|
/// Uses the [DevicePathFromText] protocol exclusively, and will fail if it cannot acquire the protocol.
|
||||||
pub fn text_to_device_path(path: &str) -> Result<PoolDevicePath> {
|
pub fn text_to_device_path(path: &str) -> Result<PoolDevicePath> {
|
||||||
@@ -272,3 +275,22 @@ pub fn find_handle(protocol: &Guid) -> Result<Option<Handle>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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")
|
||||||
|
}
|
||||||
|
|||||||
@@ -33,8 +33,6 @@ struct MediaLoaderProtocol {
|
|||||||
/// You MUST call [MediaLoaderHandle::unregister] when ready to unregister.
|
/// You MUST call [MediaLoaderHandle::unregister] when ready to unregister.
|
||||||
/// [Drop] is not implemented for this type.
|
/// [Drop] is not implemented for this type.
|
||||||
pub struct MediaLoaderHandle {
|
pub struct MediaLoaderHandle {
|
||||||
/// The vendor GUID of the media loader.
|
|
||||||
guid: Guid,
|
|
||||||
/// The handle of the media loader in the UEFI stack.
|
/// The handle of the media loader in the UEFI stack.
|
||||||
handle: Handle,
|
handle: Handle,
|
||||||
/// The protocol interface pointer.
|
/// The protocol interface pointer.
|
||||||
@@ -229,7 +227,6 @@ impl MediaLoaderHandle {
|
|||||||
|
|
||||||
// Return a handle to the media loader.
|
// Return a handle to the media loader.
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
guid,
|
|
||||||
handle: primary_handle,
|
handle: primary_handle,
|
||||||
protocol,
|
protocol,
|
||||||
path,
|
path,
|
||||||
@@ -239,13 +236,8 @@ impl MediaLoaderHandle {
|
|||||||
/// Unregisters a media loader from the UEFI stack.
|
/// Unregisters a media loader from the UEFI stack.
|
||||||
/// This will free the memory allocated by the passed data.
|
/// This will free the memory allocated by the passed data.
|
||||||
pub fn unregister(self) -> Result<()> {
|
pub fn unregister(self) -> Result<()> {
|
||||||
// Check if the media loader is registered.
|
// SAFETY: We know that the media loader is registered if the handle is valid,
|
||||||
// If it is not, we don't need to do anything.
|
// so we can safely uninstall it.
|
||||||
if !Self::already_registered(self.guid)? {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
// SAFETY: We know that the media loader is registered, so we can safely uninstall it.
|
|
||||||
// We should have allocated the pointers involved, so we can safely free them.
|
// We should have allocated the pointers involved, so we can safely free them.
|
||||||
unsafe {
|
unsafe {
|
||||||
// Uninstall the protocol interface for the device path protocol.
|
// Uninstall the protocol interface for the device path protocol.
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
use crate::utils;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
|
use log::warn;
|
||||||
use uefi::{CString16, guid};
|
use uefi::{CString16, guid};
|
||||||
use uefi_raw::Status;
|
use uefi_raw::Status;
|
||||||
use uefi_raw::table::runtime::{VariableAttributes, VariableVendor};
|
use uefi_raw::table::runtime::{VariableAttributes, VariableVendor};
|
||||||
@@ -44,6 +46,41 @@ impl VariableController {
|
|||||||
CString16::try_from(key).context("unable to convert variable name to 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 utils::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`.
|
/// Retrieve a boolean value specified by the `key`.
|
||||||
pub fn get_bool(&self, key: &str) -> Result<bool> {
|
pub fn get_bool(&self, key: &str) -> Result<bool> {
|
||||||
let name = Self::name(key)?;
|
let name = Self::name(key)?;
|
||||||
@@ -98,4 +135,18 @@ impl VariableController {
|
|||||||
pub fn set_bool(&self, key: &str, value: bool, class: VariableClass) -> Result<()> {
|
pub fn set_bool(&self, key: &str, value: bool, class: VariableClass) -> Result<()> {
|
||||||
self.set(key, &[value as u8], class)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
184
src/utils/vercmp.rs
Normal file
184
src/utils/vercmp.rs
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::iter::Peekable;
|
||||||
|
|
||||||
|
/// Handles single character advancement and comparison.
|
||||||
|
macro_rules! handle_single_char {
|
||||||
|
($ca: expr, $cb:expr, $a_chars:expr, $b_chars:expr, $c:expr) => {
|
||||||
|
match ($ca == $c, $cb == $c) {
|
||||||
|
(true, false) => return Ordering::Less,
|
||||||
|
(false, true) => return Ordering::Greater,
|
||||||
|
(true, true) => {
|
||||||
|
$a_chars.next();
|
||||||
|
$b_chars.next();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares two strings using the BLS version comparison specification.
|
||||||
|
/// Handles optional values as well by comparing only if both are specified.
|
||||||
|
pub fn compare_versions_optional(a: Option<&str>, b: Option<&str>) -> Ordering {
|
||||||
|
match (a, b) {
|
||||||
|
// If both have values, compare them.
|
||||||
|
(Some(a), Some(b)) => compare_versions(a, b),
|
||||||
|
// If the second value is None, return that it is less than the first.
|
||||||
|
(Some(_a), None) => Ordering::Less,
|
||||||
|
// If the first value is None, return that it is greater than the second.
|
||||||
|
(None, Some(_b)) => Ordering::Greater,
|
||||||
|
// If both values are None, return that they are equal.
|
||||||
|
(None, None) => Ordering::Equal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares two strings using the BLS version comparison specification.
|
||||||
|
/// See: https://uapi-group.org/specifications/specs/version_format_specification/
|
||||||
|
pub fn compare_versions(a: &str, b: &str) -> Ordering {
|
||||||
|
// Acquire a peekable iterator for each string.
|
||||||
|
let mut a_chars = a.chars().peekable();
|
||||||
|
let mut b_chars = b.chars().peekable();
|
||||||
|
|
||||||
|
// Loop until we have reached the end of one of the strings.
|
||||||
|
loop {
|
||||||
|
// Skip invalid characters in both strings.
|
||||||
|
skip_invalid(&mut a_chars);
|
||||||
|
skip_invalid(&mut b_chars);
|
||||||
|
|
||||||
|
// Check if either string has ended.
|
||||||
|
match (a_chars.peek(), b_chars.peek()) {
|
||||||
|
// No more characters in either string.
|
||||||
|
(None, None) => return Ordering::Equal,
|
||||||
|
// One string has ended, the other hasn't.
|
||||||
|
(None, Some(_)) => return Ordering::Less,
|
||||||
|
(Some(_), None) => return Ordering::Greater,
|
||||||
|
// Both strings have characters left.
|
||||||
|
(Some(&ca), Some(&cb)) => {
|
||||||
|
// Handle the ~ character.
|
||||||
|
handle_single_char!(ca, cb, a_chars, b_chars, '~');
|
||||||
|
|
||||||
|
// Handle '-' character.
|
||||||
|
handle_single_char!(ca, cb, a_chars, b_chars, '-');
|
||||||
|
|
||||||
|
// Handle the '^' character.
|
||||||
|
handle_single_char!(ca, cb, a_chars, b_chars, '^');
|
||||||
|
|
||||||
|
// Handle the '.' character.
|
||||||
|
handle_single_char!(ca, cb, a_chars, b_chars, '.');
|
||||||
|
|
||||||
|
// Handle digits with numerical comparison.
|
||||||
|
// We key off of the A character being a digit intentionally as we presume
|
||||||
|
// this indicates it will be the same at this position.
|
||||||
|
if ca.is_ascii_digit() || cb.is_ascii_digit() {
|
||||||
|
let result = compare_numeric(&mut a_chars, &mut b_chars);
|
||||||
|
if result != Ordering::Equal {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle letters with alphabetical comparison.
|
||||||
|
// We key off of the A character being alphabetical intentionally as we presume
|
||||||
|
// this indicates it will be the same at this position.
|
||||||
|
if ca.is_ascii_alphabetic() || cb.is_ascii_alphabetic() {
|
||||||
|
let result = compare_alphabetic(&mut a_chars, &mut b_chars);
|
||||||
|
if result != Ordering::Equal {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Skips characters that are not in the valid character set.
|
||||||
|
fn skip_invalid<I: Iterator<Item = char>>(iter: &mut Peekable<I>) {
|
||||||
|
while let Some(&c) = iter.peek() {
|
||||||
|
if is_valid_char(c) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
iter.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks if a character is in the valid character set for comparison.
|
||||||
|
fn is_valid_char(c: char) -> bool {
|
||||||
|
matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '.' | '~' | '^')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares numerical prefixes by extracting numbers.
|
||||||
|
fn compare_numeric<I: Iterator<Item = char>>(
|
||||||
|
iter_a: &mut Peekable<I>,
|
||||||
|
iter_b: &mut Peekable<I>,
|
||||||
|
) -> Ordering {
|
||||||
|
let num_a = extract_number(iter_a);
|
||||||
|
let num_b = extract_number(iter_b);
|
||||||
|
|
||||||
|
num_a.cmp(&num_b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts a number from the iterator, skipping leading zeros.
|
||||||
|
fn extract_number<I: Iterator<Item = char>>(iter: &mut Peekable<I>) -> u64 {
|
||||||
|
// Skip leading zeros
|
||||||
|
while let Some(&'0') = iter.peek() {
|
||||||
|
iter.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut num = 0u64;
|
||||||
|
while let Some(&c) = iter.peek() {
|
||||||
|
if c.is_ascii_digit() {
|
||||||
|
iter.next();
|
||||||
|
num = num.saturating_mul(10).saturating_add(c as u64 - '0' as u64);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
num
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares alphabetical prefixes
|
||||||
|
/// Capital letters compare lower than lowercase letters (B < a)
|
||||||
|
fn compare_alphabetic<I: Iterator<Item = char>>(
|
||||||
|
iter_a: &mut Peekable<I>,
|
||||||
|
iter_b: &mut Peekable<I>,
|
||||||
|
) -> Ordering {
|
||||||
|
loop {
|
||||||
|
return match (iter_a.peek(), iter_b.peek()) {
|
||||||
|
(Some(&ca), Some(&cb)) if ca.is_ascii_alphabetic() && cb.is_ascii_alphabetic() => {
|
||||||
|
if ca == cb {
|
||||||
|
// Same character, we should continue.
|
||||||
|
iter_a.next();
|
||||||
|
iter_b.next();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Different characters found.
|
||||||
|
// All capital letters compare lower than lowercase letters.
|
||||||
|
match (ca.is_ascii_uppercase(), cb.is_ascii_uppercase()) {
|
||||||
|
(true, false) => Ordering::Less, // uppercase < lowercase
|
||||||
|
(false, true) => Ordering::Greater, // lowercase > uppercase
|
||||||
|
(true, true) => ca.cmp(&cb), // both are uppercase
|
||||||
|
(false, false) => ca.cmp(&cb), // both are lowercase
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(Some(&ca), Some(_)) if ca.is_ascii_alphabetic() => {
|
||||||
|
// a has letters, b doesn't
|
||||||
|
Ordering::Greater
|
||||||
|
}
|
||||||
|
|
||||||
|
(Some(_), Some(&cb)) if cb.is_ascii_alphabetic() => {
|
||||||
|
// b has letters, a doesn't
|
||||||
|
Ordering::Less
|
||||||
|
}
|
||||||
|
|
||||||
|
(Some(&ca), None) if ca.is_ascii_alphabetic() => Ordering::Greater,
|
||||||
|
|
||||||
|
(None, Some(&cb)) if cb.is_ascii_alphabetic() => Ordering::Less,
|
||||||
|
|
||||||
|
_ => Ordering::Equal,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user