1
//! Implement a concrete type to build channels over a transport.
2

            
3
use async_trait::async_trait;
4
use futures::{AsyncRead, AsyncWrite};
5
use std::io;
6
use std::sync::{Arc, Mutex};
7
use std::time::Duration;
8
use tracing::instrument;
9

            
10
use crate::factory::{BootstrapReporter, ChannelFactory, IncomingChannelFactory};
11
use crate::transport::TransportImplHelper;
12
use crate::{Error, event::ChanMgrEventSender};
13

            
14
use safelog::MaybeSensitive;
15
use tor_basic_utils::rand_hostname;
16
use tor_error::internal;
17
use tor_linkspec::{ChanTarget, HasChanMethod, IntoOwnedChanTarget, OwnedChanTarget};
18
use tor_proto::channel::ChannelType;
19
use tor_proto::channel::kist::KistParams;
20
use tor_proto::channel::params::ChannelPaddingInstructionsUpdates;
21
use tor_proto::memquota::ChannelAccount;
22
use tor_proto::peer::PeerAddr;
23
use tor_rtcompat::SpawnExt;
24
use tor_rtcompat::{CertifiedConn, Runtime, StreamOps, TlsProvider, tls::TlsConnector};
25

            
26
#[cfg(feature = "relay")]
27
use {
28
    crate::mgr::ChannelBandwidthPools, safelog::Sensitive, std::net::SocketAddr,
29
    tor_async_utils::global_rate_limit::GlobalRateLimitedConn, tor_error::bad_api_usage,
30
    tor_proto::RelayChannelAuthMaterial, tor_proto::relay::CreateRequestHandler,
31
};
32

            
33
/// Handshake timeout in seconds.
34
///
35
/// C-tor has this at 5 minutes but that is way too high. Put it at 60 seconds so we
36
/// leave room for network hiccups or natural latency.
37
#[cfg(feature = "relay")]
38
const INCOMING_HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
39

            
40
/// TLS-based channel builder.
41
///
42
/// This is a separate type so that we can keep our channel management code
43
/// network-agnostic.
44
///
45
/// It uses a provided `TransportHelper` type to make a connection (possibly
46
/// directly over TCP, and possibly over some other protocol).  It then
47
/// negotiates TLS over that connection, and negotiates a Tor channel over that
48
/// TLS session.
49
///
50
/// This channel builder does not retry on failure, but it _does_ implement a
51
/// time-out.
52
pub struct ChanBuilder<R: Runtime, H: TransportImplHelper>
53
where
54
    R: tor_rtcompat::TlsProvider<H::Stream>,
55
{
56
    /// Asynchronous runtime for TLS, TCP, spawning, and timeouts.
57
    runtime: R,
58
    /// The transport object that we use to construct streams.
59
    transport: H,
60
    /// Object to build TLS connections.
61
    tls_connector: <R as TlsProvider<H::Stream>>::Connector,
62
    /// Object to accept TLS connections.
63
    #[cfg(feature = "relay")]
64
    tls_acceptor: Option<<R as TlsProvider<H::Stream>>::Acceptor>,
65
    /// Relay authentication key material needed for relay channels.
66
    #[cfg(feature = "relay")]
67
    auth_material: Option<Arc<RelayChannelAuthMaterial>>,
68
    /// Our address(es) to use in the NETINFO cell.
69
    // TODO: We might want one day to support updating the addresses here in the same way we
70
    // support updating the auth_material. One use case for this is the relay config reload.
71
    #[cfg(feature = "relay")]
72
    my_addrs: Vec<SocketAddr>,
73
    /// Provided to each new channel so that they can handle CREATE* requests.
74
    #[cfg(feature = "relay")]
75
    create_request_handler: Option<Arc<CreateRequestHandler>>,
76
    /// Bandwidth pools shared by all channels for global rate limiting.
77
    #[cfg(feature = "relay")]
78
    bw_pools: Option<ChannelBandwidthPools>,
79
    /// Allow outgoing relay channels to all addresses, including local and private
80
    /// addresses.
81
    #[cfg(feature = "relay")]
82
    allow_any_addrs: bool,
83
}
84

            
85
impl<R: Runtime, H: TransportImplHelper> ChanBuilder<R, H>
86
where
87
    R: TlsProvider<H::Stream>,
