1
//! Relay responder channel.
2
//!
3
//! Code related to the relay channel opened as a responder. The handshake code is responsible for
4
//! creating an [`MaybeVerifiableRelayResponderChannel`] when accepting an inbound connection.
5
//!
6
//! It can then be used to get a fully working channel.
7

            
8
use digest::Digest;
9
use futures::{AsyncRead, AsyncWrite};
10
use safelog::{MaybeSensitive, Sensitive};
11
use std::{net::IpAddr, ops::Deref, sync::Arc};
12
use tracing::instrument;
13

            
14
use tor_cell::chancell::msg;
15
use tor_linkspec::{OwnedChanTarget, RelayIds};
16
use tor_llcrypto as ll;
17
use tor_rtcompat::{CertifiedConn, CoarseTimeProvider, SleepProvider, StreamOps};
18

            
19
use crate::{
20
    ClockSkew, Error, RelayIdentities, Result,
21
    channel::{
22
        Channel, Reactor,
23
        handshake::{UnverifiedChannel, VerifiedChannel},
24
    },
25
    peer::{PeerAddr, PeerInfo},
26
    relay::channel::ChannelAuthenticationData,
27
};
28

            
29
/// An enum combining both the possibility of a verifable (relay) or non verifiable channel
30
/// (client/bridge).
31
#[allow(clippy::exhaustive_enums)]
32
pub enum MaybeVerifiableRelayResponderChannel<
33
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
34
    S: CoarseTimeProvider + SleepProvider,
35
> {
36
    /// Verifiable channel (relay).
37
    Verifiable(UnverifiedResponderRelayChannel<T, S>),
38
    /// Non verifiable channel (client/bridge).
39
    NonVerifiable(NonVerifiableResponderRelayChannel<T, S>),
40
}
41

            
42
/// A channel that can NOT be verified. This is solely either a client or bridge on the other end.
43
///
44
/// This can only be built if no [`msg::Authenticate`] was ever received.
45
pub struct NonVerifiableResponderRelayChannel<
46
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
47
    S: CoarseTimeProvider + SleepProvider,
48
> {
49
    /// The common unverified channel that both client and relays use.
50
    pub(crate) inner: UnverifiedChannel<T, S>,
51
    /// The netinfo cell received from the initiator.
52
    pub(crate) netinfo_cell: msg::Netinfo,
53
    /// Our advertised addresses.
54
    pub(crate) my_addrs: Vec<IpAddr>,
55
    /// The peer address which is sensitive considering it is either client or bridge.
56
    pub(crate) peer_addr: Sensitive<PeerAddr>,
57
}
58

            
59
/// A verifiable relay responder channel that is currently unverified. This can only be a relay on
60
/// the other end.
61
///
62
/// The verify() and then finish() functions are to be used to get a final Channel/Reactor.
63
pub struct UnverifiedResponderRelayChannel<
64
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
65
    S: CoarseTimeProvider + SleepProvider,
66
> {
67
    /// The common unverified channel that both client and relays use.
68
    pub(crate) inner: UnverifiedChannel<T, S>,
69
    /// AUTHENTICATE cell received from the initiator.
70
    pub(crate) auth_cell: msg::Authenticate,
71
    /// The netinfo cell received from the initiator.
72
    pub(crate) netinfo_cell: msg::Netinfo,
73
    /// Our identity keys needed for authentication.
74
    pub(crate) identities: Arc<RelayIdentities>,
75
    /// Our advertised addresses.
76
    pub(crate) my_addrs: Vec<IpAddr>,
77
    /// The peer address which we know is a relay.
78
    pub(crate) peer_addr: PeerAddr,
79
}
80

            
81
/// A verified relay responder channel.
82
///
83
/// Only finish() remains to transform this into a fully usable [`crate::channel::Channel`] and
84
/// [`crate::channel::Reactor`].
85
pub struct VerifiedResponderRelayChannel<
86
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
87
    S: CoarseTimeProvider + SleepProvider,
88
> {
89
    /// The common unverified channel that both client and relays use.
90
    inner: VerifiedChannel<T, S>,
91
    /// The netinfo cell that we got from the relay. Canonicity decision.
92
    netinfo_cell: msg::Netinfo,
93
    /// Our advertised addresses.
94
    my_addrs: Vec<IpAddr>,
95
    /// The peer address which we know is a relay.
96
    peer_addr: PeerAddr,
97
}
98

            
99
impl<T, S> UnverifiedResponderRelayChannel<T, S>
100
where
101
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
102
    S: CoarseTimeProvider + SleepProvider,
