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
use std::io::{Cursor, Read};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use zeroize::Zeroize;
use super::ratchet::Ratchet;
use crate::{
utilities::{base64_decode, base64_encode},
Ed25519PublicKey, Ed25519Signature, SignatureError,
};
#[derive(Debug, Error)]
pub enum SessionKeyDecodeError {
#[error("The session key had a invalid version, expected {0}, got {1}")]
Version(u8, u8),
#[error("The session key was too short {0}")]
Read(#[from] std::io::Error),
#[error("The session key wasn't valid base64: {0}")]
Base64(#[from] base64::DecodeError),
#[error("The signature on the session key was invalid: {0}")]
Signature(#[from] SignatureError),
#[error("The public key of session was invalid: {0}")]
PublicKey(#[from] crate::KeyError),
}
pub struct ExportedSessionKey {
pub(crate) ratchet_index: u32,
pub(crate) ratchet: Box<[u8; 128]>,
pub(crate) signing_key: Ed25519PublicKey,
}
pub struct SessionKey {
pub(super) session_key: ExportedSessionKey,
pub(super) signature: Ed25519Signature,
}
impl Zeroize for ExportedSessionKey {
fn zeroize(&mut self) {
self.ratchet_index.zeroize();
self.ratchet.zeroize();
}
}
impl Drop for ExportedSessionKey {
fn drop(&mut self) {
self.zeroize()
}
}
impl ExportedSessionKey {
const VERSION: u8 = 1;
pub(super) fn new(ratchet: &Ratchet, signing_key: Ed25519PublicKey) -> Self {
let ratchet_index = ratchet.index();
let mut ratchet_bytes = Box::new([0u8; Ratchet::RATCHET_LENGTH]);
ratchet_bytes.copy_from_slice(ratchet.as_bytes());
Self { ratchet_index, ratchet: ratchet_bytes, signing_key }
}
fn to_bytes_with_version(&self, version: u8) -> Vec<u8> {
let index = self.ratchet_index.to_be_bytes();
[[version].as_ref(), index.as_ref(), self.ratchet.as_ref(), self.signing_key.as_bytes()]
.concat()
}
pub fn to_bytes(&self) -> Vec<u8> {
self.to_bytes_with_version(Self::VERSION)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, SessionKeyDecodeError> {
let mut cursor = Cursor::new(bytes);
Self::decode_key(Self::VERSION, &mut cursor)
}
pub fn to_base64(&self) -> String {
let mut bytes = self.to_bytes();
let ret = base64_encode(&bytes);
bytes.zeroize();
ret
}
pub fn from_base64(key: &str) -> Result<Self, SessionKeyDecodeError> {
let mut bytes = base64_decode(key)?;
let ret = Self::from_bytes(&bytes);
bytes.zeroize();
ret
}
fn decode_key(
expected_version: u8,
cursor: &mut Cursor<&[u8]>,
) -> Result<ExportedSessionKey, SessionKeyDecodeError> {
let mut version = [0u8; 1];
let mut index = [0u8; 4];
let mut ratchet = Box::new([0u8; 128]);
let mut public_key = [0u8; Ed25519PublicKey::LENGTH];
cursor.read_exact(&mut version)?;
if version[0] != expected_version {
Err(SessionKeyDecodeError::Version(expected_version, version[0]))
} else {
cursor.read_exact(&mut index)?;
cursor.read_exact(ratchet.as_mut_slice())?;
cursor.read_exact(&mut public_key)?;
let signing_key = Ed25519PublicKey::from_slice(&public_key)?;
let ratchet_index = u32::from_be_bytes(index);
Ok(ExportedSessionKey { ratchet_index, ratchet, signing_key })
}
}
}
impl SessionKey {
const VERSION: u8 = 2;
pub(super) fn new(ratchet: &Ratchet, signing_key: Ed25519PublicKey) -> Self {
let session_key = ExportedSessionKey::new(ratchet, signing_key);
Self {
session_key,
signature: Ed25519Signature::from_slice(&[0; Ed25519Signature::LENGTH])
.expect("Can't create an empty signature"),
}
}
pub(crate) fn to_signature_bytes(&self) -> Vec<u8> {
self.session_key.to_bytes_with_version(Self::VERSION)
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = self.to_signature_bytes();
bytes.extend(self.signature.to_bytes());
bytes
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, SessionKeyDecodeError> {
let mut cursor = Cursor::new(bytes);
let session_key = ExportedSessionKey::decode_key(Self::VERSION, &mut cursor)?;
let mut signature = [0u8; Ed25519Signature::LENGTH];
cursor.read_exact(&mut signature)?;
let signature = Ed25519Signature::from_slice(&signature)?;
let decoded = cursor.into_inner();
session_key
.signing_key
.verify(&decoded[..decoded.len() - Ed25519Signature::LENGTH], &signature)?;
Ok(Self { session_key, signature })
}
pub fn to_base64(&self) -> String {
let mut bytes = self.to_bytes();
let ret = base64_encode(&bytes);
bytes.zeroize();
ret
}
pub fn from_base64(key: &str) -> Result<Self, SessionKeyDecodeError> {
let mut bytes = base64_decode(key)?;
let ret = Self::from_bytes(&bytes);
bytes.zeroize();
ret
}
}
impl Serialize for SessionKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut encoded = self.to_base64();
let ret = encoded.serialize(serializer);
encoded.zeroize();
ret
}
}
impl<'de> Deserialize<'de> for SessionKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let mut session_key = String::deserialize(deserializer)?;
let ret = Self::from_base64(&session_key).map_err(serde::de::Error::custom);
session_key.zeroize();
ret
}
}
impl Serialize for ExportedSessionKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut encoded = self.to_base64();
let ret = encoded.serialize(serializer);
encoded.zeroize();
ret
}
}
impl<'de> Deserialize<'de> for ExportedSessionKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let mut session_key = String::deserialize(deserializer)?;
let ret = Self::from_base64(&session_key).map_err(serde::de::Error::custom);
session_key.zeroize();
ret
}
}
impl TryFrom<&[u8]> for SessionKey {
type Error = SessionKeyDecodeError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Self::from_bytes(value)
}
}
impl TryFrom<&str> for SessionKey {
type Error = SessionKeyDecodeError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_base64(value)
}
}
impl TryFrom<&[u8]> for ExportedSessionKey {
type Error = SessionKeyDecodeError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Self::from_bytes(value)
}
}
impl TryFrom<&str> for ExportedSessionKey {
type Error = SessionKeyDecodeError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_base64(value)
}
}
#[cfg(test)]
mod test {
use crate::megolm::{ExportedSessionKey, GroupSession, InboundGroupSession, SessionKey};
#[test]
fn session_key_serialization() -> Result<(), anyhow::Error> {
let session = GroupSession::new();
let key = session.session_key();
let serialized = serde_json::to_string(&key)?;
let deserialized: SessionKey = serde_json::from_str(&serialized)?;
assert_eq!(key.session_key.ratchet, deserialized.session_key.ratchet);
assert_eq!(key.session_key.ratchet_index, deserialized.session_key.ratchet_index);
assert_eq!(key.session_key.signing_key, deserialized.session_key.signing_key);
assert_eq!(key.signature, deserialized.signature);
Ok(())
}
#[test]
fn exported_session_key_serialization() -> Result<(), anyhow::Error> {
let session = GroupSession::new();
let mut session = InboundGroupSession::from(&session);
let key = session.export_at(0).expect(
"A freshly created inbound session can always be exported at the initial index",
);
let serialized = serde_json::to_string(&key)?;
let deserialized: ExportedSessionKey = serde_json::from_str(&serialized)?;
assert_eq!(key.ratchet, deserialized.ratchet);
assert_eq!(key.ratchet_index, deserialized.ratchet_index);
assert_eq!(key.signing_key, deserialized.signing_key);
Ok(())
}
}