1
//! Implementation for the introduce-and-rendezvous handshake.
2

            
3
use super::*;
4

            
5
// These imports just here, because they have names unsuitable for importing widely.
6
use tor_cell::relaycell::{
7
    hs::intro_payload::{IntroduceHandshakePayload, OnionKey},
8
    msg::{Introduce2, Rendezvous1},
9
};
10
use tor_circmgr::{ServiceOnionServiceDataTunnel, build::onion_circparams_from_netparams};
11
use tor_linkspec::verbatim::VerbatimLinkSpecCircTarget;
12
use tor_proto::{
13
    client::circuit::handshake::{
14
        self,
15
        hs_ntor::{self, HsNtorHkdfKeyGenerator},
16
    },
17
    stream::{IncomingStream, IncomingStreamRequestFilter},
18
};
19
use tor_protover::Protocols;
20

            
21
/// An error produced while trying to process an introduction request we have
22
/// received from a client via an introduction point.
23
#[derive(Debug, Clone, thiserror::Error)]
24
#[allow(clippy::enum_variant_names)]
25
#[non_exhaustive]
26
pub enum IntroRequestError {
27
    /// We couldn't get a timely network directory in
28
    /// chosen circuits.
29
    #[error("Network directory not available")]
30
    NetdirUnavailable(#[source] tor_netdir::Error),
31

            
32
    /// Got an onion key with an unrecognized type (not ntor).
33
    #[error("Received an unsupported type of onion key")]
34
    UnsupportedOnionKey,
35

            
36
    /// The rendezvous point in the Introduce2 message was invalid and couldn't be used.
37
    #[error("Couldn't decode rendezvous point")]
38
    InvalidRendezvousPoint(#[source] tor_netdir::VerbatimCircTargetDecodeError),
39

            
40
    /// The handshake (e.g. hs_ntor) in the Introduce2 message was invalid and
41
    /// could not be completed.
42
    #[error("Introduction handshake was invalid")]
43
    InvalidHandshake(#[source] tor_proto::Error),
44

            
45
    /// The decrypted payload of the Introduce2 message could not be parsed.
46
    #[error("Could not parse INTRODUCE2 payload")]
47
    InvalidPayload(#[source] tor_bytes::Error),
48

            
49
    /// We weren't able to build a ChanTarget from the Introduce2 message.
50
    #[error("Invalid link specifiers in INTRODUCE2 payload")]
51
    InvalidLinkSpecs(#[source] tor_linkspec::decode::ChanTargetDecodeError),
52

            
53
    /// The client requested a capability or combination of capabilities
54
    /// that we don't support, or don't support negotiating.
55
    #[error("Client requested an invalid or unsupported subprotocol capability")]
56
    UnsupportedCapability,
57

            
58
    /// We weren't able to obtain the subcredentials for decrypting the Introduce2 message.
59
    #[error("Could not obtain subcredentials")]
60
    Subcredentials(#[source] crate::FatalError),
61
}
62

            
63
impl HasKind for IntroRequestError {
64
    fn kind(&self) -> tor_error::ErrorKind {
65
        use IntroRequestError as E;
66
        use tor_error::ErrorKind as EK;
67
        match self {
68
            E::NetdirUnavailable(e) => e.kind(),
69
            E::UnsupportedOnionKey => EK::RemoteProtocolViolation,
70
            E::InvalidRendezvousPoint(_) => EK::RemoteProtocolViolation,
71
            E::InvalidHandshake(e) => e.kind(),
72
            E::InvalidPayload(_) => EK::RemoteProtocolViolation,
73
            E::InvalidLinkSpecs(_) => EK::RemoteProtocolViolation,
74
            E::UnsupportedCapability => EK::RemoteProtocolViolation,
75
            E::Subcredentials(e) => e.kind(),
76
        }
77
    }
78
}
79

            
80
/// An error produced while trying to connect to a rendezvous point and open a
81
/// session with a client.
82
#[derive(Debug, Clone, thiserror::Error)]
83
#[non_exhaustive]
84
pub enum EstablishSessionError {
85
    /// We couldn't get a timely network directory in order to build our
86
    /// chosen circuits.
87
    #[error("Network directory not available")]
88
    NetdirUnavailable(#[source] tor_netdir::Error),
89
    /// Unable to build a circuit to the rendezvous point.
90
    #[error("Could not establish circuit to rendezvous point")]
91
    RendCirc(#[source] RetryError<tor_circmgr::Error>),
92
    /// Encountered a failure while trying to add a virtual hop to the circuit.
93
    #[error("Could not add virtual hop to circuit")]
94
    VirtualHop(#[source] tor_circmgr::Error),
95
    /// We encountered an error while configuring the virtual hop to send us
96
    /// BEGIN messages.
97
    #[error("Could not configure circuit to allow BEGIN messages")]
98
    AcceptBegins(#[source] tor_circmgr::Error),
99
    /// We encountered an error while sending the rendezvous1 message.
100
    #[error("Could not send RENDEZVOUS1 message")]
101
    SendRendezvous(#[source] tor_circmgr::Error),
102
    /// An internal error occurred.
103
    #[error("Internal error")]
104
    Bug(#[from] tor_error::Bug),
105
}
106

            
107
impl HasKind for EstablishSessionError {
108
    fn kind(&self) -> tor_error::ErrorKind {
109
        use EstablishSessionError as E;
110
        match self {
111
            E::NetdirUnavailable(e) => e.kind(),
112
            EstablishSessionError::RendCirc(e) => {
113
                tor_circmgr::Error::summarized_error_kind(e.sources())
114
            }
115
            EstablishSessionError::VirtualHop(e) => e.kind(),
116
            EstablishSessionError::AcceptBegins(e) => e.kind(),
117
            EstablishSessionError::SendRendezvous(e) => e.kind(),
118
            EstablishSessionError::Bug(e) => e.kind(),
119
        }
120
    }
121
}
122

            
123
/// A decrypted request from an onion service client which we can
124
/// choose to answer (or not).
125
///
126
/// This corresponds to a processed INTRODUCE2 message.
127
///
128
/// To accept this request, call its
129
/// [`establish_session`](IntroRequest::establish_session) method.
130
/// To reject this request, simply drop it.
131
#[derive(educe::Educe)]
132
#[educe(Debug)]
133
pub(crate) struct IntroRequest {
134
    /// The introduce2 message itself. We keep this in case we want to look at
135
    /// the outer header.
136
    #[allow(unused)] // TODO we don't currently use this?
137
    req: Introduce2,
138

            
139
    /// The key generator we'll use to derive our shared keys with the client when
140
    /// creating a virtual hop.
141
    #[educe(Debug(ignore))]
142
    key_gen: HsNtorHkdfKeyGenerator,
143

            
144
    /// The RENDEZVOUS1 message we'll send to the rendezvous point.
145
    ///
146
    /// (The rendezvous point will in turn send this to the client as a RENDEZVOUS2.)
147
    rend1_msg: Rendezvous1,
148

            
149
    /// The decrypted and parsed body of the introduce2 message.
150
    intro_payload: IntroduceHandshakePayload,
151

            
152
    /// A set of capabilities requested by the client that we are willing to support.
153
    requested_protocols: Protocols,
154

            
155
    /// The circuit target for the rendezvous point.
156
    rend_point: VerbatimLinkSpecCircTarget<OwnedCircTarget>,
157
}
158

            
159
/// An open session with a single client.
160
///
161
/// (We consume this type and take ownership of its members later in
162
/// [`RendRequest::accept()`](crate::req::RendRequest::accept).)
163
pub(crate) struct OpenSession {
164
    /// A stream of incoming BEGIN requests.
165
    pub(crate) stream_requests: BoxStream<'static, IncomingStream>,
166

            
167
    /// Our circuit with the client in question.
168
    ///
169
    /// See `RendRequest::accept()` for more information on the life cycle of
170
    /// this circuit.
171
    pub(crate) tunnel: ServiceOnionServiceDataTunnel,
172
}
173

            
174
/// Dyn-safe trait to represent a `HsCircPool`.
175
///
176
/// We need this so that we can hold an `Arc<HsCircPool<R>>` in
177
/// `RendRequestContext` without needing to parameterize on R.
178
#[async_trait]
179
pub(crate) trait RendCircConnector: Send + Sync {
180
    /// Launch or return an existing circuit to the specified target.
181
    async fn get_or_launch_specific(
182
        &self,
183
        netdir: &tor_netdir::NetDir,
184
        target: VerbatimLinkSpecCircTarget<OwnedCircTarget>,
185
    ) -> tor_circmgr::Result<ServiceOnionServiceDataTunnel>;
186

            
187
    /// Return the current time instant from the runtime.
188
    ///
189
    /// This provides mockable time for use in error tracking.
190
    fn now(&self) -> Instant;
191

            
192
    /// Return the current wall-clock time from the runtime.
193
    fn wallclock(&self) -> SystemTime;
194
}
195

            
196
#[async_trait]
197
impl<R: Runtime> RendCircConnector for HsCircPool<R> {
198
    async fn get_or_launch_specific(
199
        &self,
200
        netdir: &tor_netdir::NetDir,
201
        target: VerbatimLinkSpecCircTarget<OwnedCircTarget>,
202
    ) -> tor_circmgr::Result<ServiceOnionServiceDataTunnel> {
203
        HsCircPool::get_or_launch_svc_rend(self, netdir, target).await
204
    }
205

            
206
    fn now(&self) -> Instant {
207
        HsCircPool::now(self)
208
    }
209

            
210
    fn wallclock(&self) -> SystemTime {
211
        HsCircPool::wallclock(self)
212
    }
213
}
214

            
215
/// Filter callback used to enforce early requirements on streams.
216
#[derive(Clone, Debug)]
217
pub(crate) struct RequestFilter {
218
    /// Largest number of streams we will accept on a circuit at a time.
219
    //
220
    // TODO: Conceivably, this should instead be a
221
    // watch::Receiver<Arc<OnionServiceConfig>>, so we can re-check the latest
222
    // value of the setting every time.  Instead, we currently only copy this
223
    // setting when an intro request is accepted.
224
    pub(crate) max_concurrent_streams: usize,
225
}
226
impl IncomingStreamRequestFilter for RequestFilter {
227
    fn disposition(
228
        &mut self,
229
        _ctx: &tor_proto::stream::IncomingStreamRequestContext<'_>,
230
        circ: &tor_proto::circuit::CircHopSyncView<'_>,
231
    ) -> tor_proto::Result<tor_proto::stream::IncomingStreamRequestDisposition> {
232
        if circ.n_open_streams() >= self.max_concurrent_streams {
233
            // TODO: We may want to have a way to send back an END message as
234
            // well and not tear down the circuit.
235
            Ok(tor_proto::stream::IncomingStreamRequestDisposition::CloseCircuit)
236
        } else {
237
            Ok(tor_proto::stream::IncomingStreamRequestDisposition::Accept)
238
        }
239
    }
240
}
241

            
242
impl IntroRequest {
243
    /// Try to decrypt an incoming Introduce2 request, using the set of keys provided.
244
    pub(crate) fn decrypt_from_introduce2(
245
        req: Introduce2,
246
        context: &RendRequestContext,
247
    ) -> Result<Self, IntroRequestError> {
248
        use IntroRequestError as E;
249
        let mut rng = rand::rng();
250

            
251
        // We need the subcredential for the *current time period* in order to do the hs_ntor
252
        // handshake. But that can change over time.  We will instead use KeyMgr::get_matching to
253
        // find all current subcredentials.
254
        let subcredentials = context
255
            .compute_subcredentials()
256
            .map_err(IntroRequestError::Subcredentials)?;
257

            
258
        let (key_gen, rend1_body, msg_body) = hs_ntor::server_receive_intro(
259
            &mut rng,
260
            &context.kp_hss_ntor,
261
            &context.kp_hs_ipt_sid,
262
            &subcredentials[..],
263
            req.encoded_header(),
264
            req.encrypted_body(),
265
        )
266
        .map_err(E::InvalidHandshake)?;
267

            
268
        let intro_payload: IntroduceHandshakePayload = {
269
            let mut r = tor_bytes::Reader::from_slice(&msg_body);
270
            r.extract().map_err(E::InvalidPayload)?
271
            // Note: we _do not_ call `should_be_exhausted` here, since we
272
            // explicitly expect the payload of an introduce2 message to be
273
            // padded to hide its size.
274
        };
275
        let requested_protocols = crate::caps::negotiated_capabilities(&intro_payload)?;
276

            
277
        // We build the rend_point now, so that we can detect any
278
        // problems as early as possible.
279
        let netdir = context
280
            .netdir_provider
281
            .netdir(tor_netdir::Timeliness::Timely)
282
            .map_err(E::NetdirUnavailable)?;
283
        let ntor_onion_key = match intro_payload.onion_key() {
284
            OnionKey::NtorOnionKey(ntor_key) => ntor_key,
285
            _ => return Err(E::UnsupportedOnionKey),
286
        };
287

            
288
        let rend_point = netdir
289
            .circ_target_from_verbatim_linkspecs(intro_payload.link_specifiers(), ntor_onion_key)
290
            .map_err(E::InvalidRendezvousPoint)?;
291

            
292
        let rend1_msg = Rendezvous1::new(*intro_payload.cookie(), rend1_body);
293

            
294
        Ok(IntroRequest {
295
            req,
296
            key_gen,
297
            rend1_msg,
298
            intro_payload,
299
            requested_protocols,
300
            rend_point,
301
        })
302
    }
303

            
304
    /// Try to accept this client's request.
305
    ///
306
    /// To do so, we open a circuit to the client's chosen rendezvous point,
307
    /// send it a RENDEZVOUS1 message, and wait for incoming BEGIN messages from
308
    /// the client.
309
    pub(crate) async fn establish_session(
310
        self,
311
        filter: RequestFilter,
312
        hs_pool: Arc<dyn RendCircConnector>,
313
        provider: Arc<dyn NetDirProvider>,
314
    ) -> Result<OpenSession, EstablishSessionError> {
315
        use EstablishSessionError as E;
316

            
317
        // Find a netdir.  Note that we _won't_ try to wait or retry if the
318
        // netdir isn't there: we probably can't answer this user's request.
319
        let netdir = provider
320
            .netdir(tor_netdir::Timeliness::Timely)
321
            .map_err(E::NetdirUnavailable)?;
322

            
323
        let max_n_attempts = netdir.params().hs_service_rendezvous_failures_max;
324
        let mut tunnel = None;
325
        let mut retry_err: RetryError<tor_circmgr::Error> =
326
            RetryError::in_attempt_to("Establish a circuit to a rendezvous point");
327

            
328
        // Open circuit to rendezvous point.
329
        for _attempt in 1..=max_n_attempts.into() {
330
            match hs_pool
331
                .get_or_launch_specific(&netdir, self.rend_point.clone())
332
                .await
333
            {
334
                Ok(t) => {
335
                    tunnel = Some(t);
336
                    break;
337
                }
338
                Err(e) => {
339
                    retry_err.push_timed(e, hs_pool.now(), Some(hs_pool.wallclock()));
340
                    // Note that we do not sleep on errors: if there is any
341
                    // error that will be solved by waiting, it would probably
342
                    // require waiting too long to satisfy the client.
343
                }
344
            }
345
        }
346
        let tunnel = tunnel.ok_or_else(|| E::RendCirc(retry_err))?;
347

            
348
        // We'll need parameters to extend the virtual hop.
349
        //
350
        // (TODO #2594: If we stored our cc_sendme_inc along with our intro points, this would be the
351
        // place to look at it.)
352
        let params = onion_circparams_from_netparams(netdir.params())
353
            .map_err(into_internal!("Unable to build CircParameters"))?;
354

            
355
        // We won't need the netdir any longer; stop holding the reference.
356
        drop(netdir);
357

            
358
        let last_real_hop = tunnel
359
            .last_hop()
360
            .map_err(into_internal!("Circuit with no final hop"))?;
361

            
362
        // Add a virtual hop.
363
        tunnel
364
            .extend_virtual(
365
                handshake::RelayProtocol::HsV3,
366
                handshake::HandshakeRole::Responder,
367
                self.key_gen,
368
                params,
369
                &self.requested_protocols,
370
            )
371
            .await
372
            .map_err(E::VirtualHop)?;
373

            
374
        let virtual_hop = tunnel
375
            .last_hop()
376
            .map_err(into_internal!("Circuit with no virtual hop"))?;
377

            
378
        // Accept begins from that virtual hop
379
        let stream_requests = tunnel
380
            .allow_stream_requests(&[tor_cell::relaycell::RelayCmd::BEGIN], virtual_hop, filter)
381
            .await
382
            .map_err(E::AcceptBegins)?
383
            .boxed();
384

            
385
        // Send the RENDEZVOUS1 message.
386
        tunnel
387
            .send_raw_msg(self.rend1_msg.into(), last_real_hop)
388
            .await
389
            .map_err(E::SendRendezvous)?;
390

            
391
        Ok(OpenSession {
392
            stream_requests,
393
            tunnel,
394
        })
395
    }
396

            
397
    /// Get the [`IntroduceHandshakePayload`] associated with this [`IntroRequest`].
398
    pub(crate) fn intro_payload(&self) -> &IntroduceHandshakePayload {
399
        &self.intro_payload
400
    }
401
}