diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index 9a3047d0d1157..ad4e2c48a3dc4 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -2247,7 +2247,8 @@ impl SepData { } let user = UserPtr::from_addr(arg); match read_request(cmd, arg)? { - KeyRequest::Info => write_user(user, &info_for(self.profile.key_store == crate::profile::KeyStore::Variant5)), + // Password keys live in per-user bags (see `userbag`). + KeyRequest::Info => write_user(user, &info_for(self.profile.per_user_keybags)), KeyRequest::Create(mut req, policy) => { may_create_machine_key(crate::shim::capable_admin(), crate::shim::current_euid())?; let (acl, flags) = match policy { diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index c87d46f44eb9f..5d2261f0ff7df 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -185,6 +185,16 @@ pub(crate) struct PlatformProfile { pub(crate) key_store: KeyStore, /// Platforms with reboot-tested owner export and user-before-master saves. pub(crate) persistent_enrol: bool, + /// Whether creating a NEW per-user key bag (`userbag_ioctl`, linux#921) is + /// supported on this enclave. This is NOT the same as the create-encoding + /// [`KeyStore`] variant: the warm, macOS-shared enclaves (T8112/M2, + /// T8122/M3) encode identity bags with the variant-5 form yet never reply + /// to a user-bag `DESIGNATE_KEYBAG`, which would condemn the SKS endpoint + /// for the boot. Set true only where user-bag create/designate is proven on + /// hardware (T8140/Neo and the J616s/M4-Pro enclave family); false + /// elsewhere so the ioctl refuses cleanly with `EOPNOTSUPP`. Touch ID and + /// the identity bag are unaffected (they do not use `userbag_ioctl`). + pub(crate) per_user_keybags: bool, /// The `xart_guard` level when the parameter is left at its default (see /// [`crate::xart_guard`]). pub(crate) xart_guard: u8, @@ -222,6 +232,9 @@ pub(crate) const T8103: PlatformProfile = PlatformProfile { cpx_encryption_mode: 2, }, persistent_enrol: true, + // User-bag create, designate, import/export, unlock, lock and password + // change on the 13.5 key store, proven on J293 hardware (cold-boot SEP). + per_user_keybags: true, nonce_session: false, // Off: Touch ID setup on a cold-boot SEP rewrites a session record that // predates Linux, so the guard would only block it. @@ -263,6 +276,7 @@ pub(crate) const T6000: PlatformProfile = PlatformProfile { cpx_encryption_mode: 2, }, persistent_enrol: true, + per_user_keybags: false, nonce_session: false, // As T8103. On J316s, creating the identity keybag also rewrites a // session record that predates Linux. @@ -297,6 +311,8 @@ pub(crate) const T6020: PlatformProfile = PlatformProfile { }, key_store: KeyStore::Variant5, persistent_enrol: true, + // M2 Pro's warm macOS-shared enclave: user-bag create not proven (as M2). + per_user_keybags: false, nonce_session: false, // A warm-attach enclave shared with macOS, as on T8112. xart_guard: 1, @@ -326,6 +342,9 @@ pub(crate) const T6020_SEPOS13: PlatformProfile = PlatformProfile { pub(crate) const T8140: PlatformProfile = PlatformProfile { key_store: KeyStore::Variant5, persistent_enrol: true, + // User-bag create/designate proven on J700 hardware (variant-5 capture); + // the J616s/M4-Pro family (T6040 and its inheritors) shares this. + per_user_keybags: true, name: "T8140/J700", shmem_capacity: 0x4_0000, shmem_first_item: b"CINP", @@ -398,6 +417,9 @@ pub(crate) const T8112: PlatformProfile = PlatformProfile { }, key_store: KeyStore::Variant5, persistent_enrol: true, + // M2's warm macOS-shared enclave encodes the identity bag variant-5 but + // never replies to a user-bag DESIGNATE_KEYBAG (wedges SKS): refuse cleanly. + per_user_keybags: false, nonce_session: false, // Guarded from its first Linux boot (2026-10-16): no record refused. xart_guard: 1, diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index f0fde4827754a..088c2fc648333 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -13,6 +13,23 @@ use kernel::sync::atomic::Relaxed; pub(crate) const REFKEY_ENVELOPE_VERSION: u32 = 2; +fn refkey_target(key_store: profile::KeyStore, keybag: i32) -> Result<(i32, u32)> { + match key_store { + // Explicit user designations retain their own bag on the 13.5 protocol. + profile::KeyStore::Sepos13 { .. } if keybag <= -crate::sks::SKS_DESIGNATE_USER_MIN => { + Ok((keybag, 3)) + } + profile::KeyStore::Sepos13 { .. } => { + // Identity calls use the designated session. A loaded source + // handle and class F with -1 did not persist correctly on J313. + let user = crate::sks::DesignateUser::new(crate::SBIO_PROBE_USER_ID) + .ok_or(EINVAL)?; + Ok((user.special_handle().value(), 3)) + } + profile::KeyStore::Variant5 => Ok((keybag, REFKEY_ENVELOPE_VERSION)), + } +} + impl SepData { /// Keep only decoded bytes across switch-root, never an open initrd file. fn with_identity_keybag( @@ -37,17 +54,7 @@ impl SepData { } fn sks_req_refkey(&self, keybag: i32, der_set: &[u8]) -> Result { - let (keybag, envelope) = match self.profile.key_store { - // The 13.5 operation envelope is 3. Use the designated identity - // session rather than the source handle; class F with -1 expired - // at the next boot on J313. - profile::KeyStore::Sepos13 { .. } => { - let user = crate::sks::DesignateUser::new(crate::SBIO_PROBE_USER_ID) - .ok_or(EINVAL)?; - (user.special_handle().value(), 3) - } - profile::KeyStore::Variant5 => (keybag, REFKEY_ENVELOPE_VERSION), - }; + let (keybag, envelope) = refkey_target(self.profile.key_store, keybag)?; let mut body = image::Body::new(); body.put_u32(0)?; body.put_u64(crate::sks::SKS_CLIENT_ID)?; @@ -530,18 +537,24 @@ impl SepData { } /// Test only (`key_selftest`): a ref-key under the designated user bag - /// `user` (outer handle `-uid`), which the caller has unlocked. Variant-5 - /// key store only. + /// `user` (outer handle `-uid`), which the caller has unlocked. The key + /// type follows the key store, as for identity-bag keys: the 13.5 store + /// makes EC type 4 under a designated user bag as it does under the + /// identity bag. pub(crate) fn user_key_create_in_bag( &self, user: crate::sks::DesignateUser, acl: Option<&[u8]>, ) -> Result> { - if self.profile.key_store != profile::KeyStore::Variant5 { + if !self.profile.per_user_keybags { return Err(EOPNOTSUPP); } + let key_type = match self.profile.key_store { + profile::KeyStore::Sepos13 { .. } => 4, + profile::KeyStore::Variant5 => 5, + }; crate::xart_guard::close_policy_window(); - self.sks_create_refkey_at(user.special_handle().value(), 9, 5, acl).ok_or(EIO) + self.sks_create_refkey_at(user.special_handle().value(), 9, key_type, acl).ok_or(EIO) } /// Unseal (enclave `ock` + kernel decrypt, as `user_key_unseal`) with a @@ -601,7 +614,7 @@ impl SepData { /// caller has unlocked the bag with the user's password. Variant-5 key /// store only. pub(crate) fn fde_key_create(&self, user: crate::sks::DesignateUser) -> Result> { - if self.profile.key_store != profile::KeyStore::Variant5 { + if !self.profile.per_user_keybags { return Err(EOPNOTSUPP); } crate::xart_guard::close_policy_window(); @@ -651,7 +664,7 @@ impl SepData { record: &[u8], sealed: &[u8], ) -> Result> { - if self.profile.key_store != profile::KeyStore::Variant5 { + if !self.profile.per_user_keybags { return Err(EOPNOTSUPP); } Self::refkey_pub(record).ok_or(EINVAL)?; @@ -805,3 +818,27 @@ impl SepData { } } } + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[::kernel::macros::kunit_tests(apple_sep_refkey_target)] +mod target_tests { + use super::*; + + #[test] + fn user_designations_keep_their_bag_on_each_protocol() -> Result<()> { + let old = profile::KeyStore::Sepos13 { cpx_encryption_mode: 2 }; + let identity = crate::sks::DesignateUser::new(crate::SBIO_PROBE_USER_ID) + .ok_or(EINVAL)?.special_handle().value(); + for handle in [0, 7, -1, -(crate::sks::SKS_DESIGNATE_USER_MIN - 1)] { + assert_eq!(refkey_target(old, handle)?, (identity, 3)); + } + for handle in [-crate::sks::SKS_DESIGNATE_USER_MIN, -0x0100_03e8] { + assert_eq!(refkey_target(old, handle)?, (handle, 3)); + } + for handle in [0, 7, -1, -0x0100_03e8] { + assert_eq!(refkey_target(profile::KeyStore::Variant5, handle)?, + (handle, REFKEY_ENVELOPE_VERSION)); + } + Ok(()) + } +} diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 02fcc78b25564..e42378fb5a6f5 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -738,6 +738,11 @@ struct SepData { #[pin] cold_match_contexts: Mutex>, + // Per-user bags the 13.5 key store keeps loaded between import and + // logout (see `userbag::LoadedBags`). + #[pin] + user_bags: Mutex, + // The sensor stayed powered and registered after the last verify, so the // next verify captures without a new bring-up, as macOS does. Cleared by // anything that powers the sensor off or resets it. @@ -1215,6 +1220,7 @@ impl SepData { match_context <- new_mutex!(None), match_context_generation: Atomic::new(0), cold_match_contexts <- new_mutex!(KVec::new()), + user_bags <- new_mutex!(userbag::LoadedBags::new()), sensor_kept: Atomic::new(false), sensor_reset_in_capture: Atomic::new(false), bg_ops_ready: Atomic::new(false), diff --git a/drivers/soc/apple/sks.rs b/drivers/soc/apple/sks.rs index 547780e3483dc..c9e0be1819d19 100644 --- a/drivers/soc/apple/sks.rs +++ b/drivers/soc/apple/sks.rs @@ -407,10 +407,7 @@ impl SepData { /// designate uses struct version 0; the other profile uses its own /// variant. fn sks_designate_variant(&self) -> u32 { - match self.profile.key_store { - profile::KeyStore::Sepos13 { .. } => crate::sks::SKS_DESIGNATE_VERSION_13, - profile::KeyStore::Variant5 => crate::sks::SKS_DESIGNATE_VARIANT, - } + designate_variant(self.profile.key_store) } /// `0x0d` designate, which makes the system key bag. On 13.5 the body is: @@ -1468,6 +1465,16 @@ pub(crate) const SKS_DESIGNATE_VARIANT: u32 = 1; static_assert!(SKS_DESIGNATE_VARIANT == 1); pub(crate) const SKS_DESIGNATE_VERSION_13: u32 = 0; +/// The designate request's leading variant on `key_store`: `0` on the 13.5 +/// key store, which ends the body after the empty blob, and `1` on variant 5, +/// which adds the flags word. +pub(crate) fn designate_variant(key_store: profile::KeyStore) -> u32 { + match key_store { + profile::KeyStore::Sepos13 { .. } => SKS_DESIGNATE_VERSION_13, + profile::KeyStore::Variant5 => SKS_DESIGNATE_VARIANT, + } +} + pub(crate) const SKS_DESIGNATE_USER_MIN: i32 = 10; static_assert!(SKS_DESIGNATE_USER_MIN > 0); diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index 5b6bdeff833fb..99054c5e8caa3 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -30,7 +30,6 @@ const CLIENT: u64 = crate::sks::SKS_CLIENT_ID; const CREATE_VARIANT: u32 = 4; const CREATE_BAG_TYPE: u32 = 0; const CREATE_ARG: i32 = -1; -const DESIGNATE_VARIANT: u32 = 1; const CHANGE_VARIANT: u32 = 3; const LOCK_STATE_VARIANT: u32 = 1; const DEVICE_STATE_VARIANT: u32 = 0; @@ -200,28 +199,110 @@ fn decode_create_reply(body: &[u8]) -> Option { Some(crate::sks::KeyBagHandle::from_create_reply(handle)) } -fn encode_designate(source_handle: i32, user_handle: i32) -> Result { +// The 13.5 key store (M1/M2 generation, `KeyStore::Sepos13`) takes older +// forms of create and of the loaded-bag lock-state change. Both are the +// hardware-tested J293 encodings: the generic DeviceBag constructor and the +// version-0 CHANGE_LOCK_STATE with no flags trailer. The device-state +// transition and designation are shared with variant 5 (see +// `encode_transition`, `crate::sks::designate_variant`). +const CREATE_VARIANT_13: u32 = 1; +const LOCK_STATE_VARIANT_13: u32 = 0; + +fn encode_create_13(secret: &[u8]) -> Result { + let mut body = crate::image::Body::new(); + body.put_u32(CREATE_VARIANT_13)?; + body.put_u64(CLIENT)?; + body.put_u32(0)?; + body.put_u32(0)?; + body.put_blob(secret)?; + body.put_blob(&[])?; + Ok(body) +} + +fn decode_create_reply_13(body: &[u8]) -> Option { + let mut c = Cursor::new(body); + if c.u32()? != CREATE_VARIANT_13 { + return None; + } + let handle = c.i32()?; + if handle < 0 || !c.done() { + return None; + } + Some(crate::sks::KeyBagHandle::from_create_reply(handle)) +} + +/// Changes a loaded bag's lock state by its handle: unlocked (0) with the +/// secret, or locked (1) with none. On the 13.5 store the unlock precedes the +/// designated-session transition; neither alone lets a key under the bag +/// run, and the session transition alone does not lock it either. +fn encode_loaded_lock_state_13(bag: i32, state: TransitionState, secret: &[u8]) -> Result { + if bag < 0 || (state == TransitionState::Unlocked) == secret.is_empty() { + return Err(EINVAL); + } + let mut body = crate::image::Body::new(); + body.put_u32(LOCK_STATE_VARIANT_13)?; + body.put_u64(CLIENT)?; + body.put_i32(bag)?; + body.put_i32(state.wire() as i32)?; + body.put_blob(secret)?; + Ok(body) +} + +/// Bags the 13.5 store holds loaded for designated users. Variant 5 keeps a +/// designation after its temporary handle is unloaded; on the 13.5 store the +/// loaded-bag unlock needs the handle, so a user's bag stays loaded from +/// import or create until logout. Keyed by the designation's special handle. +pub(crate) struct LoadedBags(KVec<(i32, crate::sks::KeyBagHandle)>); + +impl LoadedBags { + pub(crate) const fn new() -> Self { + LoadedBags(KVec::new()) + } + + fn get(&self, user: i32) -> Option { + self.0.iter().find(|(u, _)| *u == user).map(|(_, h)| *h) + } + + fn insert(&mut self, user: i32, handle: crate::sks::KeyBagHandle) -> Result<()> { + if self.get(user).is_some() { + return Err(EBUSY); + } + self.0.push((user, handle), GFP_KERNEL)?; + Ok(()) + } + + fn remove(&mut self, user: i32) -> Option { + let at = self.0.iter().position(|(u, _)| *u == user)?; + Some(self.0.remove(at).ok()?.1) + } +} + +fn encode_designate(key_store: crate::profile::KeyStore, source_handle: i32, user_handle: i32) -> Result { if source_handle < 0 || user_handle >= 0 { return Err(EINVAL); } let mut body = crate::image::Body::new(); - body.put_u32(DESIGNATE_VARIANT)?; + body.put_u32(crate::sks::designate_variant(key_store))?; body.put_u64(CLIENT)?; body.put_i32(source_handle)?; body.put_i32(user_handle)?; body.put_blob(&[])?; - body.put_u64(0)?; + // The 13.5 structure ends after the empty blob, as in sks_req_designate. + if key_store == crate::profile::KeyStore::Variant5 { + body.put_u64(0)?; + } Ok(body) } -fn decode_designate(body: &[u8]) -> Option { +fn decode_designate(key_store: crate::profile::KeyStore, body: &[u8]) -> Option { let mut c = Cursor::new(body); - if c.u32()? != DESIGNATE_VARIANT || c.u64()? != CLIENT { + if c.u32()? != crate::sks::designate_variant(key_store) || c.u64()? != CLIENT { return None; } let source_handle = c.i32()?; let user_handle = c.i32()?; - if source_handle < 0 || user_handle >= 0 || !c.blob()?.is_empty() || c.u64()? != 0 || !c.done() + if source_handle < 0 || user_handle >= 0 || !c.blob()?.is_empty() + || (key_store == crate::profile::KeyStore::Variant5 && c.u64()? != 0) || !c.done() { return None; } @@ -231,8 +312,8 @@ fn decode_designate(body: &[u8]) -> Option { }) } -fn decode_designate_reply(body: &[u8]) -> bool { - body == DESIGNATE_VARIANT.to_le_bytes() +fn decode_designate_reply(key_store: crate::profile::KeyStore, body: &[u8]) -> bool { + body == crate::sks::designate_variant(key_store).to_le_bytes() } fn encode_transition( @@ -353,6 +434,37 @@ fn decode_change_secret(body: &[u8]) -> Option> { }) } +/// The 13.5 store's change-secret request (opcode 7): version 1, then the +/// variant-5 fields without its last word, as macOS 13 sends it: client, +/// handle, the old and new secrets, two further blobs (empty, as in the +/// variant-5 capture), a u8 flag widened to a word (0xff, as captured) and +/// the generation option (0). +const CHANGE_VARIANT_13: u32 = 1; + +fn encode_change_secret_13(user_handle: i32, old: &[u8], new: &[u8]) -> Result { + if user_handle >= 0 || old.is_empty() || new.is_empty() { + return Err(EINVAL); + } + let mut body = crate::image::Body::new(); + body.put_u32(CHANGE_VARIANT_13)?; + body.put_u64(CLIENT)?; + body.put_i32(user_handle)?; + body.put_blob(old)?; + body.put_blob(new)?; + body.put_blob(&[])?; + body.put_blob(&[])?; + body.put_u32(CHANGE_TRAILER)?; + body.put_u32(0)?; + Ok(body) +} + +/// The 13.5 reply: version 1, then zero words (the generation out-value). +fn decode_change_secret_reply_13(body: &[u8]) -> bool { + body.len() >= 4 + && body[..4] == CHANGE_VARIANT_13.to_le_bytes() + && body[4..].iter().all(|b| *b == 0) +} + fn decode_change_secret_reply(body: &[u8]) -> bool { body == [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } @@ -1090,21 +1202,132 @@ impl crate::SepData { .ok_or(EACCES) } - /// Opens a user's bag through the captured device-state transition. + /// Whether `user`'s designation slot already names the loaded `bag`. + fn userbag_designation_names(&self, user: crate::sks::DesignateUser, bag: crate::sks::KeyBagHandle) -> bool { + let Some(loaded) = self.sks_read_uuid(bag) else { + return false; + }; + let Some(out) = self.sks_send(self.sks_req_copy_uuid_special(user.special_handle())) else { + return false; + }; + out.reply.status == 0 && self.sks_uuid_from_reply(&out) == Some(loaded) + } + + fn userbag_sepos13(&self) -> bool { + matches!(self.profile.key_store, crate::profile::KeyStore::Sepos13 { .. }) + } + + /// Opens a user's bag through the captured device-state transition. The + /// 13.5 store first unlocks the loaded bag itself. pub(crate) fn userbag_unlock( &self, user: crate::sks::DesignateUser, secret: &[u8], ) -> Result<()> { + if !self.userbag_sepos13() { + return self.userbag_transition(user, TransitionState::Unlocked, 0, secret); + } + let bags = self.user_bags.lock(); + let bag = bags.get(user.special_handle().value()).ok_or(ENOENT)?; + self.userbag_loaded_lock_state_13(bag, TransitionState::Unlocked, secret)?; self.userbag_transition(user, TransitionState::Unlocked, 0, secret) } + fn userbag_loaded_lock_state_13( + &self, + bag: crate::sks::KeyBagHandle, + state: TransitionState, + secret: &[u8], + ) -> Result<()> { + let out = self + .sks_step(crate::sks::SKS_LOCK_STATE_NAME, |_healthy| { + self.userbag_request( + crate::sks::SKS_LOCK_STATE_NAME, + encode_loaded_lock_state_13(bag.value(), state, secret)?, + |seq, len| crate::sks::encode_sks_change_lock_state(seq, len).ok_or(EINVAL), + ) + }) + .ok_or(EACCES)?; + let body = self.userbag_body(crate::sks::SKS_LOCK_STATE_NAME, &out)?; + if body.len() != 16 || crate::image::operation_status(body) != Some(0) { + return Err(self.userbag_refused("loaded-bag lock state", body)); + } + Ok(()) + } + + /// Locks the session and the loaded bag itself (13.5 store), then sends + /// grace-timer fires, as the Mac's kernel does, until the store reports + /// the bag locked. Both lock requests are accepted with the bag still + /// usable: the store locks only when its timer fires, about 10 s later + /// even for an immediate lock on M1. + fn userbag_lock_13(&self, user: crate::sks::DesignateUser, flags: u64) -> Result<()> { + const FIRES: u32 = 15; + // Not held across the requests and the waits between fires: every + // other bag and Touch ID path takes this lock. + let bag = self.user_bags.lock().get(user.special_handle().value()).ok_or(ENOENT)?; + self.userbag_transition(user, TransitionState::Locked, flags, &[])?; + self.userbag_loaded_lock_state_13(bag, TransitionState::Locked, &[])?; + for fire in 0..FIRES { + let out = self + .sks_step(crate::sks::SKS_HANDLE_TIMER_FIRE_NAME, |_healthy| { + self.userbag_request( + crate::sks::SKS_HANDLE_TIMER_FIRE_NAME, + encode_timer_fire()?, + |seq, len| Ok(crate::sks::encode_sks_handle_timer_fire(seq, len)), + ) + }) + .ok_or(EACCES)?; + let body = self.userbag_body(crate::sks::SKS_HANDLE_TIMER_FIRE_NAME, &out)?; + match decode_timer_fire_reply(body) { + Some(h) if h == user.special_handle().value() => { + dev_dbg!(self.dev, "userbag: {}'s bag locked after {} timer fires\n", h, fire + 1); + return Ok(()); + } + Some(_) => {} + None => return Err(self.userbag_refused("13.5 timer fire", body)), + } + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(1000)); + } + dev_info_ratelimited!(self.dev, "userbag: the store did not lock {}'s bag within {} s\n", user.special_handle().value(), FIRES); + Err(ETIMEDOUT) + } + + /// Logout on the 13.5 store: lock the session, then unload the bag. The + /// caller exports it first; the next login imports it again. + fn userbag_logout_13(&self, user: crate::sks::DesignateUser) -> Result<()> { + let locked = self.userbag_lock_13(user, 0); + let removed = self.user_bags.lock().remove(user.special_handle().value()); + if let Some(bag) = removed { + let unloaded = self.sks_send(self.sks_req_unload_keybag(bag)); + if !matches!(unloaded, Some(ref out) if out.reply.status == 0) { + dev_info_ratelimited!(self.dev, "userbag: unloading {}'s bag at logout failed\n", user.special_handle().value()); + return Err(EIO); + } + } + locked + } + pub(crate) fn userbag_lock( &self, user: crate::sks::DesignateUser, screen_lock: bool, immediate: bool, ) -> Result<()> { + // The 13.5 store locks as it unlocks: the device-state transition + // (the variant-5 layout; flags 1 for a screen lock, 0 at once), then + // the loaded bag. The transition alone leaves the bag usable. + if self.userbag_sepos13() { + // A screen lock that keeps the class keys for a grace period has + // not been captured on this store: refuse it rather than wait. + if screen_lock && !immediate { + dev_info_ratelimited!( + self.dev, + "userbag: a screen lock with a grace period is not supported on the 13.5 key store yet\n" + ); + return Err(EOPNOTSUPP); + } + return self.userbag_lock_13(user, 0); + } if immediate { let handle = user.special_handle().value(); return self @@ -1132,18 +1355,24 @@ impl crate::SepData { new: &[u8], ) -> Result<()> { let handle = user.special_handle().value(); + let sepos13 = self.userbag_sepos13(); let out = self .sks_step(crate::sks::SKS_CHANGE_SECRET_NAME, |_healthy| { self.userbag_request( crate::sks::SKS_CHANGE_SECRET_NAME, - encode_change_secret(handle, old, new)?, + if sepos13 { + encode_change_secret_13(handle, old, new)? + } else { + encode_change_secret(handle, old, new)? + }, |seq, len| Ok(crate::sks::encode_sks_change_secret(seq, len)), ) }) .ok_or(EACCES)?; let body = self.userbag_body(crate::sks::SKS_CHANGE_SECRET_NAME, &out)?; - if !decode_change_secret_reply(body) { - return Err(EPROTO); + let ok = if sepos13 { decode_change_secret_reply_13(body) } else { decode_change_secret_reply(body) }; + if !ok { + return Err(self.userbag_refused("change secret", body)); } Ok(()) } @@ -1165,17 +1394,35 @@ impl crate::SepData { /// handle, in macOS's order. pub(crate) fn userbag_import(&self, user: crate::sks::DesignateUser, wrapped: &[u8]) -> Result<()> { let handle = self.sks_load_wrapped(wrapped).ok_or(EACCES)?; + // The 13.5 store keeps a designation after its bag is unloaded and + // refuses to designate the slot again: a second login in one boot + // finds it already naming this bag. + if self.userbag_sepos13() && self.userbag_designation_names(user, handle) { + if let Err(e) = self.user_bags.lock().insert(user.special_handle().value(), handle) { + let _ = self.sks_send(self.sks_req_unload_keybag(handle)); + return Err(e); + } + return Ok(()); + } let designated = self.sks_step(crate::sks::SKS_DESIGNATE_NAME, |_healthy| { self.userbag_request( crate::sks::SKS_DESIGNATE_NAME, - encode_designate(handle.value(), user.special_handle().value())?, + encode_designate(self.profile.key_store, handle.value(), user.special_handle().value())?, |seq, len| crate::sks::encode_sks_designate(seq, len).ok_or(EINVAL), ) }); let valid = designated.as_ref().is_some_and(|out| { self.sks_report_response(crate::sks::SKS_DESIGNATE_NAME, out) - .is_some_and(decode_designate_reply) + .is_some_and(|body| decode_designate_reply(self.profile.key_store, body)) }); + if valid && self.userbag_sepos13() { + // Kept loaded for the session (see `LoadedBags`). + if let Err(e) = self.user_bags.lock().insert(user.special_handle().value(), handle) { + let _ = self.sks_send(self.sks_req_unload_keybag(handle)); + return Err(e); + } + return Ok(()); + } let _ = self.sks_send(self.sks_req_unload_keybag(handle)); if !valid { dev_info_ratelimited!(self.dev, "userbag: designating the imported bag as {} failed\n", user.special_handle().value()); @@ -1192,9 +1439,13 @@ impl crate::SepData { let _healthy = self .sks_health_check(crate::sks::SKS_CREATE_NAME) .ok_or(EACCES)?; + let sepos13 = self.userbag_sepos13(); + if sepos13 && self.user_bags.lock().get(user.special_handle().value()).is_some() { + return Err(EBUSY); + } let request = self.userbag_request( crate::sks::SKS_CREATE_NAME, - encode_create(secret)?, + if sepos13 { encode_create_13(secret)? } else { encode_create(secret)? }, |seq, len| crate::sks::encode_sks_create(seq, len).ok_or(EINVAL), )?; let created = crate::xart_guard::keybag_create_window(|| self.sks_send(Ok(request))) @@ -1203,23 +1454,30 @@ impl crate::SepData { return Err(EACCES); } let body = self.userbag_body(crate::sks::SKS_CREATE_NAME, &created)?; - let handle = decode_create_reply(body).ok_or(EPROTO)?; + let handle = if sepos13 { decode_create_reply_13(body) } else { decode_create_reply(body) } + .ok_or_else(|| self.userbag_refused("create", body))?; let designated = self.sks_step(crate::sks::SKS_DESIGNATE_NAME, |_healthy| { self.userbag_request( crate::sks::SKS_DESIGNATE_NAME, - encode_designate(handle.value(), user.special_handle().value())?, + encode_designate(self.profile.key_store, handle.value(), user.special_handle().value())?, |seq, len| crate::sks::encode_sks_designate(seq, len).ok_or(EINVAL), ) }); let valid = designated.as_ref().is_some_and(|out| { self.sks_report_response(crate::sks::SKS_DESIGNATE_NAME, out) - .is_some_and(decode_designate_reply) + .is_some_and(|body| decode_designate_reply(self.profile.key_store, body)) }); if !valid { let _ = self.sks_send(self.sks_req_unload_keybag(handle)); return Err(EACCES); } + if sepos13 { + if let Err(e) = self.user_bags.lock().insert(user.special_handle().value(), handle) { + let _ = self.sks_send(self.sks_req_unload_keybag(handle)); + return Err(e); + } + } // Copying the wrapped bag into a per-user durable store is phase 2. // Until then this ioctl establishes only the live designated bag. Ok(()) @@ -1304,13 +1562,33 @@ impl crate::SepData { pub(crate) fn userbag_ioctl(&self, cmd: u32, arg: usize) -> Result { crate::bio::require_admin()?; - if self.profile.key_store != crate::profile::KeyStore::Variant5 { - // The user-bag layouts were captured on the variant-5 key store - // (macOS 26 on the Neo). The 13.x key store of M1/M2-generation - // Macs has not been captured, so nothing is sent there. + if !self.profile.per_user_keybags { + // Gate on the proven-hardware capability, NOT the create-encoding + // variant: the warm macOS-shared enclaves (T8112/M2, T8122/M3) use + // the variant-5 identity encoding yet never reply to a user-bag + // DESIGNATE_KEYBAG, which condemns the SKS endpoint for the boot. + // User-bag create/designate is proven only on the Neo (T8140) and + // the J616s/M4-Pro family; everything else refuses cleanly here so + // the enclave is never wedged. Touch ID / identity are untouched. dev_info_ratelimited!( self.dev, - "userbag: per-user key bags are not supported on this key store yet (only variant 5 has been captured)\n" + "userbag: per-user key bags are not supported on this Mac's Secure Enclave key store\n" + ); + return Err(EOPNOTSUPP); + } + // Variant 5 (macOS 26 on the Neo) has every layout. The 13.5 store of + // M1/M2-generation Macs has create, import/export, unlock, lock and + // password change; its state query and FDE sealing are not captured. + let supported = match self.profile.key_store { + crate::profile::KeyStore::Variant5 => true, + crate::profile::KeyStore::Sepos13 { .. } => { + matches!(cmd, IOC_CREATE | IOC_IMPORT | IOC_EXPORT | IOC_UNLOCK | IOC_LOCK | IOC_CHANGE) + } + }; + if !supported { + dev_info_ratelimited!( + self.dev, + "userbag: this request is not supported on this key store yet\n" ); return Err(EOPNOTSUPP); } @@ -1441,6 +1719,10 @@ impl crate::SepData { let (uid, reason, grace_s) = parse_lock(&request)?; let user = bag_designation(uid)?; let screen = reason == LOCK_REASON_SCREEN; + if reason == LOCK_REASON_LOGOUT && self.userbag_sepos13() { + self.userbag_logout_13(user)?; + return crate::bio::ok(); + } self.userbag_lock(user, screen, lock_is_immediate(reason, grace_s))?; crate::bio::ok() } @@ -1538,9 +1820,79 @@ mod tests { ); } + #[test] + fn sepos13_create_layout_golden() { + let body = encode_create_13(b"pw").expect("create"); + let mut golden = [0u8; 32]; + golden[0..4].copy_from_slice(&1u32.to_le_bytes()); + golden[4..12].copy_from_slice(&CLIENT_LE); + golden[20..24].copy_from_slice(&2u32.to_le_bytes()); + golden[24..26].copy_from_slice(b"pw"); + assert_eq!(body.as_slice(), &golden); + assert_eq!(decode_create_reply_13(&[1, 0, 0, 0, 7, 0, 0, 0]).unwrap().value(), 7); + // The variant-5 reply, a negative handle and a trailer are refused. + assert!(decode_create_reply_13(&[4, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0]).is_none()); + assert!(decode_create_reply_13(&[1, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]).is_none()); + assert!(decode_create_reply_13(&[1, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0]).is_none()); + assert!(decode_create_reply(&[1, 0, 0, 0, 7, 0, 0, 0]).is_none()); + } + + #[test] + fn sepos13_change_secret_layout_golden() { + let body = encode_change_secret_13(USER_HANDLE, b"ol", b"nw").expect("change"); + let mut golden = [0u8; 52]; + golden[0..4].copy_from_slice(&1u32.to_le_bytes()); + golden[4..12].copy_from_slice(&CLIENT_LE); + golden[12..16].copy_from_slice(&USER_HANDLE.to_le_bytes()); + golden[16..20].copy_from_slice(&2u32.to_le_bytes()); + golden[20..22].copy_from_slice(b"ol"); + golden[24..28].copy_from_slice(&2u32.to_le_bytes()); + golden[28..30].copy_from_slice(b"nw"); + // two empty blobs at 32 and 36 + golden[40..44].copy_from_slice(&0xffu32.to_le_bytes()); + assert_eq!(&body.as_slice()[..44], &golden[..44]); + assert_eq!(body.as_slice().len(), 48); + assert!(decode_change_secret_reply_13(&[1, 0, 0, 0, 0, 0, 0, 0])); + assert!(!decode_change_secret_reply_13(&[3, 0, 0, 0, 0, 0, 0, 0])); + assert!(!decode_change_secret_reply_13(&[1, 0, 0, 0, 5, 0, 0, 0])); + } + + #[test] + fn sepos13_loaded_unlock_layout_golden() { + let body = encode_loaded_lock_state_13(5, TransitionState::Unlocked, b"pw").expect("unlock"); + let mut golden = [0u8; 28]; + golden[4..12].copy_from_slice(&CLIENT_LE); + golden[12..16].copy_from_slice(&5i32.to_le_bytes()); + golden[20..24].copy_from_slice(&2u32.to_le_bytes()); + golden[24..26].copy_from_slice(b"pw"); + assert_eq!(body.as_slice(), &golden); + assert_eq!(encode_loaded_lock_state_13(-5, TransitionState::Unlocked, b"pw").err(), Some(EINVAL)); + assert_eq!(encode_loaded_lock_state_13(5, TransitionState::Unlocked, b"").err(), Some(EINVAL)); + let body = encode_loaded_lock_state_13(5, TransitionState::Locked, b"").expect("lock"); + let mut golden = [0u8; 24]; + golden[4..12].copy_from_slice(&CLIENT_LE); + golden[12..16].copy_from_slice(&5i32.to_le_bytes()); + golden[16..20].copy_from_slice(&1i32.to_le_bytes()); + assert_eq!(body.as_slice(), &golden); + assert_eq!(encode_loaded_lock_state_13(5, TransitionState::Locked, b"pw").err(), Some(EINVAL)); + } + + #[test] + fn loaded_bags_hold_one_bag_per_user() { + let mut bags = LoadedBags::new(); + let h = crate::sks::KeyBagHandle::from_load_reply(3); + bags.insert(USER_HANDLE, h).expect("insert"); + assert_eq!(bags.insert(USER_HANDLE, h).unwrap_err(), EBUSY); + assert_eq!(bags.get(USER_HANDLE).unwrap().value(), 3); + assert!(bags.get(USER_HANDLE - 1).is_none()); + assert_eq!(bags.remove(USER_HANDLE).unwrap().value(), 3); + assert!(bags.remove(USER_HANDLE).is_none()); + } + #[test] fn designate_layout_golden_and_round_trip() { - let body = encode_designate(1, USER_HANDLE).expect("designate"); + let key_store = crate::profile::KeyStore::Variant5; + let body = encode_designate(key_store, 1, USER_HANDLE).expect("designate"); let mut golden = [0u8; 32]; golden[0..4].copy_from_slice(&1u32.to_le_bytes()); golden[4..12].copy_from_slice(&CLIENT_LE); @@ -1548,13 +1900,32 @@ mod tests { golden[16..20].copy_from_slice(&USER_HANDLE.to_le_bytes()); assert_eq!(body.as_slice(), &golden); assert_eq!( - decode_designate(body.as_slice()), + decode_designate(key_store, body.as_slice()), Some(Designate { source_handle: 1, user_handle: USER_HANDLE }) ); - assert!(decode_designate_reply(&1u32.to_le_bytes())); + assert!(decode_designate_reply(key_store, &1u32.to_le_bytes())); + } + + #[test] + fn sepos13_designation_has_no_flags_trailer() { + let key_store = crate::profile::KeyStore::Sepos13 { cpx_encryption_mode: 0 }; + let body = encode_designate(key_store, 1, USER_HANDLE).expect("designate"); + let mut golden = [0u8; 24]; + golden[4..12].copy_from_slice(&CLIENT_LE); + golden[12..16].copy_from_slice(&1i32.to_le_bytes()); + golden[16..20].copy_from_slice(&USER_HANDLE.to_le_bytes()); + assert_eq!(body.as_slice(), &golden); + assert_eq!(decode_designate(key_store, body.as_slice()), + Some(Designate { source_handle: 1, user_handle: USER_HANDLE })); + assert!(decode_designate_reply(key_store, &0u32.to_le_bytes())); + assert!(!decode_designate_reply(key_store, &1u32.to_le_bytes())); + assert!(decode_designate(crate::profile::KeyStore::Variant5, body.as_slice()).is_none()); + let mut extra = [0u8; 32]; + extra[..24].copy_from_slice(body.as_slice()); + assert!(decode_designate(key_store, &extra).is_none()); } #[test]