From 7723f3d652306b5ba39c1c5b4330cb42a0c5436d Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Wed, 11 Nov 2026 08:31:17 -0600 Subject: [PATCH] soc: apple: sep: fail key operations when credential disposal fails A password-authorized sign or unseal creates an unlock evaluation in the enclave and deletes it afterwards. The deletion's answer was ignored, so a result could be returned while the credential context it was authorized by might still be live. Confirm the deletion before a result leaves the driver, and discard the result if it fails. An unconfirmed deletion latches key operations off until the driver restarts (a reboot or a module reload), so nothing later runs against a context that may still hold the credential; capability queries and cancellation stay available meanwhile. The KUnit cases and the host test run the production guard for success, early exits and a failed deletion, checking that the result is destroyed and that deletion is attempted exactly once. Assisted-by: LLM [Claude Code, claude-opus-5-5] Signed-off-by: Cameron Cooper --- .github/workflows/sep-source.yml | 1 + drivers/soc/apple/key.rs | 86 ++++++++++++++++--- drivers/soc/apple/sbio.rs | 2 +- drivers/soc/apple/sep.rs | 23 +++-- .../tests/test_key_context_cleanup.py | 46 ++++++++++ 5 files changed, 139 insertions(+), 19 deletions(-) create mode 100644 tools/aurora-sep/tests/test_key_context_cleanup.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 342886382a065..5c1c99444b301 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -71,6 +71,7 @@ jobs: python3 -m unittest tools/aurora-sep/tests/test_owner_preparation.py -v python3 -m unittest tools/aurora-sep/tests/test_policy_window.py -v python3 -m unittest tools/aurora-sep/tests/test_log_ratelimit.py -v + python3 -m unittest tools/aurora-sep/tests/test_key_context_cleanup.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_packaging.py -v rust-build: diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index 9a3047d0d1157..d227fd887f538 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -957,12 +957,12 @@ impl KeyGrant { /// Deletes an enclave credential context. pub(crate) trait ContextDelete { - fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]); + fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()>; } impl ContextDelete for SepData { - fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) { - self.close_unlock_evaluation(handle); + fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { + self.delete_unlock_evaluation(handle) } } @@ -972,22 +972,38 @@ impl ContextDelete for SepData { pub(crate) struct OwnedContext<'a, D: ContextDelete + ?Sized> { owner: &'a D, handle: [u8; crate::scrd::SCRD_ACM_HANDLE_LEN], + disposed: bool, } impl<'a, D: ContextDelete + ?Sized> OwnedContext<'a, D> { pub(crate) fn new(owner: &'a D, handle: [u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Self { - OwnedContext { owner, handle } + OwnedContext { owner, handle, disposed: false } } pub(crate) fn handle(&self) -> &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN] { &self.handle } + + fn dispose(&mut self) -> Result<()> { + if self.disposed { + return Ok(()); + } + self.disposed = true; + let result = self.owner.delete_context(&self.handle); + crate::image::wipe(&mut self.handle); + result + } + + /// Dispose before publishing the result. Failure drops any owned output. + pub(crate) fn finish(mut self, result: Result) -> Result { + self.dispose()?; + result + } } impl Drop for OwnedContext<'_, D> { fn drop(&mut self) { - self.owner.delete_context(&self.handle); - crate::image::wipe(&mut self.handle); + let _ = self.dispose(); } } @@ -1645,6 +1661,9 @@ impl SepData { errno_of(&job.result) ); ended?; + if self.key_context_failed.load(Relaxed) { + return Err(EIO); + } Ok(job) } @@ -2097,7 +2116,7 @@ impl SepData { digest: &[u8; DIGEST_LEN], sealed: &[u8], pw: &[u8], - ) -> Result> { + ) -> Result { let bag = bag_user(uid)?; // Not under `catacomb_writer`: a touch wait holds it for up to a // minute, and this path needs no capture. @@ -2107,9 +2126,9 @@ impl SepData { dev_info_refusal!(self.dev, "sep-key: uid {}'s password refused by the enclave (status {})\n", uid, verify); Err(EACCES) } else { - self.key_op_in(Some(uid), op, blob, digest, sealed, Some(ctx.handle())) + self.key_op_in(Some(uid), op, blob, digest, sealed, Some(ctx.handle())).map(crate::Secret) }; - drop(ctx); + let r = ctx.finish(r); dev_dbg!( self.dev, "sep-key: password-gated {:?} under uid {}'s bag: {}\n", @@ -2245,6 +2264,9 @@ impl SepData { if self.shutting_down.load(Relaxed) { return Err(ENODEV); } + if cmd != IOC_INFO && cmd != IOC_CANCEL && self.key_context_failed.load(Relaxed) { + return Err(EIO); + } let user = UserPtr::from_addr(arg); match read_request(cmd, arg)? { KeyRequest::Info => write_user(user, &info_for(self.profile.key_store == crate::profile::KeyStore::Variant5)), @@ -2348,7 +2370,7 @@ impl SepData { require_admin_or(uid)?; let pw = check_password(&req.password)?; let digest = req.sign.digest; - crate::Secret(self.key_op_with_password(uid, h.blob, TouchOp::Sign, &digest, &[], pw)?) + self.key_op_with_password(uid, h.blob, TouchOp::Sign, &digest, &[], pw)? }; put_signature(&sig, &mut req.sign)?; // `req` wipes the password when it drops. @@ -2360,7 +2382,7 @@ impl SepData { let uid = check_password_handle(&h)?; require_admin_or(uid)?; let pw = check_password(&req.password)?; - crate::Secret(self.key_op_with_password(uid, h.blob, TouchOp::Unseal, &[0; DIGEST_LEN], sealed, pw)?) + self.key_op_with_password(uid, h.blob, TouchOp::Unseal, &[0; DIGEST_LEN], sealed, pw)? }; put_secret(&secret, &mut req.seal)?; // `secret` and `req` wipe the plaintext and password when they drop. @@ -2510,9 +2532,10 @@ mod one_op_tests { } impl ContextDelete for Deleter { - fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) { + fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { self.deleted.set(self.deleted.get() + 1); self.last.set(*handle); + Ok(()) } } @@ -2553,6 +2576,45 @@ mod one_op_tests { assert_eq!(d.deleted.get(), 1); } + struct RefusingDeleter(Cell); + + impl ContextDelete for RefusingDeleter { + fn delete_context(&self, _handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { + self.0.set(self.0.get() + 1); + Err(EIO) + } + } + + struct PendingOutput<'a>(&'a Cell); + + impl Drop for PendingOutput<'_> { + fn drop(&mut self) { + self.0.set(true); + } + } + + #[test] + fn cleanup_failure_discards_success_without_retrying_disposal() { + let d = RefusingDeleter(Cell::new(0)); + let discarded = Cell::new(false); + let ctx = OwnedContext::new(&d, [0x51; crate::scrd::SCRD_ACM_HANDLE_LEN]); + let result = ctx.finish(Ok(PendingOutput(&discarded))); + assert!(matches!(result, Err(e) if e == EIO)); + assert!(discarded.get()); + assert_eq!(d.0.get(), 1); + } + + #[test] + fn confirmed_disposal_preserves_the_operation_result() { + let d = deleter(); + let ctx = OwnedContext::new(&d, [0x52; crate::scrd::SCRD_ACM_HANDLE_LEN]); + assert_eq!(ctx.finish(Ok(37)), Ok(37)); + assert_eq!(d.deleted.get(), 1); + let ctx = OwnedContext::new(&d, [0x53; crate::scrd::SCRD_ACM_HANDLE_LEN]); + assert_eq!(ctx.finish::<()>(Err(ECANCELED)), Err(ECANCELED)); + assert_eq!(d.deleted.get(), 2); + } + // Production kernels do not build the reuse measurements. #[test] fn reuse_measurements_are_research_only() { diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 0c3b733941936..e353c938bc8a5 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -2871,7 +2871,7 @@ impl SepData { Some(context) => drop(context), None => self.close_unlock_evaluation(&evaluation), } - if key_mode && matched { + if key_mode && matched && !self.key_context_failed.load(Relaxed) { self.key_touch_after_close(&evaluation); } } diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 02fcc78b25564..fa350096908c6 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -880,6 +880,8 @@ struct SepData { key_touch_active: Atomic, /// `SEP_KEY_CANCEL`: ends the touch-gated operation that is waiting. key_touch_cancel: Atomic, + /// An unconfirmed credential disposal disables private key operations. + key_context_failed: Atomic, // The enclave status of the last /dev/sep-key signature (self-test). last_key_status: Atomic, @@ -1268,6 +1270,7 @@ impl SepData { key_touch <- new_mutex!(None), key_touch_active: Atomic::new(false), key_touch_cancel: Atomic::new(false), + key_context_failed: Atomic::new(false), last_key_status: Atomic::new(0), bio_lockout: Atomic::new(false), bio_after_boot: Atomic::new(false), @@ -2771,13 +2774,21 @@ impl SepData { } pub(crate) fn close_unlock_evaluation(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) { + let _ = self.delete_unlock_evaluation(handle); + } + + pub(crate) fn delete_unlock_evaluation(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { match self.scrd_command(&crate::scrd::scrd_context_delete(handle)) { - Some((0, _)) => {} - other => dev_warn_ratelimited!( - self.dev, - "scrd: deleting the unlock evaluation answered {:?}\n", - other.map(|(status, _)| status) - ), + Some((0, _)) => Ok(()), + other => { + self.key_context_failed.store(true, Relaxed); + dev_warn_ratelimited!( + self.dev, + "scrd: deleting the unlock evaluation answered {:?}; private key operations disabled until reboot\n", + other.map(|(status, _)| status) + ); + Err(EIO) + } } } diff --git a/tools/aurora-sep/tests/test_key_context_cleanup.py b/tools/aurora-sep/tests/test_key_context_cleanup.py new file mode 100644 index 0000000000000..a127590b89ab0 --- /dev/null +++ b/tools/aurora-sep/tests/test_key_context_cleanup.py @@ -0,0 +1,46 @@ +"""Run the production credential guard and its focused cleanup tests on the host.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[3] + + +@unittest.skipUnless(shutil.which("rustc"), "rustc required") +class ContextCleanupTests(unittest.TestCase): + def test_production_context_disposal(self): + source = (ROOT / "drivers/soc/apple/key.rs").read_text() + trait = source[source.index("pub(crate) trait ContextDelete"): + source.index("impl ContextDelete for SepData")] + guard = source[source.index("/// A credential context"): + source.index("/// Self-test copies")] + tests = source[source.index(" struct Deleter {"): + source.index(" // Production kernels do not build")] + harness = r''' +use std::cell::Cell; +type Result = std::result::Result; +const EIO: i32 = -5; +const EINTR: i32 = -4; +const ECANCELED: i32 = -125; +const ETIMEDOUT: i32 = -110; +const ENODEV: i32 = -19; +mod scrd { pub const SCRD_ACM_HANDLE_LEN: usize = 16; } +mod image { pub fn wipe(bytes: &mut [u8]) { bytes.fill(0); } } +TRAIT +GUARD +TESTS +''' + harness = harness.replace("TRAIT", trait).replace("GUARD", guard).replace("TESTS", tests) + with tempfile.TemporaryDirectory() as directory: + source_path = Path(directory) / "context_cleanup.rs" + binary_path = Path(directory) / "context_cleanup" + source_path.write_text(harness) + subprocess.run(["rustc", "--edition=2021", "--test", str(source_path), + "-o", str(binary_path)], check=True, capture_output=True, text=True) + subprocess.run([str(binary_path)], check=True, capture_output=True, text=True) + + +if __name__ == "__main__": + unittest.main()