tor-proto 0.44.0

Asynchronous client-side implementation of the central Tor network protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Handler for CREATE* cells.

use crate::FlowCtrlParameters;
use crate::ccparams::{
    Algorithm, AlgorithmDiscriminants, CongestionControlParams, CongestionWindowParams,
    FixedWindowParams, RoundTripEstimatorParams, VegasParams,
};
use crate::channel::Channel;
use crate::circuit::CircuitRxSender;
use crate::circuit::UniqId;
use crate::circuit::celltypes::{CreateRequest, CreateResponse};
use crate::circuit::circhop::{HopNegotiationType, HopSettings};
use crate::client::circuit::CircParameters;
use crate::client::circuit::padding::PaddingController;
use crate::crypto::binding::CircuitBinding;
use crate::crypto::cell::CryptInit as _;
use crate::crypto::cell::{InboundRelayLayer, OutboundRelayLayer, RelayLayer, tor1};
use crate::crypto::handshake::RelayHandshakeError;
use crate::crypto::handshake::ServerHandshake as _;
use crate::crypto::handshake::fast::CreateFastServer;
use crate::crypto::handshake::ntor::{NtorSecretKey, NtorServer};
use crate::memquota::SpecificAccount as _;
use crate::memquota::{ChannelAccount, CircuitAccount};
use crate::relay::channel_provider::ChannelProvider;
use crate::relay::reactor::Reactor;
use crate::relay::{IncomingStreamRequestFilter, RelayCirc};
use smallvec::SmallVec;
use std::sync::{Arc, RwLock, Weak};
use tor_cell::chancell::ChanMsg as _;
use tor_cell::chancell::CircId;
use tor_cell::chancell::msg::{
    CreateFast, Created2, CreatedFast, Destroy, DestroyReason, HandshakeType,
};
use tor_error::{Bug, ErrorKind, HasKind, debug_report, internal, into_internal};
use tor_linkspec::OwnedChanTarget;
use tor_llcrypto::cipher::aes::Aes128Ctr;
use tor_llcrypto::d::Sha1;
use tor_llcrypto::pk::ed25519::Ed25519Identity;
use tor_llcrypto::pk::rsa::RsaIdentity;
use tor_memquota::mq_queue::ChannelSpec as _;
use tor_memquota::mq_queue::MpscSpec;
use tor_relay_crypto::pk::{RelayNtorKeypair, RelayNtorKeys};
use tor_rtcompat::SpawnExt as _;
use tor_rtcompat::{DynTimeProvider, Runtime};
use tracing::warn;

/// Everything needed to handle CREATE* messages on channels.
#[derive(derive_more::Debug)]
pub struct CreateRequestHandler {
    /// Something that can launch channels. Typically the `ChanMgr`.
    chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
    /// Circuit-related network parameters.
    circ_net_params: RwLock<CircNetParameters>,
    /// The circuit extension keys.
    #[debug(skip)]
    ntor_keys: RwLock<RelayNtorKeys>,
    /// An [`IncomingStreamRequestFilter`] factory for checking whether the user wants
    /// this request, or wants to reject it immediately.
    ///
    /// Used for obtaining a current [`IncomingStreamRequestFilter`]
    /// for building a circuit reactor.
    //
    // TODO(relay): it's likely this will end up changing quite a bit once we start
    // figuring out exactly how the config/reconfigure() logic and IncomingStreamRequestFilter
    // should function for relays.
    #[debug(skip)]
    incoming_filter_factory: Box<dyn IncomingStreamRequestFilterFactory + Send + Sync>,
}

impl CreateRequestHandler {
    /// Build a new [`CreateRequestHandler`].
    pub fn new(
        chan_provider: Weak<dyn ChannelProvider<BuildSpec = OwnedChanTarget> + Send + Sync>,
        circ_net_params: CircNetParameters,
        ntor_keys: RelayNtorKeys,
        incoming_filter_factory: Box<dyn IncomingStreamRequestFilterFactory + Send + Sync>,
    ) -> Self {
        Self {
            chan_provider,
            circ_net_params: RwLock::new(circ_net_params),
            ntor_keys: RwLock::new(ntor_keys),
            incoming_filter_factory,
        }
    }

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

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

