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_llcrypto::pk::ed25519::Ed25519Identity;
19
use tor_rtcompat::{CertifiedConn, CoarseTimeProvider, Runtime, SleepProvider, StreamOps};
20
use web_time_compat::{SystemTime, SystemTimeExt};
21

            
22
use crate::{
23
    ClockSkew, Error, RelayChannelAuthMaterial, Result,
24
    channel::{
25
        Channel, ChannelMode, ClogDigest, Reactor, SlogDigest,
26
        circmap::CircIdRange,
27
        handshake::{UnverifiedChannel, VerifiedChannel},
28
    },
29
    peer::{PeerAddr, PeerInfo},
30
    relay::CreateRequestHandler,
31
    relay::channel::ChannelAuthenticationData,
32
};
33

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

            
47
/// A channel that can NOT be verified. This is solely either a client or bridge on the other end.
48
///
49
/// This can only be built if no [`msg::Authenticate`] was ever received.
50
pub struct NonVerifiableResponderRelayChannel<
51
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
52
    S: CoarseTimeProvider + SleepProvider,
53
> {
54
    /// The common unverified channel that both client and relays use.
55
    pub(crate) inner: UnverifiedChannel<T, S>,
56
    /// The netinfo cell received from the initiator.
57
    pub(crate) netinfo_cell: msg::Netinfo,
58
    /// Our advertised addresses.
59
    pub(crate) my_addrs: Vec<IpAddr>,
60
    /// The peer address which is sensitive considering it is either client or bridge.
61
    pub(crate) peer_addr: Sensitive<PeerAddr>,
62
    /// Provided to each new channel so that they can handle CREATE* requests.
63
    pub(crate) create_request_handler: Arc<CreateRequestHandler>,
64
    /// Our Ed25519 identity.
65
    ///
66
    /// Needed for ntor handshakes.
67
    pub(crate) our_ed25519_id: Ed25519Identity,
68
}
69

            
70
/// A verifiable relay responder channel that is currently unverified. This can only be a relay on
71
/// the other end.
72
///
73
/// The verify() and then finish() functions are to be used to get a final Channel/Reactor.
74
pub struct UnverifiedResponderRelayChannel<
75
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
76
    S: CoarseTimeProvider + SleepProvider,
77
> {
78
    /// The common unverified channel that both client and relays use.
79
    pub(crate) inner: UnverifiedChannel<T, S>,
80
    /// AUTHENTICATE cell received from the initiator.
81
    pub(crate) auth_cell: msg::Authenticate,
82
    /// The netinfo cell received from the initiator.
83
    pub(crate) netinfo_cell: msg::Netinfo,
84
    /// The [`msg::Certs`] cell received from the initiator.
85
    pub(crate) certs_cell: msg::Certs,
86
    /// Our authentication key material.
87
    pub(crate) auth_material: Arc<RelayChannelAuthMaterial>,
88
    /// Our advertised addresses.
89
    pub(crate) my_addrs: Vec<IpAddr>,
90
    /// The peer address which we know is a relay.
91
    pub(crate) peer_addr: PeerAddr,
92
    /// The CLOG digest.
93
    pub(crate) clog_digest: ClogDigest,
94
    /// The SLOG digest.
95
    pub(crate) slog_digest: SlogDigest,
96
    /// Provided to each new channel so that they can handle CREATE* requests.
97
    pub(crate) create_request_handler: Arc<CreateRequestHandler>,
98
}
99

            
100
/// A verified relay responder channel.
101
///
102
/// Only finish() remains to transform this into a fully usable [`crate::channel::Channel`] and
103
/// [`crate::channel::Reactor`].
104
pub struct VerifiedResponderRelayChannel<
105
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
106
    S: CoarseTimeProvider + SleepProvider,
107
> {
108
    /// The common unverified channel that both client and relays use.
109
    inner: VerifiedChannel<T, S>,
110
    /// The netinfo cell that we got from the relay. Canonicity decision.
111
    netinfo_cell: msg::Netinfo,
112
    /// Our advertised addresses.
113
    my_addrs: Vec<IpAddr>,
114
    /// The peer address which we know is a relay.
115
    peer_addr: PeerAddr,
116
    /// Provided to each new channel so that they can handle CREATE* requests.
117
    create_request_handler: Arc<CreateRequestHandler>,
118
    /// Our Ed25519 identity.
119
    ///
120
    /// Needed for ntor handshakes.
121
    our_ed25519_id: Ed25519Identity,
122
}
123

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

            
153
        let now = now.unwrap_or_else(SystemTime::get);
