Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support to export into libolm pickles #95

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Matrix clients, such as [SAS][sas].

- [Olm](https://matrix-org.github.io/vodozemac/vodozemac/olm/index.html)
- [Megolm](https://matrix-org.github.io/vodozemac/vodozemac/megolm/index.html)
- libolm pickle format (read-only)
- libolm pickle format
- Modern pickle format
- [SAS (Short Authentication Strings)](https://matrix-org.github.io/vodozemac/vodozemac/sas/index.html)

Expand Down
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,19 @@ pub enum LibolmPickleError {
/// Olm session needs to have at least one of them.
#[error("The pickle didn't contain a valid Olm session")]
InvalidSession,
/// The session contains a chain index that is too big to be put into a
/// libolm pickle. Vodozemac uses an `u64` for its chain index, while libolm
/// uses an u32.
#[error(
"The session contains a chain index that is too big to be put into a libolm pickle: {0}"
)]
ChainIndexTooBig(u64),
/// The payload of the pickle could not be decoded.
#[error(transparent)]
Decode(#[from] matrix_pickle::DecodeError),
/// The object could not be encoded as a pickle.
#[error(transparent)]
Encode(#[from] matrix_pickle::EncodeError),
}

/// Error type describing the different ways message decoding can fail.
Expand Down
103 changes: 74 additions & 29 deletions src/megolm/group_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,45 +141,39 @@ impl GroupSession {
pickle.into()
}

/// Create a [`GroupSession`] object by unpickling a session pickle
/// in libolm legacy pickle format.
///
/// Such pickles are encrypted and need to first be decrypted using
/// `pickle_key`.
#[cfg(feature = "libolm-compat")]
pub fn from_libolm_pickle(
pickle: &str,
pickle_key: &[u8],
) -> Result<Self, crate::LibolmPickleError> {
use matrix_pickle::Decode;
use zeroize::Zeroize;

use crate::{
megolm::libolm::LibolmRatchetPickle,
utilities::{unpickle_libolm, LibolmEd25519Keypair},
};

#[derive(Zeroize, Decode)]
#[zeroize(drop)]
struct Pickle {
version: u32,
ratchet: LibolmRatchetPickle,
ed25519_keypair: LibolmEd25519Keypair,
}
use libolm::{Pickle, PICKLE_VERSION};

impl TryFrom<Pickle> for GroupSession {
type Error = crate::LibolmPickleError;
use crate::utilities::unpickle_libolm;

fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
// Removing the borrow doesn't work and clippy complains about
// this on nightly.
#[allow(clippy::needless_borrow)]
let ratchet = (&pickle.ratchet).into();
let signing_key =
Ed25519Keypair::from_expanded_key(&pickle.ed25519_keypair.private_key)?;
unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
}

Ok(Self { ratchet, signing_key, config: SessionConfig::version_1() })
}
}
/// Pickle an [`GroupSession`] into a libolm pickle format.
///
/// This pickle can be restored using the
/// [`InboundGroupSession::from_libolm_pickle`] method, or can be used in
/// the [`libolm`] C library.
///
/// The pickle will be encryptd using the pickle key.
///
/// [`libolm`]: https://gitlab.matrix.org/matrix-org/olm/
#[cfg(feature = "libolm-compat")]
pub fn to_libolm_pickle(&self, pickle_key: &[u8]) -> Result<String, crate::LibolmPickleError> {
use libolm::Pickle;

const PICKLE_VERSION: u32 = 1;
use crate::utilities::pickle_libolm;

unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
pickle_libolm::<Pickle>(self.into(), pickle_key)
}
}

Expand Down Expand Up @@ -215,3 +209,54 @@ impl From<GroupSessionPickle> for GroupSession {
Self { ratchet: pickle.ratchet, signing_key: pickle.signing_key, config: pickle.config }
}
}

