1
//! Handler for CREATE* cells.
2

            
3
use crate::FlowCtrlParameters;
4
use crate::ccparams::{
5
    AlgorithmDiscriminants, CongestionWindowParams, FixedWindowParams, RoundTripEstimatorParams,
6
    VegasParams,
7
};
8
use crate::channel::Channel;
9
use crate::circuit::celltypes::{CreateRequest, CreateResponse};
10
use crate::circuit::circhop::{HandshakeParamsError, HopSettings};
11
use crate::circuit::metrics::CircuitMetrics;
12
use crate::circuit::{
13
    CircuitRxSender, HandshakeSubprotocols, InvalidHandshakeSubprotocolError, UniqId,
14
};
15
use crate::client::circuit::padding::PaddingController;
16
use crate::crypto::binding::CircuitBinding;
17
use crate::crypto::cell::CryptInit as _;
18
use crate::crypto::cell::{
19
    CgoRelayCrypto, InboundRelayLayer, OutboundRelayLayer, RelayLayer, Tor1RelayCrypto,
20
};
21
use crate::crypto::handshake::RelayHandshakeError;
22
use crate::crypto::handshake::ServerHandshake as _;
23
use crate::crypto::handshake::fast::CreateFastServer;
24
use crate::crypto::handshake::ntor::{NtorServer, NtorServerKeys};
25
use crate::crypto::handshake::ntor_v3::{NtorV3Server, NtorV3ServerKeys};
26
use crate::memquota::SpecificAccount as _;
27
use crate::memquota::{ChannelAccount, CircuitAccount};
28
use crate::relay::channel_provider::ChannelProvider;
29
use crate::relay::reactor::Reactor;
30
use crate::relay::{IncomingStreamRequestFilter, RelayCirc};
31
use crate::stream::IncomingStream;
32
use futures::channel::mpsc;
33
use futures::{SinkExt, Stream};
34
use smallvec::SmallVec;
35
use std::sync::{Arc, RwLock, Weak};
36
use tor_cell::chancell::ChanMsg as _;
37
use tor_cell::chancell::CircId;
38
use tor_cell::chancell::msg::{
39
    CreateFast, Created2, CreatedFast, Destroy, DestroyReason, HandshakeType,
40
};
41
use tor_cell::relaycell::RelayCmd;
42
use tor_cell::relaycell::extend::{
43
    CcRequest, CcResponse, CircRequestExt, CircResponseExt, SubprotocolRequest,
44
};
45
use tor_error::{ErrorKind, HasKind, debug_report, internal, into_internal, warn_report};
46
use tor_linkspec::OwnedChanTarget;
47
use tor_llcrypto::pk::curve25519;
48
use tor_llcrypto::pk::ed25519::Ed25519Identity;
49
use tor_llcrypto::pk::rsa::RsaIdentity;
50
use tor_memquota::mq_queue::ChannelSpec as _;
51
use tor_memquota::mq_queue::MpscSpec;
52
use tor_relay_crypto::pk::{RelayNtorKeypair, RelayNtorKeys};
53
use tor_rtcompat::SpawnExt as _;
54
use tor_rtcompat::{DynTimeProvider, Runtime};
55
use tracing::{debug, trace};
56

            
57
/// Everything needed to handle CREATE* messages on channels.
58
#[derive(derive_more::Debug)]
59
pub struct CreateRequestHandler {
60
    /// Something that can launch channels. Typically the `ChanMgr`.
61
    chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
62
    /// Circuit-related network parameters.
63
    circ_net_params: RwLock<CircNetParameters>,
64
    /// The circuit extension keys.
65
    #[debug(skip)]
66
    ntor_keys: RwLock<RelayNtorKeys>,
67
    /// An [`IncomingStreamRequestFilter`] factory for checking whether the user wants
68
    /// this request, or wants to reject it immediately.
69
    ///
70
    /// Used for obtaining a current [`IncomingStreamRequestFilter`]
71
    /// for building a circuit reactor.
72
    //
73
    // TODO(relay): it's likely this will end up changing quite a bit once we start
74
    // figuring out exactly how the config/reconfigure() logic and IncomingStreamRequestFilter
75
    // should function for relays.
76
    #[debug(skip)]
77
    incoming_filter_factory: Box<dyn IncomingStreamRequestFilterFactory + Send + Sync>,
78
    /// The allowed incoming stream commands.
79
    ///
80
    /// Used for rejecting BEGIN and RESOLVE if we are not configured to be an exit.
81
    ///
82
    // TODO(relay): we might use this for rejecting BEGIN_DIR too,
83
    // if we decide to allow relays to opt out of being dir mirrors.
84
    // See https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4107/diffs#note_3426447
85
    allowed_stream_cmds: SmallVec<[RelayCmd; 3]>,
86
    /// A sender for the [`Stream`]s of `IncomingStream` of all circuits.
87
    ///
88
    /// The receiver will receive one [`Stream`] (of tor streams) per circuit.
89
    ///
90
    /// This being a bounded MPSC might seem a bit risky, because in theory,
91
    /// if the receiver is not reading fast enough, sending will block.
92
    /// In practice, however, it should never block (or buffer very much at all,
93
    /// for that matter), because the user (arti-relay) is expected to read from
94
    /// this in a tight loop, and spawn a task for handling each [`Stream`].
95
    ///
96
    /// Note: because this MPSC is not associated with any particular circuit or channel,
97
    /// it does not participate in the memquota system (see [crate::memquota]).
98
    #[debug(skip)]
99
    circuit_stream_tx: mpsc::Sender<<CircuitIncomingStreamReceiver as Stream>::Item>,
100
    /// The circuit metrics. It is shared with every circuit reactor.
101
    #[debug(skip)]
102
    metrics: Arc<CircuitMetrics>,
103
}
104

            
105
// We make the CREATE-handling methods of `CreateRequestHandler` async
106
// since we expect that in the future we may want to offload the crypto to a worker thread.
107
#[expect(clippy::unused_async)]
108
impl CreateRequestHandler {
109
    /// Build a new [`CreateRequestHandler`], and a [`CircuitIncomingStreamReceiver`]
110
    /// for receiving new streams that are opened on any incoming circuits.
111
43
    pub fn new(
112
43
        chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
113
43
        circ_net_params: CircNetParameters,
114
43
        ntor_keys: RelayNtorKeys,
115
43
        incoming_filter_factory: Box<dyn IncomingStreamRequestFilterFactory + Send + Sync>,
116
43
        allowed_stream_cmds: &[RelayCmd],
117
43
    ) -> (Self, CircuitIncomingStreamReceiver) {
118
        // TODO(relay-tuning): this MPSC can be a bottleneck,
119
        // as all the channels on this relay will want to send one item on it
120
        // each time a new circuit is created.
121
        //
122
        // The value set here is a guesstimate.
123
        const CIRC_STREAM_BUF_SIZE: usize = 1024;
124

            
125
        // This is not associated with any particular circuit
126
        // (it is for *all* circuits), so it doesn't participate in memquota
127
        // (see circuit_stream_tx docs)
128
        #[allow(clippy::disallowed_methods)]
129
43
        let (stream_tx, stream_rx) = mpsc::channel(CIRC_STREAM_BUF_SIZE);
130

            
131
43
        let handler = Self {
132
43
            chan_provider,
133
43
            circ_net_params: RwLock::new(circ_net_params),
134
43
            ntor_keys: RwLock::new(ntor_keys),
135
43
            incoming_filter_factory,
136
43
            allowed_stream_cmds: allowed_stream_cmds.into(),
137
43
            circuit_stream_tx: stream_tx,
138
43
            metrics: Arc::new(CircuitMetrics::new()),
139
43
        };
140

            
141
43
        let circuit_stream_rx = CircuitIncomingStreamReceiver {
142
43
            circuit_stream_rx: stream_rx,
143
43
        };
144

            
145
43
        (handler, circuit_stream_rx)
146
43
    }
147

            
148
    /// Update the circuit parameters from a network consensus.
149
    pub fn update_params(&self, circ_net_params: CircNetParameters) {
150
        *self.circ_net_params.write().expect("rwlock poisoned") = circ_net_params;
151
    }
152

            
153
    /// Update the handler with a new set of circuit extension keys.
154
    ///
155
    /// This is called periodically by the relay key rotation task.
156
    pub fn update_ntor_keys(&self, ntor_keys: RelayNtorKeys) {
157
        *self.ntor_keys.write().expect("rwlock poisoned") = ntor_keys;
158
    }
159

            
160
    /// Handle a CREATE* cell.
161
    ///
162
    /// This intentionally does not return a [`crate::Error`] so that we don't accidentally shut
163
    /// down the channel reactor when we really should be returning a DESTROY. Shutting down a
164
    /// channel may cause us to leak information about paths of circuits travelling through this
165
    /// relay. This is especially important here since we're handling data that is controllable from
166
    /// the other end of the circuit.
167
    #[allow(clippy::too_many_arguments)]
168
15
    pub(crate) async fn handle_create<R: Runtime>(
169
15
        &self,
170
15
        runtime: &R,
171
15
        channel: &Arc<Channel>,
172
15
        our_ed25519_id: &Ed25519Identity,
173
15
        our_rsa_id: &RsaIdentity,
174
15
        circ_id: CircId,
175
15
        msg: &CreateRequest,
176
15
        memquota: &ChannelAccount,
177
15
        circ_unique_id: UniqId,
178
15
    ) -> Result<(CreateResponse, RelayCircComponents), Destroy> {
179
15
        debug!(
180
            circ_uniq_id = %circ_unique_id,
181
            cmd = %msg.cmd(),
182
            "Handling circuit create request"
183
        );
184

            
185
15
        let result = self
186
15
            .handle_create_inner(
187
15
                runtime,
188
15
                channel,
189
15
                our_ed25519_id,
190
15
                our_rsa_id,
191
15
                circ_id,
192
15
                msg,
193
15
                memquota,
194
15
                circ_unique_id,
195
15
            )
196
15
            .await;
197

            
198
15
        match result {
199
8
            Ok(x) => Ok(x),
200
            Err(e) => {
201
                // TODO(relay): The log messages throughout could be very noisy, so should have rate limiting.
202
7
                let cmd = msg.cmd();
203
7
                debug_report!(&e, %cmd, "Failed to handle circuit create request");
204

            
205
                // `tor-spec/tearing-down-circuits.md`:
206
                //
207
                // > Implementations SHOULD always use the NONE reason to avoid side channels: [...]
208
7
                Err(Destroy::new(DestroyReason::NONE))
209
            }
210
        }
211
15
    }
212

            
213
    /// See [`Self::handle_create`].
214
    #[allow(clippy::too_many_arguments)]
215
15
    async fn handle_create_inner<R: Runtime>(
216
15
        &self,
217
15
        runtime: &R,
218
15
        channel: &Arc<Channel>,
219
15
        our_ed25519_id: &Ed25519Identity,
220
15
        our_rsa_id: &RsaIdentity,
221
15
        circ_id: CircId,
222
15
        msg: &CreateRequest,
223
15
        memquota: &ChannelAccount,
224
15
        circ_unique_id: UniqId,
225
15
    ) -> Result<(CreateResponse, RelayCircComponents), HandleCreateError> {
226
        // Perform the handshake crypto and build the response.
227
15
        let handshake_components = match msg {
228
2
            CreateRequest::CreateFast(msg) => self.handle_create_fast(msg).await?,
229
13
            CreateRequest::Create2(msg) => match msg.handshake_type() {
230
                HandshakeType::NTOR_V3 => {
231
6
                    self.handle_create2_ntorv3(msg.body(), our_ed25519_id)
232
6
                        .await?
233
                }
234
5
                HandshakeType::NTOR => self.handle_create2_ntor(msg.body(), our_rsa_id).await?,
235
                x @ HandshakeType::TAP | x => {
236
2
                    return Err(HandleCreateError::Create2HandshakeType(x));
237
                }
238
            },
239
        };
240

            
241
8
        let memquota = CircuitAccount::new(memquota)?;
242

            
243
        // We use a large mpsc queue here since a circuit should never block the channel,
244
        // and we hope that memquota will help us if an attacker intentionally fills this buffer.
245
        // We use `10_000_000` since `usize::MAX` causes `futures::channel::mpsc` to panic.
246
        // TODO(relay): We should switch to an unbounded queue, but the circuit reactor is expecting
247
        // a bounded queue.
248
8
        let time_provider = DynTimeProvider::new(runtime.clone());
249
8
        let account = memquota.as_raw_account();
250
        let (sender, receiver) =
251
8
            MpscSpec::new(10_000_000).new_mq(time_provider.clone(), account)?;
252
8
        let (sender, receiver) = crate::circuit::circ_sender::channel(sender, receiver);
253

            
254
        // TODO(relay): Do we really want a client padding machine here?
255
        let (padding_ctrl, padding_stream) =
256
8
            crate::client::circuit::padding::new_padding(DynTimeProvider::new(runtime.clone()));
257

            
258
        // Upgrade the channel provider, which in practice is the `ChanMgr` so this should not fail.
259
8
        let Some(chan_provider) = self.chan_provider.upgrade() else {
260
            return Err(internal!("Unable to upgrade weak `ChannelProvider`").into());
261
        };
262

            
263
        // Create an IncomingStreamRequestFilter for this circuit.
264
        // This will get applied to every stream request (BEGIN, BEGIN_DIR, RESOLVE)
265
        // arriving on the circuit.
266
        //
267
        // Note: once built, a circuit reactor's IncomingStreamRequestFilter cannot be changed
268
        // (it's fixed for the entire duration of the circuit).
269
8
        let incoming_filter = self.incoming_filter_factory.current_filter();
270

            
271
        // Build the relay circuit reactor.
272
8
        let (reactor, circ, incoming_streams) = Reactor::new(
273
8
            runtime.clone(),
274
8
            channel,
275
8
            circ_id,
276
8
            circ_unique_id,
277
8
            receiver,
278
8
            handshake_components.crypto_in,
279
8
            handshake_components.crypto_out,
280
8
            &handshake_components.hop_settings,
281
8
            chan_provider,
282
8
            padding_ctrl.clone(),
283
8
            padding_stream,
284
8
            incoming_filter,
285
8
            &self.allowed_stream_cmds,
286
8
            &memquota,
287
8
            Arc::clone(&self.metrics),
288
8
        )
289
8
        .map_err(into_internal!("Failed to start circuit reactor"))?;
290

            
291
8
        let mut circuit_stream_tx = self.circuit_stream_tx.clone();
292
        // Start the reactor in a task.
293
8
        let () = runtime.spawn(async move {
294
8
            if let Err(e) = circuit_stream_tx
295
8
                .send((circ_unique_id, Box::new(incoming_streams)))
296
8
                .await
297
            {
298
                warn_report!(e, "IncomingStream handler disappeared?!");
299
                // If we get here, it means the relay stream handler task has gone away,
300
                // so there won't be anything handling the incoming streams.
301
                //
302
                // The reactor is dropped, making the RelayCirc returned below
303
                // in the RelayCircComponents unusable
304
                // (RelayCirc::is_closing() will return `true`).
305
                drop(reactor);
306
            } else {
307
                // Only spawn the circuit reactor if the incoming stream handler was
308
                // able to receive our message
309
8
                match reactor.run().await {
310
3
                    Ok(()) => {}
311
                    Err(e) => {
312
                        debug_report!(e, "Relay circuit reactor exited with an error");
313
                    }
314
                }
315
            }
316
3
        })?;
317

            
318
8
        Ok((
319
8
            handshake_components.response,
320
8
            RelayCircComponents {
321
8
                circ,
322
8
                sender,
323
8
                padding_ctrl,
324
8
            },
325
8
        ))
326
15
    }
327

            
328
    /// The handshake code for a CREATE_FAST request.
329
2
    async fn handle_create_fast(
330
2
        &self,
331
2
        msg: &CreateFast,
332
2
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
333
        // TODO(relay): We might want to offload this to a CPU worker in the future.
334
2
        let (keygen, handshake_msg) = CreateFastServer::server(
335
2
            &mut rand::rng(),
336
            // The CREATE_FAST handshake doesn't accept or return extensions,
337
            // so this `AuxDataReply` is a no-op.
338
2
            &mut |_: &()| Some(()),
339
            // The CREATE_FAST handshake doesn't use any keys.
340
2
            &[],
341
2
            msg.handshake(),
342
        )?;
343

            
344
2
        let circ_net_params = self
345
2
            .circ_net_params
346
2
            .read()
347
2
            .expect("rwlock poisoned")
348
2
            .clone();
349

            
350
        // No subprotocols are requested during a CREATE_FAST handshake.
351
2
        let subprotos = HandshakeSubprotocols::default();
352

            
353
2
        let hop_settings = HopSettings::from_handshake_params(
354
2
            circ_net_params,
355
2
            // CREATE_FAST always uses fixed-window flow control.
356
2
            AlgorithmDiscriminants::FixedWindow,
357
2
            subprotos,
358
2
        )?;
359

            
360
2
        let crypt = Tor1RelayCrypto::construct(keygen)
361
2
            .map_err(into_internal!("Circuit crypt state construction failed"))?;
362

            
363
2
        let (crypto_out, crypto_in, _binding) = split_relay_layer(crypt);
364

            
365
2
        let response = CreatedFast::new(handshake_msg);
366
2
        let response = CreateResponse::CreatedFast(response);
367

            
368
2
        trace!("Completed CREATE_FAST handshake");
369

            
370
2
        Ok(CompletedHandshakeComponents {
371
2
            response,
372
2
            hop_settings,
373
2
            crypto_out,
374
2
            crypto_in,
375
2
        })
376
2
    }
377

            
378
    /// The handshake code for a CREATE2 ntor (non-v3) request.
379
5
    async fn handle_create2_ntor(
380
5
        &self,
381
5
        msg_body: &[u8],
382
5
        our_rsa_id: &RsaIdentity,
383
5
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
384
5
        let ntor_keys = self.with_ntor_keys(|k| NtorSecretKey::new(our_rsa_id, Arc::clone(k)));
385

            
386
        // TODO(relay): We might want to offload this to a CPU worker in the future.
387
5
        let (keygen, handshake_msg) = NtorServer::server(
388
5
            &mut rand::rng(),
389
            // The ntor (non-v3) handshake doesn't accept or return extensions,
390
            // so this `AuxDataReply` is a no-op.
391
5
            &mut |_: &()| Some(()),
392
5
            ntor_keys.as_ref(),
393
5
            msg_body,
394
2
        )?;
395

            
396
3
        let circ_net_params = self
397
3
            .circ_net_params
398
3
            .read()
399
3
            .expect("rwlock poisoned")
400
3
            .clone();
401

            
402
        // No subprotocols are requested during an ntor (non-v3) handshake.
403
3
        let subprotos = HandshakeSubprotocols::default();
404

            
405
3
        let hop_settings = HopSettings::from_handshake_params(
406
3
            circ_net_params,
407
3
            // CREATE2 with ntor (non-v3) always uses fixed-window flow control.
408
3
            AlgorithmDiscriminants::FixedWindow,
409
3
            subprotos,
410
3
        )?;
411

            
412
3
        let crypt = Tor1RelayCrypto::construct(keygen)
413
3
            .map_err(into_internal!("Circuit crypt state construction failed"))?;
414

            
415
3
        let (crypto_out, crypto_in, _binding) = split_relay_layer(crypt);
416

            
417
3
        let response = Created2::new(handshake_msg);
418
3
        let response = CreateResponse::Created2(response);
419

            
420
3
        trace!("Completed ntor handshake");
421

            
422
3
        Ok(CompletedHandshakeComponents {
423
3
            response,
424
3
            hop_settings,
425
3
            crypto_out,
426
3
            crypto_in,
427
3
        })
428
5
    }
429

            
430
    /// The handshake code for a CREATE2 ntor-v3 request.
431
6
    async fn handle_create2_ntorv3(
432
6
        &self,
433
6
        msg_body: &[u8],
434
6
        our_ed25519_id: &Ed25519Identity,
435
6
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
436
        let ntor_keys =
437
6
            self.with_ntor_keys(|k| NtorV3SecretKey::new(our_ed25519_id, Arc::clone(k)));
438

            
439
6
        let circ_net_params = self
440
6
            .circ_net_params
441
6
            .read()
442
6
            .expect("rwlock poisoned")
443
6
            .clone();
444

            
445
        // These extensions can be negotiated during the handshake.
446
6
        let mut cc_algorithm = AlgorithmDiscriminants::FixedWindow;
447

            
448
        // These subprotocols were requested during the handshake.
449
        // They are not validated.
450
6
        let mut subprotos = SubprotocolRequest::default();
451

            
452
        // Helper which processes extension requests and returns any responses.
453
        // Returns `None` if the handshake should fail.
454
3
        let mut ext_reply_fn = |client_exts: &[CircRequestExt]| {
455
3
            let mut response_exts = Vec::new();
456

            
457
            // https://spec.torproject.org/tor-spec/create-created-cells.html#additional-data
458
            //
459
            // > Unless otherwise specified in the documentation for an extension type:
460
            // > - [...]
461
            // > - Parties MUST ignore any occurrence of an extension with a given type after the first such occurrence.
462
            //
463
            // TODO: Is there something nicer that we can do here?
464
            // We could use accessors like `ExtList::get_cc_request()`
465
            // which iterate over the extension list for each extension,
466
            // but using an enum match like we do below is kind of nice.
467
3
            let mut handled_cc_request = false;
468
3
            let mut handled_subproto_request = false;
469

            
470
3
            for ext in client_exts {
471
                match ext {
472
                    CircRequestExt::CcRequest(CcRequest { .. }) => {
473
                        if handled_cc_request {
474
                            continue;
475
                        }
476
                        handled_cc_request = true;
477

            
478
                        cc_algorithm = AlgorithmDiscriminants::Vegas;
479

            
480
                        let sendme_inc: u8 = circ_net_params.cc.cwnd.sendme_inc();
481
                        let response = CcResponse::new(sendme_inc);
482
                        response_exts.push(CircResponseExt::CcResponse(response));
483
                    }
484
                    // The given `SubprotocolRequest` stores a list of `NumberedSubver`,
485
                    // but a circuit extension request is limited to 255 bytes (127 subprotocols).
486
                    // So while a malicious client could send us a lot of invalid subprotocols,
487
                    // this limit prevents this list from being excessively large.
488
                    CircRequestExt::SubprotocolRequest(subproto_request) => {
489
                        if handled_subproto_request {
490
                            continue;
491
                        }
492
                        handled_subproto_request = true;
493

            
494
                        // We don't check the requested subprotocols here.
495
                        subprotos = subproto_request.clone();
496
                    }
497
                    CircRequestExt::Unrecognized(ext) => {
498
                        // https://spec.torproject.org/tor-spec/create-created-cells.html#additional-data
499
                        //
500
                        // > Parties MUST ignore extensions with `EXT_FIELD_TYPE` bodies they do not recognize.
501
                        debug!(
502
                            ?ext,
503
                            "CREATE2 ntor-v3 handshake requested unrecognized extension",
504
                        );
505
                    }
506
                    ext => {
507
                        // https://spec.torproject.org/tor-spec/create-created-cells.html#additional-data
508
                        //
509
                        // > Parties MUST ignore extensions with `EXT_FIELD_TYPE` bodies they do not recognize.
510
                        //
511
                        // We recognize this but don't know what to do with it.
512
                        // We haven't implemented it, or it doesn't make sense
513
                        // (for example `CircRequestExt::ProofOfWork`).
514
                        // So we'll just behave as if we don't recognize it.
515
                        debug!(
516
                            ?ext,
517
                            "CREATE2 ntor-v3 handshake requested unsupported extension",
518
                        );
519
                    }
520
                }
521
            }
522

            
523
3
            Some(response_exts)
524
3
        };
525

            
526
        // TODO(relay): We might want to offload this to a CPU worker in the future.
527
6
        let (keygen, handshake_msg) = NtorV3Server::server(
528
6
            &mut rand::rng(),
529
6
            &mut ext_reply_fn,
530
6
            ntor_keys.as_ref(),
531
6
            msg_body,
532
6
        )?;
533

            
534
        // Ensure that the client did not request invalid/unsupported subprotocols.
535
3
        let subprotos = HandshakeSubprotocols::try_from_request(subprotos)?;
536

            
537
        let hop_settings =
538
3
            HopSettings::from_handshake_params(circ_net_params, cc_algorithm, subprotos)?;
539

            
540
3
        let (crypto_out, crypto_in, _binding) = if subprotos.relay_crypt_cgo {
541
            let crypt = CgoRelayCrypto::construct(keygen)
542
                .map_err(into_internal!("Circuit crypt state construction failed"))?;
543
            split_relay_layer(crypt)
544
        } else {
545
3
            let crypt = Tor1RelayCrypto::construct(keygen)
546
3
                .map_err(into_internal!("Circuit crypt state construction failed"))?;
547
3
            split_relay_layer(crypt)
548
        };
549

            
550
3
        let response = Created2::new(handshake_msg);
551
3
        let response = CreateResponse::Created2(response);
552

            
553
3
        trace!(?cc_algorithm, ?subprotos, "Completed ntor-v3 handshake");
554

            
555
3
        Ok(CompletedHandshakeComponents {
556
3
            response,
557
3
            hop_settings,
558
3
            crypto_out,
559
3
            crypto_in,
560
3
        })
561
6
    }
562

            
563
    /// Helper to get the ntor keypairs after some transformation `map`.
564
    ///
565
    /// The `map` transformation must be fast since it blocks a read lock.
566
    /// The returned keys are sorted with the most recent key first.
567
    ///
568
    /// It would be nice if this just returned an iterator,
569
    /// but the read lock prevents this.
570
11
    fn with_ntor_keys<T>(&self, map: impl FnMut(&Arc<RelayNtorKeypair>) -> T) -> impl AsRef<[T]> {
571
11
        let ntor_keys = self.ntor_keys.read().expect("rwlock poisoned");
572
11
        let ntor_keys = [Some(ntor_keys.latest()), ntor_keys.previous()];
573
11
        ntor_keys
574
11
            .into_iter()
575
11
            .flatten()
576
11
            .map(map)
577
11
            .collect::<SmallVec<[T; 2]>>()
578
11
    }
579
}
580

            
581
/// The server's RSA identity and ntor keypair.
582
#[derive(derive_more::Constructor)]
583
struct NtorSecretKey<'a> {
584
    /// The server's RSA identity.