88
{
89
    /// Construct a new client specific ChanBuilder.
90
19
    pub fn new_client(runtime: R, transport: H) -> Self {
91
19
        let tls_connector = <R as TlsProvider<H::Stream>>::tls_connector(&runtime);
92
19
        ChanBuilder {
93
19
            runtime,
94
19
            transport,
95
19
            tls_connector,
96
19
            #[cfg(feature = "relay")]
97
19
            tls_acceptor: None,
98
19
            #[cfg(feature = "relay")]
99
19
            auth_material: None,
100
19
            #[cfg(feature = "relay")]
101
19
            my_addrs: Vec::new(),
102
19
            #[cfg(feature = "relay")]
103
19
            create_request_handler: None,
104
19
            #[cfg(feature = "relay")]
105
19
            bw_pools: None,
106
19
            #[cfg(feature = "relay")]
107
19
            allow_any_addrs: false,
108
19
        }
109
19
    }
110

            
111
    /// Construct a new relay specific ChanBuilder.
112
    #[cfg(feature = "relay")]
113
    pub fn new_relay(
114
        runtime: R,
115
        transport: H,
116
        auth_material: Arc<RelayChannelAuthMaterial>,
117
        my_addrs: Vec<SocketAddr>,
118
        create_request_handler: Option<Arc<CreateRequestHandler>>,
119
    ) -> crate::Result<Self> {
120
        use tor_error::into_internal;
121
        use tor_rtcompat::tls::TlsAcceptorSettings;
122

            
123
        // Build the TLS acceptor.
124
        let tls_settings = TlsAcceptorSettings::new(auth_material.tls_key_and_cert().clone())
125
            .map_err(into_internal!("Unable to build TLS acceptor setting"))?;
126
        let tls_acceptor = <R as TlsProvider<H::Stream>>::tls_acceptor(&runtime, tls_settings)
127
            .map_err(into_internal!("Unable to build TLS acceptor"))?;
128

            
129
        // Same builder as a client but with auth material and acceptor.
130
        let mut builder = Self::new_client(runtime, transport);
131
        builder.auth_material = Some(auth_material);
132
        builder.tls_acceptor = Some(tls_acceptor);
133
        builder.my_addrs = my_addrs;
134
        builder.create_request_handler = create_request_handler;
135

            
136
        Ok(builder)
137
    }
138

            
139
    /// Set the bandwidth pools used to rate limit all channels.
140
    #[cfg(feature = "relay")]
141
    pub(crate) fn with_bandwidth_pools(mut self, bw_pools: Option<ChannelBandwidthPools>) -> Self {
142
        self.bw_pools = bw_pools;
143
        self
144
    }
145

            
146
    /// Set whether outgoing relay channels may connect to all addresses, including local
147
    /// and private addresses.
148
    #[cfg(feature = "relay")]
149
    pub(crate) fn allow_any_addrs(mut self, allow_any_addrs: bool) -> Self {
150
        self.allow_any_addrs = allow_any_addrs;
151
        self
152
    }
153

            
154
    /// Build a new `ChanBuilder` with the given `auth_material`,
155
    /// cloning everything else.
156
    ///
157
    /// This is needed because some relay keys rotate over time.
158
    #[cfg(feature = "relay")]
159
    pub fn rebuild_with_auth_material(
160
        &self,
161
        auth_material: Arc<RelayChannelAuthMaterial>,
162
    ) -> crate::Result<Self>
163
    where
164
        H: Clone,
165
    {
166
        Self::new_relay(
167
            self.runtime.clone(),
168
            self.transport.clone(),
169
            auth_material,
170
            self.my_addrs.clone(),
171
            self.create_request_handler.as_ref().map(Arc::clone),
172
        )
173
        .map(|b| {
174
            b.with_bandwidth_pools(self.bw_pools.as_ref().map(ChannelBandwidthPools::share))
175
                .allow_any_addrs(self.allow_any_addrs)
176
        })
177
    }
178

            
179
    /// Build a new `ChanBuilder` with the given CREATE* request `handler`,
180
    /// cloning everything else.
181
    ///
182
    /// This is needed so that we can set the handler,
183
    /// which isn't known when the builder is initially created.
184
    #[cfg(feature = "relay")]
185
    pub fn rebuild_with_create_request_handler(
186
        &self,
187
        handler: Arc<CreateRequestHandler>,
188
    ) -> crate::Result<Self>
189
    where
190
        H: Clone,
191
    {
192
        let auth_material = self.auth_material.clone().ok_or_else(|| {
193
            internal!("Trying to set a CREATE* request handler for a non-relay channel builder")
194
        })?;
195

            
196
        Self::new_relay(
197
            self.runtime.clone(),
198
            self.transport.clone(),
199
            auth_material,
200
            self.my_addrs.clone(),
201
            Some(handler),
202
        )
203
        .map(|b| {
204
            b.with_bandwidth_pools(self.bw_pools.as_ref().map(ChannelBandwidthPools::share))
205
                .allow_any_addrs(self.allow_any_addrs)
206
        })
207
    }
208

            
209
    /// Return `stream` rate limited by our bandwidth pools, or unlimited if we have none.
210
    #[cfg(feature = "relay")]
211
    fn rate_limit<S>(&self, stream: S) -> GlobalRateLimitedConn<S> {
212
        match &self.bw_pools {
213
            Some(bw_pools) => bw_pools.rate_limit(stream),
214
            None => GlobalRateLimitedConn::unlimited(stream),
215
        }
216
    }
217

            
218
    /// Return the outbound channel type of this config.
219
    ///
220
    /// The channel type is used when creating outbound channels. Relays always initiate channels
221
    /// as "relay initiator" while client and bridges behave like a "client initiator".
222
    ///
223
    /// Important: The wrong channel type is returned if this is called before `with_identities()`
224
    /// is called.
225
3
    fn outbound_chan_type(&self) -> ChannelType {
226
        #[cfg(feature = "relay")]
227
3
        if self.auth_material.is_some() {
228
            return ChannelType::RelayInitiator;
229
3
        }
230
3
        ChannelType::ClientInitiator
231
3
    }
232
}
233

            
234
#[async_trait]
235
impl<R: Runtime, H: TransportImplHelper> ChannelFactory for ChanBuilder<R, H>
236
where
237
    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