#[cfg(feature = "libolm-compat")]
mod libolm {
use matrix_pickle::{Decode, Encode};
use zeroize::Zeroize;

use super::GroupSession;
use crate::{
megolm::{libolm::LibolmRatchetPickle, SessionConfig},
utilities::LibolmEd25519Keypair,
Ed25519Keypair,
};

pub const PICKLE_VERSION: u32 = 1;

#[derive(Zeroize, Decode, Encode)]
#[zeroize(drop)]
pub struct Pickle {
version: u32,
ratchet: LibolmRatchetPickle,
ed25519_keypair: LibolmEd25519Keypair,
}

impl From<&GroupSession> for Pickle {
fn from(g: &GroupSession) -> Self {
Self {
version: PICKLE_VERSION,
ratchet: (&g.ratchet).into(),
ed25519_keypair: LibolmEd25519Keypair {
public_key: g.signing_key.public_key().as_bytes().to_owned(),
private_key: g.signing_key.expanded_secret_key(),
},
}
}
}

impl TryFrom<Pickle> for GroupSession {
type Error = crate::LibolmPickleError;

fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
// Removing the borrow doesn't work and clippy complains about
// this on nightly.
#[allow(clippy::needless_borrow)]
let ratchet = (&pickle.ratchet).into();
let signing_key =
Ed25519Keypair::from_expanded_key(&pickle.ed25519_keypair.private_key)?;

Ok(Self { ratchet, signing_key, config: SessionConfig::version_1() })
}
}
}
117 changes: 81 additions & 36 deletions src/megolm/inbound_group_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use hmac::digest::MacError;
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use thiserror::Error;
use zeroize::Zeroize;

use super::{
default_config,
Expand Down Expand Up @@ -366,52 +365,39 @@ impl InboundGroupSession {
Self::from(pickle)
}

/// Create a [`InboundGroupSession`] object by unpickling a session pickle
/// in libolm legacy pickle format.
///
/// Such pickles are encrypted and need to first be decrypted using
/// `pickle_key`.
#[cfg(feature = "libolm-compat")]
pub fn from_libolm_pickle(
pickle: &str,
pickle_key: &[u8],
) -> Result<Self, crate::LibolmPickleError> {
use matrix_pickle::Decode;
use libolm::{Pickle, PICKLE_VERSION};

use super::libolm::LibolmRatchetPickle;
use crate::utilities::unpickle_libolm;

#[derive(Zeroize, Decode)]
#[zeroize(drop)]
struct Pickle {
version: u32,
initial_ratchet: LibolmRatchetPickle,
latest_ratchet: LibolmRatchetPickle,
signing_key: [u8; 32],
signing_key_verified: bool,
}
unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
}

impl TryFrom<Pickle> for InboundGroupSession {
type Error = crate::LibolmPickleError;

fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
// Removing the borrow doesn't work and clippy complains about
// this on nightly.
#[allow(clippy::needless_borrow)]
let initial_ratchet = (&pickle.initial_ratchet).into();
#[allow(clippy::needless_borrow)]
let latest_ratchet = (&pickle.latest_ratchet).into();
let signing_key = Ed25519PublicKey::from_slice(&pickle.signing_key)?;
let signing_key_verified = pickle.signing_key_verified;

Ok(Self {
initial_ratchet,
latest_ratchet,
signing_key,
signing_key_verified,
config: SessionConfig::version_1(),
})
}
}
/// Pickle an [`InboundGroupSession`] into a libolm pickle format.
///
/// This pickle can be restored using the
/// [`InboundGroupSession::from_libolm_pickle`] method, or can be used in
/// the [`libolm`] C library.
///
/// The pickle will be encryptd using the pickle key.
///
/// [`libolm`]: https://gitlab.matrix.org/matrix-org/olm/
#[cfg(feature = "libolm-compat")]
pub fn to_libolm_pickle(&self, pickle_key: &[u8]) -> Result<String, crate::LibolmPickleError> {
use libolm::Pickle;

const PICKLE_VERSION: u32 = 2;
use crate::utilities::pickle_libolm;

unpickle_libolm::<Pickle, _>(pickle, pickle_key, PICKLE_VERSION)
pickle_libolm::<Pickle>(self.into(), pickle_key)
}
}

Expand Down Expand Up @@ -469,6 +455,65 @@ impl From<&GroupSession> for InboundGroupSession {
}
}

