1
//! Code for building paths for HS circuits.
2
//!
3
//! The path builders defined here are used for creating hidden service circuit stems.
4
//! A circuit stem is the beginning portion of a hidden service circuit,
5
//! the structure of which depends on the types of vanguards, if any, that are in use.
6
//!
7
//! There are two types of circuit stems:
8
//!   * naive circuit stems, used for building circuits to a final hop that an adversary
9
//!     cannot easily control (for example if the target is randomly chosen by us)
10
//!   * guarded circuit stems, used for building circuits to a final hop that an adversary
11
//!     can easily control (for example if the target was not chosen by us)
12
//!
13
//! Circuit stems eventually become introduction, rendezvous, and HsDir circuits.
14
//! For all circuit types except client rendezvous, the stems must first be
15
//! extended by an extra hop:
16
//!
17
//! ```text
18
//!  Client hsdir:  GUARDED -> HsDir
19
//!  Client intro:  GUARDED -> Ipt
20
//!  Client rend:   GUARDED
21
//!  Service hsdir: NAIVE   -> HsDir
22
//!  Service intro: NAIVE   -> Ipt
23
//!  Service rend:  GUARDED -> Rpt
24
//! ```
25
//!
26
//! > Note: the client rendezvous case is an exception to this rule:
27
//! > the rendezvous point is selected by the client, so it cannot easily be
28
//! > controlled by an attacker.
29
//! >
30
//! > This type of circuit would more accurately be described as a NAIVE circuit
31
//! > that gets extended by an extra hop if Full-Vanguards are in use
32
//! > (this is necessary to avoid using the L3 guard as a rendezvous point).
33
//! > However, for the sake of simplicity, we define these circuits in terms of
34
//! > GUARDED.
35
//! >
36
//! > Note: in the client rendezvous case, the last node from the GUARDED
37
//! > circuit stem is the rendezvous point.
38
//!
39
//! If vanguards are disabled, naive circuit stems (NAIVE),
40
//! and guarded circuit stems (GUARDED) are the same,
41
//! and are built using
42
//! [`ExitPathBuilder`](crate::path::exitpath::ExitPathBuilder)'s
43
//! path selection rules.
44
//!
45
//! If vanguards are enabled, the path is built without applying family
46
//! or same-subnet restrictions at all, the guard is not prohibited
47
//! from appearing as either of the last two hops of the circuit,
48
//! and the two circuit stem kinds are built differently
49
//! depending on the type of vanguards that are in use:
50
//!
51
//!   * with lite vanguards enabled:
52
//!      ```text
53
//!         NAIVE   = G -> L2 -> M
54
//!         GUARDED = G -> L2 -> M
55
//!      ```
56
//!
57
//!   * with full vanguards enabled:
58
//!      ```text
59
//!         NAIVE   = G -> L2 -> L3
60
//!         GUARDED = G -> L2 -> L3 -> M
61
//!      ```
62

            
63
#[cfg(feature = "vanguards")]
64
mod vanguards;
65

            
66
use rand::Rng;
67
use tor_error::internal;
68
use tor_linkspec::{HasRelayIds, OwnedChanTarget};
69
use tor_netdir::{NetDir, Relay};
70
use tor_relay_selection::{RelayExclusion, RelaySelectionConfig, RelaySelector, RelayUsage};
71
use tracing::instrument;
72

            
73
use crate::{Error, Result, hspool::HsCircKind, hspool::HsCircStemKind};
74

            
75
use super::AnonymousPathBuilder;
76

            
77
use {
78
    crate::path::{TorPath, pick_path},
79
    crate::{DirInfo, PathConfig},
80
    std::time::SystemTime,
81
    tor_guardmgr::{GuardMgr, GuardMonitor, GuardUsable},
82
    tor_rtcompat::Runtime,
83
};
84

            
85
#[cfg(feature = "vanguards")]
86
use {
87
    crate::path::{MaybeOwnedRelay, select_guard},
88
    tor_error::bad_api_usage,
89
    tor_guardmgr::VanguardMode,
90
    tor_guardmgr::vanguards::Layer,
91
    tor_guardmgr::vanguards::VanguardMgr,
92
};
93

            
94
#[cfg(feature = "vanguards")]
95
pub(crate) use vanguards::select_middle_for_vanguard_circ;
96

            
97
/// A path builder for hidden service circuits.
98
///
99
/// See the [hspath](crate::path::hspath) docs for more details.
100
pub(crate) struct HsPathBuilder {
101
    /// If present, a "target" that every chosen relay must be able to share a circuit with with.
102
    ///
103
    /// Ignored if vanguards are in use.
104
    compatible_with: Option<OwnedChanTarget>,
105
    /// The type of circuit stem to build.
106
    ///
107
    /// This is only used if `vanguards` are enabled.
108
    #[cfg_attr(not(feature = "vanguards"), allow(dead_code))]
109
    stem_kind: HsCircStemKind,
110

            
111
    /// If present, ensure that the circuit stem is suitable for use as (a stem for) the given kind
112
    /// of circuit.
113
    circ_kind: Option<HsCircKind>,
114
}
115

            
116
impl HsPathBuilder {
117
    /// Create a new builder that will try to build a three-hop non-exit path
118
    /// for use with the onion services protocols
119
    /// that is compatible with being extended to an optional given relay.
120
    ///
121
    /// (The provided relay is _not_ included in the built path: we only ensure
122
    /// that the path we build does not have any features that would stop us
123
    /// extending it to that relay as a fourth hop.)
124
230
    pub(crate) fn new(
125
230
        compatible_with: Option<OwnedChanTarget>,
126
230
        stem_kind: HsCircStemKind,
127
230
        circ_kind: Option<HsCircKind>,
128
230
    ) -> Self {
129
230
        Self {
130
230
            compatible_with,
131
230
            stem_kind,
132
230
            circ_kind,
133
230
        }
134
230
    }
135

            
136
    /// Try to create and return a path for a hidden service circuit stem.
137
    #[cfg_attr(feature = "vanguards", allow(unused))]
138
    #[instrument(skip_all, level = "trace")]
139
202
    pub(crate) fn pick_path<'a, R: Rng, RT: Runtime>(
140
202
        &self,
141
202
        rng: &mut R,
142
202
        netdir: DirInfo<'a>,
143
202
        guards: &GuardMgr<RT>,
144
202
        config: &PathConfig,
145
202
        now: SystemTime,
146
202
    ) -> Result<(TorPath<'a>, GuardMonitor, GuardUsable)> {
147
202
        pick_path(self, rng, netdir, guards, config, now)
148
202
    }
