1
//! Errors relating to being a hidden service client
2
use std::sync::Arc;
3

            
4
use derive_more::{From, Into};
5
use futures::task::SpawnError;
6

            
7
use thiserror::Error;
8
use tracing::error;
9

            
10
use retry_error::RetryError;
11
use safelog::{Redacted, Sensitive};
12
use tor_cell::relaycell::hs::IntroduceAckStatus;
13
use tor_error::define_asref_dyn_std_error;
14
use tor_error::{Bug, ErrorKind, ErrorReport as _, HasKind, HasRetryTime, RetryTime, internal};
15
use tor_linkspec::RelayIds;
16
use tor_llcrypto::pk::ed25519::Ed25519Identity;
17
use tor_netdir::Relay;
18

            
19
/// Identity of a rendezvous point, for use in error reports
20
pub(crate) type RendPtIdentityForError = Redacted<RelayIds>;
21

            
22
/// Given a `Relay` for a rendezvous pt, provides its identify for use in error reports
23
518
pub(crate) fn rend_pt_identity_for_error(relay: &Relay<'_>) -> RendPtIdentityForError {
24
518
    RelayIds::from_relay_ids(relay).into()
25
518
}
26

            
27
/// Index of an introduction point in the descriptor
28
///
29
/// Principally used in error reporting.
30
///
31
/// Formats as `#<n+1>`.
32
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, From, Into)]
33
#[allow(clippy::exhaustive_structs)]
34
#[derive(derive_more::Display)]
35
#[display("#{}", self.0 + 1)]
36
pub struct IntroPtIndex(pub usize);
37

            
38
/// Error that occurred attempting to reach a hidden service
39
#[derive(Error, Clone, Debug)]
40
#[non_exhaustive]
41
pub enum ConnError {
42
    /// Invalid hidden service identity (`.onion` address)
43
    #[error("Invalid hidden service identity (`.onion` address)")]
44
    InvalidHsId,
45

            
46
    /// Unable to download hidden service descriptor
47
    #[error("Unable to download hidden service descriptor")]
48
    DescriptorDownload(RetryError<tor_error::Report<DescriptorError>>),
49

            
50
    /// Obtained descriptor but unable to connect to hidden service due to problem with IPT or RPT
51
    // TODO HS is this the right name for this variant?
52
    #[error("Unable to connect to hidden service using any Rendezvous Point / Introduction Point")]
53
    Failed(#[source] RetryError<FailedAttemptError>),
54

            
55
    /// The consensus network contains no suitable hidden service directories!
56
    #[error("consensus contains no suitable hidden service directories")]
57
    NoHsDirs,
58

            
59
    /// The descriptor contained only unusable introduction points!
60
    ///
61
    /// This is the fault of the service, or shows incompatibility between us and them.
62
    #[error("hidden service has no introduction points usable by us")]
63
    NoUsableIntroPoints,
64

            
65
    /// Cannot fetch the descriptor because we are rate-limited
66
    ///
67
    /// Returned if we do not have a descriptor for the service,
68
    /// and we cannot download a new one because a rate-limit
69
    /// is in place for all HsDirs.
70
    #[error("cannot fetch descriptor (we are rate-limited)")]
71
    NoUsableHsDirs,
72

            
73
    /// Unable to spawn
74
    #[error("Unable to spawn {spawning}")]
75
    Spawn {
76
        /// What we were trying to spawn
77
        spawning: &'static str,
78
        /// What happened when we tried to spawn it
79
        #[source]
80
        cause: Arc<SpawnError>,
81
    },
82

            
83
    /// Internal error
84
    #[error("{0}")]
85
    Bug(#[from] Bug),
86
}
87

            
88
/// Error that occurred attempting to download a descriptor
89
#[derive(Error, Clone, Debug)]
90
#[non_exhaustive]
91
#[error("tried hsdir {hsdir}: {error}")]
92
pub struct DescriptorError {
93
    /// Which hsdir we were trying
94
    // TODO #813 this should be Redacted<RelayDescription> or something
95
    // It seems likely that the set of redacted hsdir ids could identify the service,
96
    // so use Sensitive rather than Redacted.
97
    pub hsdir: Sensitive<Ed25519Identity>,
98

            
99
    /// What happened
100
    #[source]
101
    pub error: DescriptorErrorDetail,
102
}
103
define_asref_dyn_std_error!(DescriptorError);
104

            
105
/// Error that occurred attempting to download a descriptor
106
#[derive(Error, Clone, Debug)]
107
#[non_exhaustive]
108
//
109
// NOTE! These are in an order!  "Most interesting" errors come last.
110
// Specifically, after various attempts, the ErrorKind of the overall error
111
// will be that of the error which is latest in this enum.
112
//
113
#[derive(strum::EnumDiscriminants)]
114
#[strum_discriminants(derive(PartialOrd, Ord))]
115
pub enum DescriptorErrorDetail {
116
    /// Timed out
117
    #[error("timed out")]
118
    Timeout,
119

            
120
    /// Failed to establish circuit to hidden service directory
121
    #[error("circuit failed")]
122
    Circuit(#[from] tor_circmgr::Error),
123

            
124
    /// Failed to establish stream to hidden service directory
125
    #[error("stream failed")]
126
    Stream(#[source] tor_proto::Error),
127

            
128
    /// Failed to make directory request
129
    #[error("directory error")]
130
    Directory(#[from] tor_dirclient::RequestError),
131

            
132
    /// Incompatibility with network parameters
133
    #[error("descriptor was not compatible with network parameters: {0}")]
134
    ParameterMismatch(String),
135

            
136
    /// Failed to parse or validate descriptor
137
    #[error("problem with descriptor")]
138
    Descriptor(#[from] tor_netdoc::doc::hsdesc::HsDescError),
139

            
140
    /// Internal error
141
    #[error("{0}")]
142
    Bug(#[from] Bug),
143
}
144

            
145
impl From<tor_rtcompat::TimeoutError> for DescriptorErrorDetail {
146
    fn from(_: tor_rtcompat::TimeoutError) -> Self {
147
        Self::Timeout
148
    }
149
}
150

            
151
/// Error that occurred making one attempt to connect to a hidden service using an IP and RP
152
#[derive(Error, Clone, Debug)]
153
#[non_exhaustive]
154
//
155
// NOTE! These are in an order!  "Most interesting" errors come last.
156
// Specifically, after various attempts, the ErrorKind of the overall error
157
// will be that of the error which is latest in this enum.
158
//
159
#[derive(strum::EnumDiscriminants)]
160
#[strum_discriminants(derive(PartialOrd, Ord))]
161
// TODO HS is this the right name for this type?  It's a very mixed bag, so maybe it is.
162
pub enum FailedAttemptError {
163
    /// Introduction point unusable because it couldn't be used as a circuit target
164
    #[error("Unusable introduction point #{intro_index}")]
165
    UnusableIntro {
166
        /// Why it's not use able
167
        #[source]
168
        error: crate::relay_info::InvalidTarget,
169

            
170
        /// The index of the IPT in the list of IPTs in the descriptor
171
        intro_index: IntroPtIndex,
172
    },
173

            
174
    /// Failed to obtain any circuit to use as a rendezvous circuit
175
    #[error("Failed to obtain any circuit to use as a rendezvous circuit")]
176
    RendezvousCircuitObtain {
177
        /// Why it's not use able
178
        #[source]
179
        error: tor_circmgr::Error,
180
    },
181

            
182
    /// Creating a rendezvous circuit and rendezvous point took too long
183
    #[error("Creating a rendezvous circuit and rendezvous point took too long")]
184
    RendezvousEstablishTimeout {
185
        /// Which relay did we choose for rendezvous point
186
        // TODO #813 this should be Redacted<RelayDescription> or something
187
        rend_pt: RendPtIdentityForError,
188
    },
189

            
190
    /// Failed to establish rendezvous point
191
    #[error("Failed to establish rendezvous point at {rend_pt}")]
192
    RendezvousEstablish {
193
        /// What happened
194
        #[source]
195
        error: tor_proto::Error,
196

            
197
        /// Which relay did we choose for rendezvous point
198
        // TODO #813 this should be Redacted<RelayDescription> or something
199
        rend_pt: RendPtIdentityForError,
200
    },
201

            
202
    /// Failed to obtain circuit to introduction point
203
    #[error("Failed to obtain circuit to introduction point {intro_index}")]
204
    IntroductionCircuitObtain {
205
        /// What happened
206
        #[source]
207
        error: tor_circmgr::Error,
208

            
209
        /// The index of the IPT in the list of IPTs in the descriptor
210
        intro_index: IntroPtIndex,
211
    },
212

            
213
    /// Introduction exchange (with the introduction point) failed
214
    #[error("Introduction exchange (with the introduction point) failed")]
215
    IntroductionExchange {
216
        /// What happened
217
        #[source]
218
        error: tor_proto::Error,
219

            
220
        /// The index of the IPT in the list of IPTs in the descriptor
221
        intro_index: IntroPtIndex,
222
    },
223

            
224
    /// Introduction point reported error in its INTRODUCE_ACK
225
    #[error("Introduction point {intro_index} reported error in its INTRODUCE_ACK: {status}")]
226
    IntroductionFailed {
227
        /// The status code provided by the introduction point
228
        status: IntroduceAckStatus,
229

            
230
        /// The index of the IPT in the list of IPTs in the descriptor
231
        intro_index: IntroPtIndex,
232
    },
233

            
234
    /// Communication with introduction point {intro_index} took too long
235
    ///
236
    /// This might mean it took too long to establish a circuit to the IPT,
237
    /// or that the INTRODUCE exchange took too long.
238
    #[error("Communication with introduction point {intro_index} took too long")]
239
    IntroductionTimeout {
240
        /// The index of the IPT in the list of IPTs in the descriptor
241
        intro_index: IntroPtIndex,
242
    },
243

            
244
    /// It took too long for the rendezvous to be completed
245
    ///
246
    /// This might be the fault of almost anyone.  All we know is that we got
247
    /// a successful `INTRODUCE_ACK` but the `RENDEZVOUS2` never arrived.
248
    #[error("Rendezvous at {rend_pt} using introduction point {intro_index} took too long")]
249
    RendezvousCompletionTimeout {
250
        /// The index of the IPT in the list of IPTs in the descriptor
251
        intro_index: IntroPtIndex,
252

            
253
        /// Which relay did we choose for rendezvous point
254
        // TODO #813 this should be Redacted<RelayDescription> or something
255
        rend_pt: RendPtIdentityForError,
256
    },
257

            
258
    /// Error on rendezvous circuit when expecting rendezvous completion (`RENDEZVOUS2`)
259
    #[error(
260
        "Error on rendezvous circuit when expecting rendezvous completion (RENDEZVOUS2 message)"
261
    )]
262
    RendezvousCompletionCircuitError {
263
        /// What happened
264
        #[source]
265
        error: tor_proto::Error,
266

            
267
        /// The index of the IPT in the list of IPTs in the descriptor
268
        intro_index: IntroPtIndex,
269

            
270
        /// Which relay did we choose for rendezvous point
271
        // TODO #813 this should be Redacted<RelayDescription> or something
272
        rend_pt: RendPtIdentityForError,
273
    },
274

            
275
    /// Error processing rendezvous completion (`RENDEZVOUS2`)
276
    ///
277
    /// This is might be the fault of the hidden service or the rendezvous point.
278
    #[error("Rendezvous completion end-to-end crypto handshake failed (bad RENDEZVOUS2 message)")]
279
    RendezvousCompletionHandshake {
280
        /// What happened
281
        #[source]
282
        error: tor_proto::Error,
283

            
284
        /// The index of the IPT in the list of IPTs in the descriptor
285
        intro_index: IntroPtIndex,
286

            
287
        /// Which relay did we choose for rendezvous point
288
        // TODO #813 this should be Redacted<RelayDescription> or something
289
        rend_pt: RendPtIdentityForError,
290
    },
291

            
292
    /// Internal error
293
    #[error("{0}")]
294
    Bug(#[from] Bug),
295
}
296
define_asref_dyn_std_error!(FailedAttemptError);
297

            
298
impl FailedAttemptError {
299
    /// Which introduction point did this error involve (or implicate), if any?
300
    ///
301
    /// This is an index into the table in the HS descriptor,
302
    /// so it can be less-than-useful outside the context where this error was generated.
303
    // TODO derive this, too much human error possibility
304
166
    pub(crate) fn intro_index(&self) -> Option<IntroPtIndex> {
305
        use FailedAttemptError as FAE;
306
166
        match self {
307
            FAE::UnusableIntro { intro_index, .. }
308
            | FAE::RendezvousCompletionCircuitError { intro_index, .. }
309
            | FAE::RendezvousCompletionHandshake { intro_index, .. }
310
            | FAE::RendezvousCompletionTimeout { intro_index, .. }
311
            | FAE::IntroductionCircuitObtain { intro_index, .. }
312
            | FAE::IntroductionExchange { intro_index, .. }
313
166
            | FAE::IntroductionFailed { intro_index, .. }
314
166
            | FAE::IntroductionTimeout { intro_index, .. } => Some(*intro_index),
315
            FAE::RendezvousCircuitObtain { .. }
316
            | FAE::RendezvousEstablish { .. }
317
            | FAE::RendezvousEstablishTimeout { .. }
318
            | FAE::Bug(_) => None,
319
        }
320
166
    }
321
}
322

            
323
/// When *an attempt like this* should be retried.
324
///
325
/// For error variants with an introduction point index
326
/// (`FailedAttemptError::intro_index` returns `Some`)
327
/// that's when we might retry *with that introduction point*.
328
///
329
/// For error variants with a rendezvous point,
330
/// that's when we might retry *with that rendezvous point*.
331
///
332
/// For variants with both, we don't know
333
/// which of the introduction point or rendezvous point is implicated.
334
/// Retrying earlier with *one* different relay out of the two relays would be reasonable,
335
/// as would delaying retrying with *either* of the same relays.
336
//
337
// Our current code doesn't keep history about rendezvous points.
338
// We use this to choose what order to try the service's introduction points.
339
// See `IptSortKey` in connect.rs.
340
impl HasRetryTime for FailedAttemptError {
341
166
    fn retry_time(&self) -> RetryTime {
342
        use FailedAttemptError as FAE;
343
        use RetryTime as RT;
344
166
        match self {
345
            // Delegate to the cause
346
            FAE::UnusableIntro { error, .. } => error.retry_time(),
347
            FAE::RendezvousCircuitObtain { error } => error.retry_time(),
348
            FAE::IntroductionCircuitObtain { error, .. } => error.retry_time(),
349
166
            FAE::IntroductionFailed { status, .. } => status.retry_time(),
350
            // tor_proto::Error doesn't impl HasRetryTime, so we guess
351
            FAE::RendezvousCompletionCircuitError { error: _e, .. }
352
            | FAE::IntroductionExchange { error: _e, .. }
353
            | FAE::RendezvousEstablish { error: _e, .. } => RT::AfterWaiting,
354
            // Timeouts
355
            FAE::RendezvousEstablishTimeout { .. }
356
            | FAE::RendezvousCompletionTimeout { .. }
357
            | FAE::IntroductionTimeout { .. } => RT::AfterWaiting,
358
            // Other cases where we define the ErrorKind ourselves
359
            // If service didn't cause this, it was the RPT, so prefer to try another RPT
360
            FAE::RendezvousCompletionHandshake { error: _e, .. } => RT::Never,
361
            FAE::Bug(_) => RT::Never,
362
        }
363
166
    }
364
}
365

            
366
impl HasKind for ConnError {
367
    fn kind(&self) -> ErrorKind {
368
        use ConnError as CE;
369
        use ErrorKind as EK;
370
        match self {
371
            CE::InvalidHsId => EK::InvalidStreamTarget,
372
            CE::NoHsDirs => EK::TorDirectoryUnusable,
373
            CE::NoUsableIntroPoints => EK::OnionServiceProtocolViolation,
374
            CE::Spawn { cause, .. } => cause.kind(),
375
            CE::Bug(e) => e.kind(),
376

            
377
            CE::DescriptorDownload(attempts) => attempts
378
                .sources()
379
                .max_by_key(|attempt| DescriptorErrorDetailDiscriminants::from(&attempt.0.error))
380
                .map(|attempt| attempt.0.kind())
381
                .unwrap_or_else(|| {
382
                    let bug = internal!("internal error, empty CE::DescriptorDownload");
383
                    error!("bug: {}", bug.report());
384
                    bug.kind()
385
                }),
386

            
387
            CE::NoUsableHsDirs => EK::OnionServiceConnectionFailed,
388

            
389
            CE::Failed(attempts) => attempts
390
                .sources()
391
                .max_by_key(|attempt| FailedAttemptErrorDiscriminants::from(*attempt))
392
                .map(|attempt| attempt.kind())
393
                .unwrap_or_else(|| {
394
                    let bug = internal!("internal error, empty CE::DescriptorDownload");
395
                    error!("bug: {}", bug.report());
396
                    bug.kind()
397
                }),
398
        }
399
    }
400
}
401

            
402
impl HasKind for DescriptorError {
403
    fn kind(&self) -> ErrorKind {
404
        self.error.kind()
405
    }
406
}
407

            
408
impl HasKind for DescriptorErrorDetail {
409
    fn kind(&self) -> ErrorKind {
410
        use DescriptorErrorDetail as DED;
411
        use ErrorKind as EK;
412
        use tor_dirclient::RequestError as RE;
413
        match self {
414
            DED::Timeout => EK::TorNetworkTimeout,
415
            DED::Circuit(e) => e.kind(),
416
            DED::Stream(e) => e.kind(),
417
            DED::Directory(RE::HttpStatus(st, _)) if *st == 404 => EK::OnionServiceNotFound,
418
            DED::Directory(RE::ResponseTooLong(_)) => EK::OnionServiceProtocolViolation,
419
            DED::Directory(RE::HeadersTooLong(_)) => EK::OnionServiceProtocolViolation,
420
            DED::Directory(RE::Utf8Encoding(_)) => EK::OnionServiceProtocolViolation,
421
            DED::Directory(other_re) => other_re.kind(),
422
            DED::ParameterMismatch(_) => EK::OnionServiceProtocolViolation,
423
            DED::Descriptor(e) => e.kind(),
424
            DED::Bug(e) => e.kind(),
425
        }
426
    }
427
}
428

            
429
impl HasKind for FailedAttemptError {
430
166
    fn kind(&self) -> ErrorKind {
431
        /*use tor_dirclient::RequestError as RE;
432
        use tor_netdoc::NetdocErrorKind as NEK;
433
        use DescriptorErrorDetail as DED;*/
434
        use ErrorKind as EK;
435
        use FailedAttemptError as FAE;
436
166
        match self {
437
            FAE::UnusableIntro { .. } => EK::OnionServiceProtocolViolation,
438
            FAE::RendezvousCircuitObtain { error, .. } => error.kind(),
439
            FAE::RendezvousEstablish { error, .. } => error.kind(),
440
            FAE::RendezvousCompletionCircuitError { error, .. } => error.kind(),
441
            FAE::RendezvousCompletionHandshake { error, .. } => error.kind(),
442
            FAE::RendezvousEstablishTimeout { .. } => EK::TorNetworkTimeout,
443
            FAE::IntroductionCircuitObtain { error, .. } => error.kind(),
444
            FAE::IntroductionExchange { error, .. } => error.kind(),
445
166
            FAE::IntroductionFailed { .. } => EK::OnionServiceConnectionFailed,
446
            FAE::IntroductionTimeout { .. } => EK::TorNetworkTimeout,
447
            FAE::RendezvousCompletionTimeout { .. } => EK::RemoteNetworkTimeout,
448
            FAE::Bug(e) => e.kind(),
449
        }
450
166
    }
451
}
452

            
453
/// Error that occurred attempting to start up a hidden service client connector
454
#[derive(Error, Clone, Debug)]
455
#[non_exhaustive]
456
pub enum StartupError {
457
    /// Unable to spawn
458
    #[error("Unable to spawn {spawning}")]
459
    Spawn {
460
        /// What we were trying to spawn
461
        spawning: &'static str,
462
        /// What happened when we tried to spawn it
463
        #[source]
464
        cause: Arc<SpawnError>,
465
    },
466

            
467
    /// Internal error
468
    #[error("{0}")]
469
    Bug(#[from] Bug),
470
}
471

            
472
impl HasKind for StartupError {
473
    fn kind(&self) -> ErrorKind {
474
        use StartupError as SE;
475
        match self {
476
            SE::Spawn { cause, .. } => cause.kind(),
477
            SE::Bug(e) => e.kind(),
478
        }
479
    }
480
}
481

            
482
/// Error that occurred while trying to solve a proof of work puzzle
483
///
484
/// These errors will not prevent a connection from proceeding.
485
/// We may try a different proof of work scheme or none at all.
486
///
487
#[derive(Error, Clone, Debug)]
488
#[non_exhaustive]
489
pub(crate) enum ProofOfWorkError {
490
    /// Runtime error from a specific proof of work scheme
491
    #[error("Runtime error from client puzzle solver, #{0}")]
492
    Runtime(#[from] tor_hscrypto::pow::RuntimeError),
493

            
494
    /// Time-limited parameters are not valid
495
    #[error("Client puzzle parameters are not valid at this time")]
496
    TimeValidity(#[from] tor_checkable::TimeValidityError),
497

            
498
    /// Unexpectedly lost contact with solver
499
    #[error("Unexpectedly lost contact with solver task")]
500
    #[allow(dead_code)]
501
    SolverDisconnected,
502
}
503

            
504
impl DescriptorErrorDetail {
505
    /// Return true if this error is one that we should report as a suspicious event,
506
    /// along with the dirserver and description of the relevant document.
507
    pub(crate) fn should_report_as_suspicious(&self) -> bool {
508
        use DescriptorErrorDetail as E;
509
        match self {
510
            E::Timeout => false,
511
            E::Circuit(_) => false,
512
            E::Stream(_) => false, // TODO prop360
513
            E::ParameterMismatch(_) => false,
514
            E::Directory(e) => e.should_report_as_suspicious_if_anon(),
515
            E::Descriptor(e) => e.should_report_as_suspicious(),
516
            E::Bug(_) => false,
517
        }
518
    }
519
}