#[cfg(feature = "libolm-compat")]
mod libolm {
use matrix_pickle::{Decode, Encode};
use zeroize::Zeroize;

use super::InboundGroupSession;
use crate::{
megolm::{libolm::LibolmRatchetPickle, SessionConfig},
Ed25519PublicKey,
};

pub const PICKLE_VERSION: u32 = 2;

#[derive(Zeroize, Decode, Encode)]
#[zeroize(drop)]
pub struct Pickle {
version: u32,
initial_ratchet: LibolmRatchetPickle,
latest_ratchet: LibolmRatchetPickle,
signing_key: [u8; 32],
signing_key_verified: bool,
}

impl From<&InboundGroupSession> for Pickle {
fn from(s: &InboundGroupSession) -> Self {
Self {
version: PICKLE_VERSION,
initial_ratchet: (&s.initial_ratchet).into(),
latest_ratchet: (&s.latest_ratchet).into(),
signing_key: s.signing_key.as_bytes().to_owned(),
signing_key_verified: s.signing_key_verified,
}
}
}

impl TryFrom<Pickle> for InboundGroupSession {
type Error = crate::LibolmPickleError;

fn try_from(pickle: Pickle) -> Result<Self, Self::Error> {
// Removing the borrow doesn't work and clippy complains about
// this on nightly.
#[allow(clippy::needless_borrow)]
let initial_ratchet = (&pickle.initial_ratchet).into();
#[allow(clippy::needless_borrow)]
let latest_ratchet = (&pickle.latest_ratchet).into();
let signing_key = Ed25519PublicKey::from_slice(&pickle.signing_key)?;
let signing_key_verified = pickle.signing_key_verified;

Ok(Self {
initial_ratchet,
latest_ratchet,
signing_key,
signing_key_verified,
config: SessionConfig::version_1(),
})
}
}
}

#[cfg(test)]
mod test {
use super::InboundGroupSession;
Expand Down
52 changes: 50 additions & 2 deletions src/megolm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ fn default_config() -> SessionConfig {

#[cfg(feature = "libolm-compat")]
mod libolm {
use matrix_pickle::Decode;
use matrix_pickle::{Decode, Encode};
use zeroize::Zeroize;

use super::ratchet::Ratchet;

#[derive(Zeroize, Decode)]
#[derive(Zeroize, Decode, Encode)]
#[zeroize(drop)]
pub(crate) struct LibolmRatchetPickle {
#[secret]
Expand All @@ -54,6 +54,15 @@ mod libolm {
Ratchet::from_bytes(pickle.ratchet.clone(), pickle.index)
}
}

impl From<&Ratchet> for LibolmRatchetPickle {
fn from(r: &Ratchet) -> Self {
let mut ratchet = Box::new([0u8; 128]);
ratchet.copy_from_slice(r.as_bytes());

LibolmRatchetPickle { ratchet, index: r.index() }
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -244,6 +253,45 @@ mod test {
Ok(())
}

#[test]
#[cfg(feature = "libolm-compat")]
fn libolm_pickle_cycle() -> Result<()> {
let key = b"DEFAULT_PICKLE_KEY";
let session = GroupSession::new(SessionConfig::version_1());

let pickle = session.to_libolm_pickle(key)?;

let olm = OlmOutboundGroupSession::unpickle(
pickle,
olm_rs::PicklingMode::Encrypted { key: key.to_vec() },
)?;

assert_eq!(olm.session_id(), session.session_id());
assert_eq!(olm.session_message_index(), session.message_index());

Ok(())
}

#[test]
#[cfg(feature = "libolm-compat")]
fn libolm_inbound_pickle_cycle() -> Result<()> {
let key = b"DEFAULT_PICKLE_KEY";
let session = GroupSession::new(SessionConfig::version_1());
let session = InboundGroupSession::from(&session);

let pickle = session.to_libolm_pickle(key)?;

let olm = OlmInboundGroupSession::unpickle(
pickle,
olm_rs::PicklingMode::Encrypted { key: key.to_vec() },
)?;

assert_eq!(olm.session_id(), session.session_id());
assert_eq!(olm.first_known_index(), session.first_known_index());

Ok(())
}

#[test]
#[cfg(feature = "libolm-compat")]
fn libolm_inbound_unpickling() -> Result<()> {
Expand Down
Loading