tor-proto 0.41.0

Asynchronous client-side implementation of the central Tor network protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Implementations for the relay channel handshake

use futures::SinkExt;
use futures::io::{AsyncRead, AsyncWrite};
use futures::stream::{Stream, StreamExt};
use rand::Rng;
use safelog::Sensitive;
use std::net::IpAddr;
use std::{sync::Arc, time::SystemTime};
use tracing::trace;

use tor_cell::chancell::msg::AnyChanMsg;
use tor_cell::chancell::{AnyChanCell, ChanMsg, msg};
use tor_cell::restrict::{RestrictedMsg, restricted_msg};
use tor_error::internal;
use tor_linkspec::{ChannelMethod, HasChanMethod, OwnedChanTarget};
use tor_rtcompat::{CertifiedConn, CoarseTimeProvider, SleepProvider, StreamOps};

use crate::channel::handshake::{
    ChannelBaseHandshake, ChannelInitiatorHandshake, UnverifiedChannel, UnverifiedInitiatorChannel,
    unauthenticated_clock_skew,
};
use crate::channel::{ChannelFrame, ChannelType, UniqId, new_frame};
use crate::memquota::ChannelAccount;
use crate::peer::PeerAddr;
use crate::relay::channel::initiator::UnverifiedInitiatorRelayChannel;
use crate::relay::channel::responder::{
    MaybeVerifiableRelayResponderChannel, NonVerifiableResponderRelayChannel,
    UnverifiedResponderRelayChannel,
};
use crate::relay::channel::{RelayIdentities, build_certs_cell, build_netinfo_cell};
use crate::{Error, Result};

/// The "Ed25519-SHA256-RFC5705" link authentication which is value "00 03".
pub(super) static AUTHTYPE_ED25519_SHA256_RFC5705: u16 = 3;

/// A relay channel handshake as the initiator.
pub struct RelayInitiatorHandshake<
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
> {
    /// Runtime handle (insofar as we need it)
    sleep_prov: S,
    /// Memory quota account
    memquota: ChannelAccount,
    /// Underlying TLS stream in a channel frame.
    ///
    /// (We don't enforce that this is actually TLS, but if it isn't, the
    /// connection won't be secure.)
    framed_tls: ChannelFrame<T>,
    /// Logging identifier for this stream.  (Used for logging only.)
    unique_id: UniqId,
    /// Our identity keys needed for authentication.
    identities: Arc<RelayIdentities>,
    /// The peer we are attempting to connect to.
    target_method: ChannelMethod,
    /// Our advertised addresses. Needed for the NETINFO.
    my_addrs: Vec<IpAddr>,
}

/// Implement the base channel handshake trait.
impl<T, S> ChannelBaseHandshake<T> for RelayInitiatorHandshake<T, S>
where
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
{
    fn framed_tls(&mut self) -> &mut ChannelFrame<T> {
        &mut self.framed_tls
    }
    fn unique_id(&self) -> &UniqId {
        &self.unique_id
    }
}

/// Implement the initiator channel handshake trait.
impl<T, S> ChannelInitiatorHandshake<T> for RelayInitiatorHandshake<T, S>
where
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
{
}

