use std::{
collections::{BTreeMap, HashMap},
fmt,
ops::Deref,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc,
},
};
use matrix_sdk_common::locks::Mutex;
use ruma::{
api::client::keys::{
upload_keys,
upload_signatures::v3::{Request as SignatureUploadRequest, SignedKeys},
},
events::AnyToDeviceEvent,
serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId,
RoomId, SecondsSinceUnixEpoch, UInt, UserId,
};
use serde::{Deserialize, Serialize};
use serde_json::{value::RawValue as RawJsonValue, Value};
use sha2::{Digest, Sha256};
use tracing::{debug, info, trace, warn};
use vodozemac::{
olm::{
Account as InnerAccount, AccountPickle, IdentityKeys, OlmMessage, PreKeyMessage,
SessionConfig,
},
Curve25519PublicKey, Ed25519Signature, KeyId, PickleError,
};
use super::{
utility::SignJson, EncryptionSettings, InboundGroupSession, OutboundGroupSession,
PrivateCrossSigningIdentity, Session, SessionCreationError as MegolmSessionCreationError,
};
#[cfg(feature = "experimental-algorithms")]
use crate::types::events::room::encrypted::OlmV2Curve25519AesSha2Content;
use crate::{
error::{EventError, OlmResult, SessionCreationError},
identities::{MasterPubkey, ReadOnlyDevice},
requests::UploadSigningKeysRequest,
store::{Changes, Store},
types::{
events::{
olm_v1::AnyDecryptedOlmEvent,
room::encrypted::{
EncryptedToDeviceEvent, OlmV1Curve25519AesSha2Content,
ToDeviceEncryptedEventContent,
},
},
CrossSigningKey, DeviceKeys, EventEncryptionAlgorithm, OneTimeKey, SignedKey,
},
utilities::encode,
CryptoStoreError, OlmError, SignatureError,
};
#[derive(Debug, Clone)]
pub struct Account {
pub inner: ReadOnlyAccount,
pub store: Store,
}
#[derive(Debug, Clone)]
pub enum SessionType {
New(Session),
Existing(Session),
}
#[derive(Debug)]
pub struct InboundCreationResult {
pub session: Session,
pub plaintext: String,
}
impl SessionType {
#[cfg(test)]
pub fn session(self) -> Session {
match self {
SessionType::New(s) => s,
SessionType::Existing(s) => s,
}
}
}
#[derive(Debug)]
pub(crate) struct OlmDecryptionInfo {
pub sender: OwnedUserId,
pub session: SessionType,
pub message_hash: OlmMessageHash,
pub inbound_group_session: Option<InboundGroupSession>,
pub result: DecryptionResult,
}
#[derive(Debug)]
pub(crate) struct DecryptionResult {
pub event: AnyDecryptedOlmEvent,
pub raw_event: Raw<AnyToDeviceEvent>,
pub sender_key: Curve25519PublicKey,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OlmMessageHash {
pub sender_key: String,
pub hash: String,
}
impl OlmMessageHash {
fn new(sender_key: Curve25519PublicKey, ciphertext: &OlmMessage) -> Self {
let (message_type, ciphertext) = ciphertext.clone().to_parts();
let sender_key = sender_key.to_base64();
let sha = Sha256::new()
.chain_update(sender_key.as_bytes())
.chain_update([message_type as u8])
.chain_update(&ciphertext)
.finalize();
Self { sender_key, hash: encode(sha.as_slice()) }
}
}
impl Deref for Account {
type Target = ReadOnlyAccount;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl Account {
pub async fn save(&self) -> Result<(), CryptoStoreError> {
self.store.save_account(self.inner.clone()).await
}
async fn decrypt_olm_helper(
&self,
sender: &UserId,
sender_key: Curve25519PublicKey,
ciphertext: &OlmMessage,
) -> OlmResult<OlmDecryptionInfo> {
let message_hash = OlmMessageHash::new(sender_key, ciphertext);
match self.decrypt_olm_message(sender, sender_key, ciphertext).await {
Ok((session, result)) => Ok(OlmDecryptionInfo {
sender: sender.to_owned(),
session,
message_hash,
result,
inbound_group_session: None,
}),
Err(OlmError::SessionWedged(user_id, sender_key)) => {
if self.store.is_message_known(&message_hash).await? {
info!(
sender = sender.as_str(),
%sender_key, "An Olm message got replayed, decryption failed"
);
Err(OlmError::ReplayedMessage(user_id, sender_key))
} else {
Err(OlmError::SessionWedged(user_id, sender_key))
}
}
Err(e) => Err(e),
}
}
#[cfg(feature = "experimental-algorithms")]
async fn decrypt_olm_v2(
&self,
sender: &UserId,
content: &OlmV2Curve25519AesSha2Content,
) -> OlmResult<OlmDecryptionInfo> {
self.decrypt_olm_helper(sender, content.sender_key, &content.ciphertext).await
}
async fn decrypt_olm_v1(
&self,
sender: &UserId,
content: &OlmV1Curve25519AesSha2Content,
) -> OlmResult<OlmDecryptionInfo> {
if content.recipient_key != self.identity_keys().curve25519 {
warn!(
sender = sender.as_str(),
sender_key = content.sender_key.to_base64(),
"Olm event doesn't contain a ciphertext for our key"
);
Err(EventError::MissingCiphertext.into())
} else {
self.decrypt_olm_helper(sender, content.sender_key, &content.ciphertext).await
}
}
pub(crate) async fn decrypt_to_device_event(
&self,
event: &EncryptedToDeviceEvent,
) -> OlmResult<OlmDecryptionInfo> {
trace!(
sender = event.sender.as_str(),
algorithm = %event.content.algorithm(),
"Decrypting a to-device event"
);
match &event.content {
ToDeviceEncryptedEventContent::OlmV1Curve25519AesSha2(c) => {
self.decrypt_olm_v1(&event.sender, c).await
}
#[cfg(feature = "experimental-algorithms")]
ToDeviceEncryptedEventContent::OlmV2Curve25519AesSha2(c) => {
self.decrypt_olm_v2(&event.sender, c).await
}
ToDeviceEncryptedEventContent::Unknown(_) => {
warn!(
sender = event.sender.as_str(),
algorithm = %event.content.algorithm(),
"Error decrypting an to-device event, unsupported \
encryption algorithm"
);
Err(EventError::UnsupportedAlgorithm.into())
}
}
}
pub async fn receive_keys_upload_response(
&self,
response: &upload_keys::v3::Response,
) -> OlmResult<()> {
if !self.inner.shared() {
debug!("Marking account as shared");
}
self.inner.mark_as_shared();
debug!("Marking one-time keys as published");
self.update_key_counts(&response.one_time_key_counts, None).await;
self.inner.mark_keys_as_published().await;
self.store.save_account(self.inner.clone()).await?;
Ok(())
}
async fn decrypt_with_existing_sessions(
&self,
sender_key: Curve25519PublicKey,
message: &OlmMessage,
) -> OlmResult<Option<(Session, String)>> {
let s = self.store.get_sessions(&sender_key.to_base64()).await?;
let sessions = if let Some(s) = s {
s
} else {
return Ok(None);
};
let mut decrypted: Option<(Session, String)> = None;
for session in &mut *sessions.lock().await {
if let Ok(p) = session.decrypt(message).await {
decrypted = Some((session.clone(), p));
break;
} else {
continue;
}
}
Ok(decrypted)
}
async fn decrypt_olm_message(
&self,
sender: &UserId,
sender_key: Curve25519PublicKey,
message: &OlmMessage,
) -> OlmResult<(SessionType, DecryptionResult)> {
let (session, plaintext) =
if let Some(d) = self.decrypt_with_existing_sessions(sender_key, message).await? {
(SessionType::Existing(d.0), d.1)
} else {
match message {
OlmMessage::Normal(_) => {
warn!(
%sender,
%sender_key,
"Failed to decrypt a non-pre-key message with all \
available sessions",
);
return Err(OlmError::SessionWedged(sender.to_owned(), sender_key));
}
OlmMessage::PreKey(m) => {
let result = match self.inner.create_inbound_session(sender_key, m).await {
Ok(r) => r,
Err(e) => {
warn!(
%sender,
%sender_key,
session_keys = ?m.session_keys(),
"Failed to create a new Olm session from a \
pre-key message: {e:?}",
);
return Err(OlmError::SessionWedged(sender.to_owned(), sender_key));
}
};
let changes = Changes {
account: Some(self.inner.clone()),
sessions: vec![result.session.clone()],
..Default::default()
};
self.store.save_changes(changes).await?;
(SessionType::New(result.session), result.plaintext)
}
}
};
trace!(
%sender,
%sender_key,
"Successfully decrypted an Olm message"
);
match self.parse_decrypted_to_device_event(sender, sender_key, plaintext).await {
Ok(result) => Ok((session, result)),
Err(e) => {
match session {
SessionType::New(s) => {
let changes = Changes {
account: Some(self.inner.clone()),
sessions: vec![s],
..Default::default()
};
self.store.save_changes(changes).await?;
}
SessionType::Existing(s) => {
self.store.save_sessions(&[s]).await?;
}
}
warn!(
sender = sender.as_str(),
sender_key = sender_key.to_base64(),
error = ?e,
"A to-device message was successfully decrypted but \
parsing and checking the event fields failed"
);
Err(e)
}
}
}
async fn parse_decrypted_to_device_event(
&self,
sender: &UserId,
sender_key: Curve25519PublicKey,
plaintext: String,
) -> OlmResult<DecryptionResult> {
let event: AnyDecryptedOlmEvent = serde_json::from_str(&plaintext)?;
let identity_keys = self.inner.identity_keys();
if event.recipient() != self.user_id() {
Err(EventError::MismatchedSender(
event.recipient().to_owned(),
self.user_id().to_owned(),
)
.into())
} else if event.sender() != sender {
Err(EventError::MismatchedSender(event.sender().to_owned(), sender.to_owned()).into())
} else if identity_keys.ed25519 != event.recipient_keys().ed25519 {
Err(EventError::MismatchedKeys(
identity_keys.ed25519.into(),
event.recipient_keys().ed25519.into(),
)
.into())
} else {
if !matches!(event, AnyDecryptedOlmEvent::RoomKey(_)) {
if let Some(device) =
self.store.get_device_from_curve_key(event.sender(), sender_key).await?
{
if let Some(key) = device.ed25519_key() {
if key != event.keys().ed25519 {
return Err(EventError::MismatchedKeys(
key.into(),
event.keys().ed25519.into(),
)
.into());
}
} else {
return Err(EventError::MissingSigningKey.into());
}
} else {
return Err(EventError::MissingSigningKey.into());
}
}
Ok(DecryptionResult {
event,
raw_event: Raw::from_json(RawJsonValue::from_string(plaintext)?),
sender_key,
})
}
}
}
#[derive(Clone)]
pub struct ReadOnlyAccount {
pub user_id: Arc<UserId>,
pub device_id: Arc<DeviceId>,
inner: Arc<Mutex<InnerAccount>>,
pub identity_keys: Arc<IdentityKeys>,
shared: Arc<AtomicBool>,
uploaded_signed_key_count: Arc<AtomicU64>,
}
#[derive(Serialize, Deserialize)]
#[allow(missing_debug_implementations)]
pub struct PickledAccount {
pub user_id: OwnedUserId,
pub device_id: OwnedDeviceId,
pub pickle: AccountPickle,
pub shared: bool,
pub uploaded_signed_key_count: u64,
}
#[cfg(not(tarpaulin_include))]
impl fmt::Debug for ReadOnlyAccount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Account")
.field("identity_keys", &self.identity_keys())
.field("shared", &self.shared())
.finish()
}
}
impl ReadOnlyAccount {
const ALGORITHMS: &'static [&'static EventEncryptionAlgorithm] = &[
&EventEncryptionAlgorithm::OlmV1Curve25519AesSha2,
#[cfg(feature = "experimental-algorithms")]
&EventEncryptionAlgorithm::OlmV2Curve25519AesSha2,
&EventEncryptionAlgorithm::MegolmV1AesSha2,
#[cfg(feature = "experimental-algorithms")]
&EventEncryptionAlgorithm::MegolmV2AesSha2,
];
#[allow(clippy::ptr_arg)]
pub fn new(user_id: &UserId, device_id: &DeviceId) -> Self {
let account = InnerAccount::new();
let identity_keys = account.identity_keys();
Self {
user_id: user_id.into(),
device_id: device_id.into(),
inner: Arc::new(Mutex::new(account)),
identity_keys: Arc::new(identity_keys),
shared: Arc::new(AtomicBool::new(false)),
uploaded_signed_key_count: Arc::new(AtomicU64::new(0)),
}
}
pub fn user_id(&self) -> &UserId {
&self.user_id
}
pub fn device_id(&self) -> &DeviceId {
&self.device_id
}
pub fn identity_keys(&self) -> IdentityKeys {
*self.identity_keys
}
pub fn signing_key_id(&self) -> OwnedDeviceKeyId {
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id())
}
pub fn update_uploaded_key_count(&self, new_count: u64) {
self.uploaded_signed_key_count.store(new_count, Ordering::SeqCst);
}
pub fn uploaded_key_count(&self) -> u64 {
self.uploaded_signed_key_count.load(Ordering::SeqCst)
}
pub fn shared(&self) -> bool {
self.shared.load(Ordering::SeqCst)
}
pub fn mark_as_shared(&self) {
self.shared.store(true, Ordering::SeqCst);
}
pub async fn one_time_keys(&self) -> HashMap<KeyId, Curve25519PublicKey> {
self.inner.lock().await.one_time_keys()
}
pub async fn generate_one_time_keys_helper(&self, count: usize) {
self.inner.lock().await.generate_one_time_keys(count);
}
pub async fn max_one_time_keys(&self) -> usize {
self.inner.lock().await.max_number_of_one_time_keys()
}
pub(crate) async fn update_key_counts(
&self,
one_time_key_counts: &BTreeMap<DeviceKeyAlgorithm, UInt>,
unused_fallback_keys: Option<&[DeviceKeyAlgorithm]>,
) {
if let Some(count) = one_time_key_counts.get(&DeviceKeyAlgorithm::SignedCurve25519) {
let count: u64 = (*count).into();
let old_count = self.uploaded_key_count();
if count != old_count {
debug!(
"Updated uploaded one-time key count {} -> {count}.",
self.uploaded_key_count(),
);
}
self.update_uploaded_key_count(count);
}
if let Some(unused) = unused_fallback_keys {
if !unused.contains(&DeviceKeyAlgorithm::SignedCurve25519) {
self.generate_fallback_key_helper().await;
}
}
}
pub async fn generate_one_time_keys(&self) -> Option<u64> {
if self.one_time_keys().await.is_empty() {
let count = self.uploaded_key_count();
let max_keys = self.max_one_time_keys().await;
if count >= max_keys as u64 {
return None;
}
let key_count = (max_keys as u64) - count;
let key_count: usize = key_count.try_into().unwrap_or(max_keys);
self.generate_one_time_keys_helper(key_count).await;
Some(key_count as u64)
} else {
Some(0)
}
}
async fn generate_fallback_key_helper(&self) {
let mut account = self.inner.lock().await;
if account.fallback_key().is_empty() {
debug!(
"No unused fallback keys were found on the server, generating \
a new fallback key.",
);
account.generate_fallback_key();
}
}
async fn fallback_key(&self) -> HashMap<KeyId, Curve25519PublicKey> {
self.inner.lock().await.fallback_key()
}
pub async fn keys_for_upload(
&self,
) -> (
Option<DeviceKeys>,
BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>,
BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>,
) {
let device_keys = if !self.shared() { Some(self.device_keys().await) } else { None };
let one_time_keys = self.signed_one_time_keys().await;
let fallback_keys = self.signed_fallback_keys().await;
(device_keys, one_time_keys, fallback_keys)
}
pub async fn mark_keys_as_published(&self) {
self.inner.lock().await.mark_keys_as_published();
}
pub async fn sign(&self, string: &str) -> Ed25519Signature {
self.inner.lock().await.sign(string)
}
#[cfg(feature = "backups_v1")]
pub fn has_signed_raw(
&self,
signatures: &crate::types::Signatures,
canonical_json: &str,
) -> Result<(), SignatureError> {
use crate::olm::utility::VerifyJson;
let signing_key = self.identity_keys.ed25519;
signing_key.verify_canonicalized_json(
&self.user_id,
&DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signatures,
canonical_json,
)
}
pub async fn pickle(&self) -> PickledAccount {
let pickle = self.inner.lock().await.pickle();
PickledAccount {
user_id: self.user_id().to_owned(),
device_id: self.device_id().to_owned(),
pickle,
shared: self.shared(),
uploaded_signed_key_count: self.uploaded_key_count(),
}
}
pub fn from_pickle(pickle: PickledAccount) -> Result<Self, PickleError> {
let account: vodozemac::olm::Account = pickle.pickle.into();
let identity_keys = account.identity_keys();
Ok(Self {
user_id: (*pickle.user_id).into(),
device_id: (*pickle.device_id).into(),
inner: Arc::new(Mutex::new(account)),
identity_keys: Arc::new(identity_keys),
shared: Arc::new(AtomicBool::from(pickle.shared)),
uploaded_signed_key_count: Arc::new(AtomicU64::new(pickle.uploaded_signed_key_count)),
})
}
pub fn unsigned_device_keys(&self) -> DeviceKeys {
let identity_keys = self.identity_keys();
let keys = BTreeMap::from([
(
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Curve25519, &self.device_id),
identity_keys.curve25519.into(),
),
(
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.device_id),
identity_keys.ed25519.into(),
),
]);
DeviceKeys::new(
(*self.user_id).to_owned(),
(*self.device_id).to_owned(),
Self::ALGORITHMS.iter().map(|a| (**a).clone()).collect(),
keys,
Default::default(),
)
}
pub async fn device_keys(&self) -> DeviceKeys {
let mut device_keys = self.unsigned_device_keys();
let json_device_keys =
serde_json::to_value(&device_keys).expect("device key is always safe to serialize");
let signature = self
.sign_json(json_device_keys)
.await
.expect("Newly created device keys can always be signed");
device_keys.signatures.add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, &self.device_id),
signature,
);
device_keys
}
pub async fn bootstrap_cross_signing(
&self,
) -> (PrivateCrossSigningIdentity, UploadSigningKeysRequest, SignatureUploadRequest) {
PrivateCrossSigningIdentity::with_account(self).await
}
pub async fn sign_cross_signing_key(
&self,
cross_signing_key: &mut CrossSigningKey,
) -> Result<(), SignatureError> {
let signature = self.sign_json(serde_json::to_value(&cross_signing_key)?).await?;
cross_signing_key.signatures.add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signature,
);
Ok(())
}
pub async fn sign_master_key(
&self,
master_key: MasterPubkey,
) -> Result<SignatureUploadRequest, SignatureError> {
let public_key =
master_key.get_first_key().ok_or(SignatureError::MissingSigningKey)?.to_base64().into();
let mut cross_signing_key: CrossSigningKey = master_key.as_ref().clone();
cross_signing_key.signatures.clear();
self.sign_cross_signing_key(&mut cross_signing_key).await?;
let mut user_signed_keys = SignedKeys::new();
user_signed_keys.add_cross_signing_keys(public_key, cross_signing_key.to_raw());
let signed_keys = [(self.user_id().to_owned(), user_signed_keys)].into();
Ok(SignatureUploadRequest::new(signed_keys))
}
pub async fn sign_json(&self, json: Value) -> Result<Ed25519Signature, SignatureError> {
self.inner.lock().await.sign_json(json)
}
pub async fn signed_one_time_keys(
&self,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let _ = self.generate_one_time_keys().await;
let one_time_keys = self.one_time_keys().await;
if one_time_keys.is_empty() {
BTreeMap::new()
} else {
self.signed_keys(one_time_keys, false).await
}
}
pub async fn signed_fallback_keys(
&self,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let fallback_key = self.fallback_key().await;
if fallback_key.is_empty() {
BTreeMap::new()
} else {
self.signed_keys(fallback_key, true).await
}
}
async fn signed_keys(
&self,
keys: HashMap<KeyId, Curve25519PublicKey>,
fallback: bool,
) -> BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>> {
let mut keys_map = BTreeMap::new();
for (key_id, key) in keys {
let signed_key = self.sign_key(key, fallback).await;
keys_map.insert(
DeviceKeyId::from_parts(
DeviceKeyAlgorithm::SignedCurve25519,
key_id.to_base64().as_str().into(),
),
signed_key.into_raw(),
);
}
keys_map
}
async fn sign_key(&self, key: Curve25519PublicKey, fallback: bool) -> SignedKey {
let mut key = if fallback {
SignedKey::new_fallback(key.to_owned())
} else {
SignedKey::new(key.to_owned())
};
let signature = self
.sign_json(serde_json::to_value(&key).expect("Can't serialize a signed key"))
.await
.expect("Newly created one-time keys can always be signed");
key.signatures_mut().add_signature(
self.user_id().to_owned(),
DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, self.device_id()),
signature,
);
key
}
pub async fn create_outbound_session_helper(
&self,
config: SessionConfig,
identity_key: Curve25519PublicKey,
one_time_key: Curve25519PublicKey,
fallback_used: bool,
) -> Session {
let session =
self.inner.lock().await.create_outbound_session(config, identity_key, one_time_key);
let now = SecondsSinceUnixEpoch::now();
let session_id = session.session_id();
Session {
user_id: self.user_id.clone(),
device_id: self.device_id.clone(),
our_identity_keys: self.identity_keys.clone(),
inner: Arc::new(Mutex::new(session)),
session_id: session_id.into(),
sender_key: identity_key,
created_using_fallback_key: fallback_used,
creation_time: now,
last_use_time: now,
}
}
pub async fn create_outbound_session(
&self,
device: ReadOnlyDevice,
key_map: &BTreeMap<OwnedDeviceKeyId, Raw<ruma::encryption::OneTimeKey>>,
) -> Result<Session, SessionCreationError> {
let one_time_key = key_map.values().next().ok_or_else(|| {
SessionCreationError::OneTimeKeyMissing(
device.user_id().to_owned(),
device.device_id().into(),
)
})?;
let one_time_key: SignedKey = match one_time_key.deserialize_as() {
Ok(OneTimeKey::SignedKey(k)) => k,
Ok(OneTimeKey::Key(_)) => {
return Err(SessionCreationError::OneTimeKeyNotSigned(
device.user_id().to_owned(),
device.device_id().into(),
));
}
Ok(_) => {
return Err(SessionCreationError::OneTimeKeyUnknown(
device.user_id().to_owned(),
device.device_id().into(),
));
}
Err(e) => return Err(SessionCreationError::InvalidJson(e)),
};
device.verify_one_time_key(&one_time_key).map_err(|e| {
SessionCreationError::InvalidSignature(
device.user_id().to_owned(),
device.device_id().into(),
e,
)
})?;
let identity_key = device.curve25519_key().ok_or_else(|| {
SessionCreationError::DeviceMissingCurveKey(
device.user_id().to_owned(),
device.device_id().into(),
)
})?;
let is_fallback = one_time_key.fallback();
let one_time_key = one_time_key.key();
let config = device.olm_session_config();
Ok(self
.create_outbound_session_helper(config, identity_key, one_time_key, is_fallback)
.await)
}
pub async fn create_inbound_session(
&self,
their_identity_key: Curve25519PublicKey,
message: &PreKeyMessage,
) -> Result<InboundCreationResult, SessionCreationError> {
debug!(
sender_key = %their_identity_key,
session_keys = ?message.session_keys(),
"Creating a new Olm session from a pre-key message"
);
let result = self.inner.lock().await.create_inbound_session(their_identity_key, message)?;
let now = SecondsSinceUnixEpoch::now();
let session_id = result.session.session_id();
let session = Session {
user_id: self.user_id.clone(),
device_id: self.device_id.clone(),
our_identity_keys: self.identity_keys.clone(),
inner: Arc::new(Mutex::new(result.session)),
session_id: session_id.into(),
sender_key: their_identity_key,
created_using_fallback_key: false,
creation_time: now,
last_use_time: now,
};
let plaintext = String::from_utf8_lossy(&result.plaintext).to_string();
Ok(InboundCreationResult { session, plaintext })
}
pub async fn create_group_session_pair(
&self,
room_id: &RoomId,
settings: EncryptionSettings,
) -> Result<(OutboundGroupSession, InboundGroupSession), MegolmSessionCreationError> {
trace!(?room_id, algorithm = settings.algorithm.as_str(), "Creating a new room key");
let visibility = settings.history_visibility.clone();
let algorithm = settings.algorithm.to_owned();
let outbound = OutboundGroupSession::new(
self.device_id.clone(),
self.identity_keys.clone(),
room_id,
settings,
)?;
let identity_keys = self.identity_keys();
let sender_key = identity_keys.curve25519;
let signing_key = identity_keys.ed25519;
let inbound = InboundGroupSession::new(
sender_key,
signing_key,
room_id,
&outbound.session_key().await,
algorithm,
Some(visibility),
)?;
Ok((outbound, inbound))
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub async fn create_group_session_pair_with_defaults(
&self,
room_id: &RoomId,
) -> (OutboundGroupSession, InboundGroupSession) {
self.create_group_session_pair(room_id, EncryptionSettings::default())
.await
.expect("Can't create default group session pair")
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
pub async fn create_session_for(&self, other: &ReadOnlyAccount) -> (Session, Session) {
use ruma::events::dummy::ToDeviceDummyEventContent;
other.generate_one_time_keys_helper(1).await;
let one_time = other.signed_one_time_keys().await;
let device = ReadOnlyDevice::from_account(other).await;
let mut our_session =
self.create_outbound_session(device.clone(), &one_time).await.unwrap();
other.mark_keys_as_published().await;
let message = our_session
.encrypt(
&device,
"m.dummy",
serde_json::to_value(ToDeviceDummyEventContent::new()).unwrap(),
)
.await
.unwrap()
.deserialize()
.unwrap();
#[cfg(feature = "experimental-algorithms")]
let content = if let ToDeviceEncryptedEventContent::OlmV2Curve25519AesSha2(c) = message {
c
} else {
panic!("Invalid encrypted event algorithm {}", message.algorithm());
};
#[cfg(not(feature = "experimental-algorithms"))]
let content = if let ToDeviceEncryptedEventContent::OlmV1Curve25519AesSha2(c) = message {
c
} else {
panic!("Invalid encrypted event algorithm {}", message.algorithm());
};
let prekey = if let OlmMessage::PreKey(m) = content.ciphertext {
m
} else {
panic!("Wrong Olm message type");
};
let our_device = ReadOnlyDevice::from_account(self).await;
let other_session = other
.create_inbound_session(our_device.curve25519_key().unwrap(), &prekey)
.await
.unwrap();
(our_session, other_session.session)
}
}
impl PartialEq for ReadOnlyAccount {
fn eq(&self, other: &Self) -> bool {
self.identity_keys() == other.identity_keys() && self.shared() == other.shared()
}
}
#[cfg(test)]
mod tests {
use std::{
collections::{BTreeMap, BTreeSet},
ops::Deref,
};
use matrix_sdk_test::async_test;
use ruma::{device_id, user_id, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, UserId};
use super::ReadOnlyAccount;
use crate::error::OlmResult as Result;
fn user_id() -> &'static UserId {
user_id!("@alice:localhost")
}
fn device_id() -> &'static DeviceId {
device_id!("DEVICEID")
}
#[async_test]
async fn one_time_key_creation() -> Result<()> {
let account = ReadOnlyAccount::new(user_id(), device_id());
let (_, one_time_keys, _) = account.keys_for_upload().await;
assert!(!one_time_keys.is_empty());
let (_, second_one_time_keys, _) = account.keys_for_upload().await;
assert!(!second_one_time_keys.is_empty());
let device_key_ids: BTreeSet<&DeviceKeyId> =
one_time_keys.keys().map(Deref::deref).collect();
let second_device_key_ids: BTreeSet<&DeviceKeyId> =
second_one_time_keys.keys().map(Deref::deref).collect();
assert_eq!(device_key_ids, second_device_key_ids);
account.mark_keys_as_published().await;
account.update_uploaded_key_count(50);
let (_, third_one_time_keys, _) = account.keys_for_upload().await;
assert!(third_one_time_keys.is_empty());
account.update_uploaded_key_count(0);
let (_, fourth_one_time_keys, _) = account.keys_for_upload().await;
assert!(!fourth_one_time_keys.is_empty());
let fourth_device_key_ids: BTreeSet<&DeviceKeyId> =
fourth_one_time_keys.keys().map(Deref::deref).collect();
assert_ne!(device_key_ids, fourth_device_key_ids);
Ok(())
}
#[async_test]
async fn fallback_key_creation() -> Result<()> {
let account = ReadOnlyAccount::new(user_id(), device_id());
let (_, _, fallback_keys) = account.keys_for_upload().await;
assert!(fallback_keys.is_empty());
let one_time_keys = BTreeMap::from([(DeviceKeyAlgorithm::SignedCurve25519, 50u8.into())]);
account.update_key_counts(&one_time_keys, None).await;
let (_, _, fallback_keys) = account.keys_for_upload().await;
assert!(fallback_keys.is_empty());
let unused_fallback_keys = &[];
account.update_key_counts(&one_time_keys, Some(unused_fallback_keys.as_ref())).await;
let (_, _, fallback_keys) = account.keys_for_upload().await;
assert!(!fallback_keys.is_empty());
account.mark_keys_as_published().await;
let unused_fallback_keys = &[DeviceKeyAlgorithm::SignedCurve25519];
account.update_key_counts(&one_time_keys, Some(unused_fallback_keys.as_ref())).await;
let (_, _, fallback_keys) = account.keys_for_upload().await;
assert!(fallback_keys.is_empty());
Ok(())
}
}