1
//! Code to construct paths through the Tor network
2
//!
3
//! TODO: I'm not sure this belongs in circmgr, but this is the best place
4
//! I can think of for now.  I'm also not sure this should be public.
5

            
6
pub(crate) mod dirpath;
7
pub(crate) mod exitpath;
8

            
9
// Care must be taken if/when we decide to make this pub.
10
//
11
// The `HsPathBuilder` exposes two path building functions,
12
// one that uses vanguards, and one that doesn't.
13
// We want to strongly encourage the use of the vanguards-aware
14
// version of the function whenever the `vanguards` feature is enabled,
15
// without breaking any of its existing non-vanguard uses.
16
#[cfg(feature = "hs-common")]
17
pub(crate) mod hspath;
18

            
19
use std::result::Result as StdResult;
20
use std::time::SystemTime;
21

            
22
use rand::Rng;
23

            
24
use tor_dircommon::fallback::FallbackDir;
25
use tor_error::{Bug, bad_api_usage, internal};
26
#[cfg(feature = "geoip")]
27
use tor_geoip::{CountryCode, HasCountryCode};
28
use tor_guardmgr::{GuardMgr, GuardMonitor, GuardUsable};
29
use tor_linkspec::{HasAddrs, HasRelayIds, OwnedChanTarget, OwnedCircTarget, RelayIdSet};
30
use tor_netdir::{FamilyRules, NetDir, Relay};
31
use tor_relay_selection::{RelayExclusion, RelaySelectionConfig, RelaySelector, RelayUsage};
32
use tor_rtcompat::Runtime;
33

            
34
#[cfg(all(feature = "vanguards", feature = "hs-common"))]
35
use tor_guardmgr::vanguards::Vanguard;
36

            
37
use crate::usage::ExitPolicy;
38
use crate::{DirInfo, Error, PathConfig, Result};
39

            
40
/// A list of Tor relays through the network.
41
pub struct TorPath<'a> {
42
    /// The inner TorPath state.
43
    inner: TorPathInner<'a>,
44
}
45

            
46
/// Non-public helper type to represent the different kinds of Tor path.
47
///
48
/// (This is a separate type to avoid exposing its details to the user.)
49
///
50
/// NOTE: This type should NEVER be visible outside of path.rs and its
51
/// sub-modules.
52
enum TorPathInner<'a> {
53
    /// A single-hop path for use with a directory cache, when a relay is
54
    /// known.
55
    OneHop(Relay<'a>), // This could just be a routerstatus.
56
    /// A single-hop path for use with a directory cache, when we don't have
57
    /// a consensus.
58
    FallbackOneHop(&'a FallbackDir),
59
    /// A single-hop path taken from an OwnedChanTarget.
60
    OwnedOneHop(OwnedChanTarget),
61
    /// A multi-hop path, containing one or more relays.
62
    Path(Vec<MaybeOwnedRelay<'a>>),
63
}
64

            
65
/// Identifier for a relay that could be either known from a NetDir, or
66
/// specified as an OwnedCircTarget.
67
///
68
/// NOTE: This type should NEVER be visible outside of path.rs and its
69
/// sub-modules.
70
#[derive(Clone)]
71
enum MaybeOwnedRelay<'a> {
72
    /// A relay from the netdir.
73
    Relay(Relay<'a>),
74
    /// An owned description of a relay.
75
    //
76
    // TODO: I don't love boxing this, but it fixes a warning about
77
    // variant sizes and is probably not the worst thing we could do.  OTOH, we
78
    // could probably afford to use an Arc here and in guardmgr? -nickm
79
    //
80
    // TODO: Try using an Arc. -nickm
81
    Owned(Box<OwnedCircTarget>),
82
}
83

            
84
impl<'a> MaybeOwnedRelay<'a> {
85
    /// Extract an OwnedCircTarget from this relay.
86
74716
    fn to_owned(&self) -> OwnedCircTarget {
87
74716
        match self {
88
74716
            MaybeOwnedRelay::Relay(r) => OwnedCircTarget::from_circ_target(r),
89
            MaybeOwnedRelay::Owned(o) => o.as_ref().clone(),
90
        }
91
74716
    }
92
}
93

            
94
impl<'a> From<OwnedCircTarget> for MaybeOwnedRelay<'a> {
95
    fn from(ct: OwnedCircTarget) -> Self {
96
        MaybeOwnedRelay::Owned(Box::new(ct))
97
    }
98
}
99
impl<'a> From<Relay<'a>> for MaybeOwnedRelay<'a> {
100
74176
    fn from(r: Relay<'a>) -> Self {
101
74176
        MaybeOwnedRelay::Relay(r)
102
74176
    }
103
}
104
impl<'a> HasAddrs for MaybeOwnedRelay<'a> {
105
    fn addrs(&self) -> &[std::net::SocketAddr] {
106
        match self {
107
            MaybeOwnedRelay::Relay(r) => r.addrs(),
108
            MaybeOwnedRelay::Owned(r) => r.addrs(),
109
        }
110
    }
111
}
112
impl<'a> HasRelayIds for MaybeOwnedRelay<'a> {
113
588960
    fn identity(
114
588960
        &self,
115
588960
        key_type: tor_linkspec::RelayIdType,
116
588960
    ) -> Option<tor_linkspec::RelayIdRef<'_>> {
117
588960
        match self {
118
588960
            MaybeOwnedRelay::Relay(r) => r.identity(key_type),
119
            MaybeOwnedRelay::Owned(r) => r.identity(key_type),
120
        }
121
588960
    }
122
}
123

            
124
#[cfg(all(feature = "vanguards", feature = "hs-common"))]
125
impl<'a> From<Vanguard<'a>> for MaybeOwnedRelay<'a> {
126
80
    fn from(r: Vanguard<'a>) -> Self {
127
80
        MaybeOwnedRelay::Relay(r.relay().clone())
128
80
    }
