diff --git a/Documentation/ABI/testing/sysfs-driver-apple-sep b/Documentation/ABI/testing/sysfs-driver-apple-sep index b2d673ca52ef1..d575f242da296 100644 --- a/Documentation/ABI/testing/sysfs-driver-apple-sep +++ b/Documentation/ABI/testing/sysfs-driver-apple-sep @@ -594,3 +594,32 @@ 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 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 9260cc09151c2..079ffba1a9b8c 100644 --- a/drivers/soc/apple/diag.rs +++ b/drivers/soc/apple/diag.rs @@ -52,6 +52,16 @@ 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); + #[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); @@ -287,6 +297,59 @@ 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), +} + +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) = state.raw(); + // SAFETY: no preconditions; stores one word. + 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. 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..b073720d9abd6 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,40 @@ 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) +{ + 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. */ void sep_diag_xart_guard_refused(int matching) { diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index f0fde4827754a..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( @@ -102,12 +118,15 @@ 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 { return false; }; - body.len() == 20 && body[..4] == [0; 4] + record_identity_unlock(body) } fn sks_create_refkey( @@ -342,6 +361,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) } @@ -805,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 456492d6e8afe..9a3df1a9debdb 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,10 @@ 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_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/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_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_) 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, 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..c614a0738c875 --- /dev/null +++ b/tools/aurora-sep/tests/test_trusted_refused.py @@ -0,0 +1,229 @@ +#!/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_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 +#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 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; +} +''' + 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; +} +''' + 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', '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 +# 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 + if [ "${3:-}" = "aurora-sep-load-check" ] && [ -d "$DIAG" ] && [ -n "${FAKE_TRUSTED:-}" ]; then + printf 'ready\n' >"$DIAG/trusted" + fi + 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 trusted is not None: + env['FAKE_TRUSTED'] = '1' + if refuse: + env['FAKE_REFUSE'] = '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 + 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, 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, _, 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') + 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, _, 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__': + unittest.main()