openmls/group/mls_group/processing.rs
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
//! Processing functions of an [`MlsGroup`] for incoming messages.
use std::mem;
use errors::{CommitToPendingProposalsError, MergePendingCommitError};
use openmls_traits::{crypto::OpenMlsCrypto, signatures::Signer, storage::StorageProvider as _};
use crate::{
framing::mls_content::FramedContentBody,
group::{errors::MergeCommitError, StageCommitError, ValidationError},
messages::group_info::GroupInfo,
storage::OpenMlsProvider,
tree::sender_ratchet::SenderRatchetConfiguration,
};
use super::{errors::ProcessMessageError, *};
impl MlsGroup {
/// Parses incoming messages from the DS. Checks for syntactic errors and
/// makes some semantic checks as well. If the input is an encrypted
/// message, it will be decrypted. This processing function does syntactic
/// and semantic validation of the message. It returns a [ProcessedMessage]
/// enum.
///
/// # Errors:
/// Returns an [`ProcessMessageError`] when the validation checks fail
/// with the exact reason of the failure.
pub fn process_message<Provider: OpenMlsProvider>(
&mut self,
provider: &Provider,
message: impl Into<ProtocolMessage>,
) -> Result<ProcessedMessage, ProcessMessageError> {
// Make sure we are still a member of the group
if !self.is_active() {
return Err(ProcessMessageError::GroupStateError(
MlsGroupStateError::UseAfterEviction,
));
}
let message = message.into();
// Check that handshake messages are compatible with the incoming wire format policy
if !message.is_external()
&& message.is_handshake_message()
&& !self
.configuration()
.wire_format_policy()
.incoming()
.is_compatible_with(message.wire_format())
{
return Err(ProcessMessageError::IncompatibleWireFormat);
}
// Parse the message
let sender_ratchet_configuration =
self.configuration().sender_ratchet_configuration().clone();
// Checks the following semantic validation:
// - ValSem002
// - ValSem003
// - ValSem006
// - ValSem007 MembershipTag presence
let decrypted_message =
self.decrypt_message(provider.crypto(), message, &sender_ratchet_configuration)?;
let unverified_message = self
.public_group
.parse_message(decrypted_message, &self.message_secrets_store)
.map_err(ProcessMessageError::from)?;
// If this is a commit, we need to load the private key material we need for decryption.
let (old_epoch_keypairs, leaf_node_keypairs) =
if let ContentType::Commit = unverified_message.content_type() {
self.read_decryption_keypairs(provider, &self.own_leaf_nodes)?
} else {
(vec![], vec![])
};
self.process_unverified_message(
provider,
unverified_message,
old_epoch_keypairs,
leaf_node_keypairs,
)
}
/// Stores a standalone proposal in the internal [ProposalStore]
pub fn store_pending_proposal<Storage: StorageProvider>(
&mut self,
storage: &Storage,
proposal: QueuedProposal,
) -> Result<(), Storage::Error> {
storage.queue_proposal(self.group_id(), &proposal.proposal_reference(), &proposal)?;
// Store the proposal in in the internal ProposalStore
self.proposal_store_mut().add(proposal);
Ok(())
}
/// Creates a Commit message that covers the pending proposals that are
/// currently stored in the group's [ProposalStore]. The Commit message is
/// created even if there are no valid pending proposals.
///
/// Returns an error if there is a pending commit. Otherwise it returns a
/// tuple of `Commit, Option<Welcome>, Option<GroupInfo>`, where `Commit`
/// and [`Welcome`] are MlsMessages of the type [`MlsMessageOut`].
///
/// [`Welcome`]: crate::messages::Welcome
// FIXME: #1217
#[allow(clippy::type_complexity)]
pub fn commit_to_pending_proposals<Provider: OpenMlsProvider>(
&mut self,
provider: &Provider,
signer: &impl Signer,
) -> Result<
(MlsMessageOut, Option<MlsMessageOut>, Option<GroupInfo>),
CommitToPendingProposalsError<Provider::StorageError>,
> {
self.is_operational()?;
// Build and stage the commit using the commit builder
// TODO #751
let (commit, welcome, group_info) = self
.commit_builder()
// This forces committing to the proposals in the proposal store:
.consume_proposal_store(true)
.load_psks(provider.storage())?
.build(provider.rand(), provider.crypto(), signer, |_| true)?
.stage_commit(provider)?
.into_contents();
Ok((
commit,
// Turn the [`Welcome`] to an [`MlsMessageOut`], if there is one
welcome.map(|welcome| MlsMessageOut::from_welcome(welcome, self.version())),
group_info,
))
}
/// Merge a [StagedCommit] into the group after inspection. As this advances
/// the epoch of the group, it also clears any pending commits.
pub fn merge_staged_commit<Provider: OpenMlsProvider>(
&mut self,
provider: &Provider,
staged_commit: StagedCommit,
) -> Result<(), MergeCommitError<Provider::StorageError>> {
// Check if we were removed from the group
if staged_commit.self_removed() {
self.group_state = MlsGroupState::Inactive;
}
provider
.storage()
.write_group_state(self.group_id(), &self.group_state)
.map_err(MergeCommitError::StorageError)?;
// Merge staged commit
self.merge_commit(provider, staged_commit)?;
// Extract and store the resumption psk for the current epoch
let resumption_psk = self.group_epoch_secrets().resumption_psk();
self.resumption_psk_store
.add(self.context().epoch(), resumption_psk.clone());
provider
.storage()
.write_resumption_psk_store(self.group_id(), &self.resumption_psk_store)
.map_err(MergeCommitError::StorageError)?;
// Delete own KeyPackageBundles
self.own_leaf_nodes.clear();
provider
.storage()
.delete_own_leaf_nodes(self.group_id())
.map_err(MergeCommitError::StorageError)?;
// Delete a potential pending commit
self.clear_pending_commit(provider.storage())
.map_err(MergeCommitError::StorageError)?;
Ok(())
}
/// Merges the pending [`StagedCommit`] if there is one, and
/// clears the field by setting it to `None`.
pub fn merge_pending_commit<Provider: OpenMlsProvider>(
&mut self,
provider: &Provider,
) -> Result<(), MergePendingCommitError<Provider::StorageError>> {
match &self.group_state {
MlsGroupState::PendingCommit(_) => {
let old_state = mem::replace(&mut self.group_state, MlsGroupState::Operational);
if let MlsGroupState::PendingCommit(pending_commit_state) = old_state {
self.merge_staged_commit(provider, (*pending_commit_state).into())?;
}
Ok(())
}
MlsGroupState::Inactive => Err(MlsGroupStateError::UseAfterEviction)?,
MlsGroupState::Operational => Ok(()),
}
}
/// Helper function to read decryption keypairs.
pub(super) fn read_decryption_keypairs(
&self,
provider: &impl OpenMlsProvider,
own_leaf_nodes: &[LeafNode],
) -> Result<(Vec<EncryptionKeyPair>, Vec<EncryptionKeyPair>), StageCommitError> {
// All keys from the previous epoch are potential decryption keypairs.
let old_epoch_keypairs = self.read_epoch_keypairs(provider.storage()).map_err(|e| {
log::error!("Error reading epoch keypairs: {:?}", e);
StageCommitError::MissingDecryptionKey
})?;
// If we are processing an update proposal that originally came from
// us, the keypair corresponding to the leaf in the update is also a
// potential decryption keypair.
let leaf_node_keypairs = own_leaf_nodes
.iter()
.map(|leaf_node| {
EncryptionKeyPair::read(provider, leaf_node.encryption_key())
.ok_or(StageCommitError::MissingDecryptionKey)
})
.collect::<Result<Vec<EncryptionKeyPair>, StageCommitError>>()?;
Ok((old_epoch_keypairs, leaf_node_keypairs))
}
/// This processing function does most of the semantic verifications.
/// It returns a [ProcessedMessage] enum.
/// Checks the following semantic validation:
/// - ValSem008
/// - ValSem010
/// - ValSem101
/// - ValSem102
/// - ValSem104
/// - ValSem106
/// - ValSem107
/// - ValSem108
/// - ValSem110
/// - ValSem111
/// - ValSem112
/// - ValSem113: All Proposals: The proposal type must be supported by all
/// members of the group
/// - ValSem200
/// - ValSem201
/// - ValSem202: Path must be the right length
/// - ValSem203: Path secrets must decrypt correctly
/// - ValSem204: Public keys from Path must be verified and match the
/// private keys from the direct path
/// - ValSem205
/// - ValSem240
/// - ValSem241
/// - ValSem242
/// - ValSem244
/// - ValSem246 (as part of ValSem010)
pub(crate) fn process_unverified_message<Provider: OpenMlsProvider>(
&self,
provider: &Provider,
unverified_message: UnverifiedMessage,
old_epoch_keypairs: Vec<EncryptionKeyPair>,
leaf_node_keypairs: Vec<EncryptionKeyPair>,
) -> Result<ProcessedMessage, ProcessMessageError> {
// Checks the following semantic validation:
// - ValSem010
// - ValSem246 (as part of ValSem010)
// - https://validation.openmls.tech/#valn1302
// - https://validation.openmls.tech/#valn1304
let (content, credential) =
unverified_message.verify(self.ciphersuite(), provider.crypto(), self.version())?;
match content.sender() {
Sender::Member(_) | Sender::NewMemberCommit | Sender::NewMemberProposal => {
let sender = content.sender().clone();
let authenticated_data = content.authenticated_data().to_owned();
let epoch = content.epoch();
let content = match content.content() {
FramedContentBody::Application(application_message) => {
ProcessedMessageContent::ApplicationMessage(ApplicationMessage::new(
application_message.as_slice().to_owned(),
))
}
FramedContentBody::Proposal(_) => {
let proposal = Box::new(QueuedProposal::from_authenticated_content_by_ref(
self.ciphersuite(),
provider.crypto(),
content,
)?);
if matches!(sender, Sender::NewMemberProposal) {
ProcessedMessageContent::ExternalJoinProposalMessage(proposal)
} else {
ProcessedMessageContent::ProposalMessage(proposal)
}
}
FramedContentBody::Commit(_) => {
let staged_commit = self.stage_commit(
&content,
old_epoch_keypairs,
leaf_node_keypairs,
provider,
)?;
ProcessedMessageContent::StagedCommitMessage(Box::new(staged_commit))
}
};
Ok(ProcessedMessage::new(
self.group_id().clone(),
epoch,
sender,
authenticated_data,
content,
credential,
))
}
Sender::External(_) => {
let sender = content.sender().clone();
let data = content.authenticated_data().to_owned();
match content.content() {
FramedContentBody::Application(_) => {
Err(ProcessMessageError::UnauthorizedExternalApplicationMessage)
}
FramedContentBody::Proposal(Proposal::Remove(_)) => {
let content = ProcessedMessageContent::ProposalMessage(Box::new(
QueuedProposal::from_authenticated_content_by_ref(
self.ciphersuite(),
provider.crypto(),
content,
)?,
));
Ok(ProcessedMessage::new(
self.group_id().clone(),
self.context().epoch(),
sender,
data,
content,
credential,
))
}
// TODO #151/#106
FramedContentBody::Proposal(_) => {
Err(ProcessMessageError::UnsupportedProposalType)
}
FramedContentBody::Commit(_) => unimplemented!(),
}
}
}
}
/// Performs framing validation and, if necessary, decrypts the given message.
///
/// Returns the [`DecryptedMessage`] if processing is successful, or a
/// [`ValidationError`] if it is not.
///
/// Checks the following semantic validation:
/// - ValSem002
/// - ValSem003
/// - ValSem006
/// - ValSem007 MembershipTag presence
/// - https://validation.openmls.tech/#valn1202
pub(crate) fn decrypt_message(
&mut self,
crypto: &impl OpenMlsCrypto,
message: ProtocolMessage,
sender_ratchet_configuration: &SenderRatchetConfiguration,
) -> Result<DecryptedMessage, ValidationError> {
// Checks the following semantic validation:
// - ValSem002
// - ValSem003
self.public_group.validate_framing(&message)?;
let epoch = message.epoch();
// Checks the following semantic validation:
// - ValSem006
// - ValSem007 MembershipTag presence
match message {
ProtocolMessage::PublicMessage(public_message) => {
// If the message is older than the current epoch, we need to fetch the correct secret tree first.
let message_secrets =
self.message_secrets_for_epoch(epoch).map_err(|e| match e {
SecretTreeError::TooDistantInThePast => ValidationError::NoPastEpochData,
_ => LibraryError::custom(
"Unexpected error while retrieving message secrets for epoch.",
)
.into(),
})?;
DecryptedMessage::from_inbound_public_message(
*public_message,
message_secrets,
message_secrets.serialized_context().to_vec(),
crypto,
self.ciphersuite(),
)
}
ProtocolMessage::PrivateMessage(ciphertext) => {
// If the message is older than the current epoch, we need to fetch the correct secret tree first
DecryptedMessage::from_inbound_ciphertext(
ciphertext,
crypto,
self,
sender_ratchet_configuration,
)
}
}
}
}