1
//! Relay initiator channel.
2
//!
3
//! Code only related to a relay channel opened as an initiator. The handshake code is responsible
4
//! for creating an [`UnverifiedInitiatorRelayChannel`] when connecting to another relay in order
5
//! to build a tor channel.
6
//!
7
//! The [`UnverifiedInitiatorRelayChannel::verify`] function needs to be called to verify the
8
//! underlying channel and build a [`VerifiedInitiatorRelayChannel`] channel which needs to be
9
//! finished with [`VerifiedInitiatorRelayChannel::finish`] to get a Channel/Reactor.
10
//!
11
//! Note that channel cells are sent in the handshake upon connection. And then in the finish()
12
//! process. The verify can be CPU intensive and thus in its own function.
13

            
14
use futures::{AsyncRead, AsyncWrite, SinkExt};
15
use safelog::MaybeSensitive;
16
use std::{net::IpAddr, ops::Deref, sync::Arc};
17
use tracing::trace;
18

            
19
use tor_cell::chancell::msg;
20
use tor_linkspec::OwnedChanTarget;
21
use tor_rtcompat::{CertifiedConn, CoarseTimeProvider, SleepProvider, StreamOps};
22

            
23
use crate::{
24
    ClockSkew, RelayIdentities, Result,
25
    channel::{
26
        Channel, Reactor,
27
        handshake::{UnverifiedChannel, VerifiedChannel},
28
    },
29
    peer::{PeerAddr, PeerInfo},
30
    relay::channel::ChannelAuthenticationData,
31
};
32

            
33
/// An unverified relay initiator channel.
34
///
35
/// This is built by the [`crate::relay::channel::handshake::RelayInitiatorHandshake`] upon a
36
/// connect. It has everything needed to verify in order to get a verified channel.
37
pub struct UnverifiedInitiatorRelayChannel<
38
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
39
    S: CoarseTimeProvider + SleepProvider,
40
> {
41
    /// The common unverified channel that both client and relays use.
42
    pub(crate) inner: UnverifiedChannel<T, S>,
43
    /// AUTH_CHALLENGE cell received from the responder.
44
    pub(crate) auth_challenge_cell: msg::AuthChallenge,
45
    /// The netinfo cell received from the responder.
46
    pub(crate) netinfo_cell: msg::Netinfo,
47
    /// Our identity keys needed for authentication.
48
    pub(crate) identities: Arc<RelayIdentities>,
49
    /// Our advertised IP addresses for the final NETINFO
50
    pub(crate) my_addrs: Vec<IpAddr>,
51
}
52

            
53
impl<T, S> UnverifiedInitiatorRelayChannel<T, S>
54
where
55
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
56
    S: CoarseTimeProvider + SleepProvider,