238
    H: Send + Sync,
239
{
240
    #[instrument(skip_all, level = "trace")]
241
    async fn connect_via_transport(
242
        &self,
243
        target: &OwnedChanTarget,
244
        reporter: BootstrapReporter,
245
        memquota: ChannelAccount,
246
    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
247
        use tor_rtcompat::SleepProviderExt;
248

            
249
        // TODO: make this an option.  And make a better value.
250
        let delay = if target.chan_method().is_direct() {
251
            std::time::Duration::new(5, 0)
252
        } else {
253
            std::time::Duration::new(10, 0)
254
        };
255

            
256
        self.runtime
257
            .timeout(delay, self.connect_no_timeout(target, reporter.0, memquota))
258
            .await
259
            .map_err(|_| Error::ChanTimeout {
260
                peer: target.to_logged(),
261
            })?
262
    }
263
}
264

            
265
#[async_trait]
266
impl<R: Runtime, H: TransportImplHelper> IncomingChannelFactory for ChanBuilder<R, H>
267
where
268
    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
269
    H: Send + Sync,
270
{
271
    type Stream = H::Stream;
272

            
273
    #[cfg(feature = "relay")]
274
    async fn accept_from_transport(
275
        &self,
276
        peer: Sensitive<std::net::SocketAddr>,
277
        stream: Self::Stream,
278
        memquota: ChannelAccount,
279
    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
280
        use tor_linkspec::OwnedChanTargetBuilder;
281
        use tor_rtcompat::SleepProviderExt;
282

            
283
        // Note that as we accept a connection, we don't expect any specific identities and so we
284
        // can only build a target from the peer address. This means that the verification process
285
        // will not match the identities seen (if a relay <-> relay channel) to this target which
286
        // is fine as we are a responder.
287
        let target_no_ids = OwnedChanTargetBuilder::default()
288
            .addrs(vec![peer.into_inner()])
289
            .build()
290
            .map_err(|e| internal!("Unable to build chan target from peer sockaddr: {e}"))?;
291

            
292
        // Don't let a peer hold a half-finished handshake open forever.
293
        self.runtime
294
            .timeout(
295
                INCOMING_HANDSHAKE_TIMEOUT,
296
                self.accept_no_timeout(peer, stream, &target_no_ids, memquota),
297
            )
298
            .await
299
            .map_err(|_| Error::ChanTimeout {
300
                peer: target_no_ids.to_logged(),
301
            })?
302
    }
303
}
304

            
305
impl<R: Runtime, H: TransportImplHelper> ChanBuilder<R, H>
306
where
307
    R: tor_rtcompat::TlsProvider<H::Stream> + Send + Sync,
308
    H: Send + Sync,
