From b8bb32d47b0bbcd60387d4d85d4de223f1531676 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 02:55:41 -0500 Subject: [PATCH 1/4] soc: apple: sep: report a refused identity unlock in diag/trusted Every trusted-key seal and unseal on the 13.5 key store first unlocks the identity key bag (DEVICE_STATE_TRANSITION on the designated user's special handle). When the enclave answers that unlock with a non-zero status, the driver logs "ref-key identity unlock refused (status N)" and the seal or unseal fails with EIO. Nothing outside the kernel log says so, and a caller cannot tell this from a key store that is still coming up. On a J313 running the 27.2.1 sepOS the unlock is refused with status -8 on every boot, while the key-store init, LOAD and DESIGNATE still answer. aurora-sep-load, which cannot see the refusal, retries the seal at 10 Hz until its 120 s deadline: about 1200 refused seals and kernel warnings per run, and the unit is started again on every fprintd activation. Add diag/trusted, which reads: unknown no trusted-key unseal has worked and no unlock was refused ready the latest trusted-key unseal worked (a seal unseals its new blob before returning it, so a working seal counts) refused the enclave answered the identity unlock with status The latest outcome wins, so an unseal that works after a refusal reads "ready" again, and the value resets to "unknown" when the driver binds. State and status share one atomic word, so a reader never pairs a state with another refusal's status. The value comes from the enclave's own answer: no chip, board or firmware version is consulted, and a Mac whose enclave unlocks the bag sees only "unknown" and "ready". Signed-off-by: Erik Bourget --- .../ABI/testing/sysfs-driver-apple-sep | 28 +++++++++++++++++ drivers/soc/apple/diag.rs | 22 +++++++++++++ drivers/soc/apple/diag_shim.c | 31 +++++++++++++++++++ drivers/soc/apple/refkey.rs | 5 +++ drivers/soc/apple/shim.h | 9 ++++++ tools/aurora-sep/tests/test_keystore_only.py | 4 +++ 6 files changed, 99 insertions(+) diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index b2d673ca52ef1..452241ec139c4 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -594,3 +594,31 @@ Description: power domains stay on across sleep, so every other attribute keeps its value over a suspend; a reader checking that the enclave still answers after a resume reads the hwrng. + +What: /sys/bus/platform/devices/.sep/diag/trusted +Date: November 2026 +KernelVersion: 7.3 +Contact: Erik Bourget +Description: + (RO) What the next trusted-key seal or unseal can expect of + the enclave, from the latest one this bind sent. + + ============== ============================================== + unknown No trusted-key unseal has worked and the + enclave has refused no identity unlock yet. + ready The latest trusted-key unseal worked. A seal + unseals its new blob before returning it, so + a working seal also reads "ready". + refused The enclave answered the identity key-bag + unlock, which every seal and unseal on the + 13.5 key store needs first, with status + (a signed decimal). Trusted keys fail until + an unlock works. + ============== ============================================== + + A refusal is the enclave's answer for this key bag, not a + lost reply, and a test or loader stops on it rather than + asking again. An xART guard refusal (xart_guard_refusals) + can cause one: check that first. A later unseal that works + changes the value back to "ready". The value resets to + "unknown" when the driver binds. diff --git a/drivers/soc/apple/diag.rs b/drivers/soc/apple/diag.rs index 9260cc09151c2..be0238c2f76df 100644 --- a/drivers/soc/apple/diag.rs +++ b/drivers/soc/apple/diag.rs @@ -52,6 +52,7 @@ extern "C" { 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_xart_guard_refused(matching: c_int); + fn sep_diag_set_trusted(state: c_int, status: c_int); fn sep_diag_bringup_ended(); fn sep_diag_set_endpoint(id: u8, name: u32); fn sep_diag_set_os_identity(source: c_int); @@ -287,6 +288,27 @@ pub(crate) fn xart_guard_refused() { unsafe { sep_diag_xart_guard_refused(matching() as c_int) }; } +/// What the next trusted-key seal or unseal can expect, as +/// `SEP_DIAG_TRUSTED_*` in `shim.h` spells it. +#[derive(Clone, Copy)] +pub(crate) enum Trusted { + /// A trusted-key unseal, on its own or as a seal's round trip, worked. + Ready, + /// The enclave answered the identity key-bag unlock that every seal and + /// unseal needs with this status. + Refused(i8), +} + +/// The latest trusted-key outcome; it replaces the one before. +pub(crate) fn trusted(state: Trusted) { + let (state, status) = match state { + Trusted::Ready => (1, 0), + Trusted::Refused(status) => (2, status), + }; + // SAFETY: no preconditions; stores one word. + unsafe { sep_diag_set_trusted(state, c_int::from(status)) }; +} + /// The boot-time bring-up is over, however far it got. pub(crate) fn bringup_ended() { // SAFETY: no preconditions; updates two words. diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 51453c19297f0..806d9aff65218 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -120,6 +120,8 @@ static struct { atomic_t unhandled; atomic_t sleeps; atomic_t sleeping; + /* SEP_DIAG_TRUSTED_*, with the refusal status above it. */ + atomic_t trusted; struct kernfs_node *keystore_kn; struct kernfs_node *touchid_kn; @@ -717,6 +719,23 @@ static ssize_t sleep_show(struct device *dev, struct device_attribute *attr, } static DEVICE_ATTR_RO(sleep); +static ssize_t trusted_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + int word = atomic_read(&sep_diag.trusted); + + switch (word & 0xff) { + case SEP_DIAG_TRUSTED_READY: + return sysfs_emit(buf, "ready\n"); + case SEP_DIAG_TRUSTED_REFUSED: + /* One word, so the status is the one this refusal stored. */ + return sysfs_emit(buf, "refused %d\n", (s8)(word >> 8)); + default: + return sysfs_emit(buf, "unknown\n"); + } +} +static DEVICE_ATTR_RO(trusted); + static struct attribute *sep_diag_attrs[] = { &dev_attr_abi.attr, &dev_attr_profile.attr, @@ -753,6 +772,7 @@ static struct attribute *sep_diag_attrs[] = { &dev_attr_unhandled_messages.attr, &dev_attr_sleeps.attr, &dev_attr_sleep.attr, + &dev_attr_trusted.attr, NULL }; @@ -779,6 +799,8 @@ int sep_diag_register(struct device *dev, const char *profile, sep_diag.sepos13 = sepos13; sep_diag.xart = xart; sep_diag.probe_ns = ktime_get_boottime_ns(); + /* A refusal belongs to the bind that saw it. */ + atomic_set(&sep_diag.trusted, SEP_DIAG_TRUSTED_UNKNOWN); ret = devm_device_add_group(dev, &sep_diag_group); if (ret) @@ -1017,6 +1039,15 @@ void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, atomic_set(&sep_diag.matching, matching); } +/* + * The latest answer wins: a success after a refusal (or the reverse) is what + * the next seal or unseal can expect. + */ +void sep_diag_set_trusted(int state, int status) +{ + atomic_set(&sep_diag.trusted, (state & 0xff) | ((u8)status << 8)); +} + /* With matching as the refusal leaves it. */ void sep_diag_xart_guard_refused(int matching) { diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index f0fde4827754a..b38d4eecc4f7e 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -102,6 +102,9 @@ impl SepData { "sks: ref-key identity unlock refused (status {})\n", out.reply.status ); + // An answer, not a lost reply: the enclave decided on this bag. + // diag/trusted lets readers stop on it instead of asking again. + crate::diag::trusted(crate::diag::Trusted::Refused(out.reply.status)); return false; } let Some(body) = self.sks_report_response(c"DEVICE_STATE_TRANSITION", &out) else { @@ -342,6 +345,8 @@ impl SepData { drop(crate::Secret(recovered)); return Err(EIO); // trusted.rs maps every unseal rejection to EBADMSG. } + // A seal's round trip ends here too. + crate::diag::trusted(crate::diag::Trusted::Ready); Ok(recovered) } diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 456492d6e8afe..d58aa37b2a2ee 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -209,6 +209,14 @@ int sep_sensor_irq_wait(unsigned int timeout_ms); #define SEP_DIAG_PNON_FAILED 3 #define SEP_DIAG_PNON_DIGEST_LEN 48 +/* + * Mirrored by diag.rs (Trusted). The word keeps the state in its low byte and, + * for SEP_DIAG_TRUSTED_REFUSED, the enclave's status in the next one. + */ +#define SEP_DIAG_TRUSTED_UNKNOWN 0 +#define SEP_DIAG_TRUSTED_READY 1 +#define SEP_DIAG_TRUSTED_REFUSED 2 + /* Mirrored by diag.rs (Offer): endpoints checked at bring-up, sent nothing. */ #define SEP_DIAG_OFFER_PENDING 0 #define SEP_DIAG_OFFER_IDLE 1 @@ -238,6 +246,7 @@ void sep_diag_set_restore(int state); void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, int matching); void sep_diag_xart_guard_refused(int matching); +void sep_diag_set_trusted(int state, int status); void sep_diag_bringup_ended(void); void sep_diag_set_endpoint(u8 id, u32 name); void sep_diag_set_os_identity(int source); diff --git a/tools/aurora-sep/tests/test_keystore_only.py b/tools/aurora-sep/tests/test_keystore_only.py index 3ebf2738ce61b..b8eb5e246610e 100644 --- a/tools/aurora-sep/tests/test_keystore_only.py +++ b/tools/aurora-sep/tests/test_keystore_only.py @@ -63,6 +63,10 @@ def test_production_cache_and_unseal_refusal(self): mod attach { ALLOW } +mod diag { + pub enum Trusted { Ready } + pub fn trusted(_: Trusted) {} +} struct SepData { identity_keybag: Cache, keystore_only: AtomicBool, From d32a863c55ff83f6e483e9b7c7ccddb75bac998b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 02:55:41 -0500 Subject: [PATCH 2/4] tools/aurora-sep: stop the loader when the enclave refuses the unlock aurora-sep-load probes trusted keys with a seal and unseal every 0.1 s until AURORA_SEP_READY_TIMEOUT (120 s). Its only early exit is an xART guard refusal. When the enclave refuses the identity key-bag unlock that every seal needs, the probe repeats the same refused request about 1200 times, burns several seconds of CPU and logs a refusal and a "key_seal failed (-5)" line for each attempt. fprintd's drop-in requires aurora-sep.service, so every fprintd activation (a desktop shell polls fprintd-list every few seconds) starts the 120 s run again. Read the driver's diag/trusted after each failed probe and stop at the first "refused ", logging the status and that the key bag and ref-key are kept. A run started again in the same boot reads the attribute before it probes, so it sends no seal at all. An xART guard refusal is still checked first and keeps its own message, since it has a way out (aurora-sep-policy-change). Kernels without diag/trusted read nothing there and keep the old probe-until-deadline behaviour, as do enclaves that answer late rather than refuse. The tests run the shipped loader against a synthetic sysfs and a fake keyctl: the first refusal ends the run after one seal, a re-run sends none, a guard refusal keeps its message, a kernel without the attribute still waits for the deadline, and a working enclave still verifies. They also compile the driver's diag/trusted show and setter and check all three values, with negative and positive statuses. Signed-off-by: Erik Bourget --- tools/aurora-sep/README.md | 5 + tools/aurora-sep/load-driver | 41 +++- .../aurora-sep/tests/test_trusted_refused.py | 192 ++++++++++++++++++ 3 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 tools/aurora-sep/tests/test_trusted_refused.py diff --git a/tools/aurora-sep/README.md b/tools/aurora-sep/README.md index b408ac8f72413..d91bddcd6f8a9 100644 --- a/tools/aurora-sep/README.md +++ b/tools/aurora-sep/README.md @@ -53,6 +53,11 @@ for example with `systemctl edit aurora-sep.service`: Environment=AURORA_SEP_READY_TIMEOUT=180 ``` +The loader does not wait when the enclave refuses the identity key-bag unlock +that trusted keys need: the driver's `diag/trusted` then reads +`refused `, and the loader logs it and exits at once, because asking +again gets the same answer. + SEP writes are always on: xART writes and identity-keybag provisioning have no switch. The driver's `xart_writes` and `provision_keybag` parameters were removed (aurora-silicon/linux#2591), and a stale value on the kernel command diff --git a/tools/aurora-sep/load-driver b/tools/aurora-sep/load-driver index 481e63af7e852..de3c56fb8b8f2 100755 --- a/tools/aurora-sep/load-driver +++ b/tools/aurora-sep/load-driver @@ -85,6 +85,31 @@ guard_refused() { [ -n "$refusals" ] && [ "$refusals" != 0 ] } +guard_exit() { + log "the xART guard refused a record the enclave needs to unlock Linux's keybag. After a boot policy change (a new Stage 1 or boot object) the driver lets that one update through by itself; this one it could not. Touch ID and its fingerprints are intact. To allow it on the next boot, run aurora-sep-policy-change and reboot; see XART-SAFETY.md" + exit 1 +} + +# The driver's diag/trusted reads "refused " once the enclave has +# answered the identity key-bag unlock that every seal and unseal needs with a +# refusal. That is the enclave's decision on this bag, not a slow bring-up: +# asking again at 10 Hz until the deadline only repeats it (about 1200 refused +# seals and kernel warnings per run). Kernels without the attribute read empty +# here and keep the old behaviour. +trusted_refused() { + [ -n "$diag" ] || return 1 + trusted=$(cat "$diag/trusted" 2>/dev/null || true) + case "$trusted" in + refused*) return 0 ;; + esac + return 1 +} + +refused_exit() { + log "the enclave refused to unlock the identity key bag that trusted keys need (diag/trusted: $trusted). Asking again gets the same answer, so this run stops here; trusted keys are unavailable this boot. The key bag and ref-key are left as they are: do not replace them to get past this" + exit 1 +} + start=$(uptime_s) deadline=$((start + ready_timeout)) @@ -103,6 +128,16 @@ for keystore in /sys/bus/platform/drivers/apple_sep/*/diag/keystore; do done done +# A run started again this boot (fprintd's dependency starts this unit on +# every activation) needs no probe to learn the answer. When the xART guard +# refused too, its message names the way out, so it comes first, as below. +if trusted_refused; then + if guard_refused; then + guard_exit + fi + refused_exit +fi + verified=false while :; do key_id=$(printf 'new 32' | keyctl padd trusted aurora-sep-check @s 2>/dev/null || true) @@ -119,8 +154,10 @@ while :; do fi [ "$verified" = true ] && break if guard_refused; then - log "the xART guard refused a record the enclave needs to unlock Linux's keybag. After a boot policy change (a new Stage 1 or boot object) the driver lets that one update through by itself; this one it could not. Touch ID and its fingerprints are intact. To allow it on the next boot, run aurora-sep-policy-change and reboot; see XART-SAFETY.md" - exit 1 + guard_exit + fi + if trusted_refused; then + refused_exit fi [ "$(uptime_s)" -lt "$deadline" ] || break sleep 0.1 diff --git a/tools/aurora-sep/tests/test_trusted_refused.py b/tools/aurora-sep/tests/test_trusted_refused.py new file mode 100644 index 0000000000000..6d476e56bd14b --- /dev/null +++ b/tools/aurora-sep/tests/test_trusted_refused.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""diag/trusted reports an enclave refusal, and the loader stops on it. + +The loader runs as shipped against a synthetic sysfs and a fake keyctl, so the +test sees the same control flow as aurora-sep.service: how many seals it sends +and how it exits. +""" +import os +import re +import shutil +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +SHIM = ROOT / 'drivers/soc/apple/diag_shim.c' +HEADER = ROOT / 'drivers/soc/apple/shim.h' +LOADER = ROOT / 'tools/aurora-sep/load-driver' + + +def function(text, name): + match = re.search(r'^(?:static ssize_t|void) ' + name + r'\(', text, re.M) + if not match: + raise AssertionError(name) + start = text.index('{', match.start()) + depth = 1 + at = start + 1 + while depth: + depth += (text[at] == '{') - (text[at] == '}') + at += 1 + return text[match.start():at] + + +class ShowTests(unittest.TestCase): + def test_states_and_signed_status(self): + compiler = shutil.which('cc') + self.assertIsNotNone(compiler, 'C compiler required; do not count a skip as a pass') + text = SHIM.read_text() + state = re.search(r'static struct \{.*?\} sep_diag;', text, re.S).group(0) + defines = '\n'.join(re.findall(r'^#define SEP_DIAG_(?:TRUSTED_\w+|MAX_EP)\s+\S+$', + HEADER.read_text() + text, re.M)) + body = function(text, 'trusted_show') + function(text, 'sep_diag_set_trusted') + prefix = '''#include +#include +#include +#include +typedef uint64_t u64; +typedef uint32_t u32; +typedef uint8_t u8; +typedef int8_t s8; +typedef int atomic_t; +typedef int64_t atomic64_t; +#define DECLARE_BITMAP(name, bits) unsigned long name[((bits) + 63) / 64] +struct device { int unused; }; +struct device_attribute { int unused; }; +#define atomic_read(p) (*(p)) +#define atomic_set(p, v) (*(p) = (v)) +static int sysfs_emit(char *out, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +static int sysfs_emit(char *out, const char *fmt, ...) { + va_list args; va_start(args, fmt); int n = vsnprintf(out, 4096, fmt, args); va_end(args); return n; +} +''' + main = '''int main(void) { + char out[4096]; + trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, -8); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_set_trusted(SEP_DIAG_TRUSTED_READY, 0); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, -128); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, 127); trusted_show(NULL, NULL, out); fputs(out, stdout); + return 0; +} +''' + with tempfile.TemporaryDirectory() as tmp: + source, program = Path(tmp) / 'trusted.c', Path(tmp) / 'trusted' + source.write_text(prefix + defines + '\n' + state + body + main) + subprocess.run([compiler, '-std=gnu11', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', str(source), '-o', str(program)], check=True) + lines = subprocess.check_output([str(program)], text=True).splitlines() + self.assertEqual(lines, ['unknown', 'refused -8', 'ready', 'refused -128', 'refused 127']) + + +# keyctl as the loader uses it. A refused seal writes what the driver would +# record, when FAKE_REFUSE is set, and prints no key id. +KEYCTL = r'''#!/bin/sh +case "$1" in + padd) + cat >/dev/null + echo x >>"$CALLS" + if [ -n "${FAKE_REFUSE:-}" ]; then + [ -d "$DIAG" ] && [ -n "${FAKE_TRUSTED:-}" ] && printf 'refused -8\n' >"$DIAG/trusted" + exit 1 + fi + if [ -n "${FAKE_WORK:-}" ]; then + echo 1234 + exit 0 + fi + exit 1 + ;; + pipe) printf 'c0ffee\n' ;; + revoke) ;; +esac +''' + + +class LoaderTests(unittest.TestCase): + def run_loader(self, trusted=None, guard='0', refuse=True, work=False, timeout='120'): + tmp = Path(tempfile.mkdtemp(prefix='sep-trusted-refused-')) + self.addCleanup(shutil.rmtree, tmp) + diag = tmp / 'devices/1234.sep/diag' + diag.mkdir(parents=True) + (tmp / 'drivers/apple_sep').mkdir(parents=True) + os.symlink(tmp / 'devices/1234.sep', tmp / 'drivers/apple_sep/1234.sep') + (diag / 'keystore').write_text('open\n') + (diag / 'xart_guard_refusals').write_text(guard + '\n') + if trusted is not None: + (diag / 'trusted').write_text(trusted + '\n') + (tmp / 'run').mkdir() + for name in ('keybag', 'refkey'): + (tmp / name).write_text('x') + bin_dir = tmp / 'bin' + bin_dir.mkdir() + for name, body in (('keyctl', KEYCTL), ('modprobe', '#!/bin/sh\n'), + ('journalctl', '#!/bin/sh\n')): + (bin_dir / name).write_text(body) + (bin_dir / name).chmod(0o755) + source = (LOADER.read_text() + .replace('/sys/module/apple_sep/parameters/keystore_only', str(tmp / 'none')) + .replace('/sys/bus/platform/devices', str(tmp / 'devices')) + .replace('/sys/bus/platform/drivers', str(tmp / 'drivers')) + .replace('/run/aurora-sep-load', str(tmp / 'run/aurora-sep-load')) + .replace('/var/lib/aurora-sep-keybag.bin', str(tmp / 'keybag')) + .replace('/var/lib/aurora-sep-refkey.bin', str(tmp / 'refkey'))) + script = tmp / 'load-driver' + script.write_text(source) + calls = tmp / 'calls' + env = dict(os.environ, AURORA_SEP_SESSION='1', CALLS=str(calls), DIAG=str(diag), + AURORA_SEP_READY_TIMEOUT=timeout, + PATH=str(bin_dir) + os.pathsep + os.environ['PATH']) + env.pop('FAKE_REFUSE', None) + env.pop('FAKE_WORK', None) + if refuse: + env['FAKE_REFUSE'] = '1' + if trusted is not None: + env['FAKE_TRUSTED'] = '1' + if work: + env['FAKE_WORK'] = '1' + began = time.monotonic() + done = subprocess.run(['sh', str(script)], env=env, capture_output=True, text=True, + timeout=30) + seals = len(calls.read_text().splitlines()) if calls.exists() else 0 + return done, seals, time.monotonic() - began + + def test_first_refusal_stops_the_probe(self): + done, seals, took = self.run_loader(trusted='unknown') + self.assertEqual(done.returncode, 1, done.stderr) + self.assertEqual(seals, 1) + self.assertLess(took, 10) + self.assertIn('diag/trusted: refused -8', done.stderr) + + def test_rerun_sends_no_seal(self): + done, seals, _ = self.run_loader(trusted='refused -8') + self.assertEqual(done.returncode, 1, done.stderr) + self.assertEqual(seals, 0) + self.assertIn('diag/trusted: refused -8', done.stderr) + + def test_guard_refusal_is_named_first(self): + for trusted in ('unknown', 'refused -8'): + with self.subTest(trusted=trusted): + done, seals, _ = self.run_loader(trusted=trusted, guard='1') + self.assertEqual(done.returncode, 1, done.stderr) + self.assertLessEqual(seals, 1) + self.assertIn('xART guard refused', done.stderr) + self.assertNotIn('diag/trusted', done.stderr) + + def test_without_the_attribute_the_deadline_still_applies(self): + done, seals, _ = self.run_loader(trusted=None, timeout='1') + self.assertEqual(done.returncode, 1, done.stderr) + self.assertGreater(seals, 1) + self.assertIn('within 1 s', done.stderr) + + def test_ready_kernel_still_verifies(self): + done, seals, _ = self.run_loader(trusted='ready', refuse=False, work=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(seals, 2) + self.assertIn('trusted keys work', done.stderr) + + +if __name__ == '__main__': + unittest.main() From 77114190bfb4d6c92de54ce94d69b76888757654 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 02:52:16 -0500 Subject: [PATCH 3/4] soc: apple: sep: clear stale diag/trusted refusal on identity unlock sks_prepare_identity_refkey() latches diag/trusted to "refused " when the enclave refuses the identity key-bag unlock, so aurora-sep-load stops without retrying for 120 s. A subsequent successful unlock through /dev/sep-key (with_identity_bag()) calls sks_prepare_identity_refkey() as well, without going through refkey_unseal_trusted(), so diag/trusted stayed "refused " and caused later loader runs to exit before probing. Add sep_diag_clear_trusted_refusal() and call it from sks_prepare_identity_refkey() only when the DEVICE_STATE_TRANSITION reply validates (status 0, 20-byte body with zero header). Using atomic_try_cmpxchg(), it clears SEP_DIAG_TRUSTED_REFUSED back to SEP_DIAG_TRUSTED_UNKNOWN while leaving SEP_DIAG_TRUSTED_READY untouched so "ready" remains tied to a working trusted-key unseal. Update Documentation/ABI/testing/sysfs-driver-apple-sep and extend tools/aurora-sep/tests/test_trusted_refused.py and the apple_sep KUnit tests (apple_sep_refkey_trusted) to cover refusal clearing and recovery. Signed-off-by: Erik Bourget --- .../ABI/testing/sysfs-driver-apple-sep | 7 +- drivers/soc/apple/diag.rs | 51 +++++++++++++-- drivers/soc/apple/diag_shim.c | 27 +++++++- drivers/soc/apple/refkey.rs | 64 ++++++++++++++++++- drivers/soc/apple/shim.h | 3 + .../aurora-sep/tests/test_trusted_refused.py | 57 ++++++++++++++--- 6 files changed, 189 insertions(+), 20 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index 452241ec139c4..d575f242da296 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -619,6 +619,7 @@ Description: A refusal is the enclave's answer for this key bag, not a lost reply, and a test or loader stops on it rather than asking again. An xART guard refusal (xart_guard_refusals) - can cause one: check that first. A later unseal that works - changes the value back to "ready". The value resets to - "unknown" when the driver binds. + can cause one: check that first. A later identity unlock that + works clears a stale refusal back to "unknown", and a later + unseal that works changes the value to "ready". The value + resets to "unknown" when the driver binds. diff --git a/drivers/soc/apple/diag.rs b/drivers/soc/apple/diag.rs index be0238c2f76df..079ffba1a9b8c 100644 --- a/drivers/soc/apple/diag.rs +++ b/drivers/soc/apple/diag.rs @@ -53,6 +53,15 @@ extern "C" { fn sep_diag_set_xart_guard(level: c_uint, list_loaded: bool, matching: c_int); fn sep_diag_xart_guard_refused(matching: c_int); fn sep_diag_set_trusted(state: c_int, status: c_int); + #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] + fn sep_diag_set_trusted_atomic( + word: *mut kernel::bindings::atomic_t, + state: c_int, + status: c_int, + ); + fn sep_diag_clear_trusted_refusal(); + #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] + fn sep_diag_clear_trusted_refusal_atomic(word: *mut kernel::bindings::atomic_t); fn sep_diag_bringup_ended(); fn sep_diag_set_endpoint(id: u8, name: u32); fn sep_diag_set_os_identity(source: c_int); @@ -299,14 +308,46 @@ pub(crate) enum Trusted { Refused(i8), } +impl Trusted { + fn raw(self) -> (c_int, c_int) { + match self { + Trusted::Ready => (1, 0), + Trusted::Refused(status) => (2, c_int::from(status)), + } + } +} + /// The latest trusted-key outcome; it replaces the one before. pub(crate) fn trusted(state: Trusted) { - let (state, status) = match state { - Trusted::Ready => (1, 0), - Trusted::Refused(status) => (2, status), - }; + let (state, status) = state.raw(); // SAFETY: no preconditions; stores one word. - unsafe { sep_diag_set_trusted(state, c_int::from(status)) }; + unsafe { sep_diag_set_trusted(state, status) }; +} + +/// Clears a stale refusal after a validated identity unlock, leaving `Ready` +/// tied to a working trusted-key unseal. +pub(crate) fn clear_trusted_refusal() { + // SAFETY: no preconditions; updates one atomic word. + unsafe { sep_diag_clear_trusted_refusal() }; +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +pub(crate) fn set_trusted_for_test(word: &Atomic, state: Trusted) { + kernel::static_assert!(size_of::>() == size_of::()); + kernel::static_assert!(align_of::>() == align_of::()); + let (state, status) = state.raw(); + // SAFETY: `Atomic` matches `atomic_t` in size and alignment (asserted + // above) and `word` is valid for atomic writes. + unsafe { sep_diag_set_trusted_atomic(word.as_ptr().cast(), state, status) }; +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +pub(crate) fn clear_trusted_refusal_for_test(word: &Atomic) { + kernel::static_assert!(size_of::>() == size_of::()); + kernel::static_assert!(align_of::>() == align_of::()); + // SAFETY: `Atomic` matches `atomic_t` in size and alignment (asserted + // above) and `word` is valid for atomic read-modify-write. + unsafe { sep_diag_clear_trusted_refusal_atomic(word.as_ptr().cast()) }; } /// 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 806d9aff65218..b073720d9abd6 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -1039,13 +1039,38 @@ void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, atomic_set(&sep_diag.matching, matching); } +void sep_diag_set_trusted_atomic(atomic_t *word, int state, int status) +{ + atomic_set(word, (state & 0xff) | ((u8)status << 8)); +} + /* * The latest answer wins: a success after a refusal (or the reverse) is what * the next seal or unseal can expect. */ void sep_diag_set_trusted(int state, int status) { - atomic_set(&sep_diag.trusted, (state & 0xff) | ((u8)status << 8)); + sep_diag_set_trusted_atomic(&sep_diag.trusted, state, status); +} + +/* + * A validated identity unlock (for example through /dev/sep-key) clears any + * stale refusal so a loader re-run probes again, while leaving "ready" tied + * to a working trusted-key unseal. + */ +void sep_diag_clear_trusted_refusal_atomic(atomic_t *word) +{ + int old = atomic_read(word); + + while ((old & 0xff) == SEP_DIAG_TRUSTED_REFUSED) { + if (atomic_try_cmpxchg(word, &old, SEP_DIAG_TRUSTED_UNKNOWN)) + break; + } +} + +void sep_diag_clear_trusted_refusal(void) +{ + sep_diag_clear_trusted_refusal_atomic(&sep_diag.trusted); } /* With matching as the refusal leaves it. */ diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index b38d4eecc4f7e..3e9f4f8534c46 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -13,6 +13,22 @@ use kernel::sync::atomic::Relaxed; pub(crate) const REFKEY_ENVELOPE_VERSION: u32 = 2; +/// Validates a `DEVICE_STATE_TRANSITION` response body and clears any stale +/// refusal via `clear_refusal` so a subsequent loader run probes again. `Ready` +/// stays tied to a successful trusted-key unseal. +fn record_identity_unlock_with(body: &[u8], clear_refusal: impl FnOnce()) -> bool { + if body.len() == 20 && body[..4] == [0; 4] { + clear_refusal(); + true + } else { + false + } +} + +fn record_identity_unlock(body: &[u8]) -> bool { + record_identity_unlock_with(body, crate::diag::clear_trusted_refusal) +} + impl SepData { /// Keep only decoded bytes across switch-root, never an open initrd file. fn with_identity_keybag( @@ -110,7 +126,7 @@ impl SepData { let Some(body) = self.sks_report_response(c"DEVICE_STATE_TRANSITION", &out) else { return false; }; - body.len() == 20 && body[..4] == [0; 4] + record_identity_unlock(body) } fn sks_create_refkey( @@ -810,3 +826,49 @@ impl SepData { } } } + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[::kernel::macros::kunit_tests(apple_sep_refkey_trusted)] +mod tests { + use super::*; + use kernel::sync::atomic::Atomic; + + #[test] + fn validated_unlock_clears_refusal_without_setting_ready() { + let state = Atomic::new(0i32); + crate::diag::set_trusted_for_test(&state, crate::diag::Trusted::Refused(-8)); + assert_eq!(state.load(Relaxed) & 0xff, 2); + assert_eq!((state.load(Relaxed) >> 8) as i8, -8); + + assert!(!record_identity_unlock_with(&[0; 19], || { + crate::diag::clear_trusted_refusal_for_test(&state) + })); + assert_eq!(state.load(Relaxed) & 0xff, 2); + assert_eq!((state.load(Relaxed) >> 8) as i8, -8); + + let mut bad_status = [0u8; 20]; + bad_status[0] = 1; + assert!(!record_identity_unlock_with(&bad_status, || { + crate::diag::clear_trusted_refusal_for_test(&state) + })); + assert_eq!(state.load(Relaxed) & 0xff, 2); + + assert!(record_identity_unlock_with(&[0; 20], || { + crate::diag::clear_trusted_refusal_for_test(&state) + })); + assert_eq!(state.load(Relaxed), 0); + + crate::diag::set_trusted_for_test(&state, crate::diag::Trusted::Ready); + assert_eq!(state.load(Relaxed), 1); + } + + #[test] + fn validated_unlock_preserves_ready() { + let state = Atomic::new(0i32); + crate::diag::set_trusted_for_test(&state, crate::diag::Trusted::Ready); + assert!(record_identity_unlock_with(&[0; 20], || { + crate::diag::clear_trusted_refusal_for_test(&state) + })); + assert_eq!(state.load(Relaxed), 1); + } +} diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index d58aa37b2a2ee..9a3df1a9debdb 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -247,6 +247,9 @@ void sep_diag_set_xart_guard(unsigned int level, bool list_loaded, int matching); void sep_diag_xart_guard_refused(int matching); void sep_diag_set_trusted(int state, int status); +void sep_diag_set_trusted_atomic(atomic_t *word, int state, int status); +void sep_diag_clear_trusted_refusal(void); +void sep_diag_clear_trusted_refusal_atomic(atomic_t *word); void sep_diag_bringup_ended(void); void sep_diag_set_endpoint(u8 id, u32 name); void sep_diag_set_os_identity(int source); diff --git a/tools/aurora-sep/tests/test_trusted_refused.py b/tools/aurora-sep/tests/test_trusted_refused.py index 6d476e56bd14b..c614a0738c875 100644 --- a/tools/aurora-sep/tests/test_trusted_refused.py +++ b/tools/aurora-sep/tests/test_trusted_refused.py @@ -42,7 +42,11 @@ def test_states_and_signed_status(self): state = re.search(r'static struct \{.*?\} sep_diag;', text, re.S).group(0) defines = '\n'.join(re.findall(r'^#define SEP_DIAG_(?:TRUSTED_\w+|MAX_EP)\s+\S+$', HEADER.read_text() + text, re.M)) - body = function(text, 'trusted_show') + function(text, 'sep_diag_set_trusted') + body = (function(text, 'trusted_show') + + function(text, 'sep_diag_set_trusted_atomic') + + function(text, 'sep_diag_set_trusted') + + function(text, 'sep_diag_clear_trusted_refusal_atomic') + + function(text, 'sep_diag_clear_trusted_refusal')) prefix = '''#include #include #include @@ -58,6 +62,11 @@ def test_states_and_signed_status(self): struct device_attribute { int unused; }; #define atomic_read(p) (*(p)) #define atomic_set(p, v) (*(p) = (v)) +static inline bool atomic_try_cmpxchg(atomic_t *p, int *old, int val) { + if (*p == *old) { *p = val; return true; } + *old = *p; + return false; +} static int sysfs_emit(char *out, const char *fmt, ...) __attribute__((format(printf, 2, 3))); static int sysfs_emit(char *out, const char *fmt, ...) { va_list args; va_start(args, fmt); int n = vsnprintf(out, 4096, fmt, args); va_end(args); return n; @@ -66,10 +75,14 @@ def test_states_and_signed_status(self): main = '''int main(void) { char out[4096]; trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_clear_trusted_refusal(); trusted_show(NULL, NULL, out); fputs(out, stdout); sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, -8); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_clear_trusted_refusal(); trusted_show(NULL, NULL, out); fputs(out, stdout); sep_diag_set_trusted(SEP_DIAG_TRUSTED_READY, 0); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_clear_trusted_refusal(); trusted_show(NULL, NULL, out); fputs(out, stdout); sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, -128); trusted_show(NULL, NULL, out); fputs(out, stdout); sep_diag_set_trusted(SEP_DIAG_TRUSTED_REFUSED, 127); trusted_show(NULL, NULL, out); fputs(out, stdout); + sep_diag_clear_trusted_refusal(); trusted_show(NULL, NULL, out); fputs(out, stdout); return 0; } ''' @@ -79,7 +92,10 @@ def test_states_and_signed_status(self): subprocess.run([compiler, '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', str(source), '-o', str(program)], check=True) lines = subprocess.check_output([str(program)], text=True).splitlines() - self.assertEqual(lines, ['unknown', 'refused -8', 'ready', 'refused -128', 'refused 127']) + self.assertEqual(lines, [ + 'unknown', 'unknown', 'refused -8', 'unknown', + 'ready', 'ready', 'refused -128', 'refused 127', 'unknown', + ]) # keyctl as the loader uses it. A refused seal writes what the driver would @@ -94,6 +110,9 @@ def test_states_and_signed_status(self): exit 1 fi if [ -n "${FAKE_WORK:-}" ]; then + if [ "${3:-}" = "aurora-sep-load-check" ] && [ -d "$DIAG" ] && [ -n "${FAKE_TRUSTED:-}" ]; then + printf 'ready\n' >"$DIAG/trusted" + fi echo 1234 exit 0 fi @@ -141,51 +160,69 @@ def run_loader(self, trusted=None, guard='0', refuse=True, work=False, timeout=' PATH=str(bin_dir) + os.pathsep + os.environ['PATH']) env.pop('FAKE_REFUSE', None) env.pop('FAKE_WORK', None) + if trusted is not None: + env['FAKE_TRUSTED'] = '1' if refuse: env['FAKE_REFUSE'] = '1' - if trusted is not None: - env['FAKE_TRUSTED'] = '1' if work: env['FAKE_WORK'] = '1' began = time.monotonic() done = subprocess.run(['sh', str(script)], env=env, capture_output=True, text=True, timeout=30) seals = len(calls.read_text().splitlines()) if calls.exists() else 0 - return done, seals, time.monotonic() - began + after_trusted = (diag / 'trusted').read_text().strip() if (diag / 'trusted').exists() else None + return done, seals, time.monotonic() - began, after_trusted def test_first_refusal_stops_the_probe(self): - done, seals, took = self.run_loader(trusted='unknown') + done, seals, took, after = self.run_loader(trusted='unknown') self.assertEqual(done.returncode, 1, done.stderr) self.assertEqual(seals, 1) self.assertLess(took, 10) self.assertIn('diag/trusted: refused -8', done.stderr) + self.assertEqual(after, 'refused -8') def test_rerun_sends_no_seal(self): - done, seals, _ = self.run_loader(trusted='refused -8') + done, seals, _, after = self.run_loader(trusted='refused -8') self.assertEqual(done.returncode, 1, done.stderr) self.assertEqual(seals, 0) self.assertIn('diag/trusted: refused -8', done.stderr) + self.assertEqual(after, 'refused -8') def test_guard_refusal_is_named_first(self): for trusted in ('unknown', 'refused -8'): with self.subTest(trusted=trusted): - done, seals, _ = self.run_loader(trusted=trusted, guard='1') + done, seals, _, _ = self.run_loader(trusted=trusted, guard='1') self.assertEqual(done.returncode, 1, done.stderr) self.assertLessEqual(seals, 1) self.assertIn('xART guard refused', done.stderr) self.assertNotIn('diag/trusted', done.stderr) def test_without_the_attribute_the_deadline_still_applies(self): - done, seals, _ = self.run_loader(trusted=None, timeout='1') + done, seals, _, _ = self.run_loader(trusted=None, timeout='1') self.assertEqual(done.returncode, 1, done.stderr) self.assertGreater(seals, 1) self.assertIn('within 1 s', done.stderr) def test_ready_kernel_still_verifies(self): - done, seals, _ = self.run_loader(trusted='ready', refuse=False, work=True) + done, seals, _, after = self.run_loader(trusted='ready', refuse=False, work=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(seals, 2) + self.assertIn('trusted keys work', done.stderr) + self.assertEqual(after, 'ready') + + def test_cleared_refusal_lets_rerun_probe_and_reach_ready(self): + done, seals, _, after = self.run_loader(trusted='unknown', refuse=False, work=True) self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual(seals, 2) self.assertIn('trusted keys work', done.stderr) + self.assertEqual(after, 'ready') + + def test_cleared_refusal_re_refuses_if_unlock_fails_again(self): + done, seals, _, after = self.run_loader(trusted='unknown', refuse=True, work=False) + self.assertEqual(done.returncode, 1, done.stderr) + self.assertEqual(seals, 1) + self.assertIn('diag/trusted: refused -8', done.stderr) + self.assertEqual(after, 'refused -8') if __name__ == '__main__': From 2cdd990f389eb8993215c4c78e7977676cef87fc Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 18:35:56 -0500 Subject: [PATCH 4/4] tools/aurora-sep: define atomic_t in stub linux/types.h tools/aurora-sep/tests/test_diag_sensor.py compiles diag_shim.c and its test harnesses against minimal stub kernel headers. In the kernel, defines atomic_t, whereas the test's stub headers placed the typedef in . Because drivers/soc/apple/shim.h includes and declares sep_diag_*_atomic(atomic_t *, ...), harnesses that include "shim.h" without failed to compile with "unknown type name 'atomic_t'". Move `typedef struct { int counter; } atomic_t;` from the stub linux/atomic.h into the stub linux/types.h so "shim.h" compiles standalone against the stubs, matching the kernel headers while leaving all driver and loader files unchanged. Signed-off-by: Erik Bourget --- tools/aurora-sep/tests/test_diag_sensor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/aurora-sep/tests/test_diag_sensor.py b/tools/aurora-sep/tests/test_diag_sensor.py index 86b564752c0d8..25fc78cee8b3b 100644 --- a/tools/aurora-sep/tests/test_diag_sensor.py +++ b/tools/aurora-sep/tests/test_diag_sensor.py @@ -34,13 +34,13 @@ typedef unsigned short umode_t; typedef uint64_t __u64; typedef uint32_t __u32; typedef uint16_t __u16; typedef uint8_t __u8; typedef int64_t __s64; typedef int32_t __s32; +typedef struct { int counter; } atomic_t; #define __user #define READ_ONCE(x) __atomic_load_n(&(x), __ATOMIC_RELAXED) #define WRITE_ONCE(x, v) __atomic_store_n(&(x), (v), __ATOMIC_RELAXED) ''', 'linux/atomic.h': r''' #include -typedef struct { int counter; } atomic_t; #define atomic_read(v) __atomic_load_n(&(v)->counter, __ATOMIC_SEQ_CST) #define atomic_set(v, i) __atomic_store_n(&(v)->counter, (i), __ATOMIC_SEQ_CST) static inline int atomic_cmpxchg(atomic_t *v, int old, int new_)