tor-circmgr 0.37.0

Manage a set of anonymous circuits over the Tor network
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
//! Code related to tunnel object that wraps the tor-proto tunnel.
//!
//! These tunnel types are part of the public API.

use derive_deftly::{Deftly, define_derive_deftly};
use std::{net::IpAddr, sync::Arc};

use tor_cell::relaycell::msg::AnyRelayMsg;
use tor_error::internal;
use tor_linkspec::{CircTarget, IntoOwnedChanTarget, OwnedChanTarget};
use tor_proto::{
    ClockSkew, TargetHop,
    circuit::UniqId,
    client::circuit::{CircParameters, CircuitBinding, ClientCirc},
    client::stream::{DataStream, StreamParameters},
};
use tracing::instrument;

use crate::{Error, Result};

#[cfg(feature = "hs-common")]
use tor_proto::client::circuit::handshake;

// The tunnel base methods. This MUST be derived on all tunnel types.
define_derive_deftly! {
    BaseTunnel for struct:

    impl From<tor_proto::ClientTunnel> for $ttype {
        fn from(tunnel: tor_proto::ClientTunnel) -> Self {
            Self { tunnel: Arc::new(tunnel) }
        }
    }

    impl From<Arc<tor_proto::ClientTunnel>> for $ttype {
        fn from(tunnel: Arc<tor_proto::ClientTunnel>) -> Self {
            Self { tunnel }
        }
    }

    impl AsRef<tor_proto::ClientTunnel> for $ttype {
        fn as_ref(&self) -> &tor_proto::ClientTunnel {
            self.tunnel.as_ref()
        }
    }

    impl $ttype {
        /// Return a reference to the underlying tunnel.
        ///
        /// Note: The "tunnel" name is hardcoded here. If it becomes an annoyance, we could make it
        /// as a meta value of the deftly declaration.
        fn tunnel_ref(&self) -> &Arc<tor_proto::ClientTunnel> {
            &self.tunnel
        }

        /// Return true if this tunnel is closed and therefore unusable.
        pub fn is_closed(&self) -> bool {
            self.tunnel_ref().is_closed()
        }

        /// Return a [`TargetHop`] representing precisely the last hop of the circuit as in set as a
        /// HopLocation with its id and hop number.
        ///
        /// Return an error if there is no last hop.
        pub fn last_hop(&self) -> Result<TargetHop> {
            self.tunnel_ref().last_hop()
                .map_err(|error| Error::Protocol {
                    action: "get last hop",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }

        /// Shutdown the tunnel meaning this sends a shutdown command to the underlying circuit
        /// reactor which will stop asynchronously.
        ///
        /// Note that it is not necessary to use this method as in if the tunnel reference is
        /// dropped, the circuit will close automatically.
        pub fn terminate(&self) {
            self.tunnel_ref().terminate();
        }

        /// Return a process-unique identifier for this tunnel.
        pub fn unique_id(&self) -> UniqId {
            self.tunnel_ref().unique_id()
        }

        /// Send raw message.
        #[cfg(feature = "send-control-msg")]
        pub async fn send_raw_msg(&self, msg: AnyRelayMsg, hop: TargetHop) -> Result<()> {
            self.tunnel_ref()
                .send_raw_msg(msg, hop)
                .await
                .map_err(|error| Error::Protocol {
                    action: "send raw msg",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }

        /// Start an ad-hoc protocol exchange to the specified hop on this tunnel.
        ///
        /// See [`ClientTunnel::start_conversation`](tor_proto::ClientTunnel::start_conversation)
        /// documentation for more details.
        #[cfg_attr(docsrs, doc(cfg(feature = "send-control-msg")))]
        #[cfg(feature = "send-control-msg")]
        pub async fn start_conversation(&self,
            msg: Option<tor_cell::relaycell::msg::AnyRelayMsg>,
            reply_handler: impl tor_proto::MsgHandler + Send + 'static,
            hop: TargetHop
        ) -> Result<tor_proto::Conversation<'_>> {
            self.tunnel_ref().start_conversation(msg, reply_handler, hop).await
                .map_err(|error| Error::Protocol {
                    action: "start conversation",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel_ref().unique_id()),
                })
        }

        /// Return a future that will resolve once this circuit has closed.
        ///
        /// Note that this method does not itself cause the circuit to shut down.
        ///
        // TODO: Perhaps this should return some kind of status indication instead
        // of just ()
        pub fn wait_for_close(&self) -> impl futures::Future<Output = ()> + Send + Sync + 'static + use<> {
            self.tunnel_ref().wait_for_close()
        }

        // TODO(conflux): mq_account() is not needed because it is only used internally in a ClientCirc
        // in order to open streams. It might be the case that we need at some point to get the
        // CircuitAccount(s) from a tunnel. We would need then to either have a TunnelAccount or return
        // a Vec<CircuitAccount>.
    }
}

// Methods for a single path tunnel.
define_derive_deftly! {
    SinglePathTunnel for struct:

    impl $ttype {
        /// Return a reference to the circuit of this tunnel.
        fn circuit(&self) -> Result<&ClientCirc> {
            Ok(self.tunnel_ref()
                .as_single_circ()
                .map_err(|e| internal!("Non single path in a single path tunnel: {}", e))?)
        }

        /// Extend the circuit to a new target last hop using the ntor v3 handshake.
        ///
        /// TODO: Might want to pass which handshake type as a parameter so this function can be a
        /// catch all on all possible handshakes. For now, use ntor v3 for all the things.
        pub async fn extend<T: CircTarget>(&self, target: &T, params: CircParameters) -> Result<()> {
            self.circuit()?
                .extend(target, params)
                .await
                .map_err(|error| Error::Protocol {
                    action: "extend tunnel",
                    peer: Some(target.to_owned().to_logged()),
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }

        /// Return the number of hops of the underlying circuit.
        pub fn n_hops(&self) -> Result<usize> {
            self.circuit()?.n_hops()
                .map_err(|error| Error::Protocol {
                    action: "get number hops",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel_ref().unique_id()),
                })
        }

    }
}

// Methods for a multi path tunnel.
#[cfg(feature = "conflux")]
define_derive_deftly! {
    MultiPathTunnel for struct:

    impl $ttype {
        // TODO(conflux)
        //
        // As we add multi path support accross the code, we'll might need or not some specific
        // functions that would go here.
    }
}

// Methods for a tunnel that can transmit data (BEGIN).
define_derive_deftly! {
    DataTunnel for struct:

    impl $ttype {
        /// Start a stream to the given address and port, using a BEGIN cell.
        ///
        /// The use of a string for the address is intentional: you should let
        /// the remote Tor relay do the hostname lookup for you.
        #[instrument(skip_all, level = "trace")]
        pub async fn begin_stream(
            &self,
            target: &str,
            port: u16,
            params: Option<StreamParameters>,
        ) -> Result<DataStream> {
            self.tunnel_ref()
                .begin_stream(target, port, params)
                .await
                .map_err(|error| Error::Protocol {
                    action: "begin stream",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }
    }

}

// Methods for a tunnel that can do DNS resolution (RESOLVE).
define_derive_deftly! {
    DnsTunnel for struct:

    impl $ttype {
        /// Perform a DNS lookup, using a RESOLVE cell with the last relay in this circuit.
        ///
        /// Note that this function does not check for timeouts; that's the caller's responsibility.
        pub async fn resolve(&self, hostname: &str) -> Result<Vec<IpAddr>> {
            self.tunnel_ref()
                .resolve(hostname)
                .await
                .map_err(|error| Error::Protocol {
                    action: "resolve",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }

        /// Perform a reverse DNS lookup, using a RESOLVE cell with the last relay in this circuit.
        ///
        /// Note that this function does not check for timeouts; that's the caller's responsibility.
        pub async fn resolve_ptr(&self, addr: IpAddr) -> Result<Vec<String>> {
            self.tunnel_ref()
                .resolve_ptr(addr)
                .await
                .map_err(|error| Error::Protocol {
                    action: "resolve PTR",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }
    }
}

// Methods for a tunnel that can do directory requests (BEGIN_DIR).
define_derive_deftly! {
    DirTunnel for struct:

    impl $ttype {
        /// Start a stream to the given address and port, using a BEGIN_DIR cell.
        pub async fn begin_dir_stream(&self) -> Result<DataStream> {
            self.tunnel_ref().clone()
                .begin_dir_stream()
                .await
                .map_err(|error| Error::Protocol {
                    action: "begin dir stream",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }
    }
}

// Methods for a tunnel that can transmit data (BEGIN).
define_derive_deftly! {
    OnionServiceDataTunnel for struct:

    impl $ttype {
        /// Extend this circuit by a single, "virtual" hop.
        ///
        /// A virtual hop is one for which we do not add an actual network connection
        /// between separate hosts (such as Relays).  We only add a layer of
        /// cryptography.
        ///
        /// This is used to implement onion services: the client and the service
        /// both build a circuit to a single rendezvous point, and tell the
        /// rendezvous point to relay traffic between their two circuits.  Having
        /// completed a [`handshake`] out of band[^1], the parties each extend their
        /// circuits by a single "virtual" encryption hop that represents their
        /// shared cryptographic context.
        ///
        /// Once a circuit has been extended in this way, it is an error to try to
        /// extend it in any other way.
        ///
        /// [^1]: Technically, the handshake is only _mostly_ out of band: the
        ///     client sends their half of the handshake in an ` message, and the
        ///     service's response is inline in its `RENDEZVOUS2` message.
        //
        // TODO hs: let's try to enforce the "you can't extend a circuit again once
        // it has been extended this way" property.  We could do that with internal
        // state, or some kind of a type state pattern.
        //
        // TODO hs: possibly we should take a set of Protovers, and not just `Params`.
        #[cfg(feature = "hs-common")]
        pub async fn extend_virtual(
            &self,
            protocol: handshake::RelayProtocol,
            role: handshake::HandshakeRole,
            seed: impl handshake::KeyGenerator,
            params: CircParameters,
            capabilities: &tor_protover::Protocols,
        ) -> Result<()> {
            self.circuit()?
                .extend_virtual(protocol, role, seed, &params, capabilities)
                .await
                .map_err(|error| Error::Protocol {
                    action: "extend virtual tunnel",
                    peer: None,
                    error,
                    unique_id: Some(self.tunnel.unique_id()),
                })
        }
    }

}

/// A client single path data tunnel.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, DnsTunnel, SinglePathTunnel)]
pub struct ClientDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client directory tunnel. This is always single path.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DirTunnel, SinglePathTunnel)]
pub struct ClientDirTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client onion service single path data tunnel.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, OnionServiceDataTunnel, SinglePathTunnel)]
pub struct ClientOnionServiceDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client onion service directory tunnel (to an HSDir). This is always single path.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DirTunnel, SinglePathTunnel)]
pub struct ClientOnionServiceDirTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client onion service introduction tunnel. This is always single path.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, SinglePathTunnel)]
pub struct ClientOnionServiceIntroTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A service onion service single path data tunnel.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, OnionServiceDataTunnel, SinglePathTunnel)]
pub struct ServiceOnionServiceDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A service onion service directory tunnel (to an HSDir). This is always single path.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DirTunnel, SinglePathTunnel)]
pub struct ServiceOnionServiceDirTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A service onion service introduction tunnel. This is always single path.
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, SinglePathTunnel)]
pub struct ServiceOnionServiceIntroTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client multi path data tunnel (Conflux).
#[cfg(feature = "conflux")]
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, DnsTunnel, MultiPathTunnel)]
pub struct ClientMultiPathDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A client multi path onion service data tunnel (Conflux, Rendeszvous).
#[cfg(feature = "conflux")]
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, MultiPathTunnel)]
pub struct ClientMultiPathOnionServiceDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