309
{
310
    /// Perform the work of `accept_from_transport`, but without enforcing a timeout.
311
    ///
312
    /// Return a [`Channel`](tor_proto::channel::Channel) on success.
313
    #[cfg(feature = "relay")]
314
    async fn accept_no_timeout(
315
        &self,
316
        peer: Sensitive<std::net::SocketAddr>,
317
        stream: H::Stream,
318
        target_no_ids: &OwnedChanTarget,
319
        memquota: ChannelAccount,
320
    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
321
        use tor_proto::relay::MaybeVerifiableRelayResponderChannel;
322

            
323
        // Convert into a PeerAddr but keep it sensitive, this can be a client/bridge.
324
        let peer_addr: MaybeSensitive<PeerAddr> =
325
            MaybeSensitive::sensitive(peer.into_inner().into());
326

            
327
        // Helpers: For error mapping.
328
        let map_ioe = |ioe, action| Error::Io {
329
            action,
330
            peer: peer_addr.clone(),
331
            source: ioe,
332
        };
333
        let map_proto = |source, target: &OwnedChanTarget, clock_skew| Error::Proto {
334
            source,
335
            peer: target.to_logged(),
336
            clock_skew,
337
        };
338

            
339
        let tls = self
340
            .tls_acceptor
341
            .as_ref()
342
            .ok_or_else(|| internal!("Accepting connection without TLS acceptor"))?
343
            .negotiate_unvalidated(stream, "ignored")
344
            .await
345
            .map_err(|e| map_ioe(e.into(), "TLS negotiation"))?;
346
        let auth_material = self
347
            .auth_material
348
            .as_ref()
349
            .ok_or_else(|| internal!("Unable to build relay channel without auth material"))?
350
            .clone();
351

            
352
        let our_cert = tls
353
            .own_certificate()
354
            .map_err(|e| map_ioe(e.into(), "TLS Certs"))?
355
            .ok_or_else(|| Error::Internal(internal!("TLS connection without our certificate")))?
356
            .into_owned();
357

            
358
        let create_request_handler = self.create_request_handler.as_ref().ok_or_else(|| {
359
            bad_api_usage!("Can't create a relay channel without a CREATE* request handler")
360
        })?;
361

            
362
        let builder = tor_proto::RelayChannelBuilder::new();
363

            
364
        let unverified = builder
365
            .accept(
366
                Sensitive::new(peer_addr.inner()),
367
                self.my_addrs.clone(),
368
                self.rate_limit(tls),
369
                self.runtime.clone(),
370
                auth_material,
371
                memquota,
372
                Arc::clone(create_request_handler),
373
            )
374
            .handshake(|| self.runtime.wallclock())
375
            .await
376
            .map_err(|e| map_proto(e, target_no_ids, None))?;
377

            
378
        let (chan, reactor) = match unverified {
379
            MaybeVerifiableRelayResponderChannel::Verifiable(c) => {
380
                let clock_skew = c.clock_skew();
381
                let now = self.runtime.wallclock();
382
                c.verify(target_no_ids, &our_cert, Some(now))
383
                    .map_err(|e| map_proto(e, target_no_ids, Some(clock_skew)))?
384
                    .finish()
385
                    .await
386
                    .map_err(|e| map_proto(e, target_no_ids, Some(clock_skew)))?
387
            }
388
            MaybeVerifiableRelayResponderChannel::NonVerifiable(c) => {
389
                c.finish().map_err(|e| map_proto(e, target_no_ids, None))?
390
            }
391
        };
392

            
393
        // Launch a task to run the channel reactor.
394
        self.runtime
395
            .spawn(async {
396
                let _ = reactor.run().await;
397
            })
398
            .map_err(|e| Error::from_spawn("responder channel reactor", e))?;
399

            
400
        Ok(chan)
401
    }
402

            
403
    /// Perform the work of `connect_via_transport`, but without enforcing a timeout.
404
    ///
405
    /// Return a [`Channel`](tor_proto::channel::Channel) on success.
406
    #[instrument(skip_all, level = "trace")]
407
1
    async fn connect_no_timeout(
408
1
        &self,
409
1
        target: &OwnedChanTarget,
410
1
        event_sender: Arc<Mutex<ChanMgrEventSender>>,
411
1
        memquota: ChannelAccount,
412
1
    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
413
        use tor_rtcompat::tls::CertifiedConn;
414

            
415
        {
416
            event_sender.lock().expect("Lock poisoned").record_attempt();
417
        }
418

            
419
        // Before actually doing the connect, we need to validate the channel target based on this
420
        // build outbound channel type. There are restrictions we need to apply.
421
        self.validate_target(target)?;
422

            
423
        // 1a. Negotiate the TCP connection or other stream.
424

            
425
        // The returned PeerAddr is the actual address we are connected to.
426
        let (peer_addr, stream) = self.transport.connect(target).await?;
427
        // The peer could be a bridge/guard or a relay. We have to shield it right away to avoid
428
        // leaking the info in the logs but we also want the info for a relay<-> relay.
429
        let peer_addr = match self.outbound_chan_type() {
430
            ChannelType::ClientInitiator => MaybeSensitive::sensitive(peer_addr),
431
            ChannelType::RelayInitiator => MaybeSensitive::not_sensitive(peer_addr),
432
            _ => return Err(Error::Internal(internal!("Unknown outbound channel type"))),
433
        };
434

            
435
2
        let map_ioe = |action: &'static str| {
436
2
            let peer = peer_addr.clone();
437
            move |ioe: io::Error| Error::Io {
438
                action,
439
                peer,
440
                source: ioe.into(),
441
            }
442
2
        };
443

            
444
        {
445
            // TODO(nickm): At some point, it would be helpful to the
446
            // bootstrapping logic if we could distinguish which
447
            // transport just succeeded.
448
            event_sender
449
                .lock()
450
                .expect("Lock poisoned")
451
                .record_tcp_success();
452
        }
453

            
454
        // 1b. Negotiate TLS.
455

            
456
        let hostname = rand_hostname::random_hostname(&mut rand::rng());
457

            
458
        let tls = self
459
            .tls_connector
460
            .negotiate_unvalidated(stream, hostname.as_str())
461
            .await
462
            .map_err(map_ioe("TLS negotiation"))?;
463

            
464
        let peer_tls_cert = tls
465
            .peer_certificate()
466
            .map_err(map_ioe("TLS certs"))?
467
            .ok_or_else(|| Error::Internal(internal!("TLS connection with no peer certificate")))?
468
            // Note: we could skip this "into_owned" if we computed any necessary digest on the
469
            // certificate earlier.  That would require changing out channel negotiation APIs,
470
            // though, and might not be worth it.
471
            .into_owned();
472

            
473
        {
474
            event_sender
475
                .lock()
476
                .expect("Lock poisoned")
477
                .record_tls_finished();
478
        }
479

            
480
        // Store this so we can log it in case we don't recognize it.
481
        let outbound_chan_type = self.outbound_chan_type();
482
        let chan = match outbound_chan_type {
483
            ChannelType::ClientInitiator => {
484
                self.build_client_channel(
485
                    tls,
486
                    peer_addr,
487
                    target,
488
                    &peer_tls_cert,
489
                    memquota,
490
                    event_sender.clone(),
491
                )
492
                .await?
493
            }
494
            #[cfg(feature = "relay")]
495
            ChannelType::RelayInitiator => {
496
                self.build_relay_channel(
497
                    self.rate_limit(tls),
498
                    peer_addr,
499
                    target,
500
                    &peer_tls_cert,
501
                    memquota,
502
                    event_sender.clone(),
503
                )
504
                .await?
505
            }
506
            _ => {
507
                return Err(Error::Internal(internal!(
508
                    "Unusable channel type for outbound: {outbound_chan_type}",
509
                )));
510
            }
511
        };
512

            
513
        event_sender
514
            .lock()
515
            .expect("Lock poisoned")
516
            .record_handshake_done();
517

            
518
        Ok(chan)
519
1
    }
