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 subtle::ConstantTimeEq;
13
use tracing::instrument;
14

            
15
use tor_cell::chancell::msg;
16
use tor_linkspec::{HasRelayIds, OwnedChanTarget, RelayIds};
17
use tor_llcrypto as ll;
18
use tor_rtcompat::{CertifiedConn, CoarseTimeProvider, SleepProvider, StreamOps};
19
use web_time_compat::{SystemTime, SystemTimeExt};
20

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

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

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

            
61
/// A verifiable relay responder channel that is currently unverified. This can only be a relay on
62
/// the other end.
63
///
64
/// The verify() and then finish() functions are to be used to get a final Channel/Reactor.
65
pub struct UnverifiedResponderRelayChannel<
66
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
67
    S: CoarseTimeProvider + SleepProvider,
68
> {
69
    /// The common unverified channel that both client and relays use.
70
    pub(crate) inner: UnverifiedChannel<T, S>,
71
    /// AUTHENTICATE cell received from the initiator.
72
    pub(crate) auth_cell: msg::Authenticate,
73
    /// The netinfo cell received from the initiator.
74
    pub(crate) netinfo_cell: msg::Netinfo,
75
    /// The [`msg::Certs`] cell received from the initiator.
76
    pub(crate) certs_cell: msg::Certs,
77
    /// Our authentication key material.
78
    pub(crate) auth_material: Arc<RelayChannelAuthMaterial>,
79
    /// Our advertised addresses.
80
    pub(crate) my_addrs: Vec<IpAddr>,
81
    /// The peer address which we know is a relay.
82
    pub(crate) peer_addr: PeerAddr,
83
    /// The CLOG digest.
84
    pub(crate) clog_digest: AuthLogDigest,
85
    /// The SLOG digest.
86
    pub(crate) slog_digest: AuthLogDigest,
87
}
88

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

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

            
136
        let now = now.unwrap_or_else(SystemTime::get);
137

            
138
        // We are a relay responder. We have received a CERTS cell and we need to verify these
139
        // certs:
140
        //
141
        //   Relay Identities:
142
        //      IDENTITY_V_SIGNING_CERT (CertType 4)
143
        //      RSA_ID_X509             (CertType 2)
144
        //      RSA_ID_V_IDENTITY       (CertType 7)
145
        //
146
        //   Connection Cert:
147
        //      SIGNING_V_LINK_AUTH     (CertType 6)
148
        //
149
        // Validating the relay identities first so we can make sure we are talking to the relay
150
        // (peer) we wanted. Then, check the AUTHENTICATE cell.
151
        //
152
        // The end result is a verified channel (not authenticated yet) which guarantee that we are
153
        // talking to the right relay that we wanted. We validate so we can prove these:
154
        //
155
        // - IDENTITY_V_SIGNING proves that KP_relaysign_ed speaks on behalf of KP_relayid_ed
156
        // - SIGNING_V_LINK_AUTH proves that KP_link_ed speaks on behalf of KP_relaysign_ed
157
        // - The AUTHENTICATE cell proves that the TLS session's key material is known by the
158
        //   owner of KP_link_ed
159
        // - Therefore, we have a chain from:
160
        //   KS_relayid_ed → KP_relaysign_ed → KP_link_ed → AUTHENTICATE cell → the channel itself.
161
        //
162
        // As for legacy certs, they prove nothing but we can extract keys:
163
        //
164
        // - RSA_ID_X509 proves nothing; we just extract its subject key as KP_relayid_rsa.
165
        // - RSA_ID_V_IDENTITY proves that KP_relayid_ed speaks on behalf of KP_relayid_rsa.
166
        // - Therefore we have a chain from:
167
        //   KP_relayid_rsa → KS_relayid_ed → KP_relaysign_ed → KP_link_ed → AUTHENTICATE cell →
168
        //   the channel itself.
169

            
170
        // Check the relay identities in the CERTS cell.
171
        let (peer_relay_ids, peer_kp_relaysign_ed, peer_rsa_id_digest) = self
172
            .inner
173
            .check_relay_identities(peer_target_no_ids, &self.certs_cell, now)?;
174

            
175
        // Next, verify the LINK_AUTH cert (CertType 6).
176
        let peer_kp_link_ed = crate::channel::handshake::verify_link_auth_cert(
177
            &self.certs_cell,
178
            &peer_kp_relaysign_ed,
179
            Some(now),
180
            self.inner.clock_skew,
181
        )?;
182

            
183
        let our_tls_cert_digest = ll::d::Sha256::digest(our_tls_cert).into();
184
        let peer_relayid_ed = *peer_relay_ids
185
            .ed_identity()
186
            .expect("Validated relay channel without Ed25519 identity");
187

            
188
        // By building the ChannelAuthenticationData, we are certain that the authentication type
189
        // of the initiator is supported by us.