149

            
150
    /// Try to create and return a path for a hidden service circuit stem.
151
    ///
152
    /// If vanguards are disabled, this has the same behavior as
153
    /// [pick_path](HsPathBuilder::pick_path).
154
    #[cfg(feature = "vanguards")]
155
    #[cfg_attr(not(feature = "vanguards"), allow(unused))]
156
    #[instrument(skip_all, level = "trace")]
157
28
    pub(crate) fn pick_path_with_vanguards<'a, R: Rng, RT: Runtime>(
158
28
        &self,
159
28
        rng: &mut R,
160
28
        netdir: DirInfo<'a>,
161
28
        guards: &GuardMgr<RT>,
162
28
        vanguards: &VanguardMgr<RT>,
163
28
        config: &PathConfig,
164
28
        now: SystemTime,
165
28
    ) -> Result<(TorPath<'a>, GuardMonitor, GuardUsable)> {
166
28
        let mode = vanguards.mode();
167
28
        if mode == VanguardMode::Disabled {
168
            return pick_path(self, rng, netdir, guards, config, now);
169
28
        }
170

            
171
28
        let vanguard_path_builder = VanguardHsPathBuilder {
172
28
            stem_kind: self.stem_kind,
173
28
            circ_kind: self.circ_kind,
174
28
            compatible_with: self.compatible_with.clone(),
175
28
        };
176

            
177
28
        vanguard_path_builder.pick_path(rng, netdir, guards, vanguards)
178
28
    }
179
}
180

            
181
impl AnonymousPathBuilder for HsPathBuilder {
182
404
    fn compatible_with(&self) -> Option<&OwnedChanTarget> {
183
404
        self.compatible_with.as_ref()
184
404
    }
185

            
186
2
    fn path_kind(&self) -> &'static str {
187
2
        "onion-service circuit"
188
2
    }
189

            
190
202
    fn pick_exit<'a, R: Rng>(
191
202
        &self,
192
202
        rng: &mut R,
193
202
        netdir: &'a NetDir,
194
202
        guard_exclusion: RelayExclusion<'a>,
195
202
        _rs_cfg: &RelaySelectionConfig<'_>,
196
202
    ) -> Result<(Relay<'a>, RelayUsage)> {
197
        let selector =
198
202
            RelaySelector::new(hs_stem_terminal_hop_usage(self.circ_kind), guard_exclusion);
199

            
200
202
        let (relay, info) = selector.select_relay(rng, netdir);
201
202
        let relay = relay.ok_or_else(|| Error::NoRelay {
202
1
            path_kind: self.path_kind(),
203
1
            role: "final hop",
204
1
            problem: info.to_string(),
205
1
        })?;
206
201
        Ok((relay, RelayUsage::middle_relay(Some(selector.usage()))))
207
202
    }