520

            
521
    /// Validate the given `target` as we (a relay) are attempting to connect to another relay.
522
    #[cfg(feature = "relay")]
523
    fn validate_target_as_relay<CT>(&self, target: &CT) -> crate::Result<()>
524
    where
525
        CT: ChanTarget,
526
    {
527
        use tor_linkspec::HasRelayIds;
528

            
529
        // Make sure we don't attempt to use a PT method for this relay channel.
530
        if !target.chan_method().is_direct() {
531
            // Return an internal error because the circuit reactor asking us to use a PT is a code
532
            // flow issue, not a protocol violation.
533
            return Err(Error::UnusableTarget(tor_error::bad_api_usage!(
534
                "Relays don't support outbound PT channels"
535
            )));
536
        }
537

            
538
        // Make sure that all addresses are allowed for an EXTEND. For instance, connecting to a
539
        // local/private network for security reasons as a it could lead to network
540
        // scanning by measuring latency between successful connect() and failures.
541
        //
542
        // If no addresses, it returns true and thus no error.
543
        if !self.allow_any_addrs && !target.all_addrs_allowed_for_outgoing_channels() {
544
            return Err(Error::Proto {
545
                source: tor_proto::Error::ChanProto(
546
                    "Target address is not allowed for outgoing channels".into(),
547
                ),
548
                peer: target.to_owned().into(),
549
                clock_skew: None,
550
            });
551
        }
552

            
553
        // Connecting to a relay as a relay without key material will fail. This should never
554
        // happen hence the internal error.
555
        let Some(auth_material) = &self.auth_material else {
556
            return Err(Error::Internal(tor_error::bad_api_usage!(
557
                "Relay initiating a channel without key auth material"
558
            )));
559
        };
560

            
561
        // Any of our identities match the given target, we are connecting to ourselves, refuse.
562
        if auth_material.has_any_relay_id_from(target) {
563
            Err(Error::Proto {
564
                source: tor_proto::Error::ChanProto("Refusing to build channel to ourself".into()),
565
                peer: target.to_owned().into(),
566
                clock_skew: None,
567
            })
568
        } else {
569
            Ok(())
570
        }
571
    }
572

            
573
    /// Validate the given target as in if it is fine to connect to it.
574
    ///
575
    ///There are several rules to follow based on the channel outbound type.
576
1
    fn validate_target<CT>(&self, target: &CT) -> crate::Result<()>
577
1
    where
578
1
        CT: ChanTarget,
