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

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

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

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

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

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

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

            
162
        let now = now.unwrap_or_else(SystemTime::get);
163

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

            
196
        // Check the relay identities in the CERTS cell.
197
        let (peer_relay_ids, peer_kp_relaysign_ed, peer_rsa_id_digest) = self
198
            .inner
199
            .check_relay_identities(peer_target_no_ids, &self.certs_cell, now)?;
200

            
201
        // Next, verify the LINK_AUTH cert (CertType 6).
202
        let peer_kp_link_ed = crate::channel::handshake::verify_link_auth_cert(
203
            &self.certs_cell,
204
            &peer_kp_relaysign_ed,
205
            Some(now),
206
            self.inner.clock_skew,
207
        )?;
208

            
209
        let our_tls_cert_digest = ll::d::Sha256::digest(our_tls_cert).into();
210
        let peer_relayid_ed = *peer_relay_ids
211
            .ed_identity()
212
            .expect("Validated relay channel without Ed25519 identity");
213

            
214
        // By building the ChannelAuthenticationData, we are certain that the authentication type
215
        // of the initiator is supported by us.
216
        let expected_auth_body = ChannelAuthenticationData::build_responder(
217
            peer_auth_cell.auth_type(),
218
            &identities,
219
            self.clog_digest,
220
            self.slog_digest,
221
            peer_rsa_id_digest,
222
            peer_relayid_ed,
223
            our_tls_cert_digest,
224
        )?
225
        .as_body_no_rand(self.inner.framed_tls.deref())?;
226

            
227
        // CRITICAL: This if is what authenticates a channel on the responder side. We compare
228
        // what we expected to what we received.
229
        let peer_auth_cell_body_no_rand = peer_auth_cell
230
            .body_no_rand()
231
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body_no_rand malformed: {e}")))?;
232
        // This equality is in constant-time to avoid timing attack oracle.
233
        if peer_auth_cell_body_no_rand
234
            .ct_eq(&expected_auth_body)
235
            .into()
236
        {
237
            return Err(Error::ChanProto(
238
                "AUTHENTICATE was unexpected. Failing authentication".into(),
239
            ));
240
        }
241

            
242
        // CRITICAL: Verify the signature of the AUTHENTICATE cell with the peer KP_link_ed.
243
        let peer_link_ed_pubkey: tor_llcrypto::pk::ed25519::PublicKey = peer_kp_link_ed
244
            .try_into()
245
            .expect("Peer KP_link_ed fails to convert to PublicKey");
246
        let peer_auth_cell_sig =
247
            tor_llcrypto::pk::ed25519::Signature::from_bytes(peer_auth_cell.sig().map_err(
248
                |e| Error::ChanProto(format!("AUTHENTICATE sig field is invalid: {e}")),
249
            )?);
250
        let peer_body = peer_auth_cell
251
            .body()
252
            .map_err(|e| Error::ChanProto(format!("AUTHENTICATE body malformed: {e}")))?;
253
        peer_link_ed_pubkey
254
            .verify(peer_body, &peer_auth_cell_sig)
255
            .map_err(|e| {
256
                Error::ChanProto(format!("AUTHENTICATE cell signature failed to verify: {e}"))
257
            })?;
258

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

            
262
        // This part is very important as we now flag that we are verified and thus authenticated.
263
        //
264
        // At this point, the underlying cell handler is in the Handshake state. Setting the
265
        // channel type here as authenticated means that once the handler transition to the Open
266
        // state, it will carry this authenticated flag leading to the message filter of the
267
        // channel codec to adapt its restricted message sets (meaning R2R only).
268
        //
269
        // After this call, it is considered a R2R channel.
270
        verified.set_authenticated()?;
271

            
272
        Ok(VerifiedResponderRelayChannel {
273
            inner: verified,
274
            netinfo_cell: peer_netinfo_cell,
275
            my_addrs,
276
            peer_addr: self.peer_addr,
277
            create_request_handler: self.create_request_handler,
278
            our_ed25519_id: identities.ed_id,
279
            our_rsa_id: identities.rsa_id,
280
        })
281
    }
282

            
283
    /// Return the clock skew of this channel.
284
    pub fn clock_skew(&self) -> ClockSkew {
285
        self.inner.clock_skew
286
    }
287
}
288

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

            
309
        let channel_mode = ChannelMode::Relay {
310
            circ_id_range: CircIdRange::Low,
311
            our_ed25519_id: self.our_ed25519_id,
312
            our_rsa_id: self.our_rsa_id,
313
            create_request_handler: self.create_request_handler,
314
        };
315

            
316
        self.inner
317
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info, channel_mode)
318
            .await
319
    }
320
}
321

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

            
342
        let channel_mode = ChannelMode::Relay {
343
            circ_id_range: CircIdRange::Low,
344
            our_ed25519_id: self.our_ed25519_id,
345
            our_rsa_id: self.our_rsa_id,
346
            create_request_handler: self.create_request_handler,
347
        };
348

            
349
        // Non verifiable responder channel, we simply finalize our underlying channel and we are
350
        // done. We are connected to a client or bridge.
351
        self.inner
352
            .finish(&self.netinfo_cell, &self.my_addrs, peer_info, channel_mode)
353
    }
354
}