57
{
58
    /// Validate the certificates and keys in the relay's handshake. As an initiator, we always
59
    /// authenticate no matter what.
60
    ///
61
    /// 'peer' is the peer that we want to make sure we're connecting to.
62
    ///
63
    /// 'peer_cert' is the x.509 certificate that the peer presented during its TLS handshake
64
    /// (ServerHello).
65
    ///
66
    /// 'now' is the time at which to check that certificates are valid.  `None` means to use the
67
    /// current time. It can be used for testing to override the current view of the time.
68
    ///
69
    /// This is a separate function because it's likely to be somewhat CPU-intensive.
70
    pub fn verify(
71
        self,
72
        peer: &OwnedChanTarget,
73
        peer_cert: &[u8],
74
        now: Option<std::time::SystemTime>,
75
    ) -> Result<VerifiedInitiatorRelayChannel<T, S>> {
76
        // Get these object out as we consume "self" in the inner check().
77
        let auth_challenge_cell = self.auth_challenge_cell;
78
        let identities = self.identities;
79
        let my_addrs = self.my_addrs;
80
        let netinfo_cell = self.netinfo_cell;
81

            
82
        // Verify our inner channel and then proceed to handle the authentication challenge if any.
83
        let mut verified = self.inner.check(peer, peer_cert, now)?;
84

            
85
        // By building the ChannelAuthenticationData, we are certain that the authentication
86
        // type requested by the responder is supported by us.
87
        let auth_cell = ChannelAuthenticationData::build(
88
            Some(&auth_challenge_cell),
89
            &identities,
90
            &mut verified,
91
            None,
92
        )?
93
        .into_authenticate(verified.framed_tls.deref(), &identities.link_sign_kp)?;
94

            
95
        // This part is very important as we now flag that we are authenticated. The responder
96
        // checks the received AUTHENTICATE and the initiator just needs to verify the channel.
97
        //
98
        // At this point, the underlying cell handler is in the Handshake state. Setting the
99
        // channel type here as authenticated means that once the handler transition to the Open
100
        // state, it will carry this authenticated flag leading to the message filter of the
101
        // channel codec to adapt its restricted message sets (meaning R2R only).
102
        //
103
        // After this call, it is considered a R2R channel.
104
        verified.set_authenticated()?;
105

            
106
        Ok(VerifiedInitiatorRelayChannel {
107
            inner: verified,
108
            identities,
109
            netinfo_cell,
110
            auth_cell,
111
            my_addrs,
112
        })
113
    }
114

            
115
    /// Return the clock skew of this channel.
116
    pub fn clock_skew(&self) -> ClockSkew {
117
        self.inner.clock_skew
118
    }
119
}
120

            
121
/// A verified relay initiator channel.
122
///
123
/// Holding this object means the channel TLS layer has been verified against the received CERTS
124
/// cell and we now believe that we are talking to the right relay end point.
125
///
126
/// The finish() function needs to be called in order to finalize this channel into a generic
127
/// Channel/Reactor.
128
pub struct VerifiedInitiatorRelayChannel<
129
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
130
    S: CoarseTimeProvider + SleepProvider,
131
> {
132
    /// The common unverified channel that both client and relays use.
133
    inner: VerifiedChannel<T, S>,
134
    /// Relay identities.
135
    identities: Arc<RelayIdentities>,
136
    /// The netinfo cell that we got from the relay.
137
    netinfo_cell: msg::Netinfo,
138
    /// The AUTHENTICATE cell built during verification process.
139
    auth_cell: msg::Authenticate,
140
    /// Our advertised IP addresses.
141
    my_addrs: Vec<IpAddr>,
142
}
143

            
144
impl<T, S> VerifiedInitiatorRelayChannel<T, S>
145
where
146
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
147
    S: CoarseTimeProvider + SleepProvider,
148
{
149
    /// Send our [`msg::Certs`], [`msg::Authenticate`] and [`msg::Netinfo`] to the relay to finish
150
    /// the handshake, which will create an open channel and reactor.
151
    ///
152
    /// The resulting channel is considered, by Tor protocol standard, an authenticated relay
153
    /// channel on which circuits can be opened.
154
    pub async fn finish(mut self, peer_addr: PeerAddr) -> Result<(Arc<Channel>, Reactor<S>)> {
155
        // Send CERTS, AUTHENTICATE, NETINFO
156
        let certs = super::build_certs_cell(&self.identities, /* is_responder */ false);
157
        trace!(channel_id = %self.inner.unique_id, "Sending CERTS as initiator cell.");
158
        self.inner.framed_tls.send(certs.into()).await?;
159
        trace!(channel_id = %self.inner.unique_id, "Sending AUTHENTICATE as initiator cell.");
160
        self.inner.framed_tls.send(self.auth_cell.into()).await?;
161

            
162
        // Send our NETINFO cell. This will indicate the end of the handshake.
163
        let netinfo = super::build_netinfo_cell(
164
            peer_addr.netinfo_addr(),
165
            self.my_addrs.clone(),
166
            &self.inner.sleep_prov,
167
        )?;
168
        trace!(channel_id = %self.inner.unique_id, "Sending NETINFO as initiator cell.");
169
        self.inner.framed_tls.send(netinfo.into()).await?;
170

            
171
        // Relay only initiate to another relay so NOT sensitive.
172
        let peer_info =
173
            MaybeSensitive::not_sensitive(PeerInfo::new(peer_addr, self.inner.relay_ids()?));
174

            
175
        // Get a Channel and a Reactor.
176
        self.inner
177
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info)
178
            .await
179
    }
180
}