openmls 0.9.0-rc.1

A Rust implementation of the Messaging Layer Security (MLS) protocol, as defined in RFC 9420.
Documentation
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
//! # Known Answer Tests for basic crypto operations
//!
//! This test file generates and read test vectors for tree math.
//! See <https://github.com/mlswg/mls-implementations/blob/master/test-vectors.md>
//! for more description on the test vectors.
//!
//! Parameters:
//! * Ciphersuite
//!
//! Format:
//!
//! ```text
//! {
//!   "cipher_suite": /* uint16 */,
//!   "ref_hash": {
//!     "label": /* string */,
//!     "value": /* hex-encoded binary data */,
//!     "out": /* hex-encoded binary data */,
//!   }
//!   "expand_with_label": {
//!     "secret": /* hex-encoded binary data */,
//!     "label": /* string */,
//!     "context": /* hex-encoded binary data */,
//!     "length": /* uint16 */,
//!     "out": /* hex-encoded binary data */,
//!   },
//!   "derive_secret": {
//!     "secret": /* hex-encoded binary data */,
//!     "label": /* string */,
//!     "out": /* hex-encoded binary data */,
//!   },
//!   "derive_tree_secret": {
//!     "secret": /* hex-encoded binary data */,
//!     "label": /* string */
//!     "generation": /* uint32 */
//!     "length": /* uint16 */
//!     "out": /* hex-encoded binary data */,
//!   },
//!   "sign_with_label": {
//!     "priv": /* hex-encoded binary data */,
//!     "pub": /* hex-encoded binary data */,
//!     "content": /* hex-encoded binary data */,
//!     "label": /* string */,
//!     "signature": /* string */,
//!   },
//!   "encrypt_with_label": {
//!     "priv": /* hex-encoded binary data */,
//!     "pub": /* hex-encoded binary data */,
//!     "label": /* hex-encoded binary data */,
//!     "context": /* hex-encoded binary data */,
//!     "plaintext": /* hex-encoded binary data */,
//!     "kem_output": /* hex-encoded binary data */,
//!     "ciphertext": /* hex-encoded binary data */,
//!   }
//! }
//! ```
//!
//! Verification:
//!
//! * `ref_hash`: `out == RefHash(label, value)`
//! * `expand_with_label`: `out == ExpandWithLabel(secret, label, context, length)`
//! * `derive_secret`: `out == DeriveSecret(secret, label)`
//! * `derive_tree_secret`: `out == DeriveTreeSecret(secret, label, generation, length)`
//! * `sign_with_label`:
//!   * `VerifyWithLabel(pub, label, content, signature) == true`
//!   * `VerifyWithLabel(pub, label, content, SignWithLabel(priv, label, content)) == true`
//! * `encrypt_with_label`:
//!   * `DecryptWithLabel(priv, label, context, kem_output, ciphertext) == plaintext`
//!   * `kem_output_candidate, ciphertext_candidate = EncryptWithLabel(pub, label, context, plaintext)`
//!   * `DecryptWithLabel(priv, label, context, kem_output_candidate, ciphertext_candidate) == plaintext`

use crate::prelude_test::{
    signable::{Signable, SignedStruct, VerifiedStruct},
    Signature, Verifiable,
};
#[cfg(test)]
use crate::test_utils::*;

