1
//! Implements the ntor v3 key exchange, as described in proposal 332.
2
//!
3
//! The main difference between the ntor v3r handshake and the
4
//! original ntor handshake is that this this one allows each party to
5
//! encrypt data (without forward secrecy) after it sends the first
6
//! message.
7

            
8
// TODO:
9
//    Remove any "allow" attributes for dead_code.
10
//    Make terminology and variable names consistent with spec.
11

            
12
use std::borrow::Borrow;
13
use std::marker::PhantomData;
14

            
15
use super::{RelayHandshakeError, RelayHandshakeResult};
16
use crate::util::ct;
17
use crate::{Error, Result};
18
use tor_bytes::{EncodeResult, Reader, SecretBuf, Writeable, Writer};
19
use tor_error::into_internal;
20
use tor_llcrypto::d::{Sha3_256, Shake256, Shake256Reader};
21
use tor_llcrypto::pk::{curve25519, ed25519::Ed25519Identity};
22
use tor_llcrypto::util::ct::ct_lookup;
23

            
24
use cipher::{KeyIvInit, StreamCipher};
25

            
26
use crate::crypto::handshake::KeyGenerator;
27
use rand_core::{CryptoRng, Rng};
28
use subtle::{Choice, ConstantTimeEq};
29
use tor_cell::relaycell::extend::{CircRequestExt, CircResponseExt};
30
use tor_llcrypto::cipher::aes::Aes256Ctr;
31
use zeroize::Zeroizing;
32

            
33
/// The verification string to be used for circuit extension.
34
const NTOR3_CIRC_VERIFICATION: &[u8] = b"circuit extend";
35

            
36
/// The size of an encryption key in bytes.
37
const ENC_KEY_LEN: usize = 32;
38
/// The size of a MAC key in bytes.
39
const MAC_KEY_LEN: usize = 32;
40
/// The size of a curve25519 public key in bytes.
41
#[allow(dead_code)] // TODO #1467
42
const PUB_KEY_LEN: usize = 32;
43
/// The size of a digest output in bytes.
44
const DIGEST_LEN: usize = 32;
45
/// The length of a MAC output in bytes.
46
const MAC_LEN: usize = 32;
47
/// The length of a node identity in bytes.
48
#[allow(dead_code)] // TODO #1467
49
const ID_LEN: usize = 32;
50

            
51
/// The output of the digest, as an array.
52
type DigestVal = [u8; DIGEST_LEN];
53
/// The output of the MAC.
54
type MacVal = [u8; MAC_LEN];
55
/// A key for symmetric encryption or decryption.
56
//
57
// TODO (nickm): Any move operations applied to this key could subvert the zeroizing.
58
type EncKey = Zeroizing<[u8; ENC_KEY_LEN]>;
59
/// A key for message authentication codes.
60
#[allow(dead_code)] // TODO #1467
61
type MacKey = [u8; MAC_KEY_LEN];
62

            
63
/// Opaque wrapper type for NtorV3's hash reader.
64
struct NtorV3XofReader(Shake256Reader);
65

            
66
impl digest::XofReader for NtorV3XofReader {
67
32
    fn read(&mut self, buffer: &mut [u8]) {
68
32
        self.0.read(buffer);
69
32
    }
70
}
71

            
72
/// An encapsulated value for passing as input to a MAC, digest, or
73
/// KDF algorithm.
74
///
75
/// This corresponds to the ENCAP() function in proposal 332.
76
struct Encap<'a>(&'a [u8]);
77

            
78
impl<'a> Writeable for Encap<'a> {
79
416
    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()> {
80
416
        b.write_u64(self.0.len() as u64);
81
416
        b.write(self.0)
82
416
    }
83
}
84

            
85
impl<'a> Encap<'a> {
86
    /// Return the length of the underlying data in bytes.
87
100
    fn len(&self) -> usize {
88
100
        self.0.len()
89
100
    }
90
    /// Return the underlying data
91
100
    fn data(&self) -> &'a [u8] {
92
100
        self.0
93
100
    }