579
    {
580
        // Make sure that each address has a valid port.
581
1
        if !target.has_all_nonzero_port() {
582
            return Err(Error::Proto {
583
                source: tor_proto::Error::ChanProto("Target address port is invalid".into()),
584
                peer: target.to_owned().into(),
585
                clock_skew: None,
586
            });
587
1
        }
588

            
589
        // Make sure no target address is ourself including the port. A relay is allowed to connect
590
        // to its IP address but on a different port. We also want to avoid a client bridge to
591
        // connect back to itself.
592
        #[cfg(feature = "relay")]
593
1
        for addr in target.addrs() {
594
1
            if self.my_addrs.contains(&addr) {
595
                return Err(Error::Proto {
596
                    source: tor_proto::Error::ChanProto("Target address is ours".into()),
597
                    peer: target.to_owned().into(),
598
                    clock_skew: None,
599
                });
600
1
            }
601
        }
602

            
603
1
        let chan_type = self.outbound_chan_type();
604
1
        match chan_type {
605
            // This is a client connecting to a relay.
606
1
            ChannelType::ClientInitiator => Ok(()),
607
            // This is a relay connecting to a relay.
608
            #[cfg(feature = "relay")]
609
            ChannelType::RelayInitiator => self.validate_target_as_relay(target),
610
            // ChannelType is non_exhaustive but also we only cover outbound channels.
611
            _ => Err(Error::UnusableTarget(tor_error::bad_api_usage!(
612
                "Channel type can't be used as a target: {chan_type}"
613
            ))),
614
        }
615
1
    }
616

            
617
    /// Build a client channel (always initiator).
618
    ///
619
    /// This spawns the Reactor and return the [`tor_proto::channel::Channel`].
620
1
    async fn build_client_channel<T>(
621
1
        &self,
622
1
        tls: T,
623
1
        peer_addr: MaybeSensitive<PeerAddr>,
624
1
        target: &OwnedChanTarget,
625
1
        peer_tls_cert: &[u8],
626
1
        memquota: ChannelAccount,
627
1
        event_sender: Arc<Mutex<ChanMgrEventSender>>,
628
1
    ) -> crate::Result<Arc<tor_proto::channel::Channel>>
629
1
    where
630
1
        T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
631
1
    {
632
        // Helper to map protocol level error.
633
        //
634
        // We are logging the `target` here as these protocol error happens during the handshake
635
        // and we need to log the identities that are being tried but it will honor safe logging
636
        // for the relay <-> relay case which is not ideal but a tradeoff in complexity.
637
        let map_proto = |source, target: &OwnedChanTarget, clock_skew| Error::Proto {
638
            source,
639
            peer: target.to_logged(),
640
            clock_skew,
641
        };
642

            
643
1
        let now = self.runtime.wallclock();
644

            
645
        // Get the client specific channel builder.
646
1
        let mut builder = tor_proto::ClientChannelBuilder::new();
647
1
        builder.set_declared_method(target.chan_method());
648

            
649
1
        let unverified = builder
650
1
            .launch(
651
1
                tls,
652
1
                self.runtime.clone(), /* TODO provide ZST SleepProvider instead */
653
1
                memquota,
654
1
            )
655
1
            .connect(|| self.runtime.wallclock())
656
1
            .await
657
            .map_err(|e| Error::from_proto_no_skew(e, target))?;
658

            
659
1
        let clock_skew = unverified.clock_skew();
660
1
        let (chan, reactor) = unverified
661
1
            .verify(target, peer_tls_cert, Some(now))
662
            .map_err(|source| match &source {
663
                tor_proto::Error::HandshakeCertsExpired { .. } => {
664
                    event_sender
665
                        .lock()
666
                        .expect("Lock poisoned")
667
                        .record_handshake_done_with_skewed_clock();
668
                    map_proto(source, target, Some(clock_skew))
669
                }
670
                _ => Error::from_proto_no_skew(source, target),
671
            })?
672
1
            .finish(peer_addr)
673
1
            .await
674
            .map_err(|e| map_proto(e, target, Some(clock_skew)))?;
675

            
676
        // Launch a task to run the channel reactor.
677
1
        self.runtime
678
1
            .spawn(async {
679
1
                let _ = reactor.run().await;
680
1
            })
681
            .map_err(|e| Error::from_spawn("client channel reactor", e))?;
682
1
        Ok(chan)
683
1
    }
684

            
685
    /// Build a relay initiator channel.
686
    ///
687
    /// This spawns the Reactor and return the [`tor_proto::channel::Channel`].
688
    #[cfg(feature = "relay")]
689
    async fn build_relay_channel<T>(
690
        &self,
691
        tls: T,
692
        peer_addr: MaybeSensitive<PeerAddr>,
693
        target: &OwnedChanTarget,
694
        peer_tls_cert: &[u8],
695
        memquota: ChannelAccount,
696
        event_sender: Arc<Mutex<ChanMgrEventSender>>,
697
    ) -> crate::Result<Arc<tor_proto::channel::Channel>>