129
}
130

            
131
impl<'a> TorPath<'a> {
132
    /// Create a new one-hop path for use with a directory cache with a known
133
    /// relay.
134
    pub fn new_one_hop(relay: Relay<'a>) -> Self {
135
        Self {
136
            inner: TorPathInner::OneHop(relay),
137
        }
138
    }
139

            
140
    /// Create a new one-hop path for use with a directory cache when we don't
141
    /// have a consensus.
142
    pub fn new_fallback_one_hop(fallback_dir: &'a FallbackDir) -> Self {
143
        Self {
144
            inner: TorPathInner::FallbackOneHop(fallback_dir),
145
        }
146
    }
147

            
148
    /// Construct a new one-hop path for directory use from an arbitrarily
149
    /// chosen channel target.
150
492
    pub fn new_one_hop_owned<T: tor_linkspec::ChanTarget>(target: &T) -> Self {
151
492
        Self {
152
492
            inner: TorPathInner::OwnedOneHop(OwnedChanTarget::from_chan_target(target)),
153
492
        }
154
492
    }
155

            
156
    /// Create a new multi-hop path with a given number of ordered relays.
157
    pub fn new_multihop(relays: impl IntoIterator<Item = Relay<'a>>) -> Self {
158
        Self {
159
            inner: TorPathInner::Path(relays.into_iter().map(MaybeOwnedRelay::from).collect()),
160
        }
161
    }
162
    /// Construct a new multi-hop path from a vector of `MaybeOwned`.
163
    ///
164
    /// Internal only; do not expose without fixing up this API a bit.
165
24728
    fn new_multihop_from_maybe_owned(relays: Vec<MaybeOwnedRelay<'a>>) -> Self {
166
24728
        Self {
167
24728
            inner: TorPathInner::Path(relays),
168
24728
        }
169
24728
    }
170

            
171
    /// Return the final relay in this path, if this is a path for use
172
    /// with exit circuits.
173
76
    fn exit_relay(&self) -> Option<&MaybeOwnedRelay<'a>> {
174
76
        match &self.inner {
175
76
            TorPathInner::Path(relays) if !relays.is_empty() => Some(&relays[relays.len() - 1]),
176
4
            _ => None,
177
        }
178
76
    }
179

            
180
    /// Return the exit policy of the final relay in this path, if this is a
181
    /// path for use with exit circuits with an exit taken from the network
182
    /// directory.
183
38
    pub(crate) fn exit_policy(&self) -> Option<ExitPolicy> {
184
56
        self.exit_relay().and_then(|r| match r {
185
36
            MaybeOwnedRelay::Relay(r) => Some(ExitPolicy::from_relay(r)),
186
            MaybeOwnedRelay::Owned(_) => None,
187
36
        })
188
38
    }
