1
//! Encoding and decoding for relay messages related to onion services.
2

            
3
use super::msg::{self, Body};
4
use crate::relaycell::extlist::{ExtList, decl_extension_group};
5
use caret::caret_int;
6
use derive_deftly::Deftly;
7
use tor_bytes::{EncodeError, EncodeResult, Error as BytesError, Result};
8
use tor_bytes::{Reader, Writer};
9
use tor_hscrypto::RendCookie;
10
use tor_llcrypto::pk::rsa::RsaIdentity;
11
use tor_memquota::derive_deftly_template_HasMemoryCost;
12

            
13
pub mod est_intro;
14
pub mod intro_payload;
15
pub mod pow;
16

            
17
caret_int! {
18
    /// The type of the introduction point auth key
19
    #[derive(Deftly)]
20
    #[derive_deftly(HasMemoryCost)]
21
    pub struct AuthKeyType(u8) {
22
        /// Ed25519; SHA3-256
23
        ED25519_SHA3_256 = 2,
24
    }
25
}
26

            
27
/// A message sent from client to rendezvous point.
28
#[derive(Debug, Clone, Deftly)]
29
#[derive_deftly(HasMemoryCost)]
30
pub struct EstablishRendezvous {
31
    /// A rendezvous cookie is an arbitrary 20-byte value,
32
    /// chosen randomly by the client.
33
    cookie: RendCookie,
34
}
35
impl EstablishRendezvous {
36
    /// Construct a new establish rendezvous cell.
37
5418
    pub fn new(cookie: RendCookie) -> Self {
38
5418
        Self { cookie }
39
5418
    }
40
}
41
impl msg::Body for EstablishRendezvous {
42
189
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
43
189
        let cookie = r.extract()?;
44
126
        r.take_rest();
45
126
        Ok(Self { cookie })
46
189
    }
47
3
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
48
3
        w.write(&self.cookie)
49
3
    }
50
}
51

            
52
#[derive(Debug, Clone, Deftly)]
53
#[derive_deftly(HasMemoryCost)]
54
/// A message sent from client to introduction point.
55
pub struct Introduce1(Introduce);
56

            
57
impl msg::Body for Introduce1 {
58
189
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
59
189
        let (intro, _) = Introduce::decode_from_reader(r)?;
60
126
        Ok(Self(intro))
61
189
    }
62
88
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
63
88
        self.0.encode_onto(w)
64
88
    }
65
}
66

            
67
impl Introduce1 {
68
    /// All arguments constructor
69
10773
    pub fn new(auth_key_type: AuthKeyType, auth_key: Vec<u8>, encrypted: Vec<u8>) -> Self {
70
10773
        Self(Introduce::new(auth_key_type, auth_key, encrypted))
71
10773
    }
72
}
73

            
74
#[derive(Debug, Clone, Deftly)]
75
#[derive_deftly(HasMemoryCost)]
76
/// A message sent from introduction point to hidden service host.
77
pub struct Introduce2 {
78
    /// A copy of the encoded header that we'll use to finish the hs_ntor handshake.
79
    encoded_header: Vec<u8>,
80
    /// The decoded message itself.
81
    msg: Introduce,
82
}
83

            
84
impl msg::Body for Introduce2 {
85
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
86
        let (msg, header) = Introduce::decode_from_reader(r)?;
87
        let encoded_header = header.to_vec();
88

            
89
        Ok(Self {
90
            encoded_header,
91
            msg,
92
        })
93
    }
94
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
95
        self.msg.encode_onto(w)
96
    }