585
    ident: &'a RsaIdentity,
586
    /// The server's ntor keypair.
587
    keys: Arc<RelayNtorKeypair>,
588
}
589

            
590
impl<'a> NtorServerKeys for NtorSecretKey<'a> {
591
8
    fn ident(&self) -> &RsaIdentity {
592
8
        self.ident
593
8
    }
594

            
595
8
    fn public_key(&self) -> &curve25519::PublicKey {
596
8
        self.keys.public_raw()
597
8
    }
598

            
599
3
    fn secret_key(&self) -> &curve25519::StaticSecret {
600
3
        self.keys.secret()
601
3
    }
602
}
603

            
604
/// The server's Ed25519 identity and ntor keypair.
605
#[derive(derive_more::Constructor)]
606
struct NtorV3SecretKey<'a> {
607
    /// The server's Ed25519 identity.
608
    ident: &'a Ed25519Identity,
609
    /// The server's ntor keypair.
610
    keys: Arc<RelayNtorKeypair>,
611
}
612

            
613
impl<'a> NtorV3ServerKeys for NtorV3SecretKey<'a> {
614
15
    fn ident(&self) -> &Ed25519Identity {
615
15
        self.ident
616
15
    }
617

            
618
15
    fn public_key(&self) -> &curve25519::PublicKey {
619
15
        self.keys.public_raw()
620
15
    }
621

            
622
3
    fn secret_key(&self) -> &curve25519::StaticSecret {
623
3
        self.keys.secret()
624
3
    }
625
}
626

            
627
/// A receiver of [`Stream`]s (one for each incoming circuit),
628
/// where each `Stream` produces [`IncomingStream`]s for that circuit.
629
///
630
// Note: in theory, it would be nice if we could get rid of this type altogether.
631
// In an ideal world, I would've instead
632
//
633
//   * added a `RelayCirc::take_incoming_streams()` method for obtaining
634
//     the futures::Stream of IncomingStream of that circuit
635
//   * made the CreateRequestHandler send each Arc<RelayCirc> over to arti-relay for handling
636
//   * made arti-relay obtain the futures::Stream<Item = IncomingStream> of each RelayCirc
637
//     by calling `RelayCirc::take_incoming_streams()`
638
//
639
// However, that would involve adding some locking/interior mutability within RelayCirc
640
// (which is always behind an Arc), or extending mq_queue::Receiver to be Clone,
641
// which would be tricky to pull off (see the comment on mq_queue::Receiver about this).
642
pub struct CircuitIncomingStreamReceiver {
643
    /// The receiver for the [`Stream`]s of `IncomingStream` of all circuits.
644
    ///
645
    /// Receives one [`Stream`] (of tor streams) per circuit and the circuit unique ID.
646
    /// Each of these will be handled in a new task.
647
    circuit_stream_rx: mpsc::Receiver<<Self as Stream>::Item>,
648
}
649

            
650
impl Stream for CircuitIncomingStreamReceiver {
651
    // TODO: it would be nice if we could return a type-erased Stream here
652
    // (impl Stream<...>), but impl Trait in associated types is unstable.
653
    // See rust issue #63063 <https://github.com/rust-lang/rust/issues/63063>
654
    type Item = (
655
        UniqId,
656
        Box<dyn Stream<Item = IncomingStream> + Send + Sync + Unpin>,
657
    );
658

            
659
    fn poll_next(
660
        mut self: std::pin::Pin<&mut Self>,
661
        cx: &mut std::task::Context<'_>,
662
    ) -> std::task::Poll<Option<Self::Item>> {
663
        use futures::StreamExt as _;
664

            
665
        self.circuit_stream_rx.poll_next_unpin(cx)
666
    }
667
}
668

            
669
/// Helper function to split a `RelayLayer` into forward and backward type-erased trait objects.
670
8
fn split_relay_layer<F, B>(
671
8
    crypt: impl RelayLayer<F, B>,
672
8
) -> (
673
8
    Box<dyn OutboundRelayLayer + Send>,
674
8
    Box<dyn InboundRelayLayer + Send>,
675
8
    CircuitBinding,
676
8
)
677
8
where
678
8
    F: OutboundRelayLayer + Send + 'static,