208
}
209

            
210
/// A path builder for hidden service circuits that use vanguards.
211
///
212
/// Used by [`HsPathBuilder`] when vanguards are enabled.
213
///
214
/// See the [`HsPathBuilder`] documentation for more details.
215
#[cfg(feature = "vanguards")]
216
struct VanguardHsPathBuilder {
217
    /// The kind of circuit stem we are building
218
    stem_kind: HsCircStemKind,
219
    /// If present, ensure that the circuit stem is suitable for use as (a stem for) the given kind
220
    /// of circuit.
221
    circ_kind: Option<HsCircKind>,
222
    /// The target we are about to extend the circuit to.
223
    compatible_with: Option<OwnedChanTarget>,
224
}
225

            
226
#[cfg(feature = "vanguards")]
227
impl VanguardHsPathBuilder {
228
    /// Try to create and return a path for a hidden service circuit stem.
229
    #[instrument(skip_all, level = "trace")]
230
28
    fn pick_path<'a, R: Rng, RT: Runtime>(
231
28
        &self,
232
28
        rng: &mut R,
233
28
        netdir: DirInfo<'a>,
234
28
        guards: &GuardMgr<RT>,
235
28
        vanguards: &VanguardMgr<RT>,
236
28
    ) -> Result<(TorPath<'a>, GuardMonitor, GuardUsable)> {
237
28
        let netdir = match netdir {
238
28
            DirInfo::Directory(d) => d,
239
            _ => {
240
                return Err(bad_api_usage!(
241
                    "Tried to build a multihop path without a network directory"
242
                )
243
                .into());
244
            }
245
        };
246

            
247
        // Select the guard, allowing it to appear as
248
        // either of the last two hops of the circuit.
249
28
        let (l1_guard, mon, usable) = select_guard(netdir, guards, None)?;
250

            
251
28
        let target_exclusion = if let Some(target) = self.compatible_with.as_ref() {
252
8
            RelayExclusion::exclude_identities(
253
8
                target.identities().map(|id| id.to_owned()).collect(),
254
            )
255
        } else {
256
20
            RelayExclusion::no_relays_excluded()
257
        };
258

            
259
28
        let mode = vanguards.mode();
260
28
        let path = match mode {
261
            VanguardMode::Lite => {
262
12
                self.pick_lite_vanguard_path(rng, netdir, vanguards, l1_guard, &target_exclusion)?
263
            }
264
            VanguardMode::Full => {
265
16
                self.pick_full_vanguard_path(rng, netdir, vanguards, l1_guard, &target_exclusion)?
266
            }
267
            VanguardMode::Disabled => {
268
                return Err(internal!(
269
                    "VanguardHsPathBuilder::pick_path called, but vanguards are disabled?!"
270
                )
271
                .into());
272
            }
273
            _ => {
274
                return Err(internal!("unrecognized vanguard mode {mode}").into());
275
            }
276
        };
277

            
278
20
        let actual_len = path.len();
279
20
        let expected_len = self.stem_kind.num_hops(mode)?;
280
20
        if actual_len != expected_len {
281
            return Err(internal!(
282
                "invalid path length for {} {mode}-vanguard circuit (expected {} hops, got {})",
283
                self.stem_kind,
284
                expected_len,
285
                actual_len
286
            )
287
            .into());
288
20
        }
289

            
290
20
        Ok((path, mon, usable))
291
28
    }
292

            
293
    /// Create a path for a hidden service circuit stem using full vanguards.
294
16
    fn pick_full_vanguard_path<'n, R: Rng, RT: Runtime>(
295
16
        &self,
296
16
        rng: &mut R,
297
16
        netdir: &'n NetDir,
298
16
        vanguards: &VanguardMgr<RT>,
299
16
        l1_guard: MaybeOwnedRelay<'n>,
300
16
        target_exclusion: &RelayExclusion<'n>,
301
16
    ) -> Result<TorPath<'n>> {
302
        // NOTE: if the we are using full vanguards and building an GUARDED circuit stem,
303
        // we do *not* exclude the target from occurring as the second hop
304
        // (circuits of the form G - L2 - L3 - M - L2 are valid)
305

            
306
16
        let l2_target_exclusion = match self.stem_kind {
307
8
            HsCircStemKind::Guarded => RelayExclusion::no_relays_excluded(),
308
8
            HsCircStemKind::Naive => target_exclusion.clone(),
309
        };
310
        // We have to pick the usage based on whether this hop is the last one of the stem.
311
16
        let l3_usage = match self.stem_kind {
312
8
            HsCircStemKind::Naive => hs_stem_terminal_hop_usage(self.circ_kind),
313
8
            HsCircStemKind::Guarded => hs_intermediate_hop_usage(),
314
        };
315
16
        let l2_selector = RelaySelector::new(hs_intermediate_hop_usage(), l2_target_exclusion);
