interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / security.rs

911 lines · 33931 bytes Raw Blame History
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//! M5 Key Hierarchy, Security Manifests, and Anti-Rollback (ADR 0017).
17//!
18//! Normative implementation of storage security roots:
19//! - Subkey derivation via HKDF-SHA256 (K_cortex, K_agent, K_artifact, K_root_auth)
20//! - KeySlotManifest (kind = 21, plaintext bootstrap object with up to 4 keyslots)
21//! - SecurityManifest (kind = 22, 256-byte fixed root object authenticated under K_root_auth)
22//! - MigrationManifest (kind = 23, identity-preserving migration authorization)
23//! - AntiRollbackSource trait, RollbackAnchor, and epoch validation protocol.
24
25extern crate alloc;
26
27use alloc::vec::Vec;
28
29use crate::crypto::hkdf::hkdf_expand;
30use crate::crypto::hmac::{constant_time_eq, HmacSha256};
31use crate::store::v1::ObjectId;
32use aienos_crypto::aes_gcm_siv::{decrypt as raw_decrypt, encrypt as raw_encrypt, TAG_LEN};
33
34pub const KIND_KEYSLOT_MANIFEST: u16 = 21;
35pub const KIND_SECURITY_MANIFEST: u16 = 22;
36pub const KIND_MIGRATION_MANIFEST: u16 = 23;
37
38pub const KEYSLOT_MANIFEST_MAGIC: &[u8; 8] = b"AIENKSL1";
39pub const SECURITY_MANIFEST_MAGIC: &[u8; 8] = b"AIENSEC1";
40pub const MIGRATION_MANIFEST_MAGIC: &[u8; 8] = b"AIENMIG1";
41
42pub const SECURITY_FORMAT_VERSION: u16 = 1;
43pub const SECURITY_MANIFEST_SIZE: usize = 256;
44pub const KEYSLOT_HEADER_SIZE: usize = 128;
45pub const KEYSLOT_DESCRIPTOR_SIZE: usize = 128;
46pub const KEYSLOT_MAX_SLOTS: usize = 4;
47pub const KEYSLOT_MAX_ARENA_BYTES: usize = 32768; // 32 KiB
48pub const ROOT_AUTH_DOMAIN_PREFIX: &[u8; 23] = b"AIENOS-M5-ROOT-AUTH-V1\0";
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum SecurityError {
52 FormatError(&'static str),
53 BufferTooShort,
54 InvalidMagic,
55 UnsupportedVersion,
56 NonzeroReserved,
57 AuthenticationFailed,
58 KeySlotIndexOutOfRange,
59 PayloadArenaOverflow,
60}
61
62// ---------------------------------------------------------------------------
63// 1. Subkey Derivation from K_vol
64// ---------------------------------------------------------------------------
65
66/// Subkeys derived deterministically from K_vol via HKDF-SHA256 (ADR 0017 Section 2.2).
67#[derive(Clone)]
68pub struct DerivedSubkeys {
69 pub k_cortex: [u8; 32],
70 pub k_agent: [u8; 32],
71 pub k_artifact: [u8; 32],
72 pub k_root_auth: [u8; 32],
73}
74
75impl Drop for DerivedSubkeys {
76 fn drop(&mut self) {
77 for b in &mut self.k_cortex {
78 unsafe { core::ptr::write_volatile(b, 0) };
79 }
80 for b in &mut self.k_agent {
81 unsafe { core::ptr::write_volatile(b, 0) };
82 }
83 for b in &mut self.k_artifact {
84 unsafe { core::ptr::write_volatile(b, 0) };
85 }
86 for b in &mut self.k_root_auth {
87 unsafe { core::ptr::write_volatile(b, 0) };
88 }
89 }
90}
91
92/// Derive operational subkeys from K_vol using HKDF-SHA256 domain-separated labels.
93pub fn derive_subkeys(k_vol: &[u8; 32]) -> DerivedSubkeys {
94 let mut k_cortex = [0u8; 32];
95 let mut k_agent = [0u8; 32];
96 let mut k_artifact = [0u8; 32];
97 let mut k_root_auth = [0u8; 32];
98
99 hkdf_expand(k_vol, b"AIENOS/M5/CORTEX-V1", &mut k_cortex)
100 .expect("HKDF expand 32 bytes cannot fail");
101 hkdf_expand(k_vol, b"AIENOS/M5/AGENT-STATE-V1", &mut k_agent)
102 .expect("HKDF expand 32 bytes cannot fail");
103 hkdf_expand(k_vol, b"AIENOS/M5/ARTIFACT-V1", &mut k_artifact)
104 .expect("HKDF expand 32 bytes cannot fail");
105 hkdf_expand(k_vol, b"AIENOS/M5/ROOT-AUTH-V1", &mut k_root_auth)
106 .expect("HKDF expand 32 bytes cannot fail");
107
108 DerivedSubkeys {
109 k_cortex,
110 k_agent,
111 k_artifact,
112 k_root_auth,
113 }
114}
115
116// ---------------------------------------------------------------------------
117// 2. KeySlotManifest (kind = 21)
118// ---------------------------------------------------------------------------
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121#[repr(u8)]
122pub enum KeySlotType {
123 Empty = 0,
124 Tpm2PolicyAuthorize = 1,
125 RecoveryArgon2id = 2,
126 RecoveryRawSecret = 3,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub struct KeySlotDescriptor {
131 pub slot_type: KeySlotType,
132 pub wrap_suite: u8,
133 pub kdf_suite: u8,
134 pub flags: u8,
135 pub slot_id: u32,
136 pub key_epoch: u64,
137 pub salt: [u8; 16],
138 pub argon_m_kib: u32,
139 pub argon_t_cost: u32,
140 pub argon_p_cost: u32,
141 pub wrap_nonce: [u8; 12],
142 pub wrapped_k_vol: [u8; 32],
143 pub wrap_tag: [u8; 16],
144 pub payload_offset: u32,
145 pub payload_length: u32,
146 pub reserved: [u8; 16],
147}
148
149impl KeySlotDescriptor {
150 pub const EMPTY: Self = Self {
151 slot_type: KeySlotType::Empty,
152 wrap_suite: 0x01,
153 kdf_suite: 0x00,
154 flags: 0,
155 slot_id: 0,
156 key_epoch: 0,
157 salt: [0; 16],
158 argon_m_kib: 0,
159 argon_t_cost: 0,
160 argon_p_cost: 0,
161 wrap_nonce: [0; 12],
162 wrapped_k_vol: [0; 32],
163 wrap_tag: [0; 16],
164 payload_offset: 0,
165 payload_length: 0,
166 reserved: [0; 16],
167 };
168
169 pub fn encode(&self) -> [u8; KEYSLOT_DESCRIPTOR_SIZE] {
170 let mut out = [0u8; KEYSLOT_DESCRIPTOR_SIZE];
171 out[0] = self.slot_type as u8;
172 out[1] = self.wrap_suite;
173 out[2] = self.kdf_suite;
174 out[3] = self.flags;
175 out[4..8].copy_from_slice(&self.slot_id.to_le_bytes());
176 out[8..16].copy_from_slice(&self.key_epoch.to_le_bytes());
177 out[16..32].copy_from_slice(&self.salt);
178 out[32..36].copy_from_slice(&self.argon_m_kib.to_le_bytes());
179 out[36..40].copy_from_slice(&self.argon_t_cost.to_le_bytes());
180 out[40..44].copy_from_slice(&self.argon_p_cost.to_le_bytes());
181 out[44..56].copy_from_slice(&self.wrap_nonce);
182 out[56..88].copy_from_slice(&self.wrapped_k_vol);
183 out[88..104].copy_from_slice(&self.wrap_tag);
184 out[104..108].copy_from_slice(&self.payload_offset.to_le_bytes());
185 out[108..112].copy_from_slice(&self.payload_length.to_le_bytes());
186 out[112..128].copy_from_slice(&self.reserved);
187 out
188 }
189
190 pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> {
191 if bytes.len() < KEYSLOT_DESCRIPTOR_SIZE {
192 return Err(SecurityError::BufferTooShort);
193 }
194 let slot_type = match bytes[0] {
195 0 => KeySlotType::Empty,
196 1 => KeySlotType::Tpm2PolicyAuthorize,
197 2 => KeySlotType::RecoveryArgon2id,
198 3 => KeySlotType::RecoveryRawSecret,
199 _ => return Err(SecurityError::FormatError("unknown slot type")),
200 };
201 let wrap_suite = bytes[1];
202 let kdf_suite = bytes[2];
203 let flags = bytes[3];
204 let slot_id = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
205 let key_epoch = u64::from_le_bytes([
206 bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
207 ]);
208 let mut salt = [0u8; 16];
209 salt.copy_from_slice(&bytes[16..32]);
210 let argon_m_kib = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]);
211 let argon_t_cost = u32::from_le_bytes([bytes[36], bytes[37], bytes[38], bytes[39]]);
212 let argon_p_cost = u32::from_le_bytes([bytes[40], bytes[41], bytes[42], bytes[43]]);
213
214 if argon_m_kib > 131072 || argon_t_cost > 10 || argon_p_cost > 16 {
215 return Err(SecurityError::FormatError(
216 "argon2 parameters exceed bounds",
217 ));
218 }
219
220 let mut wrap_nonce = [0u8; 12];
221 wrap_nonce.copy_from_slice(&bytes[44..56]);
222 let mut wrapped_k_vol = [0u8; 32];
223 wrapped_k_vol.copy_from_slice(&bytes[56..88]);
224 let mut wrap_tag = [0u8; 16];
225 wrap_tag.copy_from_slice(&bytes[88..104]);
226
227 let payload_offset = u32::from_le_bytes([bytes[104], bytes[105], bytes[106], bytes[107]]);
228 let payload_length = u32::from_le_bytes([bytes[108], bytes[109], bytes[110], bytes[111]]);
229
230 let mut reserved = [0u8; 16];
231 reserved.copy_from_slice(&bytes[112..128]);
232 if reserved.iter().any(|b| *b != 0) {
233 return Err(SecurityError::NonzeroReserved);
234 }
235
236 Ok(Self {
237 slot_type,
238 wrap_suite,
239 kdf_suite,
240 flags,
241 slot_id,
242 key_epoch,
243 salt,
244 argon_m_kib,
245 argon_t_cost,
246 argon_p_cost,
247 wrap_nonce,
248 wrapped_k_vol,
249 wrap_tag,
250 payload_offset,
251 payload_length,
252 reserved,
253 })
254 }
255
256 /// Unwrap K_vol given the corresponding 32-byte KEK.
257 pub fn unwrap_k_vol(&self, kek: &[u8; 32]) -> Result<[u8; 32], SecurityError> {
258 if self.slot_type == KeySlotType::Empty {
259 return Err(SecurityError::FormatError("cannot unwrap empty keyslot"));
260 }
261 if self.wrap_suite != 0x01 {
262 return Err(SecurityError::FormatError("unsupported wrap suite"));
263 }
264
265 let mut ciphertext_and_tag = [0u8; 32 + TAG_LEN];
266 ciphertext_and_tag[0..32].copy_from_slice(&self.wrapped_k_vol);
267 ciphertext_and_tag[32..48].copy_from_slice(&self.wrap_tag);
268
269 let mut k_vol = [0u8; 32];
270 let aad = self.slot_id.to_le_bytes();
271
272 raw_decrypt(kek, &self.wrap_nonce, &aad, &ciphertext_and_tag, &mut k_vol)
273 .map_err(|_| SecurityError::AuthenticationFailed)?;
274
275 Ok(k_vol)
276 }
277
278 /// Wrap K_vol with the given 32-byte KEK and fresh 12-byte nonce.
279 pub fn wrap_k_vol(&mut self, kek: &[u8; 32], k_vol: &[u8; 32], nonce: &[u8; 12]) {
280 self.wrap_suite = 0x01;
281 self.wrap_nonce = *nonce;
282 let aad = self.slot_id.to_le_bytes();
283
284 let mut out = [0u8; 32 + TAG_LEN];
285 raw_encrypt(kek, nonce, &aad, k_vol, &mut out);
286
287 self.wrapped_k_vol.copy_from_slice(&out[0..32]);
288 self.wrap_tag.copy_from_slice(&out[32..48]);
289 }
290}
291
292#[derive(Clone, Debug, PartialEq, Eq)]
293pub struct KeySlotManifest {
294 pub store_uuid: [u8; 16],
295 pub manifest_sequence: u64,
296 pub previous_keyslot_manifest_id: ObjectId,
297 pub active_key_epoch: u64,
298 pub slot_count: u32,
299 pub slots: [KeySlotDescriptor; KEYSLOT_MAX_SLOTS],
300 pub payload_arena: Vec<u8>,
301}
302
303impl KeySlotManifest {
304 pub fn encode(&self) -> Result<Vec<u8>, SecurityError> {
305 if self.payload_arena.len() > KEYSLOT_MAX_ARENA_BYTES {
306 return Err(SecurityError::PayloadArenaOverflow);
307 }
308 let total_size = KEYSLOT_HEADER_SIZE
309 + (KEYSLOT_MAX_SLOTS * KEYSLOT_DESCRIPTOR_SIZE)
310 + self.payload_arena.len();
311 let mut out = Vec::with_capacity(total_size);
312
313 out.extend_from_slice(KEYSLOT_MANIFEST_MAGIC);
314 out.extend_from_slice(&SECURITY_FORMAT_VERSION.to_le_bytes());
315 out.extend_from_slice(&0u16.to_le_bytes()); // flags
316 out.extend_from_slice(&self.store_uuid);
317 out.extend_from_slice(&self.manifest_sequence.to_le_bytes());
318 out.extend_from_slice(&self.previous_keyslot_manifest_id.0);
319 out.extend_from_slice(&self.active_key_epoch.to_le_bytes());
320 out.extend_from_slice(&self.slot_count.to_le_bytes());
321 out.extend_from_slice(&[0u8; 48]); // reserved
322
323 for slot in &self.slots {
324 out.extend_from_slice(&slot.encode());
325 }
326
327 out.extend_from_slice(&self.payload_arena);
328 Ok(out)
329 }
330
331 pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> {
332 let fixed_header_len = KEYSLOT_HEADER_SIZE + (KEYSLOT_MAX_SLOTS * KEYSLOT_DESCRIPTOR_SIZE);
333 if bytes.len() < fixed_header_len {
334 return Err(SecurityError::BufferTooShort);
335 }
336
337 if &bytes[0..8] != KEYSLOT_MANIFEST_MAGIC {
338 return Err(SecurityError::InvalidMagic);
339 }
340
341 let format_version = u16::from_le_bytes([bytes[8], bytes[9]]);
342 if format_version != SECURITY_FORMAT_VERSION {
343 return Err(SecurityError::UnsupportedVersion);
344 }
345
346 let flags = u16::from_le_bytes([bytes[10], bytes[11]]);
347 if flags != 0 {
348 return Err(SecurityError::FormatError("nonzero keyslot manifest flags"));
349 }
350
351 let mut store_uuid = [0u8; 16];
352 store_uuid.copy_from_slice(&bytes[12..28]);
353
354 let manifest_sequence = u64::from_le_bytes([
355 bytes[28], bytes[29], bytes[30], bytes[31], bytes[32], bytes[33], bytes[34], bytes[35],
356 ]);
357
358 let mut prev_id = [0u8; 32];
359 prev_id.copy_from_slice(&bytes[36..68]);
360 let previous_keyslot_manifest_id = ObjectId(prev_id);
361
362 let active_key_epoch = u64::from_le_bytes([
363 bytes[68], bytes[69], bytes[70], bytes[71], bytes[72], bytes[73], bytes[74], bytes[75],
364 ]);
365
366 let slot_count = u32::from_le_bytes([bytes[76], bytes[77], bytes[78], bytes[79]]);
367 if slot_count as usize > KEYSLOT_MAX_SLOTS {
368 return Err(SecurityError::KeySlotIndexOutOfRange);
369 }
370
371 if bytes[80..128].iter().any(|b| *b != 0) {
372 return Err(SecurityError::NonzeroReserved);
373 }
374
375 let mut slots = [KeySlotDescriptor::EMPTY; KEYSLOT_MAX_SLOTS];
376 for (i, slot) in slots.iter_mut().enumerate() {
377 let start = KEYSLOT_HEADER_SIZE + (i * KEYSLOT_DESCRIPTOR_SIZE);
378 *slot = KeySlotDescriptor::decode(&bytes[start..start + KEYSLOT_DESCRIPTOR_SIZE])?;
379 }
380
381 let arena_bytes = &bytes[fixed_header_len..];
382 if arena_bytes.len() > KEYSLOT_MAX_ARENA_BYTES {
383 return Err(SecurityError::PayloadArenaOverflow);
384 }
385
386 Ok(Self {
387 store_uuid,
388 manifest_sequence,
389 previous_keyslot_manifest_id,
390 active_key_epoch,
391 slot_count,
392 slots,
393 payload_arena: arena_bytes.to_vec(),
394 })
395 }
396}
397
398// ---------------------------------------------------------------------------
399// 3. SecurityManifest (kind = 22)
400// ---------------------------------------------------------------------------
401
402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
403pub struct SecurityManifest {
404 pub format_version: u16,
405 pub flags: u16,
406 pub reserved: u32,
407 pub store_uuid: [u8; 16],
408 pub generation: u64,
409 pub security_sequence: u64,
410 pub epoch: u64,
411 pub key_epoch: u64,
412 pub previous_security_manifest_id: ObjectId,
413 pub keyslot_manifest_id: ObjectId,
414 pub agent_root_id: ObjectId,
415 pub continuity_manifest_id: ObjectId,
416 pub migration_manifest_id: ObjectId,
417 pub root_mac: [u8; 32],
418}
419
420impl SecurityManifest {
421 /// Compute HMAC-SHA256 over header bytes [0..224] using K_root_auth.
422 pub fn compute_mac(&self, k_root_auth: &[u8; 32]) -> [u8; 32] {
423 let mut unsigned_bytes = [0u8; 224];
424 unsigned_bytes[0..8].copy_from_slice(SECURITY_MANIFEST_MAGIC);
425 unsigned_bytes[8..10].copy_from_slice(&self.format_version.to_le_bytes());
426 unsigned_bytes[10..12].copy_from_slice(&self.flags.to_le_bytes());
427 unsigned_bytes[12..16].copy_from_slice(&self.reserved.to_le_bytes());
428 unsigned_bytes[16..32].copy_from_slice(&self.store_uuid);
429 unsigned_bytes[32..40].copy_from_slice(&self.generation.to_le_bytes());
430 unsigned_bytes[40..48].copy_from_slice(&self.security_sequence.to_le_bytes());
431 unsigned_bytes[48..56].copy_from_slice(&self.epoch.to_le_bytes());
432 unsigned_bytes[56..64].copy_from_slice(&self.key_epoch.to_le_bytes());
433 unsigned_bytes[64..96].copy_from_slice(&self.previous_security_manifest_id.0);
434 unsigned_bytes[96..128].copy_from_slice(&self.keyslot_manifest_id.0);
435 unsigned_bytes[128..160].copy_from_slice(&self.agent_root_id.0);
436 unsigned_bytes[160..192].copy_from_slice(&self.continuity_manifest_id.0);
437 unsigned_bytes[192..224].copy_from_slice(&self.migration_manifest_id.0);
438
439 let mut hmac = HmacSha256::new(k_root_auth);
440 hmac.update(ROOT_AUTH_DOMAIN_PREFIX);
441 hmac.update(&unsigned_bytes);
442 hmac.finalize()
443 }
444
445 /// Sign this manifest in place under K_root_auth.
446 pub fn sign(&mut self, k_root_auth: &[u8; 32]) {
447 self.root_mac = self.compute_mac(k_root_auth);
448 }
449
450 /// Verify this manifest's root_mac in constant time.
451 pub fn verify(&self, k_root_auth: &[u8; 32]) -> bool {
452 let expected = self.compute_mac(k_root_auth);
453 constant_time_eq(&self.root_mac, &expected)
454 }
455
456 /// Encode the 256-byte SecurityManifest.
457 pub fn encode(&self) -> [u8; SECURITY_MANIFEST_SIZE] {
458 let mut out = [0u8; SECURITY_MANIFEST_SIZE];
459 out[0..8].copy_from_slice(SECURITY_MANIFEST_MAGIC);
460 out[8..10].copy_from_slice(&self.format_version.to_le_bytes());
461 out[10..12].copy_from_slice(&self.flags.to_le_bytes());
462 out[12..16].copy_from_slice(&self.reserved.to_le_bytes());
463 out[16..32].copy_from_slice(&self.store_uuid);
464 out[32..40].copy_from_slice(&self.generation.to_le_bytes());
465 out[40..48].copy_from_slice(&self.security_sequence.to_le_bytes());
466 out[48..56].copy_from_slice(&self.epoch.to_le_bytes());
467 out[56..64].copy_from_slice(&self.key_epoch.to_le_bytes());
468 out[64..96].copy_from_slice(&self.previous_security_manifest_id.0);
469 out[96..128].copy_from_slice(&self.keyslot_manifest_id.0);
470 out[128..160].copy_from_slice(&self.agent_root_id.0);
471 out[160..192].copy_from_slice(&self.continuity_manifest_id.0);
472 out[192..224].copy_from_slice(&self.migration_manifest_id.0);
473 out[224..256].copy_from_slice(&self.root_mac);
474 out
475 }
476
477 /// Decode and structurally validate a 256-byte SecurityManifest.
478 pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> {
479 if bytes.len() != SECURITY_MANIFEST_SIZE {
480 return Err(SecurityError::BufferTooShort);
481 }
482
483 if &bytes[0..8] != SECURITY_MANIFEST_MAGIC {
484 return Err(SecurityError::InvalidMagic);
485 }
486
487 let format_version = u16::from_le_bytes([bytes[8], bytes[9]]);
488 if format_version != SECURITY_FORMAT_VERSION {
489 return Err(SecurityError::UnsupportedVersion);
490 }
491
492 let flags = u16::from_le_bytes([bytes[10], bytes[11]]);
493 if flags != 0 {
494 return Err(SecurityError::FormatError(
495 "nonzero security manifest flags",
496 ));
497 }
498
499 let reserved = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
500 if reserved != 0 {
501 return Err(SecurityError::NonzeroReserved);
502 }
503
504 let mut store_uuid = [0u8; 16];
505 store_uuid.copy_from_slice(&bytes[16..32]);
506
507 let generation = u64::from_le_bytes([
508 bytes[32], bytes[33], bytes[34], bytes[35], bytes[36], bytes[37], bytes[38], bytes[39],
509 ]);
510 let security_sequence = u64::from_le_bytes([
511 bytes[40], bytes[41], bytes[42], bytes[43], bytes[44], bytes[45], bytes[46], bytes[47],
512 ]);
513 let epoch = u64::from_le_bytes([
514 bytes[48], bytes[49], bytes[50], bytes[51], bytes[52], bytes[53], bytes[54], bytes[55],
515 ]);
516 let key_epoch = u64::from_le_bytes([
517 bytes[56], bytes[57], bytes[58], bytes[59], bytes[60], bytes[61], bytes[62], bytes[63],
518 ]);
519
520 let mut prev_id = [0u8; 32];
521 prev_id.copy_from_slice(&bytes[64..96]);
522 let previous_security_manifest_id = ObjectId(prev_id);
523
524 let mut keyslot_id = [0u8; 32];
525 keyslot_id.copy_from_slice(&bytes[96..128]);
526 let keyslot_manifest_id = ObjectId(keyslot_id);
527
528 let mut agent_id = [0u8; 32];
529 agent_id.copy_from_slice(&bytes[128..160]);
530 let agent_root_id = ObjectId(agent_id);
531
532 let mut cont_id = [0u8; 32];
533 cont_id.copy_from_slice(&bytes[160..192]);
534 let continuity_manifest_id = ObjectId(cont_id);
535
536 let mut mig_id = [0u8; 32];
537 mig_id.copy_from_slice(&bytes[192..224]);
538 let migration_manifest_id = ObjectId(mig_id);
539
540 let mut root_mac = [0u8; 32];
541 root_mac.copy_from_slice(&bytes[224..256]);
542
543 Ok(Self {
544 format_version,
545 flags,
546 reserved,
547 store_uuid,
548 generation,
549 security_sequence,
550 epoch,
551 key_epoch,
552 previous_security_manifest_id,
553 keyslot_manifest_id,
554 agent_root_id,
555 continuity_manifest_id,
556 migration_manifest_id,
557 root_mac,
558 })
559 }
560}
561
562// ---------------------------------------------------------------------------
563// 4. MigrationManifest (kind = 23)
564// ---------------------------------------------------------------------------
565
566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
567pub struct MigrationManifest {
568 pub format_version: u16,
569 pub flags: u16,
570 pub reserved: u32,
571 pub agent_root_id: ObjectId,
572 pub genesis_store_uuid: [u8; 16],
573 pub origin_store_uuid: [u8; 16],
574 pub target_store_uuid: [u8; 16],
575 pub origin_security_manifest_id: ObjectId,
576 pub origin_continuity_manifest_id: ObjectId,
577 pub origin_sequence: u64,
578 pub origin_incarnation: u64,
579 pub origin_epoch: u64,
580 pub origin_rollback_digest: [u8; 32],
581 pub migration_sequence: u64,
582 pub offline_signature: [u8; 64],
583}
584
585pub const MIGRATION_MANIFEST_SIZE: usize =
586 8 + 2 + 2 + 4 + 32 + 16 + 16 + 16 + 32 + 32 + 8 + 8 + 8 + 32 + 8 + 64;
587
588impl MigrationManifest {
589 pub fn encode(&self) -> [u8; MIGRATION_MANIFEST_SIZE] {
590 let mut out = [0u8; MIGRATION_MANIFEST_SIZE];
591 out[0..8].copy_from_slice(MIGRATION_MANIFEST_MAGIC);
592 out[8..10].copy_from_slice(&self.format_version.to_le_bytes());
593 out[10..12].copy_from_slice(&self.flags.to_le_bytes());
594 out[12..16].copy_from_slice(&self.reserved.to_le_bytes());
595 out[16..48].copy_from_slice(&self.agent_root_id.0);
596 out[48..64].copy_from_slice(&self.genesis_store_uuid);
597 out[64..80].copy_from_slice(&self.origin_store_uuid);
598 out[80..96].copy_from_slice(&self.target_store_uuid);
599 out[96..128].copy_from_slice(&self.origin_security_manifest_id.0);
600 out[128..160].copy_from_slice(&self.origin_continuity_manifest_id.0);
601 out[160..168].copy_from_slice(&self.origin_sequence.to_le_bytes());
602 out[168..176].copy_from_slice(&self.origin_incarnation.to_le_bytes());
603 out[176..184].copy_from_slice(&self.origin_epoch.to_le_bytes());
604 out[184..216].copy_from_slice(&self.origin_rollback_digest);
605 out[216..224].copy_from_slice(&self.migration_sequence.to_le_bytes());
606 out[224..288].copy_from_slice(&self.offline_signature);
607 out
608 }
609
610 pub fn decode(bytes: &[u8]) -> Result<Self, SecurityError> {
611 if bytes.len() != MIGRATION_MANIFEST_SIZE {
612 return Err(SecurityError::BufferTooShort);
613 }
614 if &bytes[0..8] != MIGRATION_MANIFEST_MAGIC {
615 return Err(SecurityError::InvalidMagic);
616 }
617 let format_version = u16::from_le_bytes([bytes[8], bytes[9]]);
618 if format_version != SECURITY_FORMAT_VERSION {
619 return Err(SecurityError::UnsupportedVersion);
620 }
621 let flags = u16::from_le_bytes([bytes[10], bytes[11]]);
622 if flags != 0 {
623 return Err(SecurityError::FormatError("nonzero migration flags"));
624 }
625 let reserved = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
626 if reserved != 0 {
627 return Err(SecurityError::NonzeroReserved);
628 }
629
630 let mut agent_root_id = [0u8; 32];
631 agent_root_id.copy_from_slice(&bytes[16..48]);
632 let mut genesis_store_uuid = [0u8; 16];
633 genesis_store_uuid.copy_from_slice(&bytes[48..64]);
634 let mut origin_store_uuid = [0u8; 16];
635 origin_store_uuid.copy_from_slice(&bytes[64..80]);
636 let mut target_store_uuid = [0u8; 16];
637 target_store_uuid.copy_from_slice(&bytes[80..96]);
638
639 let mut orig_sec = [0u8; 32];
640 orig_sec.copy_from_slice(&bytes[96..128]);
641 let mut orig_cont = [0u8; 32];
642 orig_cont.copy_from_slice(&bytes[128..160]);
643
644 let origin_sequence = u64::from_le_bytes([
645 bytes[160], bytes[161], bytes[162], bytes[163], bytes[164], bytes[165], bytes[166],
646 bytes[167],
647 ]);
648 let origin_incarnation = u64::from_le_bytes([
649 bytes[168], bytes[169], bytes[170], bytes[171], bytes[172], bytes[173], bytes[174],
650 bytes[175],
651 ]);
652 let origin_epoch = u64::from_le_bytes([
653 bytes[176], bytes[177], bytes[178], bytes[179], bytes[180], bytes[181], bytes[182],
654 bytes[183],
655 ]);
656
657 let mut origin_rollback_digest = [0u8; 32];
658 origin_rollback_digest.copy_from_slice(&bytes[184..216]);
659
660 let migration_sequence = u64::from_le_bytes([
661 bytes[216], bytes[217], bytes[218], bytes[219], bytes[220], bytes[221], bytes[222],
662 bytes[223],
663 ]);
664
665 let mut offline_signature = [0u8; 64];
666 offline_signature.copy_from_slice(&bytes[224..288]);
667
668 Ok(Self {
669 format_version,
670 flags,
671 reserved,
672 agent_root_id: ObjectId(agent_root_id),
673 genesis_store_uuid,
674 origin_store_uuid,
675 target_store_uuid,
676 origin_security_manifest_id: ObjectId(orig_sec),
677 origin_continuity_manifest_id: ObjectId(orig_cont),
678 origin_sequence,
679 origin_incarnation,
680 origin_epoch,
681 origin_rollback_digest,
682 migration_sequence,
683 offline_signature,
684 })
685 }
686}
687
688// ---------------------------------------------------------------------------
689// 5. AntiRollbackSource & Boot Protocol (ADR 0017 Section 2.6)
690// ---------------------------------------------------------------------------
691
692/// Off-disk hardware anti-rollback anchor.
693#[derive(Clone, Copy, Debug, PartialEq, Eq)]
694pub struct RollbackAnchor {
695 pub store_uuid: [u8; 16],
696 pub epoch: u64,
697 pub commit_record_id: ObjectId,
698 pub security_root_digest: [u8; 32],
699}
700
701#[derive(Clone, Copy, Debug, PartialEq, Eq)]
702pub enum AntiRollbackError {
703 DeviceError,
704 PermissionDenied,
705}
706
707/// Abstract hardware off-disk anti-rollback source (TPM NV index, RPMB, or secure flash).
708pub trait AntiRollbackSource {
709 fn read_anchor(
710 &self,
711 store_uuid: &[u8; 16],
712 ) -> Result<Option<RollbackAnchor>, AntiRollbackError>;
713 fn advance_anchor(&mut self, anchor: &RollbackAnchor) -> Result<(), AntiRollbackError>;
714}
715
716/// Evaluation decision produced by comparing disk security state against the hardware anchor.
717#[derive(Clone, Copy, Debug, PartialEq, Eq)]
718pub enum AntiRollbackDecision {
719 /// Valid normal resume: disk matches the current anchored security epoch.
720 ValidResume,
721 /// Prepared unanchored epoch: disk committed epoch E+1, but anchor has not advanced yet.
722 /// External effects remain frozen until the anchor advancement completes.
723 PreparedEpochAdvance {
724 disk_epoch: u64,
725 disk_digest: [u8; 32],
726 },
727 /// Replay detected: halt into Recovery Core (RecoveryRequired::RollbackDetected).
728 RollbackDetected(&'static str),
729 /// Inconsistent epoch jump: halt into Recovery Core (RecoveryRequired::InconsistentEpoch).
730 InconsistentEpoch(&'static str),
731}
732
733/// Validate disk security state against the hardware anti-rollback anchor per ADR 0017 Section 2.6.
734pub fn evaluate_anti_rollback(
735 disk_epoch: u64,
736 disk_digest: &[u8; 32],
737 anchor: Option<&RollbackAnchor>,
738) -> AntiRollbackDecision {
739 let Some(anchor) = anchor else {
740 // First boot / genesis initialization
741 return AntiRollbackDecision::PreparedEpochAdvance {
742 disk_epoch,
743 disk_digest: *disk_digest,
744 };
745 };
746
747 if disk_epoch == anchor.epoch && constant_time_eq(disk_digest, &anchor.security_root_digest) {
748 AntiRollbackDecision::ValidResume
749 } else if disk_epoch == anchor.epoch + 1 {
750 AntiRollbackDecision::PreparedEpochAdvance {
751 disk_epoch,
752 disk_digest: *disk_digest,
753 }
754 } else if disk_epoch < anchor.epoch {
755 AntiRollbackDecision::RollbackDetected("disk epoch behind anchor (rollback detected)")
756 } else if disk_epoch == anchor.epoch
757 && !constant_time_eq(disk_digest, &anchor.security_root_digest)
758 {
759 AntiRollbackDecision::RollbackDetected(
760 "digest mismatch at current epoch (rollback detected)",
761 )
762 } else {
763 AntiRollbackDecision::InconsistentEpoch("disk epoch jumped ahead of anchor (> anchor + 1)")
764 }
765}
766
767#[cfg(test)]
768mod tests {
769 use super::*;
770
771 #[test]
772 fn test_subkey_derivation_separation() {
773 let k_vol = [0x5au8; 32];
774 let subkeys = derive_subkeys(&k_vol);
775
776 assert_ne!(subkeys.k_cortex, subkeys.k_agent);
777 assert_ne!(subkeys.k_cortex, subkeys.k_artifact);
778 assert_ne!(subkeys.k_cortex, subkeys.k_root_auth);
779 assert_ne!(subkeys.k_agent, subkeys.k_root_auth);
780 assert_ne!(subkeys.k_cortex, k_vol);
781 }
782
783 #[test]
784 fn test_keyslot_manifest_roundtrip_and_unwrap() {
785 let k_vol = [0x77u8; 32];
786 let k_recovery_kek = [0x88u8; 32];
787 let store_uuid = [0x11u8; 16];
788
789 let mut slot0 = KeySlotDescriptor::EMPTY;
790 slot0.slot_type = KeySlotType::RecoveryRawSecret;
791 slot0.slot_id = 0;
792 slot0.key_epoch = 1;
793 slot0.wrap_k_vol(&k_recovery_kek, &k_vol, &[0x33u8; 12]);
794
795 let manifest = KeySlotManifest {
796 store_uuid,
797 manifest_sequence: 1,
798 previous_keyslot_manifest_id: ObjectId([0; 32]),
799 active_key_epoch: 1,
800 slot_count: 1,
801 slots: [
802 slot0,
803 KeySlotDescriptor::EMPTY,
804 KeySlotDescriptor::EMPTY,
805 KeySlotDescriptor::EMPTY,
806 ],
807 payload_arena: alloc::vec![0xaa, 0xbb, 0xcc],
808 };
809
810 let encoded = manifest.encode().unwrap();
811 let decoded = KeySlotManifest::decode(&encoded).unwrap();
812
813 assert_eq!(decoded.store_uuid, store_uuid);
814 assert_eq!(decoded.slot_count, 1);
815 assert_eq!(decoded.payload_arena, alloc::vec![0xaa, 0xbb, 0xcc]);
816
817 // Unwrapping with valid KEK succeeds and yields exact original K_vol
818 let unwrapped = decoded.slots[0].unwrap_k_vol(&k_recovery_kek).unwrap();
819 assert_eq!(unwrapped, k_vol);
820
821 // Unwrapping with wrong KEK fails authentication
822 let wrong_kek = [0x99u8; 32];
823 assert_eq!(
824 decoded.slots[0].unwrap_k_vol(&wrong_kek),
825 Err(SecurityError::AuthenticationFailed)
826 );
827 }
828
829 #[test]
830 fn test_security_manifest_roundtrip_and_mac() {
831 let k_root_auth = [0x44u8; 32];
832 let store_uuid = [0x22u8; 16];
833
834 let mut manifest = SecurityManifest {
835 format_version: 1,
836 flags: 0,
837 reserved: 0,
838 store_uuid,
839 generation: 10,
840 security_sequence: 1,
841 epoch: 5,
842 key_epoch: 1,
843 previous_security_manifest_id: ObjectId([0; 32]),
844 keyslot_manifest_id: ObjectId([1; 32]),
845 agent_root_id: ObjectId([2; 32]),
846 continuity_manifest_id: ObjectId([3; 32]),
847 migration_manifest_id: ObjectId([0; 32]),
848 root_mac: [0; 32],
849 };
850
851 manifest.sign(&k_root_auth);
852 assert!(manifest.verify(&k_root_auth));
853
854 let encoded = manifest.encode();
855 assert_eq!(encoded.len(), SECURITY_MANIFEST_SIZE);
856
857 let decoded = SecurityManifest::decode(&encoded).unwrap();
858 assert!(decoded.verify(&k_root_auth));
859
860 // Wrong key fails
861 let wrong_key = [0x55u8; 32];
862 assert!(!decoded.verify(&wrong_key));
863 }
864
865 #[test]
866 fn test_anti_rollback_decision_matrix() {
867 let store_uuid = [0x11u8; 16];
868 let digest_1 = [0xaa; 32];
869 let digest_2 = [0xbb; 32];
870
871 let anchor = RollbackAnchor {
872 store_uuid,
873 epoch: 10,
874 commit_record_id: ObjectId([1; 32]),
875 security_root_digest: digest_1,
876 };
877
878 // 1. Same epoch, matching digest -> ValidResume
879 assert_eq!(
880 evaluate_anti_rollback(10, &digest_1, Some(&anchor)),
881 AntiRollbackDecision::ValidResume
882 );
883
884 // 2. Next epoch (E + 1) -> PreparedEpochAdvance
885 assert_eq!(
886 evaluate_anti_rollback(11, &digest_2, Some(&anchor)),
887 AntiRollbackDecision::PreparedEpochAdvance {
888 disk_epoch: 11,
889 disk_digest: digest_2
890 }
891 );
892
893 // 3. Stale epoch (E - 1) -> RollbackDetected
894 assert!(matches!(
895 evaluate_anti_rollback(9, &digest_1, Some(&anchor)),
896 AntiRollbackDecision::RollbackDetected(_)
897 ));
898
899 // 4. Same epoch, altered digest -> RollbackDetected
900 assert!(matches!(
901 evaluate_anti_rollback(10, &digest_2, Some(&anchor)),
902 AntiRollbackDecision::RollbackDetected(_)
903 ));
904
905 // 5. Jumped epoch (E + 2) -> InconsistentEpoch
906 assert!(matches!(
907 evaluate_anti_rollback(12, &digest_2, Some(&anchor)),
908 AntiRollbackDecision::InconsistentEpoch(_)
909 ));
910 }
911}