190
        let expected_auth_body = ChannelAuthenticationData::build_responder(
191
            peer_auth_cell.auth_type(),
192
            &identities,
193
            self.clog_digest,
194
            self.slog_digest,
195
            peer_rsa_id_digest,
196
            peer_relayid_ed,
197
            our_tls_cert_digest,
198
        )?
199
        .as_body_no_rand(self.inner.framed_tls.deref())?;
200

            
201
        // CRITICAL: This if is what authenticates a channel on the responder side. We compare
202
        // what we expected to what we received.
203
        let peer_auth_cell_body_no_rand = peer_auth_cell
204
            .body_no_rand()
205
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body_no_rand malformed: {e}")))?;
206
        // This equality is in constant-time to avoid timing attack oracle.
207
        if peer_auth_cell_body_no_rand
208
            .ct_eq(&expected_auth_body)
209
            .into()
210
        {
211
            return Err(Error::ChanProto(
212
                "AUTHENTICATE was unexpected. Failing authentication".into(),
213
            ));
214
        }
215

            
216
        // CRITICAL: Verify the signature of the AUTHENTICATE cell with the peer KP_link_ed.
217
        let peer_link_ed_pubkey: tor_llcrypto::pk::ed25519::PublicKey = peer_kp_link_ed
218
            .try_into()
219
            .expect("Peer KP_link_ed fails to convert to PublicKey");
220
        let peer_auth_cell_sig =
221
            tor_llcrypto::pk::ed25519::Signature::from_bytes(peer_auth_cell.sig().map_err(
222
                |e| Error::ChanProto(format!("AUTHENTICATE sig field is invalid: {e}")),
223
            )?);
224
        let peer_body = peer_auth_cell
225
            .body()
226
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body malformed: {e}")))?;
227
        peer_link_ed_pubkey
228
            .verify(peer_body, &peer_auth_cell_sig)
229
            .map_err(|e| {
230
                Error::ChanProto(format!("AUTHENTICATE cell signature failed to verify: {e}"))
231
            })?;
232

            
233
        // Transform our inner into a verified channel now that we are verified.
234
        let mut verified = self.inner.into_verified(peer_relay_ids, peer_rsa_id_digest);
235

            
236
        // This part is very important as we now flag that we are verified and thus authenticated.
237
        //
238
        // At this point, the underlying cell handler is in the Handshake state. Setting the
239
        // channel type here as authenticated means that once the handler transition to the Open
240
        // state, it will carry this authenticated flag leading to the message filter of the
241
        // channel codec to adapt its restricted message sets (meaning R2R only).
242
        //
243
        // After this call, it is considered a R2R channel.
244
        verified.set_authenticated()?;
245

            
246
        Ok(VerifiedResponderRelayChannel {
247
            inner: verified,
248
            netinfo_cell: peer_netinfo_cell,
249
            my_addrs,
250
            peer_addr: self.peer_addr,
251
        })
252
    }
253

            
254
    /// Return the clock skew of this channel.
255
    pub fn clock_skew(&self) -> ClockSkew {
256
        self.inner.clock_skew
257
    }
258
}
259

            
260
impl<T, S> VerifiedResponderRelayChannel<T, S>
261
where
262
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
263
    S: CoarseTimeProvider + SleepProvider,
264
{
265
    /// Finish the handhshake which will create an open channel and reactor.
266
    ///
267
    /// The resulting channel is considered, by Tor protocol standard, an authenticated relay
268
    /// channel on which circuits can be opened.
269
    #[instrument(skip_all, level = "trace")]
270
    pub async fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)> {
271
        // Relay<->Relay channels are NOT sensitive as we need their info in the log.
272
        let peer_info = MaybeSensitive::not_sensitive(PeerInfo::new(
273
            self.peer_addr,
274
            self.inner.relay_ids().clone(),
275
        ));
276
        self.inner
277
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info)
278
            .await
279
    }
280
}
281

            
282
impl<T, S> NonVerifiableResponderRelayChannel<T, S>
283
where
284
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
285
    S: CoarseTimeProvider + SleepProvider,
286
{
287
    /// Finish the handhshake which will create an open channel and reactor.
288
    ///
289
    /// The resulting channel is considered, by Tor protocol standard, a client/bridge relay
290
    /// channel meaning not authenticated. Circuit can be opened on it.
291
    #[instrument(skip_all, level = "trace")]
292
    pub fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)> {
293
        // This is either a client or a bridge so very sensitive.
294
        let peer_info = MaybeSensitive::sensitive(PeerInfo::new(
295
            self.peer_addr.into_inner(),
296
            RelayIds::empty(),
297
        ));
298
        // Non verifiable responder channel, we simply finalize our underlying channel and we are
299
        // done. We are connected to a client or bridge.
300
        self.inner
301
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info)
302
    }
303
}