316
16
        let l3_selector = RelaySelector::new(l3_usage, target_exclusion.clone());
317

            
318
16
        let path = vanguards::PathBuilder::new(rng, netdir, vanguards, l1_guard);
319

            
320
16
        let path = path
321
16
            .add_vanguard(&l2_selector, Layer::Layer2)?
322
16
            .add_vanguard(&l3_selector, Layer::Layer3)?;
323

            
324
12
        match self.stem_kind {
325
            HsCircStemKind::Guarded => {
326
                // If full vanguards are enabled, we need an extra hop for the GUARDED stem:
327
                //     NAIVE   = G -> L2 -> L3
328
                //     GUARDED = G -> L2 -> L3 -> M
329

            
330
6
                let mid_selector = RelaySelector::new(
331
6
                    hs_stem_terminal_hop_usage(self.circ_kind),
332
6
                    target_exclusion.clone(),
333
6
                );
334
6
                path.add_middle(&mid_selector)?.build()
335
            }
336
6
            HsCircStemKind::Naive => path.build(),
337
        }
338
16
    }
339

            
340
    /// Create a path for a hidden service circuit stem using lite vanguards.
341
12
    fn pick_lite_vanguard_path<'n, R: Rng, RT: Runtime>(
342
12
        &self,
343
12
        rng: &mut R,
344
12
        netdir: &'n NetDir,
345
12
        vanguards: &VanguardMgr<RT>,
346
12
        l1_guard: MaybeOwnedRelay<'n>,
347
12
        target_exclusion: &RelayExclusion<'n>,
348
12
    ) -> Result<TorPath<'n>> {
349
12
        let l2_selector = RelaySelector::new(hs_intermediate_hop_usage(), target_exclusion.clone());
350
12
        let mid_selector = RelaySelector::new(
351
12
            hs_stem_terminal_hop_usage(self.circ_kind),
352
12
            target_exclusion.clone(),
353
12
        );
354

            
355
12
        vanguards::PathBuilder::new(rng, netdir, vanguards, l1_guard)
356
12
            .add_vanguard(&l2_selector, Layer::Layer2)?
357
12
            .add_middle(&mid_selector)?
358
            .build()
359
12
    }