189

            
190
    /// Return the country code of the final relay in this path, if this is a
191
    /// path for use with exit circuits with an exit taken from the network
192
    /// directory.
193
    #[cfg(feature = "geoip")]
194
36
    pub(crate) fn country_code(&self) -> Option<CountryCode> {
195
54
        self.exit_relay().and_then(|r| match r {
196
36
            MaybeOwnedRelay::Relay(r) => r.country_code(),
197
            MaybeOwnedRelay::Owned(_) => None,
198
36
        })
199
36
    }
200

            
201
    /// Return the number of relays in this path.
202
    #[allow(clippy::len_without_is_empty)]
203
758
    pub fn len(&self) -> usize {
204
        use TorPathInner::*;
205
758
        match &self.inner {
206
            OneHop(_) => 1,
207
            FallbackOneHop(_) => 1,
208
12
            OwnedOneHop(_) => 1,
209
746
            Path(p) => p.len(),
210
        }
211
758
    }
212

            
213
    /// Return true if every `Relay` in this path has the stable flag.
214
    ///
215
    /// Assumes that Owned elements of this path are stable.
216
24
    pub(crate) fn appears_stable(&self) -> bool {
217
        // TODO #504: this looks at low_level_details() in questionable way.
218
24
        match &self.inner {
219
            TorPathInner::OneHop(r) => r.low_level_details().is_flagged_stable(),
220
            TorPathInner::FallbackOneHop(_) => true,
221
            TorPathInner::OwnedOneHop(_) => true,
222
84
            TorPathInner::Path(relays) => relays.iter().all(|maybe_owned| match maybe_owned {
223
72
                MaybeOwnedRelay::Relay(r) => r.low_level_details().is_flagged_stable(),
224
                MaybeOwnedRelay::Owned(_) => true,
225
72
            }),
226
        }
227
24
    }
228
}
229

            
230
/// A path composed entirely of owned components.
231
#[derive(Clone, Debug)]
232
pub(crate) enum OwnedPath {
233
    /// A path where we only know how to make circuits via CREATE_FAST.
234
    ChannelOnly(OwnedChanTarget),
235
    /// A path of one or more hops created via normal Tor handshakes.
236
    Normal(Vec<OwnedCircTarget>),
237
}
238

            
239
impl<'a> TryFrom<&TorPath<'a>> for OwnedPath {
240
    type Error = crate::Error;
241
24902
    fn try_from(p: &TorPath<'a>) -> Result<OwnedPath> {
242
        use TorPathInner::*;
243

            
244
24902
        Ok(match &p.inner {
245
            FallbackOneHop(h) => OwnedPath::ChannelOnly(OwnedChanTarget::from_chan_target(*h)),
246
            OneHop(h) => OwnedPath::Normal(vec![OwnedCircTarget::from_circ_target(h)]),
247
            OwnedOneHop(owned) => OwnedPath::ChannelOnly(owned.clone()),
248
24902
            Path(p) if !p.is_empty() => {
249
24900
                OwnedPath::Normal(p.iter().map(MaybeOwnedRelay::to_owned).collect())
250
            }
251
            Path(_) => {
252
2
                return Err(bad_api_usage!("Path with no entries!").into());
253
            }
254
        })
255
24902
    }
256
}
257

            
258
impl OwnedPath {
259
    /// Return the number of hops in this path.
260
    #[allow(clippy::len_without_is_empty)]
261
16
    pub(crate) fn len(&self) -> usize {
262
16
        match self {
263
4
            OwnedPath::ChannelOnly(_) => 1,
264
12
            OwnedPath::Normal(p) => p.len(),
265
        }
266
16
    }
267

            
268
    /// Return a reference to the first hop of this path, as an OwnedChanTarget.
269
16
    pub(crate) fn first_hop_as_chantarget(&self) -> &OwnedChanTarget {
270
16
        match self {
271
4
            OwnedPath::ChannelOnly(ct) => ct,
272
            // This access won't panic, since we enforce that path is nonempty.
273
12
            OwnedPath::Normal(path) => path[0].chan_target(),
274
        }
275
16
    }
276
}
277

            
278
/// A path builder that builds multi-hop, anonymous paths.
279
trait AnonymousPathBuilder {
280
    /// Return the "target" that every chosen relay must be able to share a circuit with with.
281
    fn compatible_with(&self) -> Option<&OwnedChanTarget>;
282

            
283
    /// Return a short description of the path we're trying to build,
284
    /// for error reporting purposes.
285
    fn path_kind(&self) -> &'static str;
286

            
287
    /// Find a suitable exit node from either the chosen exit or from the network directory.
288
    ///
289
    /// Return the exit, along with the usage for a middle node corresponding
290
    /// to this exit.
291
    fn pick_exit<'a, R: Rng>(
292
        &self,
293
        rng: &mut R,
294
        netdir: &'a NetDir,
295
        guard_exclusion: RelayExclusion<'a>,
296
        rs_cfg: &RelaySelectionConfig<'_>,
297
    ) -> Result<(Relay<'a>, RelayUsage)>;
298
}
299

            
300
/// Try to create and return a path corresponding to the requirements of
301
/// this builder.
302
24716
fn pick_path<'a, B: AnonymousPathBuilder, R: Rng, RT: Runtime>(
303
24716
    builder: &B,