    /// Handle a CREATE* cell.
    ///
    /// This intentionally does not return a [`crate::Error`] so that we don't accidentally shut
    /// down the channel reactor when we really should be returning a DESTROY. Shutting down a
    /// channel may cause us to leak information about paths of circuits travelling through this
    /// relay. This is especially important here since we're handling data that is controllable from
    /// the other end of the circuit.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn handle_create<R: Runtime>(
        &self,
        runtime: &R,
        channel: &Arc<Channel>,
        our_ed25519_id: &Ed25519Identity,
        our_rsa_id: &RsaIdentity,
        circ_id: CircId,
        msg: &CreateRequest,
        memquota: &ChannelAccount,
        circ_unique_id: UniqId,
    ) -> Result<(CreateResponse, RelayCircComponents), Destroy> {
        let result = self.handle_create_inner(
            runtime,
            channel,
            our_ed25519_id,
            our_rsa_id,
            circ_id,
            msg,
            memquota,
            circ_unique_id,
        );

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

                // `tor-spec/tearing-down-circuits.md`:
                //
                // > Implementations SHOULD always use the NONE reason to avoid side channels: [...]
                Err(Destroy::new(DestroyReason::NONE))
            }
        }
    }

    /// See [`Self::handle_create`].
    #[allow(clippy::too_many_arguments)]
    fn handle_create_inner<R: Runtime>(
        &self,
        runtime: &R,
        channel: &Arc<Channel>,
        our_ed25519_id: &Ed25519Identity,
        our_rsa_id: &RsaIdentity,
        circ_id: CircId,
        msg: &CreateRequest,
        memquota: &ChannelAccount,
        circ_unique_id: UniqId,
    ) -> Result<(CreateResponse, RelayCircComponents), HandleCreateError> {
        // Perform the handshake crypto and build the response.
        let handshake_components = match msg {
            CreateRequest::CreateFast(msg) => self.handle_create_fast(msg)?,
            CreateRequest::Create2(msg) => match msg.handshake_type() {
                HandshakeType::NTOR_V3 => self.handle_create2_ntorv3(msg.body(), our_ed25519_id)?,
                HandshakeType::NTOR => self.handle_create2_ntor(msg.body(), our_rsa_id)?,
                x @ HandshakeType::TAP | x => {
                    return Err(HandleCreateError::Create2HandshakeType(x));
                }
            },
        };

        let memquota = CircuitAccount::new(memquota)?;

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

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

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

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

        // Build the relay circuit reactor.
        let (reactor, circ, _incoming_streams) = Reactor::new(
            runtime.clone(),
            channel,
            circ_id,
            circ_unique_id,
            receiver,
            handshake_components.crypto_in,
            handshake_components.crypto_out,
            &handshake_components.hop_settings,
            chan_provider,
            padding_ctrl.clone(),
            padding_stream,
            incoming_filter,
            &memquota,
        )
        .map_err(into_internal!("Failed to start circuit reactor"))?;

        // TODO(relay): send the incoming_streams stream to the handler in arti-relay

        // Start the reactor in a task.
        let () = runtime.spawn(async {
            match reactor.run().await {
                Ok(()) => {}
                Err(e) => {
                    debug_report!(e, "Relay circuit reactor exited with an error");
                }
            }
        })?;

        Ok((
            handshake_components.response,
            RelayCircComponents {
                circ,
                sender,
                padding_ctrl,
            },
        ))
    }

    /// The handshake code for a CREATE_FAST request.
    fn handle_create_fast(
        &self,
        msg: &CreateFast,
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
        // TODO(relay): We might want to offload this to a CPU worker in the future.
        let (keygen, handshake_msg) = CreateFastServer::server(
            &mut rand::rng(),
            // The CREATE_FAST handshake doesn't accept or return extensions,
            // so this `AuxDataReply` is a no-op.
            &mut |_: &()| Some(()),
            // The CREATE_FAST handshake doesn't use any keys.
            &[()],
            msg.handshake(),
        )?;

        let crypt = tor1::CryptStatePair::<Aes128Ctr, Sha1>::construct(keygen)
            .map_err(into_internal!("Circuit crypt state construction failed"))?;

        let circ_params = self
            .circ_net_params
            .read()
            .expect("rwlock poisoned")
            // CREATE_FAST always uses fixed-window flow control.
            .as_circ_parameters(AlgorithmDiscriminants::FixedWindow)?;

        // TODO(relay): I don't think that this is the right way to do this. It works for
        // CREATE_FAST, but we might want to rethink it for CREATE2.
        let protos = tor_protover::Protocols::default();
        let hop_settings =
            HopSettings::from_params_and_caps(HopNegotiationType::None, &circ_params, &protos)
                .map_err(into_internal!("Unable to build `HopSettings`"))?;

        let response = CreatedFast::new(handshake_msg);
        let response = CreateResponse::CreatedFast(response);

        let (crypto_out, crypto_in, _binding) = split_relay_layer(crypt);

        Ok(CompletedHandshakeComponents {
            response,
            hop_settings,
            crypto_out,
            crypto_in,
        })
    }

    /// The handshake code for a CREATE2 ntor (non-v3) request.
    fn handle_create2_ntor(
        &self,
        msg_body: &[u8],
        our_rsa_id: &RsaIdentity,
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
        let ntor_keys = self.ntor_keys(|k| {
            NtorSecretKey::new(k.secret().clone(), *k.public().inner(), *our_rsa_id)
        });

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

        let crypt = tor1::CryptStatePair::<Aes128Ctr, Sha1>::construct(keygen)
            .map_err(into_internal!("Circuit crypt state construction failed"))?;

        let (crypto_out, crypto_in, _binding) = split_relay_layer(crypt);

        let circ_params = self
            .circ_net_params
            .read()
            .expect("rwlock poisoned")
            // CREATE2 with ntor (non-v3) always uses fixed-window flow control.
            .as_circ_parameters(AlgorithmDiscriminants::FixedWindow)?;

        // TODO(relay): I don't think that this is the right way to do this. It works for
        // ntor, but won't work well for ntor-v3.
        let protos = tor_protover::Protocols::default();
        let hop_settings =
            HopSettings::from_params_and_caps(HopNegotiationType::None, &circ_params, &protos)
                .map_err(into_internal!("Unable to build `HopSettings`"))?;

        let response = Created2::new(handshake_msg);
        let response = CreateResponse::Created2(response);

        Ok(CompletedHandshakeComponents {
            response,
            hop_settings,
            crypto_out,
            crypto_in,
        })
    }

    /// The handshake code for a CREATE2 ntor-v3 request.
    fn handle_create2_ntorv3(
        &self,
        _msg_body: &[u8],
        _our_ed25519_id: &Ed25519Identity,
    ) -> Result<CompletedHandshakeComponents, HandleCreateError> {
        Err(HandleCreateError::Create2HandshakeType(
            HandshakeType::NTOR_V3,
        ))
    }

    /// Helper to get the ntor keypairs after some transformation `map`.
    ///
    /// The `map` transformation must be fast since it blocks a read lock.
    /// The returned keys are sorted with the most recent key first.
    ///
    /// It would be nice if this just returned an iterator,
    /// but the read lock prevents this.
    fn ntor_keys<T>(&self, map: impl FnMut(&RelayNtorKeypair) -> T) -> impl AsRef<[T]> {
        let ntor_keys = self.ntor_keys.read().expect("rwlock poisoned");
        let ntor_keys = [Some(ntor_keys.latest()), ntor_keys.previous()];
        ntor_keys
            .into_iter()
            .flatten()
            .map(map)
            .collect::<SmallVec<[T; 2]>>()
    }
}