97
}
98

            
99
impl Introduce2 {
100
    /// All arguments constructor.
101
    ///
102
    /// This is only useful for testing, since in reality the only time this
103
    /// message type is created is when an introduction point is forwarding an
104
    /// INTRODUCE1 message.
105
    #[cfg(test)] // Don't expose this generally without dealing somehow with the `expect` below
106
    pub fn new(auth_key_type: AuthKeyType, auth_key: Vec<u8>, encrypted: Vec<u8>) -> Self {
107
        use tor_bytes::Writeable as _;
108
        let msg = Introduce::new(auth_key_type, auth_key, encrypted);
109
        let mut encoded_header = Vec::new();
110
        msg.header
111
            .write_onto(&mut encoded_header)
112
            .expect("Generated a header that we could not encode");
113
        Self {
114
            encoded_header,
115
            msg,
116
        }
117
    }
118

            
119
    /// Return the bytes used to transmit `header`.
120
    ///
121
    /// (This data is used as part of the handshake.)
122
    pub fn encoded_header(&self) -> &[u8] {
123
        &self.encoded_header[..]
124
    }
125
    /// Return the parsed header of this message.
126
    pub fn header(&self) -> &IntroduceHeader {
127
        &self.msg.header
128
    }
129
    /// Return the encrypted body of this message.
130
    ///
131
    /// (This body is decrypted as part of the handshake.)
132
    pub fn encrypted_body(&self) -> &[u8] {
133
        &self.msg.encrypted[..]
134
    }
135
}
136

            
137
caret_int! {
138
    /// The recognized unencrypted extension types for an `Introduce1` or `Introduce2` message.
139
    #[derive(Ord,PartialOrd)]
140
    pub struct IntroduceExtType(u8) {
141
    }
142
}
143

            
144
decl_extension_group! {
145
    /// An unencrypted extension to an `Introduce` or `Introduce2` message.
146
    ///
147
    /// (Currently, no extensions of this type are recognized)
148
    #[derive(Debug,Clone,Deftly)]
149
    #[derive_deftly(HasMemoryCost)]
150
    enum IntroduceExt [ IntroduceExtType ] {
151
    }
152
}
153

            
154
/// The unencrypted header portion of an `Introduce1` or `Introduce2` message.
155
///
156
/// This is a separate type because the `hs_ntor` handshake requires access to the
157
/// encoded format of the header, only.
158
#[derive(Debug, Clone, Deftly)]
159
#[derive_deftly(HasMemoryCost)]
160
pub struct IntroduceHeader {
161
    /// Introduction point auth key type and the type of
162
    /// the MAC used in `handshake_auth`.
163
    auth_key_type: AuthKeyType,
164
    /// The public introduction point auth key.
165
    auth_key: Vec<u8>,
166
    /// A list of extensions
167
    extensions: ExtList<IntroduceExt>,
168
}
169

            
170
impl tor_bytes::Readable for IntroduceHeader {
171
189
    fn take_from(r: &mut Reader<'_>) -> Result<Self> {
172
189
        let legacy_key_id: RsaIdentity = r.extract()?;
173
189
        if !legacy_key_id.is_zero() {
174
63
            return Err(BytesError::InvalidMessage(
175
63
                "legacy key id in Introduce1.".into(),
176
63
            ));
177
126
        }
178
126
        let auth_key_type = r.take_u8()?.into();
179
126
        let auth_key_len = r.take_u16()?;
180
126
        let auth_key = r.take(auth_key_len as usize)?.into();
181
126
        let extensions = r.extract()?;
182
126
        Ok(Self {
183
126
            auth_key_type,
184
126
            auth_key,
185
126
            extensions,
186
126
        })
187
189
    }
188
}
189

            
190
impl tor_bytes::Writeable for IntroduceHeader {
191
88
    fn write_onto<W: Writer + ?Sized>(&self, w: &mut W) -> EncodeResult<()> {
192
88
        w.write_all(&[0_u8; 20]);
193
88
        w.write_u8(self.auth_key_type.get());
194
88
        w.write_u16(u16::try_from(self.auth_key.len()).map_err(|_| EncodeError::BadLengthValue)?);
195
88
        w.write_all(&self.auth_key[..]);
196
88
        w.write(&self.extensions)?;
197
88
        Ok(())
198
88
    }
199
}
200

            
201
#[derive(Debug, Clone, Deftly)]
202
#[derive_deftly(HasMemoryCost)]
203
/// A message body shared by Introduce1 and Introduce2
204
struct Introduce {
205
    /// The unencrypted header portion of the message.
206
    header: IntroduceHeader,
207
    /// Up to end of relay payload.
208
    encrypted: Vec<u8>,
209
}
210

            
211
impl Introduce {
212
    /// All arguments constructor
213
10773
    fn new(auth_key_type: AuthKeyType, auth_key: Vec<u8>, encrypted: Vec<u8>) -> Self {
214
10773
        Self {
215
10773
            header: IntroduceHeader {
216
10773
                auth_key_type,
217
10773
                auth_key,
218
10773
                extensions: Default::default(),
219
10773
            },
220
10773
            encrypted,
221
10773
        }
222
10773
    }
223
    /// Decode an Introduce message body from the given reader.
224
    ///
225
    /// Return the Introduce message body itself, and the text of the body's header.
226
189
    fn decode_from_reader<'a>(r: &mut Reader<'a>) -> Result<(Self, &'a [u8])> {
227
189
        let header_start = r.cursor();
228
189
        let header = r.extract()?;
229
126
        let header_end = r.cursor();
230
126
        let encrypted = r.take_rest().into();
231
126
        Ok((
232
126
            Self { header, encrypted },
233
126
            r.range(header_start, header_end),
234
126
        ))
235
189
    }
236
    /// Encode an Introduce message body onto the given writer
