From 343cf4299c2a41f7909ac2fef325eddec4eae10a Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:08:25 +0000 Subject: [PATCH] feat(sep): serve persistent system identity public keys --- Cargo.lock | 1 + crates/stela-boot/Cargo.lock | 103 +++++++++++ crates/stela-runtime/Cargo.toml | 2 + .../stela-runtime/src/platform/apple/sep.rs | 1 + .../src/platform/apple/sep/{image => }/der.rs | 2 +- .../src/platform/apple/sep/image.rs | 2 +- .../src/platform/apple/sep/keystore.rs | 147 +++++++++++++++- .../platform/apple/sep/keystore/system_key.rs | 163 ++++++++++++++++++ .../src/platform/apple/sep/os.rs | 33 +++- .../src/platform/apple/sep/state.rs | 11 +- .../src/platform/apple/sep/store.rs | 14 ++ 11 files changed, 474 insertions(+), 5 deletions(-) rename crates/stela-runtime/src/platform/apple/sep/{image => }/der.rs (98%) create mode 100644 crates/stela-runtime/src/platform/apple/sep/keystore/system_key.rs diff --git a/Cargo.lock b/Cargo.lock index 6d1620cbeb..999b5bf45c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1730,6 +1730,7 @@ dependencies = [ "libc", "lzfse_rust", "miniz_oxide", + "p256", "serde", "serde_json", "sha1", diff --git a/crates/stela-boot/Cargo.lock b/crates/stela-boot/Cargo.lock index 60d0c534a3..72421def07 100644 --- a/crates/stela-boot/Cargo.lock +++ b/crates/stela-boot/Cargo.lock @@ -26,6 +26,12 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "bit_field" version = "0.10.3" @@ -85,6 +91,12 @@ dependencies = [ "inout", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -100,7 +112,10 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ + "generic-array", + "rand_core", "subtle", + "zeroize", ] [[package]] @@ -144,6 +159,16 @@ dependencies = [ "thiserror", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -155,6 +180,33 @@ dependencies = [ "subtle", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "ff", + "generic-array", + "group", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -169,6 +221,18 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", ] [[package]] @@ -268,6 +332,25 @@ dependencies = [ "memchr", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "elliptic-curve", + "primeorder", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -306,6 +389,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rustc_apfloat" version = "0.2.3+llvm-462a31f5a5ab" @@ -316,6 +405,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -475,6 +577,7 @@ dependencies = [ "hmac", "httparse", "miniz_oxide", + "p256", "serde", "serde_json", "sha1", diff --git a/crates/stela-runtime/Cargo.toml b/crates/stela-runtime/Cargo.toml index 14db64e51c..f65a397225 100644 --- a/crates/stela-runtime/Cargo.toml +++ b/crates/stela-runtime/Cargo.toml @@ -23,6 +23,8 @@ sha2 = { version = "0.10", default-features = false } # SEP root derivations and secret lifetime; both work without std. hmac = { version = "0.12", default-features = false } zeroize = { version = "1.9", default-features = false, features = ["alloc"] } +# Stela-owned SEP system identity keys; constant-time no_std curve arithmetic. +p256 = { version = "0.13.2", default-features = false, features = ["arithmetic"] } # Public RSA verification for Image4 evidence; no private-key operations. crypto-bigint = { version = "0.5", default-features = false } # The AES engine model's cipher: constant-time, no_std, AES-NI when present. diff --git a/crates/stela-runtime/src/platform/apple/sep.rs b/crates/stela-runtime/src/platform/apple/sep.rs index 986bc30043..c962d1a393 100644 --- a/crates/stela-runtime/src/platform/apple/sep.rs +++ b/crates/stela-runtime/src/platform/apple/sep.rs @@ -16,6 +16,7 @@ //! `firmware`/`os`/`control` and docs/research/sep.md. pub mod boot_policy; pub mod control; +mod der; pub mod endpoint; pub mod firmware; pub mod image; diff --git a/crates/stela-runtime/src/platform/apple/sep/image/der.rs b/crates/stela-runtime/src/platform/apple/sep/der.rs similarity index 98% rename from crates/stela-runtime/src/platform/apple/sep/image/der.rs rename to crates/stela-runtime/src/platform/apple/sep/der.rs index bdc00b8347..05829c58fc 100644 --- a/crates/stela-runtime/src/platform/apple/sep/image/der.rs +++ b/crates/stela-runtime/src/platform/apple/sep/der.rs @@ -1,4 +1,4 @@ -//! Strict, bounded DER cursor for SEP Image4 signature evidence. +//! Strict, bounded DER cursor for SEP firmware and keystore protocols. //! X.690 definite, minimal lengths/tags; no BER normalization before hashing. #[derive(Clone, Copy, Debug)] diff --git a/crates/stela-runtime/src/platform/apple/sep/image.rs b/crates/stela-runtime/src/platform/apple/sep/image.rs index 4f84dfc837..23818dca77 100644 --- a/crates/stela-runtime/src/platform/apple/sep/image.rs +++ b/crates/stela-runtime/src/platform/apple/sep/image.rs @@ -4,7 +4,7 @@ //! IOVA in 4-KiB units without a length. DER supplies the container extent; //! the caller supplies its permitted maximum. This is source-integrity //! evidence only: measurement never authenticates Image4 or boots sepOS. -mod der; +use super::der; pub(crate) mod rsa; pub mod signature; diff --git a/crates/stela-runtime/src/platform/apple/sep/keystore.rs b/crates/stela-runtime/src/platform/apple/sep/keystore.rs index 3092539c8b..90b6bd349e 100644 --- a/crates/stela-runtime/src/platform/apple/sep/keystore.rs +++ b/crates/stela-runtime/src/platform/apple/sep/keystore.rs @@ -55,6 +55,7 @@ //! 0xff to -1, then maps it to IOReturn 0xe00002bc (0x2d3a324, table //! 0x725990). No sepOS-specific authorization error is invented. mod keybag; +mod system_key; use super::{ endpoint::Service, @@ -63,6 +64,7 @@ use super::{ }; use alloc::{vec, vec::Vec}; use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; /// Stela's catalog ID for the service, after the xART pair. pub const ID: u8 = 0x12; @@ -131,9 +133,17 @@ pub struct Environment { #[derive(Default)] pub struct KeyStore { environment: Option, + system_keys: Option, } impl KeyStore { + pub(super) fn with_system_keys(root: Zeroizing<[u8; 32]>) -> Self { + Self { + environment: None, + system_keys: Some(system_key::SystemKeys::new(root)), + } + } + pub fn environment(&self) -> Option { self.environment } @@ -153,13 +163,37 @@ impl KeyStore { )); } let command = frame.tag; - if !matches!(command, GET_CAPABILITIES | SET_ENVIRONMENT) && !keybag::recognizes(command) { + if !matches!( + command, + GET_CAPABILITIES | SET_ENVIRONMENT | system_key::PERFORM_OPERATION + ) && !keybag::recognizes(command) + { return Err(refuse("SEP keystore command is not implemented")); } let mut bytes = vec![0; (frame.data >> LENGTH_SHIFT) as usize]; payload.input(&mut bytes).map_err(refuse)?; let message = Message::parse(&bytes).map_err(refuse)?; let mut fields = message.fields(); + if command == system_key::PERFORM_OPERATION { + let operation = + system_key::public_query(message.variant(), &mut fields).map_err(refuse)?; + let keys = self + .system_keys + .as_mut() + .ok_or_else(|| refuse("SEP system identity requires provisioned machine roots"))?; + let public = keys.public(operation).map_err(refuse)?; + let mut reply_fields = (public.len() as u32).to_le_bytes().to_vec(); + reply_fields.extend_from_slice(public); + reply_fields.resize(reply_fields.len().next_multiple_of(4), 0); + let reply = message.reply(&reply_fields); + payload.output(&reply).map_err(refuse)?; + return Ok(Frame { + tag: command | REPLY, + parameter: 0, + data: (reply.len() as u32) << LENGTH_SHIFT, + ..frame + }); + } if keybag::recognizes(command) { keybag::validate(command, message.variant(), &mut fields).map_err(refuse)?; return Err(refuse(keybag::UNIMPLEMENTED)); @@ -384,6 +418,117 @@ pub(crate) mod tests { bytes } + // Authored encoding of the source-recovered public SIK dictionary: + // SET { SEQUENCE { "skg", 1 }, { "skt", 1 }, { "o", "oskgp" } }. + pub(crate) const SIK_QUERY: &[u8] = b"\x31\x20\x30\x08\x0c\x03skg\x02\x01\x01\x30\x08\x0c\x03skt\x02\x01\x01\x30\x0a\x0c\x01o\x0c\x05oskgp"; + + pub(crate) fn system_request(version: u32, query: &[u8]) -> Vec { + let mut request = message(version, 0, 1, &[]); + let body = Message::parse(&request).unwrap().body; + request.truncate(body); + request.extend_from_slice(&0u32.to_le_bytes()); // variant + request.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes()); + request.extend_from_slice(&u32::MAX.to_le_bytes()); + request.extend_from_slice(&2u32.to_le_bytes()); + request.extend_from_slice(&(query.len() as u32).to_le_bytes()); + request.extend_from_slice(query); + request.resize(request.len().next_multiple_of(4), 0); + let hash = digest(&request); + request[DIGEST_START..DIGEST_START + DIGEST_BYTES].copy_from_slice(&hash); + request + } + + #[test] + fn system_identity_query_returns_one_raw_public_point_in_both_ipc_versions() { + let mut expected = None; + for version in [1, 2] { + let mut keystore = KeyStore::with_system_keys(Zeroizing::new([1; 32])); + let request = system_request(version, SIK_QUERY); + let before = request.clone(); + let (reply, output) = ask( + &mut keystore, + frame(system_key::PERFORM_OPERATION, 19, request.len()), + request, + ); + let reply = reply.unwrap(); + assert_eq!(reply.tag, system_key::PERFORM_OPERATION | REPLY); + assert_eq!(reply.opcode, 19); + assert_eq!(reply.parameter, 0); + assert_eq!(reply.data as usize >> LENGTH_SHIFT, output.len()); + let parsed = Message::parse(&output).unwrap(); + assert_eq!(parsed.variant(), 0); + assert_eq!(output[VERSION..parsed.body], before[VERSION..parsed.body]); + let mut fields = parsed.fields(); + let public = fields.blob().unwrap(); + p256::PublicKey::from_sec1_bytes(public).unwrap(); + assert_eq!(public.len(), 65); + if let Some(expected) = &expected { + assert_eq!(public, expected); + } else { + expected = Some(public.to_vec()); + } + fields.end().unwrap(); + assert!(keystore.environment().is_none()); + } + } + + #[test] + fn unsupported_or_malformed_system_queries_never_publish_success() { + let mut dictionaries = vec![vec![], SIK_QUERY[..SIK_QUERY.len() - 1].to_vec()]; + for index in [11, 21, 33] { + // generation, type and operation + let mut bad = SIK_QUERY.to_vec(); + bad[index] ^= 1; + dictionaries.push(bad); + } + let mut duplicate = SIK_QUERY.to_vec(); + duplicate[16..19].copy_from_slice(b"skg"); + dictionaries.push(duplicate); + let mut unsorted = SIK_QUERY.to_vec(); + unsorted[2..12].copy_from_slice(&SIK_QUERY[12..22]); + unsorted[12..22].copy_from_slice(&SIK_QUERY[2..12]); + dictionaries.push(unsorted); + let mut trailing = SIK_QUERY.to_vec(); + trailing.push(0); + dictionaries.push(trailing); + let mut nonminimal = SIK_QUERY.to_vec(); + nonminimal.insert(2, 0x20); + nonminimal[1] = 0x81; + dictionaries.push(nonminimal); + let mut requests: Vec<_> = dictionaries.iter().map(|q| system_request(2, q)).collect(); + // Even a valid digest cannot authorize different framing operands. + for index in [84, 96, 100] { + // variant, handle and operation + let mut bad = system_request(2, SIK_QUERY); + bad[index] ^= 1; + let hash = digest(&bad); + bad[DIGEST_START..DIGEST_START + DIGEST_BYTES].copy_from_slice(&hash); + requests.push(bad); + } + for request in requests { + let mut keystore = KeyStore::with_system_keys(Zeroizing::new([1; 32])); + let (result, output) = ask( + &mut keystore, + frame(system_key::PERFORM_OPERATION, 20, request.len()), + request, + ); + assert_eq!(result.unwrap_err().answer.unwrap().frame.parameter, FAILURE); + assert!(output.is_empty()); + assert!(keystore.environment().is_none()); + } + let request = system_request(2, SIK_QUERY); + let (result, output) = ask( + &mut KeyStore::default(), + frame(system_key::PERFORM_OPERATION, 21, request.len()), + request, + ); + assert_eq!( + result.unwrap_err().reason, + "SEP system identity requires provisioned machine roots" + ); + assert!(output.is_empty()); + } + fn ask( keystore: &mut KeyStore, frame: Frame, diff --git a/crates/stela-runtime/src/platform/apple/sep/keystore/system_key.rs b/crates/stela-runtime/src/platform/apple/sep/keystore/system_key.rs new file mode 100644 index 0000000000..f8da7a9b37 --- /dev/null +++ b/crates/stela-runtime/src/platform/apple/sep/keystore/system_key.rs @@ -0,0 +1,163 @@ +//! System-key public queries through AKS perform_operation (command 0x22). +//! +//! 26A434 kernel file 0x2d41f50: variant 0, session, handle, operation, +//! blob; reply variant 0 and one raw result blob. The public system-key +//! wrapper uses handle -1, operation 2 (constant at 0x725890). Its DER +//! dictionary is a SET of SEQUENCE { UTF8 key, value } pairs, sorted by +//! complete encoded pair. `o=oskgp`, `skt=1`, `skg=1` requests the SIK. +//! +//! P-256 is Stela's system-identity policy, not a recovered Apple hardware +//! KDF or an Apple-certified identity. The genuine private scalar is derived +//! from provisioned machine roots, retained only here and zeroized on drop. +//! No attestation, key rotation, signing or other key types are advertised. +use super::{ + super::der::{self, Cursor}, + Fields, +}; +use hmac::{Hmac, Mac}; +use p256::{SecretKey, elliptic_curve::sec1::ToEncodedPoint}; +use sha2::Sha256; +use zeroize::Zeroizing; + +pub(super) const PERFORM_OPERATION: u8 = 0x22; +const PUBLIC_HANDLE: u32 = u32::MAX; +const PUBLIC_OPERATION: u32 = 2; +const IDENTITY_TYPE: u32 = 1; +const IDENTITY_GENERATION: u32 = 1; +const SCALAR_DOMAIN: &[u8] = b"Stela SEP system identity P-256 v1\0"; +const MAX_SCALAR_ATTEMPTS: u32 = 256; +const PUBLIC_BYTES: usize = 65; + +pub(super) enum PublicQuery { + Identity, +} + +pub(super) struct SystemKeys { + root: Zeroizing<[u8; 32]>, + identity: Option<(SecretKey, [u8; PUBLIC_BYTES])>, +} + +impl SystemKeys { + pub(super) fn new(root: Zeroizing<[u8; 32]>) -> Self { + Self { + root, + identity: None, + } + } + + pub(super) fn public(&mut self, query: PublicQuery) -> Result<&[u8], &'static str> { + match query { + PublicQuery::Identity => { + if self.identity.is_none() { + let secret = identity_secret(&self.root)?; + let point = secret.public_key().to_encoded_point(false); + let mut public = [0; PUBLIC_BYTES]; + public.copy_from_slice(point.as_bytes()); + self.identity = Some((secret, public)); + } + Ok(&self.identity.as_ref().unwrap().1) + } + } + } +} + +fn identity_secret(root: &[u8; 32]) -> Result { + // Rejection sampling preserves the scalar distribution, unlike reducing + // a 256-bit digest modulo the curve order. The counter changes only on + // an out-of-range candidate, so reopen reconstructs the identical key. + for counter in 0..MAX_SCALAR_ATTEMPTS { + let mut mac = Hmac::::new_from_slice(root).expect("HMAC accepts 256-bit roots"); + mac.update(SCALAR_DOMAIN); + mac.update(&IDENTITY_TYPE.to_be_bytes()); + mac.update(&IDENTITY_GENERATION.to_be_bytes()); + mac.update(&counter.to_be_bytes()); + let candidate = Zeroizing::new(<[u8; 32]>::from(mac.finalize().into_bytes())); + if let Ok(secret) = SecretKey::from_slice(candidate.as_ref()) { + return Ok(secret); + } + } + Err("SEP system identity scalar derivation exhausted") +} + +pub(super) fn public_query( + variant: u32, + fields: &mut Fields<'_>, +) -> Result { + if variant != 0 { + return Err("SEP perform-operation variant is not implemented"); + } + // This read-only public query grants no session, bag or credential state. + let _session = fields.lword()?; + if fields.word()? != PUBLIC_HANDLE || fields.word()? != PUBLIC_OPERATION { + return Err("SEP perform-operation handle or operation is not implemented"); + } + let bytes = fields.blob()?; + fields.end()?; + let mut outer = Cursor(bytes); + let set = outer.take(17)?; + outer.end()?; + let mut pairs = Cursor(set.value); + let mut previous: Option<&[u8]> = None; + let (mut operation, mut key_type, mut generation) = (false, false, false); + while !pairs.0.is_empty() { + let pair = pairs.take(16)?; + if previous.is_some_and(|p| p >= pair.encoded) { + return Err("SEP system-key dictionary is duplicated or not DER sorted"); + } + previous = Some(pair.encoded); + let mut entry = Cursor(pair.value); + match entry.take(12)?.value { + b"o" => { + if operation || entry.take(12)?.value != b"oskgp" { + return Err("SEP system-key operation is not implemented"); + } + operation = true; + } + b"skt" => { + if key_type || der::unsigned(entry.take(2)?.value)? != [IDENTITY_TYPE as u8] { + return Err("SEP system-key type is not implemented"); + } + key_type = true; + } + b"skg" => { + if generation || der::unsigned(entry.take(2)?.value)? != [IDENTITY_GENERATION as u8] + { + return Err("SEP system-key generation is not implemented"); + } + generation = true; + } + _ => return Err("SEP system-key parameter is not implemented"), + } + entry.end()?; + } + if !(operation && key_type && generation) { + return Err("SEP system-key dictionary is incomplete"); + } + Ok(PublicQuery::Identity) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identity_is_a_real_curve_key_and_reopens_without_new_entropy() { + let root = Zeroizing::new([1; 32]); + let mut first = SystemKeys::new(root.clone()); + let public = first.public(PublicQuery::Identity).unwrap().to_vec(); + p256::PublicKey::from_sec1_bytes(&public).unwrap(); + assert_eq!(public.len(), PUBLIC_BYTES); + assert_eq!(public[0], 4); + // Independent Python HMAC + OpenSSL EC public-key derivation for + // this test-only seed and the exact domain/type/generation/counter. + assert_eq!( + hex::encode(&public), + "04c5f1cca66ff986742be7e6ccf4996fde1a031bf7697cf7fe104b23a82f98c5c3d908693dbc7b4df331a1940e69526c8417327beab5ca48fd505e2337bcdff437" + ); + assert_eq!(public, first.public(PublicQuery::Identity).unwrap()); + let mut reopened = SystemKeys::new(root); + assert_eq!(public, reopened.public(PublicQuery::Identity).unwrap()); + let mut other = SystemKeys::new(Zeroizing::new([2; 32])); + assert_ne!(public, other.public(PublicQuery::Identity).unwrap()); + } +} diff --git a/crates/stela-runtime/src/platform/apple/sep/os.rs b/crates/stela-runtime/src/platform/apple/sep/os.rs index 9934590232..a2718c7430 100644 --- a/crates/stela-runtime/src/platform/apple/sep/os.rs +++ b/crates/stela-runtime/src/platform/apple/sep/os.rs @@ -143,9 +143,10 @@ impl SepOs { self.observe = Some(Journal::default()); } self.catalog = Catalog::new(services)?; + let keystore = KeyStore::with_system_keys(store.system_key_root()?); self.services = Some(Services { xart: Xart::new(store), - keystore: KeyStore::default(), + keystore, boot_policy: BootPolicy::new(None), }); Ok(self) @@ -1007,6 +1008,36 @@ mod tests { assert!(os.keystore().unwrap().environment().is_none()); } + #[test] + fn system_identity_uses_the_machine_store_and_registered_dma_buffers() { + let mut os = SepOs::new(None).with_services(store(), false).unwrap(); + map_shared(&mut os, shm(0x1234_4000, 0x20)).unwrap(); + register(&mut os, keystore::ID, 0x8000, 0x8000); + let request = keystore::tests::system_request(2, keystore::tests::SIK_QUERY); + let frame = Frame { + service: keystore::ID, + tag: 0x22, + opcode: 17, + parameter: 0, + data: (request.len() as u32) << 16, + }; + let mut ram = crate::platform::dma::tests::Ram::new(0x10_0000, 0x10000); + ram.bytes[..request.len()].copy_from_slice(&request); + assert!(reply(&mut os, frame).unwrap().is_empty()); + assert_eq!( + dma(&mut os, &mut ram).unwrap(), + [Frame { + tag: 0x22 | keystore::REPLY, + data: 160 << 16, + ..frame + }] + ); + // v2 header + variant, then blob length, SEC1 point and pad4. + assert_eq!(ram.bytes[0x8000 + 88..0x8000 + 92], 65u32.to_le_bytes()); + p256::PublicKey::from_sec1_bytes(&ram.bytes[0x8000 + 92..0x8000 + 157]).unwrap(); + assert_eq!(&ram.bytes[0x8000 + 157..0x8000 + 160], &[0; 3]); + } + #[test] fn recovery_policy_nonce_commands_use_the_registered_buffers_and_shared_store() { let mut os = SepOs::new(None).with_services(store(), false).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/sep/state.rs b/crates/stela-runtime/src/platform/apple/sep/state.rs index b76e190f09..2177177b4b 100644 --- a/crates/stela-runtime/src/platform/apple/sep/state.rs +++ b/crates/stela-runtime/src/platform/apple/sep/state.rs @@ -175,11 +175,20 @@ mod tests { let disk = disk(); let (mut store, fresh) = open(at(&disk), ECID, &mut entropy).unwrap(); assert!(fresh); + let identity_root = store.system_key_root().unwrap(); let nonce = store.generate(0, &mut entropy).unwrap(); drop(store); + let (mut store, fresh) = open(at(&disk), ECID, &mut entropy).unwrap(); + assert!(!fresh); + assert_eq!(store.read(0).unwrap(), nonce); + assert_eq!(*store.system_key_root().unwrap(), *identity_root); + store.erase().unwrap(); + drop(store); let (store, fresh) = open(at(&disk), ECID, &mut entropy).unwrap(); assert!(!fresh); - assert_eq!(store.read(0).unwrap(), nonce); + assert_eq!(*store.system_key_root().unwrap(), *identity_root); + // Moving roots to a different ECID cannot reopen authenticated state. + assert!(open(at(&disk), ECID + 1, &mut entropy).is_err()); // The NOR image before the area is untouched. let mut nor = [0u8; 512]; disk.window(2047, 1).unwrap().read(0, &mut nor).unwrap(); diff --git a/crates/stela-runtime/src/platform/apple/sep/store.rs b/crates/stela-runtime/src/platform/apple/sep/store.rs index 10b56ed0a0..51ca0c56b5 100644 --- a/crates/stela-runtime/src/platform/apple/sep/store.rs +++ b/crates/stela-runtime/src/platform/apple/sep/store.rs @@ -18,6 +18,7 @@ use zeroize::Zeroizing; const MAGIC: &[u8; 8] = b"STSEPN02"; const PURPOSE: &[u8] = b"sepos/nonce-store/v1"; +const SYSTEM_KEY_PURPOSE: &[u8] = b"keystore/system-key-root/v1"; const MAC_BYTES: usize = 32; const HEADER_BYTES: usize = 18; pub const NONCE_BYTES: usize = 20; @@ -104,6 +105,7 @@ struct State { pub struct Nonces { backend: B, key: Zeroizing<[u8; MAC_BYTES]>, + system_key_root: Zeroizing<[u8; MAC_BYTES]>, state: Option, } @@ -115,6 +117,7 @@ impl Nonces { return Err("SEP nonce store is already provisioned"); } let key = roots.uid(PURPOSE)?; + let system_key_root = roots.uid(SYSTEM_KEY_PURPOSE)?; let state = State { generation: 1, slots: BTreeMap::new(), @@ -133,12 +136,14 @@ impl Nonces { Ok(Self { backend, key, + system_key_root, state: Some(state), }) } pub fn open(roots: &Roots, mut backend: B) -> Result { let key = roots.uid(PURPOSE)?; + let system_key_root = roots.uid(SYSTEM_KEY_PURPOSE)?; let head = backend .load()? .ok_or("SEP nonce store is missing; explicit provisioning required")?; @@ -146,6 +151,7 @@ impl Nonces { Ok(Self { backend, key, + system_key_root, state: Some(state), }) } @@ -156,6 +162,14 @@ impl Nonces { .ok_or("SEP nonce store commit outcome is uncertain; reopen required") } + /// Immutable machine identity is separate from erasable nonce state. This + /// seed is reconstructed from the same persisted roots on every open; it + /// is never serialized into the nonce banks or exposed to the guest. + pub(super) fn system_key_root(&self) -> Result, &'static str> { + self.state()?; + Ok(self.system_key_root.clone()) + } + /// The currently authenticated durable revision. A pending policy update /// uses it to refuse a commit after another service changed or erased the /// store. Poisoned state cannot authorize a new transaction.