Skip to main content

capsule_core/crypto/keys/
hardware.rs

1//! Hardware-bound device signing (SSoT: [Cryptography — Keys § Device Keys]).
2//!
3//! The design binds the device signing key (DSK) to a per-platform secure element — Secure
4//! Enclave (iOS), StrongBox (Android), TPM (desktop) — so the private key never leaves
5//! hardware. No shipping secure element holds ML-DSA-65 keys, so only the **classical** Ed25519
6//! half lives in hardware; the post-quantum ML-DSA-65 half stays software-sealed under the
7//! master key. A hybrid signature is therefore composed from a hardware-produced Ed25519
8//! signature and a software-produced ML-DSA-65 signature.
9//!
10//! [`HardwareSigner`] is the seam native code implements — a plain Rust trait here, reached from
11//! Swift/Kotlin through the `capsule_sdk` namespace's `FfiHardwareSigner` foreign trait, which
12//! adapts to it one call per method. [`HardwareBackedSigner`]
13//! adapts it to [`Signer`]. The per-platform round-trip + non-exportability harness is owned by
14//! the design (`keys.md` Validation); the in-process contract is exercised here against a mock.
15//!
16//! [Cryptography — Keys § Device Keys]: https://docs/design/cryptography/keys/#device-keys
17
18use std::sync::Arc;
19
20use ml_dsa::{B32, Keypair as _, MlDsa65, Signer as _, SigningKey as MlSigningKey};
21
22use super::hybrid_sig::{HybridSignature, HybridVerifyingKey};
23use super::signer::Signer;
24use crate::crypto::CryptoError;
25
26/// The per-platform hardware secure element, implemented by native code (Swift/Kotlin) behind the
27/// `capsule_sdk` namespace's `FfiHardwareSigner` foreign trait. Rust calls *into* it to enroll a
28/// non-exportable Ed25519 key and to sign with it; the ML-DSA-65 half is handled in Rust.
29pub trait HardwareSigner: Send + Sync {
30    /// Generate (or bind to) the hardware Ed25519 keypair for `key_alias`, returning its
31    /// 32-byte public key. Idempotent per alias.
32    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError>;
33
34    /// The 32-byte Ed25519 public key for an already-enrolled `key_alias`.
35    fn classical_public_key(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError>;
36
37    /// Produce a 64-byte Ed25519 signature over `msg` with the hardware key for `key_alias`.
38    fn sign_classical(
39        &self,
40        key_alias: String,
41        msg: Vec<u8>,
42    ) -> Result<Vec<u8>, HardwareSignerError>;
43
44    /// Non-exportability assertion: a conforming element MUST refuse to reveal the private
45    /// bytes, returning [`HardwareSignerError::Exportable`] if they can be read. This drives the
46    /// per-platform smoke test (`keys.md` Validation).
47    fn assert_non_exportable(&self, key_alias: String) -> Result<(), HardwareSignerError>;
48}
49
50/// The per-platform hardware **key-agreement** element — the ECDH analogue of
51/// [`HardwareSigner`], implemented by native code (Swift/Kotlin) behind the `capsule_sdk`
52/// namespace's `FfiHardwareKeyAgreement` foreign trait. It backs the hardware-bound classical half of the device **encryption** key (DEK):
53/// shipping secure elements expose **ECDH-P256** (Secure Enclave `P256.KeyAgreement`, StrongBox
54/// ECDH, TPM 2.0 ECDH), so the DEK's X25519 half of [the X-Wing KEM](super::DekKeypair) is replaced by a
55/// hardware-held P-256 static key while the ML-KEM-768 half stays software-sealed. The element
56/// holds the P-256 private key and performs the ECDH so it never leaves hardware; Rust drives the
57/// ML-KEM half and the hybrid combiner (SSoT: [Cryptography — Keys § Device Keys]).
58///
59/// [Cryptography — Keys § Device Keys]: https://docs/design/cryptography/keys/#device-keys
60pub trait HardwareKeyAgreement: Send + Sync {
61    /// Generate (or bind to) the hardware P-256 key-agreement keypair for `key_alias`, returning
62    /// its public key as **uncompressed SEC1 / x9.63** (`0x04‖x‖y`, 65 bytes — the form Secure
63    /// Enclave and StrongBox emit). Idempotent per alias.
64    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError>;
65
66    /// The uncompressed-SEC1 P-256 public key for an already-enrolled `key_alias`.
67    fn public_key(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError>;
68
69    /// Perform ECDH against `peer_public` (the sender's ephemeral P-256 public key, uncompressed
70    /// SEC1) with the hardware key for `key_alias`, returning the **raw 32-byte shared secret**
71    /// (the big-endian x-coordinate of the ECDH point — CryptoKit's `SharedSecret` /
72    /// `SecKeyCopyKeyExchangeResult`, before any KDF). The Rust side folds it into the hybrid
73    /// combiner; no KDF is applied inside the element.
74    fn key_agreement(
75        &self,
76        key_alias: String,
77        peer_public: Vec<u8>,
78    ) -> Result<Vec<u8>, HardwareSignerError>;
79
80    /// Non-exportability assertion (mirrors [`HardwareSigner::assert_non_exportable`]): a
81    /// conforming element MUST refuse to reveal the private bytes, returning
82    /// [`HardwareSignerError::Exportable`] if they can be read.
83    fn assert_non_exportable(&self, key_alias: String) -> Result<(), HardwareSignerError>;
84}
85
86/// Failure surfaced by a [`HardwareSigner`] or [`HardwareKeyAgreement`] backend.
87#[derive(Debug, thiserror::Error)]
88pub enum HardwareSignerError {
89    /// The user cancelled the biometric / the element refused authentication.
90    #[error("hardware authentication cancelled")]
91    AuthCancelled,
92    /// No secure element is available on this device.
93    #[error("hardware secure element unavailable")]
94    Unavailable,
95    /// No key exists for the requested alias.
96    #[error("hardware key not found")]
97    NotFound,
98    /// The private key was readable — non-exportability is violated (a failure).
99    #[error("hardware private key is exportable")]
100    Exportable,
101    /// Any other backend error.
102    #[error("hardware backend error: {0}")]
103    Backend(String),
104}
105
106/// Adapts a [`HardwareSigner`] to [`Signer`]: the Ed25519 half is produced in hardware, the
107/// ML-DSA-65 half in software from the sealed `ξ` seed, and the two are combined into a
108/// [`HybridSignature`].
109pub struct HardwareBackedSigner {
110    hardware: Arc<dyn HardwareSigner>,
111    key_alias: String,
112    ml: MlSigningKey<MlDsa65>,
113    verifying_key: HybridVerifyingKey,
114}
115
116impl HardwareBackedSigner {
117    /// Enroll the device key: ensure the hardware Ed25519 key exists (returning its public
118    /// half) and build the published hybrid verifying key from it plus the software ML-DSA-65
119    /// public key derived from `ml_seed` (the `ξ` half of the sealed DSK seed).
120    pub fn enroll(
121        hardware: Arc<dyn HardwareSigner>,
122        key_alias: String,
123        ml_seed: &[u8; 32],
124    ) -> Result<Self, CryptoError> {
125        let ed_public = hardware
126            .enroll(key_alias.clone())
127            .map_err(|_| CryptoError::Key("hardware key enrollment failed"))?;
128        if ed_public.len() != 32 {
129            return Err(CryptoError::Malformed(
130                "hardware Ed25519 public key must be 32 bytes",
131            ));
132        }
133        let seed =
134            B32::try_from(&ml_seed[..]).map_err(|_| CryptoError::Malformed("bad ML-DSA seed"))?;
135        let ml = MlSigningKey::<MlDsa65>::from_seed(&seed);
136
137        let mut vk_bytes = ed_public;
138        vk_bytes.extend_from_slice(ml.verifying_key().encode().as_slice());
139        let verifying_key = HybridVerifyingKey::from_bytes(&vk_bytes)?;
140
141        Ok(Self {
142            hardware,
143            key_alias,
144            ml,
145            verifying_key,
146        })
147    }
148}
149
150impl Signer for HardwareBackedSigner {
151    fn sign(&self, msg: &[u8]) -> Result<HybridSignature, CryptoError> {
152        let ed = self
153            .hardware
154            .sign_classical(self.key_alias.clone(), msg.to_vec())
155            .map_err(|_| CryptoError::Auth("hardware classical signature failed"))?;
156        let ed: [u8; 64] = ed
157            .as_slice()
158            .try_into()
159            .map_err(|_| CryptoError::Malformed("hardware Ed25519 signature must be 64 bytes"))?;
160        let ml = self.ml.sign(msg).encode().to_vec();
161        Ok(HybridSignature::from_halves(ed, ml))
162    }
163
164    fn verifying_key(&self) -> HybridVerifyingKey {
165        self.verifying_key.clone()
166    }
167}
168
169/// An in-memory stand-in for a secure element. Test-only; a real element keeps the Ed25519 key
170/// in hardware. Shared with the lifecycle tests, so it lives outside the `tests` module and is
171/// exported under `test-support` for `capsule-library`'s.
172#[cfg(any(test, feature = "test-support"))]
173pub struct MockHardwareSigner {
174    ed: ed25519_dalek::SigningKey,
175    exportable: bool,
176}
177
178#[cfg(any(test, feature = "test-support"))]
179impl MockHardwareSigner {
180    /// A mock element over `scalar`/`seed`; `exportable` makes it fail the non-exportability assertion.
181    pub fn new(ed_seed: [u8; 32], exportable: bool) -> Self {
182        Self {
183            ed: ed25519_dalek::SigningKey::from_bytes(&ed_seed),
184            exportable,
185        }
186    }
187}
188
189#[cfg(any(test, feature = "test-support"))]
190impl HardwareSigner for MockHardwareSigner {
191    fn enroll(&self, alias: String) -> Result<Vec<u8>, HardwareSignerError> {
192        self.classical_public_key(alias)
193    }
194    fn classical_public_key(&self, _alias: String) -> Result<Vec<u8>, HardwareSignerError> {
195        Ok(self.ed.verifying_key().to_bytes().to_vec())
196    }
197    fn sign_classical(&self, _alias: String, msg: Vec<u8>) -> Result<Vec<u8>, HardwareSignerError> {
198        use ed25519_dalek::Signer as _;
199        Ok(self.ed.sign(&msg).to_bytes().to_vec())
200    }
201    fn assert_non_exportable(&self, _alias: String) -> Result<(), HardwareSignerError> {
202        if self.exportable {
203            Err(HardwareSignerError::Exportable)
204        } else {
205            Ok(())
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests;