Skip to content

apple_sep: J613 (M3 Air) Touch ID blocked on every boot after one macOS boot: xART guard refuses the kind-4 rewrite, DESIGNATE_KEYBAG times out #396

Open

Description

@elbourru

Drafted with an AI assistant (Claude Code) from this machine's logs; I reviewed it before posting.

Mac and installed build

Model / board / SoC: MacBook Air 13" M3 (2024) / apple,j613 / apple,t8122 (driver profile T8122/J613)
uname -r: 7.2.11-14-1-ARCH
linux-aurora 7.2.11.aurora14-1, m1n1-aurora 1.6.1.aurora22-1, omarchy-aurora-firmware 20261014-7
omarchy-mac 0.2.3-2, omarchy-mac-boot 20261104-1
libfprint-git 1:1.94.100.r10.g6f9479c-5, fprintd 1.94.5-2
Distribution / local patches: Omarchy on Arch Linux ARM, no local patches
Module options: xart_writes=1 provision_keybag=1 (omarchy-mac-touchid.conf), xart_guard default (level 1)
xART lane: /chosen/apfs-preboot-uuid, no os_uuid_* on the command line

Both firmware versions and provisioning

asahi,os-fw-version: 14.7
asahi,system-fw-version: 27.0
Own-Mac provisioning status: calibration carved from this Mac's own iBoot System Container by omarchy-mac; identity keybag created by this install on its first Touch ID boot (2026-11-03)

Reproduction, expected result, and actual result

  1. 2026-11-03: turn on Touch ID in Omarchy, which creates the keybag on Linux's first boot with the driver. Enrol one finger. Verify works for the rest of that boot.
  2. Boot macOS once.
  3. Boot Linux again.

Expected: the Linux enrolment keeps matching after a macOS boot, or the driver recovers without lowering the guard.

Actual: on every Linux boot since the macOS boot (4 boots so far, 2026-11-05 to 2026-11-06), the xART guard refuses the enclave's rewrite of a kind-4 record and DESIGNATE_KEYBAG gets no reply. Matching and enrolment then stay blocked for the whole boot: diag/matching reads blocked and touchid reads not-ready. Verify is refused before the sensor is touched, so re-enrolling doesn't help either. Suspend and resume make no difference.

On the first boot, the guard's exception allowed the enclave to commit the existing kind-4 locker "during this install's first keybag creation". Every later boot still reports 0 created by Linux, so the same record counts as foreign once that exception no longer applies. The xART max revision went from 3226 (working boot) to 3350 (first broken boot) across the macOS boot. It is 3353 now.

No Linux packages changed between the last working boot and the first broken one.

diag now: abi=2 protocol=variant5 boot=warm xart=enabled xart_guard=1 xart_guard_refusals=1 keybag=present keystore=open restore=unknown sensor=failed sensor_attach=not-ready touchid=not-ready matching=blocked

Relevant error lines

Working boot (2026-11-03):

apple_sep: xART guard level 1: 10 session records exist, 0 created by Linux; the other 10 are protected
apple_sep 29e400000.sep: xART: APFS-resolved .gl extent (base 0x4d4000); 170 slots, 12 live records, max revision 3226, 0 malformed, 0 duplicate, 0 repaired; writes ENABLED
apple_sep 29e400000.sep: xART: using /chosen/apfs-preboot-uuid
apple_sep: xART guard: allowed the enclave to commit an existing kind-4 locker during this install's first keybag creation
apple_sep 29e400000.sep: sks: identity keybag provisioned
apple_sep 29e400000.sep: sks: LOAD_KEYBAG reply mailbox status 0, response size 84, copied 84 bytes
apple_sep 29e400000.sep: sks: snapshot identity bound to recovered and designated bag; generated lookup false
apple_sep 29e400000.sep: scrd: cold-match credential established true
apple_sep 29e400000.sep: sbio: pre-restore special unlock true, SCRD match context true
apple_sep 29e400000.sep: sbio: cold-match preparation true, component restore false
apple_sep 29e400000.sep: enrol: opt-in opt-in completed user catacomb state Some(7)
apple_sep 29e400000.sep: enrol: opt-in opt-in post-user master catacomb state Some(7)

Every boot after the macOS boot (current boot shown):

