diff --git a/drivers/soc/apple/bio.rs b/drivers/soc/apple/bio.rs index ea45ee49d1510..19d904d886dea 100644 --- a/drivers/soc/apple/bio.rs +++ b/drivers/soc/apple/bio.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT // Copyright 2026 Dj +pub(crate) mod key; +pub(crate) use key::worker_done; + use crate::store::{Key, Store}; use kernel::ioctl::{_IO, _IOR, _IOW, _IOWR}; use kernel::prelude::*; @@ -383,6 +386,7 @@ impl IdentityIndex { enum Op { Idle, + Key(key::Operation), Enrol { label: [u8; LABEL_LEN], stage: u32, @@ -406,6 +410,7 @@ impl Op { fn is_terminal(&self) -> bool { match self { Op::Idle => false, + Op::Key(operation) => operation.is_terminal(), Op::Enrol { terminal, .. } => terminal.is_some(), Op::Verify { terminal, .. } => terminal.is_some(), } @@ -418,6 +423,7 @@ impl Op { pub(crate) struct Session { open: bool, + worker_active: bool, op: Op, unseen: bool, enrol_stage_unseen: bool, @@ -428,6 +434,7 @@ impl Session { pub(crate) fn new() -> Session { Session { open: false, + worker_active: false, op: Op::Idle, unseen: false, enrol_stage_unseen: false, @@ -443,6 +450,10 @@ impl Session { self.token = None; } + pub(crate) fn available(&self) -> bool { + !self.worker_active && self.op.may_start() + } + pub(crate) fn ready(&self) -> bool { self.unseen } @@ -453,6 +464,7 @@ pub(crate) struct Context<'a> { pub(crate) index: &'a IdentityIndex, pub(crate) sensor_present: bool, pub(crate) live_identity_count: Option, + pub(crate) biometric_keys_supported: bool, } pub(crate) struct Handled { @@ -519,7 +531,7 @@ fn get_info(ctx: &mut Context<'_>, user: UserPtr) -> Result { // when SEP itself successfully answered LIST_IDENTITIES; older // kernels and unavailable SEP contexts leave this flag clear. reserved: [ - u32::from(ctx.live_identity_count.is_some()), + u32::from(ctx.live_identity_count.is_some()) | key::capabilities(ctx.biometric_keys_supported), ctx.live_identity_count.unwrap_or(0) as u32, 0, ], @@ -560,7 +572,7 @@ fn enrol_start(ctx: &mut Context<'_>, user: UserPtr) -> Result { } require_sensor(ctx.sensor_present)?; - if !ctx.session.op.may_start() { + if !ctx.session.available() { return Err(EBUSY); } if matches!(ctx.live_identity_count, Some(count) if count >= SEP_USER_CAPACITY) @@ -569,6 +581,7 @@ fn enrol_start(ctx: &mut Context<'_>, user: UserPtr) -> Result { return Err(ENOSPC); } + ctx.session.worker_active = true; ctx.session.op = Op::Enrol { label: request.label, stage: 0, @@ -632,6 +645,7 @@ pub(crate) fn capture_guide(session: &mut Session, guide: Guidance) -> bool { false } } + Op::Key(operation) => operation.capture_guide(guide), Op::Idle => false, }; if changed { @@ -682,7 +696,7 @@ fn enrol_poll(ctx: &mut Context<'_>, user: UserPtr) -> Result { match &ctx.session.op { Op::Idle => out.state = State::Idle, - Op::Verify { .. } => return Err(EBUSY), + Op::Verify { .. } | Op::Key(_) => return Err(EBUSY), Op::Enrol { stage, terminal, @@ -732,7 +746,7 @@ fn verify_start(ctx: &mut Context<'_>, user: UserPtr) -> Result { } require_sensor(ctx.sensor_present)?; - if !ctx.session.op.may_start() { + if !ctx.session.available() { return Err(EBUSY); } @@ -755,6 +769,7 @@ fn verify_start(ctx: &mut Context<'_>, user: UserPtr) -> Result { } ctx.session.token = None; + ctx.session.worker_active = true; ctx.session.op = Op::Verify { nonce: request.nonce, terminal: None, @@ -798,7 +813,7 @@ pub(crate) fn verify_is_live(session: &Session) -> bool { } pub(crate) fn capture_is_live(session: &Session) -> bool { - enrol_is_live(session) || verify_is_live(session) + enrol_is_live(session) || verify_is_live(session) || key::key_is_live(session) } fn verify_poll(ctx: &mut Context<'_>, user: UserPtr) -> Result { @@ -808,7 +823,7 @@ fn verify_poll(ctx: &mut Context<'_>, user: UserPtr) -> Result { match &ctx.session.op { Op::Idle => out.state = State::Idle, - Op::Enrol { .. } => return Err(EBUSY), + Op::Enrol { .. } | Op::Key(_) => return Err(EBUSY), Op::Verify { nonce, terminal, guidance } => { out.guidance = *guidance; match terminal { @@ -858,7 +873,10 @@ fn verify_poll(ctx: &mut Context<'_>, user: UserPtr) -> Result { } fn cancel(ctx: &mut Context<'_>) -> Result { - if ctx.session.op.is_terminal() { + if ctx.session.op.is_terminal() + && !matches!(&ctx.session.op, Op::Key(operation) + if operation.can_cancel()) + { return Err(ENOENT); } @@ -866,6 +884,7 @@ fn cancel(ctx: &mut Context<'_>) -> Result { Op::Idle => return Err(ENOENT), Op::Enrol { terminal, .. } => *terminal = Some(EnrolOutcome::Failed(STATUS_LOCAL)), Op::Verify { terminal, .. } => *terminal = Some(VerifyOutcome::Failed(STATUS_LOCAL)), + Op::Key(operation) => operation.cancel(), } ctx.session.token = None; @@ -892,6 +911,7 @@ pub(crate) fn abort_capture(session: &mut Session) -> bool { Op::Verify { terminal, .. } if terminal.is_none() => { *terminal = Some(VerifyOutcome::Failed(STATUS_LOCAL)) } + Op::Key(operation) if operation.can_cancel() => operation.cancel(), _ => return false, } session.token = None; @@ -906,6 +926,7 @@ pub(crate) fn starts_capture(cmd: u32) -> bool { fn delete(ctx: &mut Context<'_>, user: UserPtr) -> Result { require_admin()?; + if !ctx.session.available() { return Err(EBUSY); } let request: Delete = UserSlice::new(user, core::mem::size_of::()) .reader() .read()?; @@ -935,6 +956,7 @@ fn delete(ctx: &mut Context<'_>, user: UserPtr) -> Result { fn delete_all(ctx: &mut Context<'_>) -> Result { require_admin()?; + if !ctx.session.available() { return Err(EBUSY); } if ctx.index.total() == 0 { pr_info!("sep_bio: DELETE_ALL on empty index; reporting success (nothing to delete)\n"); @@ -963,7 +985,7 @@ fn delete_all(ctx: &mut Context<'_>) -> Result { } pub(crate) fn open(session: &mut Session) -> Result<()> { - if session.open { + if session.open || session.worker_active { return Err(EBUSY); } session.reset(); diff --git a/drivers/soc/apple/bio/key.rs b/drivers/soc/apple/bio/key.rs new file mode 100644 index 0000000000000..89850dfabfd0b --- /dev/null +++ b/drivers/soc/apple/bio/key.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Key-operation state, result delivery and expiry for the biometric session. + +use super::*; +use crate::keys::{KeyRequest, Output}; + +const KEY_PLAINTEXT_LIFETIME_NS: u64 = 5 * 1_000_000_000; + +const INFO_BIOMETRIC_KEYS: u32 = 1 << 1; +const INFO_BIOMETRIC_DECRYPT: u32 = 1 << 2; + +pub(super) fn capabilities(supported: bool) -> u32 { + if supported { INFO_BIOMETRIC_KEYS | INFO_BIOMETRIC_DECRYPT } else { 0 } +} + +pub(super) struct Operation { + request: Option, + deadline_ns: u64, + terminal: Option>, + decrypt: bool, + guidance: Guidance, +} + +impl Operation { + pub(super) fn is_terminal(&self) -> bool { + self.terminal.is_some() + } + + pub(super) fn can_cancel(&self) -> bool { + self.terminal.is_none() + || matches!(&self.terminal, Some(Ok(crate::keys::Output::Plaintext(_)))) + } + + pub(super) fn cancel(&mut self) { + self.terminal = Some(Err(ECANCELED)); + } + + pub(super) fn capture_guide(&mut self, guide: Guidance) -> bool { + if self.terminal.is_none() && self.guidance != guide { + self.guidance = guide; + true + } else { + false + } + } +} + +pub(crate) fn worker_done(session: &mut Session) { + session.worker_active = false; +} + +pub(crate) fn start_key(session: &mut Session, request: crate::keys::KeyRequest) -> Result { + if !session.available() { + return Err(EBUSY); + } + session.op = Op::Key(Operation { + deadline_ns: request.deadline_ns, + decrypt: matches!(&request.input, crate::keys::Input::Decrypt(_)), + request: Some(request), + terminal: None, + guidance: Guidance::Place, + }); + session.token = None; + session.worker_active = true; + session.unseen = false; + Ok(Handled { start_verify: true, ..ok()? }) +} + +pub(crate) fn is_key_operation(session: &Session) -> bool { + matches!(session.op, Op::Key(_)) +} + +pub(crate) fn take_key_request(session: &mut Session) -> Option { + let Op::Key(signing) = &mut session.op else { return None; }; + if signing.terminal.is_some() || !session.open { return None; } + signing.request.take() +} + +pub(crate) fn key_is_live(session: &Session) -> bool { + let Op::Key(signing) = &session.op else { return false; }; + session.open && signing.terminal.is_none() && crate::shim::monotonic_ns() < signing.deadline_ns +} + +pub(crate) fn finish_key(session: &mut Session, result: Result) -> bool { + let Op::Key(signing) = &mut session.op else { return false; }; + if !session.open || signing.terminal.is_some() { return false; } + let now = crate::shim::monotonic_ns(); + if matches!(&result, Ok(crate::keys::Output::Plaintext(_))) { + signing.deadline_ns = signing.deadline_ns.min(now.saturating_add(KEY_PLAINTEXT_LIFETIME_NS)); + } + signing.terminal = Some(if now >= signing.deadline_ns { + Err(ETIMEDOUT) + } else { + result + }); + session.unseen = true; + true +} + +/// Return the remaining delivery window, wiping expired plaintext. +/// The capture worker retains ownership until delivery, cancellation or expiry. +pub(crate) fn key_plaintext_wait_ns(session: &mut Session, now: u64) -> Option { + let Op::Key(operation) = &mut session.op else { return None; }; + if !matches!(&operation.terminal, Some(Ok(crate::keys::Output::Plaintext(_)))) { + return None; + } + if now >= operation.deadline_ns { + operation.terminal = Some(Err(ETIMEDOUT)); + session.unseen = true; + return None; + } + Some(operation.deadline_ns - now) +} + +pub(crate) fn poll_sign(session: &mut Session, user: UserPtr) -> Result { + let Op::Key(signing) = &session.op else { return Err(ENOENT); }; + if signing.decrypt { return Err(EBUSY); } + let mut out = crate::keys::SignPoll { + state: State::Pending as u32, + status: 0, + guidance: signing.guidance as u32, + sig_len: 0, + signature: [0; ATTEST_SIG_MAX], + }; + match &signing.terminal { + Some(Ok(crate::keys::Output::Signature(signature))) => { + out.state = State::Done as u32; + out.sig_len = signature.len; + out.signature = signature.bytes; + } + Some(Err(error)) => { + out.state = State::Failed as u32; + out.status = error.to_errno(); + } + Some(Ok(_)) => return Err(EIO), + None => {}, + } + UserSlice::new(user, core::mem::size_of_val(&out)).writer().write(&out)?; + session.unseen = false; + ok() +} + +#[kernel::macros::kunit_tests(apple_sep_sign_lifecycle)] +mod sign_tests { + use super::*; + + fn request(deadline_ns: u64, decrypt: bool) -> crate::keys::KeyRequest { + let input = if decrypt { crate::keys::Input::Decrypt(KVec::new()) } + else { crate::keys::Input::Sign([0; 32]) }; + crate::keys::KeyRequest { blob: KVec::new(), input, deadline_ns } + } + + #[test] + fn undelivered_plaintext_expires_or_cancels() -> Result { + for cancel in [false, true] { + let mut session = Session::new(); + open(&mut session)?; + start_key(&mut session, request(u64::MAX, true))?; + let _ = take_key_request(&mut session); + assert!(finish_key(&mut session, Ok(crate::keys::Output::Plaintext(crate::Secret(KVec::new()))))); + let Op::Key(operation) = &session.op else { return Err(EINVAL); }; + let deadline = operation.deadline_ns; + assert_eq!(key_plaintext_wait_ns(&mut session, deadline - 1), Some(1)); + if cancel { assert!(abort_capture(&mut session)); } + assert_eq!(key_plaintext_wait_ns(&mut session, deadline), None); + let Op::Key(operation) = &session.op else { return Err(EINVAL); }; + let expected = if cancel { ECANCELED } else { ETIMEDOUT }; + assert!(matches!(&operation.terminal, Some(Err(error)) if *error == expected)); + } + Ok(()) + } + + #[test] + fn canceled_or_closed_worker_cannot_complete_a_new_request() -> Result { + for (close, decrypt) in [(false, false), (true, false), (false, true), (true, true)] { + let mut session = Session::new(); + open(&mut session)?; + start_key(&mut session, request(u64::MAX, decrypt))?; + assert!(start_key(&mut session, request(u64::MAX, decrypt)).is_err()); + assert!(take_key_request(&mut session).is_some()); + assert!(take_key_request(&mut session).is_none()); + if close { release(&mut session); } else { abort_capture(&mut session); } + assert!(!key_is_live(&session)); + assert!(!finish_key(&mut session, Err(EIO))); + assert!(!session.available()); + assert!(open(&mut session).is_err()); + worker_done(&mut session); + if close { open(&mut session)?; } + start_key(&mut session, request(0, decrypt))?; + assert!(!key_is_live(&session)); + assert!(finish_key(&mut session, Err(EIO))); + let Op::Key(signing) = &session.op else { return Err(EINVAL); }; + assert!(matches!(signing.terminal, Some(Err(ETIMEDOUT)))); + } + Ok(()) + } +} + +pub(crate) fn poll_decrypt(session: &mut Session, user: UserPtr) -> Result { + let mut out: crate::keys::DecryptPoll = + UserSlice::new(user, core::mem::size_of::()).reader().read()?; + let capacity = out.plain_len as usize; + if capacity > crate::keys::MAX_BLOB { return Err(EINVAL); } + let Op::Key(operation) = &mut session.op else { return Err(ENOENT); }; + if !operation.decrypt { return Err(EBUSY); } + if crate::shim::monotonic_ns() >= operation.deadline_ns { + operation.terminal = Some(Err(ETIMEDOUT)); + } + out.state = State::Pending as u32; + out.status = 0; + out.guidance = operation.guidance as u32; + out.plain_len = 0; + let mut consume = false; + match &operation.terminal { + Some(Ok(crate::keys::Output::Plaintext(plain))) => { + out.state = State::Done as u32; + out.plain_len = plain.len() as u32; + if capacity < plain.len() { + UserSlice::new(user, core::mem::size_of_val(&out)).writer().write(&out)?; + return Err(ENOSPC); + } + UserSlice::new(UserPtr::from_addr(out.plain_ptr as usize), capacity) + .writer().write_slice(plain)?; + consume = true; + } + Some(Ok(crate::keys::Output::Consumed)) => return Err(ENODATA), + Some(Ok(_)) => return Err(EIO), + Some(Err(error)) => { + out.state = State::Failed as u32; + out.status = error.to_errno(); + } + None => {}, + } + UserSlice::new(user, core::mem::size_of_val(&out)).writer().write(&out)?; + if consume { operation.terminal = Some(Ok(crate::keys::Output::Consumed)); } + session.unseen = false; + ok() +} diff --git a/drivers/soc/apple/der.rs b/drivers/soc/apple/der.rs index fcd198561872f..808a2e2cc46c4 100644 --- a/drivers/soc/apple/der.rs +++ b/drivers/soc/apple/der.rs @@ -48,13 +48,13 @@ fn integer_bytes(v: u32) -> Result> { pub(crate) enum RefKeyValue<'a> { /// op mnemonic: `oc`/`ow`/`ouw`. Utf8(&'a [u8]), + Boolean(bool), Integer(u32), Octets(&'a [u8]), Der(&'a [u8]), } -/// Canonical DER `SET OF SEQUENCE`, members sorted by key — the shape the -/// enclave parser requires. +/// Apple key-store `SET OF SEQUENCE`, sorted by complete encoded member. pub(crate) fn encode_refkey_set(items: &[(&[u8], RefKeyValue<'_>)]) -> Result> { let mut members: KVec<(&[u8], KVec)> = KVec::new(); for (key, value) in items { @@ -65,6 +65,10 @@ pub(crate) fn encode_refkey_set(items: &[(&[u8], RefKeyValue<'_>)]) -> Result { + // Apple's access-control serializer uses 0x01 for true. + inner.extend_from_slice(&[0x01, 0x01, u8::from(*v)], GFP_KERNEL)?; + } RefKeyValue::Utf8(s) => { if s.len() > MAX_ITEM { return Err(EINVAL); @@ -91,7 +95,7 @@ pub(crate) fn encode_refkey_set(items: &[(&[u8], RefKeyValue<'_>)]) -> Result { + sep: &'a SepData, + handle: [u8; scrd::SCRD_ACM_HANDLE_LEN], +} + +impl<'a> Credential<'a> { + pub(crate) fn new(sep: &'a SepData, handle: [u8; scrd::SCRD_ACM_HANDLE_LEN]) -> Self { + Self { sep, handle } + } + + pub(crate) fn handle(&self) -> &[u8; scrd::SCRD_ACM_HANDLE_LEN] { + &self.handle + } + + pub(crate) fn into_handle(self) -> [u8; scrd::SCRD_ACM_HANDLE_LEN] { + let handle = self.handle; + core::mem::forget(self); + handle + } +} + +impl Drop for Credential<'_> { + fn drop(&mut self) { + if !matches!(self.sep.scrd_command(&scrd::scrd_context_delete(&self.handle)), Some((0, _))) { + self.sep.key_api_failed.store(true, Relaxed); + dev_err!(self.sep.dev, "keys: credential disposal failed; application key operations disabled until reboot\n"); + } + self.handle.fill(0); + } +} + +impl SepData { + pub(crate) fn biometric_keys_supported(&self) -> bool { + // The credential-match layout and policy are validated on this protocol + // generation only. Other profiles retain their existing capabilities. + matches!(self.profile.key_store, profile::KeyStore::Sepos13 { .. }) + && !self.key_api_failed.load(Relaxed) + } + + pub(crate) fn key_credential(&self) -> Result> { + if !self.biometric_keys_supported() { + return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); + } + let keybag::State::Present(stored) = keybag::read(keybag::Slot::Identity)? else { + return Err(ENOENT); + }; + let (handle, _) = self.sks_recover(&stored).ok_or(EIO)?; + let result = (|| { + if !self.sks_prepare_identity_refkey(handle, stored.secret()) { + return Err(EIO); + } + let user = sbio::UserId::new(crate::SBIO_PROBE_USER_ID).ok_or(EINVAL)?; + let context = self.establish_passcode_validated_context(user).ok_or_else(|| { + self.key_api_failed.store(true, Relaxed); + EIO + })?; + Ok(Credential::new(self, context)) + })(); + let unloaded = self.sks_send(self.sks_req_unload_keybag(handle)); + if !matches!(unloaded, Some(ref out) if out.reply.status == 0) { + self.key_api_failed.store(true, Relaxed); + return Err(EIO); + } + result + } + + fn application_refkey_op(&self, items: &[(&[u8], V<'_>)]) -> Result> { + let encoded = der::encode_refkey_set(items)?; + let out = self.sks_send(self.sks_req_refkey(0, &encoded)).ok_or(EIO)?; + if out.reply.status == -8 { + return Err(EACCES); + } + if out.reply.status != 0 { + return Err(EIO); + } + let body = self.sks_report_response(crate::sks::SKS_PERFORM_OP_NAME, &out).ok_or(EIO)?; + let mut fields = proto::FieldCursor::new(body); + match fields.i32().ok_or(EIO)? { + 0 => {}, + -8 => return Err(EACCES), + _ => return Err(EIO), + } + let blob = fields.blob().ok_or(EIO)?; + if blob.len() > MAX_BLOB { + return Err(EIO); + } + let mut owned = KVec::new(); + owned.extend_from_slice(blob, GFP_KERNEL)?; + Ok(owned) + } + + pub(crate) fn create_biometric_key(&self, policy_kind: u32) -> Result<(KVec, [u8; bio::ATTEST_PUB_LEN])> { + let credential = self.key_credential()?; + let result = (|| { + let user = sbio::UserId::new(crate::SBIO_PROBE_USER_ID).ok_or(EINVAL)?; + let crate::SbioOutcome::Ok(binding) = self.sbio_call(&sbio::sbio_catacomb_id(user)) else { + return Err(EIO); + }; + let binding: &[u8; 16] = binding.as_slice().try_into().map_err(|_| EIO)?; + let policy = if policy_kind == 1 { + crate::refkey_policy::biometric_combined_policy(binding)? + } else { + crate::refkey_policy::biometric_signing_policy(binding)? + }; + let items = [ + (b"o".as_slice(), V::Utf8(b"oc")), + (b"bc".as_slice(), V::Integer(9)), + (b"kt".as_slice(), V::Integer(4)), + (b"ed".as_slice(), V::Der(&policy)), + (b"acmh".as_slice(), V::Octets(credential.handle())), + ]; + let blob = self.application_refkey_op(&items)?; + let mut public = [0; bio::ATTEST_PUB_LEN]; + public.copy_from_slice(Self::refkey_pub(&blob).ok_or(EIO)?); + Ok((blob, public)) + })(); + drop(credential); + if self.key_api_failed.load(Relaxed) { return Err(EIO); } + result + } + + pub(crate) fn sign_biometric_key( + &self, + blob: &[u8], + digest: &[u8; 32], + credential: &Credential<'_>, + ) -> Result { + let encoded = self.application_refkey_op(&[ + (b"o", V::Utf8(b"osgn")), + (b"d", V::Octets(digest)), + (b"rk", V::Der(blob)), + (b"acmh", V::Octets(credential.handle())), + ])?; + let bytes = der::octet_string_body(&encoded).unwrap_or(&encoded); + if bytes.len() > bio::ATTEST_SIG_MAX || bytes.first() != Some(&0x30) { + return Err(EIO); + } + let mut signature = Signature { len: bytes.len() as u32, bytes: [0; bio::ATTEST_SIG_MAX] }; + signature.bytes[..bytes.len()].copy_from_slice(bytes); + Ok(signature) + } + + fn decrypt_biometric_key( + &self, + blob: &[u8], + sealed: &[u8], + credential: &Credential<'_>, + ) -> Result { + let mut items = KVec::new(); + items.push((b"o".as_slice(), V::Utf8(b"oecd")), GFP_KERNEL)?; + items.push((b"d".as_slice(), V::Octets(sealed)), GFP_KERNEL)?; + items.push((b"rk".as_slice(), V::Der(blob)), GFP_KERNEL)?; + items.push((b"acmh".as_slice(), V::Octets(credential.handle())), GFP_KERNEL)?; + self.application_refkey_op(&items).map(crate::Secret) + } +} + +pub(crate) struct Signature { + pub(crate) len: u32, + pub(crate) bytes: [u8; bio::ATTEST_SIG_MAX], +} + +pub(crate) struct KeyRequest { + pub(crate) blob: KVec, + pub(crate) input: Input, + pub(crate) deadline_ns: u64, +} + +pub(crate) enum Input { + Sign([u8; 32]), + Decrypt(KVec), +} + +pub(crate) enum Output { + Signature(Signature), + Plaintext(crate::Secret), + Consumed, +} + +#[repr(C)] +struct Create { + flags: u32, + blob_len: u32, + blob_ptr: u64, + public: [u8; bio::ATTEST_PUB_LEN], + reserved: [u8; 7], +} + +#[repr(C)] +struct SignStart { + flags: u32, + timeout_ms: u32, + blob_len: u32, + reserved: u32, + blob_ptr: u64, + digest: [u8; 32], +} + +#[repr(C)] +pub(crate) struct SignPoll { + pub(crate) state: u32, + pub(crate) status: i32, + pub(crate) guidance: u32, + pub(crate) sig_len: u32, + pub(crate) signature: [u8; bio::ATTEST_SIG_MAX], +} + +#[repr(C)] +struct DecryptStart { + flags: u32, + timeout_ms: u32, + blob_len: u32, + sealed_len: u32, + blob_ptr: u64, + sealed_ptr: u64, +} + +#[repr(C)] +pub(crate) struct DecryptPoll { + pub(crate) state: u32, + pub(crate) status: i32, + pub(crate) guidance: u32, + pub(crate) plain_len: u32, + pub(crate) plain_ptr: u64, +} + +static_assert!(core::mem::size_of::() == 88); +static_assert!(core::mem::size_of::() == 56); +static_assert!(core::mem::size_of::() == 88); +static_assert!(core::mem::size_of::() == 32); +static_assert!(core::mem::size_of::() == 24); +// SAFETY: these repr(C) structures contain only integers/bytes and no padding. +unsafe impl kernel::transmute::AsBytes for Create {} +// SAFETY: every bit pattern is valid for all fields. +unsafe impl kernel::transmute::FromBytes for Create {} +// SAFETY: every bit pattern is valid for all fields. +unsafe impl kernel::transmute::FromBytes for SignStart {} +// SAFETY: repr(C), all fields initialized, no padding. +unsafe impl kernel::transmute::AsBytes for SignPoll {} +// SAFETY: every bit pattern is valid for all integer fields; no padding. +unsafe impl kernel::transmute::FromBytes for DecryptStart {} +// SAFETY: every bit pattern is valid for all integer fields; no padding. +unsafe impl kernel::transmute::FromBytes for DecryptPoll {} +// SAFETY: repr(C), initialized integer fields, no padding. +unsafe impl kernel::transmute::AsBytes for DecryptPoll {} + +pub(crate) const IOC_CREATE: u32 = kernel::ioctl::_IOWR::(0xb1, 0x0b); +pub(crate) const IOC_SIGN_START: u32 = kernel::ioctl::_IOW::(0xb1, 0x0c); +pub(crate) const IOC_SIGN_POLL: u32 = kernel::ioctl::_IOR::(0xb1, 0x0d); +pub(crate) const IOC_DECRYPT_START: u32 = kernel::ioctl::_IOW::(0xb1, 0x0e); +pub(crate) const IOC_DECRYPT_POLL: u32 = kernel::ioctl::_IOWR::(0xb1, 0x0f); + +impl SepData { + pub(crate) fn key_ioctl(&self, cmd: u32, arg: usize) -> Result { + use kernel::uaccess::{UserPtr, UserSlice}; + let user = UserPtr::from_addr(arg); + if cmd == IOC_SIGN_POLL { + return bio::key::poll_sign(&mut self.bio_session.lock(), user); + } + if cmd == IOC_DECRYPT_POLL { + let result = bio::key::poll_decrypt(&mut self.bio_session.lock(), user); + self.key_result_changed.notify_all(); + return result; + } + if !self.biometric_keys_supported() { + return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); + } + if !self.xart_writable() { + return Err(EROFS); + } + if self.suspending.load(Relaxed) || !self.bio_session.lock().available() { + return Err(EBUSY); + } + match cmd { + IOC_CREATE => { + let request: Create = UserSlice::new(user, core::mem::size_of::()) + .reader().read()?; + if request.flags > 1 || request.reserved != [0; 7] + || request.blob_len as usize != MAX_BLOB + { + return Err(EINVAL); + } + // The character-device mutex serializes synchronous ioctls. + if !self.bio_session.lock().available() { return Err(EBUSY); } + let result = if self.capture_begin() { + let result = self.create_biometric_key(request.flags); + self.capture_end(); + result + } else { + Err(EBUSY) + }; + let (blob, public) = result?; + UserSlice::new(UserPtr::from_addr(request.blob_ptr as usize), MAX_BLOB) + .writer().write_slice(&blob)?; + let out = Create { + flags: 0, + blob_len: blob.len() as u32, + blob_ptr: request.blob_ptr, + public, + reserved: [0; 7], + }; + UserSlice::new(user, core::mem::size_of::()).writer().write(&out)?; + Ok(bio::Handled { + ret: 0, wake: false, start_enrol: false, start_verify: false, + delete_identity: None, delete_identities: KVec::new(), + }) + } + IOC_SIGN_START => { + let request: SignStart = UserSlice::new(user, core::mem::size_of::()) + .reader().read()?; + if request.flags != 0 || request.reserved != 0 || request.blob_len == 0 + || request.blob_len as usize > MAX_BLOB || !(1..=120_000).contains(&request.timeout_ms) + { + return Err(EINVAL); + } + let mut blob = KVec::new(); + blob.resize(request.blob_len as usize, 0, GFP_KERNEL)?; + UserSlice::new(UserPtr::from_addr(request.blob_ptr as usize), blob.len()) + .reader().read_slice(&mut blob)?; + if Self::refkey_pub(&blob).is_none() { return Err(EINVAL); } + let deadline_ns = crate::shim::monotonic_ns() + .saturating_add(u64::from(request.timeout_ms) * 1_000_000); + bio::key::start_key(&mut self.bio_session.lock(), KeyRequest { + blob, + input: Input::Sign(request.digest), + deadline_ns, + }) + } + IOC_DECRYPT_START => { + let request: DecryptStart = UserSlice::new(user, core::mem::size_of::()) + .reader().read()?; + // P-256 ephemeral point, authenticated ciphertext, 16-byte tag. + if request.flags != 0 || !(1..=120_000).contains(&request.timeout_ms) + || request.blob_len == 0 || request.blob_len as usize > MAX_BLOB + || !(81..=MAX_BLOB).contains(&(request.sealed_len as usize)) + { + return Err(EINVAL); + } + let mut blob = KVec::new(); + blob.resize(request.blob_len as usize, 0, GFP_KERNEL)?; + UserSlice::new(UserPtr::from_addr(request.blob_ptr as usize), blob.len()) + .reader().read_slice(&mut blob)?; + if Self::refkey_pub(&blob).is_none() { return Err(EINVAL); } + let mut sealed = KVec::new(); + sealed.resize(request.sealed_len as usize, 0, GFP_KERNEL)?; + UserSlice::new(UserPtr::from_addr(request.sealed_ptr as usize), sealed.len()) + .reader().read_slice(&mut sealed)?; + if sealed[0] != 4 { return Err(EINVAL); } + let deadline_ns = crate::shim::monotonic_ns() + .saturating_add(u64::from(request.timeout_ms) * 1_000_000); + bio::key::start_key(&mut self.bio_session.lock(), KeyRequest { + blob, + input: Input::Decrypt(sealed), + deadline_ns, + }) + } + _ => Err(ENOTTY), + } + } + + pub(crate) fn run_key_operation(&self, request: KeyRequest) { + let result = (|| { + if !bio::key::key_is_live(&self.bio_session.lock()) { return Err(ECANCELED); } + let credential = self.key_credential()?; + let result = match self.verify_capture(Some(credential.handle())) { + bio::VerifyOutcome::Matched(_) => { + if !bio::key::key_is_live(&self.bio_session.lock()) { Err(ECANCELED) } + else { + match &request.input { + Input::Sign(digest) => self.sign_biometric_key(&request.blob, digest, &credential) + .map(Output::Signature), + Input::Decrypt(sealed) => self.decrypt_biometric_key(&request.blob, sealed, &credential) + .map(Output::Plaintext), + } + } + } + bio::VerifyOutcome::NoMatch => Err(EACCES), + bio::VerifyOutcome::Failed(crate::ENROL_STATUS_TIMEOUT) => Err(ETIMEDOUT), + bio::VerifyOutcome::Failed(_) => Err(EIO), + }; + drop(credential); + if self.key_api_failed.load(Relaxed) { return Err(EIO); } + result + })(); + if bio::key::finish_key(&mut self.bio_session.lock(), result) { self.bio_wake(); } + // Wait on the session predicate so a consumed/canceled result releases + // ownership promptly, and an abandoned result is wiped at its deadline. + { + let mut session = self.bio_session.lock(); + while let Some(remaining) = bio::key::key_plaintext_wait_ns(&mut session, crate::shim::monotonic_ns()) { + let timeout = kernel::time::msecs_to_jiffies(remaining.div_ceil(1_000_000) as u32); + if matches!(self.key_result_changed.wait_interruptible_timeout(&mut session, timeout), + kernel::sync::CondVarTimeoutResult::Signal { .. }) + { + bio::abort_capture(&mut session); + break; + } + } + } + self.bio_wake(); + } +} diff --git a/drivers/soc/apple/refkey.rs b/drivers/soc/apple/refkey.rs index 4d54246bf4f68..9844b5b38feb3 100644 --- a/drivers/soc/apple/refkey.rs +++ b/drivers/soc/apple/refkey.rs @@ -14,7 +14,7 @@ use kernel::sync::atomic::Relaxed; pub(crate) const REFKEY_ENVELOPE_VERSION: u32 = 2; impl SepData { - fn sks_req_refkey(&self, keybag: i32, der_set: &[u8]) -> Result { + pub(crate) fn sks_req_refkey(&self, keybag: i32, der_set: &[u8]) -> Result { let (keybag, envelope) = match self.profile.key_store { // The 13.5 operation envelope is 3. Use the designated identity // session rather than the source handle; class F with -1 expired @@ -43,7 +43,7 @@ impl SepData { }) } - fn sks_prepare_identity_refkey( + pub(crate) fn sks_prepare_identity_refkey( &self, handle: crate::sks::KeyBagHandle, secret: &[u8], @@ -157,7 +157,7 @@ impl SepData { Some(refkey_blob) } - fn refkey_pub(blob: &[u8]) -> Option<&[u8]> { + pub(crate) fn refkey_pub(blob: &[u8]) -> Option<&[u8]> { let rk_tlv = crate::der::refkey_find(blob, b"rk")?; let pub_raw = crate::der::refkey_find(rk_tlv, b"pub").and_then(crate::der::octet_string_body)?; diff --git a/drivers/soc/apple/refkey_policy.rs b/drivers/soc/apple/refkey_policy.rs new file mode 100644 index 0000000000000..c6194115c60e1 --- /dev/null +++ b/drivers/soc/apple/refkey_policy.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Access control for application-owned biometric signing keys. + +use crate::der::{encode_refkey_set, RefKeyValue as V}; +use kernel::prelude::*; + +/// Bind private-key use to this biometric credential set. Enrollment changes +/// within the set are permitted; this is not a current-enrollment-set policy. +pub(crate) fn biometric_signing_policy(binding: &[u8; 16]) -> Result> { + let biometric = biometric_constraint(binding)?; + let acl = encode_refkey_set(&[ + (b"oa", V::Boolean(true)), + (b"ock", V::Der(&biometric)), + (b"okd", V::Der(&biometric)), + (b"odel", V::Boolean(true)), + (b"osgn", V::Der(&biometric)), + ])?; + encode_refkey_set(&[(b"acl", V::Der(&acl))]) +} + +pub(crate) fn biometric_combined_policy(binding: &[u8; 16]) -> Result> { + let biometric = biometric_constraint(binding)?; + let acl = encode_refkey_set(&[ + (b"oa", V::Boolean(true)), + (b"ock", V::Der(&biometric)), + (b"okd", V::Der(&biometric)), + (b"osgn", V::Der(&biometric)), + (b"od", V::Der(&biometric)), + (b"oecd", V::Der(&biometric)), + (b"oe", V::Boolean(true)), + (b"odel", V::Boolean(true)), + ])?; + encode_refkey_set(&[(b"acl", V::Der(&acl))]) +} + +fn biometric_constraint(binding: &[u8; 16]) -> Result> { + if binding.iter().all(|v| *v == 0) { return Err(EINVAL); } + let credential = encode_refkey_set(&[(b"pbioc", V::Octets(binding))])?; + encode_refkey_set(&[(b"cbio", V::Der(&credential))]) +} + +#[kernel::macros::kunit_tests(apple_sep_refkey_policy)] +mod tests { + use super::*; + + #[test] + fn member_order_uses_encoded_length_before_key() -> Result { + let encoded = encode_refkey_set(&[ + (b"a", V::Octets(&[0; 16])), + (b"z", V::Boolean(true)), + ])?; + assert_eq!(&encoded[..10], &[0x31, 31, 0x30, 6, 0x0c, 1, b'z', 1, 1, 1]); + Ok(()) + } + + #[test] + fn policy_matches_native_encoding() -> Result { + let binding = core::array::from_fn(|i| i as u8); + let expected: &[u8] = &[ + 0x31, 0x81, 0xaa, 0x30, 0x81, 0xa7, 0x0c, 0x03, 0x61, 0x63, 0x6c, 0x31, + 0x81, 0x9f, 0x30, 0x07, 0x0c, 0x02, 0x6f, 0x61, 0x01, 0x01, 0x01, 0x30, + 0x09, 0x0c, 0x04, 0x6f, 0x64, 0x65, 0x6c, 0x01, 0x01, 0x01, 0x30, 0x2c, + 0x0c, 0x03, 0x6f, 0x63, 0x6b, 0x31, 0x25, 0x30, 0x23, 0x0c, 0x04, 0x63, + 0x62, 0x69, 0x6f, 0x31, 0x1b, 0x30, 0x19, 0x0c, 0x05, 0x70, 0x62, 0x69, + 0x6f, 0x63, 0x04, 0x10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x30, 0x2c, 0x0c, 0x03, + 0x6f, 0x6b, 0x64, 0x31, 0x25, 0x30, 0x23, 0x0c, 0x04, 0x63, 0x62, 0x69, + 0x6f, 0x31, 0x1b, 0x30, 0x19, 0x0c, 0x05, 0x70, 0x62, 0x69, 0x6f, 0x63, + 0x04, 0x10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x30, 0x2d, 0x0c, 0x04, 0x6f, 0x73, + 0x67, 0x6e, 0x31, 0x25, 0x30, 0x23, 0x0c, 0x04, 0x63, 0x62, 0x69, 0x6f, + 0x31, 0x1b, 0x30, 0x19, 0x0c, 0x05, 0x70, 0x62, 0x69, 0x6f, 0x63, 0x04, + 0x10, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + ]; + assert_eq!(biometric_signing_policy(&binding)?.as_slice(), expected); + Ok(()) + } + + #[test] + fn policy_requires_a_credential_set() { + assert!(biometric_signing_policy(&[0; 16]).is_err()); + } +} diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 6c265fe2ed425..1e23ca187accc 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -40,13 +40,17 @@ impl SepData { // answer has to be recorded here or nowhere. Success is decided as in // `sbio_call`. fn sbio_verify_step(&self, op: &crate::sbio::SbioOp) -> Option> { - let done = match self.sbio_transfer(op) { + self.sbio_verify_payload(op.opcode(), op.name(), op.payload()) + } + + fn sbio_verify_payload(&self, opcode: u16, name: &'static CStr, payload: &[u8]) -> Option> { + let done = match self.sbio_transfer_raw(opcode, name, payload) { Ok(done) => done, Err(e) => { dev_err!( self.dev, "verify: {} transfer failed ({:?})\n", - op.name(), + name, e ); return None; @@ -58,7 +62,7 @@ impl SepData { dev_err!( self.dev, "verify: {} answered status {}\n", - op.name(), + name, done.status ); None @@ -285,7 +289,8 @@ impl SepData { self.bio_wake(); } - fn bio_wake(&self) { + pub(crate) fn bio_wake(&self) { + self.key_result_changed.notify_all(); if let Some(dev) = self.bio_dev.lock().as_ref() { dev.wake(); } @@ -1299,19 +1304,13 @@ impl SepData { } pub(crate) fn run_verify(&self) { - self.retry_restore_proof(); - if !self.templates_restored.load(Relaxed) { - dev_err!( - self.dev, - "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\n" - ); - self.finish_verify( - bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE), - [0u8; bio::TOKEN_LEN], - ); + let signing = bio::key::is_key_operation(&self.bio_session.lock()); + if signing { + let request = bio::key::take_key_request(&mut self.bio_session.lock()); + if let Some(request) = request { self.run_key_operation(request); } return; } - + if !bio::verify_is_live(&self.bio_session.lock()) { return; } let Some(token_bytes) = self.mint_token_bytes() else { dev_err!(self.dev, "verify: could not draw a result token\n"); self.finish_verify( @@ -1320,20 +1319,28 @@ impl SepData { ); return; }; + let outcome = self.verify_capture(None); + self.finish_verify(outcome, token_bytes); + } + pub(crate) fn verify_capture(&self, context: Option<&[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]>) -> bio::VerifyOutcome { + self.retry_restore_proof(); + if !self.templates_restored.load(Relaxed) { + dev_err!(self.dev, "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\n"); + return bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE); + } self.settle_before_capture(); // The enclave refuses a capture from an uncalibrated sensor (0x65 answers 1). if !self.bring_sensor_online() { dev_err!(self.dev, "verify: the sensor did not come back online\n"); - self.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), token_bytes); let _ = sensor::idle(); - return; + return bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR); } - // The match uses the plain 0x23->0x06->0x65 pipeline, with no SCRD step. + // Identification and credential matches share the capture pipeline. - let outcome = self.verify_one_image(); + let outcome = self.verify_one_image(context); let _ = sensor::idle(); sensor::power(false); self.note_capture_end(); @@ -1344,27 +1351,19 @@ impl SepData { ); if definitive { let Some(user) = crate::sbio::UserId::new(SBIO_PROBE_USER_ID) else { - self.finish_verify( - bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE), - token_bytes, - ); - return; + return bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE); }; if !self.save_after_match(user) { - self.finish_verify( - bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE), - token_bytes, - ); - return; + return bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE); } } - self.finish_verify(outcome, token_bytes); + outcome } // Every exit that fails a live verify logs why: userspace sees only a bare // "unspecified error", which cannot tell a sensor fault from a refused // match step. - fn verify_one_image(&self) -> bio::VerifyOutcome { + fn verify_one_image(&self, context: Option<&[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]>) -> bio::VerifyOutcome { let Some(user) = crate::sbio::UserId::new(SBIO_PROBE_USER_ID) else { dev_err!(self.dev, "verify: invalid probe user id\n"); return bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE); @@ -1449,7 +1448,15 @@ impl SepData { user, crate::shim::monotonic_ns(), ); - if self.sbio_verify_step(&init).is_none() { + let accepted = if let Some(context) = context { + match crate::sbio::sbio_credential_image_init(&init, context) { + Ok(payload) => self.sbio_verify_payload(init.opcode(), init.name(), &payload).is_some(), + Err(_) => false, + } + } else { + self.sbio_verify_step(&init).is_some() + }; + if !accepted { return bio::VerifyOutcome::Failed(ENROL_STATUS_ENCLAVE); } @@ -2597,9 +2604,7 @@ impl SepData { pub(crate) fn bio_release(&self) { bio::release(&mut self.bio_session.lock()); - if let Some(dev) = self.bio_dev.lock().as_ref() { - dev.wake(); - } + self.bio_wake(); } /// Called by the enrol and verify work items before they touch the sensor. @@ -2684,6 +2689,7 @@ impl SepData { .is_err() { this.finish_enrolment(Err(ENROL_STATUS_SENSOR)); + bio::worker_done(&mut this.bio_session.lock()); } } @@ -2692,10 +2698,13 @@ impl SepData { .enqueue::, VERIFY_WORK_ID>(this.clone()) .is_err() { - this.finish_verify( - bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), - [0u8; bio::TOKEN_LEN], - ); + if bio::key::is_key_operation(&this.bio_session.lock()) { + bio::key::finish_key(&mut this.bio_session.lock(), Err(EIO)); + this.bio_wake(); + } else { + this.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), [0; bio::TOKEN_LEN]); + } + bio::worker_done(&mut this.bio_session.lock()); } } @@ -2720,7 +2729,13 @@ impl SepData { } pub(crate) fn bio_ioctl(&self, cmd: u32, arg: usize) -> Result { + if matches!(cmd, crate::keys::IOC_CREATE | crate::keys::IOC_SIGN_START | crate::keys::IOC_SIGN_POLL + | crate::keys::IOC_DECRYPT_START | crate::keys::IOC_DECRYPT_POLL) + { + return self.key_ioctl(cmd, arg); + } if cmd == bio::IOC_ATTEST { + if !self.bio_session.lock().available() { return Err(EBUSY); } return self.bio_attest(arg); } // With xART writes off the enclave cannot persist what an enrolment or @@ -2762,6 +2777,7 @@ impl SepData { index: &index, sensor_present, live_identity_count, + biometric_keys_supported: self.biometric_keys_supported(), }; bio::ioctl(&mut ctx, cmd, arg)? }; @@ -3050,6 +3066,8 @@ pub(crate) struct SbioOp { const SBIO_MAX_PAYLOAD: usize = 0x97; pub(crate) const SBIO_IMAGE_INIT_LEN: usize = 0x97; +pub(crate) const SBIO_CREDENTIAL_IMAGE_INIT_LEN: usize = + SBIO_IMAGE_INIT_LEN + crate::scrd::SCRD_ACM_HANDLE_LEN; static_assert!(SBIO_IMAGE_INIT_LEN <= SBIO_MAX_PAYLOAD); const fn pad_payload(src: &[u8]) -> [u8; SBIO_MAX_PAYLOAD] { @@ -3665,6 +3683,15 @@ pub(crate) fn sbio_free_identity_count(user: UserId) -> SbioOp { } } +pub(crate) fn sbio_catacomb_id(user: UserId) -> SbioOp { + SbioOp { + opcode: 0x33, + payload: pad_payload(&user.value().to_le_bytes()), + payload_len: 4, + name: c"CATACOMB_ID", + } +} + const OP_SBIO_DELETE_IDENTITY: u16 = 0x57; pub(crate) fn sbio_delete_identity(identity: &IdentityV1) -> SbioOp { SbioOp { @@ -3878,6 +3905,42 @@ pub(crate) fn sbio_prepare_image_processing() -> SbioOp { } const OP_SBIO_IMAGE_INIT: u16 = 0x06; + +/// Bind a match to a credential set, rather than returning identification only. +pub(crate) fn sbio_credential_image_init( + base: &SbioOp, + context: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN], +) -> Result<[u8; SBIO_CREDENTIAL_IMAGE_INIT_LEN]> { + if base.opcode() != OP_SBIO_IMAGE_INIT || base.payload().len() != SBIO_IMAGE_INIT_LEN { + return Err(EINVAL); + } + let mut payload = [0u8; SBIO_CREDENTIAL_IMAGE_INIT_LEN]; + payload[..SBIO_IMAGE_INIT_LEN].copy_from_slice(base.payload()); + payload[..4].copy_from_slice(&8u32.to_le_bytes()); + payload[0x93..SBIO_IMAGE_INIT_LEN] + .copy_from_slice(&(context.len() as u32).to_le_bytes()); + payload[SBIO_IMAGE_INIT_LEN..].copy_from_slice(context); + Ok(payload) +} + +#[kernel::macros::kunit_tests(apple_sep_credential_capture)] +mod credential_capture_tests { + use super::*; + + #[test] + fn credential_match_preserves_capture_fields() -> Result { + let user = UserId::new(501).ok_or(EINVAL)?; + let base = sbio_image_processing_init(ImagePurpose::Matching, true, true, 0, user, 1000); + let context = [0x5a; crate::scrd::SCRD_ACM_HANDLE_LEN]; + let payload = sbio_credential_image_init(&base, &context)?; + assert_eq!(&payload[..4], &8u32.to_le_bytes()); + assert_eq!(&payload[4..0x93], &base.payload()[4..0x93]); + assert_eq!(&payload[0x93..0x97], &16u32.to_le_bytes()); + assert_eq!(&payload[0x97..], &context); + assert!(sbio_credential_image_init(&sbio_match_result(), &context).is_err()); + Ok(()) + } +} pub(crate) fn sbio_image_processing_init( purpose: ImagePurpose, first_image: bool, diff --git a/drivers/soc/apple/scrd.rs b/drivers/soc/apple/scrd.rs index acdcdab12db65..d33b3344dc600 100644 --- a/drivers/soc/apple/scrd.rs +++ b/drivers/soc/apple/scrd.rs @@ -17,6 +17,7 @@ const SCRD_MAGIC: [u8; 4] = *b"DRCS"; const SCRD_CMD_INITIALIZE: u8 = 0x0a; const SCRD_CMD_CONTEXT_CREATE_TRACKED: u8 = 0x24; const SCRD_CMD_CONTEXT_EXTERNALIZE: u8 = 0x13; +const SCRD_CMD_CONTEXT_DELETE: u8 = 0x02; const SCRD_CMD_VERIFY_POLICY: u8 = 0x03; const SCRD_INIT_LOG_LEVEL: u8 = 0x28; @@ -90,6 +91,18 @@ pub(crate) fn scrd_context_externalize(handle: &[u8; SCRD_ACM_HANDLE_LEN]) -> Sc } } +pub(crate) fn scrd_context_delete(handle: &[u8; SCRD_ACM_HANDLE_LEN]) -> ScrdCommand { + let mut payload = [0u8; SCRD_MAX_LOGICAL]; + scrd_header(&mut payload, SCRD_CMD_CONTEXT_DELETE, 0, 1); + payload[8..8 + SCRD_ACM_HANDLE_LEN].copy_from_slice(handle); + ScrdCommand { + request: SCRD_REQUEST_COMMAND, + payload, + payload_len: 8 + SCRD_ACM_HANDLE_LEN, + name: c"SCRD_CONTEXT_DELETE", + } +} + pub(crate) fn scrd_verify_touchid_enrollment(handle: &[u8; SCRD_ACM_HANDLE_LEN]) -> ScrdCommand { let mut payload = [0u8; SCRD_MAX_LOGICAL]; scrd_header(&mut payload, SCRD_CMD_VERIFY_POLICY, 0, 1); diff --git a/drivers/soc/apple/sep-bio.h b/drivers/soc/apple/sep-bio.h index d52b880ac9332..06510ea94eb79 100644 --- a/drivers/soc/apple/sep-bio.h +++ b/drivers/soc/apple/sep-bio.h @@ -55,6 +55,8 @@ struct sep_bio_info { /* reserved[0] flags; reserved[1] is a live SEP identity count only when valid. */ #define SEP_BIO_INFO_LIVE_COUNT_VALID 1u +#define SEP_BIO_INFO_BIOMETRIC_KEYS 2u +#define SEP_BIO_INFO_BIOMETRIC_DECRYPT 4u struct sep_bio_list { __u32 count; @@ -128,3 +130,59 @@ struct sep_bio_attest { #define SEP_BIO_DELETE _IOW (SEP_BIO_IOC_MAGIC, 0x08, struct sep_bio_delete) #define SEP_BIO_DELETE_ALL _IO (SEP_BIO_IOC_MAGIC, 0x09) #define SEP_BIO_ATTEST _IOWR(SEP_BIO_IOC_MAGIC, 0x0a, struct sep_bio_attest) + +/* Application-owned P-256 keys with biometric private-key-use policy. */ +#define SEP_BIO_KEY_BLOB_MAX 4096 +/* Also constrain ECIES private-key use to biometry. */ +#define SEP_BIO_KEY_CREATE_DECRYPT 1u + +struct sep_bio_key_create { + __u32 flags; /* zero or SEP_BIO_KEY_CREATE_DECRYPT */ + __u32 blob_len; /* in: KEY_BLOB_MAX capacity; out: actual size */ + __aligned_u64 blob_ptr; /* userspace output buffer, persist with public */ + __u8 public[SEP_BIO_ATTEST_PUB_LEN]; + __u8 reserved[7]; /* must be zero */ +}; + +struct sep_bio_key_sign_start { + __u32 flags; /* must be zero */ + __u32 timeout_ms; /* 1..120000, CLOCK_MONOTONIC */ + __u32 blob_len; /* 1..KEY_BLOB_MAX */ + __u32 reserved; /* must be zero */ + __aligned_u64 blob_ptr; /* copied before START returns */ + __u8 digest[32]; /* precomputed SHA-256 digest, not message bytes */ +}; + +struct sep_bio_key_sign_poll { + __u32 state; /* SEP_BIO_STATE_* */ + __s32 status; /* negative errno when FAILED */ + __u32 guidance; /* SEP_BIO_GUIDANCE_* */ + __u32 sig_len; + __u8 signature[SEP_BIO_ATTEST_SIG_MAX]; +}; + +/* Same exclusive open, poll(2), and CANCEL as enrol/verify. */ +#define SEP_BIO_KEY_CREATE _IOWR(SEP_BIO_IOC_MAGIC, 0x0b, struct sep_bio_key_create) +#define SEP_BIO_KEY_SIGN_START _IOW (SEP_BIO_IOC_MAGIC, 0x0c, struct sep_bio_key_sign_start) +#define SEP_BIO_KEY_SIGN_POLL _IOR (SEP_BIO_IOC_MAGIC, 0x0d, struct sep_bio_key_sign_poll) + +/* ECIES: ephemeral P-256 point (65), ciphertext, AES-GCM tag (16). */ +struct sep_bio_key_decrypt_start { + __u32 flags; /* must be zero */ + __u32 timeout_ms; /* 1..120000, CLOCK_MONOTONIC */ + __u32 blob_len; /* 1..KEY_BLOB_MAX */ + __u32 sealed_len; /* 81..KEY_BLOB_MAX */ + __aligned_u64 blob_ptr; /* copied before START returns */ + __aligned_u64 sealed_ptr; /* copied before START returns */ +}; + +struct sep_bio_key_decrypt_poll { + __u32 state; + __s32 status; /* negative errno when FAILED */ + __u32 guidance; + __u32 plain_len; /* in: capacity; out: required/actual plaintext size */ + __aligned_u64 plain_ptr; /* plaintext is host-visible; consumed on success */ +}; + +#define SEP_BIO_KEY_DECRYPT_START _IOW (SEP_BIO_IOC_MAGIC, 0x0e, struct sep_bio_key_decrypt_start) +#define SEP_BIO_KEY_DECRYPT_POLL _IOWR(SEP_BIO_IOC_MAGIC, 0x0f, struct sep_bio_key_decrypt_poll) diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index cf1dc2bd91737..ba6e23489c27f 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -16,12 +16,14 @@ mod dt; mod fv; mod hwrng; mod image; +mod keys; mod keybag; mod keybag_identity; mod pm; mod profile; mod proto; mod refkey; +mod refkey_policy; mod refkey_seal; mod rxring; mod sbio; @@ -640,6 +642,10 @@ struct SepData { #[pin] bio_session: Mutex, + key_api_failed: Atomic, + + #[pin] + key_result_changed: CondVar, #[pin] bio_index: Mutex, @@ -844,6 +850,8 @@ impl SepData { sbio_wq <- new_condvar!("SepData::sbio_wq"), sbio_ready: Atomic::new(false), bio_session <- new_mutex!(bio::Session::new()), + key_api_failed: Atomic::new(false), + key_result_changed <- new_condvar!("SepData::key_result_changed"), bio_index <- new_mutex!(bio_index), bio_dev <- new_mutex!(None), store <- new_mutex!(store), @@ -1668,6 +1676,7 @@ impl SepData { } let mut acm_handle = [0u8; crate::scrd::SCRD_ACM_HANDLE_LEN]; acm_handle.copy_from_slice(&out[..crate::scrd::SCRD_ACM_HANDLE_LEN]); + let credential = keys::Credential::new(self, acm_handle); let Some((status, _)) = self.scrd_command(&crate::scrd::scrd_context_externalize(&acm_handle)) else { dev_err!(self.dev, "enrol: SCRD context externalize did not answer\n"); @@ -1698,7 +1707,7 @@ impl SepData { return None; } - Some(acm_handle) + Some(credential.into_handle()) } fn establish_scrd_match_context(&self, user: crate::sbio::UserId) -> bool { @@ -2027,6 +2036,7 @@ impl SepData { self.sbio_wq.notify_all(); self.sks_wq.notify_all(); self.scrd_wq.notify_all(); + self.key_result_changed.notify_all(); if let Some(mut handle) = self.rng.lock().take() { handle.unregister(); } @@ -2197,10 +2207,12 @@ impl WorkItem for SepData { fn run(this: Arc) { if this.shutting_down.load(Relaxed) || !this.capture_begin() { + bio::worker_done(&mut this.bio_session.lock()); return; } this.run_enrolment(); this.capture_end(); + bio::worker_done(&mut this.bio_session.lock()); } } @@ -2209,10 +2221,12 @@ impl WorkItem for SepData { fn run(this: Arc) { if this.shutting_down.load(Relaxed) || !this.capture_begin() { + bio::worker_done(&mut this.bio_session.lock()); return; } this.run_verify(); this.capture_end(); + bio::worker_done(&mut this.bio_session.lock()); } } diff --git a/tools/apple-sep/DECRYPTION.md b/tools/apple-sep/DECRYPTION.md new file mode 100644 index 0000000000000..6e18854496291 --- /dev/null +++ b/tools/apple-sep/DECRYPTION.md @@ -0,0 +1,185 @@ +# Biometric item decryption: application integration + +This extends the biometric signing interface. The driver accepts a wrapped +application P-256 key +and an ECIES ciphertext, performs a new fingerprint match in a fresh kernel-owned +context, decrypts in SEP, deletes the context, and delivers plaintext to the host. +No raw SEP protocol, authentication handle or machine artifact is needed by the +application. Do not use trusted-key machine sealing or ATTEST as a substitute. + +The recipient private scalar remains inside SEP. The requested item's plaintext +does reach the application. A synced passkey encrypted as an item is therefore +used for **software signing after biometric decryption**. This is different from +a new SEP-generated passkey, for which `sign_digest` returns only a signature. +There is no demonstrated import-existing-private-key-and-sign-in-SEP capability. + +## Files and supported entry points + +- `sep-bio.h`: structures, constants and ioctl definitions. +- `sep-key.py`: `SepClient.create(decrypt=True)` and + `SepClient.decrypt_into(blob, sealed, output, timeout_ms=60000)`. +- `sep_envelope.py`: `seal_item(public, context, plaintext)` and + `item_view(output, length, expected_context)`. + +Python 3.11+ and the `cryptography` package are needed for the envelope example. +Signing verification additionally uses OpenSSL. The examples are for integration +and disposable-data validation; Python and its crypto backend cannot guarantee +zeroization of every temporary. Production secret handling belongs in the +application's existing bounded, zeroizing memory implementation. + +The device is root-only and exclusively opened. Coordinate with fprintd through +a trusted helper/broker that checks caller identity, key ownership and purpose. +Neither the sample nor driver implements application authorization, WebAuthn +RP/origin checks or multi-user isolation. Do not grant applications unrestricted +device access or trust a caller-supplied `user_verified` boolean. + +## Key creation and persistence + +Use CREATE flag `SEP_BIO_KEY_CREATE_DECRYPT` (1) for a new biometric item key. +Flag 0 retains the existing signing policy; do not assume signing-only blobs +support decryption. The decrypt-enabled policy also permits biometric signing; +the broker must restrict allowed application operations itself. + +```sh +sudo python3 sep-key.py create --decrypt disposable-item-key.json +``` + +Creation needs working biometric restoration and current enrollments but does +not scan a finger. The blob, 65-byte public point, policy and expected key ID must +be stored atomically with integrity protection in the application's private +store. The example JSON is not a kernel format. Do not use a maintainer's test +key, provision/replace the system keybag, alter enrollments or load old xART. + +Wrapped blobs are bound to this device and secure-state lineage, not portable +backups. Their number is not a measured hardware capacity. Serialize requests +and bound live resources rather than assuming unlimited contexts or slots. + +`GET_INFO.reserved[0]` advertises `SEP_BIO_INFO_BIOMETRIC_KEYS` (2) for signing +and `SEP_BIO_INFO_BIOMETRIC_DECRYPT` (4) for this decrypt interface. The ABI version +remains 4. The client checks the appropriate capability before key creation or +decryption. Older signing-only drivers need not support decrypt. Handle ENOTTY, +EINVAL and EOPNOTSUPP explicitly; do not downgrade to an unrestricted key or +software root. Unsupported key-store protocol profiles fail closed. + +## Reference use + +The following uses only disposable application data. Resolve example paths +relative to the directory containing these files. The application supplies its +own canonical context encoding; this illustrative context is not a new storage +standard or a WebAuthn authorization scheme. + +```python +import base64 +import ctypes +import importlib.util +import json +from pathlib import Path +from sep_envelope import seal_item, item_view + +spec = importlib.util.spec_from_file_location('sep_key', Path('sep-key.py')) +api = importlib.util.module_from_spec(spec) +spec.loader.exec_module(api) +saved = json.loads(Path('disposable-item-key.json').read_text()) +blob = base64.b64decode(saved['blob'], validate=True) +public = base64.b64decode(saved['public'], validate=True) + +# Derive this from trusted selected-record state, including owner and purpose. +context = b'app=example;owner=local;record=disposable;purpose=password;v=1' +sealed = seal_item(public, context, b'disposable example secret') +# Store sealed, plus integrity-protected key/record metadata. No scan to encrypt. + +output = bytearray(4096) +try: + print('Touch an enrolled finger now', flush=True) + with api.SepClient() as client: + size = client.decrypt_into(blob, sealed, output) + item = item_view(output, size, context) + # Use this borrowed view in the authorized operation; do not log it. + # Imported passkey scalars must still be signed with host software. +finally: + ctypes.memset(ctypes.addressof((ctypes.c_ubyte * len(output)).from_buffer(output)), + 0, len(output)) +``` + +`decrypt_into` writes into a caller-owned 4096-byte bytearray and returns the +actual length. It clears that buffer on errors; the caller must clear successful +output too. `item_view` checks the decrypted binding and returns a borrowed view, +not a private-key import or a secret-free signing capability. Do not copy it to +immutable strings/bytes, logs or a plaintext temporary file. + +Encryption uses transient ECDH/AES material on the host. The persistent recipient +private key stays inside SEP; a claim that all encryption keys stay in SEP would +be incorrect. Decrypting a vault-wide root is technically possible within the +size limit, but releases that root to the host. Prefer per-item envelopes when +the desired authorization scope is one selected item. + +## Exact wire and ciphertext formats + +All ioctl fields use native integer byte order (little-endian on the target). +Pointers are aligned 64-bit userspace addresses, not IOVAs or SEP handles. + +| Request | Number | Layout in field order | Size | +| --- | --- | --- | --- | +| CREATE | `0xc058b10b` | flags u32, capacity/length u32, blob pointer u64, public[65], reserved[7] | 88 | +| DECRYPT_START | `0x4020b10e` | flags u32, timeout_ms u32, blob_len u32, sealed_len u32, blob pointer u64, ciphertext pointer u64 | 32 | +| DECRYPT_POLL | `0xc018b10f` | state u32, status i32, guidance u32, capacity/length u32, plaintext pointer u64 | 24 | + +CREATE capacity must be 4096; reserved bytes zero. DECRYPT_START flags must be +zero; timeout is 1..120000 ms; blob length 1..4096; ciphertext length 81..4096 +including overhead. Both inputs are copied before START returns. Rebuild the +POLL descriptor with output capacity before every call; never reuse a previous +pending response's zero length as the next capacity. + +States: pending 1, progress 2, done 3, failed 4. Status is negative errno on +failure. Use the same `poll(2)` and CANCEL (`0xb107`) as signing. Allocate 4096 +output bytes to avoid ENOSPC; it reports required length but does not consume +the successful result. Successful delivery consumes it; another immediate POLL +returns ENODATA. After expiry it can report ETIMEDOUT instead. + +The result is eligible for delivery only before the original monotonic request +deadline and for five seconds after completion, whichever is sooner. An existing +worker waits for delivery, cancellation or the deadline and expires abandoned +output independently of userspace polling, subject to timer granularity and +normal scheduling. Close/cancel drops retained output. These kernel +bounds do not erase plaintext already copied into application memory. + +The ciphertext format tested with this firmware is: + +```text +ephemeral uncompressed P-256 point[65] || ciphertext[N] || GCM tag[16] +Z = ECDH(sender ephemeral private, recipient public), 32-byte big-endian X +KDF block i = SHA256(Z || BE32(i) || ephemeral point[65]), starting at i=1 +material = block1 || block2 +AES key = material[0:32]; IV = material[32:48]; AAD = empty +``` + +Use AES-256 with the derived **16-byte IV**, not AES-128 or a random 12-byte IV. +The sample authenticated plaintext is `SEPITEM 0x01` (8 bytes), a BE32 context +length, context, then item bytes. The 81-byte ECIES overhead leaves at most 4015 +plaintext bytes, including that envelope. The firmware authenticates ciphertext; +the application checks the decrypted context before using the item. + +Expected context must come from trusted selected-record state, not merely an +unencrypted field stored beside the blob. Include application/owner, record ID, +purpose and algorithm with canonical unambiguous encoding. Envelope binding does +not prevent replay of an older valid version; rollback protection needs separate +trusted state. Encryption is public-key encryption: anyone with the public point +can construct a new valid ciphertext, so this is not proof of who created an +item. Preserve the application's authenticated storage and record ownership. + +## Errors and evidence limits + +Fail closed on EACCES (match/authorization refusal), ETIMEDOUT, ECANCELED, +EIO (transport/protocol/cleanup or rejected decrypt), EROFS and unsupported +operations. EBUSY means another operation/cleanup owns the device. Do not +automatically retry ambiguous completion or request another scan in a hidden +loop. A UI may offer an explicit new operation. + +Biometric-gated decryption, saved-key warm-reboot use, modified-tag rejection +without plaintext, fresh-request refusal without a new scan, single-use delivery +and signing regression passed on J293/M1. Autonomous expiry of an undelivered +result and cancellation before delivery also passed on hardware, in addition +to the focused source tests. Cold power-cycle, suspend, other hardware, +biometric enrollment-set invalidation, +native private-key import and production broker isolation are not established. +No production vault migration is implied by these primitive tests. diff --git a/tools/apple-sep/README.md b/tools/apple-sep/README.md new file mode 100644 index 0000000000000..b9478abc73ad0 --- /dev/null +++ b/tools/apple-sep/README.md @@ -0,0 +1,93 @@ +# Biometric P-256 keys + +`sep-key.py` is a small reference client for the key ioctls in +`drivers/soc/apple/sep-bio.h`. It needs Python 3.11 or newer and the OpenSSL +command-line tool for independent signature verification. It does not implement +Apple firmware protocols in userspace. + +The driver creates a P-256 private key with a biometric credential-set policy. +Applications store the returned opaque wrapped blob and public point. The private +scalar remains inside SEP. These keys are device bound; the blob is not a backup +that can be restored onto another machine or after erasing secure state. + +## Example + +The device must already have working biometric restoration and enrolled fingers. +It uses the same exclusive open as fprintd. Stop competing clients for this test; +the sample does not change services, enroll fingers or provision keybags. + +```sh +sudo python3 tools/apple-sep/sep-key.py create application-key.json +printf 'example message' > message +sudo python3 tools/apple-sep/sep-key.py sign application-key.json message signature.der +``` + +Touch the sensor when prompted. The second command hashes the message once with +SHA-256, asks SEP to sign that digest, and independently verifies the returned +DER ECDSA signature against the saved public key before writing it. Running it +again starts a new authentication request. The client never automatically retries +an operation whose completion is unknown. + +Applications which already hash their input can use `sign-digest` instead of +`sign`. Its input file must contain exactly 32 raw digest bytes; it does not hash +them again. Python callers can directly use `SepClient.sign_digest(blob, digest)`. + +The JSON file is an example application container, not a kernel wire format. +Persist the blob and public point atomically in an application's existing store. +Protect their integrity and associate them with the intended application key ID. +For WebAuthn, hash `authenticatorData || clientDataHash` once. Existing synced +passkeys cannot be replaced with newly generated SEP keys without registering +the new public key with the relying party. + +## Interface + +Open `/dev/sep-bio` read/write. `SEP_BIO_GET_INFO` advertises +`SEP_BIO_INFO_BIOMETRIC_KEYS` in `reserved[0]`. Unsupported key-store protocol +profiles fail closed. The interface is additive to biometric ABI version 4. + +* `SEP_BIO_KEY_CREATE`: flags/reserved zero for signing; use + `SEP_BIO_KEY_CREATE_DECRYPT` for biometric signing/decryption keys when + `SEP_BIO_INFO_BIOMETRIC_DECRYPT` is advertised. Supply a 4096-byte output buffer + through `blob_ptr`, with `blob_len = SEP_BIO_KEY_BLOB_MAX`. Returns actual blob + length and the 65-byte uncompressed public point. Creation does not scan a + finger; private-key use carries the biometric policy. +* `SEP_BIO_KEY_SIGN_START`: supply the saved blob, a 32-byte prehashed digest, + flags/reserved zero and a timeout from 1 to 120000 milliseconds. The driver + copies the inputs before returning. It creates a fresh authentication context, + matches into that context and signs the submitted digest after a match. +* `SEP_BIO_KEY_SIGN_POLL`: returns pending/done/failed, existing capture guidance, + a negative errno on failure, or a DER ECDSA signature. `poll(2)` wakes on guidance + or completion. Repeated polls report the same operation; they do not sign again. +* `SEP_BIO_CANCEL`: requests cancellation. Closing the descriptor also cancels + delivery. The worker retains ownership until its hardware operations and + credential cleanup finish; another start/open may temporarily return `EBUSY`. + +A request's credential never crosses the application interface. It is deleted +before successful completion is published. Disposal failure disables application +key operations until reboot. A canceled or expired request cannot deliver a +successful signature. Cancellation cannot undo a signing command already sent +into hardware; callers must not automatically retry an ambiguous failure. + +The existing firmware pipeline can finish capture before the requested maximum +timeout. `ETIMEDOUT` requires a fresh explicit request. `EACCES` reports a +nonmatching finger or authorization refusal, `ECANCELED` cancellation, `EROFS` +disabled persistent storage, `EOPNOTSUPP` an unsupported/disabled key API, and +`EIO` a transport, protocol or cleanup failure. + +## Trust and scope + +The device remains root-only. A privileged application or trusted broker owns the +request; this API does not authenticate browser origins, enforce relying-party +ownership or isolate multiple Linux users sharing one SEP identity. Do not grant +unrestricted device access to applications. fprintd and a key broker must +coordinate the existing exclusive device ownership. + +The policy accepts enrolled fingerprints in the configured credential set. It +does not implement invalidation whenever enrollment changes. Ordinary fingerprint +match tokens are not SEP key credentials. Existing machine-key attestation and +trusted-key sealing are separate operations and do not confer biometric key use. + +This interface covers new P-256 keys and biometric signing. It also supports +[biometric item decryption](DECRYPTION.md), with a reference envelope +implementation in `sep_envelope.py`. It does not implement private-key +import, P-384, protected-root migration or passkey registration. diff --git a/tools/apple-sep/sep-key.py b/tools/apple-sep/sep-key.py new file mode 100644 index 0000000000000..b961cb21b22aa --- /dev/null +++ b/tools/apple-sep/sep-key.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Example client for application-owned SEP biometric P-256 keys.""" + +import argparse +import base64 +import ctypes +import errno +import fcntl +import hashlib +import json +import os +from pathlib import Path +import select +import struct +import subprocess +import tempfile +import time + +MAX_BLOB = 4096 +BIOMETRIC_KEYS = 2 +BIOMETRIC_DECRYPT = 4 + + +def ioctl_number(direction, number, size=0): + return (direction << 30) | (size << 16) | (0xB1 << 8) | number + + +GET_INFO = ioctl_number(2, 1, 32) +CANCEL = ioctl_number(0, 7) +CREATE = ioctl_number(3, 11, 88) +SIGN_START = ioctl_number(1, 12, 56) +SIGN_POLL = ioctl_number(2, 13, 88) +DECRYPT_START = ioctl_number(1, 14, 32) +DECRYPT_POLL = ioctl_number(3, 15, 24) + + +class SepClient: + def __enter__(self): + self.fd = os.open('/dev/sep-bio', os.O_RDWR | os.O_CLOEXEC) + try: + info = bytearray(32) + fcntl.ioctl(self.fd, GET_INFO, info, True) + self.capabilities = struct.unpack('=8I', info)[5] + if not self.capabilities & BIOMETRIC_KEYS: + raise RuntimeError('driver does not advertise biometric keys') + except BaseException: + os.close(self.fd) + raise + return self + + def __exit__(self, *unused): + os.close(self.fd) + + def create(self, decrypt=False): + if decrypt and not self.capabilities & BIOMETRIC_DECRYPT: + raise OSError(errno.EOPNOTSUPP, 'driver does not advertise biometric decryption') + blob = ctypes.create_string_buffer(MAX_BLOB) + request = bytearray(struct.pack('=IIQ65s7x', int(decrypt), MAX_BLOB, + ctypes.addressof(blob), b'')) + fcntl.ioctl(self.fd, CREATE, request, True) + _, size, _, public = struct.unpack('=IIQ65s7x', request) + if not 0 < size <= MAX_BLOB or public[0] != 4: + raise RuntimeError('invalid key response') + return bytes(blob[:size]), public + + def decrypt_into(self, blob, sealed, output, timeout_ms=60000): + """Return length in caller-owned bytearray; wipe it on any failure. + + The caller must wipe successful output after use. No implicit fallback, + raw firmware context, automatic retry, or plaintext file is involved. + """ + if not isinstance(output, bytearray) or len(output) != MAX_BLOB: + raise ValueError('output must be a 4096-byte bytearray') + destination = (ctypes.c_ubyte * MAX_BLOB).from_buffer(output) + ctypes.memset(ctypes.addressof(destination), 0, MAX_BLOB) + if not self.capabilities & BIOMETRIC_DECRYPT: + raise OSError(errno.EOPNOTSUPP, 'driver does not advertise biometric decryption') + if not 0 < len(blob) <= MAX_BLOB or not 81 <= len(sealed) <= MAX_BLOB: + raise ValueError('invalid wrapped key or sealed length') + if sealed[0] != 4 or not 1 <= timeout_ms <= 120000: + raise ValueError('expected uncompressed P-256 point and valid timeout') + key = ctypes.create_string_buffer(blob) + ciphertext = ctypes.create_string_buffer(sealed) + request = struct.pack('=IIIIQQ', 0, timeout_ms, len(blob), len(sealed), + ctypes.addressof(key), ctypes.addressof(ciphertext)) + deadline = time.monotonic() + timeout_ms / 1000 + finished = False + success = False + started = False + try: + fcntl.ioctl(self.fd, DECRYPT_START, request) + started = True + poller = select.poll() + poller.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP) + while time.monotonic() < deadline: + response = bytearray(struct.pack('=IiIIQ', 0, 0, 0, MAX_BLOB, + ctypes.addressof(destination))) + fcntl.ioctl(self.fd, DECRYPT_POLL, response, True) + state, status, guidance, size, unused = struct.unpack('=IiIIQ', response) + if state == 4: + finished = True + raise OSError(-status, os.strerror(-status)) + if state == 3: + finished = True + if not 0 <= size <= MAX_BLOB: + raise RuntimeError('invalid plaintext length') + success = True + return size + events = poller.poll(min(500, max(1, int((deadline - time.monotonic()) * 1000)))) + if any(mask & (select.POLLERR | select.POLLHUP) for _, mask in events): + raise RuntimeError('SEP disconnected; completion is unknown') + raise TimeoutError('decryption expired') + finally: + if not success: + ctypes.memset(ctypes.addressof(destination), 0, MAX_BLOB) + if started and not finished: + try: + fcntl.ioctl(self.fd, CANCEL) + except OSError: + pass + + def sign_digest(self, blob, digest, timeout_ms=60000): + if not 0 < len(blob) <= MAX_BLOB or len(digest) != 32: + raise ValueError('expected wrapped key and SHA-256 digest') + if not 1 <= timeout_ms <= 120000: + raise ValueError('timeout must be 1..120000 ms') + storage = ctypes.create_string_buffer(blob) + request = struct.pack('=IIIIQ32s', 0, timeout_ms, len(blob), 0, + ctypes.addressof(storage), digest) + fcntl.ioctl(self.fd, SIGN_START, request) + deadline = time.monotonic() + timeout_ms / 1000 + poller = select.poll() + poller.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP) + finished = False + try: + while time.monotonic() < deadline: + response = bytearray(88) + fcntl.ioctl(self.fd, SIGN_POLL, response, True) + state, status, guidance, size, signature = struct.unpack('=IiII72s', response) + if state == 4: + finished = True + raise OSError(-status, os.strerror(-status)) + if state == 3: + finished = True + if not 0 < size <= 72: + raise RuntimeError('invalid signature length') + return signature[:size] + events = poller.poll(min(500, max(1, int((deadline - time.monotonic()) * 1000)))) + if any(mask & (select.POLLERR | select.POLLHUP) for _, mask in events): + raise RuntimeError('SEP disconnected; completion is unknown') + raise TimeoutError('signing expired') + finally: + if not finished: + try: + fcntl.ioctl(self.fd, CANCEL) + except OSError: + pass + # Do not automatically retry a request with uncertain completion. + + +def verify(public, digest, signature): + # SubjectPublicKeyInfo for id-ecPublicKey / prime256v1, uncompressed point. + prefix = bytes.fromhex('3059301306072a8648ce3d020106082a8648ce3d030107034200') + with tempfile.TemporaryDirectory(prefix='sep-signature-') as directory: + directory = Path(directory) + for name, data in [('public.der', prefix + public), ('digest', digest), + ('signature', signature)]: + (directory / name).write_bytes(data) + subprocess.run(['openssl', 'pkeyutl', '-verify', '-pubin', '-keyform', 'DER', + '-inkey', str(directory / 'public.der'), + '-in', str(directory / 'digest'), + '-sigfile', str(directory / 'signature'), + '-pkeyopt', 'digest:sha256'], check=True, capture_output=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + create = commands.add_parser('create') + create.add_argument('key', type=Path) + create.add_argument('--decrypt', action='store_true', + help='create a biometric signing/decryption key') + for name in ('sign', 'sign-digest'): + sign = commands.add_parser(name) + sign.add_argument('key', type=Path) + sign.add_argument('message', type=Path) + sign.add_argument('signature', type=Path) + args = parser.parse_args() + if args.command == 'create': + if args.key.exists(): + raise FileExistsError(args.key) + with SepClient() as client: + blob, public = client.create(decrypt=args.decrypt) + data = {'version': 1, 'policy': 'biometry-any', + 'blob': base64.b64encode(blob).decode(), + 'public': base64.b64encode(public).decode()} + if args.decrypt: + data['operations'] = ['sign', 'decrypt'] + fd = os.open(args.key, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o600) + with os.fdopen(fd, 'w') as output: + json.dump(data, output) + output.flush() + os.fsync(output.fileno()) + print('Biometric P-256 key created') + else: + if args.key.stat().st_size > 8192: + raise ValueError('key file too large') + data = json.loads(args.key.read_text()) + if data['version'] != 1 or data['policy'] != 'biometry-any': + raise ValueError('unsupported key file') + blob = base64.b64decode(data['blob'], validate=True) + public = base64.b64decode(data['public'], validate=True) + with args.message.open('rb') as message: + if args.command == 'sign': + digest = hashlib.file_digest(message, 'sha256').digest() + else: + digest = message.read(33) + if len(digest) != 32: + raise ValueError('sign-digest requires exactly 32 raw SHA-256 bytes') + print('Place an enrolled finger on Touch ID', flush=True) + with SepClient() as client: + signature = client.sign_digest(blob, digest) + verify(public, digest, signature) + args.signature.write_bytes(signature) + print('Biometric signature verified') + + +if __name__ == '__main__': + main() diff --git a/tools/apple-sep/sep_envelope.py b/tools/apple-sep/sep_envelope.py new file mode 100644 index 0000000000000..73d1b2a5157fb --- /dev/null +++ b/tools/apple-sep/sep_envelope.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Reference item envelope for the local biometric ECIES decrypt extension. + +Requires Python cryptography. This is an integration example, not a production +secret-memory implementation: Python/backend temporaries cannot all be wiped. +""" + +import hashlib +import hmac + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + +MAX_SEALED = 4096 +MAGIC = b'SEPITEM\x01' + + +def seal_item(public, context, plaintext): + """Encrypt to a recipient public point; no biometric scan is needed. + + context is the application's canonical binding of owner, record ID, purpose + and algorithm. It is encrypted/authenticated with the item, not sent as AAD. + """ + if len(public) != 65 or public[0] != 4: + raise ValueError('expected uncompressed P-256 public point') + if not context or len(context) > 1024: + raise ValueError('expected nonempty bounded item context') + envelope = MAGIC + len(context).to_bytes(4, 'big') + context + plaintext + if len(envelope) + 81 > MAX_SEALED: + raise ValueError('item envelope exceeds driver input limit') + peer = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), public) + sender = ec.generate_private_key(ec.SECP256R1()) + ephemeral = sender.public_key().public_bytes( + serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) + shared = sender.exchange(ec.ECDH(), peer) + material = b''.join(hashlib.sha256(shared + counter.to_bytes(4, 'big') + ephemeral).digest() + for counter in (1, 2)) + # Firmware profile: AES-256, derived 16-byte IV, no AAD, 16-byte tag. + return ephemeral + AESGCM(material[:32]).encrypt(material[32:48], envelope, None) + + +def item_view(output, length, expected_context): + """Validate trusted expected context, then borrow plaintext without copying. + + The caller owns output and must wipe it on success AND on exceptions. Do not + derive expected_context from an untrusted field beside the ciphertext. + """ + if not isinstance(output, bytearray) or not 0 <= length <= len(output): + raise ValueError('invalid plaintext buffer') + if not expected_context or len(expected_context) > 1024: + raise ValueError('invalid expected context') + view = memoryview(output)[:length] + header = len(MAGIC) + 4 + if length < header or view[:len(MAGIC)] != MAGIC: + raise ValueError('unsupported item envelope') + context_len = int.from_bytes(view[len(MAGIC):header], 'big') + if context_len != len(expected_context) or header + context_len > length: + raise ValueError('item context mismatch') + if not hmac.compare_digest(view[header:header + context_len], expected_context): + raise ValueError('item context mismatch') + return view[header + context_len:]