use openmls_basic_credential::SignatureKeyPair;
use serde::{self, Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RefHash {
    label: String,
    value: String,
    out: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ExpandWithLabel {
    secret: String,
    label: String,
    context: String,
    length: u16,
    out: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DeriveSecret {
    secret: String,
    label: String,
    out: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DeriveTreeSecret {
    secret: String,
    label: String,
    generation: u32,
    length: u16,
    out: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SignWithLabel {
    r#priv: String,
    r#pub: String,
    content: String,
    label: String,
    signature: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptWithLabel {
    r#priv: String,
    r#pub: String,
    label: String,
    context: String,
    plaintext: String,
    kem_output: String,
    ciphertext: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct ParsedSignWithLabel {
    key: SignatureKeyPair,
    content: Vec<u8>,
    label: String,
    signature: Signature,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct SignWithLabelTest {
    key: SignatureKeyPair,
    content: Vec<u8>,
    label: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct MySignature(Signature);
impl SignedStruct<ParsedSignWithLabel> for MySignature {
    fn from_payload(
        _: ParsedSignWithLabel,
        signature: Signature,
        _serialized_payload: Vec<u8>,
    ) -> Self {
        Self(signature)
    }
}
impl SignedStruct<SignWithLabelTest> for MySignature {
    fn from_payload(
        _: SignWithLabelTest,
        signature: Signature,
        _serialized_payload: Vec<u8>,
    ) -> Self {
        Self(signature)
    }
}

impl Verifiable for ParsedSignWithLabel {
    type VerifiedStruct = ();

    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
        Ok(self.content.clone())
    }

    fn signature(&self) -> &crate::prelude_test::Signature {
        &self.signature
    }

    fn label(&self) -> &str {
        &self.label
    }

    fn verify(
        self,
        crypto: &impl openmls_traits::crypto::OpenMlsCrypto,
        pk: &crate::ciphersuite::OpenMlsSignaturePublicKey,
    ) -> Result<Self::VerifiedStruct, crate::ciphersuite::signable::SignatureError> {
        self.verify_no_out(crypto, pk)?;
        Ok(())
    }
}

// Dummy implementation
impl VerifiedStruct for () {}

impl Signable for ParsedSignWithLabel {
    type SignedOutput = MySignature;

    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
        Ok(self.content.clone())
    }

    fn label(&self) -> &str {
        &self.label
    }
}

impl Signable for SignWithLabelTest {
    type SignedOutput = MySignature;

    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
        Ok(self.content.clone())
    }

    fn label(&self) -> &str {
        &self.label
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CryptoBasicsTestCase {
    cipher_suite: u16,
    ref_hash: RefHash,
    expand_with_label: ExpandWithLabel,
    derive_secret: DeriveSecret,
    derive_tree_secret: DeriveTreeSecret,
    sign_with_label: SignWithLabel,
    encrypt_with_label: EncryptWithLabel,
}

#[cfg(any(feature = "test-utils", test))]
pub fn run_test_vector(
    test: CryptoBasicsTestCase,
    provider: &OpenMlsRustCrypto,
) -> Result<(), String> {
    use openmls_traits::{crypto::OpenMlsCrypto, types::HpkeCiphertext};

    use crate::{
        prelude_test::{hash_ref, hpke, OpenMlsSignaturePublicKey, Secret},
        tree::secret_tree::derive_tree_secret,
    };

    let ciphersuite = Ciphersuite::try_from(test.cipher_suite).unwrap();
    // Skip unsupported ciphersuites.
    if !provider
        .crypto()
        .supported_ciphersuites()
        .contains(&ciphersuite)
    {
        log::debug!("Unsupported ciphersuite {ciphersuite:?} ...");
        return Ok(());
    }
    log::debug!("Basic crypto test for {ciphersuite:?} ...");

    //ref_hash
    {
        let label = test.ref_hash.label;
        let value = hex_to_bytes(&test.ref_hash.value);
        let out =
            hash_ref::HashReference::new(&value, ciphersuite, provider.crypto(), label.as_bytes())
                .unwrap();

        assert_eq!(&hex_to_bytes(&test.ref_hash.out), out.as_slice());
    }

    // expand_with_label
    {
        let secret = hex_to_bytes(&test.expand_with_label.secret);
        let label = test.expand_with_label.label;
        let context = hex_to_bytes(&test.expand_with_label.context);
        let length = test.expand_with_label.length;
        let out = Secret::from_slice(&secret)
            .kdf_expand_label(
                provider.crypto(),
                ciphersuite,
                &label,
                &context,
                length.into(),
            )
            .unwrap();

        assert_eq!(&hex_to_bytes(&test.expand_with_label.out), out.as_slice());
    }

    // derive_secret
    {
        let label = test.derive_secret.label;
        let secret = hex_to_bytes(&test.derive_secret.secret);
        let out = Secret::from_slice(&secret)
            .derive_secret(provider.crypto(), ciphersuite, &label)
            .unwrap();

        assert_eq!(&hex_to_bytes(&test.derive_secret.out), out.as_slice());
    }

    // sign with label
    {
        let private = hex_to_bytes(&test.sign_with_label.r#priv);
        let public = hex_to_bytes(&test.sign_with_label.r#pub);
        let label = test.sign_with_label.label;
        let content = hex_to_bytes(&test.sign_with_label.content);
        let signature = hex_to_bytes(&test.sign_with_label.signature).into();

        let mut parsed = ParsedSignWithLabel {
            key: SignatureKeyPair::from_raw(
                ciphersuite.signature_algorithm(),
                private,
                public.clone(),
            ),
            content,
            label,
            signature,
        };

        // sign
        let my_signature = parsed.clone().sign(&parsed.key).unwrap();

        // verify signature
        parsed
            .clone()
            .verify(
                provider.crypto(),
                &OpenMlsSignaturePublicKey::new(
                    public.clone().into(),
                    ciphersuite.signature_algorithm(),
                )
                .unwrap(),
            )
            .expect("Signature verification failed");

        // verify own signature
        parsed.signature = my_signature.0;
        parsed
            .verify(
                provider.crypto(),
                &OpenMlsSignaturePublicKey::new(public.into(), ciphersuite.signature_algorithm())
                    .unwrap(),
            )
            .expect("Signature verification failed");
    }

    // encrypt with label
    {
        let context = hex_to_bytes(&test.encrypt_with_label.context);
        let label = test.encrypt_with_label.label;
        let ciphertext = hex_to_bytes(&test.encrypt_with_label.ciphertext);
        let kem_output = hex_to_bytes(&test.encrypt_with_label.kem_output);
        let plaintext = hex_to_bytes(&test.encrypt_with_label.plaintext);
        let private = hex_to_bytes(&test.encrypt_with_label.r#priv);
        let public = hex_to_bytes(&test.encrypt_with_label.r#pub);

        // Check that decryption works.
        let decrypted_plaintext = hpke::decrypt_with_label(
            &private,
            &label,
            &context,
            &HpkeCiphertext {
                kem_output: kem_output.into(),
                ciphertext: ciphertext.into(),
            },
            ciphersuite,
            provider.crypto(),
        )
        .unwrap();
        assert_eq!(plaintext, decrypted_plaintext);

        // Check that encryption works.
        let my_ciphertext = hpke::encrypt_with_label(
            &public,
            &label,
            &context,
            &plaintext,
            ciphersuite,
            provider.crypto(),
        )
        .unwrap();
        let decrypted_plaintext = hpke::decrypt_with_label(
            &private,
            &label,
            &context,
            &my_ciphertext,
            ciphersuite,
            provider.crypto(),
        )
        .unwrap();
        assert_eq!(plaintext, decrypted_plaintext);
    }

    // Derive tree secret.
    {
        let secret = hex_to_bytes(&test.derive_tree_secret.secret);
        let label = test.derive_tree_secret.label;
        let generation = test.derive_tree_secret.generation;
        let length = test.derive_tree_secret.length;
        let out = hex_to_bytes(&test.derive_tree_secret.out);

        let tree_secret = derive_tree_secret(
            ciphersuite,
            &Secret::from_slice(&secret),
            &label,
            generation,
            length.into(),
            provider.crypto(),
        )
        .unwrap();

        assert_eq!(tree_secret.as_slice(), &out);
    }

    Ok(())
}

#[test]
fn read_test_vectors() {
    let _ = pretty_env_logger::try_init();

    log::debug!("Generating new basic crypto test vectors ...");

    let provider = OpenMlsRustCrypto::default();

    let tests: Vec<CryptoBasicsTestCase> = read_json!("../../../test_vectors/crypto-basics.json");
    for test in tests {
        match run_test_vector(test, &provider) {
            Ok(_) => {}
            Err(e) => panic!("Error while checking crypto basic test vector.\n{e:?}"),
        }
    }
}