impl<
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
> RelayInitiatorHandshake<T, S>
{
    /// Constructor.
    pub(crate) fn new(
        tls: T,
        sleep_prov: S,
        identities: Arc<RelayIdentities>,
        my_addrs: Vec<IpAddr>,
        peer: &OwnedChanTarget,
        memquota: ChannelAccount,
    ) -> Self {
        Self {
            framed_tls: new_frame(tls, ChannelType::RelayInitiator),
            unique_id: UniqId::new(),
            sleep_prov,
            identities,
            memquota,
            my_addrs,
            target_method: peer.chan_method(),
        }
    }

    /// Connect to another relay as the relay Initiator.
    ///
    /// Takes a function that reports the current time.  In theory, this can just be
    /// `SystemTime::get()`.
    pub async fn connect<F>(mut self, now_fn: F) -> Result<UnverifiedInitiatorRelayChannel<T, S>>
    where
        F: FnOnce() -> SystemTime,
    {
        // Send the VERSIONS.
        let (versions_flushed_at, versions_flushed_wallclock) =
            self.send_versions_cell(now_fn).await?;

        // Receive the VERSIONS.
        let link_protocol = self.recv_versions_cell().await?;

        // VERSIONS cell have been exchanged, set the link protocol into our channel frame.
        self.set_link_protocol(link_protocol)?;

        // Read until we have all the remaining cells from the responder.
        let (auth_challenge_cell, certs_cell, (netinfo_cell, netinfo_rcvd_at), slog_digest) = self
            .recv_cells_from_responder(/* take_slog= */ true)
            .await?;

        // TODO: It would be nice to come up with a better design for getting the SLOG.
        let slog_digest = slog_digest.ok_or(internal!("Asked for SLOG, but `None` returned?"))?;

        trace!(stream_id = %self.unique_id,
            "received handshake, ready to verify.",
        );

        // Calculate our clock skew from the timings we just got/calculated.
        let clock_skew = unauthenticated_clock_skew(
            &netinfo_cell,
            netinfo_rcvd_at,
            versions_flushed_at,
            versions_flushed_wallclock,
        );

        Ok(UnverifiedInitiatorRelayChannel {
            inner: UnverifiedInitiatorChannel {
                inner: UnverifiedChannel {
                    link_protocol,
                    framed_tls: self.framed_tls,
                    clock_skew,
                    memquota: self.memquota,
                    target_method: Some(self.target_method),
                    unique_id: self.unique_id,
                    sleep_prov: self.sleep_prov.clone(),
                },
                certs_cell,
            },
            auth_challenge_cell,
            slog_digest,
            netinfo_cell,
            identities: self.identities,
            my_addrs: self.my_addrs,
        })
    }
}

/// A relay channel handshake as the responder.
pub struct RelayResponderHandshake<
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
> {
    /// Runtime handle (insofar as we need it)
    sleep_prov: S,
    /// Memory quota account
    memquota: ChannelAccount,
    /// Underlying TLS stream in a channel frame.
    ///
    /// (We don't enforce that this is actually TLS, but if it isn't, the
    /// connection won't be secure.)
    framed_tls: ChannelFrame<T>,
    /// The peer IP address as in the address the initiator is connecting from. This can be a
    /// client so keep it sensitive.
    peer_addr: Sensitive<PeerAddr>,
    /// Our advertised addresses. Needed for the NETINFO.
    my_addrs: Vec<IpAddr>,
    /// Logging identifier for this stream.  (Used for logging only.)
    unique_id: UniqId,
    /// Our identity keys needed for authentication.
    identities: Arc<RelayIdentities>,
}

/// Implement the base channel handshake trait.
impl<T, S> ChannelBaseHandshake<T> for RelayResponderHandshake<T, S>
where
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
{
    fn framed_tls(&mut self) -> &mut ChannelFrame<T> {
        &mut self.framed_tls
    }
    fn unique_id(&self) -> &UniqId {
        &self.unique_id
    }
}

impl<
    T: AsyncRead + AsyncWrite + CertifiedConn + StreamOps + Send + Unpin + 'static,
    S: CoarseTimeProvider + SleepProvider,