679
8
    B: InboundRelayLayer + Send + 'static,
680
{
681
8
    let (crypto_out, crypto_in, binding) = crypt.split_relay_layer();
682
8
    let (crypto_out, crypto_in) = (Box::new(crypto_out), Box::new(crypto_in));
683

            
684
8
    (crypto_out, crypto_in, binding)
685
8
}
686

            
687
/// An error that occurred while handling a CREATE* request.
688
#[derive(Debug, thiserror::Error)]
689
enum HandleCreateError {
690
    /// Circuit relay handshake failed.
691
    #[error("Circuit relay handshake failed")]
692
    Handshake(#[from] RelayHandshakeError),
693
    /// Circuit relay handshake failed.
694
    #[error("Failed to process the circuit relay handshake parameters")]
695
    HandshakeParameters(#[from] HandshakeParamsError),
696
    /// Requested subprotocols which aren't supported.
697
    #[error("Client requested subprotocol(s) which aren't supported")]
698
    HandshakeSubprotocols(#[from] InvalidHandshakeSubprotocolError),
699
    /// The requested handshake type is unsupported.
700
    #[error("Unsupported handshake type {0}")]
701
    Create2HandshakeType(HandshakeType),
702
    /// A memquota error.
703
    #[error("Memquota error")]
704
    Memquota(#[from] tor_memquota::Error),
705
    /// Error when spawning a task.
706
    #[error("Runtime task spawn error")]
707
    Spawn(#[from] futures::task::SpawnError),
708
    /// An internal error.
709
    ///
710
    /// Note that other variants (such as `Handshake` containing a [`RelayHandshakeError`])
711
    /// may themselves contain internal errors.
712
    #[error("Internal error")]
713
    Internal(#[from] tor_error::Bug),
714
}
715

            
716
impl HasKind for HandleCreateError {
717
7
    fn kind(&self) -> ErrorKind {
718
7
        match self {
719
5
            Self::Handshake(e) => e.kind(),
720
            Self::HandshakeParameters(e) => e.kind(),
721
            Self::HandshakeSubprotocols(e) => e.kind(),
722
2
            Self::Create2HandshakeType(_) => ErrorKind::NotImplemented,
723
            Self::Memquota(e) => e.kind(),
724
            Self::Spawn(e) => e.kind(),
725
            Self::Internal(_) => ErrorKind::Internal,
726
        }
727
7
    }
728
}
729

            
730
/// The components of a completed CREATE* handshake.
731
struct CompletedHandshakeComponents {
732
    /// The message to send in response.
733
    response: CreateResponse,
734
    /// The negotiated hop settings.
735
    hop_settings: HopSettings,
736
    /// Outbound onion crypto.
737
    crypto_out: Box<dyn OutboundRelayLayer + Send>,
738
    /// Inbound onion crypto.
739
    crypto_in: Box<dyn InboundRelayLayer + Send>,
740
}
741

            
742
/// A collection of objects built for a new relay circuit.
743
pub(crate) struct RelayCircComponents {
744
    /// The relay circuit handle.
745
    pub(crate) circ: Arc<RelayCirc>,
746
    /// Used to send data from the channel to the circuit reactor.
747
    pub(crate) sender: CircuitRxSender,
748
    /// The circuit's padding controller.
749
    pub(crate) padding_ctrl: PaddingController,
750
}
751

            
752
/// Congestion control network parameters.
753
#[derive(Debug, Clone)]
754
#[allow(clippy::exhaustive_structs)]
755
pub struct CongestionControlNetParams {
756
    /// Fixed-window algorithm parameters.
757
    pub fixed_window: FixedWindowParams,
758

            
759
    /// Vegas algorithm parameters for exit circuits.
760
    // NOTE: In this module we are handling CREATE* cells,
761
    // which only happens for non-hs circuits.
762
    // So we don't need to store the vegas hs parameters here.
763
    pub vegas_exit: VegasParams,
764

            
765
    /// Congestion window parameters.
766
    pub cwnd: CongestionWindowParams,
767

            
768
    /// RTT calculation parameters.
769
    pub rtt: RoundTripEstimatorParams,
770

            
771
    /// Flow control parameters to use for all streams on this circuit.
772
    pub flow_ctrl: FlowCtrlParameters,
773
}
774

            
775
impl CongestionControlNetParams {
776
    #[cfg(test)]
777
    // These have been copied from C-tor.
778
43
    pub(crate) fn defaults_for_tests() -> Self {
779
43
        Self {
780
43
            fixed_window: FixedWindowParams::defaults_for_tests(),
781
43
            vegas_exit: VegasParams::defaults_for_tests(),
782
43
            cwnd: CongestionWindowParams::defaults_for_tests(),
783
43
            rtt: RoundTripEstimatorParams::defaults_for_tests(),
784
43
            flow_ctrl: FlowCtrlParameters::defaults_for_tests(),
785
43
        }
786
43
    }
787
}
788

            
789
/// Network consensus parameters for handling incoming circuits.
790
///
791
/// Unlike `CircParameters`,
792
/// this is unopinionated and contains all relevant consensus parameters,
793
/// which is needed when handling an incoming CREATE* request where the
794
/// circuit origin chooses the type/settings
795
/// (for example congestion control type) of the circuit.
796
#[derive(Debug, Clone)]
797
#[allow(clippy::exhaustive_structs)]
798
pub struct CircNetParameters {
799
    /// Congestion control network parameters.
800
    pub cc: CongestionControlNetParams,
801
}
802

            
803
/// An [`IncomingStreamRequestFilter`] factory for building [`IncomingStreamRequestFilter`]s.
804
///
805
/// Each time a new circuit is opened, the [`CreateRequestHandler`] calls
806
/// [`IncomingStreamRequestFilterFactory::current_filter`] to build
807
/// an [`IncomingStreamRequestFilter`] for the circuit.
808
pub trait IncomingStreamRequestFilterFactory {
809
    /// Return the [`IncomingStreamRequestFilter`] to apply to the incoming stream requests
810
    /// arriving on a circuit.
811
    fn current_filter(&self) -> Box<dyn IncomingStreamRequestFilter>;
812
}
813

            
814
impl<F> IncomingStreamRequestFilterFactory for F
815
where
816
    F: Fn() -> Box<dyn IncomingStreamRequestFilter>,
817
{
818
8
    fn current_filter(&self) -> Box<dyn IncomingStreamRequestFilter> {
819
8
        (self)()
820
8
    }
821
}
822

            
823
#[cfg(test)]
824
mod test {
825
    // @@ begin test lint list maintained by maint/add_warning @@
826
    #![allow(clippy::bool_assert_comparison)]
827
    #![allow(clippy::clone_on_copy)]
828
    #![allow(clippy::dbg_macro)]
829
    #![allow(clippy::mixed_attributes_style)]
830
    #![allow(clippy::print_stderr)]
831
    #![allow(clippy::print_stdout)]
832
    #![allow(clippy::single_char_pattern)]
833
    #![allow(clippy::unwrap_used)]
834
    #![allow(clippy::unchecked_time_subtraction)]
835
    #![allow(clippy::useless_vec)]
836
    #![allow(clippy::needless_pass_by_value)]
837
    #![allow(clippy::string_slice)] // See arti#2571
838
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
839

            
840
    use tor_cell::chancell::msg::{AnyChanMsg, Create2, CreateFast, HandshakeType};
841
    use tor_cell::chancell::{AnyChanCell, ChanCmd, ChanMsg as _};
842
    use tor_rtcompat::test_with_one_runtime;
843

            
844
    use crate::channel::test_utils;
845
    use crate::circuit::CircParameters;
846

            
847
    /// Test the CREATE_FAST handshake.
848
    #[test]
849
    fn create_fast() {
850
        test_with_one_runtime!(|rt| async move {
851
            let mut conn_inspector = test_utils::ConnInspector::new();
852

            
853
            let (client_chan, relay_chan, _circuit_stream_rx, _target_builder) =
854
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
855

            
856
            let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
857

            
858
            let circ_params = CircParameters::default();
859

            
860
            let tunnel = pending_tunnel
861
                .create_firsthop_fast(circ_params)
862
                .await
863
                .unwrap();
864

            
865
            // Client sent a CREATE_FAST, relay responded with a CREATED_FAST.
866
            assert_eq!(
867
                conn_inspector.try_client_cell().unwrap().msg().cmd(),
868
                ChanCmd::CREATE_FAST,
869
            );
870
            assert_eq!(
871
                conn_inspector.try_relay_cell().unwrap().msg().cmd(),
872
                ChanCmd::CREATED_FAST,
873
            );
874

            
875
            drop(tunnel);
876

            
877
            assert_eq!(
878
                conn_inspector.client_cell().await.unwrap().msg().cmd(),
879
                ChanCmd::DESTROY,
880
            );
881

            
882
            // Wait for both channels to close (ignoring any channel errors).
883
            let wait_fut =
884
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
885
            drop((client_chan, relay_chan));
886
            let _ = wait_fut.await;
887

            
888
            // We don't expect any other messages to have been sent.
889
            assert!(conn_inspector.try_client_cell().is_none());
890
            assert!(conn_inspector.try_relay_cell().is_none());
891
        });
892
    }
893

            
894
    /// Test the CREATE_FAST handshake, but with a modified handshake payload.
895
    #[test]
896
    fn create_fast_fail() {
897
        test_with_one_runtime!(|rt| async move {
898
            let mut conn_inspector = test_utils::ConnInspector::new();
899

            
900
            // Rewrite any client-sent CREATE_FAST messages to cause the client to fail the
901
            // handshake when processing the CREATED_FAST.
902
            conn_inspector.set_client_cell_modifier(|cell: &mut AnyChanCell| {
903
                let circ_id = cell.circid();
904
                if let AnyChanMsg::CreateFast(msg) = cell.msg() {
905
                    let mut new_handshake = msg.handshake().to_vec();
906

            
907
                    // Flip all bits.
908
                    for byte in &mut new_handshake {
909
                        *byte = !*byte;
910
                    }
911

            
912
                    // Reassemble the CREATE_FAST cell with the incorrect handshake body.
913
                    let new_msg = CreateFast::new(new_handshake);
914
                    *cell = AnyChanCell::new(circ_id, AnyChanMsg::CreateFast(new_msg));
915
                }
916
            });
917

            
918
            let (client_chan, relay_chan, _circuit_stream_rx, _target_builder) =
919
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
920

            
921
            let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
922

            
923
            let circ_params = CircParameters::default();
924

            
925
            // I don't think it's possible to modify the CREATE_FAST cell to make the relay fail the
926
            // handshake (the CREATE_FAST payload consists of only random bytes),
927
            // so the relay will respond successfully with a CREATED_FAST.
928
            // But the client will fail since the CREATED_FAST will contain garbage bytes.
929

            
930
            // The relay successfully processed the handshake,
931
            // but the client fails to validate the handshake since the handshake data was modified.
932
            assert!(matches!(
933
                pending_tunnel.create_firsthop_fast(circ_params).await,
934
                Err(crate::Error::BadCircHandshakeAuth),
935
            ));
936

            
937
            // Client sent a CREATE_FAST, relay responded with a CREATED_FAST.
938
            assert_eq!(
939
                conn_inspector.try_client_cell().unwrap().msg().cmd(),
940
                ChanCmd::CREATE_FAST,
941
            );
942
            assert_eq!(
943
                conn_inspector.try_relay_cell().unwrap().msg().cmd(),
944
                ChanCmd::CREATED_FAST,
945
            );
946

            
947
            // Since the `create_firsthop_fast()` failed above,
948
            // the client should have sent a DESTROY.
949
            assert_eq!(
950
                conn_inspector.client_cell().await.unwrap().msg().cmd(),
951
                ChanCmd::DESTROY,
952
            );
953

            
954
            // Wait for both channels to close (ignoring any channel errors).
955
            let wait_fut =
956
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
957
            drop((client_chan, relay_chan));
958
            let _ = wait_fut.await;
959

            
960
            // We don't expect any other messages to have been sent.
961
            assert!(conn_inspector.try_client_cell().is_none());
962
            assert!(conn_inspector.try_relay_cell().is_none());
963
        });
964
    }
965

            
966
    /// Test the client with the "Relay=1" subprotocol (corresponds to the TAP handshake),
967
    /// which Arti doesn't support.
968
    #[test]
969
    fn tap() {
970
        test_with_one_runtime!(|rt| async move {
971
            let mut conn_inspector = test_utils::ConnInspector::new();
972

            
973
            let (client_chan, _relay_chan, _circuit_stream_rx, mut target_builder) =
974
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
975

            
976
            let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
977

            
978
            let circ_params = CircParameters::default();
979

            
980
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
981
            // 1 = RELAY_BASE
982
            let protocols = "Relay=1".parse().unwrap();
983
            let target = target_builder.protocols(protocols).build().unwrap();
984

            
985
            // TODO: This should fail since we don't support TAP handshakes.
986
            // But the channel will do an ntor handshake anyway even though it's not supported.
987
            // https://gitlab.torproject.org/tpo/core/arti/-/work_items/2489
988
            let _tunnel = pending_tunnel
989
                .create_firsthop(&target, circ_params)
990
                .await
991
                .unwrap();
992

            
993
            // TODO: As above, this is wrong.
994
            assert_eq!(
995
                conn_inspector.try_client_cell().unwrap().msg().cmd(),
996
                ChanCmd::CREATE2,
997
            );
998
            assert_eq!(
999
                conn_inspector.try_relay_cell().unwrap().msg().cmd(),
                ChanCmd::CREATED2,
            );
        });
    }
    /// Test the CREATE2 ntor handshake.
    #[test]
    fn ntor() {
        test_with_one_runtime!(|rt| async move {
            let mut conn_inspector = test_utils::ConnInspector::new();
            let (client_chan, relay_chan, _circuit_stream_rx, mut target_builder) =
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
            // 2 = RELAY_NTOR
            // 3 = RELAY_EXTEND_IPv6
            for relay_version in [2, 3] {
                let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
                let circ_params = CircParameters::default();
                let protocols = format!("Relay=2-{relay_version}").parse().unwrap();
                let target = target_builder.protocols(protocols).build().unwrap();
                let tunnel = pending_tunnel
                    .create_firsthop(&target, circ_params)
                    .await
                    .unwrap();
                let client_cell = conn_inspector.try_client_cell().unwrap().msg().clone();
                let relay_cell = conn_inspector.try_relay_cell().unwrap().msg().clone();
                // Client sent a CREATE2, relay responded with a CREATED2.
                assert_eq!(client_cell.cmd(), ChanCmd::CREATE2);
                assert_eq!(relay_cell.cmd(), ChanCmd::CREATED2);
                // Check that it was an ntor handshake.
                let AnyChanMsg::Create2(client_cell) = client_cell else {
                    unreachable!("CREATE2 checked above");
                };
                assert_eq!(client_cell.handshake_type(), HandshakeType::NTOR);
                drop(tunnel);
                assert_eq!(
                    conn_inspector.client_cell().await.unwrap().msg().cmd(),
                    ChanCmd::DESTROY,
                );
                // We don't expect any other messages to have been sent.
                assert!(conn_inspector.try_client_cell().is_none());
                assert!(conn_inspector.try_relay_cell().is_none());
            }
            // Wait for both channels to close (ignoring any channel errors).
            let wait_fut =
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
            drop((client_chan, relay_chan));
            let _ = wait_fut.await;
            // We don't expect any other messages to have been sent.
            assert!(conn_inspector.try_client_cell().is_none());
            assert!(conn_inspector.try_relay_cell().is_none());
        });
    }
    /// Test the CREATE2 ntor handshake, but with a modified handshake payload.
    #[test]
    fn ntor_fail() {
        test_with_one_runtime!(|rt| async move {
            let mut conn_inspector = test_utils::ConnInspector::new();
            // Rewrite any client-sent CREATE2 messages to cause the relay to fail the handshake.
            conn_inspector.set_client_cell_modifier(|cell: &mut AnyChanCell| {
                let circ_id = cell.circid();
                if let AnyChanMsg::Create2(msg) = cell.msg() {
                    let mut new_body = msg.body().to_vec();
                    // Flip some arbitrarily chosen byte.
                    new_body[10] = !new_body[10];
                    // Reassemble the CREATE2 cell with the incorrect handshake body.
                    let new_msg = Create2::new(msg.handshake_type(), new_body);
                    *cell = AnyChanCell::new(circ_id, AnyChanMsg::Create2(new_msg));
                }
            });
            let (client_chan, relay_chan, _circuit_stream_rx, mut target_builder) =
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
            // 2 = RELAY_NTOR
            // 3 = RELAY_EXTEND_IPv6
            for relay_version in [2, 3] {
                let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
                let circ_params = CircParameters::default();
                let protocols = format!("Relay=2-{relay_version}").parse().unwrap();
                let target = target_builder.protocols(protocols).build().unwrap();
                // The relay refuses the circuit handshake since the CREATED2 cell had some
                // intentional issue with the handshake body.
                assert!(matches!(
                    pending_tunnel.create_firsthop(&target, circ_params).await,
                    Err(crate::Error::CircRefused(_)),
                ));
                // Client sent a CREATE2, relay responded with a DESTROY.
                assert_eq!(
                    conn_inspector.try_client_cell().unwrap().msg().cmd(),
                    ChanCmd::CREATE2,
                );
                assert_eq!(
                    conn_inspector.try_relay_cell().unwrap().msg().cmd(),
                    ChanCmd::DESTROY,
                );
                // We don't expect any other messages to have been sent.
                assert!(conn_inspector.try_client_cell().is_none());
                assert!(conn_inspector.try_relay_cell().is_none());
            }
            // Wait for both channels to close (ignoring any channel errors).
            let wait_fut =
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
            drop((client_chan, relay_chan));
            let _ = wait_fut.await;
            // We don't expect any other messages to have been sent.
            assert!(conn_inspector.try_client_cell().is_none());
            assert!(conn_inspector.try_relay_cell().is_none());
        });
    }
    /// Test the CREATE2 ntor-v3 handshake.
    #[test]
    fn ntor_v3() {
        test_with_one_runtime!(|rt| async move {
            let mut conn_inspector = test_utils::ConnInspector::new();
            let (client_chan, relay_chan, _circuit_stream_rx, mut target_builder) =
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
            // 4 = RELAY_NTORV3
            // 5 = RELAY_NEGOTIATE_SUBPROTO
            // 6 = RELAY_CRYPT_CGO
            for relay_version in [4, 5, 6] {
                let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
                let circ_params = CircParameters::default();
                let protocols = format!("Relay=4-{relay_version}").parse().unwrap();
                let target = target_builder.protocols(protocols).build().unwrap();
                let tunnel = pending_tunnel
                    .create_firsthop(&target, circ_params)
                    .await
                    .unwrap();
                let client_cell = conn_inspector.try_client_cell().unwrap().msg().clone();
                let relay_cell = conn_inspector.try_relay_cell().unwrap().msg().clone();
                // Client sent a CREATE2, relay responded with a CREATED2.
                assert_eq!(client_cell.cmd(), ChanCmd::CREATE2);
                assert_eq!(relay_cell.cmd(), ChanCmd::CREATED2);
                // Check that it was an ntor-v3 handshake.
                let AnyChanMsg::Create2(client_cell) = client_cell else {
                    unreachable!("CREATE2 checked above");
                };
                assert_eq!(client_cell.handshake_type(), HandshakeType::NTOR_V3);
                // TODO: It would be nice if we had a way to check that CGO was in use when
                // `relay_version` is >=6, but I don't see a nice way to do that.
                drop(tunnel);
                assert_eq!(
                    conn_inspector.client_cell().await.unwrap().msg().cmd(),
                    ChanCmd::DESTROY,
                );
                // We don't expect any other messages to have been sent.
                assert!(conn_inspector.try_client_cell().is_none());
                assert!(conn_inspector.try_relay_cell().is_none());
            }
            // Wait for both channels to close (ignoring any channel errors).
            let wait_fut =
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
            drop((client_chan, relay_chan));
            let _ = wait_fut.await;
            // We don't expect any other messages to have been sent.
            assert!(conn_inspector.try_client_cell().is_none());
            assert!(conn_inspector.try_relay_cell().is_none());
        });
    }
    /// Test the CREATE2 ntor-v3 handshake, but with a modified handshake payload.
    #[test]
    fn ntor_v3_fail() {
        test_with_one_runtime!(|rt| async move {
            let mut conn_inspector = test_utils::ConnInspector::new();
            // Rewrite any client-sent CREATE2 messages to cause the relay to fail the handshake.
            conn_inspector.set_client_cell_modifier(|cell: &mut AnyChanCell| {
                let circ_id = cell.circid();
                if let AnyChanMsg::Create2(msg) = cell.msg() {
                    let mut new_body = msg.body().to_vec();
                    // Flip some arbitrarily chosen byte.
                    new_body[10] = !new_body[10];
                    // Reassemble the CREATE2 cell with the incorrect handshake body.
                    let new_msg = Create2::new(msg.handshake_type(), new_body);
                    *cell = AnyChanCell::new(circ_id, AnyChanMsg::Create2(new_msg));
                }
            });
            let (client_chan, relay_chan, _circuit_stream_rx, mut target_builder) =
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
            // 4 = RELAY_NTORV3
            // 5 = RELAY_NEGOTIATE_SUBPROTO
            // 6 = RELAY_CRYPT_CGO
            for relay_version in [4, 5, 6] {
                let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
                let circ_params = CircParameters::default();
                let protocols = format!("Relay=4-{relay_version}").parse().unwrap();
                let target = target_builder.protocols(protocols).build().unwrap();
                // The relay refuses the circuit handshake since the CREATED2 cell had some
                // intentional issue with the handshake body.
                assert!(matches!(
                    pending_tunnel.create_firsthop(&target, circ_params).await,
                    Err(crate::Error::CircRefused(_)),
                ));
                // Client sent a CREATE2, relay responded with a DESTROY.
                assert_eq!(
                    conn_inspector.try_client_cell().unwrap().msg().cmd(),
                    ChanCmd::CREATE2,
                );
                assert_eq!(
                    conn_inspector.try_relay_cell().unwrap().msg().cmd(),
                    ChanCmd::DESTROY,
                );
                // We don't expect any other messages to have been sent.
                assert!(conn_inspector.try_client_cell().is_none());
                assert!(conn_inspector.try_relay_cell().is_none());
            }
            // Wait for both channels to close (ignoring any channel errors).
            let wait_fut =
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
            drop((client_chan, relay_chan));
            let _ = wait_fut.await;
            // We don't expect any other messages to have been sent.
            assert!(conn_inspector.try_client_cell().is_none());
            assert!(conn_inspector.try_relay_cell().is_none());
        });
    }
    /// Test the CREATE2 handshake, but with an invalid handshake type.
    #[test]
    fn create2_invalid_handshake_fail() {
        test_with_one_runtime!(|rt| async move {
            let mut conn_inspector = test_utils::ConnInspector::new();
            // Rewrite any client-sent CREATE2 messages to cause the relay to fail the handshake.
            conn_inspector.set_client_cell_modifier(|cell: &mut AnyChanCell| {
                let circ_id = cell.circid();
                if let AnyChanMsg::Create2(msg) = cell.msg() {
                    // Reassemble the CREATE2 cell with the incorrect handshake type.
                    let new_msg = tor_cell::chancell::msg::Create2::new(99.into(), msg.body());
                    *cell = AnyChanCell::new(circ_id, AnyChanMsg::Create2(new_msg));
                }
            });
            let (client_chan, relay_chan, _circuit_stream_rx, mut target_builder) =
                test_utils::new_channel_pair_with_keys(&rt, &conn_inspector);
            // https://spec.torproject.org/tor-spec/subprotocol-versioning.html
            // 2 = RELAY_NTOR
            // 3 = RELAY_EXTEND_IPv6
            // 4 = RELAY_NTORV3
            // 5 = RELAY_NEGOTIATE_SUBPROTO
            // 6 = RELAY_CRYPT_CGO
            for relay_version in [2, 6] {
                let pending_tunnel = test_utils::new_pending_tunnel(&rt, &client_chan).await;
                let circ_params = CircParameters::default();
                let protocols = format!("Relay=2-{relay_version}").parse().unwrap();
                let target = target_builder.protocols(protocols).build().unwrap();
                // The relay refuses the circuit handshake since the CREATED2 cell had some
                // unrecognized handshake type.
                assert!(matches!(
                    pending_tunnel.create_firsthop(&target, circ_params).await,
                    Err(crate::Error::CircRefused(_)),
                ));
                // Client sent a CREATE2, relay responded with a DESTROY.
                assert_eq!(
                    conn_inspector.try_client_cell().unwrap().msg().cmd(),
                    ChanCmd::CREATE2,
                );
                assert_eq!(
                    conn_inspector.try_relay_cell().unwrap().msg().cmd(),
                    ChanCmd::DESTROY,
                );
                // We don't expect any other messages to have been sent.
                assert!(conn_inspector.try_client_cell().is_none());
                assert!(conn_inspector.try_relay_cell().is_none());
            }
            // Wait for both channels to close (ignoring any channel errors).
            let wait_fut =
                futures::future::join(client_chan.wait_for_close(), relay_chan.wait_for_close());
            drop((client_chan, relay_chan));
            let _ = wait_fut.await;
            // We don't expect any other messages to have been sent.
            assert!(conn_inspector.try_client_cell().is_none());
            assert!(conn_inspector.try_relay_cell().is_none());
        });
    }
}