360
}
361

            
362
/// Return the usage that we should use when selecting an intermediary hop (vanguard or middle) of
363
/// an HS circuit or stem circuit.
364
///
365
/// (This isn't called "middle hop", since we want to avoid confusion with the M hop in vanguard
366
/// circuits.)
367
264
pub(crate) fn hs_intermediate_hop_usage() -> RelayUsage {
368
    // Restrict our intermediary relays to the set of middle relays we could use when building a new
369
    // intro circuit.
370

            
371
    // TODO: This usage is a bit convoluted, and some onion-service-
372
    // related circuits don't really need this much stability.
373
    //
374
    // TODO: new_intro_point() isn't really accurate here, but it _is_
375
    // the most restrictive target-usage we can use.
376
264
    RelayUsage::middle_relay(Some(&RelayUsage::new_intro_point()))
377
264
}
378

            
379
/// Return the usage that we should use when selecting the last hop of a stem circuit.
380
///
381
/// If `kind` is provided, we need to make sure that the last hop will yield a stem circuit
382
/// that's fit for that kind of circuit.
383
228
pub(crate) fn hs_stem_terminal_hop_usage(kind: Option<HsCircKind>) -> RelayUsage {
384
228
    let Some(kind) = kind else {
385
        // For unknown HsCircKinds, we'll pick an arbitrary last hop, and check later
386
        // that it is really suitable for whatever purpose we had in mind.
387
228
        return hs_intermediate_hop_usage();
388
    };
389
    match kind {
390
        HsCircKind::ClientRend => {
391
            // This stem circuit going to get used as-is for a ClientRend circuit,
392
            // and so the last hop of the stem circuit needs to be suitable as a rendezvous point.
393
            RelayUsage::new_rend_point()
394
        }
395
        HsCircKind::SvcHsDir
396
        | HsCircKind::SvcIntro
397
        | HsCircKind::SvcRend
398
        | HsCircKind::ClientHsDir
399
        | HsCircKind::ClientIntro => {
400
            // For all other HSCircKind cases, the last hop will be added to the stem,
401
            // so we have no additional restrictions on the usage.
402
            hs_intermediate_hop_usage()
403
        }
404
    }
405
228
}
406

            
407
#[cfg(test)]
408
mod test {
409
    // @@ begin test lint list maintained by maint/add_warning @@
410
    #![allow(clippy::bool_assert_comparison)]
411
    #![allow(clippy::clone_on_copy)]
412
    #![allow(clippy::dbg_macro)]
413
    #![allow(clippy::mixed_attributes_style)]
414
    #![allow(clippy::print_stderr)]
415
    #![allow(clippy::print_stdout)]
416
    #![allow(clippy::single_char_pattern)]
417
    #![allow(clippy::unwrap_used)]
418
    #![allow(clippy::unchecked_time_subtraction)]
419
    #![allow(clippy::useless_vec)]
420
    #![allow(clippy::needless_pass_by_value)]
421
    #![allow(clippy::string_slice)] // See arti#2571
422
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
423

            
424
    use std::sync::Arc;
425

            
426
    use super::*;
427

            
428
    use tor_linkspec::{ChannelMethod, OwnedCircTarget};
429
    use tor_llcrypto::pk::ed25519::Ed25519Identity;
430
    use tor_netdir::{NetDirProvider, testnet::NodeBuilders, testprovider::TestNetDirProvider};
431
    use tor_netdoc::types::relay_flags::RelayFlag;
432
    use tor_netdoc::{doc::netstatus::RelayBandwidth, types::family::HappyFamilyId};
433
    use tor_rtcompat::SleepProvider as _;
434
    use tor_rtmock::MockRuntime;
435

            
436
    #[cfg(all(feature = "vanguards", feature = "hs-common"))]
437
    use {
438
        crate::path::OwnedPath, tor_basic_utils::test_rng::testing_rng,
439
        tor_guardmgr::VanguardMgrError, tor_netdir::testnet::construct_custom_netdir,
440
    };
441

            
442
    /// The maximum number of relays in a test network.
443
    const MAX_NET_SIZE: usize = 40;
444

            
445
    /// Construct a test network of the specified size.
446
    fn construct_test_network<F>(size: usize, mut set_family: F) -> NetDir
447
    where
448
        F: FnMut(usize, &mut NodeBuilders),
449
    {
450
        assert!(
451
            size <= MAX_NET_SIZE,
452
            "the test network supports at most {MAX_NET_SIZE} relays"
453
        );
454
        let netdir = construct_custom_netdir(|pos, nb, _| {
455
            nb.omit_rs = pos >= size;
456
            if !nb.omit_rs {
457
                let f = RelayFlag::Running
458
                    | RelayFlag::Valid
459
                    | RelayFlag::V2Dir
460
                    | RelayFlag::Fast
461
                    | RelayFlag::Stable;
462
                nb.rs.set_flags(f | RelayFlag::Guard);
463
                nb.rs.weight(RelayBandwidth::Measured(10_000));
464

            
465
                set_family(pos, nb);
466
            }
467
        })
468
        .unwrap()
469
        .unwrap_if_sufficient()
470
        .unwrap();
471

            
472
        assert_eq!(netdir.all_relays().count(), size);
473

            
474
        netdir
475
    }
476

            
477
    /// Construct a test network where every relay is in the same family with everyone else.
478
    fn same_family_test_network(size: usize) -> NetDir {
479
        let family_id = HappyFamilyId::Ed25519(Ed25519Identity::from([12; 32]));
480
        construct_test_network(size, |_pos, nb| {
481
            // Everybody is in the same family with everyone else
482
            nb.md.add_family_id(family_id.clone());
483
        })
484
    }
485

            
486
    /// Helper for extracting the hops in a `TorPath`.
487
    fn path_hops(path: &TorPath) -> Vec<OwnedCircTarget> {
488
        let path: OwnedPath = path.try_into().unwrap();
489
        match path {
490
            OwnedPath::ChannelOnly(_) => {
491
                panic!("expected OwnedPath::Normal, got OwnedPath::ChannelOnly")
492
            }
493
            OwnedPath::Normal(ref v) => v.clone(),
494
        }
495
    }
496

            
497
    /// Check the uniqueness of the hops from the specified `TorPath`.
498
    ///
499
    /// If `expect_dupes` is `true`, asserts that the path has some duplicate hops.
500
    /// Otherwise, asserts that there are no duplicate hops in the path.
501
    fn assert_duplicate_hops(path: &TorPath, expect_dupes: bool) {
502
        let hops = path_hops(path);
503
        let has_dupes = hops.iter().enumerate().any(|(i, hop)| {
504
            hops.iter()
505
                .skip(i + 1)
506
                .any(|h| h.has_any_relay_id_from(hop))
507
        });
508
        let msg = if expect_dupes { "have" } else { "not have any" };
509

            
510
        assert_eq!(
511
            has_dupes, expect_dupes,
512
            "expected path to {msg} duplicate hops: {:?}",
513
            hops
514
        );
515
    }
516

            
517
    /// Assert that the specified `TorPath` is a valid path for a circuit using vanguards.
518
    #[cfg(feature = "vanguards")]
519
    fn assert_vanguard_path_ok(
520
        path: &TorPath,
521
        stem_kind: HsCircStemKind,
522
        mode: VanguardMode,
523
        target: Option<&OwnedChanTarget>,
524
    ) {
525
        use itertools::Itertools;
526

            
527
        assert_eq!(
528
            path.len(),
529
            stem_kind.num_hops(mode).unwrap(),
530
            "invalid path length for {stem_kind} {mode}-vanguards circuit"
531
        );
532

            
533
        let hops = path_hops(path);
534
        for (hop1, hop2, hop3) in hops.iter().tuple_windows() {
535
            if hop1.has_any_relay_id_from(hop2)
536
                || hop1.has_any_relay_id_from(hop3)
537
                || hop2.has_any_relay_id_from(hop3)
538
            {
539
                panic!(
540
                    "neighboring hops should be distinct: [{}], [{}], [{}]",
541
                    hop1.display_relay_ids(),
542
                    hop2.display_relay_ids(),
543
                    hop3.display_relay_ids(),
544
                );
545
            }
546
        }
547

            
548
        // If the circuit had a target, make sure its last 2 hops are compatible with it.
549
        if let Some(target) = target {
550
            for hop in hops.iter().rev().take(2) {
551
                if hop.has_any_relay_id_from(target) {
552
                    panic!(
553
                        "invalid path: circuit target {} appears as one of the last 2 hops (matches hop {})",
554
                        hop.display_relay_ids(),
555
                        target.display_relay_ids(),
556
                    );
557
                }
558
            }
559
        }
560
    }
561

            
562
    /// Assert that the specified `TorPath` is a valid HS path.
563
    fn assert_hs_path_ok(path: &TorPath, target: Option<&OwnedChanTarget>) {
564
        assert_eq!(path.len(), 3);
565
        assert_duplicate_hops(path, false);
566
        if let Some(target) = target {
567
            for hop in path_hops(path) {
568
                if hop.has_any_relay_id_from(target) {
569
                    panic!(
570
                        "invalid path: hop {} is the same relay as the circuit target {}",
571
                        hop.display_relay_ids(),
572
                        target.display_relay_ids()
573
                    )
574
                }
575
            }
576
        }
577
    }
578

            
579
    /// Helper for calling `HsPathBuilder::pick_path_with_vanguards`.
580
    async fn pick_vanguard_path<'a>(
581
        runtime: &MockRuntime,
582
        netdir: &'a NetDir,
583
        stem_kind: HsCircStemKind,
584
        circ_kind: Option<HsCircKind>,
585
        mode: VanguardMode,
586
        target: Option<&OwnedChanTarget>,
587
    ) -> Result<TorPath<'a>> {