94
}
95

            
96
/// Helper to define a set of tweak values as instances of `Encap`.
97
macro_rules! define_tweaks {
98
    {
99
        $(#[$pid_meta:meta])*
100
        PROTOID = $protoid:expr;
101
        $( $(#[$meta:meta])* $name:ident <= $suffix:expr ; )*
102
    } => {
103
        $(#[$pid_meta])*
104
        const PROTOID: &'static [u8] = $protoid.as_bytes();
105
        $(
106
            $(#[$meta])*
107
            const $name : Encap<'static> =
108
                Encap(concat!($protoid, ":", $suffix).as_bytes());
109
        )*
110
    }
111
}
112

            
113
define_tweaks! {
114
    /// Protocol ID: concatenated with other things in the protocol to
115
    /// prevent hash confusion.
116
    PROTOID =  "ntor3-curve25519-sha3_256-1";
117

            
118
    /// Message MAC tweak: used to compute the MAC of an encrypted client
119
    /// message.
120
    T_MSGMAC <= "msg_mac";
121
    /// Message KDF tweak: used when deriving keys for encrypting and MACing
122
    /// client message.
123
    T_MSGKDF <= "kdf_phase1";
124
    /// Key seeding tweak: used to derive final KDF input from secret_input.
125
    T_KEY_SEED <= "key_seed";
126
    /// Verifying tweak: used to derive 'verify' value from secret_input.
127
    T_VERIFY <= "verify";
128
    /// Final KDF tweak: used to derive keys for encrypting relay message
129
    /// and for the actual tor circuit.
130
    T_FINAL <= "kdf_final";
131
    /// Authentication tweak: used to derive the final authentication
132
    /// value for the handshake.
133
    T_AUTH <= "auth_final";
134
}
135

            
136
/// Compute a tweaked hash.
137
100
fn hash(t: &Encap<'_>, data: &[u8]) -> DigestVal {
138
    use digest::Digest;
139
100
    let mut d = Sha3_256::new();
140
100
    d.update((t.len() as u64).to_be_bytes());
141
100
    d.update(t.data());
142
100
    d.update(data);
143
100
    d.finalize().into()
144
100
}
145

            
146
/// Perform a symmetric encryption operation and return the encrypted data.
147
///
148
/// (This isn't safe to do more than once with the same key, but we never
149
/// do that in this protocol.)
150
104
fn encrypt(key: &EncKey, m: &[u8]) -> Vec<u8> {
151
104
    let mut d = m.to_vec();
152
104
    let zero_iv = Default::default();
153
104
    let mut cipher = Aes256Ctr::new((&**key).into(), &zero_iv);
154
104
    cipher.apply_keystream(&mut d);
155
104
    d
156
104
}
157
/// Perform a symmetric decryption operation and return the encrypted data.
158
50
fn decrypt(key: &EncKey, m: &[u8]) -> Vec<u8> {
159
50
    encrypt(key, m)
160
50
}
161

            
162
/// Wrapper around a Digest or ExtendedOutput object that lets us use it
163
/// as a tor_bytes::Writer.
164
struct DigestWriter<U>(U);
165
impl<U: digest::Update> tor_bytes::Writer for DigestWriter<U> {
166
1668
    fn write_all(&mut self, bytes: &[u8]) {
167
1668
        self.0.update(bytes);
168
1668
    }
169
}
170
impl<U> DigestWriter<U> {
171
    /// Consume this wrapper and return the underlying object.
172
208
    fn take(self) -> U {
173
208
        self.0
174
208
    }
175
}
176

            
177
/// Hash tweaked with T_KEY_SEED
178
50
fn h_key_seed(d: &[u8]) -> DigestVal {
179
50
    hash(&T_KEY_SEED, d)
180
50
}
181
/// Hash tweaked with T_VERIFY
182
50
fn h_verify(d: &[u8]) -> DigestVal {
183
50
    hash(&T_VERIFY, d)
184
50
}
185

            
186
/// Helper: compute the encryption key and mac_key for the client's
187
/// encrypted message.
188
///
189
/// Takes as inputs `xb` (the shared secret derived from
190
/// diffie-hellman as Bx or Xb), the relay's public key information,
191
/// the client's public key (B), and the shared verification string.
192
54
fn kdf_msgkdf(
193
54
    xb: &curve25519::SharedSecret,
194
54
    relay_public: &NtorV3PublicKey,
195
54
    client_public: &curve25519::PublicKey,
196
54
    verification: &[u8],
197
54
) -> EncodeResult<(EncKey, DigestWriter<Sha3_256>)> {
198
    // secret_input_phase1 = Bx | ID | X | B | PROTOID | ENCAP(VER)
199
    // phase1_keys = KDF_msgkdf(secret_input_phase1)
200
    // (ENC_K1, MAC_K1) = PARTITION(phase1_keys, ENC_KEY_LEN, MAC_KEY_LEN
201
    use digest::{ExtendableOutput, XofReader};
202
54
    let mut msg_kdf = DigestWriter(Shake256::default());
203
54
    msg_kdf.write(&T_MSGKDF)?;
204
54
    msg_kdf.write(xb)?;
205
54
    msg_kdf.write(&relay_public.id)?;
206
54
    msg_kdf.write(client_public)?;
207
54
    msg_kdf.write(&relay_public.pk)?;
208
54
    msg_kdf.write(PROTOID)?;
209
54
    msg_kdf.write(&Encap(verification))?;
210
54
    let mut r = msg_kdf.take().finalize_xof();
211
54
    let mut enc_key = Zeroizing::new([0; ENC_KEY_LEN]);
212
54
    let mut mac_key = Zeroizing::new([0; MAC_KEY_LEN]);
213

            
214
54
    r.read(&mut enc_key[..]);
215
54
    r.read(&mut mac_key[..]);
216
54
    let mut mac = DigestWriter(Sha3_256::default());
217
    {
218
54
        mac.write(&T_MSGMAC)?;
219
54
        mac.write(&Encap(&mac_key[..]))?;
220
54
        mac.write(&relay_public.id)?;
221
54
        mac.write(&relay_public.pk)?;
222
54
        mac.write(client_public)?;
223
    }
224

            
225
54
    Ok((enc_key, mac))
226
54
}
227

            
228
/// Client side of the ntor v3 handshake.
229
pub(crate) struct NtorV3Client;
230

            
231
impl super::ClientHandshake for NtorV3Client {
232
    type KeyType = NtorV3PublicKey;
233
    type StateType = NtorV3HandshakeState;
234
    type KeyGen = NtorV3KeyGenerator;
235
    type ClientAuxData = [CircRequestExt];
236
    type ServerAuxData = Vec<CircResponseExt>;
237

            
238
    /// Generate a new client onionskin for a relay with a given onion key.
239
    /// If any `extensions` are provided, encode them into to the onionskin.
240
    ///
241
    /// On success, return a state object that will be used to complete the handshake, along
242
    /// with the message to send.
243
27
    fn client1<R: Rng + CryptoRng, M: Borrow<[CircRequestExt]>>(
244
27
        rng: &mut R,
245
27
        key: &NtorV3PublicKey,
246
27
        extensions: &M,
247
27
    ) -> Result<(Self::StateType, Vec<u8>)> {
248
27
        let mut message = Vec::new();
249
27
        CircRequestExt::write_many_onto(extensions.borrow(), &mut message)
250
27
            .map_err(|e| Error::from_bytes_enc(e, "ntor3 handshake extensions"))?;
251
        Ok(
252
27
            client_handshake_ntor_v3(rng, key, &message, NTOR3_CIRC_VERIFICATION)
253
27
                .map_err(into_internal!("Can't encode ntor3 client handshake."))?,
254
        )
255
27
    }
256

            
257
    /// Handle an onionskin from a relay, and produce a key generator.
258
    ///
259
    /// The state object must match the one that was used to make the
260
    /// client onionskin that the server is replying to.
261
23
    fn client2<T: AsRef<[u8]>>(
262
23
        state: Self::StateType,
263
23
        msg: T,
264
23
    ) -> Result<(Vec<CircResponseExt>, Self::KeyGen)> {
265
23
        let (message, xofreader) =
266
23
            client_handshake_ntor_v3_part2(&state, msg.as_ref(), NTOR3_CIRC_VERIFICATION)?;
267
23
        let extensions = CircResponseExt::decode(&message).map_err(|err| Error::CellDecodeErr {
268
            object: "ntor v3 extensions",
269
            err,
270
        })?;
271
23
        let keygen = NtorV3KeyGenerator { reader: xofreader };
272

            
273
23
        Ok((extensions, keygen))
274
23
    }
275
}
276

            
277
/// Server side of the ntor v3 handshake.
278
pub(crate) struct NtorV3Server<K: NtorV3ServerKeys> {
279
    /// The `ServerHandshake` trait requires the `KeyType` to be a property of the implementer,
280
    /// so this generic needs to go here. ¯\_(ツ)_/¯
281
    _phantom: PhantomData<K>,
282
}
283

            
284
impl<K: NtorV3ServerKeys> super::ServerHandshake for NtorV3Server<K> {
285
    type KeyType = K;
286
    type KeyGen = NtorV3KeyGenerator;
287
    type ClientAuxData = [CircRequestExt];
288
    type ServerAuxData = Vec<CircResponseExt>;
289

            
290
26
    fn server<R: Rng + CryptoRng, REPLY: super::AuxDataReply<Self>, T: AsRef<[u8]>>(
291
26
        rng: &mut R,
292
26
        reply_fn: &mut REPLY,
293
26
        keys: &[Self::KeyType],
294
26
        msg: T,
295
26
    ) -> RelayHandshakeResult<(Self::KeyGen, Vec<u8>)> {
296
26
        let mut bytes_reply_fn = |bytes: &[u8]| -> Option<Vec<u8>> {
297
23
            let client_exts = CircRequestExt::decode(bytes).ok()?;
298
23
            let reply_exts = reply_fn.reply(&client_exts)?;
299
23
            let mut out = vec![];
300
23
            CircResponseExt::write_many_onto(&reply_exts, &mut out).ok()?;
301
23
            Some(out)
302
23
        };
303

            
304
26
        let (res, reader) = server_handshake_ntor_v3(
305
26
            rng,
306
26
            &mut bytes_reply_fn,
307
26
            msg.as_ref(),
308
26
            keys,
309
26
            NTOR3_CIRC_VERIFICATION,
310
3
        )?;
311
23
        Ok((NtorV3KeyGenerator { reader }, res))
312
26
    }
313
}
314

            
315
/// An object holding the keys necessary for a server-side ntor v3 handshake.
316
pub(crate) trait NtorV3ServerKeys {
317
    /// The server's identity.
318
    fn ident(&self) -> &Ed25519Identity;
319

            
320
    /// The server's public key.
321
    fn public_key(&self) -> &curve25519::PublicKey;
322

            
323
    /// The server's secret key.
324
    fn secret_key(&self) -> &curve25519::StaticSecret;
325

            
326
    /// Return true if `id` and `pk` match this set of keys.
327
    ///
328
    /// Used to perform a constant-time secret key lookup.
329
    ///
330
    /// This should not be implemented manually.
331
28
    fn matches(&self, id: Ed25519Identity, pk: curve25519::PublicKey) -> Choice {
332
28
        let pk_self = NtorV3PublicKey {
333
28
            id: *self.ident(),
334
28
            pk: *self.public_key(),
335
28
        };
336
28
        let pk_other = NtorV3PublicKey { id, pk };
337
28
        pk_self.ct_eq(&pk_other)
338
28
    }
339
}
340

            
341
/// Key information about a relay used for the ntor v3 handshake.
342
///
343
/// Contains a single curve25519 ntor onion key, and the relay's ed25519
344
/// identity.
345
#[derive(Clone, Debug)]
346
pub(crate) struct NtorV3PublicKey {
347
    /// The relay's identity.
348
    pub(crate) id: Ed25519Identity,
349
    /// The relay's onion key.
350
    pub(crate) pk: curve25519::PublicKey,
351
}
352

            
353
impl ConstantTimeEq for NtorV3PublicKey {
354
28
    fn ct_eq(&self, other: &Self) -> Choice {
355
        // TODO: use similar pattern in ntor_v1!
356
28
        self.id.as_bytes().ct_eq(other.id.as_bytes())
357
28
            & self.pk.as_bytes().ct_eq(other.pk.as_bytes())
358
28
    }
359
}
360

            
361
/// Client state for the ntor v3 handshake.
362
///
363
/// The client needs to hold this state between when it sends its part
364
/// of the handshake and when it receives the relay's reply.
365
pub(crate) struct NtorV3HandshakeState {
366
    /// The public key of the relay we're communicating with.
367
    relay_public: NtorV3PublicKey, // B, ID.
368
    /// Our ephemeral secret key for this handshake.
369
    my_sk: curve25519::StaticSecret, // x
370
    /// Our ephemeral public key for this handshake.
371
    my_public: curve25519::PublicKey, // X
372

            
373
    /// The shared secret generated as Bx or Xb.
374
    shared_secret: curve25519::SharedSecret, // Bx
375
    /// The MAC of our original encrypted message.
376
    msg_mac: MacVal, // msg_mac
377
}
378

            
379
/// A key generator returned from an ntor v3 handshake.
380
pub(crate) struct NtorV3KeyGenerator {
381
    /// The underlying `digest::XofReader`.
382
    reader: NtorV3XofReader,
383
}
384

            
385
impl KeyGenerator for NtorV3KeyGenerator {
386
28
    fn expand(mut self, keylen: usize) -> Result<SecretBuf> {
387
        use digest::XofReader;
388
28
        let mut ret: SecretBuf = vec![0; keylen].into();
389
28
        self.reader.read(ret.as_mut());
390
28
        Ok(ret)
391
28
    }
392
}
393

            
394
/// Client-side Ntor version 3 handshake, part one.
395
///
396
/// Given a secure `rng`, a relay's public key, a secret message to send,
397
/// and a shared verification string, generate a new handshake state
398
/// and a message to send to the relay.
399
28
fn client_handshake_ntor_v3<R: Rng + CryptoRng>(
400
28
    rng: &mut R,
401
28
    relay_public: &NtorV3PublicKey,
402
28
    client_msg: &[u8],
403
28
    verification: &[u8],
404
28
) -> EncodeResult<(NtorV3HandshakeState, Vec<u8>)> {
405
28
    let my_sk = curve25519::StaticSecret::random_from_rng(rng);
406
28
    client_handshake_ntor_v3_no_keygen(relay_public, client_msg, verification, my_sk)
407
28
}
408

            
409
/// As `client_handshake_ntor_v3`, but don't generate an ephemeral DH
410
/// key: instead take that key an arguments `my_sk`.
411
29
fn client_handshake_ntor_v3_no_keygen(
412
29
    relay_public: &NtorV3PublicKey,
413
29
    client_msg: &[u8],
414
29
    verification: &[u8],
415
29
    my_sk: curve25519::StaticSecret,
416
29
) -> EncodeResult<(NtorV3HandshakeState, Vec<u8>)> {
417
29
    let my_public = curve25519::PublicKey::from(&my_sk);
418
29
    let bx = my_sk.diffie_hellman(&relay_public.pk);
419

            
420
29
    let (enc_key, mut mac) = kdf_msgkdf(&bx, relay_public, &my_public, verification)?;
421

            
422
    //encrypted_msg = ENC(ENC_K1, CM)
423
    // msg_mac = MAC_msgmac(MAC_K1, ID | B | X | encrypted_msg)
424
29
    let encrypted_msg = encrypt(&enc_key, client_msg);
425
29
    let msg_mac: DigestVal = {
426
        use digest::Digest;
427
29
        mac.write(&encrypted_msg)?;
428
29
        mac.take().finalize().into()
429
    };
430

            
431
29
    let mut message = Vec::new();
432
29
    message.write(&relay_public.id)?;
433
29
    message.write(&relay_public.pk)?;
434
29
    message.write(&my_public)?;
435
29
    message.write(&encrypted_msg)?;
436
29
    message.write(&msg_mac)?;
437

            
438
29
    let state = NtorV3HandshakeState {
439
29
        relay_public: relay_public.clone(),
440
29
        my_sk,
441
29
        my_public,
442
29
        shared_secret: bx,
443
29
        msg_mac,
444
29
    };
445

            
446
29
    Ok((state, message))
447
29
}
448

            
449
/// Trait for an object that handle and incoming client message and
450
/// return a server's reply.
451
///
452
/// This is implemented for `FnMut(&[u8]) -> Option<Vec<u8>>` automatically.
453
pub(crate) trait MsgReply {
454
    /// Given a message received from a client, parse it and decide
455
    /// how (and whether) to reply.
456
    ///
457
    /// Return None if the handshake should fail.
458
    fn reply(&mut self, msg: &[u8]) -> Option<Vec<u8>>;
459
}
460

            
461
impl<F> MsgReply for F
462
where
463
    F: FnMut(&[u8]) -> Option<Vec<u8>>,
464
{
465
23
    fn reply(&mut self, msg: &[u8]) -> Option<Vec<u8>> {
466
23
        self(msg)
467
23
    }
468
}
469

            
470
/// Complete an ntor v3 handshake as a server.
471
///
472
/// Use the provided `rng` to generate keys; use the provided
473
/// `reply_fn` to handle incoming client secret message and decide how
474
/// to reply.  The client's handshake is in `message`.  Our private
475
/// key(s) are in `keys`.  The `verification` string must match the
476
/// string provided by the client.
477
///
478
/// On success, return the server handshake message to send, and an XofReader
479
/// to use in generating circuit keys.
480
27
fn server_handshake_ntor_v3<RNG: CryptoRng + Rng, REPLY: MsgReply, K: NtorV3ServerKeys>(
481
27
    rng: &mut RNG,
482
27
    reply_fn: &mut REPLY,
483
27
    message: &[u8],
484
27
    keys: &[K],
485
27
    verification: &[u8],
486
27
) -> RelayHandshakeResult<(Vec<u8>, NtorV3XofReader)> {
487
27
    let secret_key_y = curve25519::StaticSecret::random_from_rng(rng);
488
27
    server_handshake_ntor_v3_no_keygen(reply_fn, &secret_key_y, message, keys, verification)
489
27
}
490

            
491
/// As `server_handshake_ntor_v3`, but take a secret key instead of an RNG.
492
28
fn server_handshake_ntor_v3_no_keygen<REPLY: MsgReply, K: NtorV3ServerKeys>(
493
28
    reply_fn: &mut REPLY,
494
28
    secret_key_y: &curve25519::StaticSecret,
495
28
    message: &[u8],
496
28
    keys: &[K],
497
28
    verification: &[u8],
498
28
) -> RelayHandshakeResult<(Vec<u8>, NtorV3XofReader)> {
499
    // Decode the message.
500
28
    let mut r = Reader::from_slice(message);
501
28
    let id: Ed25519Identity = r.extract()?;
502
28
    let requested_pk: curve25519::PublicKey = r.extract()?;
503
28
    let client_pk: curve25519::PublicKey = r.extract()?;
504
28
    let client_msg = r.take_all_but(MAC_LEN)?;
505
28
    let msg_mac: MacVal = r.extract()?;
506
28
    r.should_be_exhausted()?;
507

            
508
    // See if we recognize the provided (id,requested_pk) pair.
509
28
    let keypair = ct_lookup(keys, |key| key.matches(id, requested_pk));
510
28
    let keypair = match keypair {
511
25
        Some(k) => k,
512
3
        None => return Err(RelayHandshakeError::MissingKey),
513
    };
514

            
515
25
    let xb = keypair.secret_key().diffie_hellman(&client_pk);
516
    // TODO: Update `kdf_msgkdf()` so that we don't need to copy these bytes.
517
25
    let relay_pk = NtorV3PublicKey {
518
25
        id: *keypair.ident(),
519
25
        pk: *keypair.public_key(),
520
25
    };
521
25
    let (enc_key, mut mac) = kdf_msgkdf(&xb, &relay_pk, &client_pk, verification)
522
25
        .map_err(into_internal!("Can't apply ntor3 kdf."))?;
523
    // Verify the message we received.
524
25
    let computed_mac: DigestVal = {
525
        use digest::Digest;
526
25
        mac.write(client_msg)
527
25
            .map_err(into_internal!("Can't compute MAC input."))?;
528
25
        mac.take().finalize().into()
529
    };
530
25
    let y_pk: curve25519::PublicKey = (secret_key_y).into();
531
25
    let xy = secret_key_y.diffie_hellman(&client_pk);
532

            
533
25
    let mut okay = computed_mac.ct_eq(&msg_mac)
534
25
        & ct::bool_to_choice(xy.was_contributory())
535
25
        & ct::bool_to_choice(xb.was_contributory());
536

            
537
25
    let plaintext_msg = decrypt(&enc_key, client_msg);
538

            
539
    // Handle the message and decide how to reply.
540
25
    let reply = reply_fn.reply(&plaintext_msg);
541

            
542
    // It's not exactly constant time to use is_some() and
543
    // unwrap_or_else() here, but that should be somewhat
544
    // hidden by the rest of the computation.
545
25
    okay &= ct::bool_to_choice(reply.is_some());
546
25
    let reply = reply.unwrap_or_default();
547

            
548
    // If we reach this point, we are actually replying, or pretending
549
    // that we're going to reply.
550

            
551
25
    let secret_input = {
552
25
        let mut si = SecretBuf::new();
553
25
        si.write(&xy)
554
25
            .and_then(|_| si.write(&xb))
555
25
            .and_then(|_| si.write(keypair.ident()))
556
25
            .and_then(|_| si.write(keypair.public_key()))
557
25
            .and_then(|_| si.write(&client_pk))
558
25
            .and_then(|_| si.write(&y_pk))
559
25
            .and_then(|_| si.write(PROTOID))
560
25
            .and_then(|_| si.write(&Encap(verification)))
561
25
            .map_err(into_internal!("can't derive ntor3 secret_input"))?;
562
25
        si
563
    };
564
25
    let ntor_key_seed = h_key_seed(&secret_input);
565
25
    let verify = h_verify(&secret_input);
566

            
567
25
    let (enc_key, keystream) = {
568
        use digest::{ExtendableOutput, XofReader};
569
25
        let mut xof = DigestWriter(Shake256::default());
570
25
        xof.write(&T_FINAL)
571
25
            .and_then(|_| xof.write(&ntor_key_seed))
572
25
            .map_err(into_internal!("can't generate ntor3 xof."))?;
573
25
        let mut r = xof.take().finalize_xof();
574
25
        let mut enc_key = Zeroizing::new([0_u8; ENC_KEY_LEN]);
575
25
        r.read(&mut enc_key[..]);
576
25
        (enc_key, r)
577
    };
578
25
    let encrypted_reply = encrypt(&enc_key, &reply);
579
25
    let auth: DigestVal = {
580
        use digest::Digest;
581
25
        let mut auth = DigestWriter(Sha3_256::default());
582
25
        auth.write(&T_AUTH)
583
25
            .and_then(|_| auth.write(&verify))
584
25
            .and_then(|_| auth.write(keypair.ident()))
585
25
            .and_then(|_| auth.write(keypair.public_key()))
586
25
            .and_then(|_| auth.write(&y_pk))
587
25
            .and_then(|_| auth.write(&client_pk))
588
25
            .and_then(|_| auth.write(&msg_mac))
589
25
            .and_then(|_| auth.write(&Encap(&encrypted_reply)))
590
25
            .and_then(|_| auth.write(PROTOID))
591
25
            .and_then(|_| auth.write(&b"Server"[..]))
592
25
            .map_err(into_internal!("can't derive ntor3 authentication"))?;
593
25
        auth.take().finalize().into()
594
    };
595

            
596
25
    let reply = {
597
25
        let mut reply = Vec::new();
598
25
        reply
599
25
            .write(&y_pk)
600
25
            .and_then(|_| reply.write(&auth))
601
25
            .and_then(|_| reply.write(&encrypted_reply))
602
25
            .map_err(into_internal!("can't encode ntor3 reply."))?;
603
25
        reply
604
    };
605

            
606
25
    if okay.into() {
607
25
        Ok((reply, NtorV3XofReader(keystream)))
608
    } else {
609
        Err(RelayHandshakeError::BadClientHandshake)
610
    }
611
28
}
612

            
613
/// Finalize the handshake on the client side.
614
///
615
/// Called after we've received a message from the relay: try to
616
/// complete the handshake and verify its correctness.
617
///
618
/// On success, return the server's reply to our original encrypted message,
619
/// and an `XofReader` to use in generating circuit keys.
620
25
fn client_handshake_ntor_v3_part2(
621
25
    state: &NtorV3HandshakeState,
622
25
    relay_handshake: &[u8],
623
25
    verification: &[u8],
624
25
) -> Result<(Vec<u8>, NtorV3XofReader)> {
625
25
    let mut reader = Reader::from_slice(relay_handshake);
626
25
    let y_pk: curve25519::PublicKey = reader
627
25
        .extract()
628
25
        .map_err(|e| Error::from_bytes_err(e, "v3 ntor handshake"))?;
629
25
    let auth: DigestVal = reader
630
25
        .extract()
631
25
        .map_err(|e| Error::from_bytes_err(e, "v3 ntor handshake"))?;
632
25
    let encrypted_msg = reader.into_rest();
633

            
634
    // TODO: Some of this code is duplicated from the server handshake code!  It
635
    // would be better to factor it out.
636
25
    let yx = state.my_sk.diffie_hellman(&y_pk);
637
25
    let secret_input = {
638
25
        let mut si = SecretBuf::new();
639
25
        si.write(&yx)
640
25
            .and_then(|_| si.write(&state.shared_secret))
641
25
            .and_then(|_| si.write(&state.relay_public.id))
642
25
            .and_then(|_| si.write(&state.relay_public.pk))
643
25
            .and_then(|_| si.write(&state.my_public))
644
25
            .and_then(|_| si.write(&y_pk))
645
25
            .and_then(|_| si.write(PROTOID))
646
25
            .and_then(|_| si.write(&Encap(verification)))
647
25
            .map_err(into_internal!("error encoding ntor3 secret_input"))?;
648
25
        si
649
    };
650
25
    let ntor_key_seed = h_key_seed(&secret_input);
651
25
    let verify = h_verify(&secret_input);
652

            
653
25
    let computed_auth: DigestVal = {
654
        use digest::Digest;
655
25
        let mut auth = DigestWriter(Sha3_256::default());
656
25
        auth.write(&T_AUTH)
657
25
            .and_then(|_| auth.write(&verify))
658
25
            .and_then(|_| auth.write(&state.relay_public.id))
659
25
            .and_then(|_| auth.write(&state.relay_public.pk))
660
25
            .and_then(|_| auth.write(&y_pk))
661
25
            .and_then(|_| auth.write(&state.my_public))
662
25
            .and_then(|_| auth.write(&state.msg_mac))
663
25
            .and_then(|_| auth.write(&Encap(encrypted_msg)))
664
25
            .and_then(|_| auth.write(PROTOID))
665
25
            .and_then(|_| auth.write(&b"Server"[..]))
666
25
            .map_err(into_internal!("error encoding ntor3 authentication input"))?;
667
25
        auth.take().finalize().into()
668
    };
669

            
670
25
    let okay = computed_auth.ct_eq(&auth)
671
25
        & ct::bool_to_choice(yx.was_contributory())
672
25
        & ct::bool_to_choice(state.shared_secret.was_contributory());
673

            
674
25
    let (enc_key, keystream) = {
675
        use digest::{ExtendableOutput, XofReader};
676
25
        let mut xof = DigestWriter(Shake256::default());
677
25
        xof.write(&T_FINAL)
678
25
            .and_then(|_| xof.write(&ntor_key_seed))
679
25
            .map_err(into_internal!("error encoding ntor3 xof input"))?;
680
25
        let mut r = xof.take().finalize_xof();
681
25
        let mut enc_key = Zeroizing::new([0_u8; ENC_KEY_LEN]);
682
25
        r.read(&mut enc_key[..]);
683
25
        (enc_key, r)
684
    };
685
25
    let server_reply = decrypt(&enc_key, encrypted_msg);
686

            
687
25
    if okay.into() {
688
25
        Ok((server_reply, NtorV3XofReader(keystream)))
689
    } else {
690
        Err(Error::BadCircHandshakeAuth)
691
    }
692
25
}
693

            
694
#[cfg(test)]
695
#[allow(non_snake_case)] // to enable variable names matching the spec.
696
#[allow(clippy::many_single_char_names)] // ibid
697
pub(crate) mod test {
698
    // @@ begin test lint list maintained by maint/add_warning @@
699
    #![allow(clippy::bool_assert_comparison)]
700
    #![allow(clippy::clone_on_copy)]
701
    #![allow(clippy::dbg_macro)]
702
    #![allow(clippy::mixed_attributes_style)]
703
    #![allow(clippy::print_stderr)]
704
    #![allow(clippy::print_stdout)]
705
    #![allow(clippy::single_char_pattern)]
706
    #![allow(clippy::unwrap_used)]
707
    #![allow(clippy::unchecked_time_subtraction)]
708
    #![allow(clippy::useless_vec)]
709
    #![allow(clippy::needless_pass_by_value)]
710
    #![allow(clippy::string_slice)] // See arti#2571
711
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
712
    use crate::crypto::handshake::{ClientHandshake, ServerHandshake};
713

            
714
    use super::*;
715
    use hex_literal::hex;
716
    use tor_basic_utils::test_rng::testing_rng;
717
    use tor_cell::relaycell::extend::{CcRequest, CcResponse, CircResponseExt};
718

            
719
    /// Secret key information used by a relay for the ntor v3 handshake.
720
    pub(crate) struct NtorV3SecretKey {
721
        /// The relay's public key information
722
        pk: NtorV3PublicKey,
723
        /// The secret onion key.
724
        sk: curve25519::StaticSecret,
725
    }
726

            
727
    impl NtorV3SecretKey {
728
        /// Construct a new NtorV3SecretKey from its components.
729
        pub(crate) fn new(
730
            sk: curve25519::StaticSecret,
731
            pk: curve25519::PublicKey,
732
            id: Ed25519Identity,
733
        ) -> Self {
734
            Self {
735
                pk: NtorV3PublicKey { id, pk },
736
                sk,
737
            }
738
        }
739

            
740
        /// Generate a key using the given `rng`, suitable for testing.
741
        pub(crate) fn generate_for_test<R: Rng + CryptoRng>(rng: &mut R) -> Self {
742
            let mut id = [0_u8; 32];
743
            // Random bytes will work for testing, but aren't necessarily actually a valid id.
744
            rng.fill_bytes(&mut id);
745

            
746
            let sk = curve25519::StaticSecret::random_from_rng(rng);
747

            
748
            let pk = NtorV3PublicKey {
749
                pk: (&sk).into(),
750
                id: id.into(),
751
            };
752
            Self { pk, sk }
753
        }
754
    }
755

            
756
    impl NtorV3ServerKeys for NtorV3SecretKey {
757
        fn ident(&self) -> &Ed25519Identity {
758
            &self.pk.id
759
        }
760

            
761
        fn public_key(&self) -> &curve25519::PublicKey {
762
            &self.pk.pk
763
        }
764

            
765
        fn secret_key(&self) -> &curve25519::StaticSecret {
766
            &self.sk
767
        }
768
    }
769

            
770
    #[test]
771
    fn test_ntor3_roundtrip() {
772
        let mut rng = rand::rng();
773
        let relay_private = NtorV3SecretKey::generate_for_test(&mut testing_rng());
774

            
775
        let verification = &b"shared secret"[..];
776
        let client_message = &b"Hello. I am a client. Let's be friends!"[..];
777
        let relay_message = &b"Greetings, client. I am a robot. Beep boop."[..];
778

            
779
        let (c_state, c_handshake) =
780
            client_handshake_ntor_v3(&mut rng, &relay_private.pk, client_message, verification)
781
                .unwrap();
782

            
783
        struct Rep(Vec<u8>, Vec<u8>);
784
        impl MsgReply for Rep {
785
            fn reply(&mut self, msg: &[u8]) -> Option<Vec<u8>> {
786
                self.0 = msg.to_vec();
787
                Some(self.1.clone())
788
            }
789
        }
790
        let mut rep = Rep(Vec::new(), relay_message.to_vec());
791

            
792
        let (s_handshake, mut s_keygen) = server_handshake_ntor_v3(
793
            &mut rng,
794
            &mut rep,
795
            &c_handshake,
796
            &[relay_private],
797
            verification,
798
        )
799
        .unwrap();
800

            
801
        let (s_msg, mut c_keygen) =
802
            client_handshake_ntor_v3_part2(&c_state, &s_handshake, verification).unwrap();
803

            
804
        assert_eq!(rep.0[..], client_message[..]);
805
        assert_eq!(s_msg[..], relay_message[..]);
806
        use digest::XofReader;
807
        let mut s_keys = [0_u8; 100];
808
        let mut c_keys = [0_u8; 1000];
809
        s_keygen.read(&mut s_keys);
810
        c_keygen.read(&mut c_keys);
811
        assert_eq!(s_keys[..], c_keys[..100]);
812
    }
813

            
814
    // Same as previous test, but use the higher-level APIs instead.
815
    #[test]
816
    fn test_ntor3_roundtrip_highlevel() {
817
        let mut rng = rand::rng();
818
        let relay_private = NtorV3SecretKey::generate_for_test(&mut testing_rng());
819

            
820
        let (c_state, c_handshake) =
821
            NtorV3Client::client1(&mut rng, &relay_private.pk, &[]).unwrap();
822

            
823
        let mut rep = |_: &[CircRequestExt]| Some(vec![]);
824

            
825
        let (s_keygen, s_handshake) =
826
            NtorV3Server::server(&mut rng, &mut rep, &[relay_private], &c_handshake).unwrap();
827

            
828
        let (extensions, keygen) = NtorV3Client::client2(c_state, s_handshake).unwrap();
829

            
830
        assert!(extensions.is_empty());
831
        let c_keys = keygen.expand(1000).unwrap();
832
        let s_keys = s_keygen.expand(100).unwrap();
833
        assert_eq!(s_keys[..], c_keys[..100]);
834
    }
835

            
836
    // Same as previous test, but encode some congestion control extensions.
837
    #[test]
838
    fn test_ntor3_roundtrip_highlevel_cc() {
839
        let mut rng = rand::rng();
840
        let relay_private = NtorV3SecretKey::generate_for_test(&mut testing_rng());
841

            
842
        let client_exts = vec![CircRequestExt::CcRequest(CcRequest::default())];
843
        let reply_exts = vec![CircResponseExt::CcResponse(CcResponse::new(42))];
844

            
845
        let (c_state, c_handshake) = NtorV3Client::client1(
846
            &mut rng,
847
            &relay_private.pk,
848
            &[CircRequestExt::CcRequest(CcRequest::default())],
849
        )
850
        .unwrap();
851

            
852
        let mut rep = |msg: &[CircRequestExt]| -> Option<Vec<CircResponseExt>> {
853
            assert_eq!(msg, client_exts);
854
            Some(reply_exts.clone())
855
        };
856

            
857
        let (s_keygen, s_handshake) =
858
            NtorV3Server::server(&mut rng, &mut rep, &[relay_private], &c_handshake).unwrap();
859

            
860
        let (extensions, keygen) = NtorV3Client::client2(c_state, s_handshake).unwrap();
861

            
862
        assert_eq!(extensions, reply_exts);
863
        let c_keys = keygen.expand(1000).unwrap();
864
        let s_keys = s_keygen.expand(100).unwrap();
865
        assert_eq!(s_keys[..], c_keys[..100]);
866
    }
867

            
868
    #[test]
869
    fn test_ntor3_testvec() {
870
        let b = hex!("4051daa5921cfa2a1c27b08451324919538e79e788a81b38cbed097a5dff454a");
871
        let id = hex!("9fad2af287ef942632833d21f946c6260c33fae6172b60006e86e4a6911753a2");
872
        let x = hex!("b825a3719147bcbe5fb1d0b0fcb9c09e51948048e2e3283d2ab7b45b5ef38b49");
873
        let y = hex!("4865a5b7689dafd978f529291c7171bc159be076b92186405d13220b80e2a053");
874
        let b: curve25519::StaticSecret = b.into();
875
        let B: curve25519::PublicKey = (&b).into();
876
        let id: Ed25519Identity = id.into();
877
        let x: curve25519::StaticSecret = x.into();
878
        //let X = (&x).into();
879
        let y: curve25519::StaticSecret = y.into();
880

            
881
        let client_message = hex!("68656c6c6f20776f726c64");
882
        let verification = hex!("78797a7a79");
883
        let server_message = hex!("486f6c61204d756e646f");
884

            
885
        let relay_public = NtorV3PublicKey { pk: B, id };
886
        let relay_private = NtorV3SecretKey {
887
            sk: b,
888
            pk: relay_public.clone(),
889
        };
890

            
891
        let (state, client_handshake) =
892
            client_handshake_ntor_v3_no_keygen(&relay_public, &client_message, &verification, x)
893
                .unwrap();
894

            
895
        assert_eq!(
896
            client_handshake[..],
897
            hex!(
898
                "9fad2af287ef942632833d21f946c6260c33fae6172b60006e86e4a6911753a2f8307a2bc1870b00b828bb74dbb8fd88e632a6375ab3bcd1ae706aaa8b6cdd1d252fe9ae91264c91d4ecb8501f79d0387e34ad8ca0f7c995184f7d11d5da4f463bebd9151fd3b47c180abc9e044d53565f04d82bbb3bebed3d06cea65db8be9c72b68cd461942088502f67"
899
            )[..]
900
        );
901

            
902
        struct Replier(Vec<u8>, Vec<u8>, bool);
903
        impl MsgReply for Replier {
904
            fn reply(&mut self, msg: &[u8]) -> Option<Vec<u8>> {
905
                assert_eq!(msg, &self.0);
906
                self.2 = true;
907
                Some(self.1.clone())
908
            }
909
        }
910
        let mut rep = Replier(client_message.to_vec(), server_message.to_vec(), false);
911

            
912
        let (server_handshake, mut server_keygen) = server_handshake_ntor_v3_no_keygen(
913
            &mut rep,
914
            &y,
915
            &client_handshake,
916
            &[relay_private],
917
            &verification,
918
        )
919
        .unwrap();
920
        assert!(rep.2);
921

            
922
        assert_eq!(
923
            server_handshake[..],
924
            hex!(
925
                "4bf4814326fdab45ad5184f5518bd7fae25dc59374062698201a50a22954246d2fc5f8773ca824542bc6cf6f57c7c29bbf4e5476461ab130c5b18ab0a91276651202c3e1e87c0d32054c"
926
            )[..]
927
        );
928

            
929
        let (server_msg_received, mut client_keygen) =
930
            client_handshake_ntor_v3_part2(&state, &server_handshake, &verification).unwrap();
931
        assert_eq!(&server_msg_received, &server_message);
932

            
933
        let (c_keys, s_keys) = {
934
            use digest::XofReader;
935
            let mut c = [0_u8; 256];
936
            let mut s = [0_u8; 256];
937
            client_keygen.read(&mut c);
938
            server_keygen.read(&mut s);
939
            (c, s)
940
        };
941
        assert_eq!(c_keys, s_keys);
942
        assert_eq!(
943
            c_keys[..],
944
            hex!(
945
                "9c19b631fd94ed86a817e01f6c80b0743a43f5faebd39cfaa8b00fa8bcc65c3bfeaa403d91acbd68a821bf6ee8504602b094a254392a07737d5662768c7a9fb1b2814bb34780eaee6e867c773e28c212ead563e98a1cd5d5b4576f5ee61c59bde025ff2851bb19b721421694f263818e3531e43a9e4e3e2c661e2ad547d8984caa28ebecd3e4525452299be26b9185a20a90ce1eac20a91f2832d731b54502b09749b5a2a2949292f8cfcbeffb790c7790ed935a9d251e7e336148ea83b063a5618fcff674a44581585fd22077ca0e52c59a24347a38d1a1ceebddbf238541f226b8f88d0fb9c07a1bcd2ea764bbbb5dacdaf5312a14c0b9e4f06309b0333b4a"
946
            )[..]
947
        );
948
    }
949
}