diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index de992f0de06337..e5717194520e26 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -3,9 +3,12 @@ Date: October 2026 KernelVersion: 7.1 Contact: Chris Kearney Description: - (RO) Version of the diag interface: "2" for the attributes - and values described in this file. Version 2 added - sensor_attach and restore; version 1 had neither. + (RO) Version of the diag interface. Version 3 distinguishes + older pin lists with matching="legacy" and can report + "usable" after a successful, persisted guarded verification. + It also exposes the effective xart_guard_pins policy. + Version 2 added sensor_attach and restore. Version 1 had + neither. Within a version, attributes are only added, and an existing attribute keeps its values and their meaning. A reader tests @@ -294,6 +297,19 @@ Description: refused too. == ================================================ +What: /sys/bus/platform/devices/.sep/diag/xart_guard_pins +Date: November 2026 +KernelVersion: 7.2 +Contact: Ryan Murray +Description: + (RO) The effective pin policy at probe. 1 means that xART + writes are enabled, the guard runs at level 1, its list + loaded within the board's pin limit, and xart_guard_pins=1 + enables pin use on this board. Otherwise 0. A fresh, empty + list qualifies on J313, J314s, J316s and J316c. J293 only + qualifies with previously recorded pins. This attribute does + not grant a new pin or indicate a keybag was created. + What: /sys/bus/platform/devices/.sep/diag/xart_guard_list Date: October 2026 KernelVersion: 7.2 @@ -326,7 +342,7 @@ Description: guard has refused since probe, as an unsigned decimal. A new record that could not be added to Linux's list counts too, since its write is refused. Only the first few - refusals are logged; this counts them all. + refusals are logged. The count saturates at 4294967295. What: /sys/bus/platform/devices/.sep/diag/matching Date: October 2026 @@ -340,12 +356,20 @@ Description: the fingerprints were restored. ========== ========================================== - usable xART writes are enabled and no guard runs. + usable xART writes are enabled without a guard, or + this boot's legacy installation has saved + and returned a successful guarded match. + legacy A valid persisted keybag and a complete + older list with its spent marker and one + or more usable pins exist. Their creation + provenance is unknown. A real verification + can establish usability for this boot. unverified A guard runs with its list loaded and has refused nothing yet, on a warm-attach Mac (boot "warm") or on a cold-boot Mac (boot - "cold") whose keybag was created under the - guard with xart_guard_pins=1. Whether every + "cold") whose validated keybag UUID matches + a guarded completion entry with pins enabled. + Whether every record a match rewrites is on the list, or is a pinned locker, is not known until a match is tried. @@ -355,12 +379,10 @@ Description: (xart_guard_refusals above 0), the guard has no list (xart_guard_list "unavailable"), or a guard runs on a - cold-boot Mac (boot "cold") whose keybag - was not created under it. Creating the - keybag there needs xart_guard=0, which - leaves the records a match rewrites off the - list, or xart_guard_pins=1 (run on a J313 - only). + cold-boot Mac (boot "cold") without proof + that its persisted keybag was committed + under the active pin policy. Legacy spent + markers alone cannot prove this. ========== ========================================== For the guard cases the documented opt-out is xart_guard=0, @@ -369,5 +391,6 @@ Description: tools/aurora-sep/XART-SAFETY.md. During a boot the value moves from "unverified" to "blocked" once the guard refuses a write. On a cold-boot Mac with xart_guard_pins=1 it also - moves from "blocked" to "unverified" when the first keybag - creation is sent under the guard, and nowhere else. + moves from "blocked" to "unverified" after the guarded keybag + and its completion entry have been committed. A refusal + always takes precedence over that update or a later verify. diff --git a/drivers/soc/apple/diag.rs b/drivers/soc/apple/diag.rs index a83cc4c1434359..e7bbf5516d546d 100644 --- a/drivers/soc/apple/diag.rs +++ b/drivers/soc/apple/diag.rs @@ -7,16 +7,12 @@ //! can block a bring-up step, and a sysfs read never reaches back into the //! driver or the SEP. -use kernel::{ - device, - prelude::*, - sync::atomic::{Atomic, Relaxed}, // -}; +use kernel::{device, prelude::*}; use crate::{ profile, registration, - xart_guard::MatchFacts, // + xart_guard::{KeybagEvidence, MatchFacts}, // }; extern "C" { @@ -40,9 +36,10 @@ extern "C" { fn sep_diag_set_touchid(started: bool); fn sep_diag_set_sensor_attach(state: c_int); fn sep_diag_set_restore(state: c_int); - fn sep_diag_set_xart_guard(level: c_uint, list_loaded: bool, matching: c_int); + fn sep_diag_set_xart_guard(level: c_uint, list_loaded: bool, pins: bool, matching: c_int); fn sep_diag_set_matching(matching: c_int); - fn sep_diag_xart_guard_refused(matching: c_int); + fn sep_diag_xart_guard_refused(); + fn sep_diag_verified_match(); fn sep_diag_bringup_ended(); } @@ -71,15 +68,15 @@ pub(crate) enum Restore { /// group goes away when the driver unbinds. /// /// `guard` is the xART guard as the store opened it: its effective level and -/// whether Linux's list loaded, or `None` when no guard runs. `guarded_setup` -/// is whether that list says this install's first keybag creation was sent -/// under the guard. +/// whether Linux's list loaded and whether its pin policy is effective, or +/// `None` when no guard runs. `keybag` describes the guard's evidence for +/// the validated, persisted identity bag. pub(crate) fn register( dev: &device::Device, profile: &profile::PlatformProfile, xart_writable: bool, - guard: Option<(u8, bool)>, - guarded_setup: bool, + guard: Option<(u8, bool, bool)>, + keybag: KeybagEvidence, ) -> Result { // Exhaustive, so a new bootstrap or key store fails to build here until // the ABI has a value for it. @@ -91,17 +88,16 @@ pub(crate) fn register( profile::KeyStore::Sepos13 { .. } => true, profile::KeyStore::Variant5 => false, }; - // The facts `matching` is derived from, kept for the guard's refusals. - // Probe runs before the guard can refuse anything. - XART_WRITABLE.store(xart_writable, Relaxed); - COLD.store(cold, Relaxed); - GUARDED_SETUP.store(guarded_setup, Relaxed); - let (level, list_loaded) = guard.unwrap_or((0, false)); - GUARD_LEVEL.store(u32::from(level), Relaxed); - GUARD_LIST.store(list_loaded, Relaxed); - REFUSALS.store(0, Relaxed); - // SAFETY: no preconditions; stores three words. - unsafe { sep_diag_set_xart_guard(c_uint::from(level), list_loaded, matching() as c_int) }; + let (level, list_loaded, pins) = guard.unwrap_or((0, false, false)); + let matching = MatchFacts { + xart_writable, + cold, + keybag, + guard: guard.map(|(level, list_loaded, _)| (level, list_loaded)), + } + .matching(); + // SAFETY: no preconditions; caches the probe's fixed facts. + unsafe { sep_diag_set_xart_guard(c_uint::from(level), list_loaded, pins, matching as c_int) }; // SAFETY: `dev` is bound for the duration of the call, which is what devres // needs. `profile.name` is a `str`, valid for reads of `profile.name.len()` @@ -181,46 +177,22 @@ pub(crate) fn restore(state: Restore) { unsafe { sep_diag_set_restore(state as c_int) }; } -static XART_WRITABLE: Atomic = Atomic::new(false); -static COLD: Atomic = Atomic::new(false); -static GUARDED_SETUP: Atomic = Atomic::new(false); -static GUARD_LEVEL: Atomic = Atomic::new(0); -static GUARD_LIST: Atomic = Atomic::new(false); -static REFUSALS: Atomic = Atomic::new(0); - -/// What a fingerprint match can expect of the xART guard, from the facts -/// [`register`] stored and the refusals since. -fn matching() -> crate::xart_guard::Matching { - let level = GUARD_LEVEL.load(Relaxed); - MatchFacts { - xart_writable: XART_WRITABLE.load(Relaxed), - cold: COLD.load(Relaxed), - guarded_setup: GUARDED_SETUP.load(Relaxed), - guard: (level != 0).then(|| { - ( - u8::try_from(level).unwrap_or(u8::MAX), - GUARD_LIST.load(Relaxed), - ) - }), - refusals: REFUSALS.load(Relaxed), - } - .matching() -} - -/// The xART guard opened this install's first-setup window and recorded it in -/// its list, so the keybag creation about to be sent runs under the guard. -pub(crate) fn xart_guard_setup_recorded() { - GUARDED_SETUP.store(true, Relaxed); - // SAFETY: no preconditions; stores one word. The refusals counted since - // probe stand, which `sep_diag_set_xart_guard` would clear. - unsafe { sep_diag_set_matching(matching() as c_int) }; +/// The caller verified the guarded identity after the keybag commit. +pub(crate) fn xart_guard_keybag_committed() { + // SAFETY: stores the base status. A refusal takes precedence at readout. + unsafe { sep_diag_set_matching(crate::xart_guard::Matching::Unverified as c_int) }; } /// The xART guard refused one of the enclave's writes or deletes. pub(crate) fn xart_guard_refused() { - REFUSALS.fetch_add(1, Relaxed); - // SAFETY: no preconditions; updates two words. - unsafe { sep_diag_xart_guard_refused(matching() as c_int) }; + // SAFETY: no preconditions; increments one counter. + unsafe { sep_diag_xart_guard_refused() }; +} + +/// The current userspace verification completed with a durably saved match. +pub(crate) fn verified_match() { + // SAFETY: promotes the base status only for a legacy pin list. + unsafe { sep_diag_verified_match() }; } /// The boot-time bring-up is over, however far it got. diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index af3e4544e8f7ef..fc1b72fde2dd73 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -17,13 +17,17 @@ #include #include #include +#include #include #include #include "shim.h" +/* Loaders check the on-disk driver before enabling writes. */ +MODULE_INFO(xart_guard_pins_abi, "1"); + /* The contract version; see Documentation/ABI/testing/sysfs-driver-apple-sep. */ -#define SEP_DIAG_ABI 2 +#define SEP_DIAG_ABI 3 #define SEP_DIAG_ATTACH_PENDING 0 #define SEP_DIAG_ATTACH_ATTACHED 1 @@ -67,6 +71,7 @@ static struct { /* The xART guard's effective level (0: none runs), and its list. */ unsigned int xart_guard; bool xart_guard_list; + bool xart_guard_pins; atomic_t attach; atomic_t endpoints; @@ -293,6 +298,13 @@ static ssize_t xart_guard_show(struct device *dev, } static DEVICE_ATTR_RO(xart_guard); +static ssize_t xart_guard_pins_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return sysfs_emit(buf, "%u\n", sep_diag.xart_guard_pins); +} +static DEVICE_ATTR_RO(xart_guard_pins); + static ssize_t xart_guard_list_show(struct device *dev, struct device_attribute *attr, char *buf) { @@ -322,6 +334,10 @@ static ssize_t matching_show(struct device *dev, struct device_attribute *attr, { const char *state; + /* Once the guard refuses, a later keybag commit cannot clear it. */ + if (atomic_read(&sep_diag.xart_refusals)) + return sysfs_emit(buf, "blocked\n"); + switch (atomic_read(&sep_diag.matching)) { case SEP_DIAG_MATCHING_USABLE: state = "usable"; @@ -329,6 +345,9 @@ static ssize_t matching_show(struct device *dev, struct device_attribute *attr, case SEP_DIAG_MATCHING_UNVERIFIED: state = "unverified"; break; + case SEP_DIAG_MATCHING_LEGACY: + state = "legacy"; + break; case SEP_DIAG_MATCHING_BLOCKED: state = "blocked"; break; @@ -356,6 +375,7 @@ static struct attribute *sep_diag_attrs[] = { &dev_attr_restore.attr, &dev_attr_xart_guard.attr, &dev_attr_xart_guard_list.attr, + &dev_attr_xart_guard_pins.attr, &dev_attr_xart_guard_refusals.attr, &dev_attr_matching.attr, NULL @@ -479,36 +499,31 @@ void sep_diag_set_restore(int state) * derived in xart_guard.rs (MatchFacts), which has KUnit tests for each case. */ void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, - int matching) + bool pins, int matching) { sep_diag.xart_guard = level; sep_diag.xart_guard_list = list_loaded; + sep_diag.xart_guard_pins = pins; atomic_set(&sep_diag.xart_refusals, 0); atomic_set(&sep_diag.matching, matching); } -/* - * After probe, when a fact matching is derived from changes without a - * refusal: the guard recorded this install's first-setup window. The level, - * the list and the refusals counted so far stand. - * - * The caller derived matching before this call, and a refusal may have - * landed since. A refusal always leaves "blocked", so the count is read - * after the store: either this sees the refusal and restores "blocked", or - * the refusal's own store comes later. - */ +/* A guarded keybag was committed after probe. */ void sep_diag_set_matching(int matching) { atomic_set(&sep_diag.matching, matching); - if (atomic_read(&sep_diag.xart_refusals)) - atomic_set(&sep_diag.matching, SEP_DIAG_MATCHING_BLOCKED); } -/* With matching as the refusal leaves it. */ -void sep_diag_xart_guard_refused(int matching) +/* A legacy installation can prove present-day usability by a real verify. */ +void sep_diag_verified_match(void) { - atomic_inc(&sep_diag.xart_refusals); - atomic_set(&sep_diag.matching, matching); + atomic_cmpxchg(&sep_diag.matching, SEP_DIAG_MATCHING_LEGACY, + SEP_DIAG_MATCHING_USABLE); +} + +void sep_diag_xart_guard_refused(void) +{ + atomic_add_unless(&sep_diag.xart_refusals, 1, -1); } /* diff --git a/drivers/soc/apple/keybag.rs b/drivers/soc/apple/keybag.rs index ef629ae4fd484b..e22114e7044b17 100644 --- a/drivers/soc/apple/keybag.rs +++ b/drivers/soc/apple/keybag.rs @@ -30,6 +30,7 @@ const MAGIC: [u8; 16] = *b"APPLE-SEP-KBAG01"; /// v2 stores the bag secret; a v1 record is refused, not reinterpreted. const VERSION: u32 = 2; +const STATE_INTENT: u32 = 0; const STATE_COMMITTED: u32 = 1; /// Create refused by the enclave: nothing exists, retry allowed (unlike an /// intent record, where a bag may exist unnamed — block retry). @@ -177,7 +178,7 @@ pub(crate) fn read(slot: Slot) -> Result { head[OFF_STATE + 3], ]); if state == STATE_REFUSED { - return Ok(State::Absent(NoStoredKeyBag { slot })); + return read_refusal(slot, size, &head); } let Some(provenance) = UuidProvenance::from_state(state) else { // Intent or unknown state: a bag may exist unnamed; creating again would @@ -237,7 +238,7 @@ pub(crate) fn read(slot: Slot) -> Result { } pub(crate) fn write_intent(slot: Slot) -> Result<()> { - write_record(slot, 0, &[], &[0; UUID_LEN], &[]) + write_record(slot, STATE_INTENT, &[], &[0; UUID_LEN], &[]) } pub(crate) fn mark_refused(slot: Slot) -> Result<()> { @@ -312,13 +313,12 @@ pub(crate) fn replace_wrapped( ) } -fn write_record( - slot: Slot, +fn record_header( state: u32, wrapped: &[u8], uuid: &[u8; UUID_LEN], secret: &[u8], -) -> Result<()> { +) -> Result<[u8; HEADER]> { let crc = crc16_ccitt_false(&checksum_input(state, wrapped, uuid, secret)?); let mut head = [0u8; HEADER]; @@ -329,7 +329,25 @@ fn write_record( head[OFF_CRC..OFF_CRC + 2].copy_from_slice(&crc.to_le_bytes()); head[OFF_UUID..OFF_UUID + UUID_LEN].copy_from_slice(uuid); head[OFF_SECRET_LEN..OFF_SECRET_LEN + 4].copy_from_slice(&(secret.len() as u32).to_le_bytes()); + Ok(head) +} + +fn read_refusal(slot: Slot, size: u64, head: &[u8; HEADER]) -> Result { + // A damaged state field on a committed bag must never authorize a second create. + if size != HEADER as u64 || *head != record_header(STATE_REFUSED, &[], &[0; UUID_LEN], &[])? { + return Err(EINVAL); + } + Ok(State::Absent(NoStoredKeyBag { slot })) +} +fn write_record( + slot: Slot, + state: u32, + wrapped: &[u8], + uuid: &[u8; UUID_LEN], + secret: &[u8], +) -> Result<()> { + let head = record_header(state, wrapped, uuid, secret)?; let file = shim::StoreFile::open_trunc(slot.path())?; // Body first, then the header that vouches for it: a crash between leaves a // bad checksum, which `read` refuses — the safe side. @@ -340,5 +358,33 @@ fn write_record( file.write_all((HEADER + wrapped.len()) as u64, secret)?; } file.write_all(0, &head)?; - file.sync() + file.sync()?; + if state == STATE_INTENT { + // CREATE_KEYBAG must not reach the enclave before the new file's + // name and intent survive a crash. Later commits reuse this inode. + file.sync_parent()?; + } + Ok(()) +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[kernel::macros::kunit_tests(apple_sep_keybag)] +mod tests { + use super::*; + + #[test] + fn retry_requires_the_complete_empty_refusal_record() -> Result { + let mut head = record_header(STATE_REFUSED, &[], &[0; UUID_LEN], &[])?; + assert!(matches!( + read_refusal(Slot::Identity, HEADER as u64, &head), + Ok(State::Absent(_)) + )); + assert!(read_refusal(Slot::Identity, (HEADER + 1) as u64, &head).is_err()); + for field in [OFF_LEN, OFF_CRC, OFF_CRC + 2, OFF_UUID, OFF_SECRET_LEN] { + head[field] ^= 1; + assert!(read_refusal(Slot::Identity, HEADER as u64, &head).is_err()); + head[field] ^= 1; + } + Ok(()) + } } diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 8af286ae443b2a..2842526d62d737 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -261,9 +261,8 @@ pub(crate) const T6000: PlatformProfile = PlatformProfile { // As T8103. On J316s, creating the identity keybag also rewrites a // session record that predates Linux. The guard refuses that, so the // keybag can only be created there with xart_guard=0, or under the - // guard with xart_guard_pins=1, which should pin it (seen refused on - // J316s, pinning untested there; the J313 setup rewrites three such - // records, after the create). + // guard with xart_guard_pins=1 and a board-specific allowance. + // XART-SAFETY.md lists the measured provisioning and activation counts. xart_guard: 1, }; diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 3922b08ddf21ab..f3c4fb8a079004 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -1382,7 +1382,7 @@ impl SepData { bio::DEVICE_NAME, e ); - // No activation can follow, so a pinning first-setup window ends. + // Discard any dormant J313 activation allowance. self.with_store(|store| store.close_first_setup()); } } @@ -1394,10 +1394,7 @@ impl SepData { if self.touchid_failed.load(Relaxed) { return Err(EIO); } - // A pinning first-setup window ends when this first activation - // returns, on every path: on a J313 the enclave rewrites the third - // shared locker about 280 ms after the LOAD_KEYBAG reply, during the - // requests that follow it. + // Every exit consumes any same-boot J313 activation allowance. let _window = crate::sks::SetupWindow::for_activation(self); let mut store = store::Store::open().inspect_err(|e| { dev_err!( @@ -1448,6 +1445,9 @@ impl SepData { ); return Err(ENODEV); } + // J313 rewrites its third locker after LOAD_KEYBAG. Admit that one + // only during this activation of the identity saved by provisioning. + self.with_store(|store| store.begin_activation(stored.uuid())); let (handle, uuid) = self.sks_recover(&stored).ok_or_else(|| { dev_err!( self.dev, @@ -3388,10 +3388,14 @@ impl SepData { } fn finish_verify(&self, outcome: bio::VerifyOutcome, token_bytes: [u8; bio::TOKEN_LEN]) { + let matched = matches!(&outcome, bio::VerifyOutcome::Matched(_)); let filed = bio::verify_finish( &mut self.bio_session.lock(), self.capture_epoch.load(Relaxed), outcome, token_bytes, ); if filed { + if matched { + diag::verified_match(); + } self.bio_wake(); } } diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index c917a8863d92a3..c7736da88ee32f 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -853,7 +853,11 @@ impl SepData { profile::Bootstrap::Boot => true, profile::Bootstrap::WarmRegister => false, }; - let xart_setup = xart_guard::setup(cold, *module_parameters::xart_guard_pins.value()); + let xart_setup = xart_guard::setup( + cold, + *module_parameters::xart_guard_pins.value(), + profile::machine_has, + ); let store = match xart_store::Store::open_owner(xart_writes, xart_start) { Ok(mut store) => { match xart_guard { @@ -2661,16 +2665,18 @@ impl platform::Driver for SepDriver { // As soon as the fixed facts are known, so a tool can watch the attach // from "pending" on. Diagnostics are not worth failing the probe for. let guard = data.with_store(|store| store.guard_state()).flatten(); - let guarded_setup = data - .with_store(|store| store.guarded_setup()) - .unwrap_or(false); - if let Err(e) = diag::register( - dev, - data.profile, - data.xart_writable(), - guard, - guarded_setup, - ) { + let keybag = if matches!(guard, Some((_, _, true))) { + match keybag::read(keybag::Slot::Identity) { + Ok(keybag::State::Present(bag)) => { + data.with_store(|store| store.keybag_evidence(bag.uuid())) + } + _ => None, + } + } else { + None + } + .unwrap_or_default(); + if let Err(e) = diag::register(dev, data.profile, data.xart_writable(), guard, keybag) { dev_warn!(dev, "diag: could not add the sysfs attributes ({:?})\n", e); } @@ -2768,7 +2774,10 @@ module! { }, xart_guard_pins: u8 { default: 0, - description: "On a Mac that cold-boots its SEP (M1 family; run on a J313 only) at xart_guard=1: 1 lets the enclave rewrite the SEP-xART lockers from before Linux (up to three, read this boot) that this install's first Touch ID setup rewrites, from the keybag creation to the first activation, then and afterwards, while every other record stays guarded; 0: that rewrite is refused", + description: "At xart_guard=1, allow rewrites of previously read SEP-xART lockers \ + pinned by this install. J314s/J316s/J316c may pin one during \ + provisioning. J313 may pin two during provisioning and one during its \ + first activation. J293 may reuse existing pins. 0 disables pins.", }, os_uuid_hi: u64 { default: 0, diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 6ae053f5ac2322..f336a19bf07c49 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -173,6 +173,7 @@ int sep_sensor_irq_wait(unsigned int timeout_ms); #define SEP_DIAG_MATCHING_USABLE 1 #define SEP_DIAG_MATCHING_UNVERIFIED 2 #define SEP_DIAG_MATCHING_BLOCKED 3 +#define SEP_DIAG_MATCHING_LEGACY 4 struct device; @@ -190,9 +191,10 @@ void sep_diag_set_touchid(bool started); void sep_diag_set_sensor_attach(int state); void sep_diag_set_restore(int state); void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, - int matching); + bool pins, int matching); void sep_diag_set_matching(int matching); -void sep_diag_xart_guard_refused(int matching); +void sep_diag_xart_guard_refused(void); +void sep_diag_verified_match(void); void sep_diag_bringup_ended(void); /* -- bio_shim.c --------------------------------------------------------- */ diff --git a/drivers/soc/apple/shim.rs b/drivers/soc/apple/shim.rs index 8e30c3f54b8177..e4fecc6064ddc6 100644 --- a/drivers/soc/apple/shim.rs +++ b/drivers/soc/apple/shim.rs @@ -81,11 +81,9 @@ impl StoreFile { } pub(crate) fn open_readonly(path: &CStr) -> Result { - // SAFETY: `path` is NUL-terminated; the shim returns NULL on failure. - let handle = unsafe { sep_store_open_ro(path.as_char_ptr()) }; - if handle.is_null() { - return Err(ENOENT); - } + // SAFETY: `path` is NUL-terminated; the shim returns a live file + // or the original error pointer from the VFS. + let handle = unsafe { kernel::error::from_err_ptr(sep_store_open_ro(path.as_char_ptr()))? }; Ok(StoreFile { handle }) } diff --git a/drivers/soc/apple/sks.rs b/drivers/soc/apple/sks.rs index 460e25cc38dca2..e7a02593dba406 100644 --- a/drivers/soc/apple/sks.rs +++ b/drivers/soc/apple/sks.rs @@ -16,15 +16,14 @@ struct KeybagCreateIntent<'a> { impl<'a> KeybagCreateIntent<'a> { fn new(dev: &'a device::Device, slot: keybag::Slot) -> Option { + // On a failed pre-send write or directory sync the drop guard can + // still mark the attempt refused: no create was sent. + let intent = Self { dev, slot, sent: false }; if let Err(e) = keybag::write_intent(slot) { dev_err!(dev, "sks: cannot persist keybag-create intent: {:?}\n", e); return None; } - Some(Self { - dev, - slot, - sent: false, - }) + Some(intent) } fn sending(&mut self) { @@ -55,8 +54,8 @@ pub(crate) struct SetupWindow<'a> { } impl<'a> SetupWindow<'a> { - /// The first activation's hold on a window provisioning may have left - /// open; closing a shut window does nothing. + /// Discard the one-shot activation allowance on every return, including + /// failures before the keybag is loaded. pub(crate) fn for_activation(sep: &'a SepData) -> Self { SetupWindow { sep, open: true } } @@ -67,10 +66,28 @@ impl<'a> SetupWindow<'a> { } } - /// Hands the window to the first activation, which closes it when it - /// returns (`activate_touchid`). Only a pinning window is still open here. - fn leave_open_for_activation(mut self) { - self.open = false; + /// Stop admitting provisioning pins as soon as COPY_KEYBAG returns. + fn end_copy(&self) { + if self.open { + self.sep.with_store(|store| store.end_copy()); + } + } + + /// The keybag has been committed. Keep J313's dormant allowance for + /// activation of that same bag. All other boards have finished. + fn provisioned(mut self, uuid: &[u8; 16]) -> Result<()> { + if self.open { + if self + .sep + .with_store(|store| store.commit_keybag(uuid)) + .transpose()? + == Some(true) + { + crate::diag::xart_guard_keybag_committed(); + } + self.open = false; + } + Ok(()) } } @@ -721,10 +738,6 @@ impl SepData { return false; } }; - if first_setup { - // The create is sent under the guard: matching follows. - crate::diag::xart_guard_setup_recorded(); - } let window = SetupWindow { sep: self, open: first_setup, @@ -810,6 +823,7 @@ impl SepData { dev_err!(self.dev, "sks: COPY_KEYBAG of the new identity keybag got no reply\n"); return false; }; + window.end_copy(); let Some(wrapped) = self.wrapped_from_copy_reply(&out, c"new identity keybag") else { dev_err!( self.dev, @@ -828,7 +842,10 @@ impl SepData { return false; } let _ = self.sks_send(self.sks_req_unload_keybag(handle)); - window.leave_open_for_activation(); + if let Err(e) = window.provisioned(bag_uuid.as_ref().unwrap_or(&uuid)) { + dev_err!(self.dev, "sks: could not record guarded keybag commit ({:?})\n", e); + return false; + } dev_info!(self.dev, "sks: identity keybag provisioned\n"); true } diff --git a/drivers/soc/apple/store_shim.c b/drivers/soc/apple/store_shim.c index 0eabe7305b0497..1d1cdbc79a9543 100644 --- a/drivers/soc/apple/store_shim.c +++ b/drivers/soc/apple/store_shim.c @@ -81,14 +81,12 @@ void *sep_store_open_trunc(const char *path) } /* - * Opens an existing file read-only, NULL if absent. O_RDONLY and no O_CREAT so - * the seed cannot be created, truncated or written by mistake. + * Opens an existing file read-only. Preserve errors: only -ENOENT proves + * that the path is absent and allows creation of a new identity keybag. */ void *sep_store_open_ro(const char *path) { - struct file *f = open_as_kernel(path, O_RDONLY | O_LARGEFILE, 0); - - return IS_ERR(f) ? NULL : f; + return open_as_kernel(path, O_RDONLY | O_LARGEFILE, 0); } void *sep_store_open_block(const char *path, int writable) diff --git a/drivers/soc/apple/xart_guard.rs b/drivers/soc/apple/xart_guard.rs index e90cb7f38f2a52..1aed4bcffeea31 100644 --- a/drivers/soc/apple/xart_guard.rs +++ b/drivers/soc/apple/xart_guard.rs @@ -45,24 +45,12 @@ //! locker as Linux's, and the list records the window as consumed before it //! opens, so no later create on this install gets it again. //! -//! A cold-boot Mac cannot stay inside the rule. Its first Touch ID setup -//! rewrites session records from before Linux that the enclave reads at every -//! attach and that belong to no single OS: on a MacBook Air M1 (J313) three -//! SEP-xART lockers, two at the `COPY_KEYBAG` after the create and one during the -//! first activation, after its `LOAD_KEYBAG`. The guard refuses them, so such a Mac -//! needs the guard off, which leaves every record open to the enclave. With -//! `xart_guard_pins=1` (run on a J313 only) the owner accepts those lockers -//! instead -//! ([`Setup::Pin`]). The first-setup window then opens on a cold-boot Mac and -//! stays open from the create until the first activation returns, closing -//! on any failed step before it. Each existing kind-4 locker the enclave -//! rewrites in it, provided the enclave read it since probe, is recorded in -//! the list as pinned before the write lands, up to [`MAX_PINS`]. From then on -//! the enclave may rewrite a pinned locker on any boot on which the parameter -//! is set and it has read the locker. A pinned locker is never deleted and -//! never listed as Linux's, and every other record from before Linux stays -//! refused. Without the parameter a cold-boot Mac gets no window and its pins -//! are not honoured. +//! Cold-boot Macs may also need to rewrite existing SEP-xART lockers. With +//! `xart_guard_pins=1`, the board's policy limits how many kind-4 lockers the +//! enclave may pin during provisioning and first activation. Each must have +//! been read since probe. Neither the interval between those operations nor a +//! later boot can admit a new pin. A stored pin permits rewriting the same +//! locker after a read, never deleting or adopting it. See XART-SAFETY.md. use crate::shim::StoreFile; use crate::xart_store::{crc32_ieee, Key}; @@ -84,13 +72,14 @@ const LOGGED_REFUSALS: usize = 8; /// three bytes an owned entry keeps zero, so a kernel without pinning reads /// the entry as unreadable and lists nothing by it. const ENTRY_PINNED: u8 = 1; +/// A completion entry identifying the committed guarded keybag by UUID. +const ENTRY_SETUP_UUID: u8 = 2; /// SEP-xART lockers the enclave read since probe that a pinning guard /// remembers. The gigalocker has at most a few hundred slots; a locker past /// the bound counts as unread. const MAX_READ: usize = 512; -/// Pre-Linux lockers one install may pin. On a MacBook Air M1 (J313, 13.5 sepOS) -/// the first setup rewrites three, all read since probe: two at COPY_KEYBAG, -/// one during the first activation, after its LOAD_KEYBAG. +/// Maximum pins supported by the list format. Admission is board- and +/// operation-specific, and can be lower or zero. const MAX_PINS: usize = 3; /// What the guard does with one enclave write or delete. @@ -121,25 +110,31 @@ pub(crate) fn decide(level: u8, key: &Key, existed: bool, owned: bool) -> Verdic } } -/// Whether a fresh install's first setup window is open: during the keybag -/// creation on a warm-attach Mac; under `xart_guard_pins` on a cold-boot Mac, -/// from the create until the first activation returns. +/// The only states that admit new shared lockers are Open and Activating. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum FirstSetup { - /// No first keybag creation is in progress. Closed, - /// The enclave may rewrite an existing SEP-xART locker: one on a - /// warm-attach Mac, up to [`MAX_PINS`] under `xart_guard_pins`. + /// The creation/provisioning operation is running. Open, - /// It has, as many as allowed; further refusals stand. + /// Provisioning has already used its allowance. Used, + /// COPY_KEYBAG returned. Only a successful host keybag commit can arm activation. + Copied, + /// J313 completed provisioning this boot. No new locker may be pinned + /// while waiting for someone to open the biometric device. + AwaitingActivation, + /// The driver is recovering and activating the provisioned J313 keybag. + Activating, } /// Whether a request the guard would refuse passes as the enclave committing a /// pending SEP-xART locker during the first keybag creation: a rewrite (not a /// delete) of a kind-4 record at level 1, while the window is open. pub(crate) fn first_setup_allows(level: u8, window: FirstSetup, key: &Key, write: bool) -> bool { - level == 1 && window == FirstSetup::Open && write && key.kind == 4 + level == 1 + && matches!(window, FirstSetup::Open | FirstSetup::Activating) + && write + && key.kind == 4 } /// What an install's first keybag creation may do to a locker from before @@ -150,20 +145,51 @@ pub(crate) enum Setup { Commit, /// Cold boot: nothing. The create's rewrite is refused. Refuse, - /// Cold boot with `xart_guard_pins=1`: pin each SEP-xART locker the first - /// setup rewrites, up to [`MAX_PINS`], which the enclave may then rewrite - /// again. - Pin, + /// J314s, J316s and J316c: one observed provisioning locker. + PinOne, + /// J313: two observed provisioning lockers and one in the first activation. + PinJ313, + /// J293 has a successful run but no measured count. Preserve existing + /// pins under opt-in without enrolling any more. + ExistingPins, } -/// The first-setup rule for a platform that cold-boots its enclave (`cold`) -/// or attaches to a running one, with `xart_guard_pins=pin`. The parameter -/// changes nothing on a warm-attach Mac. -pub(crate) fn setup(cold: bool, pin: u8) -> Setup { - match (cold, pin) { - (false, _) => Setup::Commit, - (true, 0) => Setup::Refuse, - (true, _) => Setup::Pin, +impl Setup { + fn pin_limit(self) -> usize { + match self { + Self::PinOne => 1, + Self::PinJ313 | Self::ExistingPins => MAX_PINS, + Self::Commit | Self::Refuse => 0, + } + } + + fn provisioning_pins(self) -> usize { + match self { + Self::PinOne => 1, + Self::PinJ313 => 2, + _ => 0, + } + } +} + +/// Select by the board in the root compatible list, not its shared SoC +/// profile. Unknown boards and other parameter values get no exception. +pub(crate) fn setup(cold: bool, pin: u8, machine_has: impl Fn(&[u8]) -> bool) -> Setup { + if !cold { + Setup::Commit + } else if pin != 1 { + Setup::Refuse + } else if machine_has(b"apple,j313") { + Setup::PinJ313 + } else if machine_has(b"apple,j314s") + || machine_has(b"apple,j316s") + || machine_has(b"apple,j316c") + { + Setup::PinOne + } else if machine_has(b"apple,j293") { + Setup::ExistingPins + } else { + Setup::Refuse } } @@ -189,13 +215,27 @@ pub(crate) fn level(param: i8, platform: u8) -> Option { /// as the driver can tell. The values are `SEP_DIAG_MATCHING_*` in `shim.h`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Matching { - /// xART writes are enabled and no guard runs. + /// Unguarded writes are enabled, or a legacy guarded match succeeded this boot. Usable = 1, /// A guard runs and nothing says it refuses a match, but nothing says it /// allows one either. Unverified = 2, /// A match's write is refused, or known to be. Blocked = 3, + /// A validated keybag and a prior driver's pins exist. A live match + /// must establish this boot's ability to save the result. + Legacy = 4, +} + +/// Evidence about the identity bag committed on the host. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum KeybagEvidence { + #[default] + Unknown, + /// The prior driver recorded pins without identifying the created bag. + Legacy, + /// The guarded commit and the persisted bag have the same UUID. + Committed, } /// What [`Matching`] is derived from. @@ -205,37 +245,29 @@ pub(crate) struct MatchFacts { pub(crate) xart_writable: bool, /// The platform cold-boots its enclave. pub(crate) cold: bool, - /// This install's first keybag creation was sent under the guard, as far - /// as the guard's list says (see [`Guard::guarded_setup`]). - pub(crate) guarded_setup: bool, + /// What the list establishes about the validated, persisted identity bag. + pub(crate) keybag: KeybagEvidence, /// The guard's effective level and whether its list loaded, or `None` /// when no guard runs. pub(crate) guard: Option<(u8, bool)>, - /// The guard's refusals since probe. - pub(crate) refusals: u32, } impl MatchFacts { - /// A match rewrites session records that existed before it (seen on a - /// T6000). It is blocked when xART is read-only, once the guard has - /// refused anything, when the guard has no list to allow Linux's records - /// by, and on a cold-boot Mac whose keybag was not created under the - /// guard: creating it there needs the guard off unless the owner set - /// `xart_guard_pins`, and with the guard off the records a match rewrites - /// were never listed. - /// - /// Nothing else proves an unguarded setup. An empty list in particular - /// does not: a guarded keybag creation on an M2 writes no record, and a - /// rollback can empty the list. So a guarded warm-attach Mac is - /// unverified until a refusal says otherwise, and so is a cold-boot Mac - /// set up under `xart_guard_pins`: which records a match rewrites there - /// has not been established either. + /// A match may rewrite existing session records. On a cold-boot Mac the + /// initial diagnostic needs evidence for the persisted identity. A + /// successful guarded commit establishes its origin. A legacy pin list + /// can instead qualify for an actual verification of restored fingers. + /// The sysfs read gives any later refusal precedence over this base state. pub(crate) fn matching(&self) -> Matching { match self.guard { - _ if !self.xart_writable || self.refusals != 0 => Matching::Blocked, + _ if !self.xart_writable => Matching::Blocked, None => Matching::Usable, Some((_, false)) => Matching::Blocked, - Some(_) if self.cold && !self.guarded_setup => Matching::Blocked, + Some(_) if self.cold => match self.keybag { + KeybagEvidence::Committed => Matching::Unverified, + KeybagEvidence::Legacy => Matching::Legacy, + KeybagEvidence::Unknown => Matching::Blocked, + }, Some(_) => Matching::Unverified, } } @@ -262,16 +294,32 @@ pub(crate) fn setup_consumed() -> [u8; ENTRY_SIZE] { entry_bytes(0, b"first setup used") } -/// Encodes the entry that pins `key`, a SEP-xART locker from before Linux. -/// [`decode`] reads it as no record, so it lists nothing as Linux's. -pub(crate) fn encode_pin(key: &Key) -> [u8; ENTRY_SIZE] { - let mut entry = entry_bytes(key.kind, &key.uuid); - entry[5] = ENTRY_PINNED; +/// Distinguish a new cold provisioning attempt from the previous driver's +/// spent marker. An interrupted new attempt must never be mistaken for a +/// legacy installation, even if provisioning had already pinned a locker. +fn cold_setup_consumed() -> [u8; ENTRY_SIZE] { + entry_bytes(0, b"cold setup spent") +} + +/// A tagged entry is never decoded as Linux ownership, including by older drivers. +fn tagged_entry(kind: u8, role: u8, uuid: &[u8; 16]) -> [u8; ENTRY_SIZE] { + let mut entry = entry_bytes(kind, uuid); + entry[5] = role; let crc = crc32_ieee(&entry[..24]); entry[24..28].copy_from_slice(&crc.to_le_bytes()); entry } +pub(crate) fn encode_pin(key: &Key) -> [u8; ENTRY_SIZE] { + tagged_entry(key.kind, ENTRY_PINNED, &key.uuid) +} + +/// Appended after the guarded keybag is committed on disk. Older drivers +/// still see a nonempty list and skip this entry. +fn committed_keybag(uuid: &[u8; 16]) -> [u8; ENTRY_SIZE] { + tagged_entry(0, ENTRY_SETUP_UUID, uuid) +} + /// The kind, the three bytes after it and the session id of a whole entry /// with the list's magic and a good CRC; `None` for a torn or foreign one. fn parse(entry: &[u8]) -> Option<(u8, [u8; 3], [u8; 16])> { @@ -289,7 +337,8 @@ fn parse(entry: &[u8]) -> Option<(u8, [u8; 3], [u8; 16])> { /// Decodes a pin entry; `None` for anything else, a pin of a record that is /// not a SEP-xART locker included. -pub(crate) fn decode_pin(entry: &[u8]) -> Option { +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +fn decode_pin(entry: &[u8]) -> Option { match parse(entry)? { (4, [ENTRY_PINNED, 0, 0], uuid) => Some(Key::new(4, uuid)), _ => None, @@ -349,16 +398,18 @@ pub(crate) struct Guard { first_setup: FirstSetup, /// What the first-setup window may do on this platform. setup: Setup, - /// The list holds the first-setup window's record, from this boot or an - /// earlier one. - setup_recorded: bool, - /// The SEP-xART lockers from before Linux that the list pins, up to - /// [`MAX_PINS`]. They are honoured only under [`Setup::Pin`]. + /// UUID saved after the guarded keybag commit. A spent marker alone + /// establishes no identity. + setup_uuid: Option<[u8; 16]>, + /// A complete older list starts with the original spent marker. + legacy_setup: bool, + /// Remember old pins even when their use is disabled, so an absent + /// pinned locker cannot be adopted as a new Linux record. pinned: [Option; MAX_PINS], /// Rewrites of pinned lockers let through since probe. pinned_writes: usize, /// The SEP-xART lockers the enclave read since probe, kept only under - /// [`Setup::Pin`]. + /// a board's effective pin policy. read: KVec, } @@ -389,7 +440,8 @@ impl Guard { refused: 0, first_setup: FirstSetup::Closed, setup, - setup_recorded: false, + setup_uuid: None, + legacy_setup: false, pinned: [None; MAX_PINS], pinned_writes: 0, read: KVec::new(), @@ -406,7 +458,8 @@ impl Guard { // no pin and no spent window from an unreadable list. guard.owned = KVec::new(); guard.pinned = [None; MAX_PINS]; - guard.setup_recorded = false; + guard.setup_uuid = None; + guard.legacy_setup = false; guard.end = 0; pr_warn!( "xART guard: the list of Linux's records is unreadable ({:?}); every existing session record is protected and none can be adopted\n", @@ -454,40 +507,34 @@ impl Guard { /// Says what `xart_guard_pins` and a pinned locker come to on this boot. fn announce_pin(&self) { - let honoured = self.setup == Setup::Pin && self.level == 1; - match (honoured, self.pinned[0]) { - (true, Some(_)) => { - for key in self.pinned.iter().flatten() { - pr_info!( - "xART guard: xart_guard_pins is set: the enclave may rewrite this install's pinned SEP-xART locker (tag {:08x}) once it has read it\n", - tag(key) - ); - } + if self.pins_enabled() { + for key in self.pinned.iter().flatten() { + pr_info!( + "xART guard: existing SEP-xART pin (tag {:08x}) permits rewrites after a read this boot\n", + tag(key) + ); } - (true, None) if self.list_empty() => pr_info!( - "xART guard: xart_guard_pins is set and no locker is pinned: this install's first Touch ID setup may pin up to three\n" - ), - // The window that pins a locker opens only on an empty list, so - // an earlier guarded attempt on this install shuts it for good. - (true, None) => pr_warn!( - "xART guard: xart_guard_pins is set, but no locker is pinned and the list of Linux's records is not empty or did not load: the first-setup window stays shut and a keybag creation's rewrite is refused. Reset Touch ID with the list removed to set up under xart_guard_pins\n" - ), - (false, Some(_)) => { - for key in self.pinned.iter().flatten() { - pr_info!( - "xART guard: this install pinned a SEP-xART locker (tag {:08x}), which counts only with xart_guard_pins=1 at level 1: rewrites of it are refused\n", - tag(key) - ); - } + if self.list_empty() { + pr_info!( + "xART guard: first provisioning may pin up to {} observed SEP-xART lockers on this board\n", + self.setup.provisioning_pins() + ); } - (false, None) if self.setup == Setup::Pin => pr_info!( - "xART guard: xart_guard_pins has no effect at level {}\n", - self.level - ), - (false, None) => {} + } else if self.pinned[0].is_some() { + pr_info!("xART guard: stored SEP-xART pins are protected on this boot\n"); } } + /// What a loader can rely on from the running guard. On J293 the opt-in + /// only preserves a previously populated pin list. + pub(crate) fn pins_enabled(&self) -> bool { + self.level == 1 + && self.file.is_some() + && self.setup.pin_limit() != 0 + && (self.setup != Setup::ExistingPins || self.pinned[0].is_some()) + && self.pin_count() <= self.setup.pin_limit() + } + fn load(&mut self, file: &F) -> Result<()> { let size = file.size()?; let whole = (size as usize / ENTRY_SIZE).min(MAX_ENTRIES + 1); @@ -495,33 +542,41 @@ impl Guard { return Err(EFBIG); } let mut torn = 0usize; - let mut extra_pins = 0usize; + let mut consumed = false; let mut entry = [0u8; ENTRY_SIZE]; for i in 0..whole { file.read_exact((i * ENTRY_SIZE) as u64, &mut entry)?; match decode(&entry) { Some(key) if !self.owned.contains(&key) => self.owned.push(key, GFP_KERNEL)?, Some(_) => {} - None if entry == setup_consumed() => self.setup_recorded = true, - None => match decode_pin(&entry) { - // At most MAX_PINS lockers per install: the first-setup - // window pins them, and that window opens once. - Some(key) if !self.is_pinned(&key) && !self.pins_full() => self.add_pin(key), - Some(_) => extra_pins += 1, - None => torn += 1, + None if i == 0 && entry == setup_consumed() => self.legacy_setup = true, + None if i == 0 && entry == cold_setup_consumed() => consumed = true, + None => match parse(&entry) { + Some((0, [ENTRY_SETUP_UUID, 0, 0], uuid)) if consumed => { + if self.setup_uuid.replace(uuid).is_some() { + return Err(EINVAL); + } + } + Some((4, [ENTRY_PINNED, 0, 0], uuid)) => { + let key = Key::new(4, uuid); + if !self.is_pinned(&key) { + // An omitted pin could be adopted if absent at probe. + if self.pin_count() == MAX_PINS { + return Err(EINVAL); + } + self.add_pin(key); + } + } + _ => torn += 1, }, } } + if torn != 0 || size % ENTRY_SIZE as u64 != 0 { + self.legacy_setup = false; + } if torn != 0 { pr_warn!("xART guard: ignored {} unreadable list entries\n", torn); } - if extra_pins != 0 { - pr_warn!( - "xART guard: ignored {} pin entries past the first {} or repeated\n", - extra_pins, - MAX_PINS - ); - } // A torn tail entry is overwritten by the next adoption. self.end = (whole * ENTRY_SIZE) as u64; Ok(()) @@ -537,31 +592,65 @@ impl Guard { self.file.is_some() } - /// The create exchange is over. Only a pinning window outlasts it, to the - /// end of the first activation: on a J313 the enclave rewrites the shared - /// lockers at COPY_KEYBAG and after the activation's LOAD_KEYBAG, not at - /// the create. + /// The warm-attach exception ends with CREATE_KEYBAG. Cold boards can + /// also need the following COPY_KEYBAG. pub(crate) fn end_create(&mut self) { - if self.setup != Setup::Pin { + if self.setup == Setup::Commit { self.close_first_setup(); } } - /// Whether this install's first keybag creation was sent under the guard, - /// as far as the list says: the list loaded and records the first-setup - /// window, on a platform that has one. A cold-boot Mac has one only - /// under `xart_guard_pins`, so without the parameter this is `false` there - /// whatever the list holds. - pub(crate) fn guarded_setup(&self) -> bool { - self.file.is_some() && self.setup_recorded && self.setup != Setup::Refuse + /// Stop admitting new pins before the host validates or writes the bag. + pub(crate) fn end_copy(&mut self) { + if matches!(self.first_setup, FirstSetup::Open | FirstSetup::Used) { + self.first_setup = FirstSetup::Copied; + } + } + + /// Called only after the host committed the keybag. A crash before this + /// entry leaves the window spent and the diagnostic pessimistic. + pub(crate) fn commit_keybag(&mut self, uuid: &[u8; 16]) -> Result { + if self.first_setup != FirstSetup::Copied || !self.pins_enabled() { + return Ok(false); + } + self.close_first_setup(); + self.append(&committed_keybag(uuid))?; + self.setup_uuid = Some(*uuid); + if self.setup == Setup::PinJ313 && self.pin_count() == self.setup.provisioning_pins() { + self.first_setup = FirstSetup::AwaitingActivation; + } + Ok(true) + } + + pub(crate) fn begin_activation(&mut self, uuid: &[u8; 16]) { + self.first_setup = if self.first_setup == FirstSetup::AwaitingActivation + && self.keybag_evidence(uuid) == KeybagEvidence::Committed + { + FirstSetup::Activating + } else { + FirstSetup::Closed + }; + } + + /// A caller must supply the UUID of a validated, committed host keybag. + pub(crate) fn keybag_evidence(&self, uuid: &[u8; 16]) -> KeybagEvidence { + if !self.pins_enabled() { + KeybagEvidence::Unknown + } else if self.setup_uuid.as_ref() == Some(uuid) { + KeybagEvidence::Committed + } else if self.legacy_setup && self.pinned[0].is_some() { + KeybagEvidence::Legacy + } else { + KeybagEvidence::Unknown + } } /// Notes that the enclave was handed the record under `key` since probe. - /// Only SEP-xART lockers are kept, and only under [`Setup::Pin`], whose + /// Only SEP-xART lockers are kept, and only for pin policies, whose /// allowances ask for it. A locker that cannot be kept counts as unread, /// which they refuse. pub(crate) fn note_read(&mut self, key: &Key) { - if self.setup != Setup::Pin + if !self.pins_enabled() || key.kind != 4 || self.read.contains(key) || self.read.len() >= MAX_READ @@ -575,11 +664,11 @@ impl Guard { /// on a fresh install: the list loaded and holding no entry, torn ones /// included. A cold-boot Mac has no window unless the owner set /// `xart_guard_pins`. The window is recorded as consumed in the list, - /// durably, before it opens, so it opens at most once per install whatever - /// becomes of the keybag. `Ok(false)` when the install is not eligible; an + /// durably, before it opens, so it opens at most once for this list + /// whatever becomes of the keybag. `Ok(false)` when the install is not eligible; an /// error, with the window shut, when the record could not be made durable. pub(crate) fn open_first_setup(&mut self) -> Result { - if self.level != 1 || self.setup == Setup::Refuse { + if self.level != 1 || (self.setup != Setup::Commit && self.setup.provisioning_pins() == 0) { return Ok(false); } let Some(file) = self.file.as_ref() else { @@ -587,16 +676,18 @@ impl Guard { }; // The file's length, not `end`: a torn first entry rounds `end` down // to 0 but is still an earlier setup. - if !file.size().is_ok_and(|size| size == 0) { + if self.end != 0 || !file.size().is_ok_and(|size| size == 0) { return Ok(false); } // The list's directory entry was flushed when it was opened. A failed // write or flush leaves `end` at 0, so an adoption overwrites the // slot, and any bytes that survive keep the window shut. - file.write_all(0, &setup_consumed())?; - file.sync()?; - self.end = ENTRY_SIZE as u64; - self.setup_recorded = true; + let marker = if self.setup == Setup::Commit { + setup_consumed() + } else { + cold_setup_consumed() + }; + self.append(&marker)?; self.first_setup = FirstSetup::Open; Ok(true) } @@ -606,47 +697,32 @@ impl Guard { self.first_setup = FirstSetup::Closed; } - fn adopt(&mut self, key: &Key) -> Result<()> { + /// Advance the cursor only after the entry is durable. A failed write or + /// sync is retried in the same slot; the file never exceeds the read limit. + fn append(&mut self, entry: &[u8; ENTRY_SIZE]) -> Result<()> { let file = self.file.as_ref().ok_or(ENOENT)?; - // The file's length, not the number of distinct keys: a torn or - // repeated entry still counts against what load() accepts. - if usize::try_from(self.end).map_or(true, |end| end / ENTRY_SIZE >= MAX_ENTRIES) { + if self.end / ENTRY_SIZE as u64 >= MAX_ENTRIES as u64 { return Err(ENOSPC); } - // Reserve room for the in-memory key before writing, so an entry made - // durable is always listed in memory as well: no allocation can fail - // after a record is written. - self.owned.reserve(1, GFP_KERNEL)?; - file.write_all(self.end, &encode(key))?; + file.write_all(self.end, entry)?; file.sync()?; - // Only now that the entry is written and flushed: list it (into the - // reserved slot, which cannot fail) and then advance the end. A failed - // write or flush above leaves the end unchanged, so the next adoption - // overwrites this slot, which holds no record the enclave kept. - self.owned.push_within_capacity(*key).map_err(|_| ENOMEM)?; self.end += ENTRY_SIZE as u64; Ok(()) } - /// Records `key` as one of this install's pinned lockers, durably, before the - /// enclave's rewrite of it is let through. + fn adopt(&mut self, key: &Key) -> Result<()> { + // Reserve before making the entry durable. + self.owned.reserve(1, GFP_KERNEL)?; + self.append(&encode(key))?; + self.owned.push_within_capacity(*key).map_err(|_| ENOMEM) + } + fn pin(&mut self, key: &Key) -> Result<()> { - if self.pins_full() { + if self.pin_count() >= self.setup.pin_limit() { return Err(ENOSPC); } - let file = self.file.as_ref().ok_or(ENOENT)?; - // As in adopt(): the file's length is what load() accepts. - if usize::try_from(self.end).map_or(true, |end| end / ENTRY_SIZE >= MAX_ENTRIES) { - return Err(ENOSPC); - } - file.write_all(self.end, &encode_pin(key))?; - file.sync()?; - // Only now that the entry is written and flushed. A failed write or - // flush leaves the end unchanged, so the next entry overwrites the - // slot, and a pin that survives there names the locker the owner's - // parameter was about to allow. + self.append(&encode_pin(key))?; self.add_pin(*key); - self.end += ENTRY_SIZE as u64; Ok(()) } @@ -654,8 +730,8 @@ impl Guard { self.pinned.iter().any(|pin| *pin == Some(*key)) } - fn pins_full(&self) -> bool { - self.pinned.iter().all(Option::is_some) + fn pin_count(&self) -> usize { + self.pinned.iter().flatten().count() } fn add_pin(&mut self, key: Key) { @@ -669,11 +745,7 @@ impl Guard { /// `xart_guard_pins` at level 1, a rewrite (not a delete) of a locker the /// list pins, once the enclave has read it since probe. fn pinned_allows(&self, key: &Key, write: bool) -> bool { - self.setup == Setup::Pin - && self.level == 1 - && write - && self.is_pinned(key) - && self.read.contains(key) + self.pins_enabled() && write && self.is_pinned(key) && self.read.contains(key) } /// Checks one enclave write (`write`) or delete before it reaches the @@ -682,7 +754,7 @@ impl Guard { let existed = self.existed.contains(key); let owned = self.owned.contains(key); // A pinned locker is never adopted as Linux's, even one absent at probe. - let verdict = if self.is_pinned(key) && !owned { + let verdict = if self.is_pinned(key) { Verdict::Refuse } else { decide(self.level, key, existed, owned) @@ -711,7 +783,7 @@ impl Guard { // Under xart_guard_pins the window passes only a locker the // enclave read since probe, and pins it before the write lands. Verdict::Refuse - if self.setup == Setup::Pin + if self.pins_enabled() && first_setup_allows(self.level, self.first_setup, key, write) && self.read.contains(key) => { @@ -722,8 +794,9 @@ impl Guard { e ) })?; - // The window stays open for the setup's other read lockers. - if self.pins_full() { + if self.first_setup == FirstSetup::Activating { + self.close_first_setup(); + } else if self.pin_count() >= self.setup.provisioning_pins() { self.first_setup = FirstSetup::Used; } pr_info!( @@ -756,7 +829,7 @@ impl Guard { // Under xart_guard_pins, which locker and whether the // enclave had read it tell the refusals apart: the // pinned lockers before a read, or another one. - if self.setup == Setup::Pin && key.kind == 4 { + if self.pins_enabled() && key.kind == 4 { let read = if self.read.contains(key) { "read" } else { @@ -767,19 +840,6 @@ impl Guard { tag(key), read ); - if write - && self.level == 1 - && self.read.contains(key) - && self.setup_recorded - && self.first_setup == FirstSetup::Closed - && !self.pins_full() - { - pr_warn!( - "xART guard: this install's first-setup window is spent with {} of {} lockers pinned, so this rewrite stays refused and Touch ID may fail. If the first setup did not reach Touch ID's first activation, set up again: install-aurora-sep.sh --reset-touchid --force, then remove /var/lib/aurora-sep-xart-owned.bin, which the reset keeps (Linux's earlier records are then treated as another OS's)\n", - self.pinned.iter().flatten().count(), - MAX_PINS - ); - } } } Err(EPERM) @@ -810,39 +870,29 @@ mod tests { } } + const BAG: [u8; 16] = [0x42; 16]; + fn session(byte: u8) -> Key { Key::new(4, [byte; 16]) } - fn facts( - xart_writable: bool, - cold: bool, - guard: Option<(u8, bool)>, - refusals: u32, - ) -> Matching { + fn facts(xart_writable: bool, cold: bool, guard: Option<(u8, bool)>) -> Matching { MatchFacts { xart_writable, cold, - guarded_setup: false, + keybag: KeybagEvidence::Unknown, guard, - refusals, } .matching() } /// As [`facts`], on a Mac whose first keybag creation ran under the guard. - fn facts_after_setup( - xart_writable: bool, - cold: bool, - guard: Option<(u8, bool)>, - refusals: u32, - ) -> Matching { + fn facts_after_setup(xart_writable: bool, cold: bool, guard: Option<(u8, bool)>) -> Matching { MatchFacts { xart_writable, cold, - guarded_setup: true, + keybag: KeybagEvidence::Committed, guard, - refusals, } .matching() } @@ -850,16 +900,16 @@ mod tests { #[test] fn matching_without_a_guard_is_usable() { // The Neo (warm, level 0) and an M1 Pro pinned to xart_guard=0 (cold). - assert_eq!(facts(true, false, None, 0), Matching::Usable); - assert_eq!(facts(true, true, None, 0), Matching::Usable); + assert_eq!(facts(true, false, None), Matching::Usable); + assert_eq!(facts(true, true, None), Matching::Usable); } #[test] fn matching_under_a_listed_warm_guard_is_unverified() { // An M2 set up under the guard. An empty list is still "loaded", and // does not make the setup unguarded. - assert_eq!(facts(true, false, Some((1, true)), 0), Matching::Unverified); - assert_eq!(facts(true, false, Some((2, true)), 0), Matching::Unverified); + assert_eq!(facts(true, false, Some((1, true))), Matching::Unverified); + assert_eq!(facts(true, false, Some((2, true))), Matching::Unverified); } #[test] @@ -867,39 +917,33 @@ mod tests { // Set up under the guard with xart_guard_pins: unverified, as a // warm-attach Mac is. assert_eq!( - facts_after_setup(true, true, Some((1, true)), 0), + facts_after_setup(true, true, Some((1, true))), Matching::Unverified ); // The fact changes nothing on a warm-attach Mac, or without a guard. assert_eq!( - facts_after_setup(true, false, Some((1, true)), 0), + facts_after_setup(true, false, Some((1, true))), Matching::Unverified ); - assert_eq!(facts_after_setup(true, true, None, 0), Matching::Usable); + assert_eq!(facts_after_setup(true, true, None), Matching::Usable); // What blocks any Mac still blocks this one. assert_eq!( - facts_after_setup(true, true, Some((1, true)), 1), - Matching::Blocked - ); - assert_eq!( - facts_after_setup(true, true, Some((1, false)), 0), + facts_after_setup(true, true, Some((1, false))), Matching::Blocked ); - assert_eq!(facts_after_setup(false, true, None, 0), Matching::Blocked); + assert_eq!(facts_after_setup(false, true, None), Matching::Blocked); } #[test] fn matching_is_blocked_where_it_is_known_to_be() { // A cold-boot M1-family Mac under the default level 1, not set up // under the guard: its keybag was created with the guard off. - assert_eq!(facts(true, true, Some((1, true)), 0), Matching::Blocked); + assert_eq!(facts(true, true, Some((1, true))), Matching::Blocked); // No list: nothing that existed at probe is Linux's. - assert_eq!(facts(true, false, Some((1, false)), 0), Matching::Blocked); - // A refusal seen. - assert_eq!(facts(true, false, Some((1, true)), 1), Matching::Blocked); + assert_eq!(facts(true, false, Some((1, false))), Matching::Blocked); // xART read-only: no guard runs, and no write can land. - assert_eq!(facts(false, false, None, 0), Matching::Blocked); - assert_eq!(facts(false, true, None, 0), Matching::Blocked); + assert_eq!(facts(false, false, None), Matching::Blocked); + assert_eq!(facts(false, true, None), Matching::Blocked); } #[test] @@ -1198,13 +1242,17 @@ mod tests { } #[test] - fn the_setup_rule_follows_the_boot_and_the_parameter() { - assert_eq!(setup(false, 0), Setup::Commit); - // The parameter changes nothing on a warm-attach Mac. - assert_eq!(setup(false, 1), Setup::Commit); - assert_eq!(setup(true, 0), Setup::Refuse); - assert_eq!(setup(true, 1), Setup::Pin); - assert_eq!(setup(true, u8::MAX), Setup::Pin); + fn the_setup_rule_requires_a_qualified_board_and_explicit_opt_in() { + let select = |cold, pin, board: &[u8]| setup(cold, pin, |compatible| compatible == board); + assert_eq!(select(false, 1, b"apple,j313"), Setup::Commit); + assert_eq!(select(true, 0, b"apple,j313"), Setup::Refuse); + assert_eq!(select(true, 2, b"apple,j313"), Setup::Refuse); + assert_eq!(select(true, 1, b"apple,j313"), Setup::PinJ313); + for board in [b"apple,j314s", b"apple,j316s", b"apple,j316c"] { + assert_eq!(select(true, 1, board), Setup::PinOne); + } + assert_eq!(select(true, 1, b"apple,j293"), Setup::ExistingPins); + assert_eq!(select(true, 1, b"apple,t6001"), Setup::Refuse); } #[test] @@ -1249,7 +1297,7 @@ mod tests { assert_eq!(guard.open_first_setup(), Ok(false)); assert_eq!(bytes.borrow().len(), 0); assert_eq!(guard.check(&locker, true), Err(EPERM)); - assert!(!guard.guarded_setup()); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); Ok(()) } @@ -1267,12 +1315,13 @@ mod tests { keys(&[shared, unread, other, third, fourth, user])?, Ok(mem(&bytes)), ) - .with_setup(Setup::Pin); + .with_setup(Setup::PinJ313); guard.note_read(&shared); guard.note_read(&other); guard.note_read(&third); guard.note_read(&fourth); guard.note_read(&user); + assert!(guard.pins_enabled()); // Reading a locker allows nothing by itself. assert_eq!(guard.check(&shared, true), Err(EPERM)); assert_eq!(guard.open_first_setup(), Ok(true)); @@ -1287,15 +1336,27 @@ mod tests { // one during the first activation). assert_eq!(guard.check(&shared, true), Ok(())); assert_eq!(guard.check(&other, true), Ok(())); + assert_eq!(guard.check(&third, true), Err(EPERM)); + guard.end_copy(); + assert_eq!(guard.commit_keybag(&BAG), Ok(true)); + // No userspace open yet. Other requests still cannot pin anything. + assert_eq!(guard.check(&third, true), Err(EPERM)); + guard.begin_activation(&BAG); assert_eq!(guard.check(&third, true), Ok(())); - assert_eq!(pins(&bytes)[..], [None, Some(shared), Some(other), Some(third)]); - assert_eq!(listed(&bytes)[..], [None, None, None, None]); + assert_eq!( + pins(&bytes)[..], + [None, Some(shared), Some(other), None, Some(third)] + ); + assert_eq!(listed(&bytes)[..], [None, None, None, None, None]); // A fourth read locker stays refused. assert_eq!(guard.check(&fourth, true), Err(EPERM)); // A record the setup adds is listed, as on any Mac. let created = session(9); assert_eq!(guard.check(&created, true), Ok(())); - assert_eq!(listed(&bytes)[..], [None, None, None, None, Some(created)]); + assert_eq!( + listed(&bytes)[..], + [None, None, None, None, None, Some(created)] + ); guard.close_first_setup(); // After the setup the pinned lockers stay writable, for a match's // rewrite, and are still never deleted. @@ -1307,8 +1368,8 @@ mod tests { assert_eq!(guard.check(&third, true), Ok(())); assert_eq!(guard.check(&fourth, true), Err(EPERM)); assert_eq!(guard.check(&created, true), Ok(())); - assert_eq!(guard.refused, 7); - assert!(guard.guarded_setup()); + assert_eq!(guard.refused, 9); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Committed); Ok(()) } @@ -1317,7 +1378,7 @@ mod tests { let bytes = RefCell::new(KVec::new()); let locker = session(1); let mut guard = - Guard::with_file(1, keys(&[locker])?, Ok(mem(&bytes))).with_setup(Setup::Pin); + Guard::with_file(1, keys(&[locker])?, Ok(mem(&bytes))).with_setup(Setup::PinOne); assert_eq!(guard.open_first_setup(), Ok(true)); assert_eq!(guard.check(&locker, true), Err(EPERM)); // Read during the create, it passes: the refusal left the window open. @@ -1333,19 +1394,21 @@ mod tests { let shared = session(1); let other = session(2); let mut guard = - Guard::with_file(1, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::Pin); + Guard::with_file(1, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::PinOne); guard.note_read(&shared); assert_eq!(guard.open_first_setup(), Ok(true)); assert_eq!(guard.check(&shared, true), Ok(())); + guard.end_copy(); + assert_eq!(guard.commit_keybag(&BAG), Ok(true)); guard.close_first_setup(); drop(guard); // The next boot, with the parameter: the pin holds once the enclave // has read the locker, and the window does not open again. let mut guard = - Guard::with_file(1, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::Pin); + Guard::with_file(1, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::PinOne); assert_eq!(guard.pinned[0], Some(shared)); - assert!(guard.guarded_setup()); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Committed); assert_eq!(guard.open_first_setup(), Ok(false)); assert_eq!(guard.check(&shared, true), Err(EPERM)); guard.note_read(&shared); @@ -1363,12 +1426,12 @@ mod tests { // Even with the read on record, which note_read() does not keep here. guard.read.push(shared, GFP_KERNEL)?; assert_eq!(guard.check(&shared, true), Err(EPERM)); - assert!(!guard.guarded_setup()); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); drop(guard); // Nor at level 2, which refuses the shared roots as well. let mut guard = - Guard::with_file(2, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::Pin); + Guard::with_file(2, keys(&[shared, other])?, Ok(mem(&bytes))).with_setup(Setup::PinOne); guard.note_read(&shared); assert_eq!(guard.check(&shared, true), Err(EPERM)); Ok(()) @@ -1380,7 +1443,7 @@ mod tests { let faults = Faults::default(); let locker = session(1); let mut guard = Guard::with_file(1, keys(&[locker])?, Ok(faulty(&bytes, &faults))) - .with_setup(Setup::Pin); + .with_setup(Setup::PinOne); guard.note_read(&locker); assert_eq!(guard.open_first_setup(), Ok(true)); faults.sync.set(true); @@ -1411,8 +1474,8 @@ mod tests { // Pin: the window still pins a read locker after the create. let bytes = RefCell::new(KVec::new()); let other = session(2); - let mut guard = Guard::with_file(1, keys(&[locker, other])?, Ok(mem(&bytes))) - .with_setup(Setup::Pin); + let mut guard = + Guard::with_file(1, keys(&[locker, other])?, Ok(mem(&bytes))).with_setup(Setup::PinOne); guard.note_read(&locker); assert_eq!(guard.open_first_setup(), Ok(true)); guard.end_create(); @@ -1442,14 +1505,14 @@ mod tests { keys(&[pinned, owned, other])?, Ok(faulty(&bytes, &faults)), ) - .with_setup(Setup::Pin); + .with_setup(Setup::PinOne); guard.note_read(&pinned); assert!(!guard.list_loaded()); // Neither the pin, the record listed before the failed read nor the // spent window counts. assert_eq!(guard.check(&pinned, true), Err(EPERM)); assert_eq!(guard.check(&owned, true), Err(EPERM)); - assert!(!guard.guarded_setup()); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); assert_eq!(guard.open_first_setup(), Ok(false)); Ok(()) } @@ -1463,7 +1526,7 @@ mod tests { let bytes = RefCell::new(list); let none: [Key; 0] = []; let mut guard = - Guard::with_file(1, keys(&none)?, Ok(mem(&bytes))).with_setup(Setup::Pin); + Guard::with_file(1, keys(&none)?, Ok(mem(&bytes))).with_setup(Setup::PinOne); assert_eq!(guard.check(&pinned, true), Err(EPERM)); assert_eq!(guard.check(&pinned, false), Err(EPERM)); assert!(guard.owned.is_empty()); @@ -1483,31 +1546,99 @@ mod tests { } #[test] - fn only_the_first_three_pins_in_the_list_count() -> Result<()> { - let pinned = [session(1), session(2), session(3)]; - let fourth = session(4); + fn an_unrepresentable_pin_list_fails_closed_even_for_absent_records() -> Result<()> { let mut list = KVec::new(); list.extend_from_slice(&setup_consumed(), GFP_KERNEL)?; - let all = [pinned[0], pinned[1], pinned[2], fourth]; - for key in &all { - list.extend_from_slice(&encode_pin(key), GFP_KERNEL)?; + for byte in 1..=4 { + list.extend_from_slice(&encode_pin(&session(byte)), GFP_KERNEL)?; } let bytes = RefCell::new(list); - let mut guard = Guard::with_file( + let mut guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinJ313); + assert!(!guard.list_loaded()); + assert!(!guard.pins_enabled()); + assert!(guard.check(&session(4), true).is_err()); + Ok(()) + } + + #[test] + fn legacy_j293_pins_survive_without_a_new_admission_window() -> Result<()> { + let empty = RefCell::new(KVec::new()); + let mut fresh = Guard::new(1, KVec::new(), Ok(mem(&empty)), Setup::ExistingPins); + assert_eq!(fresh.open_first_setup(), Ok(false)); + assert!(!fresh.pins_enabled()); + let pinned = session(1); + let other = session(2); + let mut list = KVec::new(); + list.extend_from_slice(&setup_consumed(), GFP_KERNEL)?; + list.extend_from_slice(&encode_pin(&pinned), GFP_KERNEL)?; + let bytes = RefCell::new(list); + let mut guard = Guard::new( 1, - keys(&all)?, + keys(&[pinned, other])?, Ok(mem(&bytes)), - ) - .with_setup(Setup::Pin); - for key in &all { - guard.note_read(key); + Setup::ExistingPins, + ); + assert!(guard.pins_enabled()); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Legacy); + assert_eq!( + MatchFacts { + xart_writable: true, + cold: true, + keybag: guard.keybag_evidence(&BAG), + guard: Some((1, true)), + } + .matching(), + Matching::Legacy + ); + guard.note_read(&pinned); + guard.note_read(&other); + assert_eq!(guard.check(&pinned, true), Ok(())); + assert_eq!(guard.check(&pinned, false), Err(EPERM)); + assert_eq!(guard.open_first_setup(), Ok(false)); + assert_eq!(guard.check(&other, true), Err(EPERM)); + Ok(()) + } + + #[test] + fn a_spent_legacy_marker_alone_or_a_damaged_list_is_not_legacy_evidence() -> Result<()> { + let mut list = KVec::new(); + list.extend_from_slice(&setup_consumed(), GFP_KERNEL)?; + let bytes = RefCell::new(list); + let guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinOne); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + drop(guard); + bytes + .borrow_mut() + .extend_from_slice(&encode_pin(&session(1)), GFP_KERNEL)?; + bytes.borrow_mut().push(0xab, GFP_KERNEL)?; + let guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinOne); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + Ok(()) + } + + #[test] + fn a_one_locker_board_never_honours_an_over_budget_legacy_set() -> Result<()> { + let bytes = RefCell::new(KVec::new()); + { + let mut old = Guard::new( + 1, + keys(&[session(1), session(2)])?, + Ok(mem(&bytes)), + Setup::PinJ313, + ); + assert_eq!(old.open_first_setup(), Ok(true)); + for i in 1..=2 { + old.note_read(&session(i)); + assert_eq!(old.check(&session(i), true), Ok(())); + } } - for key in &pinned { - assert_eq!(guard.check(key, true), Ok(())); + let mut guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinOne); + assert!(!guard.pins_enabled()); + for i in 1..=2 { + guard.note_read(&session(i)); + assert_eq!(guard.check(&session(i), true), Err(EPERM)); + assert_eq!(guard.check(&session(i), false), Err(EPERM)); } - assert_eq!(guard.check(&fourth, true), Err(EPERM)); - // No pin made its locker Linux's. - assert!(guard.owned.is_empty()); Ok(()) } @@ -1519,7 +1650,7 @@ mod tests { let mut guard = Guard::with_file(1, keys(&[locker])?, Ok(mem(&bytes))); guard.note_read(&locker); assert!(guard.read.is_empty()); - let mut guard = guard.with_setup(Setup::Pin); + let mut guard = guard.with_setup(Setup::PinOne); // Not a USER-xART locker or a root. guard.note_read(&Key::new(3, [3; 16])); guard.note_read(&Key::root(1)); @@ -1538,35 +1669,79 @@ mod tests { } #[test] - fn a_guarded_setup_is_read_from_the_list() -> Result<()> { + fn matching_needs_a_committed_bag_with_the_recorded_uuid() -> Result<()> { let bytes = RefCell::new(KVec::new()); - let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); - assert!(!guard.guarded_setup()); + { + let mut guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinOne); + assert_eq!(guard.open_first_setup(), Ok(true)); + // A failed or interrupted create leaves only a spent window. + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + assert_eq!(guard.commit_keybag(&BAG), Ok(false)); + guard.end_copy(); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + assert_eq!(guard.commit_keybag(&BAG), Ok(true)); + } + let guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinOne); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Committed); + // A later unguarded bag does not inherit the earlier bag's evidence. + assert_eq!(guard.keybag_evidence(&[0x99; 16]), KeybagEvidence::Unknown); + Ok(()) + } + + #[test] + fn a_failed_keybag_completion_cannot_arm_activation() -> Result<()> { + let bytes = RefCell::new(KVec::new()); + let faults = Faults::default(); + let mut guard = Guard::new( + 1, + keys(&[session(1), session(2), session(3)])?, + Ok(faulty(&bytes, &faults)), + Setup::PinJ313, + ); assert_eq!(guard.open_first_setup(), Ok(true)); - assert!(guard.guarded_setup()); - guard.close_first_setup(); - drop(guard); - let guard = Guard::with_file(1, KVec::new(), Ok(mem(&bytes))); - assert!(guard.guarded_setup()); + for i in 1..=2 { + guard.note_read(&session(i)); + assert_eq!(guard.check(&session(i), true), Ok(())); + } + guard.end_copy(); + faults.write.set(true); + assert_eq!(guard.commit_keybag(&BAG), Err(EIO)); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + guard.begin_activation(&BAG); + guard.note_read(&session(3)); + assert_eq!(guard.check(&session(3), true), Err(EPERM)); drop(guard); + let guard = Guard::new(1, KVec::new(), Ok(mem(&bytes)), Setup::PinJ313); + assert_eq!(guard.keybag_evidence(&BAG), KeybagEvidence::Unknown); + Ok(()) + } - // A list of Linux's records alone, as a keybag created before the - // window existed leaves, records no setup. - let own = session(4); - let older = RefCell::new(list_of(&[own])?); - let guard = Guard::with_file(1, keys(&[own])?, Ok(mem(&older))); - assert!(!guard.guarded_setup()); - - // Nor does a list that could not be loaded, or a window whose record - // could not be made durable. - let guard = Guard::>::with_file(1, KVec::new(), Err(ENOENT)); - assert!(!guard.guarded_setup()); - let unsynced = RefCell::new(KVec::new()); - let faults = Faults::default(); - let mut guard = Guard::with_file(1, KVec::new(), Ok(faulty(&unsynced, &faults))); - faults.sync.set(true); - assert_eq!(guard.open_first_setup(), Err(EIO)); - assert!(!guard.guarded_setup()); + #[test] + fn activation_only_accepts_the_same_bag_in_the_provisioning_boot() -> Result<()> { + let bytes = RefCell::new(KVec::new()); + let mut guard = Guard::new( + 1, + keys(&[session(1), session(2), session(3)])?, + Ok(mem(&bytes)), + Setup::PinJ313, + ); + assert_eq!(guard.open_first_setup(), Ok(true)); + for i in 1..=2 { + guard.note_read(&session(i)); + assert_eq!(guard.check(&session(i), true), Ok(())); + } + guard.end_copy(); + assert_eq!(guard.commit_keybag(&BAG), Ok(true)); + guard.note_read(&session(3)); + guard.begin_activation(&[0x99; 16]); + assert_eq!(guard.check(&session(3), true), Err(EPERM)); + guard.begin_activation(&BAG); + assert_eq!(guard.check(&session(3), true), Err(EPERM)); + drop(guard); + let mut guard = Guard::new(1, keys(&[session(3)])?, Ok(mem(&bytes)), Setup::PinJ313); + guard.note_read(&session(3)); + guard.begin_activation(&BAG); + assert_eq!(guard.check(&session(3), true), Err(EPERM)); Ok(()) } diff --git a/drivers/soc/apple/xart_store.rs b/drivers/soc/apple/xart_store.rs index b711d68497f00e..40b760afacd492 100644 --- a/drivers/soc/apple/xart_store.rs +++ b/drivers/soc/apple/xart_store.rs @@ -437,18 +437,22 @@ impl Store { /// The guard's effective level and whether its list was loaded, or /// `None` when no guard runs. - pub(crate) fn guard_state(&self) -> Option<(u8, bool)> { - self.guard - .as_ref() - .map(|guard| (guard.effective_level(), guard.list_loaded())) + pub(crate) fn guard_state(&self) -> Option<(u8, bool, bool)> { + self.guard.as_ref().map(|guard| { + ( + guard.effective_level(), + guard.list_loaded(), + guard.pins_enabled(), + ) + }) } - /// Whether this install's first keybag creation was sent under the guard, - /// as far as the guard's list says; `false` when no guard runs. - pub(crate) fn guarded_setup(&self) -> bool { + /// What the guard can establish about the validated, persisted identity bag. + pub(crate) fn keybag_evidence(&self, uuid: &[u8; 16]) -> crate::xart_guard::KeybagEvidence { self.guard .as_ref() - .is_some_and(|guard| guard.guarded_setup()) + .map(|guard| guard.keybag_evidence(uuid)) + .unwrap_or_default() } /// Tells the guard that the enclave was handed the record under `key`. @@ -474,6 +478,24 @@ impl Store { } } + pub(crate) fn end_copy(&mut self) { + if let Some(guard) = self.guard.as_mut() { + guard.end_copy(); + } + } + + pub(crate) fn commit_keybag(&mut self, uuid: &[u8; 16]) -> Result { + self.guard + .as_mut() + .map_or(Ok(false), |guard| guard.commit_keybag(uuid)) + } + + pub(crate) fn begin_activation(&mut self, uuid: &[u8; 16]) { + if let Some(guard) = self.guard.as_mut() { + guard.begin_activation(uuid); + } + } + pub(crate) fn close_first_setup(&mut self) { if let Some(guard) = self.guard.as_mut() { guard.close_first_setup(); diff --git a/tools/aurora-sep/XART-SAFETY.md b/tools/aurora-sep/XART-SAFETY.md index 1789eabb21a3da..14a38c924a4a20 100644 --- a/tools/aurora-sep/XART-SAFETY.md +++ b/tools/aurora-sep/XART-SAFETY.md @@ -22,10 +22,7 @@ two shared root records. A refused write fails the enclave's request the way a read-only gigalocker does: Touch ID may then be unavailable, but no other OS's record changes. The one exception is a fresh install's first keybag creation on a warm-attach Mac at level 1, which may rewrite one existing -SEP-xART locker (see "Fresh installs" below). On a cold-boot Mac the owner -can accept up to three more with `xart_guard_pins=1` (run on a J313 only): rewrites of the shared -lockers its first Touch ID setup reaches (see "Cold-boot Macs: pinning the shared -locker" below; three on the MacBook Air M1). +SEP-xART locker (see "Fresh installs" below). On a cold-boot Mac the optional `xart_guard_pins=1` policy admits a board-specific number of pre-Linux lockers during guarded provisioning and, on J313, activation. The measured limits and legacy-list rules are documented below. The default, `xart_guard=-1`, takes the platform's level: @@ -73,12 +70,7 @@ established, so: set it up. - On a warm-attach Mac set up under the guard, whether every record a match rewrites is on the list has not been tested. -- On the J313 set up under the guard with `xart_guard_pins=1` (the only - cold-boot Mac run so far), the record the create added is on the list and - the three shared lockers the first setup rewrote are pinned. On that J313, matches before - and after a reboot had no refusal: every pre-Linux record they rewrote - was pinned or listed (writes to the shared roots are allowed at level 1 - and not logged). Other boards are untested. +- Several cold-boot Macs have matched and restored a fingerprint using pins. Each reported run and its pin count are described below. Reads, pinning and enrollment alone cannot establish what a future match will write. ### Setting up Touch ID: creating the keybag @@ -88,7 +80,7 @@ another finger into an existing keybag does not create one. | Platform | Bootstrap | Keybag creation under level 1 | | --- | --- | --- | -| M1 (T8103), M1 Pro/Max (T6000/T6001) | cold boot | Refused: it rewrites pre-Linux session records (seen on T6000; on a T8103 J313, three SEP-xART lockers; T6001 untested). Needs `xart_guard=0`, or `xart_guard_pins=1`, run on a J313 only. | +| M1 (T8103), M1 Pro/Max (T6000/T6001) | cold boot | Refuses rewrites of pre-Linux lockers unless the board-specific pin policy permits them. The table below lists the measured boards. | | M2 (T8112) | warm attach | No xART writes (J413), so the guard does not affect it. | | M2 Max (T6021, J416c) | warm attach | On a fresh install, commits one pending SEP-xART locker; allowed once (see "Fresh installs"). Otherwise no xART writes. | | M2 Pro (T6020), M3 (T8122) | warm attach | Untested. | @@ -102,20 +94,9 @@ been measured on a guarded Mac; a refused write fails the enrolment closed. A refusal fails closed: the enclave's request fails, no record changes, and the kernel log names the refused kind. What to do depends on the case: -- A cold-boot Mac, or any Mac set up with the guard off: set - `options apple_sep xart_guard=0` in `/etc/modprobe.d/` and reboot. Do it - only once the rewrite of the shared, pre-Linux record has been accepted for - that Mac (see the next section), and treat macOS Touch ID as unverified - until it has been checked there. -- A cold-boot Mac that has never tried to create its keybag under the guard: - `options apple_sep xart_guard_pins=1` keeps the guard on and accepts the - rewrites of the lockers its first setup reaches, up to three, only (run on - a J313 only) (see - "Cold-boot Macs: pinning the shared locker"). The same caution about macOS applies. A Mac that has tried, or - that already has a keybag, must reset Touch ID and remove - `/var/lib/aurora-sep-xart-owned.bin` first: the window that pins the - lockers opens only on an empty list, and a reset alone keeps the list. The - driver says at probe which of the two it found. +- If a guarded cold-boot setup fails, keep the keybag, list and existing backups. Report the board, firmware, refusal count and the operation that failed. A pre-Linux locker can be shared with macOS. Deleting the list discards ownership history and can grant a new setup another pin budget. +- A cold-boot Mac with an existing enrollment can retain the use of recorded pins within the supported policy. A consumed window, unreadable list, or missing completion UUID cannot be repaired by inferring ownership from the gigalocker. + - A warm-attach Mac set up under the guard whose verify is refused: report the log line. `xart_guard=0` restores use at the cost of the protection. - A list that could not be read: every record that existed at boot is @@ -134,18 +115,18 @@ was off. match can save its state. The driver's `diag` attributes (see `Documentation/ABI/testing/sysfs-driver-apple-sep`) report the guard's effective level (`xart_guard`), whether its list loaded -(`xart_guard_list`), how many writes it refused (`xart_guard_refusals`), +(`xart_guard_list`), whether pins are enabled (`xart_guard_pins`), how many writes it refused (`xart_guard_refusals`), and from those `matching`: | `matching` | When | `aurora-sep-ready` | | --- | --- | --- | -| `usable` | xART writes enabled, no guard | ready | -| `unverified` | guard with its list loaded and nothing refused yet, on a warm-attach Mac or on a cold-boot Mac whose keybag was created under it with `xart_guard_pins=1` | restored, matching UNVERIFIED (not called ready; exit 0) | -| `blocked` | xART writes disabled, a refusal seen, no list, or a guard on a cold-boot Mac whose keybag was not created under it | NOT ready (exit 1), with the reason and the `xart_guard=0` opt-out | +| `usable` | xART writes enabled without a guard, or an existing legacy installation completed a live guarded verification and saved the result this boot | ready | +| `legacy` | a fully read older list has its spent marker and usable pins, and the driver validated a persisted identity bag | known empty stores can enroll, restored fingerprints can be verified | +| `unverified` | guard with its list loaded and nothing refused yet, on a warm-attach Mac or on a cold-boot Mac whose committed guarded keybag UUID matches the persisted bag under the effective pin policy | restored, matching UNVERIFIED (not called ready; exit 0) | +| `blocked` | xART writes disabled, a refusal seen, no list, or a cold-boot guard without evidence tying the persisted keybag to a successful guarded commit | NOT ready (exit 1), with the reason and the `xart_guard=0` opt-out | | absent | a kernel that does not report it | restored, matching UNVERIFIED (exit 0) | -The diag ABI stays at version 2: these attributes were added to it, and a -reader tests for them rather than for a version. +The diag ABI is version 3. Older version 2 kernels can expose the original guard attributes. Readers can check whether the attributes they need are present. Version 3 adds the legacy state and can report a durably verified legacy match as usable. An empty list next to an existing keybag is not taken as a sign that Touch ID was set up without the guard: a guarded keybag creation on an M2 wrote no @@ -182,15 +163,10 @@ it: install's first-setup window (see "Fresh installs") has been used. It lists no record. Resetting Touch ID keeps the list, so the new keybag gets no window; a reinstall or deleting the file gives the next create one. -- On a cold-boot Mac set up with `xart_guard_pins=1`, up to three entries - are pins instead of records: each names a shared SEP-xART locker the - enclave may rewrite, and lists no record as Linux's. Only the first three - pins in the list count. A kernel without pinning counts them as - unreadable entries and ignores them, so that kernel refuses the lockers as - before. +- Each pin entry names one shared SEP-xART locker. A list containing more than three distinct pins is unreadable. A complete list beyond the board's lower cap protects all its pinned lockers, including ones absent at probe. +- A separate completion entry records the UUID of the identity keybag after the host has committed the bag. Its UUID must agree with the validated on-disk keybag before a cold-boot guard reports `matching=unverified`. An earlier driver still sees a nonempty list that prevents reopening the window. It recognizes the pins and skips the new markers. -The file holds only record kinds and session ids, no key material, and it -can be backed up and copied like any other file. +The list holds record kinds, identifiers and markers. It contains no key material. ## Cold-boot SEP Macs rewrite a pre-Linux record (2026-10-16) @@ -218,8 +194,7 @@ On a T600x Mac where Linux has created its keybag, treat macOS Touch ID as unverified until macOS Touch ID unlock and keychain access have been checked there. The other cold-boot SoCs differ in detail: on a T8103 (J313) the create rewrites no pre-Linux record, the COPY_KEYBAG after it and the first -activation (after its LOAD_KEYBAG) rewrite three (see "MacBook Air M1 (J313)" below). T6001 and -T6002 are untested. +activation (after its LOAD_KEYBAG) rewrite three. This earlier measurement covered J316s and J313. The later J316c/T6001 run below recorded one. T6002 has no measured budget. ## Cold-boot Macs: pinning the shared locker (`xart_guard_pins`) @@ -230,99 +205,34 @@ Run on a J313 with macOS 13.5 firmware (sepOS 13.5), `xart_guard_pins=1`, guard - The create does not rewrite a pre-Linux locker on this Mac. The `COPY_KEYBAG` of the new bag rewrites two (tags `da70de89`, `140a890d`), and the first activation a third (`5700cc64`), about 280 ms after its `LOAD_KEYBAG` reply, during the requests that follow it. The enclave had read all three since probe. - All three were in a raw copy of the iBoot System Container taken before Linux's first xART write. An earlier setup on the same Mac with `xart_guard=0` changed five 4 KiB blocks of the gigalocker, which are where those three lockers sat or moved. - With the window closed after the create, the first was refused and provisioning failed. With it held through provisioning, the second was refused. With two pins, the third was refused during the first activation; after that refusal the enclave answered nothing more that boot (`DEVICE_STATE_TRANSITION` and the ref-key unlock got no reply, sensor registration timed out). -- So the window now runs from the create to the first `activate_touchid()`, and pins up to three lockers. With that: `identity keybag provisioned`, three pins, `xart_guard_refusals` 0, enrol, 3 of 3 matches, then after a reboot `16 session records exist, 1 created by Linux; the other 15 are protected`, the enrolment restored, 2 of 2 matches, refusals 0. The owner reports macOS Touch ID still works afterwards; macOS unlock and keychain were not checked one by one, so treat macOS Touch ID as unverified as below. - -Run on that J313 only. The rule was first built from the J316s measurements above, which saw one locker at the create. - -Until now a cold-boot Mac had two choices: no Touch ID, or `xart_guard=0`, -which lets the enclave rewrite or delete any session record on the Mac. -The J316s measurement says the create needs far less: one new record, a -shared root, and one existing session record that the enclave reads at -every attach; the J313 needs three such lockers. `xart_guard_pins=1` -(default 0) lets the owner accept exactly those records, if they are -SEP-xART lockers (kind 4), up to three, and keep the guard on for everything -else. It has an effect only on a cold-boot Mac at level 1. Its name, -`xart_guard_pins`, is what `modinfo -p apple_sep` shows for this rule; -the first draft of it (`xart_guard_pin`) pinned one locker at the create -only and did not work on a J313. - -- The first-setup window, which cold-boot Macs otherwise never get, opens - for the first `CREATE_KEYBAG` of an install whose list is loaded and - empty, and stays open until the first activation (`activate_touchid`) - returns. A version that closed it right after `LOAD_KEYBAG` refused the - third locker on the J313. Any failed step of provisioning or of that - activation before the load closes it. The marker is written first, as on a - warm-attach Mac. Without the parameter a cold-boot Mac gets no window. -- In the window the guard passes rewrites of existing kind-4 lockers, up to - three, and only of lockers the enclave read since probe (the driver notes - each `OP_SESSION_READ` it answers with a record). Before each write reaches - the gigalocker, the guard appends a pin entry naming that locker to the - list and flushes it. If the pin cannot be made durable, the rewrite is - refused. -- If the first activation does not complete in the boot that - created the keybag, a locker it would have pinned cannot be pinned later. - If nothing opens `/dev/sep-bio` that boot, the window stays open until - the boot ends; if `/dev/sep-bio` cannot be published, or an early step of - the activation fails, the window closes then. Either way: - the window opens once. Once the window is closed, the guard logs a reset hint with the first - eight refusals in a boot of a read kind-4 locker on an install with free - pins. Recovery is a Touch ID reset with - `/var/lib/aurora-sep-xart-owned.bin` removed. -- A pin counts only from a list that loaded whole, and a pinned locker is - never adopted as Linux's, even if it was absent at probe. -- From then on the enclave may rewrite a pinned locker, on any boot where - the parameter is set and the enclave has read the locker. That covers a - match, if the locker is one of the records a match rewrites, and should - cover a later `CREATE_KEYBAG` after a Touch ID reset (untested). -- A pinned locker is never deleted and never listed as Linux's. Every - other record from before Linux, kind 3 or 4, stays refused. Level 2 gets - none of this. -- Without the parameter the pin stays in the list and is not honoured, so - the Mac is back to refusing those lockers. -- The record the create adds is listed as Linux's, as on any guarded Mac, - so a match's rewrite of it passes. `matching` then reads `unverified` - rather than `blocked`. - -Before the first setup under the pin: - -- Boot macOS once after installing, so that macOS's enclave commits any - SEP-xART locker the install left pending (see "Fresh installs" below). - The window pins the first existing lockers the setup rewrites. On a Mac - where one of those is the pending locker, a shared one is refused - afterwards and the setup fails. -- Start with no list. An earlier guarded attempt leaves entries in it, and - the window does not open on a list that is not empty. - -What the pin does not establish: - -- On boards other than the J313, that the records the setup rewrites are - SEP-xART lockers. The refusals logged on J316s and J314s name kind 4, but - the ledger above does not give the kind. A kind-3 record is refused in the - window as anywhere else, and the setup then fails as it does today. -- That macOS is unaffected by Linux's rewrites of those lockers. The locker - is not tied to an OS identity and macOS reads it too. This is the same - open question as with `xart_guard=0` on these Macs; the pin narrows which - records Linux can change, not what a change to them does. Treat macOS - Touch ID as unverified until unlock and keychain access have been checked - after a Linux keybag creation and after Linux matches. -- That a match rewrites only listed records and pinned lockers. If it - rewrites another record from before Linux, the guard refuses it; for a - kind-4 locker, among the first eight refusals in a boot, it also logs the - locker's tag and whether the enclave had read it, next to the - pinned lockers' tags in the earlier log lines, so the two can be compared. -- That each pinned locker keeps its session id. If another OS replaces one - under a new id, its pin names a record that no longer exists and the new - locker is refused; the tags in the log show the difference. The window - does not open twice, so recovering means resetting Touch ID with the list - removed. -- That the pin survives a driver reload. The allowance needs the enclave's - reads of the locker since probe. If the driver is bound again while the - enclave keeps running and does not repeat its attach reads, the pinned - locker is refused until a restart. -- That T6001 and T6002 behave as T6000 or T8103 does. - -The tags in those log lines are a CRC-32 of the session id. They identify a -locker across boots in the log without printing its id. +- The J313 run with enrollment, three same-boot matches, two matches after a reboot and zero refusals used the earlier 7.2 tree `d7cbd45fe`. A separate build that stopped after `LOAD_KEYBAG` refused the third locker. The later head `56b08faee168` could not be staged for Malik's review. On J313, a separate 7.3 port, `7d15e097`, pinned three lockers and matched before and after a reboot. The 7.3 port has additional changes. [7.2 build history](https://github.com/omacom/linux-aurora/commit/a71e98bd8c95) · [J313 review](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7206020097) · [7.3 test](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7068344056) + +### Cold-boot board limits + +The board's root device-tree compatible selects the policy. A family name alone gives no fresh pin allowance. The counts come from runs of earlier drivers. They are ceilings on the exception and cannot identify which OS owns a locker. + +| Board | During first provisioning | During first activation | Observation | +| --- | ---: | ---: | --- | +| J313 / T8103 | 2 | 1 | Two lockers during the copy, then one during activation on 13.5 sepOS. See the J313 runs above. | +| J314s / T6000 | 1 | 0 | One pin during setup. Guarded enrollment and matches before and after reboot on a Stable backport. [J314s report](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7195314332) | +| J316s / T6000 | 1 | 0 | One provisioning pin at `56b08faee168`. Enrollment failed at capture, so an additional activation allowance has no supporting measurement. [J316s report](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7040944575) | +| J316c / T6001 | 1 | 0 | The original guarded Stable backport's kernel journal records one pin before the keybag was persisted. The enrollment matched and was later verified after reboot. [J316c test](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7182520459) · [J316c reboot](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7184616701) | +| J293 / T8103 | 0 | 0 | An earlier full guarded test succeeded without publishing a count. The driver permits the same recorded pins on opted-in existing installations. A count and the stage of each pin from that run would establish a fresh budget. [J293 report](https://github.com/omacom/linux-aurora/pull/506#issuecomment-7064715679) | +| Other cold-boot boards | 0 | 0 | No pin exception. | + +With `xart_guard_pins=1` at level 1, a board with a fresh allowance requires a loaded, empty list. The driver flushes the named identity intent and its parent directory, then the list's spent marker, before sending `CREATE_KEYBAG`. An eligible write must target an existing kind-4 locker the enclave has read since probe. The driver flushes its pin entry before forwarding the rewrite. Previously pinned lockers still require a read that boot, and deletes remain refused. + +`COPY_KEYBAG` returning closes admission for new provisioning pins, including while the host validates and saves the bag. A J313 that used both provisioning pins and durably saved the guarded identity may admit one further locker only while the driver is recovering and activating that same keybag. The gap before a client opens `/dev/sep-bio` permits no new pins. Activation exits consume the allowance. It expires on reboot, even if no client opened the device. + +`modinfo -F xart_guard_pins_abi apple_sep` reports `1` for this implementation. The running driver's `diag/xart_guard_pins` reports whether its actual board, level and loaded list enable the pin policy. An empty list qualifies for boards with a measured fresh allowance. J293 requires a previously populated list. Pin counts and the identity of a shared locker remain private to the driver. + +Older 7.2 lists may contain their original spent marker and valid pins without a completion entry. A validated bag alongside that complete legacy list reports `matching=legacy` when its pins fit the board's limit. A known empty store can enroll a first fingerprint, and a restored finger can be verified. Neither operation grants any new pin. The creation provenance remains unknown. After the driver saves the post-match state and publishes a successful result to the current verification session, `matching=usable` for the rest of that boot unless a refusal occurs. A spent marker alone, a missing bag or an interrupted newer guarded attempt reports `blocked`. + +Keep the keybag, list and their history. Restoring or deleting the list can grant a fresh set of pins across attempts. The cap applies to the list, and resetting Touch ID alone preserves it. + +On J313, refusing the third locker left the enclave silent for the rest of that boot. Rebooting to the guarded build lets it read the saved pins again. A previously recorded pin becomes usable after the enclave reads its locker. A reboot cannot recover a pin that was never saved during first setup. + +A refusal among the first eight for a kind-4 locker includes a short CRC-32 tag and whether it was read. This permits comparing logged pins without publishing session IDs. Hardware qualification of this revision requires the exact kernel build, board and OS firmware, the count and stage of its pins, Linux enrollment and matching before and after a reboot, and separate checks of macOS Touch ID and the login keychain. macOS also reads these lockers. ## Fresh installs: the pending SEP-xART locker (2026-10-25) @@ -380,7 +290,8 @@ A create that gets no reply, as one with a refused write does, keeps its intent record, so later creates fail with `EEXIST` until Touch ID is reset (`install-aurora-sep.sh --reset-touchid`): the enclave may have kept part of what it saved before the refusal. A create the enclave answers with an error -stays retryable, as before. +stays retryable when its complete, checksummed refusal record is present. +A malformed refusal leaves the keybag file in place and blocks another create. ## Earlier deployment policy diff --git a/tools/aurora-sep/aurora-sep-ready b/tools/aurora-sep/aurora-sep-ready index dcc152ff570a33..87f7cc18ba3205 100644 --- a/tools/aurora-sep/aurora-sep-ready +++ b/tools/aurora-sep/aurora-sep-ready @@ -18,9 +18,10 @@ # and the xART guard (apple_sep xart_guard) refuses that where it is known # to, for instance on a cold-boot Mac whose Touch ID was set up with the # guard off. So, from diag "matching": -# usable ready: no guard runs and xART is writable; +# usable ready: writable without a guard, or a verified legacy match; # blocked NOT ready, with the reason and, for the guard, the # documented xart_guard=0 opt-out and what it gives up; +# legacy an existing enrollment needs a real guarded match this boot # unverified restored, but whether a match can save its state is not # known (a guard that has refused nothing yet, or a kernel # that does not report it). Not called ready. @@ -112,7 +113,7 @@ blocked_reason() { elif [ "$(attr xart_guard_list)" = unavailable ]; then echo "the xART guard could not load its list of Linux's records, so it refuses every session write. $optout" elif [ "$(attr boot)" = cold ]; then - echo "on this cold-boot Mac no keybag was created under the xART guard, which takes xart_guard_pins=1, so the session records a match rewrites are not on the guard's list. $optout" + echo "the cold-boot guard cannot confirm the persisted keybag and its pin policy. $optout" else echo "the xART guard refuses a match's write. $optout" fi @@ -123,6 +124,13 @@ blocked_reason() { restored() { case "$(attr matching)" in usable) ready "$1; matching is usable" ;; + legacy) + if [ "$(attr restore)" = empty ]; then + log "Touch ID can enroll a fingerprint after $(elapsed) s; the keybag has legacy pins, matching is UNVERIFIED until a live verify succeeds" + exit 0 + fi + unverified "$1; this driver found legacy pins and a persisted keybag. Verify an enrolled finger to confirm matching on this boot" + ;; unverified) unverified "$1; the xART guard (level $(attr xart_guard)) has refused nothing yet, but whether it allows every record a match rewrites is untested on this Mac. If a verify fails with an \"xART guard: refused\" kernel message, see XART-SAFETY.md" ;; diff --git a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD index f1455d13bb4086..696cd040fb72a5 100644 --- a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD +++ b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD @@ -7,7 +7,7 @@ pkgname=aurora-sep pkgver=1 -pkgrel=12 +pkgrel=13 pkgdesc="Loader and desktop integration for the Apple SEP (Touch ID) driver" url="https://github.com/aurora-silicon/linux/tree/aurora-wip/tools/aurora-sep" arch=(any) @@ -34,14 +34,14 @@ source=(load-driver sha256sums=('abea60bb264ced349f7cf671d8d26e1609a81a60ea4c34d66ec6f7f73b847dbb' '447f99cc3c7e683134f31b993aa825fadde24e4854954a3035c96e6631d4d4d0' 'f8d0c4b9385e6716d5ac5dd9941a57459fbc551a8238383bcde36cd929d0523f' - '4c389da1af40b7713b5940283e74483ee19c3941c70ef00150c63555f30419c3' + 'd5496c6947e917a0b9dbe81bbe5beb8b161ebbb635627b69622e8a7dd30bacf1' 'f38421360c2f885bb102bc5076d81006d352d03d12b5fb35b4da8a5132f4ccc0' '8d8df0ba2a6861b2edb2110e606906d84ca4848617621ad3cb48493a1522971d' '0695bd9ce4c207241db13c3ea07819a032d8213417021378f5015ab9317cde12' '5936eb76db666496a8700dade7ac6bcb3785b517958dcea10685690f1822c86f' 'ffab97b20bfd5f0eb1ab641179a131843349cf16890fff0cf2d893f0b5681b37' 'dbcf59cecd62c0245cf39c3c8ee41e3088e2890da89288e91d1c53ee3f02cba4' - 'f47a023975c4c0e6c2d74fb1fe75b7423d9548ac66e21195fe2ff7b840ae326f') + '5d7b0ff63966eb11d164fc4967ed74be7907f84f5f2f3ed97d7f95a860e6f255') # A unit and the helper it runs ($1, installed as $3), pointed at the # packaged helper. diff --git a/tools/aurora-sep/packaging/fedora/aurora-sep.spec b/tools/aurora-sep/packaging/fedora/aurora-sep.spec index c32d5363130473..68679af249f628 100644 --- a/tools/aurora-sep/packaging/fedora/aurora-sep.spec +++ b/tools/aurora-sep/packaging/fedora/aurora-sep.spec @@ -8,7 +8,7 @@ Name: aurora-sep Version: 1 -Release: 7%{?dist} +Release: 8%{?dist} Summary: Loader and desktop integration for the Apple SEP fingerprint driver License: GPL-2.0-only @@ -144,6 +144,9 @@ fi %ghost %verify(not md5 size mode mtime) %{_sharedstatedir}/selinux/%{selinuxtype}/active/modules/200/%{modulename} %changelog +* Fri Nov 27 2026 Adrian Rangel - 1-8 +- Report legacy guarded keybag verification and document board-specific pins. + * Mon Oct 19 2026 Ryan Murray - 1-7 - XART-SAFETY.md: what the xART guard allows for restore, use, setup and recovery, per platform, and what a rollback does to its list diff --git a/tools/aurora-sep/tests/test_diag_sensor.py b/tools/aurora-sep/tests/test_diag_sensor.py index 903c3d88131224..56b1dc5b2315f8 100644 --- a/tools/aurora-sep/tests/test_diag_sensor.py +++ b/tools/aurora-sep/tests/test_diag_sensor.py @@ -24,6 +24,7 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'aurora-sep-ready' HEADERS = { + 'linux/module.h': '#define MODULE_INFO(tag, value)\n', 'linux/types.h': r''' #include #include @@ -52,7 +53,12 @@ return __atomic_compare_exchange_n(&v->counter, old, new_, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); } -#define atomic_inc(v) __atomic_add_fetch(&(v)->counter, 1, __ATOMIC_SEQ_CST) +static inline void atomic_add_unless(atomic_t *v, int add, int unless) +{ + int old = atomic_read(v); + while (old != unless && !atomic_try_cmpxchg(v, &old, (int)((unsigned int)old + add))) + ; +} ''', 'linux/device.h': r''' #include @@ -137,7 +143,7 @@ { static const char *names[] = { "abi", "touchid", "sensor", "sensor_attach", "restore", "keybag", "keystore", "boot", "xart", - "xart_guard", "xart_guard_list", + "xart_guard", "xart_guard_list", "xart_guard_pins", "xart_guard_refusals", "matching", NULL }; char path[4096]; @@ -157,14 +163,15 @@ unsigned int bind, stale; /* The Neo: warm attach, xART writable, no guard. */ - sep_diag_set_xart_guard(0, false, SEP_DIAG_MATCHING_USABLE); + sep_diag_set_xart_guard(0, false, false, SEP_DIAG_MATCHING_USABLE); sep_diag_register(&dev, "T8140/J700", 10, false, false, true); - /* The guard's attributes were added within version 2. */ - expect("probe", "abi", "2"); + /* Version 3 distinguishes legacy pins from a recorded guarded commit. */ + expect("probe", "abi", "3"); expect("probe", "sensor", "unbound"); expect("probe", "touchid", "unknown"); expect("probe", "xart_guard", "0"); expect("probe", "xart_guard_list", "none"); + expect("probe", "xart_guard_pins", "0"); expect("probe", "xart_guard_refusals", "0"); expect("probe", "matching", "usable"); @@ -246,24 +253,26 @@ } /* - * argv: level list matching-at-probe refusals matching-after-refusal - * [matching-after-first-setup] + * argv: level list pins matching-at-probe refusals [matching-after-commit] */ int main(int argc, char **argv) { struct device dev; - int refusals = atoi(argv[4]); + int refusals = atoi(argv[5]); - sep_diag_set_xart_guard(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); + sep_diag_set_xart_guard(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atoi(argv[4])); sep_diag_register(&dev, "TEST", 4, false, false, true); while (refusals--) - sep_diag_xart_guard_refused(atoi(argv[5])); - if (argc > 6) + sep_diag_xart_guard_refused(); + if (argc > 6 && atoi(argv[6])) sep_diag_set_matching(atoi(argv[6])); + if (argc > 7 && atoi(argv[7])) + sep_diag_verified_match(); /* attr() returns one static buffer: print each before the next. */ printf("%s ", attr("abi")); printf("%s ", attr("xart_guard")); printf("%s ", attr("xart_guard_list")); + printf("%s ", attr("xart_guard_pins")); printf("%s ", attr("xart_guard_refusals")); printf("%s\n", attr("matching")); return 0; @@ -297,24 +306,24 @@ def build(self, root, harness, name): @unittest.skipUnless(shutil.which('cc'), 'needs a C compiler') def test_matching_follows_the_guard(self): - usable, unverified, blocked = 1, 2, 3 # SEP_DIAG_MATCHING_* in shim.h + usable, unverified, blocked, legacy = 1, 2, 3, 4 # SEP_DIAG_MATCHING_* in shim.h cases = [ - # level, list, matching at probe, refusals, matching after them - # and, where given, matching once the first setup is recorded - ((0, 0, usable, 0, 0), '2 0 none 0 usable'), # Neo, M1 Pro (pinned 0) - ((1, 1, unverified, 0, 0), '2 1 loaded 0 unverified'), # M2 under the guard - ((1, 1, unverified, 2, blocked), '2 1 loaded 2 blocked'), # ... after refusals - ((2, 1, unverified, 0, 0), '2 2 loaded 0 unverified'), - ((1, 0, blocked, 0, 0), '2 1 unavailable 0 blocked'), # no list - ((1, 1, blocked, 0, 0), '2 1 loaded 0 blocked'), # cold boot, level 1 - # ... with xart_guard_pins, once its first keybag creation is sent - ((1, 1, blocked, 0, 0, unverified), '2 1 loaded 0 unverified'), - # ... and the refusals counted before that stand, and win over a - # matching value that was derived before they landed - ((1, 1, blocked, 2, blocked, blocked), '2 1 loaded 2 blocked'), - ((1, 1, blocked, 2, blocked, unverified), '2 1 loaded 2 blocked'), - ((0, 0, 0, 0, 0), '2 0 none 0 unknown'), # never set - ((0, 0, 7, 0, 0), '2 0 none 0 unknown'), # out of range + # level, list, effective pin mode, base matching, refusals, optional commit + ((0, 0, 0, usable, 0), '3 0 none 0 0 usable'), + ((1, 1, 0, unverified, 0), '3 1 loaded 0 0 unverified'), + ((1, 1, 0, unverified, 2), '3 1 loaded 0 2 blocked'), + ((2, 1, 0, unverified, 0), '3 2 loaded 0 0 unverified'), + ((1, 0, 0, blocked, 0), '3 1 unavailable 0 0 blocked'), + ((1, 1, 1, blocked, 0), '3 1 loaded 1 0 blocked'), + ((1, 1, 1, blocked, 0, unverified), '3 1 loaded 1 0 unverified'), + # A commit racing or following the refusal cannot clear it. + ((1, 1, 1, blocked, 2, unverified), '3 1 loaded 1 2 blocked'), + ((1, 1, 1, legacy, 0), '3 1 loaded 1 0 legacy'), + ((1, 1, 1, legacy, 0, 0, 1), '3 1 loaded 1 0 usable'), + ((1, 1, 1, legacy, 1, 0, 1), '3 1 loaded 1 1 blocked'), + ((1, 1, 1, blocked, 0, 0, 1), '3 1 loaded 1 0 blocked'), + ((0, 0, 0, 0, 0), '3 0 none 0 0 unknown'), + ((0, 0, 0, 7, 0), '3 0 none 0 0 unknown'), ] with tempfile.TemporaryDirectory() as directory: harness = self.build(Path(directory), GUARD_HARNESS, 'guard') @@ -324,43 +333,30 @@ def test_matching_follows_the_guard(self): self.assertEqual(done.stdout.strip(), want, args) def test_the_first_setup_window_brackets_the_create(self): - # sks.rs asks the guard for the window on every platform (the guard - # decides which get one), tells diag once it opens, holds it across - # the create and tells the guard when the create is over (the guard - # decides whether the window outlasts it: KUnit - # only_a_pinning_window_outlasts_the_create). A successful create - # hands it to the first activation, which releases it when it - # returns; any failed exit in between shuts it on drop. + # KUnit exercises the state machine. Check the actual SKS and SBIO + # callers delimit the two operations and only record a persisted bag. source = (APPLE / 'sks.rs').read_text() create = function(source, 'pub(crate) fn sks_provision_identity_keybag(&self) -> bool') - steps = ['store.open_first_setup()', 'crate::diag::xart_guard_setup_recorded()', - 'SetupWindow {', 'intent.sending()', 'self.sks_exchange(request.name', - 'window.end_create()', 'self.sks_req_copy_keybag(handle)', - 'window.leave_open_for_activation()'] - places = [create.find(step) for step in steps] - self.assertNotIn(-1, places, steps) - self.assertEqual(places, sorted(places), steps) - for step in steps: - self.assertEqual(create.count(step), 1, step) - self.assertNotIn('close_first_setup', create) - # The holder's end_create hands the decision to the guard. - holder = function(source, 'fn end_create(&self)') - self.assertIn('store.end_create()', holder) - # Nothing else in the key store opens or reports the window. - for step in (steps[0], steps[1]): - self.assertEqual(source.count(step), 1, step) - # The bootstrap no longer decides here: xart_guard.rs (Setup) does. - self.assertNotIn('Bootstrap', create[:places[3]]) + steps = ['store.open_first_setup()', 'SetupWindow {', 'intent.sending()', + 'self.sks_exchange(request.name', 'window.end_create()', + 'self.sks_req_copy_keybag(handle)', 'window.end_copy()', + 'let committed =', 'if let Err(e) = committed', 'window.provisioned('] + places = [create.index(step) for step in steps] + self.assertEqual(places, sorted(places)) + finish = function(source, 'fn provisioned(mut self,') + self.assertLess(finish.index('store.commit_keybag(uuid)'), finish.index('diag::xart_guard_keybag_committed()')) + record = function((APPLE / 'keybag.rs').read_text(), 'fn write_record(') + syncs = ['file.write_all(0, &head)?', 'file.sync()?', 'if state == STATE_INTENT', 'file.sync_parent()?'] + self.assertEqual([record.index(x) for x in syncs], sorted(record.index(x) for x in syncs)) + self.assertLess(create.index('KeybagCreateIntent::new('), create.index('store.open_first_setup()')) sbio = (APPLE / 'sbio.rs').read_text() + failed_register = function(sbio, 'if let Err(e) = self.register_bio()') + self.assertIn('store.close_first_setup()', failed_register) activate = function(sbio, 'fn activate_touchid(&self) -> Result<()>') - # The first activation holds the window from before its first step - # to its return (a J313 rewrites a shared locker after LOAD_KEYBAG), - # and nothing releases it earlier. - hold = activate.find('let _window = crate::sks::SetupWindow::for_activation(self);') - self.assertNotEqual(hold, -1) - self.assertLess(hold, activate.find('store::Store::open()')) - self.assertNotIn('drop(_window)', activate) - self.assertNotIn('close_first_setup', activate) + steps = ['SetupWindow::for_activation(self)', 'keybag::read(keybag::Slot::Identity)', + 'store.begin_activation(stored.uuid())', 'self.sks_recover(&stored)'] + places = [activate.index(step) for step in steps] + self.assertEqual(places, sorted(places)) def test_probe_and_remove_report_the_bind(self): source = (APPLE / 'sensor_shim.c').read_text() diff --git a/tools/aurora-sep/tests/test_sep_ready.py b/tools/aurora-sep/tests/test_sep_ready.py index b667ba60d17f80..deda88d1af45cf 100644 --- a/tools/aurora-sep/tests/test_sep_ready.py +++ b/tools/aurora-sep/tests/test_sep_ready.py @@ -108,6 +108,19 @@ def test_restored_with_matching_unverified(self): self.assertIn("level 1", log) self.assertIn("the enrolled fingerprints are restored", log) + def test_legacy_pins_offer_enrollment_or_verification_without_claiming_a_match(self): + self.attached(matching="legacy", xart="enabled", xart_guard="1", + xart_guard_list="loaded", xart_guard_refusals="0", boot="cold") + rc, log = self.run_ready() + self.assertEqual(rc, 0, log) + self.assert_unverified(log) + self.assertIn("Verify an enrolled finger", log) + self.attached(restore="empty", matching="legacy") + rc, log = self.run_ready() + self.assertEqual(rc, 0, log) + self.assertIn("can enroll a fingerprint", log) + self.assertIn("UNVERIFIED until a live verify succeeds", log) + def assert_blocked(self, log, *reasons, optout=True): self.assertIn("NOT ready", log) self.assertNotIn("is ready", log)