From a6b2e47c27b8295b1428db953b910f530e2bc477 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:39:03 +1100 Subject: [PATCH 01/11] soc: apple: sep: gate per-user key bags on a proven capability, not the create variant userbag_ioctl refused per-user key bags unless profile.key_store was the variant-5 create encoding. That encoding describes how the identity key bag is created, not whether the enclave can create a NEW per-user bag. T8112 (M2) and T8122 (M3) are warm-register platforms whose SEP is handed over running and shared with macOS; their identity bag uses the variant-5 form, so they passed the Variant5 check, yet their enclave never replies to a user-bag DESIGNATE_KEYBAG. A single unanswered DESIGNATE condemns the SKS endpoint for the rest of the boot (sks_wedged), taking the whole key store down: the log shows "DESIGNATE_KEYBAG got no reply" followed by every later SKS request reporting "endpoint gone for this boot". Per-user bag create and designate are proven only on T8140 (J700) and the T6040 (J616s / M4 Pro) enclave family. Add an explicit PlatformProfile capability, per_user_keybags, true only on those, and gate userbag_ioctl and the per-user-bag ref-key / FDE paths on it instead of on the create-encoding variant. The unsupported platforms now return EOPNOTSUPP before any enclave request, so the SKS endpoint is never wedged. Touch ID and the identity bag are unaffected: neither uses userbag_ioctl. The sep KUnit suite passes (598 run, 596 passed, 2 skipped, 0 failed). Assisted-by: LLM Signed-off-by: Ryan Murray Signed-off-by: Cameron Cooper --- drivers/soc/apple/profile.rs | 20 ++++++++++++++++++++ drivers/soc/apple/refkey.rs | 6 +++--- drivers/soc/apple/userbag.rs | 14 +++++++++----- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 29e74e2df0c57..a64c86dded9a3 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,7 @@ pub(crate) const T8103: PlatformProfile = PlatformProfile { cpx_encryption_mode: 2, }, persistent_enrol: true, + per_user_keybags: false, 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 +274,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 +309,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 +340,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 +415,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..c0ffcb1d98074 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -537,7 +537,7 @@ impl SepData { 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); } crate::xart_guard::close_policy_window(); @@ -601,7 +601,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 +651,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)?; diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index 5b6bdeff833fb..f2db368e5d85e 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -1304,13 +1304,17 @@ 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); } From f4bbb2bb5417684d3ed632ff18c8162497571559 Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:55:36 +1100 Subject: [PATCH 02/11] soc: apple: sep: derive per-user key bags from the key store variant per_user_keybags was a list of the enclaves where a user-bag create and designate had been run: true on T8140 and the T6040 family, false everywhere else. That makes every enclave nobody has tried refuse, and says nothing about why the one measured failure fails. The user-bag requests are part of the variant-5 key store; the 13.5 key store has no such requests. The one measured defect is the T8112 (J415) enclave, which returns a handle for CREATE_KEYBAG and then never answers DESIGNATE_KEYBAG, condemning the SKS endpoint for the boot. Name that defect, designate_unanswered, set it on T8112 only, and derive per_user_keybags() from the key store variant and that flag. T8122 no longer inherits the flag from the T8112 profile it extends: the unanswered DESIGNATE was measured on J415, not on an M3. T6020 on current firmware, T8122, T8132 and T8142 therefore offer per-user key bags; none of them has run a user-bag DESIGNATE yet. T8103, T6000 and T6020 on the 13.5 key store keep refusing, as does T8112. Add a KUnit case covering per_user_keybags() for every profile. Signed-off-by: Ryan Signed-off-by: Cameron Cooper --- drivers/soc/apple/profile.rs | 69 +++++++++++++++++++++++++----------- drivers/soc/apple/refkey.rs | 6 ++-- drivers/soc/apple/userbag.rs | 12 +++---- 3 files changed, 56 insertions(+), 31 deletions(-) diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index a64c86dded9a3..f15645eb3f468 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -185,21 +185,29 @@ 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 enclave never answers a user-bag `DESIGNATE_KEYBAG`, and that + /// unanswered request condemns the SKS endpoint for the rest of the boot + /// (`sks_wedged`), taking the whole key store down. Measured on T8112 + /// (J415, OS firmware 26.6.2): CREATE_KEYBAG returns a handle, then + /// DESIGNATE_KEYBAG gets no reply. Such an enclave refuses per-user key + /// bags with `EOPNOTSUPP` before any request is sent (see + /// [`PlatformProfile::per_user_keybags`]). + pub(crate) designate_unanswered: bool, /// The `xart_guard` level when the parameter is left at its default (see /// [`crate::xart_guard`]). pub(crate) xart_guard: u8, } +impl PlatformProfile { + /// Whether the enclave can create and designate a NEW per-user key bag + /// (`userbag_ioctl`, linux#921). The user-bag requests are the variant-5 + /// key store's; the 13.5 key store has no such request shapes. An enclave + /// with the measured unanswered-DESIGNATE defect is the exception. + pub(crate) const fn per_user_keybags(&self) -> bool { + matches!(self.key_store, KeyStore::Variant5) && !self.designate_unanswered + } +} + pub(crate) const T8103: PlatformProfile = PlatformProfile { name: "T8103/J313", shmem_capacity: 0x3_0000, @@ -232,7 +240,7 @@ pub(crate) const T8103: PlatformProfile = PlatformProfile { cpx_encryption_mode: 2, }, persistent_enrol: true, - per_user_keybags: false, + designate_unanswered: false, 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. @@ -274,7 +282,7 @@ pub(crate) const T6000: PlatformProfile = PlatformProfile { cpx_encryption_mode: 2, }, persistent_enrol: true, - per_user_keybags: false, + designate_unanswered: false, nonce_session: false, // As T8103. On J316s, creating the identity keybag also rewrites a // session record that predates Linux. @@ -309,8 +317,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, + // Not measured: no M2 Pro/Max has run a user-bag DESIGNATE. + designate_unanswered: false, nonce_session: false, // A warm-attach enclave shared with macOS, as on T8112. xart_guard: 1, @@ -340,9 +348,8 @@ 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, + // J700 answers the user-bag CREATE and DESIGNATE (variant-5 capture). + designate_unanswered: false, name: "T8140/J700", shmem_capacity: 0x4_0000, shmem_first_item: b"CINP", @@ -415,9 +422,8 @@ 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, + // J415 never answers a user-bag DESIGNATE_KEYBAG (see the field). + designate_unanswered: true, nonce_session: false, // Guarded from its first Linux boot (2026-10-16): no record refused. xart_guard: 1, @@ -447,6 +453,10 @@ pub(crate) const T8122: PlatformProfile = PlatformProfile { dart_window: &DART_HIGH_ALIAS, // A warm-attach enclave shared with macOS, as on T8112. xart_guard: 1, + // The unanswered DESIGNATE is a J415 measurement, not a property of the + // T8112 profile this one extends; no M3 (nor the M4/M5 Airs extending + // this) has run a user-bag DESIGNATE. + designate_unanswered: false, ..T8112 }; @@ -819,6 +829,25 @@ mod tests { assert!(T6040.xart_guard == 1); } + #[test] + fn per_user_keybags_follow_the_key_store_and_the_designate_defect() { + // The 13.5 key store has no user-bag requests. + assert!(!T8103.per_user_keybags()); + assert!(!T6000.per_user_keybags()); + assert!(!T6020_SEPOS13.per_user_keybags()); + // The measured unanswered DESIGNATE. + assert!(T8112.designate_unanswered); + assert!(!T8112.per_user_keybags()); + // Every other variant-5 enclave. + for p in [ + &T6020, &T8140, &T8122, &T6040, &T6041, &T6050, &T8132, &T8142, + ] { + assert!(p.key_store == KeyStore::Variant5); + assert!(!p.designate_unanswered); + assert!(p.per_user_keybags()); + } + } + /// The name of the profile `select` picks for a root `compatible` list. fn picked(compatibles: &[&[u8]]) -> Option<&'static str> { let has = |c: &[u8]| compatibles.iter().any(|x| *x == c); diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index c0ffcb1d98074..c92dd28cfa1b8 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -537,7 +537,7 @@ impl SepData { user: crate::sks::DesignateUser, acl: Option<&[u8]>, ) -> Result> { - if !self.profile.per_user_keybags { + if !self.profile.per_user_keybags() { return Err(EOPNOTSUPP); } crate::xart_guard::close_policy_window(); @@ -601,7 +601,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.per_user_keybags { + if !self.profile.per_user_keybags() { return Err(EOPNOTSUPP); } crate::xart_guard::close_policy_window(); @@ -651,7 +651,7 @@ impl SepData { record: &[u8], sealed: &[u8], ) -> Result> { - if !self.profile.per_user_keybags { + if !self.profile.per_user_keybags() { return Err(EOPNOTSUPP); } Self::refkey_pub(record).ok_or(EINVAL)?; diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index f2db368e5d85e..3c27b8dbe0327 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -1304,14 +1304,10 @@ impl crate::SepData { pub(crate) fn userbag_ioctl(&self, cmd: u32, arg: usize) -> Result { crate::bio::require_admin()?; - 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. + if !self.profile.per_user_keybags() { + // The 13.5 key store has no user-bag requests, and an enclave + // that never answers a user-bag DESIGNATE_KEYBAG would condemn + // the SKS endpoint for the boot: refuse before sending anything. dev_info_ratelimited!( self.dev, "userbag: per-user key bags are not supported on this Mac's Secure Enclave key store\n" From 8fe79c8560dade3b627612eaf12e4ed630fc52ae Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Wed, 11 Nov 2026 08:38:03 -0600 Subject: [PATCH 03/11] soc: apple: sep: keep explicit user bags in 13.5 ref-key requests On the 13.5 key store, sks_req_refkey always substituted the configured Linux user's designation for the target handle. That is right for the identity bag's source handles, but it also redirected an explicitly designated user bag, so a key meant for a per-user bag was made and used under the identity bag instead. Factor the choice into refkey_target(): source handles keep the identity mapping, and an explicit user designation keeps its own bag. Variant 5 is unchanged. The KUnit cases cover the identity fallback, the user-designation boundaries and variant 5. Signed-off-by: Cameron Cooper --- drivers/soc/apple/refkey.rs | 53 +++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index c92dd28cfa1b8..53f8ecc3446cf 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)?; @@ -805,3 +812,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(()) + } +} From 1f88c9f6ddf3caee27dd5abd335ddfcab73132ba Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Wed, 11 Nov 2026 12:37:23 -0600 Subject: [PATCH 04/11] soc: apple: sep: userbag: designate with the key store's own variant The per-user bag path hard-coded designate variant 1 and its flags trailer, the variant-5 form. The 13.5 key store takes variant 0 with the body ending after the empty blob, as the identity-bag path already sends it. Move the variant choice into sks::designate_variant(), shared by both paths, and encode and decode the user-bag designation with it. The variant-5 layout is unchanged; the user-bag ioctls stay gated by per_user_keybags. The KUnit golden test gains a 13.5 case for the shorter body and its reply, and checks that each store rejects the other's form. Signed-off-by: Cameron Cooper --- drivers/soc/apple/sks.rs | 15 +++++++--- drivers/soc/apple/userbag.rs | 55 +++++++++++++++++++++++++----------- 2 files changed, 50 insertions(+), 20 deletions(-) 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 3c27b8dbe0327..fb3e22c89433e 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,32 @@ 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 { +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 +234,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( @@ -1168,13 +1171,13 @@ impl crate::SepData { 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)) }); let _ = self.sks_send(self.sks_req_unload_keybag(handle)); if !valid { @@ -1208,13 +1211,13 @@ impl crate::SepData { 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)); @@ -1540,7 +1543,8 @@ mod tests { #[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 +1552,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] From 2e61ba15b4502f47a92f68b01cd26c40bcff08d1 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Sat, 14 Nov 2026 10:57:12 -0600 Subject: [PATCH 05/11] soc: apple: sep: userbag: per-user bags on the 13.5 key store The user-bag ioctls refused every request on the 13.5 key store of M1/M2-generation Macs. Add that store's backend for create, import, export, unlock and lock: - create uses the generic DeviceBag constructor (version 1); - unlock first unlocks the loaded bag with the version-0 CHANGE_LOCK_STATE, which has no flags trailer, then runs the designated-session device-state transition. Neither alone lets a key under the bag run; - lock runs the transition with state Locked and the loaded-bag lock, then sends grace-timer fires, as the Mac's kernel does, until the store names the bag locked. The store locks only on a fire, about 10 s after an immediate lock on M1. The bag lock is not held while it waits. A screen lock with a grace period is not captured on this store and is refused with EOPNOTSUPP; - import of a bag the user's designation already names (a repeated login) keeps that bag rather than designating it twice. Variant 5 keeps a designation after its temporary handle is unloaded. The 13.5 loaded-bag unlock needs the handle, so the bag stays loaded from import or create until logout, which locks and unloads it. Password change, state query and FDE sealing stay EOPNOTSUPP on the 13.5 store. KUnit golden layouts cover the 13.5 create and its reply, the loaded-bag unlock and lock, the timer fire, and the loaded-bag registry. Signed-off-by: Cameron Cooper --- drivers/soc/apple/sep.rs | 6 + drivers/soc/apple/userbag.rs | 293 ++++++++++++++++++++++++++++++++++- 2 files changed, 296 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 715774d719d8e..b4b5746babf3b 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/userbag.rs b/drivers/soc/apple/userbag.rs index fb3e22c89433e..1fdfebfe2cb72 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -199,6 +199,84 @@ fn decode_create_reply(body: &[u8]) -> Option { Some(crate::sks::KeyBagHandle::from_create_reply(handle)) } +// 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); @@ -1093,21 +1171,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 @@ -1168,6 +1357,16 @@ 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, @@ -1179,6 +1378,14 @@ impl crate::SepData { self.sks_report_response(crate::sks::SKS_DESIGNATE_NAME, out) .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()); @@ -1195,9 +1402,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))) @@ -1206,7 +1417,8 @@ 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( @@ -1223,6 +1435,12 @@ impl crate::SepData { 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(()) @@ -1317,6 +1535,22 @@ impl crate::SepData { ); 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 and lock; + // its password change, 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) + } + }; + if !supported { + dev_info_ratelimited!( + self.dev, + "userbag: this request is not supported on this key store yet\n" + ); + return Err(EOPNOTSUPP); + } let user_ptr = UserPtr::from_addr(arg); if cmd != IOC_STATE && !crate::bio::idle_for_mutation(&self.bio_session.lock()) { return Err(EBUSY); @@ -1444,6 +1678,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() } @@ -1541,6 +1779,55 @@ 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_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 key_store = crate::profile::KeyStore::Variant5; From c60e099e4920c924a4c262c40c6cec25c2b961fd Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Sat, 14 Nov 2026 15:21:49 -0600 Subject: [PATCH 06/11] soc: apple: sep: userbag: password change on the 13.5 key store The 13.5 key store refused CHANGE with EOPNOTSUPP, so a user's bag could not follow a password change. Its change-secret request is version 1 of the variant-5 one, as macOS 13 sends it: client, handle, the old and new secrets, two further blobs and two words (a u8 flag and the generation option), without variant 5's last word. Send it with the two blobs empty, the flag 0xff and the generation option 0, as the variant-5 path does, and accept the version-1 reply. KUnit adds the golden layout. Not yet run on hardware. Signed-off-by: Cameron Cooper --- drivers/soc/apple/userbag.rs | 69 ++++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index 1fdfebfe2cb72..d284bef1f1d01 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -434,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] } @@ -1324,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(()) } @@ -1536,12 +1573,12 @@ impl crate::SepData { 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 and lock; - // its password change, state query and FDE sealing are not captured. + // 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) + matches!(cmd, IOC_CREATE | IOC_IMPORT | IOC_EXPORT | IOC_UNLOCK | IOC_LOCK | IOC_CHANGE) } }; if !supported { @@ -1796,6 +1833,26 @@ mod tests { 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"); From 78149ebe14bb39173e2fbcd5992036e4970fc652 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Sat, 14 Nov 2026 10:58:57 -0600 Subject: [PATCH 07/11] soc: apple: sep: sep-key: user-bag keys on the 13.5 key store CREATE_USER refused on the 13.5 key store because user_key_create_in_bag made only variant 5's EC key type 5. The 13.5 store makes EC type 4 ref-keys, as it already does under the identity bag. Choose the key type from the key store, and advertise SEP_KEY_FEATURE_PASSWORD wherever per_user_keybags allows user bags. Sign and unseal under a user bag already address the designation's special handle on either store. On J293, keys created under a user's bag signed with an enclave-checked password. Signed-off-by: Cameron Cooper --- drivers/soc/apple/key.rs | 3 ++- drivers/soc/apple/refkey.rs | 12 +++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index d227fd887f538..47dbd2ec50f07 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -2269,7 +2269,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/refkey.rs b/drivers/soc/apple/refkey.rs index 53f8ecc3446cf..a148326dfeeb2 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -537,8 +537,10 @@ 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, @@ -547,8 +549,12 @@ impl SepData { 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 From e5d4668f46539ad3944d54e35eadda73e0383d66 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Thu, 19 Nov 2026 09:18:23 -0600 Subject: [PATCH 08/11] soc: apple: sep: per-user key bags on the 13.5 key store per_user_keybags() refuses the 13.5 key store because that store had no user-bag requests. It has them now: create, designate, import/export, unlock, lock and password change in its own shapes (userbag_sepos13), and user-bag keys under them. Derive the capability from the measured DESIGNATE defect alone, so T8112 stays the only enclave that refuses. On J293 (MacBook Pro 13-inch, M1, cold-boot SEP) the userbag ioctls created, exported, imported, unlocked and locked (logout and suspend) a user's bag, and user-bag keys signed with an enclave-checked password. T6000 and T6020 on the 13.5 store send the same requests and now offer per-user bags too; no M1 Pro/Max or 13.5-store M2 Pro/Max has run them yet. Signed-off-by: Cameron Cooper --- drivers/soc/apple/profile.rs | 24 ++++++++++++++++-------- drivers/soc/apple/userbag.rs | 6 +++--- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index f15645eb3f468..d711f4252e119 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -200,11 +200,16 @@ pub(crate) struct PlatformProfile { impl PlatformProfile { /// Whether the enclave can create and designate a NEW per-user key bag - /// (`userbag_ioctl`, linux#921). The user-bag requests are the variant-5 - /// key store's; the 13.5 key store has no such request shapes. An enclave - /// with the measured unanswered-DESIGNATE defect is the exception. + /// (`userbag_ioctl`, linux#921): a rule of the key store, not of the SoC. + /// Both key stores have the user-bag requests, the variant-5 store's and + /// the 13.5 store's own shapes (`userbag_sepos13`, run on T8103). An + /// enclave with the measured unanswered-DESIGNATE defect is the only + /// exception, and a key store added later is refused until its requests + /// are written. pub(crate) const fn per_user_keybags(&self) -> bool { - matches!(self.key_store, KeyStore::Variant5) && !self.designate_unanswered + match self.key_store { + KeyStore::Variant5 | KeyStore::Sepos13 { .. } => !self.designate_unanswered, + } } } @@ -831,10 +836,13 @@ mod tests { #[test] fn per_user_keybags_follow_the_key_store_and_the_designate_defect() { - // The 13.5 key store has no user-bag requests. - assert!(!T8103.per_user_keybags()); - assert!(!T6000.per_user_keybags()); - assert!(!T6020_SEPOS13.per_user_keybags()); + // The 13.5 key store's own user-bag requests: run on T8103 (J293); + // T6000 and T6020 on the 13.5 store use the same requests. + for p in [&T8103, &T6000, &T6020_SEPOS13] { + assert!(matches!(p.key_store, KeyStore::Sepos13 { .. })); + assert!(!p.designate_unanswered); + assert!(p.per_user_keybags()); + } // The measured unanswered DESIGNATE. assert!(T8112.designate_unanswered); assert!(!T8112.per_user_keybags()); diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index d284bef1f1d01..690ec70b6a9cc 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -1563,9 +1563,9 @@ impl crate::SepData { pub(crate) fn userbag_ioctl(&self, cmd: u32, arg: usize) -> Result { crate::bio::require_admin()?; if !self.profile.per_user_keybags() { - // The 13.5 key store has no user-bag requests, and an enclave - // that never answers a user-bag DESIGNATE_KEYBAG would condemn - // the SKS endpoint for the boot: refuse before sending anything. + // An enclave that never answers a user-bag DESIGNATE_KEYBAG + // would condemn the SKS endpoint for the boot: refuse before + // sending anything. dev_info_ratelimited!( self.dev, "userbag: per-user key bags are not supported on this Mac's Secure Enclave key store\n" From af703c8d4c026ad030ab06e44ad5753b446d9a96 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Thu, 19 Nov 2026 14:26:39 -0600 Subject: [PATCH 09/11] soc: apple: sep: userbag: hold a bag locked when the store does not confirm its lock On the 13.5 store a lock is two requests the store accepts with the bag still usable, then grace-timer fires until the store reports the bag locked. When that failed (a refused request, an unreadable reply, or no lock after 15 fires), userbag_lock_13() returned an error with the bag still unlocked in the store, and the suspend and logout locks rely on it. On any such failure the driver now holds the bag locked: key creation, signing and unsealing under it are refused with EACCES until an unlock of it succeeds. The hold outlives an unload, so a bag the logout could not lock stays refused if it is loaded again before its password. Also say why the host sends the timer fires: the store locks the bag only on a fire it is sent, and on macOS the kernel sends them; nothing else on Linux does. Signed-off-by: Cameron Cooper --- drivers/soc/apple/refkey.rs | 3 ++ drivers/soc/apple/userbag.rs | 88 ++++++++++++++++++++++++++++++++---- 2 files changed, 82 insertions(+), 9 deletions(-) diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index a148326dfeeb2..0f8e31aaf41b5 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -549,6 +549,7 @@ impl SepData { if !self.profile.per_user_keybags() { return Err(EOPNOTSUPP); } + self.userbag_key_admitted(user)?; let key_type = match self.profile.key_store { profile::KeyStore::Sepos13 { .. } => 4, profile::KeyStore::Variant5 => 5, @@ -567,6 +568,7 @@ impl SepData { acm: Option<&[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]>, ) -> Result> { Self::refkey_pub(blob).ok_or(EINVAL)?; + self.userbag_key_admitted(user)?; let eph = refkey_seal::sealed_ephemeral(sealed)?; let handle = crate::sks::KeyBagHandle::from_load_reply(user.special_handle().value()); let shared = crate::Secret(self.sks_refkey_key_exchange(handle, blob, eph, acm)?); @@ -581,6 +583,7 @@ impl SepData { digest: &[u8; 32], acm: Option<&[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]>, ) -> Result> { + self.userbag_key_admitted(user)?; let handle = crate::sks::KeyBagHandle::from_load_reply(user.special_handle().value()); self.sks_refkey_sign(handle, blob, digest, acm) } diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index 690ec70b6a9cc..d3a2a77594738 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -252,11 +252,29 @@ fn encode_loaded_lock_state_13(bag: i32, state: TransitionState, secret: &[u8]) /// 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)>); +/// The loaded bags, and the bags the driver holds locked (`hold_locked`): +/// a lock the store never confirmed. A held bag stays held when it is +/// unloaded, until a later unlock of it succeeds. +pub(crate) struct LoadedBags(KVec<(i32, crate::sks::KeyBagHandle)>, KVec); impl LoadedBags { pub(crate) const fn new() -> Self { - LoadedBags(KVec::new()) + LoadedBags(KVec::new(), KVec::new()) + } + + fn hold_locked(&mut self, user: i32) -> Result<()> { + if !self.held_locked(user) { + self.1.push(user, GFP_KERNEL)?; + } + Ok(()) + } + + fn held_locked(&self, user: i32) -> bool { + self.1.contains(&user) + } + + fn release_hold(&mut self, user: i32) { + self.1.retain(|u| *u != user); } fn get(&self, user: i32) -> Option { @@ -1227,10 +1245,14 @@ impl crate::SepData { if !self.userbag_sepos13() { return self.userbag_transition(user, TransitionState::Unlocked, 0, secret); } - let bags = self.user_bags.lock(); + let mut 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) + self.userbag_transition(user, TransitionState::Unlocked, 0, secret)?; + // The store has the bag unlocked again: a hold from a lock it never + // confirmed ends. + bags.release_hold(user.special_handle().value()); + Ok(()) } fn userbag_loaded_lock_state_13( @@ -1255,12 +1277,45 @@ impl crate::SepData { 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. + /// Locks the session and the loaded bag itself (13.5 store). If the + /// store does not confirm the lock (a refused request, an unreadable + /// reply, or no lock within the timer fires), the driver holds the bag + /// locked: its keys are refused here (`userbag_key_admitted`) until an + /// unlock of it succeeds, whatever the store still allows. fn userbag_lock_13(&self, user: crate::sks::DesignateUser, flags: u64) -> Result<()> { + let locked = self.userbag_lock_13_steps(user, flags); + if let Err(e) = &locked { + if *e != ENOENT { + let held = self.user_bags.lock().hold_locked(user.special_handle().value()); + dev_info_ratelimited!( + self.dev, + "userbag: the store did not confirm {}'s lock ({:?}); its keys are refused until its next unlock{}\n", + user.special_handle().value(), + e, + if held.is_ok() { "" } else { " (the hold could not be recorded)" } + ); + } + } + locked + } + + /// Whether a key request under `user`'s bag may go to the store: not + /// while the driver holds the bag locked (`userbag_lock_13`). + pub(crate) fn userbag_key_admitted(&self, user: crate::sks::DesignateUser) -> Result<()> { + if self.user_bags.lock().held_locked(user.special_handle().value()) { + return Err(EACCES); + } + Ok(()) + } + + /// The 13.5 store's lock: the session and the loaded bag, then + /// grace-timer fires until the store reports the bag locked. Both lock + /// requests are accepted with the bag still usable: the store locks + /// only when its grace timer fires, about 10 s later even for an + /// immediate lock on M1. The store acts only on a fire it is sent, and + /// on macOS the kernel sends them; nothing else on Linux does, so + /// without these the bag would stay unlocked. + fn userbag_lock_13_steps(&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. @@ -1771,6 +1826,21 @@ impl crate::SepData { mod tests { use super::*; + #[test] + fn a_held_bag_stays_held_until_its_unlock() { + let mut bags = LoadedBags::new(); + assert!(!bags.held_locked(-5)); + bags.hold_locked(-5).expect("hold"); + bags.hold_locked(-5).expect("hold again"); + assert!(bags.held_locked(-5)); + // Another bag is not held, and unloading does not end the hold. + assert!(!bags.held_locked(-6)); + assert!(bags.remove(-5).is_none()); + assert!(bags.held_locked(-5)); + bags.release_hold(-5); + assert!(!bags.held_locked(-5)); + } + const H: u64 = 3600; const T0: u64 = 1000; From fbb280ae7bce5f8ed05db3fe2016e84823099be1 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Thu, 19 Nov 2026 14:27:29 -0600 Subject: [PATCH 10/11] soc: apple: sep: userbag: log a refused reply's length and status only userbag_refused() printed up to 96 bytes of a refused reply at info level. The 13.5 store's create and change-secret replies now reach it, and those can carry key-bag material. Print the length and the operation status instead. Signed-off-by: Cameron Cooper --- drivers/soc/apple/userbag.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index d3a2a77594738..9a9eb16e8dab1 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -1196,8 +1196,15 @@ impl crate::SepData { /// Logs a reply the decoders refused: which step, its length and its /// first bytes. Replies to these queries carry no secret. fn userbag_refused(&self, step: &str, body: &[u8]) -> Error { - let n = body.len().min(96); - dev_info_ratelimited!(self.dev, "userbag: {}: reply refused, {} bytes: {:02x?}\n", step, body.len(), &body[..n]); + // Length and status only: the replies refused here (create, + // change-secret, the lock steps) can carry key-bag material. + dev_info_ratelimited!( + self.dev, + "userbag: {}: reply refused, {} bytes, status {:?}\n", + step, + body.len(), + crate::image::operation_status(body) + ); EPROTO } From 0455829bb02ac35c3870c4eb4fe1ac94c264dfc8 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Mon, 23 Nov 2026 15:02:54 -0600 Subject: [PATCH 11/11] soc: apple: sep: userbag: an import of a bag still held is EBUSY The login helper imports the saved bag at every password login and takes EBUSY as "already loaded: unlock it". A bag locked for a suspend (or open for another session) stays in user_bags, so a password unlock after the lock imports it again. The 13.5 store got EBUSY from LoadedBags::insert() once the second copy was loaded. Variant 5 never got there: it designated the second copy, the store refused (the bag was still designated), and the import answered EACCES. On J716c (M5 Max) the password at the lock screen then left the bag locked, and the user's Touch ID keys refused until a logout. Answer EBUSY before loading a copy when the driver still holds the user's bag, on both stores. The helper then unlocks it as before. Signed-off-by: Cameron Cooper --- drivers/soc/apple/userbag.rs | 6 ++++++ include/uapi/linux/apple-sep.h | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/userbag.rs b/drivers/soc/apple/userbag.rs index 9a9eb16e8dab1..3eeb593c2ef50 100644 --- a/drivers/soc/apple/userbag.rs +++ b/drivers/soc/apple/userbag.rs @@ -1455,6 +1455,12 @@ impl crate::SepData { /// stays locked until the password unlocks it), then drops the temporary /// handle, in macOS's order. pub(crate) fn userbag_import(&self, user: crate::sks::DesignateUser, wrapped: &[u8]) -> Result<()> { + // A bag still held (locked for a suspend, or a second session) is + // only unlocked again: EBUSY, before a second copy is loaded. Variant + // 5 refuses to designate a bag that is already designated. + if self.user_bags.lock().get(user.special_handle().value()).is_some() { + return Err(EBUSY); + } 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 diff --git a/include/uapi/linux/apple-sep.h b/include/uapi/linux/apple-sep.h index 2b949a8c89597..d99ec7e70664b 100644 --- a/include/uapi/linux/apple-sep.h +++ b/include/uapi/linux/apple-sep.h @@ -518,7 +518,9 @@ struct sep_keybag_change { * A user's wrapped bag, for userspace to keep across reboots (as macOS * saves it). It holds no secret: it opens only with the user's password, * on this Mac. EXPORT copies the designated bag; IMPORT loads a saved one - * and designates it again, locked until SEP_BIO_KEYBAG_UNLOCK. + * and designates it again, locked until SEP_BIO_KEYBAG_UNLOCK. IMPORT of a + * bag the driver still holds (locked, or open for another session) is + * EBUSY: unlock it instead. */ #define SEP_KEYBAG_BLOB_MAX 4096