304
24716
    rng: &mut R,
305
24716
    netdir: DirInfo<'a>,
306
24716
    guards: &GuardMgr<RT>,
307
24716
    config: &PathConfig,
308
24716
    _now: SystemTime,
309
24716
) -> Result<(TorPath<'a>, GuardMonitor, GuardUsable)> {
310
24716
    let netdir = match netdir {
311
24716
        DirInfo::Directory(d) => d,
312
        _ => {
313
            return Err(bad_api_usage!(
314
                "Tried to build a multihop path without a network directory"
315
            )
316
            .into());
317
        }
318
    };
319
24716
    let rs_cfg = config.relay_selection_config();
320
24716
    let family_rules = FamilyRules::from(netdir.params());
321

            
322
24716
    let target_exclusion = match builder.compatible_with() {
323
202
        Some(ct) => {
324
            // Exclude the target from appearing in other positions in the path.
325
404
            let ids = RelayIdSet::from_iter(ct.identities().map(|id_ref| id_ref.to_owned()));
326
            // TODO torspec#265: we do not apply same-family restrictions
327
            // (a relay in the same family as the target can occur in the path).
328
            //
329
            // We need to decide if this is the correct behavior,
330
            // and if so, document it in torspec.
331
202
            RelayExclusion::exclude_identities(ids)
332
        }
333
24514
        None => RelayExclusion::no_relays_excluded(),
334
    };
335

            
336
    // TODO-SPEC: Because of limitations in guard selection, we have to
337
    // pick the guard before the exit, which is not what our spec says.
338
24716
    let (guard, mon, usable) = select_guard(netdir, guards, builder.compatible_with())?;
339

            
340
24716
    let guard_exclusion = match &guard {
341
24716
        MaybeOwnedRelay::Relay(r) => RelayExclusion::exclude_relays_in_same_family(
342
24716
            &config.relay_selection_config(),
343
24716
            vec![r.clone()],
344
24716
            family_rules,
345
        ),
346
        MaybeOwnedRelay::Owned(ct) => RelayExclusion::exclude_channel_target_family(
347
            &config.relay_selection_config(),
348
            ct.as_ref(),
349
            netdir,
350
        ),
351
    };
352

            
353
24716
    let mut exclusion = guard_exclusion.clone();
354
24716
    exclusion.extend(&target_exclusion);
355
24716
    let (exit, middle_usage) = builder.pick_exit(rng, netdir, exclusion, &rs_cfg)?;
356

            
357
24690
    let mut family_exclusion =
358
24690
        RelayExclusion::exclude_relays_in_same_family(&rs_cfg, vec![exit.clone()], family_rules);
359
24690
    family_exclusion.extend(&guard_exclusion);
360
24690
    let mut exclusion = family_exclusion;
361
24690
    exclusion.extend(&target_exclusion);
362

            
363
24690
    let selector = RelaySelector::new(middle_usage, exclusion);
364
24690
    let (middle, info) = selector.select_relay(rng, netdir);
365
24690
    let middle = middle.ok_or_else(|| Error::NoRelay {
366
2
        path_kind: builder.path_kind(),
367
        role: "middle relay",
368
2
        problem: info.to_string(),
369
2
    })?;
370

            
371
24688
    let hops = vec![
372
24688
        guard,
373
24688
        MaybeOwnedRelay::from(middle),
374
24688
        MaybeOwnedRelay::from(exit),
375
    ];
376

            
377
24688
    ensure_unique_hops(&hops)?;
378

            
379
24688
    Ok((TorPath::new_multihop_from_maybe_owned(hops), mon, usable))
380
24716
}
381

            
382
/// Returns an error if the specified hop list contains duplicates.
383
24688
fn ensure_unique_hops<'a>(hops: &'a [MaybeOwnedRelay<'a>]) -> StdResult<(), Bug> {
384
74064
    for (i, hop) in hops.iter().enumerate() {
385
74064
        if let Some(hop2) = hops
386
74064
            .iter()
387
74064
            .skip(i + 1)
388
111096
            .find(|hop2| hop.clone().has_any_relay_id_from(*hop2))
389
        {
390
            return Err(internal!(
391
                "invalid path: the IDs of hops {} and {} overlap?!",
392
                hop.display_relay_ids(),
393
                hop2.display_relay_ids()
394
            ));
395
74064
        }
396
    }
397
24688
    Ok(())
398
24688
}
399

            
400
/// Try to select a guard corresponding to the requirements of
401
/// this builder.
402
24772
fn select_guard<'a, RT: Runtime>(
403
24772
    netdir: &'a NetDir,
