matrix-sdk-crypto 0.19.0

Matrix encryption library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright 2026 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

use std::{fmt::Debug, sync::Arc};

use cms::cert::x509::{
    Certificate,
    attr::AttributeValue,
    der,
    der::oid as const_oid,
    ext::pkix::{SubjectAltName, name::GeneralName},
};
use ruma::{MatrixUri, OwnedUserId, UserId, matrix_uri::MatrixId};

use crate::{
    olm::SignedJsonObject,
    types::{Signature, X509Signature},
    x509::{
        errors::X509SignatureVerificationError,
        raw_x509_signature::{RawX509Signature, RawX509SignatureAndFirstCertificate},
    },
};

/// Hold one of these if you want to verify X.509 signatures, and call
/// [`Self::verify_x509_signature`] to do it.
///
/// Internally, this holds an implementation of [`RawX509Verifier`] that does
/// the real work of verifying things. This struct provides a convenient
/// wrapper.
#[derive(Debug, Clone)]
pub(crate) struct X509Verifier {
    x509_verify: Arc<dyn RawX509Verifier>,
}

impl X509Verifier {
    /// Create a new `X509Verifier` that wraps the supplied [`RawX509Verifier`].
    pub(crate) fn new(x509_verify: Arc<dyn RawX509Verifier>) -> X509Verifier {
        X509Verifier { x509_verify }
    }

    /// Verify that the given object is signed with a certificate issued by a
    /// trusted CA, and that the certificate was issued to the given user
    /// ID.
    ///
    /// Note that, unlike verifying an Ed25519 signature, the result here is
    /// derived from the configured trust anchors at the time of the call, and
    /// so this method may give a different answer in the future, e.g. once the
    /// certificate chain expires.
    pub(crate) fn verify_signed_object(
        &self,
        user_id: &UserId,
        signed_object: &(impl SignedJsonObject + Debug),
    ) -> bool {
        let Some(this_user_sigs) = signed_object.signatures().get(user_id) else {
            tracing::info!("X509: verify_signed_object(): no signatures on object");
            return false;
        };

        let Ok(msg) = signed_object.to_canonical_json() else {
            tracing::warn!("Unable to serialize object");
            return false;
        };

        for sig in this_user_sigs.values().flatten() {
            // `this_user_sigs` can and will contain non-X.509 signatures, which we should
            // ignore.
            if let Signature::X509(sig) = sig
                && self
                    .verify_x509_signature(user_id, &msg, sig)
                    .inspect_err(|e| {
                        tracing::warn!(
                            "X509: verify_signed_object(): X509 signature failed verification: {e}"
                        )
                    })
                    .is_ok()
            {
                tracing::debug!("X509: verify_signed_object(): verified X509 signature");
                return true;
            }
        }
        false
    }

    /// Check if the given signature is a valid X.509 signature for the given
    /// message.
    ///
    /// Also validates that the certificate used for the signature is issued via
    /// one of our trusted CAs, and was issued to the given user id.
    pub(crate) fn verify_x509_signature(
        &self,
        user_id: &UserId,
        message: &str,
        sig: &X509Signature,
    ) -> Result<(), X509SignatureVerificationError> {
        let res: RawX509SignatureAndFirstCertificate =
            sig.try_into().map_err(X509SignatureVerificationError::RawSignatureParseError)?;

        // Before we pass over to the X.509 certificate verifier, check that the leaf
        // certificate is valid for the given user_id.
        if !cert_contains_user_id_or_equivalent_email(user_id, &res.leaf_cert) {
            tracing::warn!(?user_id, "Verifying certificate user ID or email failed");
            return Err(X509SignatureVerificationError::BadUserIdOrEmail);
        }

        self.x509_verify.verify(message.as_bytes(), &res.raw_x509signature)
    }
}

fn cert_contains_user_id_or_equivalent_email(user_id: &UserId, certificate: &Certificate) -> bool {
    // Check for a user ID in its SAN
    if let Some(certificate_user_id) = get_user_id_from_certificate(certificate) {
        if certificate_user_id == user_id {
            return true;
        } else {
            tracing::warn!(
                "Certificate not valid for this user. \
                Certificate user ID: {certificate_user_id}, \
                User ID: {user_id}",
            );
            return false;
        }
    }

    // Otherwise, as a fallback, check for an email address

    tracing::info!("Certificate subject does not contain a user ID. Checking for email address");

    let Some(certificate_email) = get_email_address_from_certificate(certificate) else {
        tracing::warn!("Certificate subject does not contain an email address");
        return false;
    };

    let expected_email = map_user_id_to_email(user_id);
    if certificate_email == expected_email {
        true
    } else {
        tracing::warn!(
            "Certificate not valid for this user. \
                Certificate email: {certificate_email}, \
                Expected email: {expected_email}, User ID: {user_id}",
        );
        false
    }
}