> RelayResponderHandshake<T, S>
{
    /// Constructor.
    pub(crate) fn new(
        peer_addr: Sensitive<PeerAddr>,
        my_addrs: Vec<IpAddr>,
        tls: T,
        sleep_prov: S,
        identities: Arc<RelayIdentities>,
        memquota: ChannelAccount,
    ) -> Self {
        Self {
            peer_addr,
            my_addrs,
            framed_tls: new_frame(
                tls,
                ChannelType::RelayResponder {
                    authenticated: false,
                },
            ),
            unique_id: UniqId::new(),
            sleep_prov,
            identities,
            memquota,
        }
    }

    /// Begin the handshake process.
    ///
    /// Takes a function that reports the current time.  In theory, this can just be
    /// `SystemTime::get()`.
    pub async fn handshake<F>(
        mut self,
        now_fn: F,
    ) -> Result<MaybeVerifiableRelayResponderChannel<T, S>>
    where
        F: FnOnce() -> SystemTime,
    {
        // Receive initiator VERSIONS.
        let link_protocol = self.recv_versions_cell().await?;

        // Send the VERSIONS message.
        let (versions_flushed_at, versions_flushed_wallclock) =
            self.send_versions_cell(now_fn).await?;

        // VERSIONS cell have been exchanged, set the link protocol into our channel frame.
        self.set_link_protocol(link_protocol)?;

        // Send CERTS, AUTH_CHALLENGE and NETINFO
        let slog_digest = self.send_cells_to_initiator().await?;

        // Receive NETINFO and possibly [CERTS, AUTHENTICATE]. The connection could be from a
        // client/bridge and thus no authentication meaning no CERTS/AUTHENTICATE cells.
        let (certs_and_auth_and_clog, (netinfo_cell, netinfo_rcvd_at)) =
            self.recv_cells_from_initiator().await?;

        // Try to unpack these into something we can use later.
        let (certs_cell, auth_and_clog) = match certs_and_auth_and_clog {
            Some((certs, auth, clog)) => (Some(certs), Some((auth, clog))),
            None => (None, None),
        };

        // Calculate our clock skew from the timings we just got/calculated.
        let clock_skew = unauthenticated_clock_skew(
            &netinfo_cell,
            netinfo_rcvd_at,
            versions_flushed_at,
            versions_flushed_wallclock,
        );

        let inner = UnverifiedChannel {
            link_protocol,
            framed_tls: self.framed_tls,
            clock_skew,
            memquota: self.memquota,
            target_method: None,
            unique_id: self.unique_id,
            sleep_prov: self.sleep_prov,
        };

        // With an AUTHENTICATE cell, we can verify (relay). Else (client/bridge), we can't.
        Ok(match auth_and_clog {
            Some((auth_cell, clog_digest)) => {
                MaybeVerifiableRelayResponderChannel::Verifiable(UnverifiedResponderRelayChannel {
                    inner,
                    auth_cell,
                    netinfo_cell,
                    // TODO(relay): Should probably put that in the match {} and not assume.
                    certs_cell: certs_cell.expect("AUTHENTICATE cell without CERTS cell"),
                    identities: self.identities,
                    my_addrs: self.my_addrs,
                    peer_addr: self.peer_addr.into_inner(), // Relay address.
                    clog_digest,
                    slog_digest,
                })
            }
            None => MaybeVerifiableRelayResponderChannel::NonVerifiable(
                NonVerifiableResponderRelayChannel {
                    inner,
                    netinfo_cell,
                    my_addrs: self.my_addrs,
                    peer_addr: self.peer_addr,
                },
            ),
        })
    }

    /// Receive all the cells expected from the initiator of the connection. Keep in mind that it
    /// can be either a relay or client or bridge.
    async fn recv_cells_from_initiator(
        &mut self,
    ) -> Result<(
        Option<(
            msg::Certs,
            msg::Authenticate,
            /* the CLOG digest */ [u8; 32],
        )>,
        (msg::Netinfo, coarsetime::Instant),
    )> {
        // IMPORTANT: Protocol wise, we MUST only allow one single cell of each type for a valid
        // handshake. Any duplicates lead to a failure.
        // They must arrive in a specific order in order for the CLOG calculation to be valid.

        /// Read a message from the stream.
        ///
        /// The `expecting` parameter is used for logging purposes, not filtering.
        async fn read_msg<T>(
            stream_id: UniqId,
            mut stream: impl Stream<Item = Result<AnyChanCell>> + Unpin,
        ) -> Result<T>
        where
            T: RestrictedMsg + TryFrom<AnyChanMsg, Error = AnyChanMsg>,
        {
            let Some(cell) = stream.next().await.transpose()? else {
                // The entire channel has ended, so nothing else to be done.
                return Err(Error::HandshakeProto("Stream ended unexpectedly".into()));
            };

            let (id, m) = cell.into_circid_and_msg();
            trace!(%stream_id, "received a {} cell", m.cmd());

            // TODO: Maybe also check this in the channel handshake codec?
            if let Some(id) = id {
                return Err(Error::HandshakeProto(format!(
                    "Expected no circ ID for {} cell, but received circ ID of {id} instead",
                    m.cmd(),
                )));
            }

            let m = m.try_into().map_err(|m: AnyChanMsg| {
                Error::HandshakeProto(format!(
                    "Expected [{}] cell, but received {} cell instead",
                    tor_basic_utils::iter_join(", ", T::cmds_for_logging().iter()),
                    m.cmd(),
                ))
            })?;

            Ok(m)
        }

        // Note that the `ChannelFrame` already restricts the messages due to its handshake cell
        // handler.

        // This is kind of ugly, but I don't see a nicer way to write the authentication branch
        // without a bunch of boilerplate for a state machine.
        let (certs_and_auth_and_clog, netinfo, netinfo_rcvd_at) = 'outer: {
            // CERTS or NETINFO cell.
            let certs = loop {
                restricted_msg! {
                    enum CertsNetinfoMsg : ChanMsg {
                        // VPADDING cells (but not PADDING) can be sent during handshaking.
                        Vpadding,
                        Netinfo,
                        Certs,
                   }
                }

                break match read_msg(*self.unique_id(), self.framed_tls()).await? {
                    CertsNetinfoMsg::Vpadding(_) => continue,
                    // If a NETINFO cell, the initiator did not authenticate and we can stop early.
                    CertsNetinfoMsg::Netinfo(msg) => {
                        break 'outer (None, msg, coarsetime::Instant::now());
                    }
                    // If a CERTS cell, the initiator is authenticating.
                    CertsNetinfoMsg::Certs(msg) => msg,
                };
            };

            // We're the responder, which means that the recv log is the CLOG.
            let clog_digest = self.framed_tls().codec_mut().take_recv_log_digest()?;

            // AUTHENTICATE cell.
            let auth = loop {
                restricted_msg! {
                    enum AuthenticateMsg : ChanMsg {
                        // VPADDING cells (but not PADDING) can be sent during handshaking.
                        Vpadding,
                        Authenticate,
                   }
                }

                break match read_msg(*self.unique_id(), self.framed_tls()).await? {
                    AuthenticateMsg::Vpadding(_) => continue,
                    AuthenticateMsg::Authenticate(msg) => msg,
                };
            };

            // NETINFO cell (if we didn't receive it earlier).
            let (netinfo, netinfo_rcvd_at) = loop {
                restricted_msg! {
                    enum NetinfoMsg : ChanMsg {
                        // VPADDING cells (but not PADDING) can be sent during handshaking.
                        Vpadding,
                        Netinfo,
                   }
                }

                break match read_msg(*self.unique_id(), self.framed_tls()).await? {
                    NetinfoMsg::Vpadding(_) => continue,
                    NetinfoMsg::Netinfo(msg) => (msg, coarsetime::Instant::now()),
                };
            };

            (Some((certs, auth, clog_digest)), netinfo, netinfo_rcvd_at)
        };

        Ok((certs_and_auth_and_clog, (netinfo, netinfo_rcvd_at)))
    }

    /// Send all expected cells to the initiator of the channel as the responder.
    ///
    /// Return the sending times of the [`msg::Versions`] so it can be used for clock skew
    /// validation, and the SLOG digest to be later used when verifying the initiator's
    /// AUTHENTICATE cell.
    async fn send_cells_to_initiator(&mut self) -> Result<[u8; 32]> {
        // Send the CERTS message.
        let certs = build_certs_cell(&self.identities, /* is_responder */ true);
        trace!(channel_id = %self.unique_id, "Sending CERTS as responder cell.");
        self.framed_tls.send(certs.into()).await?;

        // Send the AUTH_CHALLENGE.
        let challenge: [u8; 32] = rand::rng().random();
        let auth_challenge = msg::AuthChallenge::new(challenge, [AUTHTYPE_ED25519_SHA256_RFC5705]);
        trace!(channel_id = %self.unique_id, "Sending AUTH_CHALLENGE as responder cell.");
        self.framed_tls.send(auth_challenge.into()).await?;

        // We're the responder, which means that the send log is the SLOG.
        let slog_digest = self.framed_tls.codec_mut().take_send_log_digest()?;

        // Send the NETINFO message.
        let peer_ip = self.peer_addr.netinfo_addr();
        let netinfo = build_netinfo_cell(peer_ip, self.my_addrs.clone(), &self.sleep_prov)?;
        trace!(channel_id = %self.unique_id, "Sending NETINFO as responder cell.");
        self.framed_tls.send(netinfo.into()).await?;

        Ok(slog_digest)
    }
}