404
24772
    guardmgr: &GuardMgr<RT>,
405
24772
    compatible_with: Option<&OwnedChanTarget>,
406
24772
) -> Result<(MaybeOwnedRelay<'a>, GuardMonitor, GuardUsable)> {
407
    // TODO: Extract this section into its own function, and see
408
    // what it can share with tor_relay_selection.
409
24772
    let mut b = tor_guardmgr::GuardUsageBuilder::default();
410
24772
    b.kind(tor_guardmgr::GuardUsageKind::Data);
411
24772
    if let Some(avoid_target) = compatible_with {
412
202
        let mut family = RelayIdSet::new();
413
404
        family.extend(avoid_target.identities().map(|id| id.to_owned()));
414
202
        if let Some(avoid_relay) = netdir.by_ids(avoid_target) {
415
            family.extend(netdir.known_family_members(&avoid_relay).map(|r| *r.id()));
416
202
        }
417
202
        b.restrictions()
418
202
            .push(tor_guardmgr::GuardRestriction::AvoidAllIds(family));
419
24570
    }
420
24772
    let guard_usage = b.build().expect("Failed while building guard usage!");
421
24772
    let (guard, mon, usable) = guardmgr.select_guard(guard_usage)?;
422
24772
    let guard = if let Some(ct) = guard.as_circ_target() {
423
        // This is a bridge; we will not look for it in the network directory.
424
        MaybeOwnedRelay::from(ct.clone())
425
    } else {
426
        // Look this up in the network directory: we expect to find a relay.
427
24772
        guard
428
24772
            .get_relay(netdir)
429
24772
            .ok_or_else(|| {
430
                internal!(
431
                    "Somehow the guardmgr gave us an unlisted guard {:?}!",
432
                    guard
433
                )
434
            })?
435
24772
            .into()
436
    };
437
24772
    Ok((guard, mon, usable))
438
24772
}
439

            
440
/// For testing: make sure that `path` is the same when it is an owned
441
/// path.
442
#[cfg(test)]
443
24240
fn assert_same_path_when_owned(path: &TorPath<'_>) {
444
    #![allow(clippy::unwrap_used)]
445
24240
    let owned: OwnedPath = path.try_into().unwrap();
446

            
447
24240
    match (&owned, &path.inner) {
448
        (OwnedPath::ChannelOnly(c), TorPathInner::FallbackOneHop(f)) => {
449
            assert!(c.same_relay_ids(*f));
450
        }
451
        (OwnedPath::Normal(p), TorPathInner::OneHop(h)) => {
452
            assert_eq!(p.len(), 1);
453
            assert!(p[0].same_relay_ids(h));
454
        }
455
24240
        (OwnedPath::Normal(p1), TorPathInner::Path(p2)) => {
456
24240
            assert_eq!(p1.len(), p2.len());
457
72720
            for (n1, n2) in p1.iter().zip(p2.iter()) {
458
72720
                assert!(n1.same_relay_ids(n2));
459
            }
460
        }
461
        (_, _) => {
462
            panic!("Mismatched path types.");
463
        }
464
    }
465
24240
}