/// Something that can verify an X.509 signature.
pub trait RawX509Verifier: Debug + Send + Sync {
    /// Check if the given signature is a valid X.509 signature for the given
    /// message.
    ///
    /// Also validates that the certificate used for the signature is issued via
    /// one of our trusted CAs.
    fn verify(
        &self,
        message: &[u8],
        signature: &RawX509Signature,
    ) -> Result<(), X509SignatureVerificationError>;
}

fn map_user_id_to_email(user_id: &UserId) -> String {
    // TODO RAV: this is not a reliable way to map from user_ids to email addresses.
    format!("{}@{}", user_id.localpart(), user_id.server_name())
}

/// Search this certificate's Subject Alternative Name for a URI that matches
/// the format of a Matrix URI that contains a valid Matrix user ID.
fn get_user_id_from_certificate(certificate: &Certificate) -> Option<OwnedUserId> {
    // If we have no SAN or SAN is not understood here, we definitely can't find a
    // user ID.
    let Ok(Some((_, san))) = certificate.tbs_certificate.get::<SubjectAltName>() else {
        return None;
    };

    /// Check whether a SAN contains a valid Matrix user ID
    fn matrix_user_uri(alt_name: &GeneralName) -> Option<OwnedUserId> {
        // If it's a URI SAN type
        if let GeneralName::UniformResourceIdentifier(uri) = alt_name {
            // And it parses as a `matrix:...` URI
            if let Ok(matrix_uri) = MatrixUri::parse(uri.as_str()) {
                // And it's a user URI that produces a valid Matrix user ID
                if let MatrixId::User(user_id) = matrix_uri.id() {
                    // Then return it
                    return Some(user_id.clone());
                }
            }
        }

        // Otherwise, we didn't find a user ID
        None
    }

    // If any name looks right, return it - otherwise None
    san.0.iter().find_map(matrix_user_uri)
}

fn get_email_address_from_certificate(certificate: &Certificate) -> Option<String> {
    // Check for an email address in the Subject Alternative Name
    if let Ok(Some((_, san))) = certificate.tbs_certificate.get::<SubjectAltName>()
        && let Some(email) = san
            .0
            .into_iter()
            .find_map(|n| if let GeneralName::Rfc822Name(email) = n { Some(email) } else { None })
    {
        return Some(email.as_str().to_owned());
    }

    // Otherwise, check for the (legacy) email address in the Subject
    // Distinguished Name
    let subject = &certificate.tbs_certificate.subject;
    for atav in subject.0.iter().flat_map(|rdn| rdn.0.iter()) {
        if atav.oid == const_oid::db::rfc3280::EMAIL_ADDRESS
            && let Some(e) = get_attribute_value_as_string(&atav.value)
        {
            return Some(e.to_owned());
        }
    }

    // Otherwise, nothing was found
    None
}

/// Attempt to parse the given X.501 Attribute as a string
fn get_attribute_value_as_string(value: &AttributeValue) -> Option<&str> {
    use der::Tagged;
    match value.tag() {
        der::Tag::PrintableString => {
            der::asn1::PrintableStringRef::try_from(value).ok().map(|s| s.as_str())
        }
        der::Tag::Utf8String => der::asn1::Utf8StringRef::try_from(value).ok().map(|s| s.as_str()),
        der::Tag::Ia5String => der::asn1::Ia5StringRef::try_from(value).ok().map(|s| s.as_str()),
        der::Tag::TeletexString => {
            der::asn1::TeletexStringRef::try_from(value).ok().map(|s| s.as_str())
        }
        _ => None,
    }
}

#[cfg(test)]
pub(crate) mod tests {

    use cms::cert::x509::der::Decode;
    use matrix_sdk_test::async_test;
    use rcgen::generate_simple_self_signed;
    use ruma::{DeviceKeyAlgorithm, DeviceKeyId, encryption::KeyUsage, user_id};
    use vodozemac::Ed25519SecretKey;

    use super::*;
    use crate::{
        types::{CrossSigningKey, SigningKeys},
        x509::tests::{
            cert_and_key_with_email_in_subject_alternate_name,
            cert_and_key_with_email_in_subject_distinguished_name, cert_and_key_with_no_user_id,
            cert_and_key_with_user_id_in_subject_alternate_name, create_rust_signer_and_verifier,
        },
    };

    #[test]
    fn test_can_extract_email_address_from_a_cert_sdn() {
        // Given a certificate containing an email address in the Subject
        // Distinguished Name
        let (cert, _) =
            cert_and_key_with_email_in_subject_distinguished_name("myname@company.co.uk");

        // When we extract the email address it contains
        let email = get_email_address_from_certificate(&Certificate::from_der(cert.der()).unwrap())
            .expect("Failed to get email address from cert");

        // Then it matches what we put in
        assert_eq!(email, "myname@company.co.uk");
    }

    #[test]
    fn test_can_extract_email_address_from_a_cert_san() {
        // Given a certificate containing an email address in the Subject
        // Alternative Name
        let (cert, _) = cert_and_key_with_email_in_subject_alternate_name("myname@company.co.uk");

        // When we extract the email address it contains
        let email = get_email_address_from_certificate(&Certificate::from_der(cert.der()).unwrap())
            .expect("Failed to get email address from cert");

        // Then it matches what we put in
        assert_eq!(email, "myname@company.co.uk");
    }