588
        let vanguardmgr = VanguardMgr::new_testing(runtime, mode).unwrap();
589
        let _provider = vanguardmgr.init_vanguard_sets(netdir).await.unwrap();
590

            
591
        let mut rng = testing_rng();
592
        let guards = tor_guardmgr::GuardMgr::new(
593
            runtime.clone(),
594
            tor_persist::TestingStateMgr::new(),
595
            &tor_guardmgr::TestConfig::default(),
596
        )
597
        .unwrap();
598
        let netdir_provider = Arc::new(TestNetDirProvider::new());
599
        netdir_provider.set_netdir(netdir.clone());
600
        let netdir_provider: Arc<dyn NetDirProvider> = netdir_provider;
601
        guards.install_netdir_provider(&netdir_provider).unwrap();
602
        let config = PathConfig::default();
603
        let now = runtime.wallclock();
604
        let dirinfo = (netdir).into();
605
        HsPathBuilder::new(target.cloned(), stem_kind, circ_kind)
606
            .pick_path_with_vanguards(&mut rng, dirinfo, &guards, &vanguardmgr, &config, now)
607
            .map(|res| res.0)
608
    }
609

            
610
    /// Helper for calling `HsPathBuilder::pick_path`.
611
    fn pick_hs_path_no_vanguards<'a>(
612
        netdir: &'a NetDir,
613
        target: Option<&OwnedChanTarget>,
614
        circ_kind: Option<HsCircKind>,
615
    ) -> Result<TorPath<'a>> {
616
        let mut rng = testing_rng();
617
        let config = PathConfig::default();
618
        let runtime = MockRuntime::new();
619
        let now = runtime.wallclock();
620
        let dirinfo = (netdir).into();
621
        let guards = tor_guardmgr::GuardMgr::new(
622
            runtime,
623
            tor_persist::TestingStateMgr::new(),
624
            &tor_guardmgr::TestConfig::default(),
625
        )
626
        .unwrap();
627
        let netdir_provider = Arc::new(TestNetDirProvider::new());
628
        netdir_provider.set_netdir(netdir.clone());
629
        let netdir_provider: Arc<dyn NetDirProvider> = netdir_provider;
630
        guards.install_netdir_provider(&netdir_provider).unwrap();
