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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use hkdf::Hkdf;
use hmac::{digest::MacError, Hmac, Mac as _};
use rand::thread_rng;
use sha2::Sha256;
use thiserror::Error;
use x25519_dalek::{EphemeralSecret, SharedSecret};
use crate::{
utilities::{base64_decode, base64_encode},
Curve25519PublicKey, KeyError,
};
type HmacSha256Key = Box<[u8; 32]>;
pub struct Mac(Vec<u8>);
impl Mac {
pub fn to_base64(&self) -> String {
base64_encode(&self.0)
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn from_slice(bytes: &[u8]) -> Self {
Self(bytes.to_vec())
}
pub fn from_base64(mac: &str) -> Result<Self, base64::DecodeError> {
let bytes = base64_decode(mac)?;
Ok(Self(bytes))
}
}
#[derive(Debug, Clone, Error)]
#[error("The given count of bytes was too large")]
pub struct InvalidCount;
#[derive(Debug, Error)]
pub enum SasError {
#[error("The SAS MAC validation didn't succeed: {0}")]
Mac(#[from] MacError),
}
pub struct Sas {
secret_key: EphemeralSecret,
public_key: Curve25519PublicKey,
}
pub struct EstablishedSas {
shared_secret: SharedSecret,
our_public_key: Curve25519PublicKey,
their_public_key: Curve25519PublicKey,
}
impl std::fmt::Debug for EstablishedSas {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EstablishedSas")
.field("our_public_key", &self.our_public_key.to_base64())
.field("their_public_key", &self.their_public_key.to_base64())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SasBytes {
bytes: [u8; 6],
}
impl SasBytes {
pub fn emoji_indices(&self) -> [u8; 7] {
Self::bytes_to_emoji_index(&self.bytes)
}
pub fn decimals(&self) -> (u16, u16, u16) {
Self::bytes_to_decimal(&self.bytes)
}
pub fn as_bytes(&self) -> &[u8; 6] {
&self.bytes
}
fn bytes_to_emoji_index(bytes: &[u8; 6]) -> [u8; 7] {
let bytes: Vec<u64> = bytes.iter().map(|b| *b as u64).collect();
let mut num: u64 = bytes[0] << 40;
num += bytes[1] << 32;
num += bytes[2] << 24;
num += bytes[3] << 16;
num += bytes[4] << 8;
num += bytes[5];
[
((num >> 42) & 63) as u8,
((num >> 36) & 63) as u8,
((num >> 30) & 63) as u8,
((num >> 24) & 63) as u8,
((num >> 18) & 63) as u8,
((num >> 12) & 63) as u8,
((num >> 6) & 63) as u8,
]
}
fn bytes_to_decimal(bytes: &[u8; 6]) -> (u16, u16, u16) {
let bytes: Vec<u16> = bytes.iter().map(|b| *b as u16).collect();
let first = bytes[0] << 5 | bytes[1] >> 3;
let second = (bytes[1] & 0x7) << 10 | bytes[2] << 2 | bytes[3] >> 6;
let third = (bytes[3] & 0x3F) << 7 | bytes[4] >> 1;
(first + 1000, second + 1000, third + 1000)
}
}
impl Default for Sas {
fn default() -> Self {
Self::new()
}
}
impl Sas {
pub fn new() -> Self {
let rng = thread_rng();
let secret_key = EphemeralSecret::new(rng);
let public_key = Curve25519PublicKey::from(&secret_key);
Self { secret_key, public_key }
}
pub fn public_key(&self) -> Curve25519PublicKey {
self.public_key
}
pub fn diffie_hellman(
self,
their_public_key: Curve25519PublicKey,
) -> Result<EstablishedSas, KeyError> {
let shared_secret = self.secret_key.diffie_hellman(&their_public_key.inner);
if shared_secret.was_contributory() {
Ok(EstablishedSas { shared_secret, our_public_key: self.public_key, their_public_key })
} else {
Err(KeyError::NonContributoryKey)
}
}
pub fn diffie_hellman_with_raw(
self,
other_public_key: &str,
) -> Result<EstablishedSas, KeyError> {
let other_public_key = Curve25519PublicKey::from_base64(other_public_key)?;
self.diffie_hellman(other_public_key)
}
}
impl EstablishedSas {
pub fn bytes(&self, info: &str) -> SasBytes {
let mut bytes = [0u8; 6];
let byte_vec =
self.bytes_raw(info, 6).expect("HKDF should always be able to generate 6 bytes");
bytes.copy_from_slice(&byte_vec);
SasBytes { bytes }
}
pub fn bytes_raw(&self, info: &str, count: usize) -> Result<Vec<u8>, InvalidCount> {
let mut output = vec![0u8; count];
let hkdf = self.get_hkdf();
hkdf.expand(info.as_bytes(), &mut output[0..count]).map_err(|_| InvalidCount)?;
Ok(output)
}
pub fn calculate_mac(&self, input: &str, info: &str) -> Mac {
let mut mac = self.get_mac(info);
mac.update(input.as_ref());
Mac(mac.finalize().into_bytes().to_vec())
}
#[cfg(feature = "libolm-compat")]
pub fn calculate_mac_invalid_base64(&self, input: &str, info: &str) -> String {
let mac = self.calculate_mac(input, info);
let mut out = base64_encode(&mac.as_bytes()[0..3]);
let mut bytes_from_mac = 2;
for i in (6..10).step_by(3) {
let from_mac = &mac.as_bytes()[i - bytes_from_mac..i];
let from_out = &out.as_bytes()[out.len() - (3 - bytes_from_mac)..];
let bytes = [from_out, from_mac].concat();
let encoded = base64_encode(bytes);
bytes_from_mac -= 1;
out = out + &encoded;
}
for i in (9..30).step_by(3) {
let next = &out.as_bytes()[i..i + 3];
let next_four = base64_encode(next);
out = out + &next_four;
}
let next = &out.as_bytes()[30..32];
let next = base64_encode(next);
out + &next
}
pub fn verify_mac(&self, input: &str, info: &str, tag: &Mac) -> Result<(), SasError> {
let mut mac = self.get_mac(info);
mac.update(input.as_bytes());
Ok(mac.verify_slice(&tag.0)?)
}
pub fn our_public_key(&self) -> Curve25519PublicKey {
self.our_public_key
}
pub fn their_public_key(&self) -> Curve25519PublicKey {
self.their_public_key
}
fn get_hkdf(&self) -> Hkdf<Sha256> {
Hkdf::new(None, self.shared_secret.as_bytes())
}
fn get_mac_key(&self, info: &str) -> HmacSha256Key {
let mut mac_key = Box::new([0u8; 32]);
let hkdf = self.get_hkdf();
hkdf.expand(info.as_bytes(), mac_key.as_mut_slice()).expect("Can't expand the MAC key");
mac_key
}
fn get_mac(&self, info: &str) -> Hmac<Sha256> {
let mac_key = self.get_mac_key(info);
Hmac::<Sha256>::new_from_slice(mac_key.as_slice()).expect("Can't create a HMAC object")
}
}
#[cfg(test)]
mod test {
use anyhow::Result;
use olm_rs::sas::OlmSas;
use proptest::prelude::*;
use super::{Mac, Sas, SasBytes};
const ALICE_MXID: &str = "@alice:example.com";
const ALICE_DEVICE_ID: &str = "AAAAAAAAAA";
const BOB_MXID: &str = "@bob:example.com";
const BOB_DEVICE_ID: &str = "BBBBBBBBBB";
#[test]
fn mac_from_slice_as_bytes_is_identity() {
let bytes = "ABCDEFGH".as_bytes();
assert_eq!(
Mac::from_slice(bytes).as_bytes(),
bytes,
"as_bytes() after from_slice() is not identity"
);
}
#[test]
fn libolm_and_vodozemac_generate_same_bytes() -> Result<()> {
let mut olm = OlmSas::new();
let dalek = Sas::new();
olm.set_their_public_key(dalek.public_key().to_base64())
.expect("Couldn't set the public key for libolm");
let established = dalek.diffie_hellman_with_raw(&olm.public_key())?;
assert_eq!(
olm.generate_bytes("TEST", 10).expect("libolm couldn't generate SAS bytes"),
established.bytes_raw("TEST", 10)?
);
Ok(())
}
#[test]
fn vodozemac_and_vodozemac_generate_same_bytes() -> Result<()> {
let alice = Sas::default();
let bob = Sas::default();
let alice_public_key_encoded = alice.public_key().to_base64();
let alice_public_key = alice.public_key().to_owned();
let bob_public_key_encoded = bob.public_key().to_base64();
let bob_public_key = bob.public_key();
let alice_established = alice.diffie_hellman_with_raw(&bob_public_key_encoded)?;
let bob_established = bob.diffie_hellman_with_raw(&alice_public_key_encoded)?;
assert_eq!(alice_established.our_public_key(), alice_public_key);
assert_eq!(alice_established.their_public_key(), bob_public_key);
assert_eq!(bob_established.our_public_key(), bob_public_key);
assert_eq!(bob_established.their_public_key(), alice_public_key);
let alice_bytes = alice_established.bytes("TEST");
let bob_bytes = bob_established.bytes("TEST");
assert_eq!(alice_bytes, bob_bytes, "The two sides calculated different bytes.");
assert_eq!(
alice_bytes.emoji_indices(),
bob_bytes.emoji_indices(),
"The two sides calculated different emoji indices."
);
assert_eq!(
alice_bytes.decimals(),
bob_bytes.decimals(),
"The two sides calculated different decimals."
);
assert_eq!(alice_bytes.as_bytes(), bob_bytes.as_bytes());
Ok(())
}
#[test]
fn calculate_mac_vodozemac_vodozemac() -> Result<()> {
let alice = Sas::new();
let bob = Sas::new();
let alice_public_key = alice.public_key().to_base64();
let bob_public_key = bob.public_key().to_base64();
let message = format!("ed25519:{}", BOB_DEVICE_ID);
let extra_info = format!(
"{}{}{}{}{}{}{}",
"MATRIX_KEY_VERIFICATION_MAC",
BOB_MXID,
BOB_DEVICE_ID,
ALICE_MXID,
ALICE_DEVICE_ID,
"$1234567890",
"KEY_IDS"
);
let alice_established = alice.diffie_hellman_with_raw(&bob_public_key)?;
let bob_established = bob.diffie_hellman_with_raw(&alice_public_key)?;
let alice_mac = alice_established.calculate_mac(&message, &extra_info);
let bob_mac = bob_established.calculate_mac(&message, &extra_info);
assert_eq!(
alice_mac.to_base64(),
bob_mac.to_base64(),
"Two vodozemac devices calculated different SAS MACs."
);
alice_established.verify_mac(&message, &extra_info, &bob_mac)?;
bob_established.verify_mac(&message, &extra_info, &alice_mac)?;
Ok(())
}
#[test]
fn calculate_mac_vodozemac_libolm() -> Result<()> {
let alice_on_dalek = Sas::new();
let mut bob_on_libolm = OlmSas::new();
let alice_public_key = alice_on_dalek.public_key().to_base64();
let bob_public_key = bob_on_libolm.public_key();
let message = format!("ed25519:{}", BOB_DEVICE_ID);
let extra_info = format!(
"{}{}{}{}{}{}{}",
"MATRIX_KEY_VERIFICATION_MAC",
BOB_MXID,
BOB_DEVICE_ID,
ALICE_MXID,
ALICE_DEVICE_ID,
"$1234567890",
"KEY_IDS"
);
bob_on_libolm
.set_their_public_key(alice_public_key)
.expect("Couldn't set the public key for libolm");
let established = alice_on_dalek.diffie_hellman_with_raw(&bob_public_key)?;
let olm_mac = bob_on_libolm
.calculate_mac_fixed_base64(&message, &extra_info)
.expect("libolm couldn't calculate SAS MAC.");
assert_eq!(olm_mac, established.calculate_mac(&message, &extra_info).to_base64());
let olm_mac =
Mac::from_base64(&olm_mac).expect("SAS MAC generated by libolm wasn't valid base64.");
established.verify_mac(&message, &extra_info, &olm_mac)?;
Ok(())
}
#[test]
fn calculate_mac_invalid_base64() -> Result<()> {
let mut olm = OlmSas::new();
let dalek = Sas::new();
olm.set_their_public_key(dalek.public_key().to_base64())
.expect("Couldn't set the public key for libolm");
let established = dalek.diffie_hellman_with_raw(&olm.public_key())?;
let olm_mac = olm.calculate_mac("", "").expect("libolm couldn't calculate a MAC");
assert_eq!(olm_mac, established.calculate_mac_invalid_base64("", ""));
Ok(())
}
#[test]
fn emoji_generation() {
let bytes: [u8; 6] = [0, 0, 0, 0, 0, 0];
let index: [u8; 7] = [0, 0, 0, 0, 0, 0, 0];
assert_eq!(SasBytes::bytes_to_emoji_index(&bytes), index.as_ref());
let bytes: [u8; 6] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
let index: [u8; 7] = [63, 63, 63, 63, 63, 63, 63];
assert_eq!(SasBytes::bytes_to_emoji_index(&bytes), index.as_ref());
}
#[test]
fn decimal_generation() {
let bytes: [u8; 6] = [0, 0, 0, 0, 0, 0];
let result = SasBytes::bytes_to_decimal(&bytes);
assert_eq!(result, (1000, 1000, 1000));
let bytes: [u8; 6] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
let result = SasBytes::bytes_to_decimal(&bytes);
assert_eq!(result, (9191, 9191, 9191));
}
proptest! {
#[test]
fn proptest_emoji(bytes in prop::array::uniform6(0u8..)) {
let numbers = SasBytes::bytes_to_emoji_index(&bytes);
for number in numbers.iter() {
prop_assert!(*number < 64);
}
}
}
proptest! {
#[test]
fn proptest_decimals(bytes in prop::array::uniform6(0u8..)) {
let (first, second, third) = SasBytes::bytes_to_decimal(&bytes);
prop_assert!((1000..=9191).contains(&first));
prop_assert!((1000..=9191).contains(&second));
prop_assert!((1000..=9191).contains(&third));
}
}
}