1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
1415use ruma::{DeviceKeyAlgorithm, OwnedRoomId};
16use serde::{Deserialize, Serialize};
1718mod inbound;
19mod outbound;
20mod sender_data;
21pub(crate) mod sender_data_finder;
2223pub use inbound::{InboundGroupSession, PickledInboundGroupSession};
24pub(crate) use outbound::ShareState;
25pub use outbound::{
26 EncryptionSettings, OutboundGroupSession, PickledOutboundGroupSession, ShareInfo,
27};
28pub use sender_data::{KnownSenderData, SenderData, SenderDataType};
29use thiserror::Error;
30pub use vodozemac::megolm::{ExportedSessionKey, SessionKey};
31use vodozemac::{megolm::SessionKeyDecodeError, Curve25519PublicKey};
3233#[cfg(feature = "experimental-algorithms")]
34use crate::types::events::forwarded_room_key::ForwardedMegolmV2AesSha2Content;
35use crate::types::{
36 deserialize_curve_key, deserialize_curve_key_vec,
37 events::forwarded_room_key::{ForwardedMegolmV1AesSha2Content, ForwardedRoomKeyContent},
38 serialize_curve_key, serialize_curve_key_vec, EventEncryptionAlgorithm, SigningKey,
39 SigningKeys,
40};
4142/// An error type for the creation of group sessions.
43#[derive(Debug, Error)]
44pub enum SessionCreationError {
45/// The provided algorithm is not supported.
46#[error("The provided algorithm is not supported: {0}")]
47Algorithm(EventEncryptionAlgorithm),
48/// The room key key couldn't be decoded.
49#[error(transparent)]
50Decode(#[from] SessionKeyDecodeError),
51}
5253/// An error type for the export of inbound group sessions.
54///
55/// Exported inbound group sessions will be either uploaded as backups, sent as
56/// `m.forwarded_room_key`s, or exported into a file backup.
57#[derive(Debug, Error)]
58pub enum SessionExportError {
59/// The provided algorithm is not supported.
60#[error("The provided algorithm is not supported: {0}")]
61Algorithm(EventEncryptionAlgorithm),
62/// The session export is missing a claimed Ed25519 sender key.
63#[error("The provided room key export is missing a claimed Ed25519 sender key")]
64MissingEd25519Key,
65}
6667/// An exported version of an [`InboundGroupSession`].
68///
69/// This can be used to share the `InboundGroupSession` in an exported file.
70///
71/// See <https://spec.matrix.org/v1.13/client-server-api/#key-export-format>.
72#[derive(Deserialize, Serialize)]
73#[allow(missing_debug_implementations)]
74pub struct ExportedRoomKey {
75/// The encryption algorithm that the session uses.
76pub algorithm: EventEncryptionAlgorithm,
7778/// The room where the session is used.
79pub room_id: OwnedRoomId,
8081/// The Curve25519 key of the device which initiated the session originally.
82#[serde(deserialize_with = "deserialize_curve_key", serialize_with = "serialize_curve_key")]
83pub sender_key: Curve25519PublicKey,
8485/// The ID of the session that the key is for.
86pub session_id: String,
8788/// The key for the session.
89pub session_key: ExportedSessionKey,
9091/// The Ed25519 key of the device which initiated the session originally.
92#[serde(default)]
93pub sender_claimed_keys: SigningKeys<DeviceKeyAlgorithm>,
9495/// Chain of Curve25519 keys through which this session was forwarded, via
96 /// m.forwarded_room_key events.
97#[serde(
98 default,
99 deserialize_with = "deserialize_curve_key_vec",
100 serialize_with = "serialize_curve_key_vec"
101)]
102pub forwarding_curve25519_key_chain: Vec<Curve25519PublicKey>,
103104/// Whether this [`ExportedRoomKey`] can be shared with users who are
105 /// invited to the room in the future, allowing access to history, as
106 /// defined in [MSC3061].
107 ///
108 /// [MSC3061]: https://github.com/matrix-org/matrix-spec-proposals/pull/3061
109#[serde(default, rename = "org.matrix.msc3061.shared_history")]
110pub shared_history: bool,
111}
112113impl ExportedRoomKey {
114/// Create an `ExportedRoomKey` from a `BackedUpRoomKey`.
115 ///
116 /// This can be used when importing the keys from a backup into the store.
117pub fn from_backed_up_room_key(
118 room_id: OwnedRoomId,
119 session_id: String,
120 room_key: BackedUpRoomKey,
121 ) -> Self {
122let BackedUpRoomKey {
123 algorithm,
124 sender_key,
125 session_key,
126 sender_claimed_keys,
127 forwarding_curve25519_key_chain,
128 shared_history,
129 } = room_key;
130131Self {
132 algorithm,
133 room_id,
134 sender_key,
135 session_id,
136 session_key,
137 sender_claimed_keys,
138 forwarding_curve25519_key_chain,
139 shared_history,
140 }
141 }
142}
143144/// A backed up version of an [`InboundGroupSession`].
145///
146/// This can be used to back up the [`InboundGroupSession`] to the server using
147/// [server-side key backups].
148///
149/// See <https://spec.matrix.org/v1.13/client-server-api/#definition-backedupsessiondata>.
150///
151/// [server-side key backups]: https://spec.matrix.org/v1.13/client-server-api/#server-side-key-backups
152#[derive(Deserialize, Serialize)]
153#[allow(missing_debug_implementations)]
154pub struct BackedUpRoomKey {
155/// The encryption algorithm that the session uses.
156pub algorithm: EventEncryptionAlgorithm,
157158/// The Curve25519 key of the device which initiated the session originally.
159#[serde(deserialize_with = "deserialize_curve_key", serialize_with = "serialize_curve_key")]
160pub sender_key: Curve25519PublicKey,
161162/// The key for the session.
163pub session_key: ExportedSessionKey,
164165/// The Ed25519 key of the device which initiated the session originally.
166pub sender_claimed_keys: SigningKeys<DeviceKeyAlgorithm>,
167168/// Chain of Curve25519 keys through which this session was forwarded, via
169 /// `m.forwarded_room_key` events.
170#[serde(
171 default,
172 deserialize_with = "deserialize_curve_key_vec",
173 serialize_with = "serialize_curve_key_vec"
174)]
175pub forwarding_curve25519_key_chain: Vec<Curve25519PublicKey>,
176177/// Whether this [`BackedUpRoomKey`] can be shared with users who are
178 /// invited to the room in the future, allowing access to history, as
179 /// defined in [MSC3061].
180 ///
181 /// [MSC3061]: https://github.com/matrix-org/matrix-spec-proposals/pull/3061
182#[serde(default, rename = "org.matrix.msc3061.shared_history")]
183pub shared_history: bool,
184}
185186impl TryFrom<ExportedRoomKey> for ForwardedRoomKeyContent {
187type Error = SessionExportError;
188189/// Convert an exported room key into a content for a forwarded room key
190 /// event.
191 ///
192 /// This will fail if the exported room key doesn't contain an Ed25519
193 /// claimed sender key.
194fn try_from(room_key: ExportedRoomKey) -> Result<ForwardedRoomKeyContent, Self::Error> {
195match room_key.algorithm {
196 EventEncryptionAlgorithm::MegolmV1AesSha2 => {
197// The forwarded room key content only supports a single claimed sender
198 // key and it requires it to be a Ed25519 key. This here will be lossy
199 // conversion since we're dropping all other key types.
200 //
201 // This was fixed by the megolm v2 content. Hopefully we'll deprecate megolm v1
202 // before we have multiple signing keys.
203if let Some(SigningKey::Ed25519(claimed_ed25519_key)) =
204 room_key.sender_claimed_keys.get(&DeviceKeyAlgorithm::Ed25519)
205 {
206Ok(ForwardedRoomKeyContent::MegolmV1AesSha2(
207 ForwardedMegolmV1AesSha2Content {
208 room_id: room_key.room_id,
209 session_id: room_key.session_id,
210 session_key: room_key.session_key,
211 claimed_sender_key: room_key.sender_key,
212 claimed_ed25519_key: *claimed_ed25519_key,
213 forwarding_curve25519_key_chain: room_key
214 .forwarding_curve25519_key_chain
215 .clone(),
216 other: Default::default(),
217 }
218 .into(),
219 ))
220 } else {
221Err(SessionExportError::MissingEd25519Key)
222 }
223 }
224#[cfg(feature = "experimental-algorithms")]
225EventEncryptionAlgorithm::MegolmV2AesSha2 => {
226Ok(ForwardedRoomKeyContent::MegolmV2AesSha2(
227 ForwardedMegolmV2AesSha2Content {
228 room_id: room_key.room_id,
229 session_id: room_key.session_id,
230 session_key: room_key.session_key,
231 claimed_sender_key: room_key.sender_key,
232 claimed_signing_keys: room_key.sender_claimed_keys,
233 other: Default::default(),
234 }
235 .into(),
236 ))
237 }
238_ => Err(SessionExportError::Algorithm(room_key.algorithm)),
239 }
240 }
241}
242243impl From<ExportedRoomKey> for BackedUpRoomKey {
244fn from(value: ExportedRoomKey) -> Self {
245let ExportedRoomKey {
246 algorithm,
247 room_id: _,
248 sender_key,
249 session_id: _,
250 session_key,
251 sender_claimed_keys,
252 forwarding_curve25519_key_chain,
253 shared_history,
254 } = value;
255256Self {
257 algorithm,
258 sender_key,
259 session_key,
260 sender_claimed_keys,
261 forwarding_curve25519_key_chain,
262 shared_history,
263 }
264 }
265}
266267impl TryFrom<ForwardedRoomKeyContent> for ExportedRoomKey {
268type Error = SessionExportError;
269270/// Convert the content of a forwarded room key into a exported room key.
271fn try_from(forwarded_key: ForwardedRoomKeyContent) -> Result<Self, Self::Error> {
272let algorithm = forwarded_key.algorithm();
273274match forwarded_key {
275 ForwardedRoomKeyContent::MegolmV1AesSha2(content) => {
276let mut sender_claimed_keys = SigningKeys::new();
277 sender_claimed_keys
278 .insert(DeviceKeyAlgorithm::Ed25519, content.claimed_ed25519_key.into());
279280Ok(Self {
281 algorithm,
282 room_id: content.room_id,
283 session_id: content.session_id,
284 forwarding_curve25519_key_chain: content.forwarding_curve25519_key_chain,
285 sender_claimed_keys,
286 sender_key: content.claimed_sender_key,
287 session_key: content.session_key,
288 shared_history: false,
289 })
290 }
291#[cfg(feature = "experimental-algorithms")]
292ForwardedRoomKeyContent::MegolmV2AesSha2(content) => Ok(Self {
293 algorithm,
294 room_id: content.room_id,
295 session_id: content.session_id,
296 forwarding_curve25519_key_chain: Default::default(),
297 sender_claimed_keys: content.claimed_signing_keys,
298 sender_key: content.claimed_sender_key,
299 session_key: content.session_key,
300 shared_history: false,
301 }),
302 ForwardedRoomKeyContent::Unknown(c) => Err(SessionExportError::Algorithm(c.algorithm)),
303 }
304 }
305}
306307#[cfg(test)]
308mod tests {
309use serde_json::json;
310311use super::BackedUpRoomKey;
312313#[test]
314fn test_deserialize_backed_up_key() {
315let data = json!({
316"algorithm": "m.megolm.v1.aes-sha2",
317"room_id": "!room:id",
318"sender_key": "FOvlmz18LLI3k/llCpqRoKT90+gFF8YhuL+v1YBXHlw",
319"session_id": "/2K+V777vipCxPZ0gpY9qcpz1DYaXwuMRIu0UEP0Wa0",
320"session_key": "AQAAAAAclzWVMeWBKH+B/WMowa3rb4ma3jEl6n5W4GCs9ue65CruzD3ihX+85pZ9hsV9Bf6fvhjp76WNRajoJYX0UIt7aosjmu0i+H+07hEQ0zqTKpVoSH0ykJ6stAMhdr6Q4uW5crBmdTTBIsqmoWsNJZKKoE2+ldYrZ1lrFeaJbjBIY/9ivle++74qQsT2dIKWPanKc9Q2Gl8LjESLtFBD9Fmt",
321"sender_claimed_keys": {
322"ed25519": "F4P7f1Z0RjbiZMgHk1xBCG3KC4/Ng9PmxLJ4hQ13sHA"
323},
324"forwarding_curve25519_key_chain": ["DBPC2zr6c9qimo9YRFK3RVr0Two/I6ODb9mbsToZN3Q", "bBc/qzZFOOKshMMT+i4gjS/gWPDoKfGmETs9yfw9430"]
325 });
326327let backed_up_room_key: BackedUpRoomKey = serde_json::from_value(data)
328 .expect("We should be able to deserialize the backed up room key.");
329assert_eq!(
330 backed_up_room_key.forwarding_curve25519_key_chain.len(),
3312,
332"The number of forwarding Curve25519 chains should be two."
333);
334 }
335}