154

            
155
        // We are a relay responder. We have received a CERTS cell and we need to verify these
156
        // certs:
157
        //
158
        //   Relay Identities:
159
        //      IDENTITY_V_SIGNING_CERT (CertType 4)
160
        //      RSA_ID_X509             (CertType 2)
161
        //      RSA_ID_V_IDENTITY       (CertType 7)
162
        //
163
        //   Connection Cert:
164
        //      SIGNING_V_LINK_AUTH     (CertType 6)
165
        //
166
        // Validating the relay identities first so we can make sure we are talking to the relay
167
        // (peer) we wanted. Then, check the AUTHENTICATE cell.
168
        //
169
        // The end result is a verified channel (not authenticated yet) which guarantee that we are
170
        // talking to the right relay that we wanted. We validate so we can prove these:
171
        //
172
        // - IDENTITY_V_SIGNING proves that KP_relaysign_ed speaks on behalf of KP_relayid_ed
173
        // - SIGNING_V_LINK_AUTH proves that KP_link_ed speaks on behalf of KP_relaysign_ed
174
        // - The AUTHENTICATE cell proves that the TLS session's key material is known by the
175
        //   owner of KP_link_ed
176
        // - Therefore, we have a chain from:
177
        //   KS_relayid_ed → KP_relaysign_ed → KP_link_ed → AUTHENTICATE cell → the channel itself.
178
        //
179
        // As for legacy certs, they prove nothing but we can extract keys:
180
        //
181
        // - RSA_ID_X509 proves nothing; we just extract its subject key as KP_relayid_rsa.
182
        // - RSA_ID_V_IDENTITY proves that KP_relayid_ed speaks on behalf of KP_relayid_rsa.
183
        // - Therefore we have a chain from:
184
        //   KP_relayid_rsa → KS_relayid_ed → KP_relaysign_ed → KP_link_ed → AUTHENTICATE cell →
185
        //   the channel itself.
186

            
187
        // Check the relay identities in the CERTS cell.
188
        let (peer_relay_ids, peer_kp_relaysign_ed, peer_rsa_id_digest) = self
189
            .inner
190
            .check_relay_identities(peer_target_no_ids, &self.certs_cell, now)?;
191

            
192
        // Next, verify the LINK_AUTH cert (CertType 6).
193
        let peer_kp_link_ed = crate::channel::handshake::verify_link_auth_cert(
194
            &self.certs_cell,
195
            &peer_kp_relaysign_ed,
196
            Some(now),
197
            self.inner.clock_skew,
198
        )?;
199

            
200
        let our_tls_cert_digest = ll::d::Sha256::digest(our_tls_cert).into();
201
        let peer_relayid_ed = *peer_relay_ids
202
            .ed_identity()
203
            .expect("Validated relay channel without Ed25519 identity");
204

            
205
        // By building the ChannelAuthenticationData, we are certain that the authentication type
206
        // of the initiator is supported by us.
207
        let expected_auth_body = ChannelAuthenticationData::build_responder(
208
            peer_auth_cell.auth_type(),
209
            &identities,
210
            self.clog_digest,
211
            self.slog_digest,
212
            peer_rsa_id_digest,
213
            peer_relayid_ed,
214
            our_tls_cert_digest,
215
        )?
216
        .as_body_no_rand(self.inner.framed_tls.deref())?;
217

            
218
        // CRITICAL: This if is what authenticates a channel on the responder side. We compare
219
        // what we expected to what we received.
220
        let peer_auth_cell_body_no_rand = peer_auth_cell
221
            .body_no_rand()
222
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body_no_rand malformed: {e}")))?;
223
        // This equality is in constant-time to avoid timing attack oracle.
224
        if peer_auth_cell_body_no_rand
225
            .ct_eq(&expected_auth_body)
226
            .into()
227
        {
228
            return Err(Error::ChanProto(
229
                "AUTHENTICATE was unexpected. Failing authentication".into(),
230
            ));
231
        }
232

            
233
        // CRITICAL: Verify the signature of the AUTHENTICATE cell with the peer KP_link_ed.