[   10.024014] apple_sep: xART guard level 1: 10 session records exist, 0 created by Linux; the other 10 are protected
[   10.024063] apple_sep 29e400000.sep: xART: APFS-resolved .gl extent (base 0x4d4000); 170 slots, 12 live records, max revision 3353, 0 malformed, 0 duplicate, 0 repaired; writes ENABLED
[   10.850449] apple_sep 29e400000.sep: xART: using /chosen/apfs-preboot-uuid
[   13.205047] apple_sep 29e400000.sep: sks: LOAD_KEYBAG reply mailbox status 0, response size 84, copied 84 bytes
[   13.857020] apple_sep: xART guard: refused to rewrite a kind-4 record this Linux install did not create
[   15.266059] apple_sep 29e400000.sep: sks: DESIGNATE_KEYBAG got no reply after 2060 ms
[   15.266652] apple_sep 29e400000.sep: sks: DESIGNATE_KEYBAG did not complete; enrolment will refuse
[   17.313762] apple_sep 29e400000.sep: sbio: pre-restore special unlock false, SCRD match context false
[   22.498027] apple_sep 29e400000.sep: sbio: cold-match preparation false, component restore false
[   27.617024] apple_sep 29e400000.sep: sbio: identity list unavailable after Catacomb restore with sensor registered
[   27.617346] apple_sep 29e400000.sep: matching unavailable this boot: cold-match preparation, SCRD credential, Catacomb restore, or identity proof did not complete; template state is unproven
[   32.738026] apple_sep 29e400000.sep: sbio: the sensor did not wake at attach
[   38.370136] apple_sep 29e400000.sep: sbio: attach-time sensor bring-up did not complete; matching unavailable; retrying in 10 s
           ... sensor: the enclave did not register the sensor   (5 late retries)
           ... sensor: authenticated attach incomplete after the late retry; capture unavailable until an enrol or verify brings the sensor up
[  428.651010] apple_sep 29e400000.sep: verify: refusing before touching the sensor; cold-match prep, restore, or device-view identity proof did not complete. This is not a non-matching finger

Userspace:

touchid-activate: Touch ID is not ready to enrol and match: a match could not save its state (matching blocked)
fprintd: Device reported an error during verify: verification failed: the secure enclave refused a step (driver status 2)

Related issues, pull requests, or code examples

Workarounds tried: rebooting Linux several times, and suspend/resume. Neither recovers. I have not tried xart_guard=0, because of the macOS data-loss risk (FileVault is a possibility on this Mac).

Questions:

  • Should the kind-4 locker this install adopted during its first keybag creation count as Linux-created from then on?
  • Is there a supported way to recover that doesn't need xart_guard=0? For example, deleting the keybag and turning Touch ID off and on again, or another macOS boot.

What was not tested

