1
//! Request objects used to implement onion services.
2
//!
3
//! These requests are yielded on a stream, and the calling code needs to decide
4
//! whether to permit or reject them.
5

            
6
use crate::internal_prelude::*;
7

            
8
use tor_cell::relaycell::msg::{Connected, End, Introduce2};
9
use tor_circmgr::ServiceOnionServiceDataTunnel;
10
use tor_hscrypto::Subcredential;
11
use tor_keymgr::ArtiPath;
12
use tor_proto::stream::{IncomingStream, IncomingStreamRequest};
13

            
14
/// Request to complete an introduction/rendezvous handshake.
15
///
16
/// A request of this kind indicates that a client has asked permission to
17
/// connect to an onion service through an introduction point.  The caller needs
18
/// to decide whether or not to complete the handshake.
19
///
20
/// Protocol details: More specifically, we create one of these whenever we get a well-formed
21
/// `INTRODUCE2` message.  Based on this, the caller decides whether to send a
22
/// `RENDEZVOUS1` message.
23
#[derive(Educe)]
24
#[educe(Debug)]
25
pub struct RendRequest {
26
    /// The introduction point that sent this request.
27
    #[allow(unused)] // TODO we don't currently use this?
28
    ipt_lid: IptLocalId,
29

            
30
    /// The message as received from the remote introduction point.
31
    raw: Introduce2,
32

            
33
    /// Reference to the keys we'll need to decrypt and handshake with this request.
34
    #[educe(Debug(ignore))]
35
    context: Arc<RendRequestContext>,
36

            
37
    /// The introduce2 message that we've decrypted and processed.
38
    ///
39
    /// We do not compute this immediately upon receiving the Introduce2 cell,
40
    /// since there is a bit of cryptography involved and we don't want to add
41
    /// any extra latency to the message handler.
42
    ///
43
    /// TODO: This also contains `raw`, which is maybe not so great; it would be
44
    /// neat to implement more efficiently.
45
    //
46
    // TODO MSRV TBD: Replace with std OnceCell (#1996)
47
    expanded: once_cell::unsync::OnceCell<rend_handshake::IntroRequest>,
48
}
49

            
50
/// A request from a client to open a new stream to an onion service.
51
///
52
/// We can only receive these _after_ we have already permitted the client to
53
/// connect via a [`RendRequest`].
54
///
55
/// Protocol details: More specifically, we create one of these whenever we get a well-formed
56
/// `BEGIN` message.  Based on this, the caller decides whether to send a
57
/// `CONNECTED` message.
58
#[derive(Debug)]
59
pub struct StreamRequest {
60
    /// The object that will be used to send data to and from the client.
61
    stream: IncomingStream,
62

            
63
    /// The circuit that made this request.
64
    on_tunnel: Arc<ServiceOnionServiceDataTunnel>,
65
}
66

            
67
/// Keys and objects needed to answer a RendRequest.
68
pub(crate) struct RendRequestContext {
69
    /// The nickname of the service receiving the request.
70
    pub(crate) nickname: HsNickname,
71

            
72
    /// The key manager, used for looking up subcredentials.
73
    pub(crate) keymgr: Arc<KeyMgr>,
74

            
75
    /// Key we'll use to decrypt the rendezvous request.
76
    pub(crate) kp_hss_ntor: Arc<HsSvcNtorKeypair>,
77

            
78
    /// We use this key to identify our session with this introduction point,
79
    /// and prevent replays across sessions.
80
    pub(crate) kp_hs_ipt_sid: HsIntroPtSessionIdKey,
81

            
82
    /// Configuration for a filter for this service.
83
    pub(crate) filter: rend_handshake::RequestFilter,
84

            
85
    /// Provider we'll use to find a directory so that we can build a rendezvous
86
    /// circuit.
87
    pub(crate) netdir_provider: Arc<dyn tor_netdir::NetDirProvider>,
88

            
89
    /// Circuit pool we'll use to build a rendezvous circuit.
90
    pub(crate) circ_pool: Arc<dyn RendCircConnector + Send + Sync>,
91
}
92

            
93
impl RendRequestContext {
94
    /// Obtain the all current `Subcredential`s of `nickname`
95
    /// from the `K_hs_blind_id` read from the keystore.
96
    pub(crate) fn compute_subcredentials(&self) -> Result<Vec<Subcredential>, FatalError> {
97
        let hsid_key_spec = HsIdPublicKeySpecifier::new(self.nickname.clone());
98

            
99
        let hsid = self
100
            .keymgr
101
            .get::<HsIdKey>(&hsid_key_spec)?
102
            .ok_or_else(|| FatalError::MissingHsIdKeypair(self.nickname.clone()))?;
103

            
104
        let pattern = BlindIdKeypairSpecifierPattern {
105
            nickname: Some(self.nickname.clone()),
106
            period: None,
107
        }
108
        .arti_pattern()?;
109

            
110
        let blind_id_kps: Vec<(HsBlindIdKeypair, TimePeriod)> = self
111
            .keymgr
112
            .list_matching(&pattern)?
113
            .iter()
114
            .map(|entry| -> Result<Option<_>, FatalError> {
115
                let path = entry
116
                    .key_path()
117
                    .arti()
118
                    .ok_or_else(|| internal!("CTorPath matched arti pattern?!"))?;
119
                let matches = path
120
                    .matches(&pattern)
121
                    .ok_or_else(|| internal!("path matched but no longer does?!"))?;
122
                let period = Self::parse_time_period(path, &matches)?;
123
                // Try to retrieve the key.
124
                self.keymgr
125
                    .get_entry::<HsBlindIdKeypair>(entry)
126
                    .map_err(FatalError::Keystore)
127
                    // If the key is not found, it means it has been garbage collected between the time
128
                    // we queried the keymgr for the list of keys matching the pattern and now.
129
                    // This is OK, because we only need the "current" keys
130
                    .map(|maybe_key| maybe_key.map(|key| (key, period)))
131
            })
132
            .flatten_ok()
133
            .collect::<Result<Vec<_>, FatalError>>()?;
134

            
135
        Ok(blind_id_kps
136
            .iter()
137
            .map(|(blind_id_key, period)| hsid.compute_subcredential(&blind_id_key.into(), *period))
138
            .collect())
139
    }
140

            
141
    /// Try to parse the `captures` of `path` as a [`TimePeriod`].
142
    fn parse_time_period(
143
        path: &ArtiPath,
144
        captures: &[ArtiPathRange],
145
    ) -> Result<TimePeriod, tor_keymgr::Error> {
146
        use tor_keymgr::{ArtiPathError, KeyPathError, KeystoreCorruptionError as KCE};
147

            
148
        let [denotator] = captures else {
149
            return Err(internal!(
150
                "invalid number of denotator captures: expected 1, found {}",
151
                captures.len()
152
            )
153
            .into());
154
        };
155

            
156
        let Some(denotator) = path.substring(denotator) else {
157
            return Err(internal!("captured substring out of range?!").into());
158
        };
159

            
160
        let tp = (|| {
161
            let slug = Slug::new(denotator.to_string())
162
                .map_err(|e| ArtiPathError::InvalidArtiPath(e.into()))?;
163

            
164
            TimePeriod::from_slug(&slug).map_err(|error| {
165
                ArtiPathError::InvalidKeyPathComponentValue {
166
                    key: "time_period".to_owned(),
167
                    value: slug.clone(),
168
                    error,
169
                }
170
            })
171
        })()
172
        .map_err(|err| {
173
            KCE::KeyPath(KeyPathError::Arti {
174
                path: path.clone(),
175
                err,
176
            })
177
        })?;
178

            
179
        Ok(tp)
180
    }
181
}
182

            
183
impl RendRequest {
184
    /// Construct a new RendRequest from its parts.
185
    pub(crate) fn new(
186
        ipt_lid: IptLocalId,
187
        msg: Introduce2,
188
        context: Arc<RendRequestContext>,
189
    ) -> Self {
190
        Self {
191
            ipt_lid,
192
            raw: msg,
193
            context,
194
            expanded: Default::default(),
195
        }
196
    }
197

            
198
    /// Try to return a reference to the intro_request, creating it if it did
199
    /// not previously exist.
200
    pub(crate) fn intro_request(
201
        &self,
202
    ) -> Result<&rend_handshake::IntroRequest, rend_handshake::IntroRequestError> {
203
        self.expanded.get_or_try_init(|| {
204
            rend_handshake::IntroRequest::decrypt_from_introduce2(self.raw.clone(), &self.context)
205
        })
206
    }
207

            
208
    /// Mark this request as accepted, and try to connect to the client's
209
    /// provided rendezvous point.
210
    pub async fn accept(
211
        mut self,
212
    ) -> Result<impl Stream<Item = StreamRequest> + Unpin, ClientError> {
213
        // Make sure the request is there.
214
        self.intro_request().map_err(ClientError::BadIntroduce)?;
215
        // Take ownership of the request.
216
        let intro_request = self
217
            .expanded
218
            .take()
219
            .expect("intro_request succeeded but did not fill 'expanded'.");
220
        let rend_handshake::OpenSession {
221
            stream_requests,
222
            tunnel,
223
        } = intro_request
224
            .establish_session(
225
                self.context.filter.clone(),
226
                self.context.circ_pool.clone(),
227
                self.context.netdir_provider.clone(),
228
            )
229
            .await
230
            .map_err(ClientError::EstablishSession)?;
231

            
232
        let tunnel = Arc::new(tunnel);
233

            
234
        // Note that we move circuit (which is an Arc<ClientCirc>) into this
235
        // closure, which lives for as long as the stream of StreamRequest, and
236
        // for as long as each individual StreamRequest.  This is how we keep
237
        // the rendezvous circuit alive, and ensure that it gets closed when
238
        // the Stream we return is dropped.
239
        Ok(stream_requests.map(move |stream| StreamRequest {
240
            stream,
241
            on_tunnel: tunnel.clone(),
242
        }))
243
    }
244

            
245
    /// Reject this request.  (The client will receive no notification.)
246
    #[allow(clippy::unused_async)] // we might need this to be async at some point
247
    pub async fn reject(self) -> Result<(), Bug> {
248
        // nothing to do.
249
        Ok(())
250
    }
251

            
252
    // TODO: also add various accessors, as needed.
253
}
254

            
255
impl StreamRequest {
256
    /// Return the message that was used to request this stream.
257
    ///
258
    /// NOTE: for consistency with other onion service implementations, you
259
    /// should typically only accept `BEGIN` messages, and only check the port
260
    /// in those messages. If you behave differently, your implementation will
261
    /// be distinguishable.
262
    pub fn request(&self) -> &IncomingStreamRequest {
263
        self.stream.request()
264
    }
265

            
266
    /// Accept this request and send the client a `CONNECTED` message.
267
    pub async fn accept(self, connected_message: Connected) -> Result<DataStream, ClientError> {
268
        self.stream
269
            .accept_data(connected_message)
270
            .await
271
            .map_err(ClientError::AcceptStream)
272
    }
273

            
274
    /// Reject this request, and send the client an `END` message.
275
    ///
276
    /// NOTE: If you need to be consistent with other onion service
277
    /// implementations, you should typically only send back `End` messages with
278
    /// the `DONE` reason. If you send back any other rejection, your
279
    /// implementation will be distinguishable.
280
    pub async fn reject(self, end_message: End) -> Result<(), ClientError> {
281
        self.stream
282
            .reject(end_message)
283
            .await
284
            .map_err(ClientError::RejectStream)
285
    }
286

            
287
    /// Reject this request and close the rendezvous circuit entirely,
288
    /// along with all other streams attached to the circuit.
289
    pub fn shutdown_circuit(self) -> Result<(), Bug> {
290
        self.on_tunnel.terminate();
291
        Ok(())
292
    }
293

            
294
    // TODO various accessors, including for circuit.
295
}