feat(restore): persist FDR commits in a verified two-slot USB journal

This commit is contained in:
Tyler Smith committed 2026-10-26 04:46:59 +00:00
1 parent 1d9cca072e
commit a497fe2ee5
13 files changed
+1044 -30

No files matched your search

+15 -1
View File
@@ -10,6 +10,7 @@
pub(crate) mod bundle;
mod console_lines;
mod display;
pub(crate) mod fdr;
pub(crate) mod host;
mod input;
pub(crate) mod install;
@@ -1223,6 +1224,12 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
.find(|file| file.name() == translations::FILE)
.and_then(|file| translations::install(bundle::contents(file)))
.filter(|_| handoff.storage.present);
let fdr_placement = restore::inventory_file(handoff, stela_runtime::restore::fdr::FILE)
.map(fdr::Placement::parse)
.transpose()
.unwrap_or_else(|error| output::fatal(&error));
let fdr_partition = fdr_placement.as_ref().map(|placement| placement.partition);
let mut fdr_device = None;
// `--nor` naming the `--storage` partition keeps the machine state in
// that partition's tail (`pc::machine_state`): one device, split below.
let state_in_storage = options.nor.is_some() && options.nor == options.storage;
@@ -1269,6 +1276,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
&& !options.external_disks
&& !options.guest_network
&& translation_store.is_none()
&& fdr_partition.is_none()
{
(
Vec::new(),
@@ -1298,6 +1306,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
preboot,
store,
log,
fdr,
inputs,
mut links,
usb_disks,
@@ -1311,6 +1320,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
preboot: options.preboot.as_ref(),
store: translation_store,
log: handoff.log_partition.map(Guid),
fdr: fdr_partition,
},
&options.usb_storage,
options.external_disks.then(|| {
@@ -1344,6 +1354,7 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
if let Some(store) = store {
translations::set_partition(store);
}
fdr_device = fdr;
// The guest's adapter is its own: the mount's client keeps the
// first one. Without one the Mac boots with no network, which
// is reported once.
@@ -2136,7 +2147,10 @@ pub extern "sysv64" fn entry(handoff: u64) -> ! {
true => Verify::OnRead,
false => Verify::Full,
},
signer,
restore::Services {
signer,
fdr_storage: fdr_device.take(),
},
)
.unwrap_or_else(|error| {
output::arguments(format_args!("restore preparation refusal: {error}\n"));
+27 -2
View File
@@ -263,11 +263,36 @@ pub fn with_inventory(
match root.open(&diagnostic_name, FileMode::Read, FileAttribute::empty()) {
Ok(file) => {
drop(file);
Some(read_bounded(
let seed = read_bounded(
&mut root,
&diagnostic_path,
stela_runtime::restore::fdr::MAX_BYTES as u64,
)?)
)?;
let state_path = format!("{directory}\\{}", super::fdr::STATE_FILE);
let image = read_bounded(
&mut root,
&state_path,
stela_runtime::pc::fdr_store::FILE_BYTES as u64,
)
.map_err(|_| "FDR diagnostic needs its preallocated fdr-state.bin")?;
let partition = super::translations::partition(handle)
.ok_or("FDR storage volume needs a GPT partition identity")?;
// SAFETY: both regions were just read into retained loader pages.
let bytes = |region: Region| unsafe {
core::slice::from_raw_parts(
region.physical as *const u8,
region.bytes as usize,
)
};
let path = state_path.trim_start_matches('\\').replace('\\', "/");
Some(
super::fdr::prepare(partition, &path, bytes(seed), bytes(image)).map_err(
|error| {
output::arguments(format_args!("FDR state refusal: {error}\n"));
"FDR persisted state could not be loaded"
},
)?,
)
}
Err(error) if error.status() == uefi::Status::NOT_FOUND => None,
Err(_) => return Err("cannot open the FDR diagnostic"),
+140
View File
@@ -0,0 +1,140 @@
//! Host-owned durable FDR storage. The loader identifies one preallocated
//! file; the engine writes only its existing FAT clusters through host drivers.
use super::bundle::Bytes;
use crate::{firmware, handoff::Region, output, paging::PAGE};
use alloc::{boxed::Box, format, string::String};
use sha2::{Digest, Sha256};
use stela_drivers::block::{BlockDevice, Shared};
use stela_runtime::{
pc::{boot_log, fat32::Fat32, fdr_store, gpt::Guid},
restore::{self, answers::FdrCommit, fdr::Diagnostic},
};
pub const STATE_FILE: &str = stela_runtime::restore::fdr::STATE_FILE;
const MAGIC: &[u8; 8] = b"STLFDRH1";
const HEADER: usize = 80;
fn digest(bytes: &[u8]) -> [u8; 32] {
Sha256::digest(bytes).into()
}
pub struct Placement<'a> {
pub partition: Guid,
pub path: &'a str,
pub diagnostic: &'a [u8],
snapshot: Option<[u8; 32]>,
}
impl<'a> Placement<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self, String> {
if bytes.len() < HEADER || &bytes[..8] != MAGIC {
return Err(String::from("invalid FDR storage placement"));
}
let word = |at| u32::from_le_bytes(bytes[at..at + 4].try_into().expect("word")) as usize;
let path_end = HEADER
.checked_add(word(24))
.ok_or("FDR placement overflow")?;
let end = path_end
.checked_add(word(28))
.ok_or("FDR placement overflow")?;
if end != bytes.len() || word(64) > 1 {
return Err(String::from("invalid FDR placement length/flags"));
}
let path = core::str::from_utf8(bytes.get(HEADER..path_end).ok_or("FDR path bounds")?)
.map_err(|_| "FDR path is not UTF-8")?;
if !stela_runtime::payload::safe_path(path) {
return Err(String::from("invalid FDR state file path"));
}
Ok(Self {
partition: Guid(bytes[8..24].try_into().expect("GUID")),
path,
diagnostic: &bytes[path_end..end],
snapshot: (word(64) == 1).then(|| bytes[32..64].try_into().expect("digest")),
})
}
}
/// One existing handoff slot carries placement plus selected diagnostic. No
/// extra file slot is consumed, and committed state retains the seed identity.
pub fn prepare(
partition: [u8; 16],
path: &str,
seed: &[u8],
image: &[u8],
) -> Result<Region, String> {
let initial = Diagnostic::decode(seed).map_err(|e| format!("FDR seed: {e}"))?;
let snapshot = fdr_store::read_image(image).map_err(|e| format!("FDR stored state: {e}"))?;
if let Some(snapshot) = &snapshot {
let stored =
Diagnostic::decode(snapshot).map_err(|e| format!("FDR stored binding: {e}"))?;
if !initial.same_identity(&stored) {
return Err(String::from(
"FDR stored state belongs to another machine/build",
));
}
}
let diagnostic = snapshot.as_deref().unwrap_or(seed);
let bytes = HEADER + path.len() + diagnostic.len();
let physical = firmware::pages(bytes.div_ceil(PAGE)).map_err(String::from)?;
// SAFETY: fresh loader pages, retained for the whole boot.
let buffer = unsafe { core::slice::from_raw_parts_mut(physical as *mut u8, bytes) };
buffer.fill(0);
buffer[..8].copy_from_slice(MAGIC);
buffer[8..24].copy_from_slice(&partition);
buffer[24..28].copy_from_slice(&(path.len() as u32).to_le_bytes());
buffer[28..32].copy_from_slice(&(diagnostic.len() as u32).to_le_bytes());
if let Some(snapshot) = &snapshot {
buffer[32..64].copy_from_slice(&digest(snapshot));
buffer[64..68].copy_from_slice(&1u32.to_le_bytes());
}
buffer[HEADER..HEADER + path.len()].copy_from_slice(path.as_bytes());
buffer[HEADER + path.len()..].copy_from_slice(diagnostic);
output::arguments(format_args!(
"FDR STORAGE loaded committed={} bytes={}; file={path}\n",
snapshot.is_some(),
diagnostic.len()
));
Ok(Region {
physical: physical as u64,
bytes: bytes as u64,
})
}
pub fn writer(
partition: Box<dyn BlockDevice>,
placement: &Placement<'_>,
) -> Result<FdrCommit, String> {
let block = u64::from(partition.identity().block_size);
let mut volume = Fat32::open(Bytes::new(partition)).map_err(|e| format!("FDR FAT: {e}"))?;
let file = volume
.file(placement.path)
.map_err(|e| format!("FDR state file: {e}"))?;
if file.bytes != fdr_store::FILE_BYTES as u64 {
return Err(String::from("FDR state file must be exactly 4 MiB"));
}
let runs = boot_log::file_runs(&file, block, fdr_store::FILE_BYTES as u64)
.map_err(|e| format!("FDR state extents: {e}"))?;
let partition = volume.into_inner().into_inner();
let mut device = Shared::new(partition)
.runs(runs)
.map_err(|e| format!("FDR state view: {e}"))?;
let mut journal =
fdr_store::Journal::open(&mut device).map_err(|e| format!("FDR journal: {e}"))?;
let actual = journal.snapshot().map(digest);
if actual != placement.snapshot {
return Err(String::from(
"FDR state changed between firmware and engine reads",
));
}
Ok(Box::new(move |bytes| {
journal
.commit(&mut device, bytes)
.map_err(|e| restore::Error::Transport(format!("FDR durable commit: {e}")))?;
output::arguments(format_args!(
"FDR COMMIT durable bytes={} sha256={} flushed/readback verified\n",
bytes.len(),
stela_runtime::sha256(bytes)
));
Ok(())
}))
}
+18 -5
View File
@@ -159,6 +159,12 @@ pub struct Experiment {
ledger: usize,
mode: Mode,
}
/// Native services retained for the whole restore session.
pub struct Services {
pub signer: Option<stela_runtime::restore::tss::Signer>,
pub fdr_storage: Option<Box<dyn BlockDevice>>,
}
impl Experiment {
/// The study runs `identity`; the install the inventory's one Erase
/// identity, and the update its one Update identity. The payload is
@@ -172,8 +178,12 @@ impl Experiment {
mode: Mode,
identity: Option<usize>,
verify: Verify,
signer: Option<stela_runtime::restore::tss::Signer>,
services: Services,
) -> Result<Self, String> {
let Services {
signer,
fdr_storage,
} = services;
let manifest = inventory(handoff)?;
let purpose = match mode {
Mode::Update => Purpose::Update,
@@ -226,14 +236,17 @@ impl Experiment {
}
let mut answers = Answers::new(store);
if let Some(bytes) = inventory_file(handoff, stela_runtime::restore::fdr::FILE) {
let placement = super::fdr::Placement::parse(bytes)?;
answers.fdr_diagnostic = Some(
stela_runtime::restore::fdr::Diagnostic::decode(bytes)
stela_runtime::restore::fdr::Diagnostic::decode(placement.diagnostic)
.map_err(|error| format!("FDR diagnostic refused: {error}"))?,
);
let device = fdr_storage.ok_or("the required FDR storage volume was not opened")?;
answers.fdr_commit = Some(super::fdr::writer(device, &placement)?);
output::arguments(format_args!(
"FDR DIAGNOSTIC bytes={} sha256={} original Memory-store import; factory trust unqualified; durable commit unsupported\n",
bytes.len(),
stela_runtime::sha256(bytes),
"FDR DIAGNOSTIC bytes={} sha256={} original Memory-store import; durable host commit enabled; factory trust unqualified\n",
placement.diagnostic.len(),
stela_runtime::sha256(placement.diagnostic),
));
}
if signer.is_some() {
+7
View File
@@ -130,6 +130,8 @@ pub struct Partitions<'a> {
pub store: Option<Guid>,
/// The USB's boot log, by its GUID; left out when it cannot open.
pub log: Option<Guid>,
/// Required host-owned durable FDR file volume, when explicitly staged.
pub fdr: Option<Guid>,
}
/// Open the explicitly selected partitions while the loader's identity root
@@ -153,6 +155,7 @@ pub unsafe fn open(
preboot,
store,
log,
fdr,
} = *partitions;
if let Some(serial) = usb_disks
.iter()
@@ -224,6 +227,7 @@ pub unsafe fn open(
.map(|target| Named::Disk((*target).clone()))
.chain(medium.map(Named::Unique))
.chain(preboot.map(|target| Named::Disk(target.clone())))
.chain(fdr.map(Named::Host))
.collect();
let required = named.len();
let mut optional: Vec<(Named, Optional)> = store
@@ -280,6 +284,7 @@ pub unsafe fn open(
Optional::Log => log_partition = partition,
}
}
let fdr = fdr.map(|_| service(opened.pop().expect("FDR storage"), " (FDR storage)"));
let preboot = preboot.map(|_| {
service(
opened.pop().expect("the installed system"),
@@ -339,6 +344,7 @@ pub unsafe fn open(
preboot,
store: store_partition,
log: log_partition,
fdr,
inputs,
links,
usb_disks,
@@ -374,6 +380,7 @@ pub struct Opened {
pub store: Option<Box<dyn BlockDevice>>,
/// The partition holding the USB's boot log, found by its GUID.
pub log: Option<Box<dyn BlockDevice>>,
pub fdr: Option<Box<dyn BlockDevice>>,
pub inputs: Inputs,
pub links: super::network::Links,
/// Whole disks for the guest's USB mass storage, in option order.
+1
View File
@@ -50,6 +50,7 @@
mod bundle;
mod doctor;
mod ecid;
mod fdr;
mod firmware;
pub(crate) mod host;
mod installed;
+101
View File
@@ -0,0 +1,101 @@
//! Initialize durable storage only for an explicitly staged FDR diagnostic.
//! Existing commits are validated and preserved, never replaced by the seed.
use super::Record;
use crate::efi;
use anyhow::{Context, Result, ensure};
use std::{fs, io::ErrorKind, path::Path};
use stela_runtime::{
pc::fdr_store,
restore::fdr::{self, Diagnostic},
};
pub(super) fn prepare(record: &Record, dry_run: bool) -> Result<String> {
let mut report = String::new();
for medium in &record.media {
if prepare_directory(&medium.directory(), dry_run)? {
report.push_str(
" FDR storage initialize a 4 MiB journal from the staged diagnostic\n",
);
}
}
Ok(report)
}
fn prepare_directory(directory: &Path, dry_run: bool) -> Result<bool> {
let seed = match fs::read(directory.join(fdr::FILE)) {
Ok(bytes) => bytes,
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error).context("cannot read staged FDR diagnostic"),
};
let initial =
Diagnostic::decode(&seed).map_err(|e| anyhow::anyhow!("invalid FDR seed: {e}"))?;
let path = directory.join(fdr::STATE_FILE);
match fs::read(&path) {
Ok(image) => {
let snapshot = fdr_store::read_image(&image)?.context(
"existing FDR journal is uninitialized; preserve it and repair explicitly",
)?;
let stored = Diagnostic::decode(&snapshot)
.map_err(|e| anyhow::anyhow!("invalid FDR stored binding: {e}"))?;
ensure!(
initial.same_identity(&stored),
"FDR journal belongs to another machine/build"
);
return Ok(false);
}
Err(error) if error.kind() == ErrorKind::NotFound => (),
Err(error) => return Err(error).context("cannot read FDR journal"),
}
if !dry_run {
let image = fdr_store::initial_image(&seed)?;
efi::write_atomic(&path, &image, true)?;
ensure!(
fs::read(&path)? == image,
"FDR journal readback differs after initialization"
);
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use stela_runtime::restore::plist::{self, Limits, Value};
#[test]
fn initialization_is_opt_in_atomic_and_never_replaces_committed_records() {
let dir = tempfile::tempdir().unwrap();
assert!(!prepare_directory(dir.path(), false).unwrap());
let value = Value::dict([
("DiagnosticVersion", Value::Integer(1)),
("ECID", Value::Integer(42)),
("ChipID", Value::Integer(8)),
("BoardID", Value::Integer(9)),
("Build", Value::from("test")),
("Model", Value::from("test")),
(
"FDRMemoryStoreData",
Value::dict([("class-own", Value::Data(vec![1]))]),
),
]);
let seed = plist::encode_binary(&value, Limits::default()).unwrap();
fs::write(dir.path().join(fdr::FILE), &seed).unwrap();
assert!(prepare_directory(dir.path(), true).unwrap());
let path = dir.path().join(fdr::STATE_FILE);
assert!(!path.exists());
assert!(prepare_directory(dir.path(), false).unwrap());
assert_eq!(
fdr_store::read_image(&fs::read(&path).unwrap()).unwrap(),
Some(seed.clone())
);
let initial = Diagnostic::decode(&seed).unwrap();
let committed = initial.with_records(Value::dict([])).unwrap();
let image = fdr_store::initial_image(&committed).unwrap();
fs::write(&path, &image).unwrap();
assert!(!prepare_directory(dir.path(), false).unwrap());
assert_eq!(fs::read(&path).unwrap(), image);
fs::write(&path, vec![7; fdr_store::FILE_BYTES]).unwrap();
assert!(prepare_directory(dir.path(), false).is_err());
assert_eq!(fs::read(&path).unwrap(), vec![7; fdr_store::FILE_BYTES]);
}
}
+5
View File
@@ -295,7 +295,11 @@ pub(super) fn update_stela(
};
let mut text = String::new();
writeln!(text, "Stela update on {}:", esp.display())?;
text.push_str(&super::fdr::prepare(&record, true)?);
if from == to && record.pending.is_none() && from_generation == to_generation {
if !dry_run {
super::fdr::prepare(&record, false)?;
}
writeln!(text, " stela.efi version {to} is already installed")?;
if let Some(store) = &record.translations
&& (!store.config_intact() || !store.spare_ready())
@@ -437,6 +441,7 @@ pub(super) fn update_stela(
if let Some(store) = &record.translations {
store.publish()?;
}
super::fdr::prepare(&record, false)?;
activate_stela(&esp, &to)?;
publish(&mut record)?;
record.stela_version = Some(to.clone());
+1
View File
@@ -15,6 +15,7 @@ pub mod acpi;
pub mod boot_log;
pub mod display;
pub mod fat32;
pub mod fdr_store;
pub mod gpt;
pub mod machine_state;
pub mod power;
@@ -0,0 +1,595 @@
//! Durable, bounded FDR host-response storage in a preallocated file view.
//!
//! Two independent slots retain the previous commit while the next payload,
//! then its header, are flushed. Checksums detect damage; they authenticate
//! neither the records nor their author. The caller supplies an exclusive
//! block-device view of exactly [`FILE_BYTES`], never a whole filesystem.
use alloc::{vec, vec::Vec};
use core::fmt;
use sha2::{Digest, Sha256};
use stela_drivers::block::{BlockDevice, BlockError};
pub const FILE_BYTES: usize = 4 << 20;
pub const MAX_PAYLOAD: usize = 1 << 20;
const SLOT_BYTES: usize = FILE_BYTES / 2;
const HEADER_BYTES: usize = 4096;
const MAGIC: &[u8; 8] = b"STELAFDR";
const VERSION: u32 = 1;
const HEADER_DIGEST: usize = 64;
const HEADER_RECORD: usize = HEADER_DIGEST + 32;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
ImageSize {
bytes: usize,
},
BlockSize(u32),
DeviceSize {
blocks: u64,
block_size: u32,
},
PayloadSize {
bytes: usize,
},
/// Nonblank storage without a valid slot, or ambiguous generations.
Corrupt,
SequenceExhausted,
/// A preceding failed commit may have reached storage. Reopen first.
NeedsReopen,
/// The reopened device does not hold the state this journal loaded.
Changed,
Readback,
Device(BlockError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ImageSize { bytes } => {
write!(f, "FDR journal has {bytes} bytes; needs {FILE_BYTES}")
}
Self::BlockSize(size) => write!(f, "FDR journal does not support {size}-byte sectors"),
Self::DeviceSize { blocks, block_size } => write!(
f,
"FDR journal device has {blocks} sectors of {block_size} bytes; needs {FILE_BYTES} bytes"
),
Self::PayloadSize { bytes } => {
write!(f, "FDR payload has {bytes} bytes; needs 1..={MAX_PAYLOAD}")
}
Self::Corrupt => f.write_str("FDR journal is damaged or has ambiguous generations"),
Self::SequenceExhausted => f.write_str("FDR journal sequence is exhausted"),
Self::NeedsReopen => f.write_str("FDR journal must be reopened after a failed commit"),
Self::Changed => f.write_str("FDR journal changed since it was opened"),
Self::Readback => f.write_str("FDR journal readback does not match the commit"),
Self::Device(error) => write!(f, "FDR journal device: {error}"),
}
}
}
impl core::error::Error for Error {}
impl From<BlockError> for Error {
fn from(error: BlockError) -> Self {
Self::Device(error)
}
}
#[derive(Debug, PartialEq, Eq)]
struct Record {
slot: usize,
sequence: u64,
payload: Vec<u8>,
}
/// One exclusive journal session. A failed write/flush/readback requires
/// reopening: its header may have committed even though no acknowledgement
/// was returned. `snapshot` keeps the last successfully acknowledged state.
#[derive(Debug)]
pub struct Journal {
record: Option<Record>,
needs_reopen: bool,
}
impl Journal {
pub fn open(device: &mut dyn BlockDevice) -> Result<Self, Error> {
Ok(Self {
record: read_device(device)?,
needs_reopen: false,
})
}
pub fn snapshot(&self) -> Option<&[u8]> {
self.record.as_ref().map(|record| record.payload.as_slice())
}
/// Return success only after both flushes and independent readback.
pub fn commit(&mut self, device: &mut dyn BlockDevice, bytes: &[u8]) -> Result<(), Error> {
if self.needs_reopen {
return Err(Error::NeedsReopen);
}
if bytes.is_empty() || bytes.len() > MAX_PAYLOAD {
return Err(Error::PayloadSize { bytes: bytes.len() });
}
let block = geometry(device)?;
if device.identity().read_only {
return Err(BlockError::ReadOnly.into());
}
let sequence = self
.record
.as_ref()
.map_or(Some(1), |record| record.sequence.checked_add(1))
.ok_or(Error::SequenceExhausted)?;
// Refuse stale sessions and unexpected backing data before mutation.
if read_device(device)? != self.record {
return Err(Error::Changed);
}
let slot = self.record.as_ref().map_or(0, |record| 1 - record.slot);
let offset = slot * SLOT_BYTES;
let mut payload = vec![0; bytes.len().div_ceil(block) * block];
payload[..bytes.len()].copy_from_slice(bytes);
let header = encode_header(sequence, bytes);
// Even an error from the first write can have changed the medium.
self.needs_reopen = true;
device.write(((offset + HEADER_BYTES) / block) as u64, &payload)?;
device.flush()?;
device.write((offset / block) as u64, &header)?;
device.flush()?;
let mut readback = vec![0; SLOT_BYTES];
device.read((offset / block) as u64, &mut readback)?;
let record = decode_slot(slot, &readback).ok_or(Error::Readback)?;
if record.sequence != sequence || record.payload != bytes {
return Err(Error::Readback);
}
self.record = Some(record);
self.needs_reopen = false;
Ok(())
}
}
/// Read the same format from firmware file bytes before ExitBootServices.
/// An entirely zero file is uninitialized. Damage never becomes empty state.
pub fn read_image(bytes: &[u8]) -> Result<Option<Vec<u8>>, Error> {
Ok(select(bytes)?.map(|record| record.payload))
}
/// Build a first committed image for atomic publication by a host file tool.
/// Seeding before boot leaves a valid old slot during the first guest commit.
pub fn initial_image(payload: &[u8]) -> Result<Vec<u8>, Error> {
if payload.is_empty() || payload.len() > MAX_PAYLOAD {
return Err(Error::PayloadSize {
bytes: payload.len(),
});
}
let mut image = vec![0; FILE_BYTES];
image[..HEADER_BYTES].copy_from_slice(&encode_header(1, payload));
image[HEADER_BYTES..HEADER_BYTES + payload.len()].copy_from_slice(payload);
Ok(image)
}
fn geometry(device: &dyn BlockDevice) -> Result<usize, Error> {
let identity = device.identity();
if !matches!(identity.block_size, 512 | 4096) {
return Err(Error::BlockSize(identity.block_size));
}
let block = identity.block_size as usize;
if identity.blocks != (FILE_BYTES / block) as u64 {
return Err(Error::DeviceSize {
blocks: identity.blocks,
block_size: identity.block_size,
});
}
Ok(block)
}
fn read_device(device: &mut dyn BlockDevice) -> Result<Option<Record>, Error> {
geometry(device)?;
let mut image = vec![0; FILE_BYTES];
device.read(0, &mut image)?;
select(&image)
}
fn select(bytes: &[u8]) -> Result<Option<Record>, Error> {
if bytes.len() != FILE_BYTES {
return Err(Error::ImageSize { bytes: bytes.len() });
}
match (
decode_slot(0, &bytes[..SLOT_BYTES]),
decode_slot(1, &bytes[SLOT_BYTES..]),
) {
(Some(a), Some(b)) if a.sequence == b.sequence => Err(Error::Corrupt),
(Some(a), Some(b)) => Ok(Some(if a.sequence > b.sequence { a } else { b })),
(Some(record), None) | (None, Some(record)) => Ok(Some(record)),
(None, None) if bytes.iter().all(|&byte| byte == 0) => Ok(None),
(None, None) => Err(Error::Corrupt),
}
}
// Header, little endian: magic[8], version:u32, header_bytes:u32,
// sequence:u64, payload_bytes:u64, SHA256(payload)[32], SHA256(header)[32].
// The header digest field is zeroed for hashing; remaining bytes are zero.
fn encode_header(sequence: u64, payload: &[u8]) -> [u8; HEADER_BYTES] {
let mut header = [0; HEADER_BYTES];
header[..8].copy_from_slice(MAGIC);
header[8..12].copy_from_slice(&VERSION.to_le_bytes());
header[12..16].copy_from_slice(&(HEADER_BYTES as u32).to_le_bytes());
header[16..24].copy_from_slice(&sequence.to_le_bytes());
header[24..32].copy_from_slice(&(payload.len() as u64).to_le_bytes());
header[32..64].copy_from_slice(&Sha256::digest(payload));
let digest = header_hash(&header);
header[HEADER_DIGEST..HEADER_RECORD].copy_from_slice(&digest);
header
}
fn header_hash(header: &[u8]) -> [u8; 32] {
let mut hash = Sha256::new();
hash.update(&header[..HEADER_DIGEST]);
hash.update([0; 32]);
hash.update(&header[HEADER_RECORD..]);
hash.finalize().into()
}
fn decode_slot(slot: usize, bytes: &[u8]) -> Option<Record> {
let header = &bytes[..HEADER_BYTES];
if &header[..8] != MAGIC
|| header[8..12] != VERSION.to_le_bytes()
|| header[12..16] != (HEADER_BYTES as u32).to_le_bytes()
|| header[HEADER_RECORD..].iter().any(|&byte| byte != 0)
|| header_hash(header) != header[HEADER_DIGEST..HEADER_RECORD]
{
return None;
}
let sequence = u64::from_le_bytes(header[16..24].try_into().ok()?);
let length = u64::from_le_bytes(header[24..32].try_into().ok()?);
if sequence == 0 || length == 0 || length > MAX_PAYLOAD as u64 {
return None;
}
let payload = &bytes[HEADER_BYTES..HEADER_BYTES + length as usize];
if Sha256::digest(payload)[..] != header[32..64] {
return None;
}
Some(Record {
slot,
sequence,
payload: payload.to_vec(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use stela_drivers::block::{Identity, RamDisk};
fn disk(block: u32) -> RamDisk {
RamDisk::new("FDR", FILE_BYTES as u64 / u64::from(block), block)
}
#[test]
fn alternates_and_reopens_with_both_sector_sizes_and_payload_bounds() {
let initial = initial_image(b"seed").unwrap();
assert_eq!(read_image(&initial).unwrap(), Some(b"seed".to_vec()));
assert!(initial_image(&[]).is_err());
assert!(initial_image(&vec![0; MAX_PAYLOAD + 1]).is_err());
for block in [512, 4096] {
let mut device = disk(block);
let mut journal = Journal::open(&mut device).unwrap();
assert_eq!(journal.snapshot(), None);
assert_eq!(read_image(&device.bytes).unwrap(), None);
for payload in [vec![1], vec![2; MAX_PAYLOAD], vec![3; 513]] {
journal.commit(&mut device, &payload).unwrap();
assert_eq!(journal.snapshot(), Some(payload.as_slice()));
assert_eq!(
Journal::open(&mut device).unwrap().snapshot(),
Some(payload.as_slice())
);
assert_eq!(read_image(&device.bytes).unwrap(), Some(payload));
}
assert_eq!(device.flushes, 6);
}
}
#[test]
fn corruption_recovers_a_valid_older_slot_but_never_becomes_empty() {
let mut device = disk(512);
let mut journal = Journal::open(&mut device).unwrap();
journal.commit(&mut device, b"older").unwrap();
journal.commit(&mut device, b"newer").unwrap();
let valid = device.bytes.clone();
// Every header field, reserved area, checksum and payload is covered.
for byte in [0, 8, 12, 16, 24, 32, 64, 96, HEADER_BYTES - 1, HEADER_BYTES] {
let mut damaged = valid.clone();
damaged[SLOT_BYTES + byte] ^= 1;
assert_eq!(read_image(&damaged).unwrap(), Some(b"older".to_vec()));
damaged[byte] ^= 1;
assert_eq!(read_image(&damaged), Err(Error::Corrupt));
}
let mut nonblank = vec![0; FILE_BYTES];
nonblank[FILE_BYTES - 1] = 1;
assert_eq!(read_image(&nonblank), Err(Error::Corrupt));
// A valid checksum cannot legalize an empty/oversized/zero-sequence record.
for (sequence, length) in [(0_u64, 5), (1, 0), (1, MAX_PAYLOAD as u64 + 1)] {
let mut damaged = valid.clone();
damaged[SLOT_BYTES..].fill(0);
damaged[16..24].copy_from_slice(&sequence.to_le_bytes());
damaged[24..32].copy_from_slice(&length.to_le_bytes());
let digest = header_hash(&damaged[..HEADER_BYTES]);
damaged[HEADER_DIGEST..HEADER_RECORD].copy_from_slice(&digest);
assert_eq!(read_image(&damaged), Err(Error::Corrupt));
}
let mut ambiguous = valid;
let first = ambiguous[..SLOT_BYTES].to_vec();
ambiguous[SLOT_BYTES..].copy_from_slice(&first);
assert_eq!(read_image(&ambiguous), Err(Error::Corrupt));
}
#[test]
fn refuses_geometry_readonly_oversize_and_stale_sessions_without_writes() {
let mut device = disk(512);
let mut journal = Journal::open(&mut device).unwrap();
for payload in [vec![], vec![0; MAX_PAYLOAD + 1]] {
assert_eq!(
journal.commit(&mut device, &payload),
Err(Error::PayloadSize {
bytes: payload.len()
})
);
}
device.identity.read_only = true;
assert!(Journal::open(&mut device).is_ok());
assert_eq!(
journal.commit(&mut device, b"x"),
Err(Error::Device(BlockError::ReadOnly))
);
device.identity.read_only = false;
let mut other = Journal::open(&mut device).unwrap();
other.commit(&mut device, b"other session").unwrap();
let before = device.bytes.clone();
assert_eq!(journal.commit(&mut device, b"stale"), Err(Error::Changed));
assert_eq!(device.bytes, before);
device.identity.blocks -= 1;
assert!(matches!(
Journal::open(&mut device),
Err(Error::DeviceSize { .. })
));
device.identity.blocks += 2;
assert!(matches!(
Journal::open(&mut device),
Err(Error::DeviceSize { .. })
));
for block in [0, 256, 1000, 8192] {
device.identity.block_size = block;
assert!(
matches!(Journal::open(&mut device), Err(Error::BlockSize(size)) if size == block)
);
}
assert_eq!(read_image(&[0; 512]), Err(Error::ImageSize { bytes: 512 }));
}
#[test]
fn sequence_overflow_refuses_without_touching_the_medium() {
let mut device = disk(512);
device.bytes[..HEADER_BYTES].copy_from_slice(&encode_header(u64::MAX, b"last"));
device.bytes[HEADER_BYTES..HEADER_BYTES + 4].copy_from_slice(b"last");
let before = device.bytes.clone();
let mut journal = Journal::open(&mut device).unwrap();
assert_eq!(
journal.commit(&mut device, b"next"),
Err(Error::SequenceExhausted)
);
assert_eq!(device.bytes, before);
assert_eq!(device.flushes, 0);
}
#[derive(Clone, Copy)]
enum Fault {
Before(usize),
After(usize),
/// A torn write has partly reached stable storage when power fails.
Torn {
phase: usize,
bytes: usize,
},
Readback,
BadReadback,
}
struct PowerDisk {
cache: RamDisk,
durable: Vec<u8>,
fault: Option<Fault>,
phase: usize,
reads: usize,
events: Vec<&'static str>,
}
impl PowerDisk {
fn seeded(block: u32) -> Self {
let mut cache = disk(block);
let mut journal = Journal::open(&mut cache).unwrap();
journal.commit(&mut cache, b"first").unwrap();
journal.commit(&mut cache, b"previous").unwrap();
Self {
durable: cache.bytes.clone(),
cache,
fault: None,
phase: 0,
reads: 0,
events: Vec::new(),
}
}
fn arm(&mut self, fault: Fault) {
self.fault = Some(fault);
self.phase = 0;
self.reads = 0;
self.events.clear();
}
fn lost_power(&mut self) {
self.cache.bytes.copy_from_slice(&self.durable);
self.fault = None;
}
fn failure() -> BlockError {
BlockError::Device { status: 0xfdfd }
}
}
impl BlockDevice for PowerDisk {
fn identity(&self) -> &Identity {
self.cache.identity()
}
fn read(&mut self, lba: u64, bytes: &mut [u8]) -> Result<(), BlockError> {
self.events.push("read");
self.reads += 1;
if self.reads == 2 && matches!(self.fault, Some(Fault::Readback)) {
return Err(Self::failure());
}
self.cache.read(lba, bytes)?;
if self.reads == 2 && matches!(self.fault, Some(Fault::BadReadback)) {
bytes[HEADER_BYTES] ^= 1;
}
Ok(())
}
fn write(&mut self, lba: u64, bytes: &[u8]) -> Result<(), BlockError> {
self.events.push("write");
let phase = self.phase;
self.phase += 1;
if matches!(self.fault, Some(Fault::Before(n)) if n == phase) {
return Err(Self::failure());
}
if let Some(Fault::Torn {
phase: n,
bytes: count,
}) = self.fault
{
if n == phase {
let offset = lba as usize * self.identity().block_size as usize;
let count = count.min(bytes.len());
self.durable[offset..offset + count].copy_from_slice(&bytes[..count]);
return Err(Self::failure());
}
}
self.cache.write(lba, bytes)?;
if matches!(self.fault, Some(Fault::After(n)) if n == phase) {
return Err(Self::failure());
}
Ok(())
}
fn flush(&mut self) -> Result<(), BlockError> {
self.events.push("flush");
let phase = self.phase;
self.phase += 1;
if matches!(self.fault, Some(Fault::Before(n)) if n == phase) {
return Err(Self::failure());
}
self.durable.copy_from_slice(&self.cache.bytes);
if matches!(self.fault, Some(Fault::After(n)) if n == phase) {
return Err(Self::failure());
}
Ok(())
}
}
#[test]
fn loss_before_and_after_every_write_and_flush_keeps_a_complete_generation() {
for block in [512, 4096] {
for phase in 0..4 {
for fault in [Fault::Before(phase), Fault::After(phase)] {
let mut device = PowerDisk::seeded(block);
let mut journal = Journal::open(&mut device).unwrap();
device.arm(fault);
assert!(journal.commit(&mut device, b"new commit").is_err());
assert_eq!(journal.snapshot(), Some(b"previous".as_slice()));
assert_eq!(
journal.commit(&mut device, b"retry"),
Err(Error::NeedsReopen)
);
device.lost_power();
let expected: &[u8] = if matches!(fault, Fault::After(3)) {
b"new commit"
} else {
b"previous"
};
assert_eq!(
Journal::open(&mut device).unwrap().snapshot(),
Some(expected)
);
assert_eq!(
read_image(&device.durable).unwrap(),
Some(expected.to_vec())
);
}
}
}
}
#[test]
fn torn_payload_or_header_never_displaces_the_previous_valid_generation() {
for block in [512, 4096] {
for phase in [0, 2] {
for count in [0, 1, 24, 64, 80, 96, 512, 2048, 4095] {
let mut device = PowerDisk::seeded(block);
let mut journal = Journal::open(&mut device).unwrap();
device.arm(Fault::Torn {
phase,
bytes: count,
});
let payload = vec![b'n'; 8193];
assert!(journal.commit(&mut device, &payload).is_err());
device.lost_power();
let actual = read_image(&device.durable).unwrap().unwrap();
// A header whose entire nonzero/checksummed record reached
// storage can already be valid, despite the write error.
assert!(actual == b"previous" || actual == payload);
if phase == 0 || count < HEADER_RECORD {
assert_eq!(actual, b"previous");
}
}
}
}
}
#[test]
fn readback_failure_never_acknowledges_a_durable_commit_and_retry_reopens() {
for fault in [Fault::Readback, Fault::BadReadback] {
let mut device = PowerDisk::seeded(4096);
let mut journal = Journal::open(&mut device).unwrap();
device.arm(fault);
assert!(
journal
.commit(&mut device, b"durable but unacknowledged")
.is_err()
);
assert_eq!(
device.events,
["read", "write", "flush", "write", "flush", "read"]
);
assert_eq!(journal.snapshot(), Some(b"previous".as_slice()));
assert_eq!(
journal.commit(&mut device, b"retry"),
Err(Error::NeedsReopen)
);
device.lost_power();
assert_eq!(
Journal::open(&mut device).unwrap().snapshot(),
Some(b"durable but unacknowledged".as_slice())
);
}
}
#[test]
fn interruption_of_the_first_commit_does_not_relabel_nonblank_bytes_as_empty() {
let mut device = PowerDisk::seeded(512);
device.cache.bytes.fill(0);
device.durable.fill(0);
let mut journal = Journal::open(&mut device).unwrap();
device.arm(Fault::After(1));
assert!(journal.commit(&mut device, b"first interrupted").is_err());
device.lost_power();
assert_eq!(read_image(&device.durable), Err(Error::Corrupt));
assert!(matches!(Journal::open(&mut device), Err(Error::Corrupt)));
}
}
+21 -4
View File
@@ -21,6 +21,8 @@ use sha2::{Digest, Sha384};
const MAX_STAGED_ANSWERS: usize = 128;
const MAX_STAGED_BYTES: usize = 16 * 1024 * 1024;
const MAX_REPLY_BYTES: usize = 8 * 1024 * 1024;
/// The writer returns success only after durable storage and readback.
pub type FdrCommit = Box<dyn FnMut(&[u8]) -> Result<()>>;
/// A transfer is a bounded recipe. A scheduler opens DataPort and polls a Job;
/// control-only responses use the control stream at its next frame boundary.
pub enum Plan {
@@ -219,6 +221,7 @@ const DATA_TYPES: [(&str, bool); 69] = [
pub struct Answers<R> {
pub store: Store<R>,
pub fdr_diagnostic: Option<super::fdr::Diagnostic>,
pub fdr_commit: Option<FdrCommit>,
pub staged: Staged,
/// Apple's signing service, only when the user enables it (`tss`).
pub signer: Option<tss::Signer>,
@@ -233,6 +236,7 @@ impl<R: ReadAt> Answers<R> {
Self {
store,
fdr_diagnostic: None,
fdr_commit: None,
staged: Staged::default(),
signer: None,
roots: BTreeMap::new(),
@@ -507,10 +511,23 @@ impl<R: ReadAt> Answers<R> {
.as_ref()
.map_or_else(|| Value::dict([]), super::fdr::Diagnostic::reply),
)),
"FDRMemoryCommit" => Err(super::refuse(
"FDR memory diagnostic has no durable commit implementation; refusing acknowledgement",
r,
)),
"FDRMemoryCommit" => {
let diagnostic = self.fdr_diagnostic.as_ref().ok_or(Error::Invalid(
"FDR commit without an imported machine binding",
))?;
let records = args.required("FDRMemoryStoreData")?.clone();
let bytes = diagnostic.with_records(records)?;
self.fdr_commit.as_mut().ok_or_else(|| {
super::refuse(
"FDR memory store has no durable commit writer; refusing acknowledgement",
r,
)
})?(&bytes)?;
self.fdr_diagnostic = Some(super::fdr::Diagnostic::decode(&bytes)?);
// R7252c checks that a response exists before checking the
// original recover result. An empty dictionary is the ACK.
Ok(Plan::Reply(Value::dict([])))
}
"RecoveryOSLocalPolicy" => self.recovery_local_policy(&identity, args),
// restored's `set_device_time` (R 0x10003172c..0x100031778) reads
// `SetHostTimeOnDevice` as a 64-bit CFNumber and keeps it only
+35 -4
View File
@@ -1,13 +1,14 @@
//! Explicit diagnostic import through restored's original FDR memory store.
//! Imported signatures are opaque: only Apple's consumer decides their trust.
//! This experiment cannot acknowledge FDRMemoryCommit or complete an install.
//! A commit is acknowledged only after the host's durable writer succeeds.
use super::{
Error, Result,
plist::{self, Limits, Value},
};
use alloc::string::String;
use alloc::{string::String, vec::Vec};
pub const FILE: &str = "fdr-diagnostic.plist";
pub const STATE_FILE: &str = "fdr-state.bin";
pub const MAX_BYTES: usize = 1024 * 1024;
pub struct Diagnostic {
@@ -39,7 +40,7 @@ impl Diagnostic {
let Value::Dict(entries) = &records else {
return Err(Error::Invalid("FDR memory-store dictionary"));
};
if entries.is_empty() || entries.len() > 128 {
if entries.len() > 128 {
return Err(Error::Limit("FDR diagnostic records"));
}
for (key, value) in entries {
@@ -72,6 +73,36 @@ impl Diagnostic {
pub fn reply(&self) -> Value {
Value::dict([("FDRMemoryStoreData", self.records.clone())])
}
/// Replace opaque records without changing the machine/build binding.
pub fn with_records(&self, records: Value) -> Result<Vec<u8>> {
let value = Value::dict([
("DiagnosticVersion", Value::Integer(1)),
("ECID", Value::Integer(self.ecid)),
("ChipID", Value::Integer(self.chip)),
("BoardID", Value::Integer(self.board)),
("Build", Value::String(self.build.clone())),
("Model", Value::String(self.model.clone())),
("FDRMemoryStoreData", records),
]);
let bytes = plist::encode_binary(
&value,
Limits {
bytes: MAX_BYTES,
..Limits::default()
},
)?;
Self::decode(&bytes)?;
Ok(bytes)
}
pub fn same_identity(&self, other: &Self) -> bool {
self.ecid == other.ecid
&& self.chip == other.chip
&& self.board == other.board
&& self.build == other.build
&& self.model == other.model
}
}
#[cfg(test)]
@@ -131,7 +162,7 @@ mod tests {
#[test]
fn malformed_store_is_refused() {
for records in [
Value::dict([]),
Value::dict([("", Value::Data(vec![1]))]),
Value::dict([("appv-own", Value::from("not-data"))]),
] {
let mut value = input();
+78 -14
View File
@@ -1074,6 +1074,7 @@ mod tests {
#[test]
fn fdr_commit_never_acknowledges_unpersisted_records() {
let (mut session, mut answers) = ready();
answers.fdr_diagnostic = Some(fdr_fixture(&answers.store, Value::dict([])));
let mut commit = request("FDRMemoryCommit");
let Value::Dict(entries) = &mut commit else {
unreachable!()
@@ -1098,20 +1099,7 @@ mod tests {
fn fdr_import_is_opt_in_and_preserves_the_original_reply_schema() {
let store = fixture(b"payload", false);
let records = Value::dict([("appv-own", Value::Data(vec![1, 2, 3]))]);
let input = Value::dict([
("DiagnosticVersion", Value::Integer(1)),
("ECID", Value::Signed(-111_111_111_111_111_111)),
("ChipID", Value::Integer(0x8112)),
("BoardID", Value::Integer(0x24)),
(
"Build",
Value::from(store.manifest().product_build.as_str()),
),
("Model", Value::from(store.manifest().model.as_str())),
("FDRMemoryStoreData", records.clone()),
]);
let bytes = super::super::plist::encode_binary(&input, Limits::default()).unwrap();
let diagnostic = super::super::fdr::Diagnostic::decode(&bytes).unwrap();
let diagnostic = fdr_fixture(&store, records.clone());
let (_, mut answers, start) = ready_with_fdr(store, Some(diagnostic));
assert_eq!(
start
@@ -1146,4 +1134,80 @@ mod tests {
};
assert_eq!(reply, Value::dict([]));
}
fn fdr_fixture(store: &Fixture, records: Value) -> super::super::fdr::Diagnostic {
let input = Value::dict([
("DiagnosticVersion", Value::Integer(1)),
("ECID", Value::Signed(-111_111_111_111_111_111)),
("ChipID", Value::Integer(0x8112)),
("BoardID", Value::Integer(0x24)),
(
"Build",
Value::from(store.manifest().product_build.as_str()),
),
("Model", Value::from(store.manifest().model.as_str())),
("FDRMemoryStoreData", records.clone()),
]);
let bytes = super::super::plist::encode_binary(&input, Limits::default()).unwrap();
super::super::fdr::Diagnostic::decode(&bytes).unwrap()
}
#[test]
fn fdr_commit_is_durable_before_acknowledgement_and_retains_binding() {
use crate::pc::fdr_store::{self, Journal};
use alloc::rc::Rc;
use core::cell::RefCell;
use stela_drivers::block::RamDisk;
let store = fixture(b"payload", false);
let diagnostic = fdr_fixture(&store, Value::dict([]));
let seed = diagnostic.with_records(Value::dict([])).unwrap();
let mut disk = RamDisk::new("FDR", (fdr_store::FILE_BYTES / 512) as u64, 512);
disk.bytes = fdr_store::initial_image(&seed).unwrap();
let mut journal = Journal::open(&mut disk).unwrap();
let disk = Rc::new(RefCell::new(disk));
let (mut session, mut answers, _) = ready_with_fdr(store, Some(diagnostic));
let writer = Rc::clone(&disk);
answers.fdr_commit = Some(Box::new(move |bytes| {
journal
.commit(&mut *writer.borrow_mut(), bytes)
.map_err(|error| Error::Transport(format!("{error}")))
}));
let records = Value::dict([("class-own", Value::Data(vec![9, 8, 7]))]);
let commit = Value::dict([
("MsgType", Value::from("DataRequestMsg")),
("DataType", Value::from("FDRMemoryCommit")),
(
"Arguments",
Value::dict([("FDRMemoryStoreData", records.clone())]),
),
]);
assert!(matches!(
session.receive(commit, &mut answers).unwrap(),
Action::Transfer(_)
));
let reopened = Journal::open(&mut *disk.borrow_mut()).unwrap();
let stored = super::super::fdr::Diagnostic::decode(reopened.snapshot().unwrap()).unwrap();
assert!(stored.same_identity(answers.fdr_diagnostic.as_ref().unwrap()));
assert_eq!(
stored.reply(),
Value::dict([("FDRMemoryStoreData", records)])
);
assert_eq!(disk.borrow().flushes, 2);
answers.fdr_commit = Some(Box::new(|_| {
Err(Error::Transport("injected persistence failure".into()))
}));
let request = Value::dict([
("DataType", Value::from("FDRMemoryCommit")),
(
"Arguments",
Value::dict([("FDRMemoryStoreData", Value::dict([]))]),
),
]);
assert!(answers.plan(&request).is_err());
assert!(stored.same_identity(answers.fdr_diagnostic.as_ref().unwrap()));
assert_eq!(
stored.reply(),
answers.fdr_diagnostic.as_ref().unwrap().reply()
);
}
}