Debian Codegraph @

third_party/rust/mls-rs/src/group/message_verifier.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 #[cfg(feature = "by_ref_proposal")]
6 use alloc::{vec, vec::Vec};
7
8 use crate::{
9 client::MlsError,
10 crypto::SignaturePublicKey,
11 group::{GroupContext, PublicMessage, Sender},
12 signer::Signable,
13 tree_kem::{node::LeafIndex, TreeKemPublic},
14 CipherSuiteProvider,
15 };
16
17 #[cfg(feature = "by_ref_proposal")]
18 use crate::{extension::ExternalSendersExt, identity::SigningIdentity};
19
20 use super::{
21 key_schedule::KeySchedule,
22 message_signature::{AuthenticatedContent, MessageSigningContext},
23 state::GroupState,
24 };
25
26 #[cfg(feature = "by_ref_proposal")]
27 use super::proposal::Proposal;
28
29 #[derive(Debug)]
30 pub(crate) enum SignaturePublicKeysContainer<'a> {
31 RatchetTree(&'a TreeKemPublic),
32 #[cfg(feature = "private_message")]
33 List(&'a [Option<SignaturePublicKey>]),
34 }
35
36 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
37 pub(crate) async fn verify_plaintext_authentication<P: CipherSuiteProvider>(
38 cipher_suite_provider: &P,
39 plaintext: PublicMessage,
40 key_schedule: Option<&KeySchedule>,
41 state: &GroupState,
42 ) -> Result<AuthenticatedContent, MlsError> {
43 let tag = plaintext.membership_tag.clone();
44 let auth_content = AuthenticatedContent::from(plaintext);
45 let context = &state.context;
46
47 #[cfg(feature = "by_ref_proposal")]
48 let external_signers = external_signers(context);
49
50 let current_tree = &state.public_tree;
51
52 // Verify the membership tag if needed
53 match &auth_content.content.sender {
54 Sender::Member(_) => {
55 if let Some(key_schedule) = key_schedule {
56 let expected_tag = &key_schedule
57 .get_membership_tag(&auth_content, context, cipher_suite_provider)
58 .await?;
59
60 let plaintext_tag = tag.as_ref().ok_or(MlsError::InvalidMembershipTag)?;
61
62 if expected_tag != plaintext_tag {
63 return Err(MlsError::InvalidMembershipTag);
64 }
65 }
66 }
67 _ => {
68 tag.is_none()
69 .then_some(())
70 .ok_or(MlsError::MembershipTagForNonMember)?;
71 }
72 }
73
74 // Verify that the signature on the MLSAuthenticatedContent verifies using the public key
75 // from the credential stored at the leaf in the tree indicated by the sender field.
76 verify_auth_content_signature(
77 cipher_suite_provider,
78 SignaturePublicKeysContainer::RatchetTree(current_tree),
79 context,
80 &auth_content,
81 #[cfg(feature = "by_ref_proposal")]
82 &external_signers,
83 )
84 .await?;
85
86 Ok(auth_content)
87 }
88
89 #[cfg(feature = "by_ref_proposal")]
90 fn external_signers(context: &GroupContext) -> Vec<SigningIdentity> {
91 context
92 .extensions
93 .get_as::<ExternalSendersExt>()
94 .unwrap_or(None)
95 .map_or(vec![], |extern_senders_ext| {
96 extern_senders_ext.allowed_senders
97 })
98 }
99
100 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
101 pub(crate) async fn verify_auth_content_signature<P: CipherSuiteProvider>(
102 cipher_suite_provider: &P,
103 signature_keys_container: SignaturePublicKeysContainer<'_>,
104 context: &GroupContext,
105 auth_content: &AuthenticatedContent,
106 #[cfg(feature = "by_ref_proposal")] external_signers: &[SigningIdentity],
107 ) -> Result<(), MlsError> {
108 let sender_public_key = signing_identity_for_sender(
109 signature_keys_container,
110 &auth_content.content.sender,
111 &auth_content.content.content,
112 #[cfg(feature = "by_ref_proposal")]
113 external_signers,
114 )?;
115
116 let context = MessageSigningContext {
117 group_context: Some(context),
118 protocol_version: context.protocol_version,
119 };
120
121 auth_content
122 .verify(cipher_suite_provider, &sender_public_key, &context)
123 .await?;
124
125 Ok(())
126 }
127
128 fn signing_identity_for_sender(
129 signature_keys_container: SignaturePublicKeysContainer,
130 sender: &Sender,
131 content: &super::framing::Content,
132 #[cfg(feature = "by_ref_proposal")] external_signers: &[SigningIdentity],
133 ) -> Result<SignaturePublicKey, MlsError> {
134 match sender {
135 Sender::Member(leaf_index) => {
136 signing_identity_for_member(signature_keys_container, LeafIndex(*leaf_index))
137 }
138 #[cfg(feature = "by_ref_proposal")]
139 Sender::External(external_key_index) => {
140 signing_identity_for_external(*external_key_index, external_signers)
141 }
142 Sender::NewMemberCommit => signing_identity_for_new_member_commit(content),
143 #[cfg(feature = "by_ref_proposal")]
144 Sender::NewMemberProposal => signing_identity_for_new_member_proposal(content),
145 }
146 }
147
148 fn signing_identity_for_member(
149 signature_keys_container: SignaturePublicKeysContainer,
150 leaf_index: LeafIndex,
151 ) -> Result<SignaturePublicKey, MlsError> {
152 match signature_keys_container {
153 SignaturePublicKeysContainer::RatchetTree(tree) => Ok(tree
154 .get_leaf_node(leaf_index)?
155 .signing_identity
156 .signature_key
157 .clone()), // TODO: We can probably get rid of this clone
158 #[cfg(feature = "private_message")]
159 SignaturePublicKeysContainer::List(list) => list
160 .get(leaf_index.0 as usize)
161 .cloned()
162 .flatten()
163 .ok_or(MlsError::LeafNotFound(*leaf_index)),
164 }
165 }
166
167 #[cfg(feature = "by_ref_proposal")]
168 fn signing_identity_for_external(
169 index: u32,
170 external_signers: &[SigningIdentity],
171 ) -> Result<SignaturePublicKey, MlsError> {
172 external_signers
173 .get(index as usize)
174 .map(|spk| spk.signature_key.clone())
175 .ok_or(MlsError::UnknownSigningIdentityForExternalSender)
176 }
177
178 fn signing_identity_for_new_member_commit(
179 content: &super::framing::Content,
180 ) -> Result<SignaturePublicKey, MlsError> {
181 match content {
182 super::framing::Content::Commit(commit) => {
183 if let Some(path) = &commit.path {
184 Ok(path.leaf_node.signing_identity.signature_key.clone())
185 } else {
186 Err(MlsError::CommitMissingPath)
187 }
188 }
189 #[cfg(any(feature = "private_message", feature = "by_ref_proposal"))]
190 _ => Err(MlsError::ExpectedCommitForNewMemberCommit),
191 }
192 }
193
194 #[cfg(feature = "by_ref_proposal")]
195 fn signing_identity_for_new_member_proposal(
196 content: &super::framing::Content,
197 ) -> Result<SignaturePublicKey, MlsError> {
198 match content {
199 super::framing::Content::Proposal(proposal) => {
200 if let Proposal::Add(p) = proposal.as_ref() {
201 Ok(p.key_package
202 .leaf_node
203 .signing_identity
204 .signature_key
205 .clone())
206 } else {
207 Err(MlsError::ExpectedAddProposalForNewMemberProposal)
208 }
209 }
210 _ => Err(MlsError::ExpectedAddProposalForNewMemberProposal),
211 }
212 }
213
214 #[cfg(test)]
215 mod tests {
216 use super::*;
217 use crate::{
218 client::{
219 test_utils::{test_client_with_key_pkg, TEST_CIPHER_SUITE, TEST_PROTOCOL_VERSION},
220 MlsError,
221 },
222 client_builder::test_utils::TestClientConfig,
223 crypto::test_utils::test_cipher_suite_provider,
224 group::{
225 membership_tag::MembershipTag,
226 message_signature::{AuthenticatedContent, MessageSignature},
227 test_utils::{test_group_custom, TestGroup},
228 Group, PublicMessage,
229 },
230 };
231 use alloc::vec;
232 use assert_matches::assert_matches;
233
234 #[cfg(feature = "by_ref_proposal")]
235 use crate::{extension::ExternalSendersExt, ExtensionList};
236
237 #[cfg(feature = "by_ref_proposal")]
238 use crate::{
239 crypto::SignatureSecretKey,
240 group::{
241 message_signature::MessageSigningContext,
242 proposal::{AddProposal, Proposal, RemoveProposal},
243 Content,
244 },
245 key_package::KeyPackageGeneration,
246 signer::Signable,
247 WireFormat,
248 };
249
250 #[cfg(feature = "by_ref_proposal")]
251 use alloc::boxed::Box;
252
253 #[cfg(feature = "by_ref_proposal")]
254 use crate::group::{
255 test_utils::{test_group, test_member},
256 Sender,
257 };
258
259 #[cfg(feature = "by_ref_proposal")]
260 use crate::identity::test_utils::get_test_signing_identity;
261
262 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
263 async fn make_signed_plaintext(group: &mut Group<TestClientConfig>) -> PublicMessage {
264 group
265 .commit(vec![])
266 .await
267 .unwrap()
268 .commit_message
269 .into_plaintext()
270 .unwrap()
271 }
272
273 struct TestEnv {
274 alice: TestGroup,
275 bob: TestGroup,
276 }
277
278 impl TestEnv {
279 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
280 async fn new() -> Self {
281 let mut alice = test_group_custom(
282 TEST_PROTOCOL_VERSION,
283 TEST_CIPHER_SUITE,
284 Default::default(),
285 None,
286 None,
287 )
288 .await;
289
290 let (bob_client, bob_key_pkg) =
291 test_client_with_key_pkg(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, "bob").await;
292
293 let commit_output = alice
294 .commit_builder()
295 .add_member(bob_key_pkg)
296 .unwrap()
297 .build()
298 .await
299 .unwrap();
300
301 alice.apply_pending_commit().await.unwrap();
302
303 let (bob, _) = Group::join(
304 &commit_output.welcome_messages[0],
305 None,
306 bob_client.config,
307 bob_client.signer.unwrap(),
308 )
309 .await
310 .unwrap();
311
312 TestEnv {
313 alice,
314 bob: TestGroup { group: bob },
315 }
316 }
317 }
318
319 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
320 async fn valid_plaintext_is_verified() {
321 let mut env = TestEnv::new().await;
322
323 let message = make_signed_plaintext(&mut env.alice).await;
324
325 verify_plaintext_authentication(
326 &env.bob.cipher_suite_provider,
327 message,
328 Some(&env.bob.key_schedule),
329 &env.bob.state,
330 )
331 .await
332 .unwrap();
333 }
334
335 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
336 async fn valid_auth_content_is_verified() {
337 let mut env = TestEnv::new().await;
338
339 let message = AuthenticatedContent::from(make_signed_plaintext(&mut env.alice).await);
340
341 verify_auth_content_signature(
342 &env.bob.cipher_suite_provider,
343 super::SignaturePublicKeysContainer::RatchetTree(&env.bob.state.public_tree),
344 env.bob.context(),
345 &message,
346 #[cfg(feature = "by_ref_proposal")]
347 &[],
348 )
349 .await
350 .unwrap();
351 }
352
353 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
354 async fn invalid_plaintext_is_not_verified() {
355 let mut env = TestEnv::new().await;
356 let mut message = make_signed_plaintext(&mut env.alice).await;
357 message.auth.signature = MessageSignature::from(b"test".to_vec());
358
359 message.membership_tag = env
360 .alice
361 .key_schedule
362 .get_membership_tag(
363 &AuthenticatedContent::from(message.clone()),
364 env.alice.context(),
365 &test_cipher_suite_provider(env.alice.cipher_suite()),
366 )
367 .await
368 .unwrap()
369 .into();
370
371 let res = verify_plaintext_authentication(
372 &env.bob.cipher_suite_provider,
373 message,
374 Some(&env.bob.key_schedule),
375 &env.bob.state,
376 )
377 .await;
378
379 assert_matches!(res, Err(MlsError::InvalidSignature));
380 }
381
382 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
383 async fn plaintext_from_member_requires_membership_tag() {
384 let mut env = TestEnv::new().await;
385 let mut message = make_signed_plaintext(&mut env.alice).await;
386 message.membership_tag = None;
387
388 let res = verify_plaintext_authentication(
389 &env.bob.cipher_suite_provider,
390 message,
391 Some(&env.bob.key_schedule),
392 &env.bob.state,
393 )
394 .await;
395
396 assert_matches!(res, Err(MlsError::InvalidMembershipTag));
397 }
398
399 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
400 async fn plaintext_fails_with_invalid_membership_tag() {
401 let mut env = TestEnv::new().await;
402 let mut message = make_signed_plaintext(&mut env.alice).await;
403 message.membership_tag = Some(MembershipTag::from(b"test".to_vec()));
404
405 let res = verify_plaintext_authentication(
406 &env.bob.cipher_suite_provider,
407 message,
408 Some(&env.bob.key_schedule),
409 &env.bob.state,
410 )
411 .await;
412
413 assert_matches!(res, Err(MlsError::InvalidMembershipTag));
414 }
415
416 #[cfg(feature = "by_ref_proposal")]
417 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
418 async fn test_new_member_proposal<F>(
419 key_pkg_gen: KeyPackageGeneration,
420 signer: &SignatureSecretKey,
421 test_group: &TestGroup,
422 mut edit: F,
423 ) -> PublicMessage
424 where
425 F: FnMut(&mut AuthenticatedContent),
426 {
427 let mut content = AuthenticatedContent::new_signed(
428 &test_group.cipher_suite_provider,
429 test_group.context(),
430 Sender::NewMemberProposal,
431 Content::Proposal(Box::new(Proposal::Add(Box::new(AddProposal {
432 key_package: key_pkg_gen.key_package,
433 })))),
434 signer,
435 WireFormat::PublicMessage,
436 vec![],
437 )
438 .await
439 .unwrap();
440
441 edit(&mut content);
442
443 let signing_context = MessageSigningContext {
444 group_context: Some(test_group.context()),
445 protocol_version: test_group.protocol_version(),
446 };
447
448 content
449 .sign(&test_group.cipher_suite_provider, signer, &signing_context)
450 .await
451 .unwrap();
452
453 PublicMessage {
454 content: content.content,
455 auth: content.auth,
456 membership_tag: None,
457 }
458 }
459
460 #[cfg(feature = "by_ref_proposal")]
461 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
462 async fn valid_proposal_from_new_member_is_verified() {
463 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
464 let (key_pkg_gen, signer) =
465 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
466 let message = test_new_member_proposal(key_pkg_gen, &signer, &test_group, |_| {}).await;
467
468 verify_plaintext_authentication(
469 &test_group.cipher_suite_provider,
470 message,
471 Some(&test_group.key_schedule),
472 &test_group.state,
473 )
474 .await
475 .unwrap();
476 }
477
478 #[cfg(feature = "by_ref_proposal")]
479 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
480 async fn proposal_from_new_member_must_not_have_membership_tag() {
481 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
482 let (key_pkg_gen, signer) =
483 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
484
485 let mut message = test_new_member_proposal(key_pkg_gen, &signer, &test_group, |_| {}).await;
486 message.membership_tag = Some(MembershipTag::from(vec![]));
487
488 let res = verify_plaintext_authentication(
489 &test_group.cipher_suite_provider,
490 message,
491 Some(&test_group.key_schedule),
492 &test_group.state,
493 )
494 .await;
495
496 assert_matches!(res, Err(MlsError::MembershipTagForNonMember));
497 }
498
499 #[cfg(feature = "by_ref_proposal")]
500 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
501 async fn new_member_proposal_sender_must_be_add_proposal() {
502 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
503 let (key_pkg_gen, signer) =
504 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
505
506 let message = test_new_member_proposal(key_pkg_gen, &signer, &test_group, |msg| {
507 msg.content.content = Content::Proposal(Box::new(Proposal::Remove(RemoveProposal {
508 to_remove: LeafIndex(0),
509 })))
510 })
511 .await;
512
513 let res: Result<AuthenticatedContent, MlsError> = verify_plaintext_authentication(
514 &test_group.cipher_suite_provider,
515 message,
516 Some(&test_group.key_schedule),
517 &test_group.state,
518 )
519 .await;
520
521 assert_matches!(res, Err(MlsError::ExpectedAddProposalForNewMemberProposal));
522 }
523
524 #[cfg(feature = "by_ref_proposal")]
525 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
526 async fn new_member_commit_must_be_external_commit() {
527 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
528 let (key_pkg_gen, signer) =
529 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
530
531 let message = test_new_member_proposal(key_pkg_gen, &signer, &test_group, |msg| {
532 msg.content.sender = Sender::NewMemberCommit;
533 })
534 .await;
535
536 let res = verify_plaintext_authentication(
537 &test_group.cipher_suite_provider,
538 message,
539 Some(&test_group.key_schedule),
540 &test_group.state,
541 )
542 .await;
543
544 assert_matches!(res, Err(MlsError::ExpectedCommitForNewMemberCommit));
545 }
546
547 #[cfg(feature = "by_ref_proposal")]
548 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
549 async fn valid_proposal_from_external_is_verified() {
550 let (bob_key_pkg_gen, _) =
551 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
552
553 let (ted_signing, ted_secret) = get_test_signing_identity(TEST_CIPHER_SUITE, b"ted").await;
554
555 let mut test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
556 let mut extensions = ExtensionList::default();
557
558 extensions
559 .set_from(ExternalSendersExt {
560 allowed_senders: vec![ted_signing],
561 })
562 .unwrap();
563
564 test_group
565 .commit_builder()
566 .set_group_context_ext(extensions)
567 .unwrap()
568 .build()
569 .await
570 .unwrap();
571
572 test_group.apply_pending_commit().await.unwrap();
573
574 let message = test_new_member_proposal(bob_key_pkg_gen, &ted_secret, &test_group, |msg| {
575 msg.content.sender = Sender::External(0)
576 })
577 .await;
578
579 verify_plaintext_authentication(
580 &test_group.cipher_suite_provider,
581 message,
582 Some(&test_group.key_schedule),
583 &test_group.state,
584 )
585 .await
586 .unwrap();
587 }
588
589 #[cfg(feature = "by_ref_proposal")]
590 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
591 async fn external_proposal_must_be_from_valid_sender() {
592 let (bob_key_pkg_gen, _) =
593 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
594 let (_, ted_secret) = get_test_signing_identity(TEST_CIPHER_SUITE, b"ted").await;
595 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
596
597 let message = test_new_member_proposal(bob_key_pkg_gen, &ted_secret, &test_group, |msg| {
598 msg.content.sender = Sender::External(0)
599 })
600 .await;
601
602 let res = verify_plaintext_authentication(
603 &test_group.cipher_suite_provider,
604 message,
605 Some(&test_group.key_schedule),
606 &test_group.state,
607 )
608 .await;
609
610 assert_matches!(res, Err(MlsError::UnknownSigningIdentityForExternalSender));
611 }
612
613 #[cfg(feature = "by_ref_proposal")]
614 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
615 async fn proposal_from_external_sender_must_not_have_membership_tag() {
616 let (bob_key_pkg_gen, _) =
617 test_member(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE, b"bob").await;
618
619 let (_, ted_secret) = get_test_signing_identity(TEST_CIPHER_SUITE, b"ted").await;
620
621 let test_group = test_group(TEST_PROTOCOL_VERSION, TEST_CIPHER_SUITE).await;
622
623 let mut message =
624 test_new_member_proposal(bob_key_pkg_gen, &ted_secret, &test_group, |_| {}).await;
625
626 message.membership_tag = Some(MembershipTag::from(vec![]));
627
628 let res = verify_plaintext_authentication(
629 &test_group.cipher_suite_provider,
630 message,
631 Some(&test_group.key_schedule),
632 &test_group.state,
633 )
634 .await;
635
636 assert_matches!(res, Err(MlsError::MembershipTagForNonMember));
637 }
638 }