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    /// Set pki_env to a new shared pki environment provider
141    pub async fn set_pki_environment(&mut self, pki_env: Option<Arc<PkiEnvironment>>) {
142        *self.auth_service.pki_env.write().await = pki_env;
143    }
144
145    /// Returns whether we have a PKI env setup
146    pub async fn is_pki_env_setup(&self) -> bool {
147        self.auth_service.pki_env.read().await.is_some()
148    }
149
150    /// Reseeds the internal CSPRNG entropy pool with a brand new one.
151    ///
152    /// If [None] is provided, the new entropy will be pulled through the current OS target's capabilities
153    pub fn reseed(&self, entropy_seed: Option<EntropySeed>) -> MlsProviderResult<()> {
154        self.crypto.reseed(entropy_seed)
155    }
156}
157
158impl openmls_traits::OpenMlsCryptoProvider for CryptoProvider {
159    type CryptoProvider = RustCrypto;
160    type RandProvider = RustCrypto;
161    type KeyStoreProvider = Database;
162    type AuthenticationServiceProvider = AuthenticationService;
163
164    fn crypto(&self) -> &Self::CryptoProvider {
165        &self.crypto
166    }
167
168    fn rand(&self) -> &Self::RandProvider {
169        &self.crypto
170    }
171
172    fn key_store(&self) -> &Self::KeyStoreProvider {
173        &self.key_store
174    }
175
176    fn authentication_service(&self) -> &Self::AuthenticationServiceProvider {
177        &self.auth_service
178    }
179}
180
181/// Passthrough implementation of crypto functionality for references to `MlsCryptoProvider`.
182impl OpenMlsCrypto for &CryptoProvider {
183    fn supports(&self, ciphersuite: Ciphersuite) -> Result<(), CryptoError> {
184        self.crypto.supports(ciphersuite)
185    }
186
187    fn supported_ciphersuites(&self) -> Vec<Ciphersuite> {
188        self.crypto.supported_ciphersuites()
189    }
190
191    fn hkdf_extract(
192        &self,
193        hash_type: HashType,
194        salt: &[u8],
195        ikm: &[u8],
196    ) -> Result<tls_codec::SecretVLBytes, CryptoError> {
197        self.crypto.hkdf_extract(hash_type, salt, ikm)
198    }
199
200    fn hkdf_expand(
201        &self,
202        hash_type: HashType,
203        prk: &[u8],
204        info: &[u8],
205        okm_len: usize,
206    ) -> Result<tls_codec::SecretVLBytes, CryptoError> {
207        self.crypto.hkdf_expand(hash_type, prk, info, okm_len)
208    }
209
210    fn hash(&self, hash_type: HashType, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
211        self.crypto.hash(hash_type, data)
212    }
213
214    fn aead_encrypt(
215        &self,
216        alg: AeadType,
217        key: &[u8],
218        data: &[u8],
219        nonce: &[u8],
220        aad: &[u8],
221    ) -> Result<Vec<u8>, CryptoError> {
222        self.crypto.aead_encrypt(alg, key, data, nonce, aad)
223    }
224
225    fn aead_decrypt(
226        &self,
227        alg: AeadType,
228        key: &[u8],
229        ct_tag: &[u8],
230        nonce: &[u8],
231        aad: &[u8],
232    ) -> Result<Vec<u8>, CryptoError> {
233        self.crypto.aead_decrypt(alg, key, ct_tag, nonce, aad)
234    }
235
236    fn signature_key_gen(&self, alg: SignatureScheme) -> Result<(Vec<u8>, Vec<u8>), CryptoError> {
237        self.crypto.signature_key_gen(alg)
238    }
239
240    fn signature_public_key_len(&self, alg: SignatureScheme) -> usize {
241        self.crypto.signature_public_key_len(alg)
242    }
243
244    fn validate_signature_key(&self, alg: SignatureScheme, key: &[u8]) -> Result<(), CryptoError> {
245        self.crypto.validate_signature_key(alg, key)
246    }
247
248    fn verify_signature(
249        &self,
250        alg: SignatureScheme,
251        data: &[u8],
252        pk: &[u8],
253        signature: &[u8],
254    ) -> Result<(), CryptoError> {
255        self.crypto.verify_signature(alg, data, pk, signature)
256    }
257
258    fn sign(&self, alg: SignatureScheme, data: &[u8], key: &[u8]) -> Result<Vec<u8>, CryptoError> {
259        self.crypto.sign(alg, data, key)
260    }
261
262    fn hpke_seal(
263        &self,
264        config: HpkeConfig,
265        pk_r: &[u8],
266        info: &[u8],
267        aad: &[u8],
268        ptxt: &[u8],
269    ) -> Result<HpkeCiphertext, CryptoError> {
270        self.crypto.hpke_seal(config, pk_r, info, aad, ptxt)
271    }
272
273    fn hpke_open(
274        &self,
275        config: HpkeConfig,
276        input: &HpkeCiphertext,
277        sk_r: &[u8],
278        info: &[u8],
279        aad: &[u8],
280    ) -> Result<Vec<u8>, CryptoError> {
281        self.crypto.hpke_open(config, input, sk_r, info, aad)
282    }
283
284    fn hpke_setup_sender_and_export(
285        &self,
286        config: HpkeConfig,
287        pk_r: &[u8],
288        info: &[u8],
289        exporter_context: &[u8],
290        exporter_length: usize,
291    ) -> Result<(KemOutput, ExporterSecret), CryptoError> {
292        self.crypto
293            .hpke_setup_sender_and_export(config, pk_r, info, exporter_context, exporter_length)
294    }
295
296    fn hpke_setup_receiver_and_export(
297        &self,
298        config: HpkeConfig,
299        enc: &[u8],
300        sk_r: &[u8],
301        info: &[u8],
302        exporter_context: &[u8],
303        exporter_length: usize,
304    ) -> Result<ExporterSecret, CryptoError> {
305        self.crypto
306            .hpke_setup_receiver_and_export(config, enc, sk_r, info, exporter_context, exporter_length)
307    }
308
309    fn derive_hpke_keypair(&self, config: HpkeConfig, ikm: &[u8]) -> Result<HpkeKeyPair, CryptoError> {
310        self.crypto.derive_hpke_keypair(config, ikm)
311    }
312}