/// Helper function to split a `RelayLayer` into forward and backward type-erased trait objects.
fn split_relay_layer<F, B>(
    crypt: impl RelayLayer<F, B>,
) -> (
    Box<dyn OutboundRelayLayer + Send>,
    Box<dyn InboundRelayLayer + Send>,
    CircuitBinding,
)
where
    F: OutboundRelayLayer + Send + 'static,
    B: InboundRelayLayer + Send + 'static,
{
    let (crypto_out, crypto_in, binding) = crypt.split_relay_layer();
    let (crypto_out, crypto_in) = (Box::new(crypto_out), Box::new(crypto_in));

    (crypto_out, crypto_in, binding)
}

/// An error that occurred while handling a CREATE* request.
#[derive(Debug, thiserror::Error)]
enum HandleCreateError {
    /// Circuit relay handshake failed.
    #[error("Circuit relay handshake failed")]
    Handshake(#[from] RelayHandshakeError),
    /// The requested handshake type is unsupported.
    #[error("Unsupported handshake type {0}")]
    Create2HandshakeType(HandshakeType),
    /// A memquota error.
    #[error("Memquota error")]
    Memquota(#[from] tor_memquota::Error),
    /// Error when spawning a task.
    #[error("Runtime task spawn error")]
    Spawn(#[from] futures::task::SpawnError),
    /// An internal error.
    ///
    /// Note that other variants (such as `Handshake` containing a [`RelayHandshakeError`])
    /// may themselves contain internal errors.
    #[error("Internal error")]
    Internal(#[from] tor_error::Bug),
}

impl HasKind for HandleCreateError {
    fn kind(&self) -> ErrorKind {
        match self {
            Self::Handshake(e) => e.kind(),
            Self::Create2HandshakeType(_) => ErrorKind::NotImplemented,
            Self::Memquota(e) => e.kind(),
            Self::Spawn(e) => e.kind(),
            Self::Internal(_) => ErrorKind::Internal,
        }
    }
}

/// The components of a completed CREATE* handshake.
struct CompletedHandshakeComponents {
    /// The message to send in response.
    response: CreateResponse,
    /// The negotiated hop settings.
    hop_settings: HopSettings,
    /// Outbound onion crypto.
    crypto_out: Box<dyn OutboundRelayLayer + Send>,
    /// Inbound onion crypto.
    crypto_in: Box<dyn InboundRelayLayer + Send>,
}

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

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

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

    /// Congestion window parameters.
    pub cwnd: CongestionWindowParams,

    /// RTT calculation parameters.
    pub rtt: RoundTripEstimatorParams,

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

impl CongestionControlNetParams {
    #[cfg(test)]
    // These have been copied from C-tor.
    pub(crate) fn defaults_for_tests() -> Self {
        Self {
            fixed_window: FixedWindowParams::defaults_for_tests(),
            vegas_exit: VegasParams::defaults_for_tests(),
            cwnd: CongestionWindowParams::defaults_for_tests(),
            rtt: RoundTripEstimatorParams::defaults_for_tests(),
            flow_ctrl: FlowCtrlParameters::defaults_for_tests(),
        }
    }
}

/// Network consensus parameters for handling incoming circuits.
///
/// Unlike `CircParameters`,
/// this is unopinionated and contains all relevant consensus parameters,
/// which is needed when handling an incoming CREATE* request where the
/// circuit origin chooses the type/settings
/// (for example congestion control type) of the circuit.
#[derive(Debug, Clone)]
#[allow(clippy::exhaustive_structs)]
pub struct CircNetParameters {
    /// Whether we should include ed25519 identities when we send EXTEND2 cells.
    pub extend_by_ed25519_id: bool,

    /// Congestion control network parameters.
    pub cc: CongestionControlNetParams,
}

impl CircNetParameters {
    /// Convert the [`CircNetParameters`] into a [`CircParameters`].
    ///
    /// We expect the circuit creation handshake to know what congestion control algorithm was
    /// negotiated, and provide that as `algorithm`.
    //
    // We disable `unused` warnings at the root of tor-proto,
    // but it's nice to have here so we re-enable it.
    #[warn(unused)]
    fn as_circ_parameters(&self, algorithm: AlgorithmDiscriminants) -> Result<CircParameters, Bug> {
        // Unpack everything to make sure that we aren't missing anything
        // (otherwise clippy would warn).
        let Self {
            extend_by_ed25519_id,
            cc:
                CongestionControlNetParams {
                    fixed_window,
                    vegas_exit,
                    cwnd,
                    rtt,
                    flow_ctrl,
                },
        } = self;

        let algorithm = match algorithm {
            AlgorithmDiscriminants::FixedWindow => Algorithm::FixedWindow(*fixed_window),
            AlgorithmDiscriminants::Vegas => Algorithm::Vegas(*vegas_exit),
        };

        // TODO(arti#2442): The builder pattern here seems like a footgun.
        let cc = CongestionControlParams::builder()
            .alg(algorithm)
            .fixed_window_params(*fixed_window)
            .cwnd_params(*cwnd)
            .rtt_params(rtt.clone())
            .build()
            .map_err(into_internal!("Could not build `CongestionControlParams`"))?;

        Ok(CircParameters::new(
            *extend_by_ed25519_id,
            cc,
            flow_ctrl.clone(),
        ))
    }
}

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

impl<F> IncomingStreamRequestFilterFactory for F
where
    F: Fn() -> Box<dyn IncomingStreamRequestFilter>,
{
    fn current_filter(&self) -> Box<dyn IncomingStreamRequestFilter> {
        (self)()
    }
}