Skip to main content

tor_proto/crypto/handshake/
ntor_v3.rs

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
12use std::borrow::Borrow;
13use std::marker::PhantomData;
14
15use super::{RelayHandshakeError, RelayHandshakeResult};
16use crate::util::ct;
17use crate::{Error, Result};
18use tor_bytes::{EncodeResult, Reader, SecretBuf, Writeable, Writer};
19use tor_error::into_internal;
20use tor_llcrypto::d::{Sha3_256, Shake256, Shake256Reader};
21use tor_llcrypto::pk::{curve25519, ed25519::Ed25519Identity};
22use tor_llcrypto::util::ct::ct_lookup;
23
24use cipher::{KeyIvInit, StreamCipher};
25
26use crate::crypto::handshake::KeyGenerator;
27use rand_core::{CryptoRng, Rng};
28use subtle::{Choice, ConstantTimeEq};
29use tor_cell::relaycell::extend::{CircRequestExt, CircResponseExt};
30use tor_llcrypto::cipher::aes::Aes256Ctr;
31use zeroize::Zeroizing;
32
33/// The verification string to be used for circuit extension.
34const NTOR3_CIRC_VERIFICATION: &[u8] = b"circuit extend";
35
36/// The size of an encryption key in bytes.
37const ENC_KEY_LEN: usize = 32;
38/// The size of a MAC key in bytes.
39const MAC_KEY_LEN: usize = 32;
40/// The size of a curve25519 public key in bytes.
41#[allow(dead_code)] // TODO #1467
42const PUB_KEY_LEN: usize = 32;
43/// The size of a digest output in bytes.
44const DIGEST_LEN: usize = 32;
45/// The length of a MAC output in bytes.
46const MAC_LEN: usize = 32;
47/// The length of a node identity in bytes.
48#[allow(dead_code)] // TODO #1467
49const ID_LEN: usize = 32;
50
51/// The output of the digest, as an array.
52type DigestVal = [u8; DIGEST_LEN];
53/// The output of the MAC.
54type 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.
58type EncKey = Zeroizing<[u8; ENC_KEY_LEN]>;
59/// A key for message authentication codes.
60#[allow(dead_code)] // TODO #1467
61type MacKey = [u8; MAC_KEY_LEN];
62
63/// Opaque wrapper type for NtorV3's hash reader.
64struct NtorV3XofReader(Shake256Reader);
65
66impl digest::XofReader for NtorV3XofReader {
67    fn read(&mut self, buffer: &mut [u8]) {
68        self.0.read(buffer);
69    }
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.
76struct Encap<'a>(&'a [u8]);
77
78impl<'a> Writeable for Encap<'a> {
79    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> EncodeResult<()> {
80        b.write_u64(self.0.len() as u64);
81        b.write(self.0)
82    }
83}
84
85impl<'a> Encap<'a> {
86    /// Return the length of the underlying data in bytes.
87    fn len(&self) -> usize {
88        self.0.len()
89    }
90    /// Return the underlying data
91    fn data(&self) -> &'a [u8] {
92        self.0
93    }
94}
95
96/// Helper to define a set of tweak values as instances of `Encap`.
97macro_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
113define_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.
137fn hash(t: &Encap<'_>, data: &[u8]) -> DigestVal {
138    use digest::Digest;
139    let mut d = Sha3_256::new();
140    d.update((t.len() as u64).to_be_bytes());
141    d.update(t.data());
142    d.update(data);
143    d.finalize().into()
144}
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.)
150fn encrypt(key: &EncKey, m: &[u8]) -> Vec<u8> {
151    let mut d = m.to_vec();
152    let zero_iv = Default::default();
153    let mut cipher = Aes256Ctr::new((&**key).into(), &zero_iv);
154    cipher.apply_keystream(&mut d);
155    d
156}
157/// Perform a symmetric decryption operation and return the encrypted data.
158fn decrypt(key: &EncKey, m: &[u8]) -> Vec<u8> {
159    encrypt(key, m)
160}
161
162/// Wrapper around a Digest or ExtendedOutput object that lets us use it
163/// as a tor_bytes::Writer.
164struct DigestWriter<U>(U);
165impl<U: digest::Update> tor_bytes::Writer for DigestWriter<U> {
166    fn write_all(&mut self, bytes: &[u8]) {
167        self.0.update(bytes);
168    }
169}
170impl<U> DigestWriter<U> {
171    /// Consume this wrapper and return the underlying object.
172    fn take(self) -> U {
173        self.0
174    }
175}
176
177/// Hash tweaked with T_KEY_SEED
178fn h_key_seed(d: &[u8]) -> DigestVal {
179    hash(&T_KEY_SEED, d)
180}
181/// Hash tweaked with T_VERIFY
182fn h_verify(d: &[u8]) -> DigestVal {
183    hash(&T_VERIFY, d)
184}
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.
192fn kdf_msgkdf(
193    xb: &curve25519::SharedSecret,
194    relay_public: &NtorV3PublicKey,
195    client_public: &curve25519::PublicKey,
196    verification: &[u8],
197) -> 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    let mut msg_kdf = DigestWriter(Shake256::default());
203    msg_kdf.write(&T_MSGKDF)?;
204    msg_kdf.write(xb)?;
205    msg_kdf.write(&relay_public.id)?;
206    msg_kdf.write(client_public)?;
207    msg_kdf.write(&relay_public.pk)?;
208    msg_kdf.write(PROTOID)?;
209    msg_kdf.write(&Encap(verification))?;
210    let mut r = msg_kdf.take().finalize_xof();
211    let mut enc_key = Zeroizing::new([0; ENC_KEY_LEN]);
212    let mut mac_key = Zeroizing::new([0; MAC_KEY_LEN]);
213
214    r.read(&mut enc_key[..]);
215    r.read(&mut mac_key[..]);
216    let mut mac = DigestWriter(Sha3_256::default());
217    {
218        mac.write(&T_MSGMAC)?;
219        mac.write(&Encap(&mac_key[..]))?;
220        mac.write(&relay_public.id)?;
221        mac.write(&relay_public.pk)?;
222        mac.write(client_public)?;
223    }
224
225    Ok((enc_key, mac))
226}
227
228/// Client side of the ntor v3 handshake.
229pub(crate) struct NtorV3Client;
230
231impl 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    fn client1<R: Rng + CryptoRng, M: Borrow<[CircRequestExt]>>(
244        rng: &mut R,
245        key: &NtorV3PublicKey,
246        extensions: &M,
247    ) -> Result<(Self::StateType, Vec<u8>)> {
248        let mut message = Vec::new();
249        CircRequestExt::write_many_onto(extensions.borrow(), &mut message)
250            .map_err(|e| Error::from_bytes_enc(e, "ntor3 handshake extensions"))?;
251        Ok(
252            client_handshake_ntor_v3(rng, key, &message, NTOR3_CIRC_VERIFICATION)
253                .map_err(into_internal!("Can't encode ntor3 client handshake."))?,
254        )
255    }
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    fn client2<T: AsRef<[u8]>>(
262        state: Self::StateType,
263        msg: T,
264    ) -> Result<(Vec<CircResponseExt>, Self::KeyGen)> {
265        let (message, xofreader) =
266            client_handshake_ntor_v3_part2(&state, msg.as_ref(), NTOR3_CIRC_VERIFICATION)?;
267        let extensions = CircResponseExt::decode(&message).map_err(|err| Error::CellDecodeErr {
268            object: "ntor v3 extensions",
269            err,
270        })?;
271        let keygen = NtorV3KeyGenerator { reader: xofreader };
272
273        Ok((extensions, keygen))
274    }
275}
276
277/// Server side of the ntor v3 handshake.
278pub(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
284impl<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    fn server<R: Rng + CryptoRng, REPLY: super::AuxDataReply<Self>, T: AsRef<[u8]>>(
291        rng: &mut R,
292        reply_fn: &mut REPLY,
293        keys: &[Self::KeyType],
294        msg: T,
295    ) -> RelayHandshakeResult<(Self::KeyGen, Vec<u8>)> {
296        let mut bytes_reply_fn = |bytes: &[u8]| -> Option<Vec<u8>> {
297            let client_exts = CircRequestExt::decode(bytes).ok()?;
298            let reply_exts = reply_fn.reply(&client_exts)?;
299            let mut out = vec![];
300            CircResponseExt::write_many_onto(&reply_exts, &mut out).ok()?;
301            Some(out)
302        };
303
304        let (res, reader) = server_handshake_ntor_v3(
305            rng,
306            &mut bytes_reply_fn,
307            msg.as_ref(),
308            keys,
309            NTOR3_CIRC_VERIFICATION,
310        )?;
311        Ok((NtorV3KeyGenerator { reader }, res))
312    }
313}
314
315/// An object holding the keys necessary for a server-side ntor v3 handshake.
316pub(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    fn matches(&self, id: Ed25519Identity, pk: curve25519::PublicKey) -> Choice {
332        let pk_self = NtorV3PublicKey {
333            id: *self.ident(),
334            pk: *self.public_key(),
335        };
336        let pk_other = NtorV3PublicKey { id, pk };
337        pk_self.ct_eq(&pk_other)
338    }
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)]
346pub(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
353impl ConstantTimeEq for NtorV3PublicKey {
354    fn ct_eq(&self, other: &Self) -> Choice {
355        // TODO: use similar pattern in ntor_v1!
356        self.id.as_bytes().ct_eq(other.id.as_bytes())
357            & self.pk.as_bytes().ct_eq(other.pk.as_bytes())
358    }
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.
365pub(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.
380pub(crate) struct NtorV3KeyGenerator {
381    /// The underlying `digest::XofReader`.
382    reader: NtorV3XofReader,
383}
384
385impl KeyGenerator for NtorV3KeyGenerator {
386    fn expand(mut self, keylen: usize) -> Result<SecretBuf> {
387        use digest::XofReader;
388        let mut ret: SecretBuf = vec![0; keylen].into();
389        self.reader.read(ret.as_mut());
390        Ok(ret)
391    }
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.
399fn client_handshake_ntor_v3<R: Rng + CryptoRng>(
400    rng: &mut R,
401    relay_public: &NtorV3PublicKey,
402    client_msg: &[u8],
403    verification: &[u8],
404) -> EncodeResult<(NtorV3HandshakeState, Vec<u8>)> {
405    let my_sk = curve25519::StaticSecret::random_from_rng(rng);
406    client_handshake_ntor_v3_no_keygen(relay_public, client_msg, verification, my_sk)
407}
408
409/// As `client_handshake_ntor_v3`, but don't generate an ephemeral DH
410/// key: instead take that key an arguments `my_sk`.
411fn client_handshake_ntor_v3_no_keygen(
412    relay_public: &NtorV3PublicKey,
413    client_msg: &[u8],
414    verification: &[u8],
415    my_sk: curve25519::StaticSecret,
416) -> EncodeResult<(NtorV3HandshakeState, Vec<u8>)> {
417    let my_public = curve25519::PublicKey::from(&my_sk);
418    let bx = my_sk.diffie_hellman(&relay_public.pk);
419
420    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    let encrypted_msg = encrypt(&enc_key, client_msg);
425    let msg_mac: DigestVal = {
426        use digest::Digest;
427        mac.write(&encrypted_msg)?;
428        mac.take().finalize().into()
429    };
430
431    let mut message = Vec::new();
432    message.write(&relay_public.id)?;
433    message.write(&relay_public.pk)?;
434    message.write(&my_public)?;
435    message.write(&encrypted_msg)?;
436    message.write(&msg_mac)?;
437
438    let state = NtorV3HandshakeState {
439        relay_public: relay_public.clone(),
440        my_sk,
441        my_public,
442        shared_secret: bx,
443        msg_mac,
444    };
445
446    Ok((state, message))
447}
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.
453pub(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
461impl<F> MsgReply for F
462where
463    F: FnMut(&[u8]) -> Option<Vec<u8>>,
464{
465    fn reply(&mut self, msg: &[u8]) -> Option<Vec<u8>> {
466        self(msg)
467    }
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.
480fn server_handshake_ntor_v3<RNG: CryptoRng + Rng, REPLY: MsgReply, K: NtorV3ServerKeys>(
481    rng: &mut RNG,
482    reply_fn: &mut REPLY,
483    message: &[u8],
484    keys: &[K],
485    verification: &[u8],
486) -> RelayHandshakeResult<(Vec<u8>, NtorV3XofReader)> {
487    let secret_key_y = curve25519::StaticSecret::random_from_rng(rng);
488    server_handshake_ntor_v3_no_keygen(reply_fn, &secret_key_y, message, keys, verification)
489}
490
491/// As `server_handshake_ntor_v3`, but take a secret key instead of an RNG.
492fn server_handshake_ntor_v3_no_keygen<REPLY: MsgReply, K: NtorV3ServerKeys>(
493    reply_fn: &mut REPLY,
494    secret_key_y: &curve25519::StaticSecret,
495    message: &[u8],
496    keys: &[K],
497    verification: &[u8],
498) -> RelayHandshakeResult<(Vec<u8>, NtorV3XofReader)> {
499    // Decode the message.
500    let mut r = Reader::from_slice(message);
501    let id: Ed25519Identity = r.extract()?;
502    let requested_pk: curve25519::PublicKey = r.extract()?;
503    let client_pk: curve25519::PublicKey = r.extract()?;
504    let client_msg = r.take_all_but(MAC_LEN)?;
505    let msg_mac: MacVal = r.extract()?;
506    r.should_be_exhausted()?;
507
508    // See if we recognize the provided (id,requested_pk) pair.
509    let keypair = ct_lookup(keys, |key| key.matches(id, requested_pk));
510    let keypair = match keypair {
511        Some(k) => k,
512        None => return Err(RelayHandshakeError::MissingKey),
513    };
514
515    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    let relay_pk = NtorV3PublicKey {
518        id: *keypair.ident(),
519        pk: *keypair.public_key(),
520    };
521    let (enc_key, mut mac) = kdf_msgkdf(&xb, &relay_pk, &client_pk, verification)
522        .map_err(into_internal!("Can't apply ntor3 kdf."))?;
523    // Verify the message we received.
524    let computed_mac: DigestVal = {
525        use digest::Digest;
526        mac.write(client_msg)
527            .map_err(into_internal!("Can't compute MAC input."))?;
528        mac.take().finalize().into()
529    };
530    let y_pk: curve25519::PublicKey = (secret_key_y).into();
531    let xy = secret_key_y.diffie_hellman(&client_pk);
532
533    let mut okay = computed_mac.ct_eq(&msg_mac)
534        & ct::bool_to_choice(xy.was_contributory())
535        & ct::bool_to_choice(xb.was_contributory());
536
537    let plaintext_msg = decrypt(&enc_key, client_msg);
538
539    // Handle the message and decide how to reply.
540    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    okay &= ct::bool_to_choice(reply.is_some());
546    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    let secret_input = {
552        let mut si = SecretBuf::new();
553        si.write(&xy)
554            .and_then(|_| si.write(&xb))
555            .and_then(|_| si.write(keypair.ident()))
556            .and_then(|_| si.write(keypair.public_key()))
557            .and_then(|_| si.write(&client_pk))
558            .and_then(|_| si.write(&y_pk))
559            .and_then(|_| si.write(PROTOID))
560            .and_then(|_| si.write(&Encap(verification)))
561            .map_err(into_internal!("can't derive ntor3 secret_input"))?;
562        si
563    };
564    let ntor_key_seed = h_key_seed(&secret_input);
565    let verify = h_verify(&secret_input);
566
567    let (enc_key, keystream) = {
568        use digest::{ExtendableOutput, XofReader};
569        let mut xof = DigestWriter(Shake256::default());
570        xof.write(&T_FINAL)
571            .and_then(|_| xof.write(&ntor_key_seed))
572            .map_err(into_internal!("can't generate ntor3 xof."))?;
573        let mut r = xof.take().finalize_xof();
574        let mut enc_key = Zeroizing::new([0_u8; ENC_KEY_LEN]);
575        r.read(&mut enc_key[..]);
576        (enc_key, r)
577    };
578    let encrypted_reply = encrypt(&enc_key, &reply);
579    let auth: DigestVal = {
580        use digest::Digest;
581        let mut auth = DigestWriter(Sha3_256::default());
582        auth.write(&T_AUTH)
583            .and_then(|_| auth.write(&verify))
584            .and_then(|_| auth.write(keypair.ident()))
585            .and_then(|_| auth.write(keypair.public_key()))
586            .and_then(|_| auth.write(&y_pk))
587            .and_then(|_| auth.write(&client_pk))
588            .and_then(|_| auth.write(&msg_mac))
589            .and_then(|_| auth.write(&Encap(&encrypted_reply)))
590            .and_then(|_| auth.write(PROTOID))
591            .and_then(|_| auth.write(&b"Server"[..]))
592            .map_err(into_internal!("can't derive ntor3 authentication"))?;
593        auth.take().finalize().into()
594    };
595
596    let reply = {
597        let mut reply = Vec::new();
598        reply
599            .write(&y_pk)
600            .and_then(|_| reply.write(&auth))
601            .and_then(|_| reply.write(&encrypted_reply))
602            .map_err(into_internal!("can't encode ntor3 reply."))?;
603        reply
604    };
605
606    if okay.into() {
607        Ok((reply, NtorV3XofReader(keystream)))
608    } else {
609        Err(RelayHandshakeError::BadClientHandshake)
610    }
611}
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.
620fn client_handshake_ntor_v3_part2(
621    state: &NtorV3HandshakeState,
622    relay_handshake: &[u8],
623    verification: &[u8],
624) -> Result<(Vec<u8>, NtorV3XofReader)> {
625    let mut reader = Reader::from_slice(relay_handshake);
626    let y_pk: curve25519::PublicKey = reader
627        .extract()
628        .map_err(|e| Error::from_bytes_err(e, "v3 ntor handshake"))?;
629    let auth: DigestVal = reader
630        .extract()
631        .map_err(|e| Error::from_bytes_err(e, "v3 ntor handshake"))?;
632    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    let yx = state.my_sk.diffie_hellman(&y_pk);
637    let secret_input = {
638        let mut si = SecretBuf::new();
639        si.write(&yx)
640            .and_then(|_| si.write(&state.shared_secret))
641            .and_then(|_| si.write(&state.relay_public.id))
642            .and_then(|_| si.write(&state.relay_public.pk))
643            .and_then(|_| si.write(&state.my_public))
644            .and_then(|_| si.write(&y_pk))
645            .and_then(|_| si.write(PROTOID))
646            .and_then(|_| si.write(&Encap(verification)))
647            .map_err(into_internal!("error encoding ntor3 secret_input"))?;
648        si
649    };
650    let ntor_key_seed = h_key_seed(&secret_input);
651    let verify = h_verify(&secret_input);
652
653    let computed_auth: DigestVal = {
654        use digest::Digest;
655        let mut auth = DigestWriter(Sha3_256::default());
656        auth.write(&T_AUTH)
657            .and_then(|_| auth.write(&verify))
658            .and_then(|_| auth.write(&state.relay_public.id))
659            .and_then(|_| auth.write(&state.relay_public.pk))
660            .and_then(|_| auth.write(&y_pk))
661            .and_then(|_| auth.write(&state.my_public))
662            .and_then(|_| auth.write(&state.msg_mac))
663            .and_then(|_| auth.write(&Encap(encrypted_msg)))
664            .and_then(|_| auth.write(PROTOID))
665            .and_then(|_| auth.write(&b"Server"[..]))
666            .map_err(into_internal!("error encoding ntor3 authentication input"))?;
667        auth.take().finalize().into()
668    };
669
670    let okay = computed_auth.ct_eq(&auth)
671        & ct::bool_to_choice(yx.was_contributory())
672        & ct::bool_to_choice(state.shared_secret.was_contributory());
673
674    let (enc_key, keystream) = {
675        use digest::{ExtendableOutput, XofReader};
676        let mut xof = DigestWriter(Shake256::default());
677        xof.write(&T_FINAL)
678            .and_then(|_| xof.write(&ntor_key_seed))
679            .map_err(into_internal!("error encoding ntor3 xof input"))?;
680        let mut r = xof.take().finalize_xof();
681        let mut enc_key = Zeroizing::new([0_u8; ENC_KEY_LEN]);
682        r.read(&mut enc_key[..]);
683        (enc_key, r)
684    };
685    let server_reply = decrypt(&enc_key, encrypted_msg);
686
687    if okay.into() {
688        Ok((server_reply, NtorV3XofReader(keystream)))
689    } else {
690        Err(Error::BadCircHandshakeAuth)
691    }
692}
693
694#[cfg(test)]
695#[allow(non_snake_case)] // to enable variable names matching the spec.
696#[allow(clippy::many_single_char_names)] // ibid
697pub(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}