237
88
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
238
88
        w.write(&self.header)?;
239
88
        w.write_all(&self.encrypted[..]);
240
88
        Ok(())
241
88
    }
242
}
243

            
244
/// A message sent from an onion service to a rendezvous point, telling it to
245
/// make a connection to the client.
246
#[derive(Debug, Clone, Deftly)]
247
#[derive_deftly(HasMemoryCost)]
248
pub struct Rendezvous1 {
249
    /// The cookie originally sent by the client in its ESTABLISH_REND message.
250
    cookie: RendCookie,
251
    /// The message to send the client.
252
    handshake_info: Vec<u8>,
253
}
254

            
255
impl Body for Rendezvous1 {
256
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
257
63
        let cookie = r.extract()?;
258
63
        let handshake_info = r.take_rest().into();
259
63
        Ok(Self {
260
63
            cookie,
261
63
            handshake_info,
262
63
        })
263
63
    }
264

            
265
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
266
2
        w.write(&self.cookie)?;
267
2
        w.write_all(&self.handshake_info[..]);
268
2
        Ok(())
269
2
    }
270
}
271

            
272
impl Rendezvous1 {
273
    /// Create a new Rendezvous1 message, to handshake with a client identified
274
    /// by a given RendCookie, and send it a given message.
275
1
    pub fn new(cookie: RendCookie, handshake_info: impl Into<Vec<u8>>) -> Self {
276
1
        Self {
277
1
            cookie,
278
1
            handshake_info: handshake_info.into(),
279
1
        }
280
1
    }
281
}
282

            
283
/// A message sent from the rendezvous point to the client, telling it about the
284
/// onion service's message.
285
#[derive(Debug, Clone, Deftly)]
286
#[derive_deftly(HasMemoryCost)]
287
pub struct Rendezvous2 {
288
    /// The handshake message from the onion service.
289
    handshake_info: Vec<u8>,
290
}
291

            
292
impl Rendezvous2 {
293
    /// Construct a new Rendezvous2 cell containing a given handshake message.
294
85
    pub fn new(handshake_info: impl Into<Vec<u8>>) -> Self {
295
85
        Self {
296
85
            handshake_info: handshake_info.into(),
297
85
        }
298
85
    }
299

            
300
    /// Return the body of this Rendezvous2 cell. (That is, the handshake
301
    /// message from the onion service.)
302
    pub fn handshake_info(&self) -> &[u8] {
303
        &self.handshake_info
304
    }
305
}
306

            
307
impl From<Rendezvous1> for Rendezvous2 {
308
63
    fn from(value: Rendezvous1) -> Self {
309
63
        Self {
310
63
            handshake_info: value.handshake_info,
311
63
        }
312
63
    }
313
}
314

            
315
impl Body for Rendezvous2 {
316
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
317
63
        let handshake_info = r.take_rest().into();
318
63
        Ok(Self { handshake_info })
319
63
    }
320

            
321
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
322
2
        w.write_all(&self.handshake_info[..]);
323
2
        Ok(())
324
2
    }
325
}
326

            
327
caret_int! {
328
    /// The recognized extension types for an `IntroEstablished` message.
329
    #[derive(Ord, PartialOrd)]
330
    pub struct IntroEstablishedExtType(u8) {
331
    }
332
}
333

            
334
decl_extension_group! {
335
    /// An extension to an IntroEstablished message.
336
    ///
337
    /// (Currently, no extensions of this type are recognized)
338
    #[derive(Debug,Clone,Deftly)]
339
    #[derive_deftly(HasMemoryCost)]
340
    #[non_exhaustive]
341
    pub enum IntroEstablishedExt [ IntroEstablishedExtType ] {
342
    }
343
}
344

            
345
/// Reply sent from the introduction point to the onion service, telling it that
346
/// an introduction point is now established.
347
#[derive(Debug, Clone, Default, Deftly)]
348
#[derive_deftly(HasMemoryCost)]
349
pub struct IntroEstablished {
350
    /// The extensions included in this cell.
351
    extensions: ExtList<IntroEstablishedExt>,
352
}
353

            
354
impl IntroEstablished {
355
    /// Create a new IntroEstablished message.
356
63
    pub fn new() -> Self {
357
63
        Self::default()
358
63
    }
359

            
360
    /// Return an iterator over the extensions declared in this message.
361
    pub fn iter_extensions(&self) -> impl Iterator<Item = &IntroEstablishedExt> {
362
        self.extensions.iter()
363
    }
364
}
365

            
366
impl Body for IntroEstablished {
367
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
368
63
        let extensions = r.extract()?;
369
63
        Ok(Self { extensions })
370
63
    }
371

            
372
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
373
2
        w.write(&self.extensions)?;
