Skip to main content

core_crypto/mls_provider/
mod.rs

1// TODO: remove this expect(unreachable_pub) once the E2EI parts have been coupled.
2#![expect(unreachable_pub)]
3use std::sync::Arc;
4
5use async_lock::RwLock;
6pub use core_crypto_keystore::Database;
7
8mod crypto_provider;
9mod error;
10
11pub(crate) use crypto_provider::CRYPTO;
12pub use crypto_provider::RustCrypto;
13pub use error::{Error, MlsProviderResult};
14use openmls_traits::{
15    authentication_service::{CredentialAuthenticationStatus, CredentialRef},
16    crypto::OpenMlsCrypto,
17    types::{
18        AeadType, Ciphersuite, CryptoError, ExporterSecret, HashType, HpkeCiphertext, HpkeConfig, HpkeKeyPair,
19        KemOutput, SignatureScheme,
20    },
21};
22// TODO: remove this allow(unused) once the E2EI parts have been coupled.
23#[allow(unused)]
24pub use wire_e2e_identity::pki::{CertProfile, CertificateGenerationArgs, PkiKeypair};
25use wire_e2e_identity::pki_env::PkiEnvironment;
26
27/// 32-byte raw entropy seed
28pub type RawEntropySeed = <rand_chacha::ChaCha20Rng as rand::SeedableRng>::Seed;
29
30#[derive(Debug, Clone, Default, PartialEq, Eq, zeroize::ZeroizeOnDrop)]
31#[repr(transparent)]
32/// Wrapped 32-byte entropy seed with bounds check
33pub struct EntropySeed(RawEntropySeed);
34
35impl EntropySeed {
36    /// The expected length of the entopy seed, in bytes.
37    pub const EXPECTED_LEN: usize = std::mem::size_of::<EntropySeed>() / std::mem::size_of::<u8>();
38
39    /// Create an entropy seed from the provided slice.
40    pub fn try_from_slice(data: &[u8]) -> MlsProviderResult<Self> {
41        if data.len() < Self::EXPECTED_LEN {
42            return Err(Error::EntropySeedLength {
43                actual: data.len(),
44                expected: Self::EXPECTED_LEN,
45            });
46        }
47
48        let mut inner = RawEntropySeed::default();
49        inner.copy_from_slice(&data[..Self::EXPECTED_LEN]);
50
51        Ok(Self(inner))
52    }
53
54    /// Create an entropy seed from the provided raw entropy seed.
55    pub fn from_raw(raw: RawEntropySeed) -> Self {
56        Self(raw)
57    }
58}
59
60impl std::ops::Deref for EntropySeed {
61    type Target = [u8];
62    fn deref(&self) -> &Self::Target {
63        &self.0
64    }
65}
66
67impl std::ops::DerefMut for EntropySeed {
68    fn deref_mut(&mut self) -> &mut Self::Target {
69        &mut self.0
70    }
71}
72
73#[derive(Debug)]
74pub struct AuthenticationService {
75    /// The PKI Environment type is complicated, but it's all necessary:
76    ///
77    /// - The inner `Arc` derives from two facts: the PKI environment is provided across FFI, and it's `!Clone`, so we
78    ///   have to retain that `Arc` because the foreign environment is more-or-less guaranteed to have kept a reference
79    ///   to it.
80    /// - The `Option` is there because the PKI environment is initially unset and may never be set, according to
81    ///   client behavior.
82    /// - The `RwLock` is there because we need to be able to set the PKI environment, implying interior mutability.
83    pki_env: RwLock<Option<Arc<PkiEnvironment>>>,
84}
85
86impl AuthenticationService {
87    pub async fn pki_env(&self) -> Option<Arc<PkiEnvironment>> {
88        self.pki_env.read().await.clone()
89    }
90}
91
92#[cfg_attr(target_os = "unknown", async_trait::async_trait(?Send))]
93#[cfg_attr(not(target_os = "unknown"), async_trait::async_trait)]
94impl openmls_traits::authentication_service::AuthenticationServiceDelegate for AuthenticationService {
95    async fn validate_credential<'a>(&'a self, credential: CredentialRef<'a>) -> CredentialAuthenticationStatus {
96        match credential {
97            // We assume that Basic credentials are always valid
98            CredentialRef::Basic { .. } => CredentialAuthenticationStatus::Valid,
99
100            CredentialRef::X509 { .. } => match self.pki_env.read().await.as_ref() {
101                None => {
102                    log::warn!("unable to validate X509 credentials: PKI environment is unset");
103                    CredentialAuthenticationStatus::Unknown
104                }
105                Some(pki_env) => pki_env.validate_credential(credential).await,
106            },
107        }
108    }
109}
110
111/// The MLS crypto provider
112#[derive(Debug, Clone)]
113pub struct CryptoProvider {
114    crypto: Arc<RustCrypto>,
115    key_store: Arc<Database>,
116    auth_service: Arc<AuthenticationService>,
117}
118
119impl CryptoProvider {
120    /// Construct a crypto provider with defaults and a given [Database].
121    ///
122    /// See also:
123    ///
124    /// - [Database::open]
125    pub fn new(key_store: Arc<Database>) -> Self {
126        Self::new_with_pki_env(key_store, None)
127    }
128
129    /// Construct a crypto provider with the given database and the PKI environment.
130    pub fn new_with_pki_env(key_store: Arc<Database>, pki_env: Option<Arc<PkiEnvironment>>) -> Self {
131        let pki_env = RwLock::new(pki_env);
132        let auth_service = Arc::new(AuthenticationService { pki_env });
133        Self {
134            key_store,
135            crypto: Arc::clone(&CRYPTO),
136            auth_service,
137        }
138    }
139
140    /// Clones the references of the PkiEnvironment and the CryptoProvider into a transaction
141    /// keystore to pass to openmls as the `OpenMlsCryptoProvider`
142    pub async fn new_transaction(&self) -> MlsProviderResult<()> {
143        self.key_store.new_transaction().await.map_err(Into::into)
144    }
145
146    /// Set pki_env to a new shared pki environment provider
147    pub async fn set_pki_environment(&mut self, pki_env: Option<Arc<PkiEnvironment>>) {
148        *self.auth_service.pki_env.write().await = pki_env;
149    }
150
151    /// Returns whether we have a PKI env setup
152    pub async fn is_pki_env_setup(&self) -> bool {
153        self.auth_service.pki_env.read().await.is_some()
154    }
155
156    /// Reseeds the internal CSPRNG entropy pool with a brand new one.
157    ///
158    /// If [None] is provided, the new entropy will be pulled through the current OS target's capabilities
159    pub fn reseed(&self, entropy_seed: Option<EntropySeed>) -> MlsProviderResult<()> {
160        self.crypto.reseed(entropy_seed)
161    }
162}
163
164impl openmls_traits::OpenMlsCryptoProvider for CryptoProvider {
165    type CryptoProvider = RustCrypto;
166    type RandProvider = RustCrypto;
167    type KeyStoreProvider = Database;
168    type AuthenticationServiceProvider = AuthenticationService;
169
170    fn crypto(&self) -> &Self::CryptoProvider {
171        &self.crypto
172    }
173
174    fn rand(&self) -> &Self::RandProvider {
175        &self.crypto
176    }
177
178    fn key_store(&self) -> &Self::KeyStoreProvider {
179        &self.key_store
180    }
181
182    fn authentication_service(&self) -> &Self::AuthenticationServiceProvider {
183        &self.auth_service
184    }
185}
186
187/// Passthrough implementation of crypto functionality for references to `MlsCryptoProvider`.
188impl OpenMlsCrypto for &CryptoProvider {
189    fn supports(&self, ciphersuite: Ciphersuite) -> Result<(), CryptoError> {
190        self.crypto.supports(ciphersuite)
191    }
192
193    fn supported_ciphersuites(&self) -> Vec<Ciphersuite> {
194        self.crypto.supported_ciphersuites()
195    }
196
197    fn hkdf_extract(
198        &self,
199        hash_type: HashType,
200        salt: &[u8],
201        ikm: &[u8],
202    ) -> Result<tls_codec::SecretVLBytes, CryptoError> {
203        self.crypto.hkdf_extract(hash_type, salt, ikm)
204    }
205
206    fn hkdf_expand(
207        &self,
208        hash_type: HashType,
209        prk: &[u8],
210        info: &[u8],
211        okm_len: usize,
212    ) -> Result<tls_codec::SecretVLBytes, CryptoError> {
213        self.crypto.hkdf_expand(hash_type, prk, info, okm_len)
214    }
215
216    fn hash(&self, hash_type: HashType, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
217        self.crypto.hash(hash_type, data)
218    }
219
220    fn aead_encrypt(
221        &self,
222        alg: AeadType,
223        key: &[u8],
224        data: &[u8],
225        nonce: &[u8],
226        aad: &[u8],
227    ) -> Result<Vec<u8>, CryptoError> {
228        self.crypto.aead_encrypt(alg, key, data, nonce, aad)
229    }
230
231    fn aead_decrypt(
232        &self,
233        alg: AeadType,
234        key: &[u8],
235        ct_tag: &[u8],
236        nonce: &[u8],
237        aad: &[u8],
238    ) -> Result<Vec<u8>, CryptoError> {
239        self.crypto.aead_decrypt(alg, key, ct_tag, nonce, aad)
240    }
241
242    fn signature_key_gen(&self, alg: SignatureScheme) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
243        self.crypto.signature_key_gen(alg)
244    }
245
246    fn signature_public_key_len(&self, alg: SignatureScheme) -> usize {
247        self.crypto.signature_public_key_len(alg)
248    }
249
250    fn validate_signature_key(&self, alg: SignatureScheme, key: &[u8]) -> Result<(), CryptoError> {
251        self.crypto.validate_signature_key(alg, key)
252    }
253
254    fn verify_signature(
255        &self,
256        alg: SignatureScheme,
257        data: &[u8],
258        pk: &[u8],
259        signature: &[u8],
260    ) -> Result<(), CryptoError> {
261        self.crypto.verify_signature(alg, data, pk, signature)
262    }
263
264    fn sign(&self, alg: SignatureScheme, data: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {
265        self.crypto.sign(alg, data, key)
266    }
267
268    fn hpke_seal(
269        &self,
270        config: HpkeConfig,
271        pk_r: &[u8],
272        info: &[u8],
273        aad: &[u8],
274        ptxt: &[u8],
275    ) -> Result<HpkeCiphertext, CryptoError> {
276        self.crypto.hpke_seal(config, pk_r, info, aad, ptxt)
277    }
278
279    fn hpke_open(
280        &self,
281        config: HpkeConfig,
282        input: &HpkeCiphertext,
283        sk_r: &[u8],
284        info: &[u8],
285        aad: &[u8],
286    ) -> Result<Vec<u8>, CryptoError> {
287        self.crypto.hpke_open(config, input, sk_r, info, aad)
288    }
289
290    fn hpke_setup_sender_and_export(
291        &self,
292        config: HpkeConfig,
293        pk_r: &[u8],
294        info: &[u8],
295        exporter_context: &[u8],
296        exporter_length: usize,
297    ) -> Result<(KemOutput, ExporterSecret), CryptoError> {
298        self.crypto
299            .hpke_setup_sender_and_export(config, pk_r, info, exporter_context, exporter_length)
300    }
301
302    fn hpke_setup_receiver_and_export(
303        &self,
304        config: HpkeConfig,
305        enc: &[u8],
306        sk_r: &[u8],
307        info: &[u8],
308        exporter_context: &[u8],
309        exporter_length: usize,
310    ) -> Result<ExporterSecret, CryptoError> {
311        self.crypto
312            .hpke_setup_receiver_and_export(config, enc, sk_r, info, exporter_context, exporter_length)
313    }
314
315    fn derive_hpke_keypair(&self, config: HpkeConfig, ikm: &[u8]) -> Result<HpkeKeyPair, CryptoError> {
316        self.crypto.derive_hpke_keypair(config, ikm)
317    }
318}