    #[test]
    fn test_can_extract_user_id_from_a_cert_san() {
        // Given a certificate containing a user ID in the Subject Alternative
        // Name
        let (cert, _) =
            cert_and_key_with_user_id_in_subject_alternate_name("@myname:company.co.uk");

        // When we extract the user ID it contains
        let user_id = get_user_id_from_certificate(&Certificate::from_der(cert.der()).unwrap())
            .expect("Failed to get email address from cert");

        // Then it matches what we put in
        assert_eq!(user_id, "@myname:company.co.uk");
    }

    #[test]
    fn test_extract_email_address_from_a_cert_that_does_not_contain_one_returns_none() {
        // Given a certificate not containing an email address
        let cert = generate_simple_self_signed(&[]).expect("Failed to generate cert");

        // When we attempt to extract the email address
        let email =
            get_email_address_from_certificate(&Certificate::from_der(cert.cert.der()).unwrap());

        // Then the answer is empty
        assert!(email.is_none());
    }

    #[test]
    fn test_extract_user_id_from_a_cert_that_does_not_contain_one_returns_none() {
        // Given a certificate not containing an email address
        let cert = generate_simple_self_signed(&[]).expect("Failed to generate cert");

        // When we attempt to extract the email address
        let user_id =
            get_user_id_from_certificate(&Certificate::from_der(cert.cert.der()).unwrap());

        // Then the answer is empty
        assert!(user_id.is_none());
    }

    #[async_test]
    async fn test_can_verify_cert_containing_email_in_dn() {
        // Given a cert containing the email address in the Subject Distinguished Name
        let (cert, signing_key) =
            cert_and_key_with_email_in_subject_distinguished_name("alice@localhost");

        // And a cross-signing key
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        // When we attempt to verify it without signing, then it fails
        assert!(!x509_verifier.verify_signed_object(&user_id, &cross_signing_key));

        // But when we sign it
        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it verifies correctly
        assert!(x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_can_verify_cert_containing_email_in_san() {
        // Given a cert containing the email address in the Subject Alternative
        // Name
        let (cert, signing_key) =
            cert_and_key_with_email_in_subject_alternate_name("alice@localhost");

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it verifies correctly.
        assert!(x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_can_verify_cert_containing_username_in_san() {
        // Given a cert containing the Matrix user ID in the Subject Alternative
        // Name
        let (cert, signing_key) =
            cert_and_key_with_user_id_in_subject_alternate_name("@alice:localhost");

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it verifies correctly.
        assert!(x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_verification_fails_if_dn_email_is_wrong() {
        // Given a cert containing an incorrect email address in the Subject
        // Distinguished Name
        let (cert, signing_key) =
            cert_and_key_with_email_in_subject_distinguished_name("bob@localhost");

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it fails to verify because the supplied email address translates
        // to a different user ID.
        assert!(!x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_verification_fails_if_san_email_is_wrong() {
        // Given a cert containing an incorrect email address in the Subject
        // Alternative Name
        let (cert, signing_key) =
            cert_and_key_with_email_in_subject_alternate_name("bob@localhost");

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it fails to verify because the supplied email address translates
        // to a different user ID.
        assert!(!x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_verification_fails_if_cert_user_id_is_wrong() {
        // Given a cert containing an incorrect email address in the Subject
        // Alternative Name
        let (cert, signing_key) =
            cert_and_key_with_user_id_in_subject_alternate_name("@bob:localhost");

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it fails to verify because the supplied user ID does not match
        // the signing user.
        assert!(!x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    #[async_test]
    async fn test_verification_fails_if_cert_user_id_is_missing() {
        // Given a cert with no email or user ID at all
        let (cert, signing_key) = cert_and_key_with_no_user_id();

        // When we sign a cross-signing key using it
        let (x509_signer, x509_verifier) = create_rust_signer_and_verifier(cert, signing_key);

        let user_id = user_id!("@alice:localhost").to_owned();
        let mut cross_signing_key = create_cross_signing_key(&user_id);

        x509_signer.sign_cross_signing_key(&user_id, &mut cross_signing_key).await.unwrap();

        // Then it fails to verify because there is no user ID to check against
        // the user's ID.
        assert!(!x509_verifier.verify_signed_object(&user_id, &cross_signing_key));
    }

    fn create_cross_signing_key(user_id: &UserId) -> CrossSigningKey {
        let secret_key = Ed25519SecretKey::new();
        let public_key = secret_key.public_key();
        let keys = SigningKeys::from([(
            DeviceKeyId::from_parts(
                DeviceKeyAlgorithm::Ed25519,
                public_key.to_base64().as_str().into(),
            ),
            public_key.into(),
        )]);

        CrossSigningKey::new(user_id.to_owned(), vec![KeyUsage::Master], keys, Default::default())
    }
}