374
2
        Ok(())
375
2
    }
376
}
377

            
378
caret_int! {
379
    /// A status code returned in response to an INTRODUCE1 message.
380
    #[derive(Deftly)]
381
    #[derive_deftly(HasMemoryCost)]
382
    pub struct IntroduceAckStatus(u16) {
383
        /// The message was relayed successfully.
384
        SUCCESS = 0x0000,
385
        /// The introduction point does not have a live circuit from the
386
        /// identified service.
387
        NOT_RECOGNIZED = 0x0001,
388
        /// There was a failure while parsing the INTRODUCE1 message.
389
        BAD_MESSAGE_FORMAT = 0x0002,
390
        /// The introduction point was unable to deliver the message to the service.
391
        CANT_RELAY = 0x0003,
392
    }
393
}
394
caret_int! {
395
    /// The recognized extension types for an `IntroEstablished` message.
396
    #[derive(Ord, PartialOrd, Deftly)]
397
    #[derive_deftly(HasMemoryCost)]
398
    pub struct IntroduceAckExtType(u8) {
399
    }
400
}
401
decl_extension_group! {
402
    /// An extension to an IntroduceAct message.
403
    ///
404
    /// (Currently, no extensions of this type are recognized.)
405
    #[derive(Debug,Clone,Deftly)]
406
    #[derive_deftly(HasMemoryCost)]
407
    enum IntroduceAckExt [ IntroduceAckExtType ] {
408
    }
409
}
410

            
411
/// A reply from the introduction point to the client, telling it that its
412
/// introduce1 was received.
413
#[derive(Clone, Debug, Deftly)]
414
#[derive_deftly(HasMemoryCost)]
415
pub struct IntroduceAck {
416
    /// The status reported for the Introduce1 message.
417
    status_code: IntroduceAckStatus,
418
    /// The extensions on this message.
419
    extensions: ExtList<IntroduceAckExt>,
420
}
421
impl IntroduceAck {
422
    /// Create a new IntroduceAck message with a provided status code.
423
189
    pub fn new(status_code: IntroduceAckStatus) -> Self {
424
189
        Self {
425
189
            status_code,
426
189
            extensions: Default::default(),
427
189
        }
428
189
    }
429

            
430
    /// Return the status code from this message.
431
10584
    pub fn status(&self) -> IntroduceAckStatus {
432
10584
        self.status_code
433
10584
    }
434

            
435
    /// Checks whether the introduction was a success
436
    ///
437
    /// If introduction was forwarded successfully,
438
    /// returns an `Ok<IntroduceAck>`, whose `.status()` can safely be ignored.
439
    /// (The extension list may still be of interest.)
440
    ///
441
    /// Otherwise, returns `Err<IntroduceAckStatus>`,
442
    /// which is suitable for error reporting purposes.
443
5355
    pub fn success(self) -> std::result::Result<IntroduceAck, IntroduceAckStatus> {
444
5355
        if self.status() == IntroduceAckStatus::SUCCESS {
445
126
            Ok(self)
446
        } else {
447
5229
            Err(self.status())
448
        }
449
5355
    }
450
}
451

            
452
impl Body for IntroduceAck {
453
63
    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
454
63
        let status_code = r.take_u16()?.into();
455
63
        let extensions = r.extract()?;
456
63
        Ok(IntroduceAck {
457
63
            status_code,
458
63
            extensions,
459
63
        })
460
63
    }
461

            
462
2
    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
463
2
        w.write_u16(self.status_code.into());
464
2
        w.write(&self.extensions)?;
465
2
        Ok(())
466
2
    }
467
}
468

            
469
/// When to maybe retry introduction to the *same service* at the *same introduction point*.
470
///
471
/// (Using this on `IntroduceAckStatus::SUCCESS` is a mistake;
472
/// if you do that you'll not get a meaningful retry time, but it won't panic.)
473
impl tor_error::HasRetryTime for IntroduceAckStatus {
474
5229
    fn retry_time(&self) -> tor_error::RetryTime {
475
        use IntroduceAckStatus as S;
476
        use tor_error::RetryTime as RT;
477
5229
        match *self {
478
            S::SUCCESS => RT::Never, // this is a bug
479
5229
            S::NOT_RECOGNIZED => RT::AfterWaiting,
480
            S::BAD_MESSAGE_FORMAT => RT::Never,
481
            S::CANT_RELAY => RT::AfterWaiting,
482
            _ => RT::AfterWaiting, // who knows?
483
        }
484
5229
    }
485
}
486

            
487
super::msg::empty_body! {
488
    /// Acknowledges an EstablishRendezvous message.
489
    pub struct RendezvousEstablished {}
490
}