631
        HsPathBuilder::new(target.cloned(), HsCircStemKind::Naive, circ_kind)
632
            .pick_path(&mut rng, dirinfo, &guards, &config, now)
633
            .map(|res| res.0)
634
    }
635

            
636
    /// Return an `OwnedChanTarget` to use as the target of a circuit.
637
    ///
638
    /// This will correspond to the "first" relay from the test network
639
    /// (the one with the $0000000000000000000000000000000000000000
640
    /// RSA identity fingerprint).
641
    fn test_target() -> OwnedChanTarget {
642
        // We target one of the relays known to be the network.
643
        OwnedChanTarget::builder()
644
            .addrs(vec!["127.0.0.3:9001".parse().unwrap()])
645
            .ed_identity([0xAA; 32].into())
646
            .rsa_identity([0x00; 20].into())
647
            .method(ChannelMethod::Direct(vec!["0.0.0.3:9001".parse().unwrap()]))
648
            .build()
649
            .unwrap()
650
    }
651

            
652
    // Prevents TROVE-2024-006 (arti#1425).
653
    //
654
    // Note: this, and all the other tests that disable vanguards,
655
    // perhaps belong in ExitPathBuilder, as they are effectively
656
    // testing the vanilla pick_path() implementation.
657
    #[test]
658
    fn hs_path_no_vanguards_incompatible_target() {
659
        // We target one of the relays known to be the network.
660
        let target = test_target();
661

            
662
        let netdir = construct_test_network(3, |pos, nb| {
663
            // The target is in a family with every other relay,
664
            // so any circuit we might build is going to be incompatible with it
665
            if pos == 0 {
666
                for pp in 0..MAX_NET_SIZE {
667
                    nb.md
668
                        .add_family_id(HappyFamilyId::Ed25519(Ed25519Identity::from(
669
                            [pp as u8; 32],
670
                        )));
671
                }
672
            } else {
673
                nb.md
674
                    .add_family_id(HappyFamilyId::Ed25519(Ed25519Identity::from(
675
                        [pos as u8; 32],
676
                    )));
677
            }
678
        });
679
        // We'll fail to select a guard, because the network doesn't have any relays compatible
680
        // with the target
681
        let err = pick_hs_path_no_vanguards(&netdir, Some(&target), None)
682
            .map(|_| ())
683
            .unwrap_err();
684

            
685
        assert!(
686
            matches!(
687
                err,
688
                Error::NoRelay {
689
                    ref problem,
690
                    ..
691
                } if problem ==  "Failed: rejected 3/3 as in same family as already selected"
692
            ),
693
            "{err:?}"
694
        );
695
    }
696

            
697
    #[test]
698
    fn hs_path_no_vanguards_reject_same_family() {
699
        // All the relays in the network are in the same family,
700
        // so building HS circuits should be impossible.
701
        let netdir = same_family_test_network(MAX_NET_SIZE);
702
        let err = match pick_hs_path_no_vanguards(&netdir, None, None) {
703
            Ok(path) => panic!(
704
                "expected error, but got valid path: {:?})",
705
                OwnedPath::try_from(&path).unwrap()
706
            ),
707
            Err(e) => e,
708
        };
709

            
710
        assert!(
711
            matches!(
712
                err,
713
                Error::NoRelay {
714
                    ref problem,
715
                    ..
716
                } if problem ==  "Failed: rejected 40/40 as in same family as already selected"
717
            ),
718
            "{err:?}"
719
        );
720
    }
721

            
722
    #[test]
723
    fn hs_path_no_vanguards() {
724
        let netdir = construct_test_network(20, |_pos, _nb| {});
725
        // We target one of the relays known to be the network.
726
        let target = test_target();
727
        for _ in 0..100 {
728
            for target in [None, Some(target.clone())] {
729
                let path = pick_hs_path_no_vanguards(&netdir, target.as_ref(), None).unwrap();
730
                assert_hs_path_ok(&path, target.as_ref());
731
            }
732
        }
733
    }
734

            
735
    #[test]
736
    #[cfg(feature = "vanguards")]
737
    fn lite_vanguard_path_insufficient_relays() {
738
        MockRuntime::test_with_various(|runtime| async move {
739
            let netdir = same_family_test_network(2);
740
            for stem_kind in [HsCircStemKind::Naive, HsCircStemKind::Guarded] {
741
                let err = pick_vanguard_path(
742
                    &runtime,
743
                    &netdir,
744
                    stem_kind,
745
                    None,
746
                    VanguardMode::Lite,
747
                    None,
748
                )
749
                .await
750
                .map(|_| ())
751
                .unwrap_err();
752

            
753
                // The test network is too small to build a 3-hop circuit.
754
                assert!(
755
                    matches!(
756
                        err,
757
                        Error::NoRelay {
758
                            ref problem,
759
                            ..
760
                        } if problem == "Failed: rejected 2/2 as already selected",
761
                    ),
762
                    "{err:?}"
763
                );
764
            }
765
        });
766
    }
