Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/sep-source.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
86 changes: 74 additions & 12 deletions drivers/soc/apple/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand All @@ -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<T>(mut self, result: Result<T>) -> Result<T> {
self.dispose()?;
result
}
}

impl<D: ContextDelete + ?Sized> Drop for OwnedContext<'_, D> {
fn drop(&mut self) {
self.owner.delete_context(&self.handle);
crate::image::wipe(&mut self.handle);
let _ = self.dispose();
}
}

Expand Down Expand Up @@ -1645,6 +1661,9 @@ impl SepData {
errno_of(&job.result)
);
ended?;
if self.key_context_failed.load(Relaxed) {
return Err(EIO);
}
Ok(job)
}

Expand Down Expand Up @@ -2097,7 +2116,7 @@ impl SepData {
digest: &[u8; DIGEST_LEN],
sealed: &[u8],
pw: &[u8],
) -> Result<KVec<u8>> {
) -> Result<crate::Secret> {
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.
Expand All @@ -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",
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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(())
}
}

Expand Down Expand Up @@ -2553,6 +2576,45 @@ mod one_op_tests {
assert_eq!(d.deleted.get(), 1);
}

struct RefusingDeleter(Cell<u32>);

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<bool>);

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() {
Expand Down
2 changes: 1 addition & 1 deletion drivers/soc/apple/sbio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
23 changes: 17 additions & 6 deletions drivers/soc/apple/sep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,8 @@ struct SepData {
key_touch_active: Atomic<bool>,
/// `SEP_KEY_CANCEL`: ends the touch-gated operation that is waiting.
key_touch_cancel: Atomic<bool>,
/// An unconfirmed credential disposal disables private key operations.
key_context_failed: Atomic<bool>,
// The enclave status of the last /dev/sep-key signature (self-test).
last_key_status: Atomic<u32>,

Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)
}
}
}

Expand Down
46 changes: 46 additions & 0 deletions tools/aurora-sep/tests/test_key_context_cleanup.py
Original file line number Diff line number Diff line change
@@ -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<T> = std::result::Result<T, i32>;
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()