aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-kernel / src / recovery.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! AIENOS Deterministic Recovery Core (ADR 0006). |
| 17 | //! |
| 18 | //! A non-model, deterministic subsystem for: |
| 19 | //! - Offline local operator credential authentication |
| 20 | //! - Transactional A/B boot slot rollback |
| 21 | //! - Deterministic WAL truncation upon corruption without AI dependencies |
| 22 | |
| 23 | use crate::crypto::{constant_time_eq, sha256, HmacSha256}; |
| 24 | |
| 25 | /// Boot slot identifier for transactional updates. |
| 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 27 | pub enum BootSlot { |
| 28 | SlotA, |
| 29 | SlotB, |
| 30 | } |
| 31 | |
| 32 | impl BootSlot { |
| 33 | /// Return the alternate slot. |
| 34 | pub fn alternate(self) -> Self { |
| 35 | match self { |
| 36 | Self::SlotA => Self::SlotB, |
| 37 | Self::SlotB => Self::SlotA, |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | /// Operational state of a boot slot. |
| 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 44 | pub enum SlotHealth { |
| 45 | Unverified, |
| 46 | ConfirmedGood, |
| 47 | FailedRollback, |
| 48 | } |
| 49 | |
| 50 | /// Transactional A/B slot manager for deterministic kernel rollback. |
| 51 | #[derive(Clone, Debug)] |
| 52 | pub struct SlotManager { |
| 53 | pub active_slot: BootSlot, |
| 54 | pub slot_a_health: SlotHealth, |
| 55 | pub slot_b_health: SlotHealth, |
| 56 | pub boot_attempts: u32, |
| 57 | pub max_boot_attempts: u32, |
| 58 | } |
| 59 | |
| 60 | impl SlotManager { |
| 61 | /// Initialize with SlotA as primary confirmed good. |
| 62 | pub fn new() -> Self { |
| 63 | Self { |
| 64 | active_slot: BootSlot::SlotA, |
| 65 | slot_a_health: SlotHealth::ConfirmedGood, |
| 66 | slot_b_health: SlotHealth::Unverified, |
| 67 | boot_attempts: 0, |
| 68 | max_boot_attempts: 3, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Mark active slot as confirmed good after reaching health milestone. |
| 73 | pub fn mark_milestone_healthy(&mut self) { |
| 74 | self.boot_attempts = 0; |
| 75 | match self.active_slot { |
| 76 | BootSlot::SlotA => self.slot_a_health = SlotHealth::ConfirmedGood, |
| 77 | BootSlot::SlotB => self.slot_b_health = SlotHealth::ConfirmedGood, |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Record a failed boot attempt; triggers deterministic rollback if threshold exceeded. |
| 82 | pub fn record_boot_attempt(&mut self) -> bool { |
| 83 | self.boot_attempts += 1; |
| 84 | if self.boot_attempts >= self.max_boot_attempts { |
| 85 | // Trigger automatic rollback to alternate slot |
| 86 | match self.active_slot { |
| 87 | BootSlot::SlotA => self.slot_a_health = SlotHealth::FailedRollback, |
| 88 | BootSlot::SlotB => self.slot_b_health = SlotHealth::FailedRollback, |
| 89 | } |
| 90 | self.active_slot = self.active_slot.alternate(); |
| 91 | self.boot_attempts = 0; |
| 92 | true // Rolled back |
| 93 | } else { |
| 94 | false |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | impl Default for SlotManager { |
| 100 | fn default() -> Self { |
| 101 | Self::new() |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Offline local operator credential verifier without network or model dependencies. |
| 106 | /// |
| 107 | /// Invariant (ADR 0006): Offline authentication must use Argon2id key derivation for human |
| 108 | /// passphrases before challenge-response (or hardware/FIDO keys); do not use bare SHA-256 |
| 109 | /// for password verification. Fast hashing over human passwords is strictly prohibited to |
| 110 | /// resist offline brute-force and dictionary attacks. |
| 111 | pub struct OperatorAuth; |
| 112 | |
| 113 | /// Domain-separation prefix for the offline operator challenge-response MAC. |
| 114 | /// |
| 115 | /// It is prepended to the challenge inside the HMAC input so a tag produced for this |
| 116 | /// credential check can never be confused with any other HMAC use of the same key. The |
| 117 | /// trailing NUL terminates the label; the challenge that follows is always 32 bytes. |
| 118 | pub const OPERATOR_AUTH_DOMAIN: &[u8] = b"AIENOS-RECOVERY-OPERATOR-AUTH-v1\0"; |
| 119 | |
| 120 | impl OperatorAuth { |
| 121 | /// Verify an operator's response to an offline challenge. |
| 122 | /// |
| 123 | /// Computes exactly: |
| 124 | /// |
| 125 | /// ```text |
| 126 | /// expected = HMAC-SHA256(key = derived_key, |
| 127 | /// message = OPERATOR_AUTH_DOMAIN || challenge) |
| 128 | /// ``` |
| 129 | /// |
| 130 | /// where `OPERATOR_AUTH_DOMAIN` is `b"AIENOS-RECOVERY-OPERATOR-AUTH-v1\0"` (33 bytes), |
| 131 | /// and accepts only if `expected` equals `response`, compared with |
| 132 | /// [`constant_time_eq`] so the check does not exit early on the first differing byte. |
| 133 | /// |
| 134 | /// `derived_key` is treated as an opaque 32-byte high-entropy secret. Where it comes |
| 135 | /// from (Argon2id over a human passphrase, a FIDO/hardware-sealed key, or something |
| 136 | /// else) is out of scope for this function and not yet decided; ADR 0006 only forbids |
| 137 | /// deriving it with a fast hash of a human password. Challenge freshness (nonce |
| 138 | /// generation, single use, replay protection) is the caller's responsibility. |
| 139 | pub fn verify_offline_credentials( |
| 140 | derived_key: &[u8; 32], |
| 141 | challenge: &[u8; 32], |
| 142 | response: &[u8; 32], |
| 143 | ) -> bool { |
| 144 | let expected = Self::expected_response(derived_key, challenge); |
| 145 | constant_time_eq(&expected, response) |
| 146 | } |
| 147 | |
| 148 | /// The response a holder of `derived_key` must present for `challenge` |
| 149 | /// (used by operator-side tooling to answer a challenge). |
| 150 | pub fn expected_response(derived_key: &[u8; 32], challenge: &[u8; 32]) -> [u8; 32] { |
| 151 | let mut mac = HmacSha256::new(derived_key); |
| 152 | mac.update(OPERATOR_AUTH_DOMAIN); |
| 153 | mac.update(challenge); |
| 154 | mac.finalize() |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// Deterministic Write-Ahead Log frame recovery with truncation on corruption. |
| 159 | pub struct WalRecovery; |
| 160 | |
| 161 | impl WalRecovery { |
| 162 | /// Scan a serialized binary WAL log, validating per-record checksums. |
| 163 | /// |
| 164 | /// If corruption is encountered, deterministically truncates the log |
| 165 | /// at the last valid record boundary, preserving all uncorrupted history. |
| 166 | pub fn recover_and_truncate(raw_wal: &[u8]) -> (usize, usize) { |
| 167 | let mut offset = 0; |
| 168 | let mut valid_records = 0; |
| 169 | |
| 170 | while offset + 36 <= raw_wal.len() { |
| 171 | let record_len = u32::from_be_bytes([ |
| 172 | raw_wal[offset], |
| 173 | raw_wal[offset + 1], |
| 174 | raw_wal[offset + 2], |
| 175 | raw_wal[offset + 3], |
| 176 | ]) as usize; |
| 177 | |
| 178 | let expected_checksum = &raw_wal[offset + 4..offset + 36]; |
| 179 | let payload_start = offset + 36; |
| 180 | let payload_end = match payload_start.checked_add(record_len) { |
| 181 | Some(end) => end, |
| 182 | None => break, // Overflow in record length header: stop at valid boundary |
| 183 | }; |
| 184 | |
| 185 | if payload_end > raw_wal.len() { |
| 186 | // Incomplete or truncated record: stop at last valid boundary |
| 187 | break; |
| 188 | } |
| 189 | |
| 190 | let actual_checksum = sha256::hash(&raw_wal[payload_start..payload_end]); |
| 191 | if actual_checksum != expected_checksum { |
| 192 | // Corrupted record detected: halt and truncate log here |
| 193 | break; |
| 194 | } |
| 195 | |
| 196 | valid_records += 1; |
| 197 | offset = payload_end; |
| 198 | } |
| 199 | |
| 200 | let truncated_valid_bytes = offset; |
| 201 | (valid_records, truncated_valid_bytes) |
| 202 | } |
| 203 | |
| 204 | /// Helper to format a single WAL entry with 4-byte length and 32-byte SHA-256 checksum. |
| 205 | pub fn encode_entry(payload: &[u8], buf: &mut [u8]) -> usize { |
| 206 | let len = payload.len() as u32; |
| 207 | let checksum = sha256::hash(payload); |
| 208 | |
| 209 | let total_len = 36 + payload.len(); |
| 210 | if buf.len() < total_len { |
| 211 | return 0; |
| 212 | } |
| 213 | |
| 214 | buf[0..4].copy_from_slice(&len.to_be_bytes()); |
| 215 | buf[4..36].copy_from_slice(&checksum); |
| 216 | buf[36..total_len].copy_from_slice(payload); |
| 217 | total_len |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | #[cfg(test)] |
| 222 | mod tests { |
| 223 | use super::*; |
| 224 | use crate::crypto::hmac_sha256; |
| 225 | |
| 226 | const KEY: [u8; 32] = { |
| 227 | let mut k = [0u8; 32]; |
| 228 | let mut i = 0; |
| 229 | while i < 32 { |
| 230 | k[i] = i as u8; // 00..1f |
| 231 | i += 1; |
| 232 | } |
| 233 | k |
| 234 | }; |
| 235 | const CHALLENGE: [u8; 32] = { |
| 236 | let mut c = [0u8; 32]; |
| 237 | let mut i = 0; |
| 238 | while i < 32 { |
| 239 | c[i] = 0xa0 + i as u8; // a0..bf |
| 240 | i += 1; |
| 241 | } |
| 242 | c |
| 243 | }; |
| 244 | /// HMAC-SHA256(key = 00..1f, "AIENOS-RECOVERY-OPERATOR-AUTH-v1\0" || a0..bf), computed |
| 245 | /// independently with `openssl dgst -sha256 -mac HMAC -macopt hexkey:<KEY>`. |
| 246 | const KAT_RESPONSE: [u8; 32] = [ |
| 247 | 0xf6, 0x16, 0x2d, 0xa5, 0xf8, 0x79, 0xe9, 0xbd, 0x4d, 0xef, 0xc7, 0x10, 0x8c, 0x46, 0x3b, |
| 248 | 0x5d, 0x16, 0x4f, 0x4d, 0xb6, 0x8a, 0xe9, 0x91, 0x78, 0x1b, 0xf7, 0x98, 0xfc, 0x14, 0x90, |
| 249 | 0x7a, 0xaa, |
| 250 | ]; |
| 251 | |
| 252 | #[test] |
| 253 | fn hmac_primitive_rfc4231_case_2() { |
| 254 | let tag = hmac_sha256(b"Jefe", b"what do ya want for nothing?"); |
| 255 | assert_eq!( |
| 256 | tag, |
| 257 | [ |
| 258 | 0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, |
| 259 | 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, |
| 260 | 0x64, 0xec, 0x38, 0x43, |
| 261 | ] |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn operator_auth_known_answer_accepted() { |
| 267 | assert_eq!(OPERATOR_AUTH_DOMAIN.len(), 33); |
| 268 | assert_eq!( |
| 269 | OperatorAuth::expected_response(&KEY, &CHALLENGE), |
| 270 | KAT_RESPONSE |
| 271 | ); |
| 272 | let mut msg = [0u8; 65]; |
| 273 | msg[..33].copy_from_slice(OPERATOR_AUTH_DOMAIN); |
| 274 | msg[33..].copy_from_slice(&CHALLENGE); |
| 275 | assert_eq!(hmac_sha256(&KEY, &msg), KAT_RESPONSE); |
| 276 | assert!(OperatorAuth::verify_offline_credentials( |
| 277 | &KEY, |
| 278 | &CHALLENGE, |
| 279 | &KAT_RESPONSE |
| 280 | )); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn operator_auth_rejects_any_single_bit_flip() { |
| 285 | for byte in 0..32 { |
| 286 | for bit in 0..8 { |
| 287 | let mask = 1u8 << bit; |
| 288 | |
| 289 | let mut response = KAT_RESPONSE; |
| 290 | response[byte] ^= mask; |
| 291 | assert!( |
| 292 | !OperatorAuth::verify_offline_credentials(&KEY, &CHALLENGE, &response), |
| 293 | "response flip byte {byte} bit {bit} accepted" |
| 294 | ); |
| 295 | |
| 296 | let mut challenge = CHALLENGE; |
| 297 | challenge[byte] ^= mask; |
| 298 | assert!( |
| 299 | !OperatorAuth::verify_offline_credentials(&KEY, &challenge, &KAT_RESPONSE), |
| 300 | "challenge flip byte {byte} bit {bit} accepted" |
| 301 | ); |
| 302 | |
| 303 | let mut key = KEY; |
| 304 | key[byte] ^= mask; |
| 305 | assert!( |
| 306 | !OperatorAuth::verify_offline_credentials(&key, &CHALLENGE, &KAT_RESPONSE), |
| 307 | "key flip byte {byte} bit {bit} accepted" |
| 308 | ); |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn operator_auth_rejects_legacy_bare_sha256_response() { |
| 315 | let mut hasher = sha256::Sha256::new(); |
| 316 | hasher.update(&KEY); |
| 317 | hasher.update(&CHALLENGE); |
| 318 | let legacy = hasher.finalize(); |
| 319 | assert_ne!(legacy, KAT_RESPONSE); |
| 320 | assert!(!OperatorAuth::verify_offline_credentials( |
| 321 | &KEY, &CHALLENGE, &legacy |
| 322 | )); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn operator_auth_rejects_undomained_hmac_and_zero_response() { |
| 327 | // Plain HMAC over the challenge without the domain prefix must not verify. |
| 328 | let undomained = hmac_sha256(&KEY, &CHALLENGE); |
| 329 | assert!(!OperatorAuth::verify_offline_credentials( |
| 330 | &KEY, |
| 331 | &CHALLENGE, |
| 332 | &undomained |
| 333 | )); |
| 334 | assert!(!OperatorAuth::verify_offline_credentials( |
| 335 | &KEY, &CHALLENGE, &[0u8; 32] |
| 336 | )); |
| 337 | // All-zero key and challenge still require the real MAC, not zeros. |
| 338 | assert!(!OperatorAuth::verify_offline_credentials( |
| 339 | &[0u8; 32], &[0u8; 32], &[0u8; 32] |
| 340 | )); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn test_slot_rollback_on_failure() { |
| 345 | let mut mgr = SlotManager::new(); |
| 346 | assert_eq!(mgr.active_slot, BootSlot::SlotA); |
| 347 | |
| 348 | assert!(!mgr.record_boot_attempt()); |
| 349 | assert!(!mgr.record_boot_attempt()); |
| 350 | // 3rd attempt triggers rollback |
| 351 | assert!(mgr.record_boot_attempt()); |
| 352 | assert_eq!(mgr.active_slot, BootSlot::SlotB); |
| 353 | assert_eq!(mgr.slot_a_health, SlotHealth::FailedRollback); |
| 354 | |
| 355 | // SlotB reaches health milestone |
| 356 | mgr.mark_milestone_healthy(); |
| 357 | assert_eq!(mgr.slot_b_health, SlotHealth::ConfirmedGood); |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn test_wal_truncation_on_corruption() { |
| 362 | let mut buffer = [0u8; 512]; |
| 363 | let mut offset = 0; |
| 364 | |
| 365 | // Entry 1: 10 bytes |
| 366 | let e1 = b"boot_start"; |
| 367 | let n1 = WalRecovery::encode_entry(e1, &mut buffer[offset..]); |
| 368 | offset += n1; |
| 369 | |
| 370 | // Entry 2: 12 bytes |
| 371 | let e2 = b"cortex_mount"; |
| 372 | let n2 = WalRecovery::encode_entry(e2, &mut buffer[offset..]); |
| 373 | offset += n2; |
| 374 | |
| 375 | // Verify clean log |
| 376 | let (valid_count, valid_bytes) = WalRecovery::recover_and_truncate(&buffer[..offset]); |
| 377 | assert_eq!(valid_count, 2); |
| 378 | assert_eq!(valid_bytes, offset); |
| 379 | |
| 380 | // Entry 3: Corrupt byte in payload |
| 381 | let e3 = b"corrupted_entry_here"; |
| 382 | let n3 = WalRecovery::encode_entry(e3, &mut buffer[offset..]); |
| 383 | // Corrupt one byte of e3's payload |
| 384 | buffer[offset + 40] ^= 0xFF; |
| 385 | let total_with_corrupt = offset + n3; |
| 386 | |
| 387 | // Recovery should reject entry 3 and truncate cleanly back to 2 valid entries! |
| 388 | let (recovered_count, recovered_bytes) = |
| 389 | WalRecovery::recover_and_truncate(&buffer[..total_with_corrupt]); |
| 390 | assert_eq!(recovered_count, 2); |
| 391 | assert_eq!(recovered_bytes, offset); |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn test_wal_zero_length_entry_and_overflow_protection() { |
| 396 | let mut buffer = [0u8; 256]; |
| 397 | let mut offset = 0; |
| 398 | |
| 399 | // 1. Encode valid zero-length entry |
| 400 | let n0 = WalRecovery::encode_entry(b"", &mut buffer[offset..]); |
| 401 | assert_eq!(n0, 36); |
| 402 | offset += n0; |
| 403 | |
| 404 | // 2. Encode normal entry |
| 405 | let n1 = WalRecovery::encode_entry(b"checkpoint", &mut buffer[offset..]); |
| 406 | offset += n1; |
| 407 | |
| 408 | let (valid_count, valid_bytes) = WalRecovery::recover_and_truncate(&buffer[..offset]); |
| 409 | assert_eq!(valid_count, 2); |
| 410 | assert_eq!(valid_bytes, offset); |
| 411 | |
| 412 | // 3. Craft malicious length header (u32::MAX) that could cause integer overflow |
| 413 | let mut malicious_buf = [0u8; 100]; |
| 414 | malicious_buf[0..4].copy_from_slice(&u32::MAX.to_be_bytes()); |
| 415 | malicious_buf[4..36].copy_from_slice(&[0xAAu8; 32]); |
| 416 | let (mal_count, mal_bytes) = WalRecovery::recover_and_truncate(&malicious_buf); |
| 417 | assert_eq!(mal_count, 0); |
| 418 | assert_eq!(mal_bytes, 0); |
| 419 | |
| 420 | // 4. Incomplete header (< 36 bytes) |
| 421 | let (inc_count, inc_bytes) = WalRecovery::recover_and_truncate(&[1, 2, 3, 4, 5]); |
| 422 | assert_eq!(inc_count, 0); |
| 423 | assert_eq!(inc_bytes, 0); |
| 424 | |
| 425 | // 5. Empty slice |
| 426 | let (empty_count, empty_bytes) = WalRecovery::recover_and_truncate(&[]); |
| 427 | assert_eq!(empty_count, 0); |
| 428 | assert_eq!(empty_bytes, 0); |
| 429 | } |
| 430 | } |