698
    where
699
        T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
700
    {
701
        let builder = tor_proto::RelayChannelBuilder::new();
702
        let auth_material = self
703
            .auth_material
704
            .as_ref()
705
            .ok_or_else(|| internal!("Unable to build relay channel without auth material"))?
706
            .clone();
707

            
708
        let create_request_handler = self.create_request_handler.as_ref().ok_or_else(|| {
709
            bad_api_usage!("Can't create a relay channel without a CREATE* request handler")
710
        })?;
711

            
712
        let unverified = builder
713
            .launch(
714
                tls,
715
                self.runtime.clone(), /* TODO provide ZST SleepProvider instead */
716
                auth_material,
717
                self.my_addrs.clone(),
718
                target,
719
                memquota,
720
                Arc::clone(create_request_handler),
721
            )
722
            .connect(|| self.runtime.wallclock())
723
            .await
724
            .map_err(|e| Error::from_proto_no_skew(e, target))?;
725

            
726
        let now = self.runtime.wallclock();
727
        let clock_skew = unverified.clock_skew();
728
        let (chan, reactor) = unverified
729
            .verify(target, peer_tls_cert, Some(now))
730
            .map_err(|source| match &source {
731
                tor_proto::Error::HandshakeCertsExpired { .. } => {
732
                    event_sender
733
                        .lock()
734
                        .expect("Lock poisoned")
735
                        .record_handshake_done_with_skewed_clock();
736
                    Error::Proto {
737
                        source,
738
                        peer: target.to_logged(),
739
                        clock_skew: Some(clock_skew),
740
                    }
741
                }
742
                _ => Error::from_proto_no_skew(source, target),
743
            })?
744
            // Peer address is not sensitive as this is a relay<->relay connection.
745
            .finish(peer_addr.inner())
746
            .await
747
            .map_err(|source| Error::Proto {
748
                source,
749
                peer: target.to_logged(),
750
                clock_skew: Some(clock_skew),
751
            })?;
752

            
753
        // Launch a task to run the channel reactor.
754
        self.runtime
755
            .spawn(async {
756
                let _ = reactor.run().await;
757
            })
758
            .map_err(|e| Error::from_spawn("relay channel reactor", e))?;
759

            
760
        Ok(chan)
761
    }
