Skip to main content

tor_cell/relaycell/
hs.rs

1//! Encoding and decoding for relay messages related to onion services.
2
3use super::msg::{self, Body};
4use crate::relaycell::extlist::{ExtList, decl_extension_group};
5use caret::caret_int;
6use derive_deftly::Deftly;
7use tor_bytes::{EncodeError, EncodeResult, Error as BytesError, Result};
8use tor_bytes::{Reader, Writer};
9use tor_hscrypto::RendCookie;
10use tor_llcrypto::pk::rsa::RsaIdentity;
11use tor_memquota::derive_deftly_template_HasMemoryCost;
12
13pub mod est_intro;
14pub mod intro_payload;
15pub mod pow;
16
17caret_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)]
30pub struct EstablishRendezvous {
31    /// A rendezvous cookie is an arbitrary 20-byte value,
32    /// chosen randomly by the client.
33    cookie: RendCookie,
34}
35impl EstablishRendezvous {
36    /// Construct a new establish rendezvous cell.
37    pub fn new(cookie: RendCookie) -> Self {
38        Self { cookie }
39    }
40}
41impl msg::Body for EstablishRendezvous {
42    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
43        let cookie = r.extract()?;
44        r.take_rest();
45        Ok(Self { cookie })
46    }
47    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
48        w.write(&self.cookie)
49    }
50}
51
52#[derive(Debug, Clone, Deftly)]
53#[derive_deftly(HasMemoryCost)]
54/// A message sent from client to introduction point.
55pub struct Introduce1(Introduce);
56
57impl msg::Body for Introduce1 {
58    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
59        let (intro, _) = Introduce::decode_from_reader(r)?;
60        Ok(Self(intro))
61    }
62    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
63        self.0.encode_onto(w)
64    }
65}
66
67impl Introduce1 {
68    /// All arguments constructor
69    pub fn new(auth_key_type: AuthKeyType, auth_key: Vec<u8>, encrypted: Vec<u8>) -> Self {
70        Self(Introduce::new(auth_key_type, auth_key, encrypted))
71    }
72}
73
74#[derive(Debug, Clone, Deftly)]
75#[derive_deftly(HasMemoryCost)]
76/// A message sent from introduction point to hidden service host.
77pub 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
84impl 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
99impl 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
137caret_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
144decl_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)]
160pub 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
170impl tor_bytes::Readable for IntroduceHeader {
171    fn take_from(r: &mut Reader<'_>) -> Result<Self> {
172        let legacy_key_id: RsaIdentity = r.extract()?;
173        if !legacy_key_id.is_zero() {
174            return Err(BytesError::InvalidMessage(
175                "legacy key id in Introduce1.".into(),
176            ));
177        }
178        let auth_key_type = r.take_u8()?.into();
179        let auth_key_len = r.take_u16()?;
180        let auth_key = r.take(auth_key_len as usize)?.into();
181        let extensions = r.extract()?;
182        Ok(Self {
183            auth_key_type,
184            auth_key,
185            extensions,
186        })
187    }
188}
189
190impl tor_bytes::Writeable for IntroduceHeader {
191    fn write_onto<W: Writer + ?Sized>(&self, w: &mut W) -> EncodeResult<()> {
192        w.write_all(&[0_u8; 20]);
193        w.write_u8(self.auth_key_type.get());
194        w.write_u16(u16::try_from(self.auth_key.len()).map_err(|_| EncodeError::BadLengthValue)?);
195        w.write_all(&self.auth_key[..]);
196        w.write(&self.extensions)?;
197        Ok(())
198    }
199}
200
201#[derive(Debug, Clone, Deftly)]
202#[derive_deftly(HasMemoryCost)]
203/// A message body shared by Introduce1 and Introduce2
204struct 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
211impl Introduce {
212    /// All arguments constructor
213    fn new(auth_key_type: AuthKeyType, auth_key: Vec<u8>, encrypted: Vec<u8>) -> Self {
214        Self {
215            header: IntroduceHeader {
216                auth_key_type,
217                auth_key,
218                extensions: Default::default(),
219            },
220            encrypted,
221        }
222    }
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    fn decode_from_reader<'a>(r: &mut Reader<'a>) -> Result<(Self, &'a [u8])> {
227        let header_start = r.cursor();
228        let header = r.extract()?;
229        let header_end = r.cursor();
230        let encrypted = r.take_rest().into();
231        Ok((
232            Self { header, encrypted },
233            r.range(header_start, header_end),
234        ))
235    }
236    /// Encode an Introduce message body onto the given writer
237    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
238        w.write(&self.header)?;
239        w.write_all(&self.encrypted[..]);
240        Ok(())
241    }
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)]
248pub 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
255impl Body for Rendezvous1 {
256    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
257        let cookie = r.extract()?;
258        let handshake_info = r.take_rest().into();
259        Ok(Self {
260            cookie,
261            handshake_info,
262        })
263    }
264
265    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
266        w.write(&self.cookie)?;
267        w.write_all(&self.handshake_info[..]);
268        Ok(())
269    }
270}
271
272impl 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    pub fn new(cookie: RendCookie, handshake_info: impl Into<Vec<u8>>) -> Self {
276        Self {
277            cookie,
278            handshake_info: handshake_info.into(),
279        }
280    }
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)]
287pub struct Rendezvous2 {
288    /// The handshake message from the onion service.
289    handshake_info: Vec<u8>,
290}
291
292impl Rendezvous2 {
293    /// Construct a new Rendezvous2 cell containing a given handshake message.
294    pub fn new(handshake_info: impl Into<Vec<u8>>) -> Self {
295        Self {
296            handshake_info: handshake_info.into(),
297        }
298    }
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
307impl From<Rendezvous1> for Rendezvous2 {
308    fn from(value: Rendezvous1) -> Self {
309        Self {
310            handshake_info: value.handshake_info,
311        }
312    }
313}
314
315impl Body for Rendezvous2 {
316    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
317        let handshake_info = r.take_rest().into();
318        Ok(Self { handshake_info })
319    }
320
321    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
322        w.write_all(&self.handshake_info[..]);
323        Ok(())
324    }
325}
326
327caret_int! {
328    /// The recognized extension types for an `IntroEstablished` message.
329    #[derive(Ord, PartialOrd)]
330    pub struct IntroEstablishedExtType(u8) {
331    }
332}
333
334decl_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)]
349pub struct IntroEstablished {
350    /// The extensions included in this cell.
351    extensions: ExtList<IntroEstablishedExt>,
352}
353
354impl IntroEstablished {
355    /// Create a new IntroEstablished message.
356    pub fn new() -> Self {
357        Self::default()
358    }
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
366impl Body for IntroEstablished {
367    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
368        let extensions = r.extract()?;
369        Ok(Self { extensions })
370    }
371
372    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
373        w.write(&self.extensions)?;
374        Ok(())
375    }
376}
377
378caret_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}
394caret_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}
401decl_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)]
415pub 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}
421impl IntroduceAck {
422    /// Create a new IntroduceAck message with a provided status code.
423    pub fn new(status_code: IntroduceAckStatus) -> Self {
424        Self {
425            status_code,
426            extensions: Default::default(),
427        }
428    }
429
430    /// Return the status code from this message.
431    pub fn status(&self) -> IntroduceAckStatus {
432        self.status_code
433    }
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    pub fn success(self) -> std::result::Result<IntroduceAck, IntroduceAckStatus> {
444        if self.status() == IntroduceAckStatus::SUCCESS {
445            Ok(self)
446        } else {
447            Err(self.status())
448        }
449    }
450}
451
452impl Body for IntroduceAck {
453    fn decode_from_reader(r: &mut Reader<'_>) -> Result<Self> {
454        let status_code = r.take_u16()?.into();
455        let extensions = r.extract()?;
456        Ok(IntroduceAck {
457            status_code,
458            extensions,
459        })
460    }
461
462    fn encode_onto<W: Writer + ?Sized>(self, w: &mut W) -> EncodeResult<()> {
463        w.write_u16(self.status_code.into());
464        w.write(&self.extensions)?;
465        Ok(())
466    }
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.)
473impl tor_error::HasRetryTime for IntroduceAckStatus {
474    fn retry_time(&self) -> tor_error::RetryTime {
475        use IntroduceAckStatus as S;
476        use tor_error::RetryTime as RT;
477        match *self {
478            S::SUCCESS => RT::Never, // this is a bug
479            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    }
485}
486
487super::msg::empty_body! {
488    /// Acknowledges an EstablishRendezvous message.
489    pub struct RendezvousEstablished {}
490}