767

            
768
    // Prevents TROVE-2024-003 (arti#1409).
769
    #[test]
770
    #[cfg(feature = "vanguards")]
771
    fn lite_vanguard_path() {
772
        MockRuntime::test_with_various(|runtime| async move {
773
            // We target one of the relays known to be the network.
774
            let target = OwnedChanTarget::builder()
775
                .rsa_identity([0x00; 20].into())
776
                .build()
777
                .unwrap();
778
            let netdir = same_family_test_network(10);
779
            let mode = VanguardMode::Lite;
780

            
781
            for target in [None, Some(target)] {
782
                for stem_kind in [HsCircStemKind::Naive, HsCircStemKind::Guarded] {
783
                    let path = pick_vanguard_path(
784
                        &runtime,
785
                        &netdir,
786
                        stem_kind,
787
                        None,
788
                        mode,
789
                        target.as_ref(),
790
                    )
791
                    .await
792
                    .unwrap();
793
                    assert_vanguard_path_ok(&path, stem_kind, mode, target.as_ref());
794
                }
795
            }
796
        });
797
    }
798

            
799
    #[test]
800
    #[cfg(feature = "vanguards")]
801
    fn full_vanguard_path() {
802
        MockRuntime::test_with_various(|runtime| async move {
803
            let netdir = same_family_test_network(MAX_NET_SIZE);
804
            let mode = VanguardMode::Full;
805

            
806
            // We target one of the relays known to be the network.
807
            let target = OwnedChanTarget::builder()
808
                .rsa_identity([0x00; 20].into())
809
                .build()
810
                .unwrap();
811

            
812
            for target in [None, Some(target)] {
813
                for stem_kind in [HsCircStemKind::Naive, HsCircStemKind::Guarded] {
814
                    let path = pick_vanguard_path(
815
                        &runtime,
816
                        &netdir,
817
                        stem_kind,
818
                        None,
819
                        mode,
820
                        target.as_ref(),
821
                    )
822
                    .await
823
                    .unwrap();
824
                    assert_vanguard_path_ok(&path, stem_kind, mode, target.as_ref());
825
                }
826
            }
827
        });
828
    }
829

            
830
    #[test]
831
    #[cfg(feature = "vanguards")]
832
    fn full_vanguard_path_insufficient_relays() {
833
        MockRuntime::test_with_various(|runtime| async move {
834
            let netdir = same_family_test_network(2);
835

            
836
            for stem_kind in [HsCircStemKind::Naive, HsCircStemKind::Guarded] {
837
                let err = pick_vanguard_path(
838
                    &runtime,
839
                    &netdir,
840
                    stem_kind,
841
                    None,
842
                    VanguardMode::Full,
843
                    None,
844
                )
845
                .await
846
                .map(|_| ())
847
                .unwrap_err();
848
                assert!(
849
                    matches!(
850
                        err,
851
                        Error::VanguardMgrInit(VanguardMgrError::NoSuitableRelay(Layer::Layer3)),
852
                    ),
853
                    "{err:?}"
854
                );
855
            }
856

            
857
            // We *can* build circuit stems in a 3-relay network,
858
            // as long as they don't have a specified target
859
            let netdir = same_family_test_network(3);
860
            let mode = VanguardMode::Full;
861

            
862
            for stem_kind in [HsCircStemKind::Naive, HsCircStemKind::Guarded] {
863
                let path = pick_vanguard_path(&runtime, &netdir, stem_kind, None, mode, None)
864
                    .await
865
                    .unwrap();
866
                assert_vanguard_path_ok(&path, stem_kind, mode, None);
867
                match stem_kind {
868
                    HsCircStemKind::Naive => {
869
                        // A 3-hop circuit can't contain duplicates,
870
                        // because that would mean it has one of the following
871
                        // configurations
872
                        //
873
                        //     A - A - A
874
                        //     A - A - B
875
                        //     A - B - A
876
                        //     A - B - B
877
                        //     B - A - A
878
                        //     B - A - B
879
                        //     B - B - A
880
                        //     B - B - B
881
                        //
882
                        // none of which are valid circuits, because a relay won't extend
883
                        // to itself or its predecessor.
884
                        assert_duplicate_hops(&path, false);
885
                    }
886
                    HsCircStemKind::Guarded => {
887
                        // There are only 3 relats in the network,
888
                        // so a 4-hop circuit must contain the same hop twice.
889
                        assert_duplicate_hops(&path, true);
890
                    }
891
                }
892
            }
893
        });
894
    }
895
}