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
use crate::{Error, Result};
use tor_cell::chancell::RawCellBody;
use tor_error::internal;
use generic_array::GenericArray;
#[derive(Clone)]
pub(crate) struct RelayCellBody(RawCellBody);
impl From<RawCellBody> for RelayCellBody {
fn from(body: RawCellBody) -> Self {
RelayCellBody(body)
}
}
impl From<RelayCellBody> for RawCellBody {
fn from(cell: RelayCellBody) -> Self {
cell.0
}
}
impl AsRef<[u8]> for RelayCellBody {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl AsMut<[u8]> for RelayCellBody {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0[..]
}
}
pub(crate) trait CryptInit: Sized {
fn seed_len() -> usize;
fn initialize(seed: &[u8]) -> Result<Self>;
fn construct<K: super::handshake::KeyGenerator>(keygen: K) -> Result<Self> {
let seed = keygen.expand(Self::seed_len())?;
Self::initialize(&seed)
}
}
pub(crate) trait ClientLayer<F, B>
where
F: OutboundClientLayer,
B: InboundClientLayer,
{
fn split(self) -> (F, B);
}
pub(crate) trait RelayCrypt {
fn originate(&mut self, cell: &mut RelayCellBody);
fn encrypt_inbound(&mut self, cell: &mut RelayCellBody);
fn decrypt_outbound(&mut self, cell: &mut RelayCellBody) -> bool;
}
pub(crate) trait OutboundClientLayer {
fn originate_for(&mut self, cell: &mut RelayCellBody) -> &[u8];
fn encrypt_outbound(&mut self, cell: &mut RelayCellBody);
}
pub(crate) trait InboundClientLayer {
fn decrypt_inbound(&mut self, cell: &mut RelayCellBody) -> Option<&[u8]>;
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) struct HopNum(u8);
impl From<HopNum> for u8 {
fn from(hop: HopNum) -> u8 {
hop.0
}
}
impl From<u8> for HopNum {
fn from(v: u8) -> HopNum {
HopNum(v)
}
}
impl From<HopNum> for usize {
fn from(hop: HopNum) -> usize {
hop.0 as usize
}
}
impl std::fmt::Display for HopNum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
self.0.fmt(f)
}
}
pub(crate) struct OutboundClientCrypt {
layers: Vec<Box<dyn OutboundClientLayer + Send>>,
}
pub(crate) struct InboundClientCrypt {
layers: Vec<Box<dyn InboundClientLayer + Send>>,
}
impl OutboundClientCrypt {
pub(crate) fn new() -> Self {
OutboundClientCrypt { layers: Vec::new() }
}
pub(crate) fn encrypt(&mut self, cell: &mut RelayCellBody, hop: HopNum) -> Result<&[u8; 20]> {
let hop: usize = hop.into();
if hop >= self.layers.len() {
return Err(Error::NoSuchHop);
}
let mut layers = self.layers.iter_mut().take(hop + 1).rev();
let first_layer = layers.next().ok_or(Error::NoSuchHop)?;
let tag = first_layer.originate_for(cell);
for layer in layers {
layer.encrypt_outbound(cell);
}
Ok(tag.try_into().expect("wrong SENDME digest size"))
}
pub(crate) fn add_layer(&mut self, layer: Box<dyn OutboundClientLayer + Send>) {
assert!(self.layers.len() < std::u8::MAX as usize);
self.layers.push(layer);
}
pub(crate) fn n_layers(&self) -> usize {
self.layers.len()
}
}
impl InboundClientCrypt {
pub(crate) fn new() -> Self {
InboundClientCrypt { layers: Vec::new() }
}
pub(crate) fn decrypt(&mut self, cell: &mut RelayCellBody) -> Result<(HopNum, &[u8])> {
for (hopnum, layer) in self.layers.iter_mut().enumerate() {
if let Some(tag) = layer.decrypt_inbound(cell) {
assert!(hopnum <= std::u8::MAX as usize);
return Ok(((hopnum as u8).into(), tag));
}
}
Err(Error::BadCellAuth)
}
pub(crate) fn add_layer(&mut self, layer: Box<dyn InboundClientLayer + Send>) {
assert!(self.layers.len() < std::u8::MAX as usize);
self.layers.push(layer);
}
#[allow(dead_code)]
pub(crate) fn n_layers(&self) -> usize {
self.layers.len()
}
}
pub(crate) type Tor1RelayCrypto =
tor1::CryptStatePair<tor_llcrypto::cipher::aes::Aes128Ctr, tor_llcrypto::d::Sha1>;
pub(crate) mod tor1 {
use super::*;
use cipher::{KeyIvInit, StreamCipher};
use digest::Digest;
use typenum::Unsigned;
pub(crate) struct CryptState<SC: StreamCipher, D: Digest + Clone> {
cipher: SC,
digest: D,
last_digest_val: GenericArray<u8, D::OutputSize>,
}
pub(crate) struct CryptStatePair<SC: StreamCipher, D: Digest + Clone> {
fwd: CryptState<SC, D>,
back: CryptState<SC, D>,
}
impl<SC: StreamCipher + KeyIvInit, D: Digest + Clone> CryptInit for CryptStatePair<SC, D> {
fn seed_len() -> usize {
SC::KeySize::to_usize() * 2 + D::OutputSize::to_usize() * 2
}
fn initialize(seed: &[u8]) -> Result<Self> {
if seed.len() != Self::seed_len() {
return Err(Error::from(internal!(
"seed length {} was invalid",
seed.len()
)));
}
let keylen = SC::KeySize::to_usize();
let dlen = D::OutputSize::to_usize();
let fdinit = &seed[0..dlen];
let bdinit = &seed[dlen..dlen * 2];
let fckey = &seed[dlen * 2..dlen * 2 + keylen];
let bckey = &seed[dlen * 2 + keylen..dlen * 2 + keylen * 2];
let fwd = CryptState {
cipher: SC::new(fckey.try_into().expect("Wrong length"), &Default::default()),
digest: D::new().chain_update(fdinit),
last_digest_val: GenericArray::default(),
};
let back = CryptState {
cipher: SC::new(bckey.try_into().expect("Wrong length"), &Default::default()),
digest: D::new().chain_update(bdinit),
last_digest_val: GenericArray::default(),
};
Ok(CryptStatePair { fwd, back })
}
}
impl<SC, D> ClientLayer<CryptState<SC, D>, CryptState<SC, D>> for CryptStatePair<SC, D>
where
SC: StreamCipher,
D: Digest + Clone,
{
fn split(self) -> (CryptState<SC, D>, CryptState<SC, D>) {
(self.fwd, self.back)
}
}
impl<SC: StreamCipher, D: Digest + Clone> RelayCrypt for CryptStatePair<SC, D> {
fn originate(&mut self, cell: &mut RelayCellBody) {
let mut d_ignored = GenericArray::default();
cell.set_digest(&mut self.back.digest, &mut d_ignored);
}
fn encrypt_inbound(&mut self, cell: &mut RelayCellBody) {
self.back.cipher.apply_keystream(cell.as_mut());
}
fn decrypt_outbound(&mut self, cell: &mut RelayCellBody) -> bool {
self.fwd.cipher.apply_keystream(cell.as_mut());
let mut d_ignored = GenericArray::default();
cell.recognized(&mut self.fwd.digest, &mut d_ignored)
}
}
impl<SC: StreamCipher, D: Digest + Clone> OutboundClientLayer for CryptState<SC, D> {
fn originate_for(&mut self, cell: &mut RelayCellBody) -> &[u8] {
cell.set_digest(&mut self.digest, &mut self.last_digest_val);
self.encrypt_outbound(cell);
&self.last_digest_val
}
fn encrypt_outbound(&mut self, cell: &mut RelayCellBody) {
self.cipher.apply_keystream(&mut cell.0[..]);
}
}
impl<SC: StreamCipher, D: Digest + Clone> InboundClientLayer for CryptState<SC, D> {
fn decrypt_inbound(&mut self, cell: &mut RelayCellBody) -> Option<&[u8]> {
self.cipher.apply_keystream(&mut cell.0[..]);
if cell.recognized(&mut self.digest, &mut self.last_digest_val) {
Some(&self.last_digest_val)
} else {
None
}
}
}
impl RelayCellBody {
fn set_digest<D: Digest + Clone>(
&mut self,
d: &mut D,
used_digest: &mut GenericArray<u8, D::OutputSize>,
) {
self.0[1] = 0;
self.0[2] = 0;
self.0[5] = 0;
self.0[6] = 0;
self.0[7] = 0;
self.0[8] = 0;
d.update(&self.0[..]);
*used_digest = d.clone().finalize();
self.0[5..9].copy_from_slice(&used_digest[0..4]);
}
fn recognized<D: Digest + Clone>(
&self,
d: &mut D,
rcvd: &mut GenericArray<u8, D::OutputSize>,
) -> bool {
use crate::util::ct;
use arrayref::array_ref;
let recognized = u16::from_be_bytes(*array_ref![self.0, 1, 2]);
if recognized != 0 {
return false;
}
let mut dtmp = d.clone();
dtmp.update(&self.0[..5]);
dtmp.update([0_u8; 4]);
dtmp.update(&self.0[9..]);
let dtmp_clone = dtmp.clone();
let result = dtmp.finalize();
if ct::bytes_eq(&self.0[5..9], &result[0..4]) {
*d = dtmp_clone;
*rcvd = result;
return true;
}
false
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::SecretBytes;
use rand::RngCore;
use tor_basic_utils::test_rng::testing_rng;
fn add_layers(
cc_out: &mut OutboundClientCrypt,
cc_in: &mut InboundClientCrypt,
pair: Tor1RelayCrypto,
) {
let (outbound, inbound) = pair.split();
cc_out.add_layer(Box::new(outbound));
cc_in.add_layer(Box::new(inbound));
}
#[test]
fn roundtrip() {
use crate::crypto::handshake::ShakeKeyGenerator as KGen;
fn s(seed: &[u8]) -> SecretBytes {
let mut s: SecretBytes = SecretBytes::new(Vec::new());
s.extend(seed);
s
}
let seed1 = s(b"hidden we are free");
let seed2 = s(b"free to speak, to free ourselves");
let seed3 = s(b"free to hide no more");
let mut cc_out = OutboundClientCrypt::new();
let mut cc_in = InboundClientCrypt::new();
let pair = Tor1RelayCrypto::construct(KGen::new(seed1.clone())).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
let pair = Tor1RelayCrypto::construct(KGen::new(seed2.clone())).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
let pair = Tor1RelayCrypto::construct(KGen::new(seed3.clone())).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
assert_eq!(cc_in.n_layers(), 3);
assert_eq!(cc_out.n_layers(), 3);
let mut r1 = Tor1RelayCrypto::construct(KGen::new(seed1)).unwrap();
let mut r2 = Tor1RelayCrypto::construct(KGen::new(seed2)).unwrap();
let mut r3 = Tor1RelayCrypto::construct(KGen::new(seed3)).unwrap();
let mut rng = testing_rng();
for _ in 1..300 {
let mut cell = [0_u8; 509];
let mut cell_orig = [0_u8; 509];
rng.fill_bytes(&mut cell_orig);
cell.copy_from_slice(&cell_orig);
let mut cell = cell.into();
let _tag = cc_out.encrypt(&mut cell, 2.into()).unwrap();
assert_ne!(&cell.as_ref()[9..], &cell_orig.as_ref()[9..]);
assert!(!r1.decrypt_outbound(&mut cell));
assert!(!r2.decrypt_outbound(&mut cell));
assert!(r3.decrypt_outbound(&mut cell));
assert_eq!(&cell.as_ref()[9..], &cell_orig.as_ref()[9..]);
let mut cell = [0_u8; 509];
let mut cell_orig = [0_u8; 509];
rng.fill_bytes(&mut cell_orig);
cell.copy_from_slice(&cell_orig);
let mut cell = cell.into();
r3.originate(&mut cell);
r3.encrypt_inbound(&mut cell);
r2.encrypt_inbound(&mut cell);
r1.encrypt_inbound(&mut cell);
let (layer, _tag) = cc_in.decrypt(&mut cell).unwrap();
assert_eq!(layer, 2.into());
assert_eq!(&cell.as_ref()[9..], &cell_orig.as_ref()[9..]);
}
{
let mut cell = [0_u8; 509].into();
let err = cc_out.encrypt(&mut cell, 10.into());
assert!(matches!(err, Err(Error::NoSuchHop)));
}
{
let mut cell = [0_u8; 509].into();
let err = cc_in.decrypt(&mut cell);
assert!(matches!(err, Err(Error::BadCellAuth)));
}
}
#[test]
fn testvec() {
use digest::XofReader;
use digest::{ExtendableOutput, Update};
const K1: &[u8; 72] =
b" 'My public key is in this signed x509 object', said Tom assertively.";
const K2: &[u8; 72] =
b"'Let's chart the pedal phlanges in the tomb', said Tom cryptographically";
const K3: &[u8; 72] =
b" 'Segmentation fault bugs don't _just happen_', said Tom seethingly.";
const SEED: &[u8;108] = b"'You mean to tell me that there's a version of Sha-3 with no limit on the output length?', said Tom shakily.";
let data: &[(usize, &str)] = &include!("../../testdata/cell_crypt.data");
let mut cc_out = OutboundClientCrypt::new();
let mut cc_in = InboundClientCrypt::new();
let pair = Tor1RelayCrypto::initialize(&K1[..]).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
let pair = Tor1RelayCrypto::initialize(&K2[..]).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
let pair = Tor1RelayCrypto::initialize(&K3[..]).unwrap();
add_layers(&mut cc_out, &mut cc_in, pair);
let mut xof = tor_llcrypto::d::Shake256::default();
xof.update(&SEED[..]);
let mut stream = xof.finalize_xof();
let mut j = 0;
for cellno in 0..51 {
let mut body = [0_u8; 509];
body[0] = 2;
body[4] = 1;
body[9] = 1;
body[10] = 242;
stream.read(&mut body[11..]);
let mut cell = body.into();
let _ = cc_out.encrypt(&mut cell, 2.into());
if cellno == data[j].0 {
let expected = hex::decode(data[j].1).unwrap();
assert_eq!(cell.as_ref(), &expected[..]);
j += 1;
}
}
}
}