762
}
763

            
764
impl crate::mgr::AbstractChannel for tor_proto::channel::Channel {
765
    fn is_canonical(&self) -> bool {
766
        self.is_canonical()
767
    }
768
    fn is_canonical_to_peer(&self) -> bool {
769
        self.is_canonical_to_peer()
770
    }
771
    fn peer_matches_chan_method(&self, method: &tor_linkspec::ChannelMethod) -> bool {
772
        self.peer_matches_chan_method(method)
773
    }
774
    fn age(&self) -> Duration {
775
        self.age()
776
    }
777
1
    fn is_usable(&self) -> bool {
778
1
        !self.is_closing()
779
1
    }
780
1
    fn duration_unused(&self) -> Option<Duration> {
781
1
        self.duration_unused()
782
1
    }
783
54
    fn reparameterize(
784
54
        &self,
785
54
        updates: Arc<ChannelPaddingInstructionsUpdates>,
786
54
    ) -> tor_proto::Result<()> {
787
54
        tor_proto::channel::Channel::reparameterize(self, updates)
788
54
    }
789
    fn reparameterize_kist(&self, kist_params: KistParams) -> tor_proto::Result<()> {
790
        tor_proto::channel::Channel::reparameterize_kist(self, kist_params)
791
    }
792
18
    fn engage_padding_activities(&self) {
793
18
        tor_proto::channel::Channel::engage_padding_activities(self);
794
18
    }
795
}
796

            
797
#[cfg(test)]
798
mod test {
799
    // @@ begin test lint list maintained by maint/add_warning @@
800
    #![allow(clippy::bool_assert_comparison)]
801
    #![allow(clippy::clone_on_copy)]
802
    #![allow(clippy::dbg_macro)]
803
    #![allow(clippy::mixed_attributes_style)]
804
    #![allow(clippy::print_stderr)]
805
    #![allow(clippy::print_stdout)]
806
    #![allow(clippy::single_char_pattern)]
807
    #![allow(clippy::unwrap_used)]
808
    #![allow(clippy::unchecked_time_subtraction)]
809
    #![allow(clippy::useless_vec)]
810
    #![allow(clippy::needless_pass_by_value)]
811
    #![allow(clippy::string_slice)] // See arti#2571
812
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
813
    use super::*;
814
    use crate::{
815
        Result,
816
        mgr::{AbstractChannel, AbstractChannelFactory},
817
    };
818
    use futures::StreamExt as _;
819
    use std::net::SocketAddr;
820
    use std::time::{Duration, SystemTime};
821
    use tor_linkspec::{ChannelMethod, HasRelayIds, RelayIdType};
822
    use tor_llcrypto::pk::ed25519::Ed25519Identity;
823
    use tor_llcrypto::pk::rsa::RsaIdentity;
824
    use tor_proto::channel::Channel;
825
    use tor_proto::memquota::{ChannelAccount, SpecificAccount as _};
826
    use tor_rtcompat::{NetStreamListener, test_with_one_runtime};
827
    use tor_rtmock::{io::LocalStream, net::MockNetwork};
828

            
829
    #[allow(deprecated)] // TODO #1885
830
    use tor_rtmock::MockSleepRuntime;
831

            
832
    // Make sure that the builder can build a real channel.  To test
833
    // this out, we set up a listener that pretends to have the right
834
    // IP, fake the current time, and use a canned response from
835
    // [`testing::msgs`] crate.
836
    #[test]
837
    fn build_ok() -> Result<()> {
838
        use crate::testing::msgs;
839
        let orport: SocketAddr = msgs::ADDR.parse().unwrap();
840
        let ed: Ed25519Identity = msgs::ED_ID.into();
841
        let rsa: RsaIdentity = msgs::RSA_ID.into();
842
        let client_addr = "192.0.2.17".parse().unwrap();
843
        let tls_cert = msgs::X509_CERT.into();
844
        let target = OwnedChanTarget::builder()
845
            .addrs(vec![orport])
846
            .method(ChannelMethod::Direct(vec![orport]))
847
            .ed_identity(ed)
848
            .rsa_identity(rsa)
849
            .build()
850
            .unwrap();
851
        let now = SystemTime::UNIX_EPOCH + Duration::new(msgs::NOW, 0);
852

            
853
        test_with_one_runtime!(|rt| async move {
854
            // Stub out the internet so that this connection can work.
855
            let network = MockNetwork::new();
856

            
857
            // Set up a client runtime with a given IP
858
            let client_rt = network
859
                .builder()
860
                .add_address(client_addr)
861
                .runtime(rt.clone());
862
            // Mock the current time too
863
            #[allow(deprecated)] // TODO #1885
864
            let client_rt = MockSleepRuntime::new(client_rt);
865

            
866
            // Set up a relay runtime with a different IP
867
            let relay_rt = network
868
                .builder()
869
                .add_address(orport.ip())
870
                .runtime(rt.clone());
871

            
872
            // open a fake TLS listener and be ready to handle a request.
873
            let lis = relay_rt.mock_net().listen_tls(&orport, tls_cert).unwrap();
874

            
875
            // Tell the client to believe in a different timestamp.
876
            client_rt.jump_to(now);
877

            
878
            // Create the channel builder that we want to test.
879
            let transport = crate::transport::DefaultTransport::new(client_rt.clone(), None);
880
            let builder = ChanBuilder::new_client(client_rt, transport);
881

            
882
            let (r1, r2): (Result<Arc<Channel>>, Result<LocalStream>) = futures::join!(
883
                async {
884
                    // client-side: build a channel!
885
                    builder
886
                        .build_channel(
887
                            &target,
888
                            BootstrapReporter::fake(),
889
                            ChannelAccount::new_noop(),
890
                        )
891
                        .await
892
                },
893
                async {
894
                    // relay-side: accept the channel
895
                    // (and pretend to know what we're doing).
896
                    let (mut con, addr) = lis
897
                        .incoming()
898
                        .next()
899
                        .await
900
                        .expect("Closed?")
901
                        .expect("accept failed");
902
                    assert_eq!(client_addr, addr.ip());
903
                    crate::testing::answer_channel_req(&mut con)
904
                        .await
905
                        .expect("answer failed");
906
                    Ok(con)
907
                }
908
            );
909

            
910
            let chan = r1.unwrap();
911
            assert_eq!(chan.identity(RelayIdType::Ed25519), Some((&ed).into()));
912
            assert!(chan.is_usable());
913
            // In theory, time could pass here, so we can't just use
914
            // "assert_eq!(dur_unused, dur_unused2)".
915
            let dur_unused = Channel::duration_unused(&chan);
916
            let dur_unused_2 = AbstractChannel::duration_unused(chan.as_ref());
917
            let dur_unused_3 = Channel::duration_unused(&chan);
918
            assert!(dur_unused.unwrap() <= dur_unused_2.unwrap());
919
            assert!(dur_unused_2.unwrap() <= dur_unused_3.unwrap());
920

            
921
            r2.unwrap();
922
            Ok(())
923
        })
924
    }
925

            
926
    // TODO: Write tests for timeout logic, once there is smarter logic.
927
}