103
{
104
    /// Validate the certificates and keys in the relay's handshake.
105
    ///
106
    /// 'peer' is the peer that we want to make sure we're connecting to.
107
    ///
108
    /// 'peer_cert' is the x.509 certificate that the peer presented during its TLS handshake
109
    /// (ServerHello).
110
    ///
111
    /// 'our_cert' is the x.509 certificate that we presented during the TLS handshake.
112
    ///
113
    /// 'now' is the time at which to check that certificates are valid.  `None` means to use the
114
    /// current time. It can be used for testing to override the current view of the time.
115
    ///
116
    /// This is a separate function because it's likely to be somewhat CPU-intensive.
117
    #[instrument(skip_all, level = "trace")]
118
    pub fn verify(
119
        self,
120
        peer: &OwnedChanTarget,
121
        peer_cert: &[u8],
122
        our_cert: &[u8],
123
        now: Option<std::time::SystemTime>,
124
    ) -> Result<VerifiedResponderRelayChannel<T, S>> {
125
        // Get these object out as we consume "self" in the inner check().
126
        let identities = self.identities;
127
        let netinfo_cell = self.netinfo_cell;
128
        let initiator_auth_cell = self.auth_cell;
129
        let my_addrs = self.my_addrs;
130

            
131
        // Verify our inner channel and then proceed to handle the authentication challenge if any.
132
        let mut verified = self.inner.check(peer, peer_cert, now)?;
133
        let our_cert_digest = ll::d::Sha256::digest(our_cert).into();
134

            
135
        // By building the ChannelAuthenticationData, we are certain that the authentication type
136
        // of the initiator is supported by us.
137
        let our_auth_cell = ChannelAuthenticationData::build(
138
            None,
139
            &identities,
140
            &mut verified,
141
            Some(our_cert_digest),
142
        )?
143
        .into_authenticate(verified.framed_tls.deref(), &identities.link_sign_kp)?;
144

            
145
        // CRITICAL: This if is what authenticates a channel on the responder side. We compare
146
        // what we expected to what we received.
147
        if initiator_auth_cell != our_auth_cell {
148
            return Err(Error::ChanProto(
149
                "AUTHENTICATE was unexpected. Failing authentication".into(),
150
            ));
151
        }
152
        // This part is very important as we now flag that we are verified and thus authenticated.
153
        //
154
        // At this point, the underlying cell handler is in the Handshake state. Setting the
155
        // channel type here as authenticated means that once the handler transition to the Open
156
        // state, it will carry this authenticated flag leading to the message filter of the
157
        // channel codec to adapt its restricted message sets (meaning R2R only).
158
        //
159
        // After this call, it is considered a R2R channel.
160
        verified.set_authenticated()?;
161

            
162
        Ok(VerifiedResponderRelayChannel {
163
            inner: verified,
164
            netinfo_cell,
165
            my_addrs,
166
            peer_addr: self.peer_addr,
167
        })
168
    }
169

            
170
    /// Return the clock skew of this channel.
171
    pub fn clock_skew(&self) -> ClockSkew {
172
        self.inner.clock_skew
173
    }
174
}
175

            
176
impl<T, S> VerifiedResponderRelayChannel<T, S>
177
where
178
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
179
    S: CoarseTimeProvider + SleepProvider,
180
{
181
    /// Finish the handhshake which will create an open channel and reactor.
182
    ///
183
    /// The resulting channel is considered, by Tor protocol standard, an authenticated relay
184
    /// channel on which circuits can be opened.
185
    #[instrument(skip_all, level = "trace")]
186
    pub async fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)> {
187
        // Relay<->Relay channels are NOT sensitive as we need their info in the log.
188
        let peer_info =
189
            MaybeSensitive::not_sensitive(PeerInfo::new(self.peer_addr, self.inner.relay_ids()?));
190
        self.inner
191
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info)
192
            .await
193
    }
194
}
195

            
196
impl<T, S> NonVerifiableResponderRelayChannel<T, S>
197
where
198
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
199
    S: CoarseTimeProvider + SleepProvider,
200
{
201
    /// Finish the handhshake which will create an open channel and reactor.
202
    ///
203
    /// The resulting channel is considered, by Tor protocol standard, a client/bridge relay
204
    /// channel meaning not authenticated. Circuit can be opened on it.
205
    #[instrument(skip_all, level = "trace")]
206
    pub fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)> {
207
        // This is either a client or a bridge so very sensitive.
208
        let peer_info = MaybeSensitive::sensitive(PeerInfo::new(
209
            self.peer_addr.into_inner(),
210
            RelayIds::empty(),
211
        ));
212
        // Non verifiable responder channel, we simply finalize our underlying channel and we are
213
        // done. We are connected to a client or bridge.
214
        self.inner
215
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info)
216
    }
217
}