Activity

  1. techgyani commented on Nov 8, 2026

    @techgyani

    Another data point, from a 14-inch M3 Max (apple,j514m, apple,t6034) with the same Omarchy Touch ID path (omarchy-mac 0.2.3-2, libfprint-git 1:1.94.100.r10.g6f9479c-5, fprintd 1.94.5-2), guard at the profile default (level 1). Three macOS boots after a working Linux setup did not reproduce this issue here.

    Unreleased build: kernel 8eddf5aeb6ac + local J514M patches (a T6034/J514M SEP profile copied from T8122 with the J514M sensor, and J514M device-tree nodes) + a local guard change described below; m1n1 c6fef490 + omacom/m1n1#29. asahi,os-fw-version: 14.7, asahi,system-fw-version: unknown. omarchy-mac's eligibility check does not list this board, so touchid-enable ran with a local copy of touchid-eligibility that adds t6034 && j514m.

    The guard change: once per boot, at the first DESIGNATE_KEYBAG of a keybag that already existed, and only when the gigalocker's max revision at probe is newer than the last revision Linux wrote (kept in a host file), the guard may let the enclave rewrite one existing kind-4 record that the enclave read this boot. Never a delete, never adopted into Linux's list, logged. It was added for this issue; on this Mac it was never used (below).

    Action Result
    Provisioning (touchid-enable) pass: sks: identity keybag provisioned; no refused line; the #212 first-setup window was not used
    Enrol, right index pass: enroll-completed
    Verify, enrolled / other finger pass: verify-match / verify-no-match
    Linux reboot (2 times) pass: Touch ID: restored 1, verify-match, xart_guard_refusals 0
    macOS boot, then Linux (3 times) pass: unlock window closed unused, no refused line; Touch ID: restored 1, verify-match, xart_guard_refusals 0
    macOS after each Linux session (3 times) pass: bioutil -c unchanged (3), Touch ID unlock and a Touch ID prompt, login keychain unlocked; FileVault on
    Suspend and resume not tested
    Lock screen and sudo through PAM not tested

    Each Linux boot after macOS logged:

    apple_sep: xART guard level 1: 11 session records exist, 0 created by Linux; the other 11 are protected
    apple_sep: xART guard: gigalocker revision 53447 at probe, Linux's last 53423: another OS wrote since
    apple_sep 38a400000.sep: sks: LOAD_KEYBAG reply mailbox status 0, response size 84, copied 84 bytes
    apple_sep: xART guard: unlock window open for the first unlock of Linux's existing keybag
    apple_sep: xART guard: unlock window closed unused
    apple_sep 38a400000.sep: Touch ID: restored 1 enrolled identity/identities; enrolment survived reboot
    

    (The other two times: 53481 vs 53451 and 53517 vs 53487.)

    Record headers from apfs-xart-inspect.py before and after each macOS boot: macOS rewrote the same three kind-4 records each time (and, in the third boot, one kind-3 record), plus both roots. Lengths unchanged, no records added or removed. Linux's own boots changed only the roots.

    So on this Mac, the unlock after a macOS boot did not need a rewrite, unlike the J613 here. These logs don't show what differs.

    The guard change, against 8eddf5aeb6ac (sep.rs, sks.rs, xart_guard.rs, xart_store.rs; applies with patch -p1). It was written from the driver source at that commit and the logs in this issue and on this Mac; it contains no Apple code. KUnit under QEMU arm64: 131 apple_sep tests passed, 8 of them new. On hardware, only the closed-unused path above has run; the rewrite path has not.

    Patch (guard window)
    diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs
    index 87b90a7d9..a6b66e89d 100644
    --- a/drivers/soc/apple/sep.rs
    +++ b/drivers/soc/apple/sep.rs
    @@ -671,6 +671,8 @@ struct SepData {
         device_view_synced: Atomic<bool>,
     
         keybag_designated: Atomic<bool>,
    +    /// The identity keybag was created this boot, not loaded.
    +    keybag_created: Atomic<bool>,
     
         bringup_started: Atomic<bool>,
         touchid_started: Atomic<bool>,
    @@ -922,6 +924,7 @@ fn new(pdev: &platform::Device<device::Core<'_>>) -> Result<Arc<SepData>> {
                     late_attach_wanted: Atomic::new(false),
                     late_attach_defers: Atomic::new(0),
                     keybag_designated: Atomic::new(false),
    +                keybag_created: Atomic::new(false),
                     bringup_started: Atomic::new(false),
                     touchid_started: Atomic::new(false),
                     touchid_failed: Atomic::new(false),
    diff --git a/drivers/soc/apple/sks.rs b/drivers/soc/apple/sks.rs
    index bbc6c723c..efedb6814 100644
    --- a/drivers/soc/apple/sks.rs
    +++ b/drivers/soc/apple/sks.rs
    @@ -789,6 +789,7 @@ pub(crate) fn sks_provision_identity_keybag(&self) -> bool {
                 return false;
             }
             let _ = self.sks_send(self.sks_req_unload_keybag(handle));
    +        self.keybag_created.store(true, Relaxed);
             dev_info!(self.dev, "sks: identity keybag provisioned\n");
             true
         }
    @@ -811,7 +812,15 @@ pub(crate) fn sks_designate_user_keybag(
     
             let designation = crate::sks::Designation::new(handle, user);
     
    -        let Some(out) = self.sks_send(self.sks_req_designate(&designation, secret)) else {
    +        // After another OS wrote the gigalocker this unlock rewrites one shared locker (#396).
    +        let existing = !self.keybag_created.load(Relaxed);
    +        let warm = self.profile.bootstrap == profile::Bootstrap::WarmRegister;
    +        let window = self.with_store(|store| store.open_unlock(existing, warm)).unwrap_or(false);
    +        let sent = self.sks_send(self.sks_req_designate(&designation, secret));
    +        if window {
    +            self.with_store(|store| store.close_unlock());
    +        }
    +        let Some(out) = sent else {
                 dev_warn!(
                     self.dev,
                     "sks: DESIGNATE_KEYBAG did not complete; enrolment will refuse\n"
    diff --git a/drivers/soc/apple/xart_guard.rs b/drivers/soc/apple/xart_guard.rs
    index 6efb2a860..e19d8e766 100644
    --- a/drivers/soc/apple/xart_guard.rs
    +++ b/drivers/soc/apple/xart_guard.rs
    @@ -44,6 +44,19 @@
     //! nothing identifies that locker as the pending one. It does not list the
     //! 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 second exception keeps Touch ID working across macOS boots
    +//! (omacom/linux-aurora#396). After another OS has written the gigalocker,
    +//! the enclave's first unlock of Linux's existing keybag (`DESIGNATE_KEYBAG`)
    +//! rewrites one existing kind-4 locker; refused, the unlock never answers
    +//! and the request repeats on every boot. While that one unlock runs
    +//! ([`Unlock`]), the guard lets the enclave rewrite one kind-4 locker it read
    +//! since probe, at level 1 on a warm-attach Mac, and only when the gigalocker's
    +//! revision at probe is past the last one Linux wrote
    +//! ([`REVISION_PATH`]), so a Linux-to-Linux boot never opens it. The
    +//! locker is not listed as Linux's, and the rewrite moves Linux's last
    +//! revision forward first, so the next boot's window stays shut unless another
    +//! OS writes again.
     
     use crate::shim::StoreFile;
     use crate::xart_store::{crc32_ieee, Key};
    @@ -62,6 +75,14 @@
     /// Refusals are logged individually up to this count, then only counted.
     const LOGGED_REFUSALS: usize = 8;
     
    +/// Host file holding the last gigalocker revision Linux wrote.
    +pub(crate) const REVISION_PATH: &CStr = c"/var/lib/aurora-sep-xart-revision.bin";
    +const REVISION_SIZE: usize = 16;
    +const REVISION_MAGIC: &[u8; 4] = b"AXGR";
    +/// Keys the enclave read since probe that the guard remembers; the gigalocker
    +/// has at most a few hundred slots.
    +const MAX_READ: usize = 512;
    +
     /// What the guard does with one enclave write or delete.
     #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     pub(crate) enum Verdict {
    @@ -108,6 +129,61 @@ pub(crate) fn first_setup_allows(level: u8, window: FirstSetup, key: &Key, write
         level == 1 && window == FirstSetup::Open && write && key.kind == 4
     }
     
    +/// Whether the first unlock of Linux's existing keybag after another OS wrote
    +/// the gigalocker is in progress.
    +#[derive(Clone, Copy, Debug, PartialEq, Eq)]
    +pub(crate) enum Unlock {
    +    Closed,
    +    /// The enclave may rewrite one kind-4 locker it read since probe.
    +    Open,
    +    /// It has; further refusals stand.
    +    Used,
    +}
    +
    +/// Whether a request the guard would refuse passes as the enclave's rewrite
    +/// during that unlock: a kind-4 rewrite (not a delete) at level 1, of a record
    +/// the enclave read since probe, while the window is open.
    +pub(crate) fn unlock_allows(level: u8, window: Unlock, key: &Key, write: bool, read: bool) -> bool {
    +    level == 1 && window == Unlock::Open && write && key.kind == 4 && read
    +}
    +
    +/// Whether another OS wrote the gigalocker since Linux last did: its revision
    +/// at probe is past Linux's last. Unknown is no.
    +pub(crate) fn foreign_writes(probe: u64, last: Option<u64>) -> bool {
    +    last.is_some_and(|last| probe > last)
    +}
    +
    +/// Encodes Linux's last gigalocker revision.
    +pub(crate) fn revision_bytes(revision: u64) -> [u8; REVISION_SIZE] {
    +    let mut bytes = [0u8; REVISION_SIZE];
    +    bytes[..4].copy_from_slice(REVISION_MAGIC);
    +    bytes[4..12].copy_from_slice(&revision.to_le_bytes());
    +    let crc = crc32_ieee(&bytes[..12]);
    +    bytes[12..].copy_from_slice(&crc.to_le_bytes());
    +    bytes
    +}
    +
    +/// Decodes Linux's last gigalocker revision; `None` when damaged.
    +pub(crate) fn revision_decode(bytes: &[u8]) -> Option<u64> {
    +    if bytes.len() != REVISION_SIZE || &bytes[..4] != REVISION_MAGIC {
    +        return None;
    +    }
    +    if u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]) != crc32_ieee(&bytes[..12]) {
    +        return None;
    +    }
    +    let mut value = [0u8; 8];
    +    value.copy_from_slice(&bytes[4..12]);
    +    Some(u64::from_le_bytes(value))
    +}
    +
    +/// The first eight bytes of a session id, enough to find the record with
    +/// `apfs-xart-inspect.py`.
    +fn short_id(key: &Key) -> u64 {
    +    let mut id = [0u8; 8];
    +    id.copy_from_slice(&key.uuid[..8]);
    +    u64::from_be_bytes(id)
    +}
    +
     /// The guard level for `xart_guard=param` on a platform whose profile
     /// defaults to `platform`, or `None` for no guard. A negative value takes the
     /// platform's level; a level above 2 is treated as 2, the strictest.
    @@ -246,18 +322,33 @@ pub(crate) struct Guard<F: ListFile = StoreFile> {
         existed: KVec<Key>,
         refused: usize,
         first_setup: FirstSetup,
    +    unlock: Unlock,
    +    /// Set by the boot's first unlock attempt, which alone may open the window.
    +    unlock_tried: bool,
    +    /// Kind-3 and kind-4 keys the enclave read since probe.
    +    read: KVec<Key>,
    +    /// Linux's last revision, `None` without one: no window can open.
    +    revision_file: Option<F>,
    +    /// The gigalocker's revision at probe and Linux's last as read then.
    +    probe_revision: u64,
    +    last_at_probe: Option<u64>,
     }
     
     impl Guard {
         /// Opens Linux's list in the host file and records which keys `existing`
         /// holds now. Never fails: a list that cannot be read protects every
         /// existing record.
    -    pub(crate) fn open(level: u8, existing: KVec<Key>) -> Guard {
    -        Guard::with_file(
    +    pub(crate) fn open(level: u8, existing: KVec<Key>, revision: u64) -> Guard {
    +        let mut guard = Guard::with_file(
                 level,
                 existing,
                 StoreFile::open_host(OWNED_PATH).map(|(file, _created)| file),
    -        )
    +        );
    +        guard.open_revision(
    +            revision,
    +            StoreFile::open_host(REVISION_PATH).map(|(file, _created)| file),
    +        );
    +        guard
         }
     }
     
    @@ -272,6 +363,12 @@ pub(crate) fn with_file(level: u8, existing: KVec<Key>, file: Result<F>) -> Guar
                 existed: existing,
                 refused: 0,
                 first_setup: FirstSetup::Closed,
    +            unlock: Unlock::Closed,
    +            unlock_tried: false,
    +            read: KVec::new(),
    +            revision_file: None,
    +            probe_revision: 0,
    +            last_at_probe: None,
             };
             // A list created this boot (or by a crashed one) is only safe to adopt
             // into once its name is durable: fsync() of the file alone does not
    @@ -384,6 +481,111 @@ pub(crate) fn close_first_setup(&mut self) {
             self.first_setup = FirstSetup::Closed;
         }
     
    +    /// Reads Linux's last gigalocker revision from `file`, with the store's
    +    /// `revision` at probe. Without a readable one it records `revision` as
    +    /// the baseline: only writes after it can then count as another OS's.
    +    pub(crate) fn open_revision(&mut self, revision: u64, file: Result<F>) {
    +        self.probe_revision = revision;
    +        let file = match file.and_then(|file| file.sync_parent().map(|()| file)) {
    +            Ok(file) => file,
    +            Err(e) => {
    +                pr_warn!("xART guard: Linux's last gigalocker revision could not be opened ({:?}); no unlock window\n", e);
    +                return;
    +            }
    +        };
    +        let mut bytes = [0u8; REVISION_SIZE];
    +        let last = match file.size() {
    +            Ok(size) if size == REVISION_SIZE as u64 => {
    +                file.read_exact(0, &mut bytes).ok().and_then(|()| revision_decode(&bytes))
    +            }
    +            _ => None,
    +        };
    +        match last {
    +            Some(last) => {
    +                let since = if revision > last { "another OS wrote since" } else { "no other writes" };
    +                pr_info!(
    +                    "xART guard: gigalocker revision {} at probe, Linux's last {}: {}\n",
    +                    revision,
    +                    last,
    +                    since
    +                );
    +                self.last_at_probe = Some(last);
    +            }
    +            None => {
    +                if let Err(e) = file.write_all(0, &revision_bytes(revision)).and_then(|()| file.sync()) {
    +                    pr_warn!("xART guard: Linux's last gigalocker revision could not be recorded ({:?}); no unlock window\n", e);
    +                    return;
    +                }
    +                pr_info!("xART guard: no record of Linux's last gigalocker revision; baseline {} recorded, no unlock window this boot\n", revision);
    +            }
    +        }
    +        self.revision_file = Some(file);
    +    }
    +
    +    /// Records `revision` as Linux's last before the enclave's write lands, so
    +    /// a crash in between leaves it ahead of the gigalocker, which opens no
    +    /// window. An error refuses the write.
    +    pub(crate) fn note_write(&mut self, revision: u64) -> Result<()> {
    +        let Some(file) = self.revision_file.as_ref() else {
    +            return Ok(());
    +        };
    +        file.write_all(0, &revision_bytes(revision))
    +            .and_then(|()| file.sync())
    +            .inspect_err(|e| {
    +                crate::diag::xart_guard_refused();
    +                self.refused += 1;
    +                pr_warn!("xART guard: Linux's last gigalocker revision could not be updated ({:?}); refusing the write\n", e);
    +            })
    +    }
    +
    +    /// Remembers that the enclave read `key`.
    +    pub(crate) fn note_read(&mut self, key: &Key) {
    +        if key.kind > 2 && self.read.len() < MAX_READ && !self.read.contains(key) {
    +            let _ = self.read.push(*key, GFP_KERNEL);
    +        }
    +    }
    +
    +    /// Opens the unlock window for the boot's first unlock of a keybag, when
    +    /// it is Linux's existing one (`existing`) on a warm-attach Mac (`warm`),
    +    /// the list loaded, and another OS wrote the gigalocker since Linux last
    +    /// did. Only the boot's first attempt can open it.
    +    pub(crate) fn open_unlock(&mut self, existing: bool, warm: bool) -> bool {
    +        if self.unlock_tried {
    +            return false;
    +        }
    +        self.unlock_tried = true;
    +        let shut = if self.level != 1 {
    +            Some("the guard is not at level 1")
    +        } else if !warm {
    +            Some("this Mac cold-boots its enclave")
    +        } else if !existing {
    +            Some("the keybag was created this boot")
    +        } else if self.file.is_none() {
    +            Some("Linux's list is not loaded")
    +        } else if self.revision_file.is_none() || self.last_at_probe.is_none() {
    +            Some("Linux's last gigalocker revision is not known")
    +        } else if !foreign_writes(self.probe_revision, self.last_at_probe) {
    +            Some("no other OS wrote the gigalocker since Linux last did")
    +        } else {
    +            None
    +        };
    +        if let Some(why) = shut {
    +            pr_info!("xART guard: no unlock window this boot: {}\n", why);
    +            return false;
    +        }
    +        self.unlock = Unlock::Open;
    +        pr_info!("xART guard: unlock window open for the first unlock of Linux's existing keybag\n");
    +        true
    +    }
    +
    +    /// Closes the unlock window, used or not.
    +    pub(crate) fn close_unlock(&mut self) {
    +        if self.unlock == Unlock::Open {
    +            pr_info!("xART guard: unlock window closed unused\n");
    +        }
    +        self.unlock = Unlock::Closed;
    +    }
    +
         fn adopt(&mut self, key: &Key) -> Result<()> {
             let file = self.file.as_ref().ok_or(ENOENT)?;
             // The file's length, not the number of distinct keys: a torn or
    @@ -430,15 +632,35 @@ pub(crate) fn check(&mut self, key: &Key, write: bool) -> Result<()> {
                     );
                     Ok(())
                 }
    +            Verdict::Refuse
    +                if unlock_allows(self.level, self.unlock, key, write, self.read.contains(key)) =>
    +            {
    +                self.unlock = Unlock::Used;
    +                pr_info!(
    +                    "xART guard: allowed one rewrite of existing kind-{} record {:016x} during the first unlock of Linux's keybag (gigalocker revision {} at probe, Linux's last {})\n",
    +                    key.kind,
    +                    short_id(key),
    +                    self.probe_revision,
    +                    self.last_at_probe.unwrap_or(0)
    +                );
    +                Ok(())
    +            }
                 Verdict::Refuse => {
                     crate::diag::xart_guard_refused();
                     self.refused += 1;
                     if self.refused <= LOGGED_REFUSALS {
                         let action = if write { "rewrite" } else { "delete" };
    +                    let outside = if self.unlock == Unlock::Open {
    +                        " (outside the unlock window: not a kind-4 rewrite of a record read since probe)"
    +                    } else {
    +                        ""
    +                    };
                         pr_warn!(
    -                        "xART guard: refused to {} a kind-{} record this Linux install did not create\n",
    +                        "xART guard: refused to {} kind-{} record {:016x}, which this Linux install did not create{}\n",
                             action,
    -                        key.kind
    +                        key.kind,
    +                        short_id(key),
    +                        outside
                         );
                     }
                     Err(EPERM)
    @@ -993,6 +1215,159 @@ fn without_a_durable_directory_entry_nothing_is_adopted() -> Result<()> {
             Ok(())
         }
     
    +    fn unlock_guard<'a>(
    +        list: &'a RefCell<KVec<u8>>,
    +        rev: &'a RefCell<KVec<u8>>,
    +        existing: &[Key],
    +        probe: u64,
    +    ) -> Result<Guard<MemFile<'a>>> {
    +        let mut guard = Guard::with_file(1, keys(existing)?, Ok(mem(list)));
    +        guard.open_revision(probe, Ok(mem(rev)));
    +        Ok(guard)
    +    }
    +
    +    #[test]
    +    fn unlock_allows_only_a_read_kind_4_rewrite_at_level_1() {
    +        let open = Unlock::Open;
    +        assert!(unlock_allows(1, open, &session(1), true, true));
    +        assert!(!unlock_allows(1, open, &session(1), true, false));
    +        assert!(!unlock_allows(1, open, &session(1), false, true));
    +        assert!(!unlock_allows(1, open, &Key::new(3, [1; 16]), true, true));
    +        assert!(!unlock_allows(2, open, &session(1), true, true));
    +        assert!(!unlock_allows(1, Unlock::Closed, &session(1), true, true));
    +        assert!(!unlock_allows(1, Unlock::Used, &session(1), true, true));
    +    }
    +
    +    #[test]
    +    fn foreign_writes_need_a_known_older_revision() {
    +        assert!(foreign_writes(3350, Some(3226)));
    +        assert!(!foreign_writes(3226, Some(3226)));
    +        assert!(!foreign_writes(3000, Some(3226)));
    +        assert!(!foreign_writes(3350, None));
    +    }
    +
    +    #[test]
    +    fn revision_entries_round_trip_and_reject_damage() {
    +        let bytes = revision_bytes(0x1234_5678_9abc);
    +        assert_eq!(revision_decode(&bytes), Some(0x1234_5678_9abc));
    +        let mut bad = bytes;
    +        bad[5] ^= 1;
    +        assert_eq!(revision_decode(&bad), None);
    +        assert_eq!(revision_decode(&bytes[..15]), None);
    +        assert_eq!(revision_decode(&encode(&session(1))[..16]), None);
    +    }
    +
    +    #[test]
    +    fn a_first_boot_records_a_baseline_and_opens_no_window() -> Result<()> {
    +        let (list, rev) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()));
    +        let locker = session(1);
    +        let mut guard = unlock_guard(&list, &rev, &[locker], 3226)?;
    +        assert_eq!(revision_decode(&rev.borrow()), Some(3226));
    +        guard.note_read(&locker);
    +        assert!(!guard.open_unlock(true, true));
    +        assert_eq!(guard.check(&locker, true), Err(EPERM));
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn after_another_os_wrote_one_read_locker_may_be_rewritten() -> Result<()> {
    +        let (list, rev) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()));
    +        rev.borrow_mut().extend_from_slice(&revision_bytes(3226), GFP_KERNEL)?;
    +        let (read, unread, user) = (session(1), session(2), Key::new(3, [3; 16]));
    +        let mut guard = unlock_guard(&list, &rev, &[read, unread, user], 3350)?;
    +        guard.note_read(&read);
    +        guard.note_read(&user);
    +        // Outside the window the locker is protected as before.
    +        assert_eq!(guard.check(&read, true), Err(EPERM));
    +        assert!(guard.open_unlock(true, true));
    +        // Not a delete, not kind 3, not a record the enclave did not read.
    +        assert_eq!(guard.check(&read, false), Err(EPERM));
    +        assert_eq!(guard.check(&user, true), Err(EPERM));
    +        assert_eq!(guard.check(&unread, true), Err(EPERM));
    +        assert_eq!(guard.check(&read, true), Ok(()));
    +        // One rewrite only, and the locker does not become Linux's.
    +        assert_eq!(guard.check(&read, true), Err(EPERM));
    +        assert_eq!(list.borrow().len(), 0);
    +        guard.close_unlock();
    +        // Once per boot, used or not.
    +        assert!(!guard.open_unlock(true, true));
    +        assert_eq!(guard.refused, 5);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn the_window_stays_shut_without_its_conditions() -> Result<()> {
    +        let locker = session(1);
    +        for (level, existing, warm, probe) in
    +            [(2, true, true, 3350), (1, false, true, 3350), (1, true, false, 3350), (1, true, true, 3226)]
    +        {
    +            let (list, rev) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()));
    +            rev.borrow_mut().extend_from_slice(&revision_bytes(3226), GFP_KERNEL)?;
    +            let mut guard = Guard::with_file(level, keys(&[locker])?, Ok(mem(&list)));
    +            guard.open_revision(probe, Ok(mem(&rev)));
    +            guard.note_read(&locker);
    +            assert!(!guard.open_unlock(existing, warm));
    +            assert_eq!(guard.check(&locker, true), Err(EPERM));
    +        }
    +        // No list loaded.
    +        let (list, rev, faults) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()), Faults::default());
    +        rev.borrow_mut().extend_from_slice(&revision_bytes(3226), GFP_KERNEL)?;
    +        faults.parent.set(true);
    +        let mut guard = Guard::with_file(1, keys(&[locker])?, Ok(faulty(&list, &faults)));
    +        guard.open_revision(3350, Ok(mem(&rev)));
    +        assert!(!guard.open_unlock(true, true));
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn a_write_moves_linux_s_last_revision_first_and_shuts_the_next_window() -> Result<()> {
    +        let (list, rev) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()));
    +        rev.borrow_mut().extend_from_slice(&revision_bytes(3226), GFP_KERNEL)?;
    +        let locker = session(1);
    +        let mut guard = unlock_guard(&list, &rev, &[locker], 3350)?;
    +        guard.note_read(&locker);
    +        assert!(guard.open_unlock(true, true));
    +        assert_eq!(guard.check(&locker, true), Ok(()));
    +        assert_eq!(guard.note_write(3351), Ok(()));
    +        assert_eq!(revision_decode(&rev.borrow()), Some(3351));
    +        // The next boot, with no other OS in between, opens no window.
    +        let mut next = unlock_guard(&list, &rev, &[locker], 3351)?;
    +        next.note_read(&locker);
    +        assert!(!next.open_unlock(true, true));
    +        assert_eq!(next.check(&locker, true), Err(EPERM));
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn a_revision_that_cannot_be_recorded_refuses_the_write() -> Result<()> {
    +        let (list, rev, faults) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()), Faults::default());
    +        rev.borrow_mut().extend_from_slice(&revision_bytes(3226), GFP_KERNEL)?;
    +        let mut guard = Guard::with_file(1, KVec::new(), Ok(mem(&list)));
    +        guard.open_revision(3226, Ok(faulty(&rev, &faults)));
    +        faults.write.set(true);
    +        assert_eq!(guard.note_write(3227), Err(EIO));
    +        faults.write.set(false);
    +        faults.sync.set(true);
    +        assert_eq!(guard.note_write(3227), Err(EIO));
    +        assert_eq!(guard.refused, 2);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn a_damaged_revision_file_opens_no_window() -> Result<()> {
    +        let (list, rev) = (RefCell::new(KVec::new()), RefCell::new(KVec::new()));
    +        let mut damaged = revision_bytes(3226);
    +        damaged[13] ^= 1;
    +        rev.borrow_mut().extend_from_slice(&damaged, GFP_KERNEL)?;
    +        let locker = session(1);
    +        let mut guard = unlock_guard(&list, &rev, &[locker], 3350)?;
    +        guard.note_read(&locker);
    +        assert!(!guard.open_unlock(true, true));
    +        // It is rewritten as a new baseline.
    +        assert_eq!(revision_decode(&rev.borrow()), Some(3350));
    +        Ok(())
    +    }
    +
         #[test]
         fn the_default_follows_the_platform() {
             use crate::profile;
    diff --git a/drivers/soc/apple/xart_store.rs b/drivers/soc/apple/xart_store.rs
    index 9901912d8..e473c91c5 100644
    --- a/drivers/soc/apple/xart_store.rs
    +++ b/drivers/soc/apple/xart_store.rs
    @@ -316,6 +316,9 @@ pub(crate) fn read(&mut self, key: &Key) -> Result<Option<KVec<u8>>> {
             let Some(idx) = self.find(key) else {
                 return Ok(None);
             };
    +        if let Some(guard) = self.guard.as_mut() {
    +            guard.note_read(key);
    +        }
             let slot = self.slots[idx];
             let mut raw = KVec::with_capacity(SLOT_SIZE, GFP_KERNEL)?;
             raw.resize(SLOT_SIZE, 0, GFP_KERNEL)?;
    @@ -351,14 +354,15 @@ pub(crate) fn write(&mut self, key: &Key, value: &[u8]) -> Result<()> {
                 return Err(EINVAL);
             }
     
    -        if let Some(guard) = self.guard.as_mut() {
    -            guard.check(key, true)?;
    -        }
    -
             let old = self.find(key);
             // A new key skips the first free slot; a replacement reuses it.
             let fresh = self.find_free(usize::from(old.is_none())).ok_or(ENOSPC)?;
             let revision = self.revision.checked_add(1).ok_or(EINVAL)?;
    +
    +        if let Some(guard) = self.guard.as_mut() {
    +            guard.check(key, true)?;
    +            guard.note_write(revision)?;
    +        }
             let crc = crc32_ieee(value);
     
             let mut raw = KVec::with_capacity(SLOT_SIZE, GFP_KERNEL)?;
    @@ -430,7 +434,7 @@ pub(crate) fn live_keys(&self) -> Result<KVec<Key>> {
         /// create. See [`crate::xart_guard`].
         pub(crate) fn set_guard(&mut self, level: u8) -> Result<()> {
             let keys = self.live_keys()?;
    -        self.guard = Some(crate::xart_guard::Guard::open(level, keys));
    +        self.guard = Some(crate::xart_guard::Guard::open(level, keys, self.revision));
             Ok(())
         }
     
    @@ -456,6 +460,19 @@ pub(crate) fn close_first_setup(&mut self) {
             }
         }
     
    +    /// Opens the guard's unlock window (see [`crate::xart_guard`]).
    +    pub(crate) fn open_unlock(&mut self, existing: bool, warm: bool) -> bool {
    +        self.guard
    +            .as_mut()
    +            .is_some_and(|guard| guard.open_unlock(existing, warm))
    +    }
    +
    +    pub(crate) fn close_unlock(&mut self) {
    +        if let Some(guard) = self.guard.as_mut() {
    +            guard.close_unlock();
    +        }
    +    }
    +
         /// Byte offset of the APFS-resolved gigalocker extent in the container.
         pub(crate) fn base(&self) -> u64 {
             self.base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions