Skip to main content

core_crypto/mls/credential/
mod.rs

1//! This module focuses on [`Credential`]s: cryptographic assertions of identity.
2//!
3//! Credentials can be basic, or based on an x509 certificate chain.
4
5pub(crate) mod credential_ref;
6pub(crate) mod credential_type;
7pub(crate) mod crl;
8mod error;
9mod export_pem;
10pub(crate) mod ext;
11mod persistence;
12pub(crate) mod x509;
13
14use std::sync::Arc;
15
16use core_crypto_keystore::entities::StoredCredential;
17use openmls::prelude::{Credential as MlsCredential, CredentialWithKey, SignatureScheme};
18use openmls_basic_credential::SignatureKeyPair;
19use openmls_traits::crypto::OpenMlsCrypto;
20use tls_codec::Deserialize as _;
21
22pub(crate) use self::error::Result;
23pub use self::{
24    credential_ref::{CredentialRef, FindFilters, FindFiltersBuilder},
25    credential_type::CredentialType,
26    error::Error,
27};
28use crate::{CipherSuite, ClientId, ClientIdRef, OpenMlsError, RecursiveError, TlsCodecError, mls_provider::CRYPTO};
29
30/// A cryptographic credential.
31///
32/// This is tied to a particular client via either its client id or certificate bundle,
33/// depending on its credential type, but is independent of any client instance or storage.
34///
35/// To attach to a particular client instance and store, see
36/// [`TransactionContext::add_credential`][crate::transaction_context::TransactionContext::add_credential].
37#[derive(core_crypto_macros::Debug, Clone, serde::Serialize, serde::Deserialize)]
38pub struct Credential {
39    /// Ciphersuite used by this credential
40    pub(crate) cipher_suite: CipherSuite,
41    /// Credential type
42    pub(crate) credential_type: CredentialType,
43    /// MLS internal credential. Stores the MLS credential
44    pub(crate) mls_credential: MlsCredential,
45    /// Public and private keys, and the signature scheme.
46    #[sensitive]
47    pub(crate) signature_key_pair: SignatureKeyPair,
48    /// Earliest valid time of creation for this credential.
49    ///
50    /// This is represented as seconds after the unix epoch.
51    ///
52    /// Only meaningful for X509, where it is the "valid_from" claim of the leaf credential.
53    /// For basic credentials, this is always 0.
54    pub(crate) earliest_validity: u64,
55}
56
57impl TryFrom<Arc<StoredCredential>> for Credential {
58    type Error = Error;
59
60    fn try_from(stored_credential: Arc<StoredCredential>) -> Result<Credential> {
61        let mls_credential = MlsCredential::tls_deserialize(&mut stored_credential.credential.as_slice())
62            .map_err(TlsCodecError::deserialize("mls credential"))?;
63        let cipher_suite = CipherSuite::try_from(stored_credential.ciphersuite)?;
64        let signature_key_pair = openmls_basic_credential::SignatureKeyPair::from_raw(
65            cipher_suite.signature_algorithm(),
66            stored_credential.private_key.to_owned(),
67            stored_credential.public_key.to_owned(),
68        );
69        let credential_type = mls_credential
70            .credential_type()
71            .try_into()
72            .map_err(RecursiveError::context("loading credential from db"))?;
73        let earliest_validity = stored_credential.created_at;
74        Ok(Credential {
75            cipher_suite,
76            signature_key_pair,
77            credential_type,
78            mls_credential,
79            earliest_validity,
80        })
81    }
82}
83
84impl Credential {
85    /// Generate a basic credential.
86    ///
87    /// The result is independent of any client instance and the database; it lives in memory only.
88    ///
89    /// The earliest validity of this credential is always 0. It will be updated once the credential is added to a
90    /// session.
91    pub fn basic(cipher_suite: CipherSuite, client_id: ClientId) -> Result<Self> {
92        let signature_scheme = cipher_suite.signature_algorithm();
93        let (private_key, public_key) = CRYPTO
94            .signature_key_gen(signature_scheme)
95            .map_err(OpenMlsError::wrap("generating signature key"))?;
96        let signature_key_pair = SignatureKeyPair::from_raw(signature_scheme, private_key, public_key);
97
98        Ok(Self {
99            cipher_suite,
100            credential_type: CredentialType::Basic,
101            mls_credential: MlsCredential::new_basic(client_id.into_inner()),
102            signature_key_pair,
103            earliest_validity: 0,
104        })
105    }
106
107    /// Get the Openmls Credential type.
108    ///
109    /// This stores the credential type (basic/x509).
110    pub fn mls_credential(&self) -> &MlsCredential {
111        &self.mls_credential
112    }
113
114    /// Get the credential type
115    pub fn credential_type(&self) -> CredentialType {
116        self.credential_type
117    }
118
119    /// Get a reference to the `SignatureKeyPair`.
120    pub(crate) fn signature_key(&self) -> &SignatureKeyPair {
121        &self.signature_key_pair
122    }
123
124    /// The signature key bytes.
125    // TODO temporary. Remove when https://wearezeta.atlassian.net/wiki/x/RABtrQ is resolved.
126    pub fn signature_key_bytes(&self) -> &[u8] {
127        self.signature_key_pair.private()
128    }
129
130    /// Get the signature scheme
131    pub fn signature_scheme(&self) -> SignatureScheme {
132        self.signature_key_pair.signature_scheme()
133    }
134
135    /// Get the cipher suite
136    pub fn cipher_suite(&self) -> CipherSuite {
137        self.cipher_suite
138    }
139
140    /// Generate a `CredentialWithKey`, which combines the credential type with the public portion of the keypair.
141    pub fn to_mls_credential_with_key(&self) -> CredentialWithKey {
142        CredentialWithKey {
143            credential: self.mls_credential.clone(),
144            signature_key: self.signature_key_pair.to_public_vec().into(),
145        }
146    }
147
148    /// Earliest valid time of creation for this credential.
149    ///
150    /// This is represented as seconds after the unix epoch.
151    ///
152    /// Only meaningful for X509, where it is the "valid_from" claim of the leaf credential.
153    /// For basic credentials, this is always 0 when the credential is first created.
154    /// It is updated upon being persisted to the database.
155    pub fn earliest_validity(&self) -> u64 {
156        self.earliest_validity
157    }
158
159    /// Get the client ID associated with this credential
160    pub fn client_id(&self) -> &ClientIdRef {
161        self.mls_credential.identity().into()
162    }
163}
164
165impl From<Credential> for CredentialWithKey {
166    fn from(cb: Credential) -> Self {
167        Self {
168            credential: cb.mls_credential,
169            signature_key: cb.signature_key_pair.public().into(),
170        }
171    }
172}
173
174impl Eq for Credential {}
175impl PartialEq for Credential {
176    fn eq(&self, other: &Self) -> bool {
177        self.mls_credential == other.mls_credential && self.earliest_validity == other.earliest_validity && {
178            let sk = &self.signature_key_pair;
179            let ok = &other.signature_key_pair;
180            sk.signature_scheme() == ok.signature_scheme() && sk.public() == ok.public()
181            // public key equality implies private key equality
182        }
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::{x509::CertificateBundle, *};
189    use crate::{
190        CredentialType, E2eiConversationState,
191        mls::credential::x509::CertificatePrivateKey,
192        mls_provider::PkiKeypair,
193        test_utils::{
194            x509::{CertificateParams, X509TestChain},
195            *,
196        },
197    };
198
199    #[apply(all_cred_cipher)]
200    async fn basic_clients_can_send_messages(case: TestContext) {
201        if !case.is_basic() {
202            return;
203        }
204        let [alice, bob] = case.sessions_basic().await;
205        let conversation = case.create_conversation([&alice, &bob]).await;
206        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
207    }
208
209    #[apply(all_cred_cipher)]
210    async fn certificate_clients_can_send_messages(case: TestContext) {
211        if !case.is_x509() {
212            return;
213        }
214        let [alice, bob] = case.sessions_x509().await;
215        let conversation = case.create_conversation([&alice, &bob]).await;
216        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
217    }
218
219    #[apply(all_cred_cipher)]
220    async fn heterogeneous_clients_can_send_messages(case: TestContext) {
221        // check that both credentials can initiate/join a group
222        let ([x509_session], [basic_session]) = case.sessions_mixed_credential_types().await;
223
224        // That way the conversation creator (Alice) will have a different credential type than Bob
225        let (alice, bob) = match case.credential_type {
226            CredentialType::Basic => (x509_session, basic_session),
227            CredentialType::X509 => (basic_session, x509_session),
228        };
229
230        let conversation = case.create_conversation([&alice, &bob]).await;
231        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
232    }
233
234    #[apply(all_cred_cipher)]
235    async fn should_fail_when_certificate_chain_is_empty(case: TestContext) {
236        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
237
238        let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
239
240        let mut cert = CertificateBundle::rand(&"alice".into(), x509_intermediate);
241        cert.certificate_chain = vec![];
242        let err = Credential::x509(case.cipher_suite(), cert).unwrap_err();
243
244        assert!(innermost_source_matches!(err, Error::InvalidIdentity));
245    }
246
247    #[apply(all_cred_cipher)]
248    async fn should_fail_when_signature_key_doesnt_match_certificate_public_key(case: TestContext) {
249        if !case.is_x509() {
250            return;
251        }
252        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
253        let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
254
255        let certs = CertificateBundle::rand(&"alice".into(), x509_intermediate);
256        let new_pki_kp = PkiKeypair::rand(case.signature_scheme(), CRYPTO.as_ref()).unwrap();
257
258        let eve_key = CertificatePrivateKey::new(new_pki_kp.signing_key_bytes());
259        let cb = CertificateBundle {
260            certificate_chain: certs.certificate_chain,
261            private_key: eve_key,
262            signature_scheme: case.cipher_suite().signature_algorithm(),
263        };
264        let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
265
266        assert!(innermost_source_matches!(
267            err,
268            crate::OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::MismatchKeypair),
269        ));
270    }
271
272    #[apply(all_cred_cipher)]
273    async fn should_fail_when_certificate_signature_doesnt_match_ciphersuite(case: TestContext) {
274        use openmls::prelude::Ciphersuite;
275        if !case.is_x509() {
276            return;
277        }
278
279        let [alice] = case.sessions_x509().await;
280        let conversation = case.create_conversation([&alice]).await;
281
282        let other_cipher_suite = match case.cipher_suite() {
283            CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519) => {
284                CipherSuite(Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256)
285            }
286            _ => CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519),
287        };
288
289        let mixed_cipher_suite_case = TestContext::new(CredentialType::X509, *other_cipher_suite);
290        let [bob] = mixed_cipher_suite_case.sessions_x509().await;
291
292        let bob_kp = bob
293            .transaction
294            .generate_key_package(&bob.initial_credential, None)
295            .await
296            .unwrap()
297            .into();
298
299        assert!(conversation.guard().await.add_members(vec![bob_kp]).await.is_err());
300    }
301
302    #[apply(all_cred_cipher)]
303    async fn should_not_fail_but_degrade_when_certificate_expired(case: TestContext) {
304        if !case.is_x509() {
305            return;
306        }
307        Box::pin(async move {
308            let mut x509_test_chain = case.set_test_chain(&[], &[], None).await;
309            let expiration_time = core::time::Duration::from_secs(14);
310            let start = web_time::Instant::now();
311
312            let alice_cert = x509_test_chain.issue_simple_certificate_bundle("alice", None);
313            let alice_cred = Credential::x509(case.cipher_suite(), alice_cert).unwrap();
314            let bob_cert = x509_test_chain.issue_simple_certificate_bundle("bob", Some(expiration_time));
315            let bob_cred = Credential::x509(case.cipher_suite(), bob_cert).unwrap();
316            let alice = SessionContext::new_with_credential(&case, alice_cred).await.unwrap();
317            let bob = SessionContext::new_with_credential(&case, bob_cred).await.unwrap();
318
319            let conversation = case.create_conversation([&alice, &bob]).await;
320            // this should work since the certificate is not yet expired
321            assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
322
323            assert_eq!(
324                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
325                E2eiConversationState::Verified
326            );
327
328            let elapsed = start.elapsed();
329            // Give time to the certificate to expire
330            if expiration_time > elapsed {
331                smol::Timer::after(expiration_time - elapsed + core::time::Duration::from_secs(2)).await;
332            }
333
334            assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
335            assert_eq!(
336                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
337                E2eiConversationState::NotVerified
338            );
339        })
340        .await;
341    }
342
343    #[apply(all_cred_cipher)]
344    async fn should_not_fail_but_degrade_when_basic_joins(case: TestContext) {
345        if !case.is_x509() {
346            return;
347        }
348        Box::pin(async {
349            let ([alice, bob], [charlie]) = case.sessions_mixed_credential_types().await;
350            let conversation = case.create_conversation([&alice, &bob]).await;
351
352            // this should work since the certificate is not yet expired
353            assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
354            assert_eq!(
355                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
356                E2eiConversationState::Verified
357            );
358            assert_eq!(
359                conversation
360                    .guard_of(&bob)
361                    .await
362                    .e2ei_conversation_state()
363                    .await
364                    .unwrap(),
365                E2eiConversationState::Verified
366            );
367
368            // Charlie is a basic client that tries to join (i.e. emulates guest links in Wire)
369            let conversation = conversation
370                .invite_with_credential_notify([(&charlie, &charlie.initial_credential)])
371                .await;
372
373            assert_eq!(
374                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
375                E2eiConversationState::NotVerified
376            );
377            assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await);
378            assert_eq!(
379                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
380                E2eiConversationState::NotVerified
381            );
382        })
383        .await;
384    }
385
386    #[apply(all_cred_cipher)]
387    async fn should_fail_when_certificate_not_valid_yet(case: TestContext) {
388        use crate::OpenMlsErrorKind;
389
390        if !case.is_x509() {
391            return;
392        }
393        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
394
395        let tomorrow = now_std() + core::time::Duration::from_secs(3600 * 24);
396        let local_ca = x509_test_chain.find_local_intermediate_ca();
397        let alice_cert = {
398            let name = "alice";
399            let common_name = format!("{name} Smith");
400            let handle = format!("{}_wire", name.to_lowercase());
401            let [client_id] = case.client_ids();
402            local_ca.create_and_sign_end_identity(CertificateParams {
403                common_name: Some(common_name.clone()),
404                handle: Some(handle.clone()),
405                client_id: Some(client_id.clone()),
406                validity_start: Some(tomorrow),
407                ..Default::default()
408            })
409        };
410        let cb = CertificateBundle::from_certificate_and_issuer(&alice_cert, local_ca);
411        let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
412
413        assert!(innermost_source_matches!(
414            err,
415            OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::ExpiredCertificate),
416        ))
417    }
418
419    /// In order to be WASM-compatible
420    // pub fn now() -> wire_e2e_identity::OffsetDateTime {
421    //     let now_since_epoch = now_std().as_secs() as i64;
422    //     wire_e2e_identity::OffsetDateTime::from_unix_timestamp(now_since_epoch).unwrap()
423    // }
424    pub(crate) fn now_std() -> std::time::Duration {
425        let now = web_time::SystemTime::now();
426        now.duration_since(web_time::UNIX_EPOCH).unwrap()
427    }
428}