aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#144 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/72d4d4405a128313.bundle -o 72d4d4405a128313.bundle git fetch 72d4d4405a128313.bundle refs/pull/144/head
Provenance
github-import 1
aien-dev/aienux
144
402dba0e479e0747a3d0df6411a0f754c2720f12
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":144,"url":"https://github.com/aien-dev/aienux/pull/144","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:49Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 9f25eda8..7e1d7a60 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -31,6 +31,11 @@ store-qual = ["nvme-write"] # resume / remember / crash modes over the Store-over-NVMe path. # scripts/qemu_continuity_test.sh enables it; hardware staging never does. continuity-qual = ["store-qual"] +# Recovery Core qualification (ADR 0006, test-only, QEMU only): inspect / +# operator-authorised repair / operator-authorised provisioning, with a +# TEST-ONLY operator key. scripts/qemu_recovery_test.sh enables it; hardware +# staging never does. +recovery-qual = ["continuity-qual"] # SEED-0B qualification build (ADR 0014 ยง6): the kernel trusts the public, # TEST ONLY RFC 8032 qualification key in addition to the (empty) production # set, and every report says so. Without it, every artifact candidate is diff --git a/crates/aienos-boot/src/nvme_read.rs b/crates/aienos-boot/src/nvme_read.rs index cf58d1cc..14e90be7 100644 --- a/crates/aienos-boot/src/nvme_read.rs +++ b/crates/aienos-boot/src/nvme_read.rs @@ -895,6 +895,18 @@ fn run_store_phase(screen: &mut Option<Screen>, mut controller: QualController, return; } + #[cfg(feature = "recovery-qual")] + if crate::store_qual::is_recovery_mode(mode) { + if is_512_qual { + qualify_fail(screen, "recovery qualification runs at 4096-byte LBA"); + return; + } + let mut response = [0u8; 32]; + response.copy_from_slice(&cfg[16..48]); + recovery_phase(screen, adapter, mode, &response); + return; + } + if mode == MODE_VERIFY || mode == MODE_VERIFY_512B { verify_reopen(screen, adapter, settle, is_512_qual); return; @@ -1249,3 +1261,132 @@ fn continuity_phase(screen: &mut Option<Screen>, mut adapter: QualAdapter, mode: } } } + +/// Recovery Core qualification (ADR 0006) with the TEST ONLY operator key. +/// Mode 9 inspects and prints the challenge for the applicable action; +/// modes 10/11 verify the operator response in control-block bytes 16..48 +/// and perform the action only if it verifies for exactly this state. +#[cfg(feature = "recovery-qual")] +fn recovery_phase( + screen: &mut Option<Screen>, + mut adapter: QualAdapter, + mode: u8, + response: &[u8; 32], +) { + use crate::store_qual::{ + MODE_RECOVERY_PROVISION, MODE_RECOVERY_REPAIR, TEST_ONLY_OPERATOR_KEY, + }; + use aienos_kernel::recovery_core::{self, Action, SlotView}; + + fn hex_into(l: &mut aienos_kernel::report::ReportBuf<256>, bytes: &[u8]) { + for b in bytes { + let _ = write!(l, "{b:02x}"); + } + } + + say(screen, "RECOVERY_OPERATOR_KEY: TEST-ONLY\n"); + let record = recovery_core::inspect(&mut adapter); + + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + let _ = write!(l, "RECOVERY_RECORD:"); + for (i, slot) in record.slots.iter().enumerate() { + match slot { + SlotView::Zero => { + let _ = write!(l, " slot{i}=zero"); + } + SlotView::Superblock { generation } => { + let _ = write!(l, " slot{i}=gen{generation}"); + } + SlotView::Undecodable(e) => { + let _ = write!(l, " slot{i}=undecodable({e:?})"); + } + SlotView::ReadError => { + let _ = write!(l, " slot{i}=read-error"); + } + } + } + if let Some((m, p, g)) = record.mount { + let _ = write!(l, " mount={m:?} peer={p:?} generation={g}"); + } + if let Some((roots, manifests, other)) = record.catalog { + let _ = write!(l, " roots={roots} manifests={manifests} other={other}"); + } + let _ = write!(l, " agent="); + match &record.continuity { + Some(c) => hex_into(&mut l, &c.root.agent_id), + None => { + let _ = write!(l, "none"); + } + } + let _ = writeln!(l); + say(screen, l.as_str()); + + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + match record.reason { + Some(reason) => { + let _ = writeln!(l, "RECOVERY_CORE: ENTERED reason={reason:?}"); + } + None => { + let _ = writeln!(l, "RECOVERY_CORE: NOT_NEEDED"); + } + } + say(screen, l.as_str()); + + if let Some(action) = record.applicable() { + if let Some(challenge) = record.challenge(action) { + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + let _ = write!(l, "RECOVERY_CHALLENGE: action={} challenge=", action.name()); + hex_into(&mut l, &challenge); + let _ = writeln!(l); + say(screen, l.as_str()); + } + } + + let outcome = if mode == MODE_RECOVERY_REPAIR { + Some( + recovery_core::repair_degraded_peer(&mut adapter, &TEST_ONLY_OPERATOR_KEY, response) + .map(|_| (Action::RepairDegradedPeer, None)), + ) + } else if mode == MODE_RECOVERY_PROVISION { + let mut agent = [0u8; 32]; + for chunk in agent.as_chunks_mut::<8>().0 { + match aienos_kernel::arch::aarch64::rndr() { + Some(v) => chunk.copy_from_slice(&v.to_le_bytes()), + None => { + say(screen, "RECOVERY_REFUSED (NoEntropy)\n"); + return; + } + } + } + Some( + recovery_core::provision_identity( + &mut adapter, + &TEST_ONLY_OPERATOR_KEY, + response, + agent, + ) + .map(|c| (Action::ProvisionIdentity, Some(c.root.agent_id))), + ) + } else { + None + }; + + let Some(outcome) = outcome else { + return; + }; + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + match outcome { + Ok((action, agent)) => { + let _ = write!(l, "RECOVERY_ACTION: {} DONE", action.name()); + if let Some(agent) = agent { + let _ = write!(l, " agent="); + hex_into(&mut l, &agent); + } + let _ = writeln!(l); + } + Err(e) => { + let _ = writeln!(l, "RECOVERY_REFUSED ({e:?})"); + } + } + say(screen, l.as_str()); +} diff --git a/crates/aienos-boot/src/store_qual.rs b/crates/aienos-boot/src/store_qual.rs index 1de034ef..b06618f6 100644 --- a/crates/aienos-boot/src/store_qual.rs +++ b/crates/aienos-boot/src/store_qual.rs @@ -38,6 +38,30 @@ pub const MODE_CONT_REMEMBER: u8 = 7; #[cfg(feature = "continuity-qual")] pub const MODE_CONT_CRASH: u8 = 8; +/// Recovery Core qualification modes (ADR 0006). The operator response, when +/// needed, is control-block bytes 16..48. +#[cfg(feature = "recovery-qual")] +pub const MODE_RECOVERY_INSPECT: u8 = 9; +#[cfg(feature = "recovery-qual")] +pub const MODE_RECOVERY_REPAIR: u8 = 10; +#[cfg(feature = "recovery-qual")] +pub const MODE_RECOVERY_PROVISION: u8 = 11; + +#[cfg(feature = "recovery-qual")] +pub const fn is_recovery_mode(mode: u8) -> bool { + matches!( + mode, + MODE_RECOVERY_INSPECT | MODE_RECOVERY_REPAIR | MODE_RECOVERY_PROVISION + ) +} + +/// TEST ONLY operator key for the QEMU Recovery Core qualification. It is +/// public in this source tree and proves nothing about a real operator; the +/// real credential scheme (ADR 0006 / M5) is not decided. Every boot that uses +/// it prints `RECOVERY_OPERATOR_KEY: TEST-ONLY`. +#[cfg(feature = "recovery-qual")] +pub const TEST_ONLY_OPERATOR_KEY: [u8; 32] = [0x0f; 32]; + #[cfg(feature = "continuity-qual")] pub const fn is_continuity_mode(mode: u8) -> bool { matches!( diff --git a/crates/aienos-kernel/src/continuity.rs b/crates/aienos-kernel/src/continuity.rs index e98cac97..edc0543a 100644 --- a/crates/aienos-kernel/src/continuity.rs +++ b/crates/aienos-kernel/src/continuity.rs @@ -637,6 +637,16 @@ fn read_kind<D: StoreDevice>(store: &mut Store<D>, id: ObjectId, kind: u16) -> R pub fn resolve<D: StoreDevice>(store: &mut Store<D>) -> Result<Continuity> { let roots = ids_of_kind(store, KIND_AGENT_ROOT); let root_id = match roots.as_slice() { + // Continuity objects without their root mean the identity was lost, + // not that the store was never provisioned: fail toward preservation. + [] if [KIND_MANIFEST, KIND_AGENT_STATE, KIND_CORTEX_WAL] + .iter() + .any(|kind| !ids_of_kind(store, *kind).is_empty()) => + { + return Err(ContinuityError::Corrupt( + "continuity objects without an agent root", + )) + } [] => return Err(ContinuityError::Unprovisioned), [one] => *one, _ => return Err(ContinuityError::Conflict), diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index f64769dc..28dc2eac 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -36,6 +36,7 @@ pub mod nvme; pub mod pci; pub mod pe; pub mod recovery; +pub mod recovery_core; pub mod report; pub mod scheduler; pub mod shell; diff --git a/crates/aienos-kernel/src/recovery.rs b/crates/aienos-kernel/src/recovery.rs index 7750d7cb..d8c85d43 100644 --- a/crates/aienos-kernel/src/recovery.rs +++ b/crates/aienos-kernel/src/recovery.rs @@ -5,7 +5,7 @@ //! - Transactional A/B boot slot rollback //! - Deterministic WAL truncation upon corruption without AI dependencies -use crate::crypto::sha256; +use crate::crypto::{constant_time_eq, sha256, HmacSha256}; /// Boot slot identifier for transactional updates. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -95,22 +95,48 @@ impl Default for SlotManager { /// resist offline brute-force and dictionary attacks. pub struct OperatorAuth; +/// Domain-separation prefix for the offline operator challenge-response MAC. +/// +/// It is prepended to the challenge inside the HMAC input so a tag produced for this +/// credential check can never be confused with any other HMAC use of the same key. The +/// trailing NUL terminates the label; the challenge that follows is always 32 bytes. +pub const OPERATOR_AUTH_DOMAIN: &[u8] = b"AIENOS-RECOVERY-OPERATOR-AUTH-v1\0"; + impl OperatorAuth { - /// Verify an operator authorization token against a high-entropy root key / derived credential. + /// Verify an operator's response to an offline challenge. + /// + /// Computes exactly: + /// + /// ```text + /// expected = HMAC-SHA256(key = derived_key, + /// message = OPERATOR_AUTH_DOMAIN || challenge) + /// ``` /// - /// The `derived_key_hash` must represent either a hardware-sealed key (e.g. FIDO/YubiKey) - /// or a high-entropy root key derived from a human passphrase via Argon2id. - /// Bare SHA-256 password verification is strictly prohibited. + /// where `OPERATOR_AUTH_DOMAIN` is `b"AIENOS-RECOVERY-OPERATOR-AUTH-v1\0"` (33 bytes), + /// and accepts only if `expected` equals `response`, compared with + /// [`constant_time_eq`] so the check does not exit early on the first differing byte. + /// + /// `derived_key` is treated as an opaque 32-byte high-entropy secret. Where it comes + /// from (Argon2id over a human passphrase, a FIDO/hardware-sealed key, or something + /// else) is out of scope for this function and not yet decided; ADR 0006 only forbids + /// deriving it with a fast hash of a human password. Challenge freshness (nonce + /// generation, single use, replay protection) is the caller's responsibility. pub fn verify_offline_credentials( - derived_key_hash: &[u8; 32], + derived_key: &[u8; 32], challenge: &[u8; 32], - signature: &[u8; 32], + response: &[u8; 32], ) -> bool { - let mut hasher = sha256::Sha256::new(); - hasher.update(derived_key_hash); - hasher.update(challenge); - let expected = hasher.finalize(); - &expected == signature + let expected = Self::expected_response(derived_key, challenge); + constant_time_eq(&expected, response) + } + + /// The response a holder of `derived_key` must present for `challenge` + /// (used by operator-side tooling to answer a challenge). + pub fn expected_response(derived_key: &[u8; 32], challenge: &[u8; 32]) -> [u8; 32] { + let mut mac = HmacSha256::new(derived_key); + mac.update(OPERATOR_AUTH_DOMAIN); + mac.update(challenge); + mac.finalize() } } @@ -180,6 +206,124 @@ impl WalRecovery { #[cfg(test)] mod tests { use super::*; + use crate::crypto::hmac_sha256; + + const KEY: [u8; 32] = { + let mut k = [0u8; 32]; + let mut i = 0; + while i < 32 { + k[i] = i as u8; // 00..1f + i += 1; + } + k + }; + const CHALLENGE: [u8; 32] = { + let mut c = [0u8; 32]; + let mut i = 0; + while i < 32 { + c[i] = 0xa0 + i as u8; // a0..bf + i += 1; + } + c + }; + /// HMAC-SHA256(key = 00..1f, "AIENOS-RECOVERY-OPERATOR-AUTH-v1\0" || a0..bf), computed + /// independently with `openssl dgst -sha256 -mac HMAC -macopt hexkey:<KEY>`. + const KAT_RESPONSE: [u8; 32] = [ + 0xf6, 0x16, 0x2d, 0xa5, 0xf8, 0x79, 0xe9, 0xbd, 0x4d, 0xef, 0xc7, 0x10, 0x8c, 0x46, 0x3b, + 0x5d, 0x16, 0x4f, 0x4d, 0xb6, 0x8a, 0xe9, 0x91, 0x78, 0x1b, 0xf7, 0x98, 0xfc, 0x14, 0x90, + 0x7a, 0xaa, + ]; + + #[test] + fn hmac_primitive_rfc4231_case_2() { + let tag = hmac_sha256(b"Jefe", b"what do ya want for nothing?"); + assert_eq!( + tag, + [ + 0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, + 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, + 0x64, 0xec, 0x38, 0x43, + ] + ); + } + + #[test] + fn operator_auth_known_answer_accepted() { + assert_eq!(OPERATOR_AUTH_DOMAIN.len(), 33); + assert_eq!( + OperatorAuth::expected_response(&KEY, &CHALLENGE), + KAT_RESPONSE + ); + let mut msg = [0u8; 65]; + msg[..33].copy_from_slice(OPERATOR_AUTH_DOMAIN); + msg[33..].copy_from_slice(&CHALLENGE); + assert_eq!(hmac_sha256(&KEY, &msg), KAT_RESPONSE); + assert!(OperatorAuth::verify_offline_credentials( + &KEY, + &CHALLENGE, + &KAT_RESPONSE + )); + } + + #[test] + fn operator_auth_rejects_any_single_bit_flip() { + for byte in 0..32 { + for bit in 0..8 { + let mask = 1u8 << bit; + + let mut response = KAT_RESPONSE; + response[byte] ^= mask; + assert!( + !OperatorAuth::verify_offline_credentials(&KEY, &CHALLENGE, &response), + "response flip byte {byte} bit {bit} accepted" + ); + + let mut challenge = CHALLENGE; + challenge[byte] ^= mask; + assert!( + !OperatorAuth::verify_offline_credentials(&KEY, &challenge, &KAT_RESPONSE), + "challenge flip byte {byte} bit {bit} accepted" + ); + + let mut key = KEY; + key[byte] ^= mask; + assert!( + !OperatorAuth::verify_offline_credentials(&key, &CHALLENGE, &KAT_RESPONSE), + "key flip byte {byte} bit {bit} accepted" + ); + } + } + } + + #[test] + fn operator_auth_rejects_legacy_bare_sha256_response() { + let mut hasher = sha256::Sha256::new(); + hasher.update(&KEY); + hasher.update(&CHALLENGE); + let legacy = hasher.finalize(); + assert_ne!(legacy, KAT_RESPONSE); + assert!(!OperatorAuth::verify_offline_credentials( + &KEY, &CHALLENGE, &legacy + )); + } + + #[test] + fn operator_auth_rejects_undomained_hmac_and_zero_response() { + // Plain HMAC over the challenge without the domain prefix must not verify. + let undomained = hmac_sha256(&KEY, &CHALLENGE); + assert!(!OperatorAuth::verify_offline_credentials( + &KEY, + &CHALLENGE, + &undomained + )); + assert!(!OperatorAuth::verify_offline_credentials( + &KEY, &CHALLENGE, &[0u8; 32] + )); + // All-zero key and challenge still require the real MAC, not zeros. + assert!(!OperatorAuth::verify_offline_credentials( + &[0u8; 32], &[0u8; 32], &[0u8; 32] + )); + } #[test] fn test_slot_rollback_on_failure() { diff --git a/crates/aienos-kernel/src/recovery_core.rs b/crates/aienos-kernel/src/recovery_core.rs new file mode 100644 index 00000000..ebc03eb4 --- /dev/null +++ b/crates/aienos-kernel/src/recovery_core.rs @@ -0,0 +1,277 @@ +//! Deterministic Recovery Core entry, inspection and operator-authorised +//! actions over System Store v1 and continuity (ADR 0006, ADR 0007, ADR 0016). +//! +//! No model, no network. Inspection never writes. Every write is an explicit +//! operator action whose challenge is bound to the exact on-disk state it +//! acts on, so an authorisation cannot be replayed onto a different state or +//! used for a different action. No action here can create an identity on a +//! store that already holds data it cannot account for. + +use crate::continuity::{self, Continuity, ContinuityError, ProvisionSource}; +use crate::crypto::sha256::Sha256; +use crate::recovery::OperatorAuth; +use crate::store::engine::{MountError, MountState, PeerCondition, Store, StoreDevice}; +use crate::store::v1::{FormatError, Superblock, STORE_UNIT_BYTES}; + +/// What one superblock slot holds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SlotView { + Zero, + Superblock { generation: u64 }, + Undecodable(FormatError), + ReadError, +} + +/// Why the Recovery Core was entered (or `None` when a normal boot may proceed). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum EntryReason { + StoreUnformatted, + StoreMount(MountError), + Unprovisioned, + Conflict, + ContinuityCorrupt(&'static str), + Degraded(PeerCondition), +} + +/// Operator actions the Recovery Core can perform. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Action { + /// Zero the inactive superblock slot of a `DegradedRecovery` store so it + /// mounts writable again on its valid root. + RepairDegradedPeer = 1, + /// Create the one identity on a formatted store with no agent root. + ProvisionIdentity = 2, +} + +impl Action { + pub const fn name(self) -> &'static str { + match self { + Action::RepairDegradedPeer => "repair-degraded-peer", + Action::ProvisionIdentity => "provision-identity", + } + } +} + +/// The read-only raw system record printed on entry. +#[derive(Clone, Debug)] +pub struct SystemRecord { + pub slots: [SlotView; 2], + /// SHA-256 over both raw superblock units: binds challenges to this state. + pub state_digest: [u8; 32], + pub store_uuid: Option<[u8; 16]>, + pub mount: Option<(MountState, PeerCondition, u64)>, + pub reason: Option<EntryReason>, + pub continuity: Option<Continuity>, + /// Catalog entry counts: agent roots, manifests, other. + pub catalog: Option<(usize, usize, usize)>, +} + +impl SystemRecord { + /// The action this state admits, if any. + /// Failure semantics fail toward preservation (ADR 0007): + /// - repair only a *malformed* peer, and only when the valid root still + /// resolves the identity, so the repair cannot lose it; + /// - never discard a CRC-valid newer root whose graph is broken: that + /// would roll back committed state, so it is an out-of-band decision; + /// - provision only on a healthy (`Valid`) mount with no continuity + /// objects at all. A degraded mount is never treated as unprovisioned, + /// because the identity may live in the root that did not validate. + pub fn applicable(&self) -> Option<Action> { + let (mount, _, _) = self.mount?; + match self.reason? { + EntryReason::Degraded(PeerCondition::Malformed) if self.continuity.is_some() => { + Some(Action::RepairDegradedPeer) + } + EntryReason::Unprovisioned if mount == MountState::Valid => { + Some(Action::ProvisionIdentity) + } + _ => None, + } + } + + /// Challenge for `action` on exactly this state: + /// SHA-256(domain || store uuid || generation || action || state digest). + pub fn challenge(&self, action: Action) -> Option<[u8; 32]> { + let uuid = self.store_uuid?; + let (_, _, generation) = self.mount?; + let mut h = Sha256::new(); + h.update(b"AIENOS-RECOVERY-CHALLENGE-v1\0"); + h.update(&uuid); + h.update(&generation.to_le_bytes()); + h.update(&[action as u8]); + h.update(&self.state_digest); + Some(h.finalize()) + } +} + +/// Inspects `device` in place. Never writes. +pub fn inspect<D: StoreDevice>(device: &mut D) -> SystemRecord { + let mut raw = [[0u8; STORE_UNIT_BYTES]; 2]; + let mut slots = [SlotView::ReadError; 2]; + let mut uuid = None; + for slot in 0..2 { + if device.read_unit(slot as u64, &mut raw[slot]).is_err() { + continue; + } + slots[slot] = if raw[slot].iter().all(|b| *b == 0) { + SlotView::Zero + } else { + match Superblock::decode(&raw[slot], slot as u32) { + Ok(sb) => { + uuid.get_or_insert(sb.store_uuid); + SlotView::Superblock { + generation: sb.generation, + } + } + Err(e) => SlotView::Undecodable(e), + } + }; + } + let mut h = Sha256::new(); + h.update(&raw[0]); + h.update(&raw[1]); + let state_digest = h.finalize(); + + let mut record = SystemRecord { + slots, + state_digest, + store_uuid: uuid, + mount: None, + reason: None, + continuity: None, + catalog: None, + }; + + let mut store = match Store::open(Borrowed(device)) { + Ok(store) => store, + Err(e) => { + record.reason = Some(match e { + MountError::Unformatted => EntryReason::StoreUnformatted, + other => EntryReason::StoreMount(other), + }); + return record; + } + }; + record.mount = Some(( + store.mount_state(), + store.peer_condition(), + store.generation(), + )); + let entries = &store.catalog().entries; + let roots = entries + .iter() + .filter(|e| e.kind == continuity::KIND_AGENT_ROOT) + .count(); + let manifests = entries + .iter() + .filter(|e| e.kind == continuity::KIND_MANIFEST) + .count(); + record.catalog = Some((roots, manifests, entries.len() - roots - manifests)); + + let resolved = continuity::resolve(&mut store); + record.reason = if store.mount_state() == MountState::DegradedRecovery { + // Degraded takes precedence: what the valid (older) root says about + // continuity is not the whole story. + Some(EntryReason::Degraded(store.peer_condition())) + } else { + match &resolved { + Ok(_) => None, + Err(ContinuityError::Unprovisioned) => Some(EntryReason::Unprovisioned), + Err(ContinuityError::Conflict) => Some(EntryReason::Conflict), + Err(ContinuityError::Corrupt(why)) => Some(EntryReason::ContinuityCorrupt(why)), + Err(_) => Some(EntryReason::ContinuityCorrupt("continuity unreadable")), + } + }; + record.continuity = resolved.ok(); + record +} + +/// Borrowing adapter: `Store::open` takes its device by value, and a failed +/// mount must not lose the caller's device. +struct Borrowed<'a, D: StoreDevice>(&'a mut D); + +impl<D: StoreDevice> StoreDevice for Borrowed<'_, D> { + type Error = D::Error; + fn region_units(&self) -> u64 { + self.0.region_units() + } + fn read_unit(&mut self, unit: u64, out: &mut [u8; STORE_UNIT_BYTES]) -> Result<(), D::Error> { + self.0.read_unit(unit, out) + } + fn write_unit(&mut self, unit: u64, bytes: &[u8; STORE_UNIT_BYTES]) -> Result<(), D::Error> { + self.0.write_unit(unit, bytes) + } + fn flush(&mut self) -> Result<(), D::Error> { + self.0.flush() + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RecoveryError { + /// The state does not admit this action. + NotApplicable, + /// The operator response did not verify for this state and action. + Unauthorised, + Io, + Continuity(ContinuityError), +} + +fn authorise( + record: &SystemRecord, + action: Action, + operator_key: &[u8; 32], + response: &[u8; 32], +) -> Result<(), RecoveryError> { + if record.applicable() != Some(action) { + return Err(RecoveryError::NotApplicable); + } + let challenge = record + .challenge(action) + .ok_or(RecoveryError::NotApplicable)?; + if !OperatorAuth::verify_offline_credentials(operator_key, &challenge, response) { + return Err(RecoveryError::Unauthorised); + } + Ok(()) +} + +/// Zeroes the inactive superblock slot of a degraded store after verifying +/// the operator's response. Nothing is written unless authorisation passes. +pub fn repair_degraded_peer<D: StoreDevice>( + device: &mut D, + operator_key: &[u8; 32], + response: &[u8; 32], +) -> Result<SystemRecord, RecoveryError> { + let record = inspect(device); + authorise(&record, Action::RepairDegradedPeer, operator_key, response)?; + // The valid root is the decodable slot the engine mounted; the other goes. + let active = { + let store = Store::open(Borrowed(device)).map_err(|_| RecoveryError::Io)?; + store.active_slot() as u64 + }; + let peer = 1 - active; + device + .write_unit(peer, &[0u8; STORE_UNIT_BYTES]) + .map_err(|_| RecoveryError::Io)?; + device.flush().map_err(|_| RecoveryError::Io)?; + Ok(inspect(device)) +} + +/// Provisions the one identity on an unprovisioned store after verifying the +/// operator's response. Refused on any other state. +pub fn provision_identity<D: StoreDevice>( + device: &mut D, + operator_key: &[u8; 32], + response: &[u8; 32], + agent_id: [u8; 32], +) -> Result<Continuity, RecoveryError> { + let record = inspect(device); + authorise(&record, Action::ProvisionIdentity, operator_key, response)?; + let uuid = record.store_uuid.ok_or(RecoveryError::NotApplicable)?; + let mut store = Store::open(Borrowed(device)).map_err(|_| RecoveryError::Io)?; + continuity::provision(&mut store, agent_id, uuid, ProvisionSource::Operator) + .map_err(RecoveryError::Continuity) +} + +#[cfg(test)] +#[path = "recovery_core_tests.rs"] +mod tests; diff --git a/crates/aienos-kernel/src/recovery_core_tests.rs b/crates/aienos-kernel/src/recovery_core_tests.rs new file mode 100644 index 00000000..2bc69cc1 --- /dev/null +++ b/crates/aienos-kernel/src/recovery_core_tests.rs @@ -0,0 +1,315 @@ +use super::*; +use crate::continuity::{self, CortexRecord, Epistemic, ProvisionSource, Update}; +use crate::store::genesis::genesis_units; +use alloc::vec; +use alloc::vec::Vec; + +const UUID: [u8; 16] = [0x5a; 16]; +const AGENT: [u8; 32] = [0x11; 32]; +const OPERATOR: [u8; 32] = [0x0f; 32]; + +#[derive(Clone, PartialEq, Eq)] +struct Mem { + units: Vec<[u8; STORE_UNIT_BYTES]>, +} + +impl StoreDevice for Mem { + type Error = (); + fn region_units(&self) -> u64 { + self.units.len() as u64 + } + fn read_unit( + &mut self, + unit: u64, + out: &mut [u8; STORE_UNIT_BYTES], + ) -> core::result::Result<(), ()> { + *out = *self.units.get(unit as usize).ok_or(())?; + Ok(()) + } + fn write_unit( + &mut self, + unit: u64, + bytes: &[u8; STORE_UNIT_BYTES], + ) -> core::result::Result<(), ()> { + *self.units.get_mut(unit as usize).ok_or(())? = *bytes; + Ok(()) + } + fn flush(&mut self) -> core::result::Result<(), ()> { + Ok(()) + } +} + +fn blank() -> Mem { + Mem { + units: vec![[0u8; STORE_UNIT_BYTES]; 256], + } +} + +fn formatted() -> Mem { + let mut dev = blank(); + for (i, u) in genesis_units(UUID, 256).iter().enumerate() { + dev.units[i] = *u; + } + dev +} + +/// Provisioned, with one remembered fact committed. +fn remembered() -> Mem { + let mut store = Store::open(formatted()).unwrap(); + let c = continuity::provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap(); + continuity::commit( + &mut store, + &c, + Update { + state: None, + cortex: vec![CortexRecord { + status: Epistemic::OperatorDecision, + evidence_hash: [0; 32], + statement: b"keep this".to_vec(), + }], + }, + false, + ) + .unwrap(); + store.into_device() +} + +fn degraded() -> Mem { + let mut dev = remembered(); + let active = Store::open(dev.clone()).unwrap().active_slot() as usize; + dev.units[1 - active] = [0xa5; STORE_UNIT_BYTES]; + dev +} + +fn respond(record: &SystemRecord, action: Action, key: &[u8; 32]) -> [u8; 32] { + OperatorAuth::expected_response(key, &record.challenge(action).unwrap()) +} + +#[test] +fn inspection_never_writes_and_names_the_reason() { + let cases: [(Mem, Option<EntryReason>); 4] = [ + (blank(), Some(EntryReason::StoreUnformatted)), + (formatted(), Some(EntryReason::Unprovisioned)), + (remembered(), None), + ( + degraded(), + Some(EntryReason::Degraded(PeerCondition::Malformed)), + ), + ]; + for (dev, want) in cases { + let mut probe = dev.clone(); + let record = inspect(&mut probe); + assert!(probe == dev, "inspection wrote to the device"); + assert_eq!(record.reason, want); + } + let r = inspect(&mut remembered()); + assert_eq!(r.continuity.unwrap().root.agent_id, AGENT); + assert_eq!(r.catalog.unwrap().0, 1, "one agent root"); +} + +#[test] +fn degraded_repair_needs_the_operator_and_restores_a_writable_store() { + let mut dev = degraded(); + let record = inspect(&mut dev); + assert_eq!(record.applicable(), Some(Action::RepairDegradedPeer)); + let good = respond(&record, Action::RepairDegradedPeer, &OPERATOR); + + // Wrong key, wrong action, zero response: refused, nothing written. + let before = dev.clone(); + let wrong_key = respond(&record, Action::RepairDegradedPeer, &[0x0e; 32]); + let wrong_action = respond(&record, Action::ProvisionIdentity, &OPERATOR); + for bad in [wrong_key, wrong_action, [0; 32]] { + assert_eq!( + repair_degraded_peer(&mut dev, &OPERATOR, &bad).map(|_| ()), + Err(RecoveryError::Unauthorised) + ); + assert!(dev == before, "a refused repair wrote to the device"); + } + // Provisioning is not the applicable action here. + assert_eq!( + provision_identity(&mut dev, &OPERATOR, &wrong_action, [0x22; 32]).map(|_| ()), + Err(RecoveryError::NotApplicable) + ); + + let after = repair_degraded_peer(&mut dev, &OPERATOR, &good).unwrap(); + assert_eq!(after.reason, None, "store is healthy after repair"); + let (mount, peer, _) = after.mount.unwrap(); + assert_eq!((mount, peer), (MountState::Valid, PeerCondition::Zero)); + + // Same identity and memory, and it is writable again. + let mut store = Store::open(dev.clone()).unwrap(); + let (c, committed) = continuity::resume(&mut store).unwrap(); + assert!(committed); + assert_eq!(c.root.agent_id, AGENT); + assert_eq!(c.cortex[0].statement, b"keep this".to_vec()); + + // Replaying the old authorisation on the new state does nothing. + let mut dev = store.into_device(); + let snapshot = dev.clone(); + assert!(repair_degraded_peer(&mut dev, &OPERATOR, &good).is_err()); + assert!(dev == snapshot); +} + +#[test] +fn provisioning_is_operator_only_and_only_on_an_unprovisioned_store() { + let mut dev = formatted(); + let record = inspect(&mut dev); + assert_eq!(record.applicable(), Some(Action::ProvisionIdentity)); + let before = dev.clone(); + assert_eq!( + provision_identity(&mut dev, &OPERATOR, &[7; 32], AGENT).map(|_| ()), + Err(RecoveryError::Unauthorised) + ); + assert!(dev == before); + + let good = respond(&record, Action::ProvisionIdentity, &OPERATOR); + let c = provision_identity(&mut dev, &OPERATOR, &good, AGENT).unwrap(); + assert_eq!(c.root.agent_id, AGENT); + assert_eq!(c.root.source, ProvisionSource::Operator); + + // The same authorisation cannot provision again. + assert_eq!( + provision_identity(&mut dev, &OPERATOR, &good, [0x33; 32]).map(|_| ()), + Err(RecoveryError::NotApplicable) + ); +} + +#[test] +fn identity_lost_in_the_newest_root_never_looks_unprovisioned() { + // Found by the QEMU campaign: provision (generation 2) then corrupt the + // agent root. The graph-broken generation-2 root makes the Store mount + // degraded on generation 1 (genesis, no identity). That must not read as + // "unprovisioned", even to an operator holding a valid key. + let mut store = Store::open(formatted()).unwrap(); + continuity::provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap(); + let mut dev = store.into_device(); + let root_unit = Store::open(dev.clone()) + .unwrap() + .catalog() + .entries + .iter() + .find(|e| e.kind == continuity::KIND_AGENT_ROOT) + .unwrap() + .first_unit; + dev.units[root_unit as usize][20] ^= 0xff; + + let record = inspect(&mut dev); + assert_eq!( + record.reason, + Some(EntryReason::Degraded(PeerCondition::GraphBadNewer)) + ); + assert_eq!(record.applicable(), None); + + // A response that is genuinely valid for this exact state still cannot + // provision or repair: the refusal is the preservation rule, not the key. + let before = dev.clone(); + for action in [Action::ProvisionIdentity, Action::RepairDegradedPeer] { + let valid = respond(&record, action, &OPERATOR); + let result = match action { + Action::ProvisionIdentity => { + provision_identity(&mut dev, &OPERATOR, &valid, [0x22; 32]).map(|_| ()) + } + Action::RepairDegradedPeer => { + repair_degraded_peer(&mut dev, &OPERATOR, &valid).map(|_| ()) + } + }; + assert_eq!(result, Err(RecoveryError::NotApplicable), "{action:?}"); + } + assert!(dev == before, "nothing was written"); +} + +#[test] +fn malformed_peer_without_a_resolvable_identity_is_not_repaired() { + // Garbage in slot B of a formatted store that never had an identity: the + // valid root resolves no identity, so repair is not offered either. + let mut dev = formatted(); + dev.units[1] = [0xa5; STORE_UNIT_BYTES]; + let record = inspect(&mut dev); + assert_eq!( + record.reason, + Some(EntryReason::Degraded(PeerCondition::Malformed)) + ); + assert_eq!(record.applicable(), None); +} + +#[test] +fn orphaned_continuity_objects_are_corrupt_not_unprovisioned() { + // A manifest without its agent root means the identity was lost. + let mut store = Store::open(formatted()).unwrap(); + let orphan = continuity::Manifest { + root: crate::store::v1::ObjectId([0x77; 32]), + previous: None, + sequence: 1, + incarnation: 1, + agent_state: None, + cortex_wal: Vec::new(), + } + .encode() + .unwrap(); + store + .transact(&[crate::store::engine::ObjectInput { + kind: continuity::KIND_MANIFEST, + version: continuity::STORE_OBJECT_VERSION, + bytes: &orphan, + }]) + .unwrap(); + let mut dev = store.into_device(); + let record = inspect(&mut dev); + assert!( + matches!(record.reason, Some(EntryReason::ContinuityCorrupt(_))), + "{:?}", + record.reason + ); + assert_eq!(record.applicable(), None); +} + +#[test] +fn identity_loss_through_corruption_offers_no_action_that_mints() { + // Corrupt the agent root object's bytes: the Store graph no longer + // validates, so the Recovery Core must stop, not provision. + let mut dev = remembered(); + let root_unit = { + let store = Store::open(dev.clone()).unwrap(); + store + .catalog() + .entries + .iter() + .find(|e| e.kind == continuity::KIND_AGENT_ROOT) + .unwrap() + .first_unit + }; + dev.units[root_unit as usize][20] ^= 0xff; + let record = inspect(&mut dev); + assert!( + matches!( + record.reason, + Some(EntryReason::StoreMount(_) | EntryReason::ContinuityCorrupt(_)) + ), + "{:?}", + record.reason + ); + assert_eq!(record.applicable(), None); + let before = dev.clone(); + let forged = [0x55; 32]; + assert!(provision_identity(&mut dev, &OPERATOR, &forged, [0x22; 32]).is_err()); + assert!(repair_degraded_peer(&mut dev, &OPERATOR, &forged).is_err()); + assert!(dev == before, "no action wrote after identity loss"); +} + +#[test] +fn challenges_bind_state_and_action() { + let r1 = inspect(&mut degraded()); + let mut other = degraded(); + let active = Store::open(other.clone()).unwrap().active_slot() as usize; + other.units[1 - active] = [0x5a; STORE_UNIT_BYTES]; + let r2 = inspect(&mut other); + assert_ne!( + r1.challenge(Action::RepairDegradedPeer), + r2.challenge(Action::RepairDegradedPeer), + "different on-disk state, different challenge" + ); + assert_ne!( + r1.challenge(Action::RepairDegradedPeer), + r1.challenge(Action::ProvisionIdentity) + ); +} diff --git a/crates/aienos-store-tool/src/main.rs b/crates/aienos-store-tool/src/main.rs index dd22a9f6..71764fa6 100644 --- a/crates/aienos-store-tool/src/main.rs +++ b/crates/aienos-store-tool/src/main.rs @@ -5,11 +5,15 @@ //! implementation of the format. //! //! Commands: -//! cfg IMAGE BYTE_OFFSET MODE SETTLE +//! cfg IMAGE BYTE_OFFSET MODE SETTLE [RESPONSE_HEX] //! Write the 4096-byte qualification control block. //! tear-closure OLD NEW STORE_BYTE_OFFSET SECTOR_BYTES //! Prove that every sector-granular tear of the one superblock write that //! separates OLD from NEW leaves either the old or the new slot bytes. +//! operator-respond KEY_HEX CHALLENGE_HEX +//! Recovery Core operator response (HMAC-SHA256, kernel OperatorAuth). +//! corrupt-kind IMAGE STORE_BYTE_OFFSET REGION_UNITS KIND +//! Flip one byte in the first object of KIND (identity-loss tests). //! inject IMAGE STORE_BYTE_OFFSET SLOT|inactive CASE [SOURCE] //! Overwrite superblock SLOT with one deterministic defect (see `CASES`). @@ -43,8 +47,10 @@ fn main() -> ExitCode { Some("cfg") => cfg(&args[1..]), Some("tear-closure") => tear_closure(&args[1..]), Some("inject") => inject(&args[1..]), + Some("operator-respond") => operator_respond(&args[1..]), + Some("corrupt-kind") => corrupt_kind(&args[1..]), _ => Err(format!( - "usage: aienos-store-tool cfg|tear-closure|inject ... (cases: {})", + "usage: aienos-store-tool cfg|tear-closure|inject|operator-respond|corrupt-kind ... (cases: {})", CASES.join(",") )), }; @@ -100,17 +106,117 @@ fn rechecksum(unit: &mut Unit) { } fn cfg(args: &[String]) -> Result<String, String> { - arity(args, 4, 4)?; + arity(args, 4, 5)?; let offset = num(&args[1], "byte offset")?; let mode = u8::try_from(num(&args[2], "mode")?).map_err(|_| "mode > 255")?; let settle = u8::try_from(num(&args[3], "settle")?).map_err(|_| "settle > 255")?; let mut block = [0u8; STORE_UNIT_BYTES]; block[0] = mode; block[1] = settle; + // Optional 32-byte operator response for Recovery Core actions. + if let Some(hex) = args.get(4) { + block[16..48].copy_from_slice(&hex32(hex)?); + } write_at(&args[0], offset, &block)?; Ok(format!("cfg mode={mode} settle={settle}")) } +fn hex32(s: &str) -> Result<[u8; 32], String> { + if s.len() != 64 { + return Err(format!("expected 64 hex digits, got {}", s.len())); + } + let mut out = [0u8; 32]; + for (i, b) in out.iter_mut().enumerate() { + *b = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).map_err(|_| format!("bad hex: {s}"))?; + } + Ok(out) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Operator side of the Recovery Core challenge: HMAC response for KEY. +fn operator_respond(args: &[String]) -> Result<String, String> { + arity(args, 2, 2)?; + let key = hex32(&args[0])?; + let challenge = hex32(&args[1])?; + Ok(hex( + &aienos_kernel::recovery::OperatorAuth::expected_response(&key, &challenge), + )) +} + +/// A Store region inside an image file, as a StoreDevice. +struct FileDevice { + file: fs::File, + base: u64, + units: u64, +} + +impl aienos_kernel::store::engine::StoreDevice for FileDevice { + type Error = std::io::Error; + fn region_units(&self) -> u64 { + self.units + } + fn read_unit(&mut self, unit: u64, out: &mut Unit) -> std::io::Result<()> { + self.file + .seek(SeekFrom::Start(self.base + unit * STORE_UNIT_BYTES as u64))?; + self.file.read_exact(out) + } + fn write_unit(&mut self, unit: u64, bytes: &Unit) -> std::io::Result<()> { + self.file + .seek(SeekFrom::Start(self.base + unit * STORE_UNIT_BYTES as u64))?; + self.file.write_all(bytes) + } + fn flush(&mut self) -> std::io::Result<()> { + self.file.sync_all() + } +} + +/// Flips one byte in the first unit of the first catalog object of KIND. +fn corrupt_kind(args: &[String]) -> Result<String, String> { + arity(args, 4, 4)?; + let offset = num(&args[1], "store offset")?; + let units = num(&args[2], "region units")?; + let kind = u16::try_from(num(&args[3], "kind")?).map_err(|e| e.to_string())?; + let file = OpenOptions::new() + .read(true) + .write(true) + .open(&args[0]) + .map_err(|e| format!("{}: {e}", args[0]))?; + let dev = FileDevice { + file, + base: offset, + units, + }; + let store = aienos_kernel::store::engine::Store::open(dev) + .map_err(|e| format!("store does not mount: {e:?}"))?; + let entry = store + .catalog() + .entries + .iter() + .find(|e| e.kind == kind) + .copied() + .ok_or(format!("no catalog object of kind {kind}"))?; + let at = offset + entry.first_unit * STORE_UNIT_BYTES as u64 + 20; + let mut dev = store.into_device(); + dev.file + .seek(SeekFrom::Start(at)) + .map_err(|e| e.to_string())?; + let mut byte = [0u8; 1]; + dev.file.read_exact(&mut byte).map_err(|e| e.to_string())?; + byte[0] ^= 0xff; + dev.file + .seek(SeekFrom::Start(at)) + .map_err(|e| e.to_string())?; + dev.file.write_all(&byte).map_err(|e| e.to_string())?; + dev.file.sync_all().map_err(|e| e.to_string())?; + Ok(format!( + "corrupt kind={kind} unit={} byte=20", + entry.first_unit + )) +} + /// Describes a superblock slot's bytes for reports. fn describe(unit: &Unit, slot: u32) -> String { if unit.iter().all(|b| *b == 0) { diff --git a/evidence/recovery_core_qemu_2026-09-25.md b/evidence/recovery_core_qemu_2026-09-25.md new file mode 100644 index 00000000..f6bb5434 --- /dev/null +++ b/evidence/recovery_core_qemu_2026-09-25.md @@ -0,0 +1,78 @@ +# Recovery Core over Store v1 and continuity: QEMU qualification (2026-09-25) + +Code commit `e5b44d8ff5692f74fe191ab07f48fd21511ff82f` (clean tree), branch +`feat/recovery-core` (main `39e246a` + the operator-auth HMAC fix). +Design: ADR 0006 (Recovery Core), ADR 0007 (provisioning once), ADR 0016 +(continuity, Proposed). QEMU only, 4096-byte LBA, native NVMe driver. + +Reproduce: `./scripts/qemu_recovery_test.sh` + +**Operator credential: TEST-ONLY.** The operator key is a public constant in +this tree and every boot prints `RECOVERY_OPERATOR_KEY: TEST-ONLY`. How the +real operator key is derived (Argon2id passphrase, FIDO/hardware key, ...) is +not decided (ADR 0006 / M5, operator decision). The verification primitive is +real: `HMAC-SHA256(key, "AIENOS-RECOVERY-OPERATOR-AUTH-v1\0" || challenge)` +compared in constant time. + +## What is proven + +| Claim | Step | +|---|---| +| Entry and inspection are deterministic and read-only: the raw system record (both superblock slots, mount state, peer condition, catalog counts, agent) is printed and the image is byte-identical after the boot | 1, 2, 3 | +| A challenge binds Store UUID, generation, action and a digest of both raw superblock units; zero, wrong-key and wrong-challenge responses are refused with no write | 1, 2 | +| An authorised repair of a malformed peer restores a writable store; a cold boot resumes the same agent with the same memory; replaying the authorisation on the repaired store does nothing | 1 | +| Operator provisioning on a healthy, unprovisioned store creates exactly one identity, which a cold boot resumes | 2 | +| After identity loss (corrupted agent root) no action is offered, both actions are refused, and a normal boot neither resumes nor mints | 3 | + +## Finding fixed during qualification + +The first run (commit `fe2c2bd`) failed step 3: corrupting the agent root of a +store provisioned at generation 2 made the Store mount `DegradedRecovery` on +generation 1 (genesis, no identity), continuity reported `Unprovisioned`, and +the Recovery Core offered `provision-identity`. A valid operator response +would have minted a replacement identity after identity loss. Fixed in +`e5b44d8` (fail toward preservation): a degraded mount is never +unprovisioned; repair only a malformed peer while the valid root still +resolves the identity; never discard a CRC-valid newer root in-band; +continuity objects without an agent root are `Corrupt`. The host regression +test uses a response that is genuinely valid for the state and fails on the +previous code. + +## Result + +```text +=== 1. Degraded store: operator-authorised repair === +PASS inspection enters the Recovery Core (Degraded(Malformed)), shows the same agent, writes nothing +PASS repair with zero response refused, nothing written +PASS repair with wrong_key response refused, nothing written +PASS repair with wrong_action response refused, nothing written +PASS authorised repair done +PASS after repair a cold boot resumes writable with the same agent and memory +PASS replaying the repair authorisation on the healthy store does nothing +=== 2. Unprovisioned store: operator-authorised provisioning === +PASS unprovisioned store enters the Recovery Core and offers only provisioning +PASS provisioning with a wrong key refused, nothing written +PASS operator provisioning created one identity and a cold boot resumes it +=== 3. Identity loss: nothing may mint === +PASS corrupted agent root: Recovery Core entered, no action offered, nothing written (Degraded(GraphBadNewer)) +PASS mode 10 after identity loss refused, nothing written +PASS mode 11 after identity loss refused, nothing written +PASS a normal boot after identity loss does not resume or mint (2c0752ceed5e81cd... is not replaced) + +=== Summary (commit e5b44d8ff5692f74fe191ab07f48fd21511ff82f) === +RECOVERY_CORE_QEMU: PASS +RECOVERY_CORE_OPERATOR_CREDENTIAL: TEST-ONLY (real scheme undecided, ADR 0006 / M5) +``` + +Host tests: `cargo test -p aienos-kernel --lib recovery_core` (8) and +`recovery` (operator-auth HMAC, RFC 4231 primitive vector, known answer, +bit-flip and legacy-construction rejection). + +## Not claimed + +- A real operator credential, Machine 1 behaviour, TRUST-1, M5 encryption. +- Rolling back to an older root when the newer one is graph-broken: refused + in-band on purpose; it discards committed state and is an out-of-band + operator decision. +- A/B boot-slot rollback and crash records on hardware (ADR 0006 items + outside the Store). diff --git a/scripts/qemu_recovery_test.sh b/scripts/qemu_recovery_test.sh new file mode 100755 index 00000000..1b3b1c56 --- /dev/null +++ b/scripts/qemu_recovery_test.sh @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +# Recovery Core qualification in QEMU (ADR 0006): deterministic entry and +# read-only inspection, operator-authorised repair and provisioning bound to +# the exact on-disk state, and no action that mints an identity after +# identity loss. No model, no network. +# +# The operator key is TEST ONLY (public in this tree); the real credential +# scheme is not decided (ADR 0006 / M5). 4096-byte LBA, native NVMe driver. +# Emits RECOVERY_CORE_QEMU: PASS only when every step passes. +set -uo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" +img_bytes=67108864 +lba_bytes=4096 +cfg_offset=$(( 32 * lba_bytes )) +store_offset=$(( 64 * lba_bytes )) +region_units=256 +machine="virt,virtualization=on,gic-version=3,iommu=smmuv3" +target_dir="target/qemu-recovery" +# TEST ONLY operator key (crates/aienos-boot/src/store_qual.rs). +test_key=$(printf '0f%.0s' $(seq 32)) +wrong_key=$(printf '0e%.0s' $(seq 32)) +zero=$(printf '00%.0s' $(seq 32)) + +echo "=== Building aienos-handoff (recovery-qual) and aienos-store-tool ===" +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +git diff --quiet HEAD 2>/dev/null || commit="${commit}-dirty" +AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features recovery-qual --bin aienos-handoff \ + --target-dir "${target_dir}" || { echo "build failed"; exit 2; } +cargo build --quiet --release -p aienos-store-tool || { echo "store tool build failed"; exit 2; } +tool="target/release/aienos-store-tool" + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { [[ -n "${qemu_pid}" ]] && kill -9 "${qemu_pid}" 2>/dev/null || true; rm -rf "${work}"; } +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${target_dir}/aarch64-unknown-uefi/release/aienos-handoff.efi" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +image="${work}/nvme.img" +serial="${work}/serial.log" +fail=0 + +fresh_image() { rm -f "${image}"; truncate -s "${img_bytes}" "${image}"; } +digest() { sha256sum "${image}" | cut -d' ' -f1; } +pass() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fail=1; } + +run_qemu() { + cp -f "${vars_fd}" "${work}/vars.fd" + rm -f "${serial}" + timeout "${boot_timeout}" qemu-system-aarch64 \ + -M "${machine}" -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=nvme0,format=raw,file="${image}" \ + -device nvme,drive=nvme0,serial=aienos-recovery,logical_block_size=${lba_bytes},physical_block_size=${lba_bytes} \ + -display none -nic none -serial file:"${serial}" -no-reboot || true +} + +# boot MODE [RESPONSE_HEX]: write the control block, then one cold boot. +# before/after digests bracket only the guest's writes. +boot() { + "${tool}" cfg "${image}" "${cfg_offset}" "$1" 0 ${2:+"$2"} >/dev/null || { echo "cfg write failed"; exit 2; } + before=$(digest) + run_qemu + after=$(digest) +} +out() { tr -d '\r' <"${serial}" | grep -E "$1" | tail -1; } +challenge_for() { out "^RECOVERY_CHALLENGE: action=$1 " | sed -nE 's/.*challenge=([0-9a-f]{64}).*/\1/p'; } +respond() { "${tool}" operator-respond "$1" "$2"; } +agent_of() { sed -nE 's/.*agent=([0-9a-f]{64}).*/\1/p' <<<"$1"; } +unchanged() { [[ "${before}" == "${after}" ]]; } + +echo "=== 1. Degraded store: operator-authorised repair ===" +fresh_image +boot 5; agent=$(agent_of "$(out '^CONTINUITY: PROVISIONED')") +boot 7; memory=$(out '^CONTINUITY: REMEMBERED' | sed -nE 's/.*memory=([0-9a-f]+).*/\1/p') +[[ ${#agent} == 64 && -n "${memory}" ]] || bad "could not build a provisioned store with memory" +"${tool}" inject "${image}" "${store_offset}" inactive seeded_garbage >/dev/null || bad "inject failed" + +boot 9 +if [[ -n "$(out '^RECOVERY_OPERATOR_KEY: TEST-ONLY$')" && \ + -n "$(out '^RECOVERY_CORE: ENTERED reason=Degraded\(Malformed\)$')" && \ + "$(agent_of "$(out '^RECOVERY_RECORD:')")" == "${agent}" ]] && unchanged; then + pass "inspection enters the Recovery Core (Degraded(Malformed)), shows the same agent, writes nothing" +else + bad "inspection: $(tr -d '\r' <"${serial}" | grep -E '^RECOVERY_' | tr '\n' '|')" +fi +c_repair=$(challenge_for repair-degraded-peer) +[[ ${#c_repair} == 64 ]] || bad "no repair challenge offered" + +for case in zero wrong_key wrong_action; do + case "${case}" in + zero) r="${zero}" ;; + wrong_key) r=$(respond "${wrong_key}" "${c_repair}") ;; + wrong_action) r=$(respond "${test_key}" "$(printf 'ff%.0s' $(seq 32))") ;; + esac + boot 10 "${r}" + if [[ -n "$(out '^RECOVERY_REFUSED \(Unauthorised\)$')" ]] && unchanged; then + pass "repair with ${case} response refused, nothing written" + else + bad "repair with ${case}: $(out '^RECOVERY_(ACTION|REFUSED)')" + fi +done + +good=$(respond "${test_key}" "${c_repair}") +boot 10 "${good}" +if [[ -n "$(out '^RECOVERY_ACTION: repair-degraded-peer DONE$')" ]] && ! unchanged; then + pass "authorised repair done" +else + bad "authorised repair: $(out '^RECOVERY_(ACTION|REFUSED)')" +fi +boot 6 +r=$(out '^CONTINUITY: RESUMED ') +if [[ "$(agent_of "${r}")" == "${agent}" && "${r}" == *"memory=${memory}"* ]]; then + pass "after repair a cold boot resumes writable with the same agent and memory" +else + bad "resume after repair: '${r:-$(out '^CONTINUITY:')}'" +fi +boot 10 "${good}" +if [[ -n "$(out '^RECOVERY_REFUSED \(NotApplicable\)$')" ]] && unchanged; then + pass "replaying the repair authorisation on the healthy store does nothing" +else + bad "replay: $(out '^RECOVERY_(ACTION|REFUSED)')" +fi + +echo "=== 2. Unprovisioned store: operator-authorised provisioning ===" +fresh_image +"${tool}" cfg "${image}" "${cfg_offset}" 1 0 >/dev/null; run_qemu # formatted store with data, no identity +boot 9 +c_prov=$(challenge_for provision-identity) +if [[ -n "$(out '^RECOVERY_CORE: ENTERED reason=Unprovisioned$')" && ${#c_prov} == 64 ]] && unchanged; then + pass "unprovisioned store enters the Recovery Core and offers only provisioning" +else + bad "unprovisioned inspection: $(tr -d '\r' <"${serial}" | grep -E '^RECOVERY_' | tr '\n' '|')" +fi +boot 11 "$(respond "${wrong_key}" "${c_prov}")" +if [[ -n "$(out '^RECOVERY_REFUSED \(Unauthorised\)$')" ]] && unchanged; then + pass "provisioning with a wrong key refused, nothing written" +else + bad "wrong-key provisioning: $(out '^RECOVERY_(ACTION|REFUSED)')" +fi +boot 11 "$(respond "${test_key}" "${c_prov}")" +new_agent=$(agent_of "$(out '^RECOVERY_ACTION: provision-identity DONE')") +boot 6 +if [[ ${#new_agent} == 64 && "$(agent_of "$(out '^CONTINUITY: RESUMED ')")" == "${new_agent}" ]]; then + pass "operator provisioning created one identity and a cold boot resumes it" +else + bad "operator provisioning: agent='${new_agent}' resume='$(out '^CONTINUITY:')'" +fi + +echo "=== 3. Identity loss: nothing may mint ===" +fresh_image +boot 5; lost=$(agent_of "$(out '^CONTINUITY: PROVISIONED')") +"${tool}" corrupt-kind "${image}" "${store_offset}" "${region_units}" 16 >/dev/null || bad "corrupt-kind failed" +boot 9 +if [[ -n "$(out '^RECOVERY_CORE: ENTERED reason=')" && -z "$(out '^RECOVERY_CHALLENGE:')" ]] && unchanged; then + pass "corrupted agent root: Recovery Core entered, no action offered, nothing written ($(out '^RECOVERY_CORE:' | sed 's/.*reason=//'))" +else + bad "identity loss inspection: $(tr -d '\r' <"${serial}" | grep -E '^RECOVERY_' | tr '\n' '|')" +fi +forged=$(respond "${test_key}" "$(printf 'aa%.0s' $(seq 32))") +for m in 10 11; do + boot "${m}" "${forged}" + if [[ -n "$(out '^RECOVERY_REFUSED \(')" && -z "$(out '^RECOVERY_ACTION:')" ]] && unchanged; then + pass "mode ${m} after identity loss refused, nothing written" + else + bad "mode ${m} after identity loss: $(out '^RECOVERY_(ACTION|REFUSED)')" + fi +done +boot 6 +if [[ -z "$(out '^CONTINUITY: (RESUMED|PROVISIONED)')" ]] && unchanged; then + pass "a normal boot after identity loss does not resume or mint (${lost:0:16}... is not replaced)" +else + bad "normal boot after identity loss: $(out '^CONTINUITY:')" +fi + +echo +echo "=== Summary (commit ${commit}) ===" +if [[ "${fail}" == 0 ]]; then + echo "RECOVERY_CORE_QEMU: PASS" +else + echo "RECOVERY_CORE_QEMU: FAIL" + exit 1 +fi +echo "RECOVERY_CORE_OPERATOR_CREDENTIAL: TEST-ONLY (real scheme undecided, ADR 0006 / M5)" diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index e98309e1..a331a785 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -67,7 +67,7 @@ echo "" echo "--- [Clippy Verification: AArch64 targets, -D warnings] ---" cargo clippy -p aienos-kernel --target aarch64-unknown-none --no-default-features -- -D warnings cargo clippy -p aienos-kernel --target aarch64-unknown-none --no-default-features --features seed0b-test-anchor -- -D warnings -for features in firmware handoff seed0b-qualification usb-keyboard nvme-read nvme-write store-qual continuity-qual; do +for features in firmware handoff seed0b-qualification usb-keyboard nvme-read nvme-write store-qual continuity-qual recovery-qual; do cargo clippy -p aienos-boot --target aarch64-unknown-uefi --features "${features}" --bins -- -D warnings done echo "PASS clippy: aarch64-unknown-none kernel and aarch64-unknown-uefi images, zero warnings" @@ -157,7 +157,8 @@ fi # Step 6e: P3 native NVMe driver and System Store v1 over NVMe (QEMU only). # Read and write/flush in both DMA modes (SMMU-confined, and fail-closed with # no SMMU), 4K root-write atomicity, the 4K Store crash/reboot campaign and the -# 512-byte Store campaign, and the M4 continuity campaign (ADR 0016). Never an +# 512-byte Store campaign, the M4 continuity campaign (ADR 0016) and the +# Recovery Core campaign (ADR 0006, TEST-ONLY operator key). Never an # unsafe DMA bypass build here. echo "" echo "--- [P3 NVMe + System Store v1 in QEMU] ---" @@ -171,6 +172,7 @@ if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/ ./scripts/qemu_store_crash_test.sh ./scripts/qemu_store_512b_crash_test.sh ./scripts/qemu_continuity_test.sh + ./scripts/qemu_recovery_test.sh else skipped "qemu-system-aarch64 or AAVMF firmware not present on host." fi