234
        let peer_link_ed_pubkey: tor_llcrypto::pk::ed25519::PublicKey = peer_kp_link_ed
235
            .try_into()
236
            .expect("Peer KP_link_ed fails to convert to PublicKey");
237
        let peer_auth_cell_sig =
238
            tor_llcrypto::pk::ed25519::Signature::from_bytes(peer_auth_cell.sig().map_err(
239
                |e| Error::ChanProto(format!("AUTHENTICATE sig field is invalid: {e}")),
240
            )?);
241
        let peer_body = peer_auth_cell
242
            .body()
243
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body malformed: {e}")))?;
244
        peer_link_ed_pubkey
245
            .verify(peer_body, &peer_auth_cell_sig)
246
            .map_err(|e| {
247
                Error::ChanProto(format!("AUTHENTICATE cell signature failed to verify: {e}"))
248
            })?;
249

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

            
253
        // This part is very important as we now flag that we are verified and thus authenticated.
254
        //
255
        // At this point, the underlying cell handler is in the Handshake state. Setting the
256
        // channel type here as authenticated means that once the handler transition to the Open
257
        // state, it will carry this authenticated flag leading to the message filter of the
258
        // channel codec to adapt its restricted message sets (meaning R2R only).
259
        //
260
        // After this call, it is considered a R2R channel.
261
        verified.set_authenticated()?;
262

            
263
        Ok(VerifiedResponderRelayChannel {
264
            inner: verified,
265
            netinfo_cell: peer_netinfo_cell,
266
            my_addrs,
267
            peer_addr: self.peer_addr,
268
            create_request_handler: self.create_request_handler,
269
            our_ed25519_id: identities.ed_id,
270
        })
271
    }
272

            
273
    /// Return the clock skew of this channel.
274
    pub fn clock_skew(&self) -> ClockSkew {
275
        self.inner.clock_skew
276
    }
277
}
278

            
279
impl<T, S> VerifiedResponderRelayChannel<T, S>
280
where
281
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
282
    S: CoarseTimeProvider + SleepProvider,
283
{
284
    /// Finish the handhshake which will create an open channel and reactor.
285
    ///
286
    /// The resulting channel is considered, by Tor protocol standard, an authenticated relay
287
    /// channel on which circuits can be opened.
288
    #[instrument(skip_all, level = "trace")]
289
    pub async fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)>
290
    where
291
        S: Runtime,
292
    {
293
        // Relay<->Relay channels are NOT sensitive as we need their info in the log.
294
        let peer_info = MaybeSensitive::not_sensitive(PeerInfo::new(
295
            self.peer_addr,
296
            self.inner.relay_ids().clone(),
297
        ));
298

            
299
        let channel_mode = ChannelMode::Relay {
300
            circ_id_range: CircIdRange::Low,
301
            our_ed25519_id: self.our_ed25519_id,
302
            create_request_handler: self.create_request_handler,
303
        };
304

            
305
        self.inner
306
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info, channel_mode)
307
            .await
308
    }
309
}
310

            
311
impl<T, S> NonVerifiableResponderRelayChannel<T, S>
312
where
313
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
314
    S: CoarseTimeProvider + SleepProvider,
315
{
316
    /// Finish the handhshake which will create an open channel and reactor.
317
    ///
318
    /// The resulting channel is considered, by Tor protocol standard, a client/bridge relay
319
    /// channel meaning not authenticated. Circuit can be opened on it.
320
    #[instrument(skip_all, level = "trace")]
321
    pub fn finish(self) -> Result<(Arc<Channel>, Reactor<S>)>
322
    where
323
        S: Runtime,
324
    {
325
        // This is either a client or a bridge so very sensitive.
326
        let peer_info = MaybeSensitive::sensitive(PeerInfo::new(
327
            self.peer_addr.into_inner(),
328
            RelayIds::empty(),
329
        ));
330

            
331
        let channel_mode = ChannelMode::Relay {
332
            circ_id_range: CircIdRange::Low,
333
            our_ed25519_id: self.our_ed25519_id,
334
            create_request_handler: self.create_request_handler,
335
        };
336

            
337
        // Non verifiable responder channel, we simply finalize our underlying channel and we are
338
        // done. We are connected to a client or bridge.
339
        self.inner
340
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info, channel_mode)
341
    }
342
}