/// A service multi path onion service data tunnel (Conflux, Rendeszvous).
#[cfg(feature = "conflux")]
#[derive(Debug, Deftly)]
#[derive_deftly(BaseTunnel, DataTunnel, MultiPathTunnel)]
pub struct ServiceMultiPathOnionServiceDataTunnel {
    /// The protocol level tunnel.
    tunnel: Arc<tor_proto::ClientTunnel>,
}

impl ClientDirTunnel {
    /// Return a description of the first hop of this circuit.
    pub fn first_hop(&self) -> OwnedChanTarget {
        self.tunnel_ref()
            .first_hop()
            .expect("Bug getting dir tunnel first hop")
    }

    /// Get the clock skew claimed by the first hop of the circuit.
    ///
    /// See [`Channel::clock_skew()`](tor_proto::channel::Channel::clock_skew).
    pub async fn first_hop_clock_skew(&self) -> Result<ClockSkew> {
        // TODO(conflux): Is this CircCanceled error right?
        self.circuit()?
            .first_hop_clock_skew()
            .await
            .map_err(|_| Error::CircCanceled)
    }
}

impl ServiceOnionServiceDataTunnel {
    /// Tell this tunnel to begin allowing the final hop of the tunnel to try
    /// to create new Tor streams, and to return those pending requests in an
    /// asynchronous stream.
    ///
    /// Ordinarily, these requests are rejected.
    ///
    /// There can only be one [`Stream`](futures::Stream) of this type created on a given tunnel.
    /// If a such a [`Stream`](futures::Stream) already exists, this method will return
    /// an error.
    ///
    /// After this method has been called on a tunnel, the tunnel is expected
    /// to receive requests of this type indefinitely, until it is finally closed.
    /// If the `Stream` is dropped, the next request on this tunnel will cause it to close.
    ///
    /// Only onion services (and eventually) exit relays should call this
    /// method.
    //
    // TODO: Someday, we might want to allow a stream request handler to be
    // un-registered.  However, nothing in the Tor protocol requires it.
    #[cfg(feature = "hs-service")]
    pub async fn allow_stream_requests<'a, FILT>(
        &self,
        allow_commands: &'a [tor_cell::relaycell::RelayCmd],
        hop: TargetHop,
        filter: FILT,
    ) -> Result<
        impl futures::Stream<Item = tor_proto::client::stream::IncomingStream> + use<'a, FILT>,
    >
    where
        FILT: tor_proto::client::stream::IncomingStreamRequestFilter,
    {
        self.tunnel_ref()
            .allow_stream_requests(allow_commands, hop, filter)
            .await
            .map_err(|error| Error::Protocol {
                action: "allow stream requests",
                peer: None,
                error,
                unique_id: Some(self.tunnel.unique_id()),
            })
    }
}

#[cfg(feature = "hs-service")]
impl ServiceOnionServiceIntroTunnel {
    /// Return the cryptographic material used to prove knowledge of a shared
    /// secret with with `hop`.
    ///
    /// See [`CircuitBinding`] for more information on how this is used.
    ///
    /// Return None if we have no circuit binding information for the hop, or if
    /// the hop does not exist.
    pub async fn binding_key(&self, hop: TargetHop) -> Result<Option<CircuitBinding>> {
        let circ = self.circuit()?;
        circ.binding_key(hop)
            .await
            .map_err(|error| Error::Protocol {
                action: "binding key",
                peer: None,
                error,
                unique_id: Some(self.tunnel.unique_id()),
            })
    }
}