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
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unreachable_pub)]
use crate::crypto::handshake::KeyGenerator;
use crate::crypto::ll::kdf::{Kdf, ShakeKdf};
use crate::{Error, Result, SecretBytes};
use tor_bytes::{Reader, Writer};
use tor_llcrypto::d::Sha3_256;
use tor_llcrypto::pk::{curve25519, ed25519};
use tor_llcrypto::util::rand_compat::RngCompatExt;
use cipher::{KeyIvInit, StreamCipher};
use digest::Digest;
use generic_array::GenericArray;
use rand_core::{CryptoRng, RngCore};
use tor_error::into_internal;
use tor_llcrypto::cipher::aes::Aes256Ctr;
use zeroize::Zeroizing;
type EncKey = [u8; 32];
type MacKey = [u8; 32];
type MacTag = [u8; 32];
type AuthInputMac = MacTag;
pub type Subcredential = [u8; 32];
pub struct HsNtorHkdfKeyGenerator {
seed: SecretBytes,
}
impl HsNtorHkdfKeyGenerator {
pub fn new(seed: SecretBytes) -> Self {
HsNtorHkdfKeyGenerator { seed }
}
}
impl KeyGenerator for HsNtorHkdfKeyGenerator {
fn expand(self, keylen: usize) -> Result<SecretBytes> {
ShakeKdf::new().derive(&self.seed[..], keylen)
}
}
#[derive(Clone)]
pub struct HsNtorClientInput {
pub B: curve25519::PublicKey,
pub auth_key: ed25519::PublicKey,
pub subcredential: Subcredential,
pub plaintext: Vec<u8>,
pub intro_cell_data: Vec<u8>,
}
impl HsNtorClientInput {
pub fn new(
B: curve25519::PublicKey,
auth_key: ed25519::PublicKey,
subcredential: Subcredential,
plaintext: Vec<u8>,
intro_cell_data: Vec<u8>,
) -> Self {
HsNtorClientInput {
B,
auth_key,
subcredential,
plaintext,
intro_cell_data,
}
}
}
pub struct HsNtorClientState {
proto_input: HsNtorClientInput,
x: curve25519::StaticSecret,
X: curve25519::PublicKey,
}
fn encrypt_and_mac(
mut plaintext: Vec<u8>,
other_data: &[u8],
enc_key: EncKey,
mac_key: MacKey,
) -> Result<(Vec<u8>, MacTag)> {
let zero_iv = GenericArray::default();
let mut cipher = Aes256Ctr::new(&enc_key.into(), &zero_iv);
cipher.apply_keystream(&mut plaintext);
let ciphertext = plaintext;
let mut mac_body: Vec<u8> = Vec::new();
mac_body.extend(other_data);
mac_body.extend(&ciphertext);
let mac_tag = hs_ntor_mac(&mac_body, &mac_key)?;
Ok((ciphertext, mac_tag))
}
pub fn client_send_intro<R>(
rng: &mut R,
proto_input: &HsNtorClientInput,
) -> Result<(HsNtorClientState, Vec<u8>)>
where
R: RngCore + CryptoRng,
{
let x = curve25519::StaticSecret::new(rng.rng_compat());
let X = curve25519::PublicKey::from(&x);
let bx = x.diffie_hellman(&proto_input.B);
let state = HsNtorClientState {
proto_input: proto_input.clone(),
x,
X,
};
let (enc_key, mac_key) = get_introduce1_key_material(
&bx,
&proto_input.auth_key,
&X,
&proto_input.B,
&proto_input.subcredential,
)?;
let (ciphertext, mac_tag) = encrypt_and_mac(
proto_input.plaintext.clone(),
&proto_input.intro_cell_data,
enc_key,
mac_key,
)?;
let mut response: Vec<u8> = Vec::new();
response.write(&X);
response.write(&ciphertext);
response.write(&mac_tag);
Ok((state, response))
}
pub fn client_receive_rend<T>(state: &HsNtorClientState, msg: T) -> Result<HsNtorHkdfKeyGenerator>
where
T: AsRef<[u8]>,
{
let mut cur = Reader::from_slice(msg.as_ref());
let Y: curve25519::PublicKey = cur.extract()?;
let mac_tag: MacTag = cur.extract()?;
let xy = state.x.diffie_hellman(&Y);
let xb = state.x.diffie_hellman(&state.proto_input.B);
let (keygen, my_mac_tag) = get_rendezvous1_key_material(
&xy,
&xb,
&state.proto_input.auth_key,
&state.proto_input.B,
&state.X,
&Y,
)?;
if my_mac_tag != mac_tag {
return Err(Error::BadCircHandshake);
}
Ok(keygen)
}
pub struct HsNtorServiceInput {
pub b: curve25519::StaticSecret,
pub B: curve25519::PublicKey,
pub auth_key: ed25519::PublicKey,
pub subcredential: Subcredential,
pub intro_cell_data: Vec<u8>,
}
impl HsNtorServiceInput {
pub fn new(
b: curve25519::StaticSecret,
B: curve25519::PublicKey,
auth_key: ed25519::PublicKey,
subcredential: Subcredential,
intro_cell_data: Vec<u8>,
) -> Self {
HsNtorServiceInput {
b,
B,
auth_key,
subcredential,
intro_cell_data,
}
}
}
pub fn server_receive_intro<R, T>(
rng: &mut R,
proto_input: &HsNtorServiceInput,
msg: T,
) -> Result<(HsNtorHkdfKeyGenerator, Vec<u8>, Vec<u8>)>
where
R: RngCore + CryptoRng,
T: AsRef<[u8]>,
{
let mut cur = Reader::from_slice(msg.as_ref());
let X: curve25519::PublicKey = cur.extract()?;
let remaining_bytes = cur.remaining();
let ciphertext = &mut cur.take(remaining_bytes - 32)?.to_vec();
let mac_tag: MacTag = cur.extract()?;
let bx = proto_input.b.diffie_hellman(&X);
let (enc_key, mac_key) = get_introduce1_key_material(
&bx,
&proto_input.auth_key,
&X,
&proto_input.B,
&proto_input.subcredential,
)?;
let mut mac_body: Vec<u8> = Vec::new();
mac_body.extend(proto_input.intro_cell_data.clone());
mac_body.extend(ciphertext.clone());
let my_mac_tag = hs_ntor_mac(&mac_body, &mac_key)?;
if my_mac_tag != mac_tag {
return Err(Error::BadCircHandshake);
}
let zero_iv = GenericArray::default();
let mut cipher = Aes256Ctr::new(&enc_key.into(), &zero_iv);
cipher.apply_keystream(ciphertext);
let plaintext = ciphertext;
let y = curve25519::EphemeralSecret::new(rng.rng_compat());
let Y = curve25519::PublicKey::from(&y);
let xy = y.diffie_hellman(&X);
let xb = proto_input.b.diffie_hellman(&X);
let (keygen, auth_input_mac) =
get_rendezvous1_key_material(&xy, &xb, &proto_input.auth_key, &proto_input.B, &X, &Y)?;
let mut reply: Vec<u8> = Vec::new();
reply.write(&Y);
reply.write(&auth_input_mac);
Ok((keygen, reply, plaintext.clone()))
}
fn hs_ntor_mac(key: &[u8], message: &[u8]) -> Result<MacTag> {
let k_len = key.len();
let mut d = Sha3_256::new();
d.update((k_len as u64).to_be_bytes());
d.update(key);
d.update(message);
let result = d.finalize();
result
.try_into()
.map_err(into_internal!("failed MAC computation"))
.map_err(Error::from)
}
fn get_introduce1_key_material(
bx: &curve25519::SharedSecret,
auth_key: &ed25519::PublicKey,
X: &curve25519::PublicKey,
B: &curve25519::PublicKey,
subcredential: &Subcredential,
) -> Result<(EncKey, MacKey)> {
let hs_ntor_protoid_constant = &b"tor-hs-ntor-curve25519-sha3-256-1"[..];
let hs_ntor_key_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_extract"[..];
let hs_ntor_expand_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_expand"[..];
let mut secret_input = Zeroizing::new(Vec::new());
secret_input.write(bx);
secret_input.write(auth_key);
secret_input.write(X);
secret_input.write(B);
secret_input.write(hs_ntor_protoid_constant);
secret_input.write(hs_ntor_key_constant);
secret_input.write(hs_ntor_expand_constant);
secret_input.write(subcredential);
let hs_keys = ShakeKdf::new().derive(&secret_input[..], 32 + 32)?;
let enc_key = hs_keys[0..32]
.try_into()
.map_err(into_internal!("converting enc_key"))
.map_err(Error::from)?;
let mac_key = hs_keys[32..64]
.try_into()
.map_err(into_internal!("converting mac_key"))
.map_err(Error::from)?;
Ok((enc_key, mac_key))
}
fn get_rendezvous1_key_material(
xy: &curve25519::SharedSecret,
xb: &curve25519::SharedSecret,
auth_key: &ed25519::PublicKey,
B: &curve25519::PublicKey,
X: &curve25519::PublicKey,
Y: &curve25519::PublicKey,
) -> Result<(HsNtorHkdfKeyGenerator, AuthInputMac)> {
let hs_ntor_protoid_constant = &b"tor-hs-ntor-curve25519-sha3-256-1"[..];
let hs_ntor_mac_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_mac"[..];
let hs_ntor_verify_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_verify"[..];
let server_string_constant = &b"Server"[..];
let hs_ntor_expand_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_expand"[..];
let hs_ntor_key_constant = &b"tor-hs-ntor-curve25519-sha3-256-1:hs_key_extract"[..];
let mut secret_input = Zeroizing::new(Vec::new());
secret_input.write(xy);
secret_input.write(xb);
secret_input.write(auth_key);
secret_input.write(B);
secret_input.write(X);
secret_input.write(Y);
secret_input.write(hs_ntor_protoid_constant);
let ntor_key_seed = hs_ntor_mac(&secret_input, hs_ntor_key_constant)?;
let verify = hs_ntor_mac(&secret_input, hs_ntor_verify_constant)?;
let mut auth_input = Zeroizing::new(Vec::new());
auth_input.write(&verify);
auth_input.write(auth_key);
auth_input.write(B);
auth_input.write(Y);
auth_input.write(X);
auth_input.write(hs_ntor_protoid_constant);
auth_input.write(server_string_constant);
let auth_input_mac = hs_ntor_mac(&auth_input, hs_ntor_mac_constant)?;
let mut kdf_seed = Zeroizing::new(Vec::new());
kdf_seed.write(&ntor_key_seed);
kdf_seed.write(hs_ntor_expand_constant);
let keygen = HsNtorHkdfKeyGenerator::new(Zeroizing::new(kdf_seed.to_vec()));
Ok((keygen, auth_input_mac))
}
#[cfg(test)]
mod test {
use super::*;
use hex_literal::hex;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn hs_ntor() -> Result<()> {
let mut rng = testing_rng().rng_compat();
let intro_b_privkey = curve25519::StaticSecret::new(&mut rng);
let intro_b_pubkey = curve25519::PublicKey::from(&intro_b_privkey);
let intro_auth_key_privkey = ed25519::SecretKey::generate(&mut rng);
let intro_auth_key_pubkey = ed25519::PublicKey::from(&intro_auth_key_privkey);
let client_keys = HsNtorClientInput::new(
intro_b_pubkey,
intro_auth_key_pubkey,
[5; 32],
vec![66; 10],
vec![42; 60],
);
let service_keys = HsNtorServiceInput::new(
intro_b_privkey,
intro_b_pubkey,
intro_auth_key_pubkey,
[5; 32],
vec![42; 60],
);
let (state, cmsg) = client_send_intro(&mut rng, &client_keys)?;
let (skeygen, smsg, s_plaintext) = server_receive_intro(&mut rng, &service_keys, cmsg)?;
assert_eq!(s_plaintext, vec![66; 10]);
let ckeygen = client_receive_rend(&state, smsg)?;
let skeys = skeygen.expand(128)?;
let ckeys = ckeygen.expand(128)?;
assert_eq!(skeys, ckeys);
Ok(())
}
#[test]
fn ntor_mac() -> Result<()> {
let result = hs_ntor_mac("who".as_bytes(), b"knows?")?;
assert_eq!(
&result,
&hex!("5e7da329630fdaa3eab7498bb1dc625bbb9ca968f10392b6af92d51d5db17473")
);
let result = hs_ntor_mac("gone".as_bytes(), b"by")?;
assert_eq!(
&result,
&hex!("90071aabb06d3f7c777db41542f4790c7dd9e2e7b2b842f54c9c42bbdb37e9a0")
);
Ok(())
}
}